1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
30 static std::string getTypeString(Type *T) {
32 raw_string_ostream Tmp(Result);
37 /// Run: module ::= toplevelentity*
38 bool LLParser::Run() {
42 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
46 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48 bool LLParser::ValidateEndOfModule() {
49 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
57 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
60 if (SlotNo >= NumberedMetadata.size() ||
61 NumberedMetadata[SlotNo] == nullptr)
62 return Error(MDList[i].Loc, "use of undefined metadata '!" +
64 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
67 ForwardRefInstMetadata.clear();
70 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
71 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
73 // Handle any function attribute group forward references.
74 for (std::map<Value*, std::vector<unsigned> >::iterator
75 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
78 std::vector<unsigned> &Vec = I->second;
81 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
83 B.merge(NumberedAttrBuilders[*VI]);
85 if (Function *Fn = dyn_cast<Function>(V)) {
86 AttributeSet AS = Fn->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
93 // If the alignment was parsed as an attribute, move to the alignment
95 if (FnAttrs.hasAlignmentAttr()) {
96 Fn->setAlignment(FnAttrs.getAlignment());
97 FnAttrs.removeAttribute(Attribute::Alignment);
100 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
101 AttributeSet::get(Context,
102 AttributeSet::FunctionIndex,
104 Fn->setAttributes(AS);
105 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
106 AttributeSet AS = CI->getAttributes();
107 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
108 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
109 AS.getFnAttributes());
111 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
112 AttributeSet::get(Context,
113 AttributeSet::FunctionIndex,
115 CI->setAttributes(AS);
116 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
117 AttributeSet AS = II->getAttributes();
118 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120 AS.getFnAttributes());
122 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
123 AttributeSet::get(Context,
124 AttributeSet::FunctionIndex,
126 II->setAttributes(AS);
128 llvm_unreachable("invalid object with forward attribute group reference");
132 // If there are entries in ForwardRefBlockAddresses at this point, they are
133 // references after the function was defined. Resolve those now.
134 while (!ForwardRefBlockAddresses.empty()) {
135 // Okay, we are referencing an already-parsed function, resolve them now.
136 Function *TheFn = nullptr;
137 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
138 if (Fn.Kind == ValID::t_GlobalName)
139 TheFn = M->getFunction(Fn.StrVal);
140 else if (Fn.UIntVal < NumberedVals.size())
141 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
144 return Error(Fn.Loc, "unknown function referenced by blockaddress");
146 // Resolve all these references.
147 if (ResolveForwardRefBlockAddresses(TheFn,
148 ForwardRefBlockAddresses.begin()->second,
152 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
155 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
156 if (NumberedTypes[i].second.isValid())
157 return Error(NumberedTypes[i].second,
158 "use of undefined type '%" + Twine(i) + "'");
160 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
161 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
162 if (I->second.second.isValid())
163 return Error(I->second.second,
164 "use of undefined type named '" + I->getKey() + "'");
166 if (!ForwardRefVals.empty())
167 return Error(ForwardRefVals.begin()->second.second,
168 "use of undefined value '@" + ForwardRefVals.begin()->first +
171 if (!ForwardRefValIDs.empty())
172 return Error(ForwardRefValIDs.begin()->second.second,
173 "use of undefined value '@" +
174 Twine(ForwardRefValIDs.begin()->first) + "'");
176 if (!ForwardRefMDNodes.empty())
177 return Error(ForwardRefMDNodes.begin()->second.second,
178 "use of undefined metadata '!" +
179 Twine(ForwardRefMDNodes.begin()->first) + "'");
182 // Look for intrinsic functions and CallInst that need to be upgraded
183 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
184 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
186 UpgradeDebugInfo(*M);
191 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
192 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
193 PerFunctionState *PFS) {
194 // Loop over all the references, resolving them.
195 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
198 if (Refs[i].first.Kind == ValID::t_LocalName)
199 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
201 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
202 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
203 return Error(Refs[i].first.Loc,
204 "cannot take address of numeric label after the function is defined");
206 Res = dyn_cast_or_null<BasicBlock>(
207 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
211 return Error(Refs[i].first.Loc,
212 "referenced value is not a basic block");
214 // Get the BlockAddress for this and update references to use it.
215 BlockAddress *BA = BlockAddress::get(TheFn, Res);
216 Refs[i].second->replaceAllUsesWith(BA);
217 Refs[i].second->eraseFromParent();
223 //===----------------------------------------------------------------------===//
224 // Top-Level Entities
225 //===----------------------------------------------------------------------===//
227 bool LLParser::ParseTopLevelEntities() {
229 switch (Lex.getKind()) {
230 default: return TokError("expected top-level entity");
231 case lltok::Eof: return false;
232 case lltok::kw_declare: if (ParseDeclare()) return true; break;
233 case lltok::kw_define: if (ParseDefine()) return true; break;
234 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
235 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
236 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
237 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
238 case lltok::LocalVar: if (ParseNamedType()) return true; break;
239 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
240 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
241 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
242 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
244 // The Global variable production with no name can have many different
245 // optional leading prefixes, the production is:
246 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
247 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
248 // ('constant'|'global') ...
249 case lltok::kw_private: // OptionalLinkage
250 case lltok::kw_internal: // OptionalLinkage
251 case lltok::kw_linker_private: // Obsolete OptionalLinkage
252 case lltok::kw_linker_private_weak: // Obsolete OptionalLinkage
253 case lltok::kw_weak: // OptionalLinkage
254 case lltok::kw_weak_odr: // OptionalLinkage
255 case lltok::kw_linkonce: // OptionalLinkage
256 case lltok::kw_linkonce_odr: // OptionalLinkage
257 case lltok::kw_appending: // OptionalLinkage
258 case lltok::kw_common: // OptionalLinkage
259 case lltok::kw_extern_weak: // OptionalLinkage
260 case lltok::kw_external: // OptionalLinkage
261 case lltok::kw_default: // OptionalVisibility
262 case lltok::kw_hidden: // OptionalVisibility
263 case lltok::kw_protected: // OptionalVisibility
264 case lltok::kw_dllimport: // OptionalDLLStorageClass
265 case lltok::kw_dllexport: // OptionalDLLStorageClass
266 case lltok::kw_thread_local: // OptionalThreadLocal
267 case lltok::kw_addrspace: // OptionalAddrSpace
268 case lltok::kw_constant: // GlobalType
269 case lltok::kw_global: { // GlobalType
270 unsigned Linkage, Visibility, DLLStorageClass;
271 GlobalVariable::ThreadLocalMode TLM;
273 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
274 ParseOptionalVisibility(Visibility) ||
275 ParseOptionalDLLStorageClass(DLLStorageClass) ||
276 ParseOptionalThreadLocal(TLM) ||
277 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
278 DLLStorageClass, TLM))
283 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
290 /// ::= 'module' 'asm' STRINGCONSTANT
291 bool LLParser::ParseModuleAsm() {
292 assert(Lex.getKind() == lltok::kw_module);
296 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
297 ParseStringConstant(AsmStr)) return true;
299 M->appendModuleInlineAsm(AsmStr);
304 /// ::= 'target' 'triple' '=' STRINGCONSTANT
305 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
306 bool LLParser::ParseTargetDefinition() {
307 assert(Lex.getKind() == lltok::kw_target);
310 default: return TokError("unknown target property");
311 case lltok::kw_triple:
313 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
314 ParseStringConstant(Str))
316 M->setTargetTriple(Str);
318 case lltok::kw_datalayout:
320 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
321 ParseStringConstant(Str))
323 M->setDataLayout(Str);
329 /// ::= 'deplibs' '=' '[' ']'
330 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
331 /// FIXME: Remove in 4.0. Currently parse, but ignore.
332 bool LLParser::ParseDepLibs() {
333 assert(Lex.getKind() == lltok::kw_deplibs);
335 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
336 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
339 if (EatIfPresent(lltok::rsquare))
344 if (ParseStringConstant(Str)) return true;
345 } while (EatIfPresent(lltok::comma));
347 return ParseToken(lltok::rsquare, "expected ']' at end of list");
350 /// ParseUnnamedType:
351 /// ::= LocalVarID '=' 'type' type
352 bool LLParser::ParseUnnamedType() {
353 LocTy TypeLoc = Lex.getLoc();
354 unsigned TypeID = Lex.getUIntVal();
355 Lex.Lex(); // eat LocalVarID;
357 if (ParseToken(lltok::equal, "expected '=' after name") ||
358 ParseToken(lltok::kw_type, "expected 'type' after '='"))
361 if (TypeID >= NumberedTypes.size())
362 NumberedTypes.resize(TypeID+1);
364 Type *Result = nullptr;
365 if (ParseStructDefinition(TypeLoc, "",
366 NumberedTypes[TypeID], Result)) return true;
368 if (!isa<StructType>(Result)) {
369 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
371 return Error(TypeLoc, "non-struct types may not be recursive");
372 Entry.first = Result;
373 Entry.second = SMLoc();
381 /// ::= LocalVar '=' 'type' type
382 bool LLParser::ParseNamedType() {
383 std::string Name = Lex.getStrVal();
384 LocTy NameLoc = Lex.getLoc();
385 Lex.Lex(); // eat LocalVar.
387 if (ParseToken(lltok::equal, "expected '=' after name") ||
388 ParseToken(lltok::kw_type, "expected 'type' after name"))
391 Type *Result = nullptr;
392 if (ParseStructDefinition(NameLoc, Name,
393 NamedTypes[Name], Result)) return true;
395 if (!isa<StructType>(Result)) {
396 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
398 return Error(NameLoc, "non-struct types may not be recursive");
399 Entry.first = Result;
400 Entry.second = SMLoc();
408 /// ::= 'declare' FunctionHeader
409 bool LLParser::ParseDeclare() {
410 assert(Lex.getKind() == lltok::kw_declare);
414 return ParseFunctionHeader(F, false);
418 /// ::= 'define' FunctionHeader '{' ...
419 bool LLParser::ParseDefine() {
420 assert(Lex.getKind() == lltok::kw_define);
424 return ParseFunctionHeader(F, true) ||
425 ParseFunctionBody(*F);
431 bool LLParser::ParseGlobalType(bool &IsConstant) {
432 if (Lex.getKind() == lltok::kw_constant)
434 else if (Lex.getKind() == lltok::kw_global)
438 return TokError("expected 'global' or 'constant'");
444 /// ParseUnnamedGlobal:
445 /// OptionalVisibility ALIAS ...
446 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
447 /// ... -> global variable
448 /// GlobalID '=' OptionalVisibility ALIAS ...
449 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
450 /// ... -> global variable
451 bool LLParser::ParseUnnamedGlobal() {
452 unsigned VarID = NumberedVals.size();
454 LocTy NameLoc = Lex.getLoc();
456 // Handle the GlobalID form.
457 if (Lex.getKind() == lltok::GlobalID) {
458 if (Lex.getUIntVal() != VarID)
459 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
461 Lex.Lex(); // eat GlobalID;
463 if (ParseToken(lltok::equal, "expected '=' after name"))
468 unsigned Linkage, Visibility, DLLStorageClass;
469 GlobalVariable::ThreadLocalMode TLM;
470 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
471 ParseOptionalVisibility(Visibility) ||
472 ParseOptionalDLLStorageClass(DLLStorageClass) ||
473 ParseOptionalThreadLocal(TLM))
476 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
477 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
478 DLLStorageClass, TLM);
479 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM);
482 /// ParseNamedGlobal:
483 /// GlobalVar '=' OptionalVisibility ALIAS ...
484 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
485 /// ... -> global variable
486 bool LLParser::ParseNamedGlobal() {
487 assert(Lex.getKind() == lltok::GlobalVar);
488 LocTy NameLoc = Lex.getLoc();
489 std::string Name = Lex.getStrVal();
493 unsigned Linkage, Visibility, DLLStorageClass;
494 GlobalVariable::ThreadLocalMode TLM;
495 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
496 ParseOptionalLinkage(Linkage, HasLinkage) ||
497 ParseOptionalVisibility(Visibility) ||
498 ParseOptionalDLLStorageClass(DLLStorageClass) ||
499 ParseOptionalThreadLocal(TLM))
502 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
503 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
504 DLLStorageClass, TLM);
505 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM);
509 // ::= '!' STRINGCONSTANT
510 bool LLParser::ParseMDString(MDString *&Result) {
512 if (ParseStringConstant(Str)) return true;
513 Result = MDString::get(Context, Str);
518 // ::= '!' MDNodeNumber
520 /// This version of ParseMDNodeID returns the slot number and null in the case
521 /// of a forward reference.
522 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
523 // !{ ..., !42, ... }
524 if (ParseUInt32(SlotNo)) return true;
526 // Check existing MDNode.
527 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
528 Result = NumberedMetadata[SlotNo];
534 bool LLParser::ParseMDNodeID(MDNode *&Result) {
535 // !{ ..., !42, ... }
537 if (ParseMDNodeID(Result, MID)) return true;
539 // If not a forward reference, just return it now.
540 if (Result) return false;
542 // Otherwise, create MDNode forward reference.
543 MDNode *FwdNode = MDNode::getTemporary(Context, None);
544 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
546 if (NumberedMetadata.size() <= MID)
547 NumberedMetadata.resize(MID+1);
548 NumberedMetadata[MID] = FwdNode;
553 /// ParseNamedMetadata:
554 /// !foo = !{ !1, !2 }
555 bool LLParser::ParseNamedMetadata() {
556 assert(Lex.getKind() == lltok::MetadataVar);
557 std::string Name = Lex.getStrVal();
560 if (ParseToken(lltok::equal, "expected '=' here") ||
561 ParseToken(lltok::exclaim, "Expected '!' here") ||
562 ParseToken(lltok::lbrace, "Expected '{' here"))
565 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
566 if (Lex.getKind() != lltok::rbrace)
568 if (ParseToken(lltok::exclaim, "Expected '!' here"))
572 if (ParseMDNodeID(N)) return true;
574 } while (EatIfPresent(lltok::comma));
576 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
582 /// ParseStandaloneMetadata:
584 bool LLParser::ParseStandaloneMetadata() {
585 assert(Lex.getKind() == lltok::exclaim);
587 unsigned MetadataID = 0;
591 SmallVector<Value *, 16> Elts;
592 if (ParseUInt32(MetadataID) ||
593 ParseToken(lltok::equal, "expected '=' here") ||
594 ParseType(Ty, TyLoc) ||
595 ParseToken(lltok::exclaim, "Expected '!' here") ||
596 ParseToken(lltok::lbrace, "Expected '{' here") ||
597 ParseMDNodeVector(Elts, nullptr) ||
598 ParseToken(lltok::rbrace, "expected end of metadata node"))
601 MDNode *Init = MDNode::get(Context, Elts);
603 // See if this was forward referenced, if so, handle it.
604 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
605 FI = ForwardRefMDNodes.find(MetadataID);
606 if (FI != ForwardRefMDNodes.end()) {
607 MDNode *Temp = FI->second.first;
608 Temp->replaceAllUsesWith(Init);
609 MDNode::deleteTemporary(Temp);
610 ForwardRefMDNodes.erase(FI);
612 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
614 if (MetadataID >= NumberedMetadata.size())
615 NumberedMetadata.resize(MetadataID+1);
617 if (NumberedMetadata[MetadataID] != nullptr)
618 return TokError("Metadata id is already used");
619 NumberedMetadata[MetadataID] = Init;
625 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
626 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
627 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
631 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass
632 /// OptionalThreadLocal 'alias' OptionalLinkage Aliasee
637 /// Everything through OptionalThreadLocal has already been parsed.
639 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
640 unsigned Visibility, unsigned DLLStorageClass,
641 GlobalVariable::ThreadLocalMode TLM) {
642 assert(Lex.getKind() == lltok::kw_alias);
644 LocTy LinkageLoc = Lex.getLoc();
646 if (ParseOptionalLinkage(L))
649 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
651 if(!GlobalAlias::isValidLinkage(Linkage))
652 return Error(LinkageLoc, "invalid linkage type for alias");
654 if (!isValidVisibilityForLinkage(Visibility, L))
655 return Error(LinkageLoc,
656 "symbol with local linkage must have default visibility");
659 LocTy AliaseeLoc = Lex.getLoc();
660 if (Lex.getKind() != lltok::kw_bitcast &&
661 Lex.getKind() != lltok::kw_getelementptr &&
662 Lex.getKind() != lltok::kw_addrspacecast &&
663 Lex.getKind() != lltok::kw_inttoptr) {
664 if (ParseGlobalTypeAndValue(Aliasee))
667 // The bitcast dest type is not present, it is implied by the dest type.
671 if (ID.Kind != ValID::t_Constant)
672 return Error(AliaseeLoc, "invalid aliasee");
673 Aliasee = ID.ConstantVal;
676 Type *AliaseeType = Aliasee->getType();
677 auto *PTy = dyn_cast<PointerType>(AliaseeType);
679 return Error(AliaseeLoc, "An alias must have pointer type");
680 Type *Ty = PTy->getElementType();
681 unsigned AddrSpace = PTy->getAddressSpace();
683 // Okay, create the alias but do not insert it into the module yet.
684 std::unique_ptr<GlobalAlias> GA(
685 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
686 Name, Aliasee, /*Parent*/ nullptr));
687 GA->setThreadLocalMode(TLM);
688 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
689 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
691 // See if this value already exists in the symbol table. If so, it is either
692 // a redefinition or a definition of a forward reference.
693 if (GlobalValue *Val = M->getNamedValue(Name)) {
694 // See if this was a redefinition. If so, there is no entry in
696 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
697 I = ForwardRefVals.find(Name);
698 if (I == ForwardRefVals.end())
699 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
701 // Otherwise, this was a definition of forward ref. Verify that types
703 if (Val->getType() != GA->getType())
704 return Error(NameLoc,
705 "forward reference and definition of alias have different types");
707 // If they agree, just RAUW the old value with the alias and remove the
709 Val->replaceAllUsesWith(GA.get());
710 Val->eraseFromParent();
711 ForwardRefVals.erase(I);
714 // Insert into the module, we know its name won't collide now.
715 M->getAliasList().push_back(GA.get());
716 assert(GA->getName() == Name && "Should not be a name conflict!");
718 // The module owns this now
725 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
726 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
727 /// OptionalExternallyInitialized GlobalType Type Const
728 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
729 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
730 /// OptionalExternallyInitialized GlobalType Type Const
732 /// Everything up to and including OptionalThreadLocal has been parsed
735 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
736 unsigned Linkage, bool HasLinkage,
737 unsigned Visibility, unsigned DLLStorageClass,
738 GlobalVariable::ThreadLocalMode TLM) {
739 if (!isValidVisibilityForLinkage(Visibility, Linkage))
740 return Error(NameLoc,
741 "symbol with local linkage must have default visibility");
744 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
745 LocTy UnnamedAddrLoc;
746 LocTy IsExternallyInitializedLoc;
750 if (ParseOptionalAddrSpace(AddrSpace) ||
751 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
753 ParseOptionalToken(lltok::kw_externally_initialized,
754 IsExternallyInitialized,
755 &IsExternallyInitializedLoc) ||
756 ParseGlobalType(IsConstant) ||
757 ParseType(Ty, TyLoc))
760 // If the linkage is specified and is external, then no initializer is
762 Constant *Init = nullptr;
763 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
764 Linkage != GlobalValue::ExternalLinkage)) {
765 if (ParseGlobalValue(Ty, Init))
769 if (Ty->isFunctionTy() || Ty->isLabelTy())
770 return Error(TyLoc, "invalid type for global variable");
772 GlobalVariable *GV = nullptr;
774 // See if the global was forward referenced, if so, use the global.
776 if (GlobalValue *GVal = M->getNamedValue(Name)) {
777 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
778 return Error(NameLoc, "redefinition of global '@" + Name + "'");
779 GV = cast<GlobalVariable>(GVal);
782 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
783 I = ForwardRefValIDs.find(NumberedVals.size());
784 if (I != ForwardRefValIDs.end()) {
785 GV = cast<GlobalVariable>(I->second.first);
786 ForwardRefValIDs.erase(I);
791 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
792 Name, nullptr, GlobalVariable::NotThreadLocal,
795 if (GV->getType()->getElementType() != Ty)
797 "forward reference and definition of global have different types");
799 // Move the forward-reference to the correct spot in the module.
800 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
804 NumberedVals.push_back(GV);
806 // Set the parsed properties on the global.
808 GV->setInitializer(Init);
809 GV->setConstant(IsConstant);
810 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
811 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
812 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
813 GV->setExternallyInitialized(IsExternallyInitialized);
814 GV->setThreadLocalMode(TLM);
815 GV->setUnnamedAddr(UnnamedAddr);
817 // Parse attributes on the global.
818 while (Lex.getKind() == lltok::comma) {
821 if (Lex.getKind() == lltok::kw_section) {
823 GV->setSection(Lex.getStrVal());
824 if (ParseToken(lltok::StringConstant, "expected global section string"))
826 } else if (Lex.getKind() == lltok::kw_align) {
828 if (ParseOptionalAlignment(Alignment)) return true;
829 GV->setAlignment(Alignment);
831 TokError("unknown global variable property!");
838 /// ParseUnnamedAttrGrp
839 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
840 bool LLParser::ParseUnnamedAttrGrp() {
841 assert(Lex.getKind() == lltok::kw_attributes);
842 LocTy AttrGrpLoc = Lex.getLoc();
845 assert(Lex.getKind() == lltok::AttrGrpID);
846 unsigned VarID = Lex.getUIntVal();
847 std::vector<unsigned> unused;
851 if (ParseToken(lltok::equal, "expected '=' here") ||
852 ParseToken(lltok::lbrace, "expected '{' here") ||
853 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
855 ParseToken(lltok::rbrace, "expected end of attribute group"))
858 if (!NumberedAttrBuilders[VarID].hasAttributes())
859 return Error(AttrGrpLoc, "attribute group has no attributes");
864 /// ParseFnAttributeValuePairs
865 /// ::= <attr> | <attr> '=' <value>
866 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
867 std::vector<unsigned> &FwdRefAttrGrps,
868 bool inAttrGrp, LocTy &BuiltinLoc) {
869 bool HaveError = false;
874 lltok::Kind Token = Lex.getKind();
875 if (Token == lltok::kw_builtin)
876 BuiltinLoc = Lex.getLoc();
879 if (!inAttrGrp) return HaveError;
880 return Error(Lex.getLoc(), "unterminated attribute group");
885 case lltok::AttrGrpID: {
886 // Allow a function to reference an attribute group:
888 // define void @foo() #1 { ... }
892 "cannot have an attribute group reference in an attribute group");
894 unsigned AttrGrpNum = Lex.getUIntVal();
895 if (inAttrGrp) break;
897 // Save the reference to the attribute group. We'll fill it in later.
898 FwdRefAttrGrps.push_back(AttrGrpNum);
901 // Target-dependent attributes:
902 case lltok::StringConstant: {
903 std::string Attr = Lex.getStrVal();
906 if (EatIfPresent(lltok::equal) &&
907 ParseStringConstant(Val))
910 B.addAttribute(Attr, Val);
914 // Target-independent attributes:
915 case lltok::kw_align: {
916 // As a hack, we allow function alignment to be initially parsed as an
917 // attribute on a function declaration/definition or added to an attribute
918 // group and later moved to the alignment field.
922 if (ParseToken(lltok::equal, "expected '=' here") ||
923 ParseUInt32(Alignment))
926 if (ParseOptionalAlignment(Alignment))
929 B.addAlignmentAttr(Alignment);
932 case lltok::kw_alignstack: {
936 if (ParseToken(lltok::equal, "expected '=' here") ||
937 ParseUInt32(Alignment))
940 if (ParseOptionalStackAlignment(Alignment))
943 B.addStackAlignmentAttr(Alignment);
946 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
947 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
948 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
949 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
950 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
951 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
952 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
953 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
954 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
955 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
956 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
957 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
958 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
959 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
960 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
961 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
962 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
963 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
964 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
965 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
966 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
967 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
968 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
969 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
970 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
971 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
972 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
975 case lltok::kw_inreg:
976 case lltok::kw_signext:
977 case lltok::kw_zeroext:
980 "invalid use of attribute on a function");
982 case lltok::kw_byval:
983 case lltok::kw_inalloca:
985 case lltok::kw_noalias:
986 case lltok::kw_nocapture:
987 case lltok::kw_nonnull:
988 case lltok::kw_returned:
992 "invalid use of parameter-only attribute on a function");
1000 //===----------------------------------------------------------------------===//
1001 // GlobalValue Reference/Resolution Routines.
1002 //===----------------------------------------------------------------------===//
1004 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1005 /// forward reference record if needed. This can return null if the value
1006 /// exists but does not have the right type.
1007 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1009 PointerType *PTy = dyn_cast<PointerType>(Ty);
1011 Error(Loc, "global variable reference must have pointer type");
1015 // Look this name up in the normal function symbol table.
1017 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1019 // If this is a forward reference for the value, see if we already created a
1020 // forward ref record.
1022 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1023 I = ForwardRefVals.find(Name);
1024 if (I != ForwardRefVals.end())
1025 Val = I->second.first;
1028 // If we have the value in the symbol table or fwd-ref table, return it.
1030 if (Val->getType() == Ty) return Val;
1031 Error(Loc, "'@" + Name + "' defined with type '" +
1032 getTypeString(Val->getType()) + "'");
1036 // Otherwise, create a new forward reference for this value and remember it.
1037 GlobalValue *FwdVal;
1038 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1039 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1041 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1042 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1043 nullptr, GlobalVariable::NotThreadLocal,
1044 PTy->getAddressSpace());
1046 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1050 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1051 PointerType *PTy = dyn_cast<PointerType>(Ty);
1053 Error(Loc, "global variable reference must have pointer type");
1057 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1059 // If this is a forward reference for the value, see if we already created a
1060 // forward ref record.
1062 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1063 I = ForwardRefValIDs.find(ID);
1064 if (I != ForwardRefValIDs.end())
1065 Val = I->second.first;
1068 // If we have the value in the symbol table or fwd-ref table, return it.
1070 if (Val->getType() == Ty) return Val;
1071 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1072 getTypeString(Val->getType()) + "'");
1076 // Otherwise, create a new forward reference for this value and remember it.
1077 GlobalValue *FwdVal;
1078 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1079 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1081 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1082 GlobalValue::ExternalWeakLinkage, nullptr, "");
1084 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1089 //===----------------------------------------------------------------------===//
1091 //===----------------------------------------------------------------------===//
1093 /// ParseToken - If the current token has the specified kind, eat it and return
1094 /// success. Otherwise, emit the specified error and return failure.
1095 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1096 if (Lex.getKind() != T)
1097 return TokError(ErrMsg);
1102 /// ParseStringConstant
1103 /// ::= StringConstant
1104 bool LLParser::ParseStringConstant(std::string &Result) {
1105 if (Lex.getKind() != lltok::StringConstant)
1106 return TokError("expected string constant");
1107 Result = Lex.getStrVal();
1114 bool LLParser::ParseUInt32(unsigned &Val) {
1115 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1116 return TokError("expected integer");
1117 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1118 if (Val64 != unsigned(Val64))
1119 return TokError("expected 32-bit integer (too large)");
1126 /// := 'localdynamic'
1127 /// := 'initialexec'
1129 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1130 switch (Lex.getKind()) {
1132 return TokError("expected localdynamic, initialexec or localexec");
1133 case lltok::kw_localdynamic:
1134 TLM = GlobalVariable::LocalDynamicTLSModel;
1136 case lltok::kw_initialexec:
1137 TLM = GlobalVariable::InitialExecTLSModel;
1139 case lltok::kw_localexec:
1140 TLM = GlobalVariable::LocalExecTLSModel;
1148 /// ParseOptionalThreadLocal
1150 /// := 'thread_local'
1151 /// := 'thread_local' '(' tlsmodel ')'
1152 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1153 TLM = GlobalVariable::NotThreadLocal;
1154 if (!EatIfPresent(lltok::kw_thread_local))
1157 TLM = GlobalVariable::GeneralDynamicTLSModel;
1158 if (Lex.getKind() == lltok::lparen) {
1160 return ParseTLSModel(TLM) ||
1161 ParseToken(lltok::rparen, "expected ')' after thread local model");
1166 /// ParseOptionalAddrSpace
1168 /// := 'addrspace' '(' uint32 ')'
1169 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1171 if (!EatIfPresent(lltok::kw_addrspace))
1173 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1174 ParseUInt32(AddrSpace) ||
1175 ParseToken(lltok::rparen, "expected ')' in address space");
1178 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1179 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1180 bool HaveError = false;
1185 lltok::Kind Token = Lex.getKind();
1187 default: // End of attributes.
1189 case lltok::kw_align: {
1191 if (ParseOptionalAlignment(Alignment))
1193 B.addAlignmentAttr(Alignment);
1196 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1197 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1198 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1199 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1200 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1201 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1202 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1203 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1204 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1205 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1206 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1207 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1208 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1210 case lltok::kw_alignstack:
1211 case lltok::kw_alwaysinline:
1212 case lltok::kw_builtin:
1213 case lltok::kw_inlinehint:
1214 case lltok::kw_jumptable:
1215 case lltok::kw_minsize:
1216 case lltok::kw_naked:
1217 case lltok::kw_nobuiltin:
1218 case lltok::kw_noduplicate:
1219 case lltok::kw_noimplicitfloat:
1220 case lltok::kw_noinline:
1221 case lltok::kw_nonlazybind:
1222 case lltok::kw_noredzone:
1223 case lltok::kw_noreturn:
1224 case lltok::kw_nounwind:
1225 case lltok::kw_optnone:
1226 case lltok::kw_optsize:
1227 case lltok::kw_returns_twice:
1228 case lltok::kw_sanitize_address:
1229 case lltok::kw_sanitize_memory:
1230 case lltok::kw_sanitize_thread:
1232 case lltok::kw_sspreq:
1233 case lltok::kw_sspstrong:
1234 case lltok::kw_uwtable:
1235 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1243 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1244 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1245 bool HaveError = false;
1250 lltok::Kind Token = Lex.getKind();
1252 default: // End of attributes.
1254 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1255 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1256 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1257 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1258 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1261 case lltok::kw_align:
1262 case lltok::kw_byval:
1263 case lltok::kw_inalloca:
1264 case lltok::kw_nest:
1265 case lltok::kw_nocapture:
1266 case lltok::kw_returned:
1267 case lltok::kw_sret:
1268 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1271 case lltok::kw_alignstack:
1272 case lltok::kw_alwaysinline:
1273 case lltok::kw_builtin:
1274 case lltok::kw_cold:
1275 case lltok::kw_inlinehint:
1276 case lltok::kw_jumptable:
1277 case lltok::kw_minsize:
1278 case lltok::kw_naked:
1279 case lltok::kw_nobuiltin:
1280 case lltok::kw_noduplicate:
1281 case lltok::kw_noimplicitfloat:
1282 case lltok::kw_noinline:
1283 case lltok::kw_nonlazybind:
1284 case lltok::kw_noredzone:
1285 case lltok::kw_noreturn:
1286 case lltok::kw_nounwind:
1287 case lltok::kw_optnone:
1288 case lltok::kw_optsize:
1289 case lltok::kw_returns_twice:
1290 case lltok::kw_sanitize_address:
1291 case lltok::kw_sanitize_memory:
1292 case lltok::kw_sanitize_thread:
1294 case lltok::kw_sspreq:
1295 case lltok::kw_sspstrong:
1296 case lltok::kw_uwtable:
1297 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1300 case lltok::kw_readnone:
1301 case lltok::kw_readonly:
1302 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1309 /// ParseOptionalLinkage
1316 /// ::= 'linkonce_odr'
1317 /// ::= 'available_externally'
1320 /// ::= 'extern_weak'
1323 /// Deprecated Values:
1324 /// ::= 'linker_private'
1325 /// ::= 'linker_private_weak'
1326 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1328 switch (Lex.getKind()) {
1329 default: Res=GlobalValue::ExternalLinkage; return false;
1330 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1331 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1332 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1333 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1334 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1335 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1336 case lltok::kw_available_externally:
1337 Res = GlobalValue::AvailableExternallyLinkage;
1339 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1340 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1341 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1342 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1344 case lltok::kw_linker_private:
1345 case lltok::kw_linker_private_weak:
1346 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1349 // treat linker_private and linker_private_weak as PrivateLinkage
1350 Res = GlobalValue::PrivateLinkage;
1358 /// ParseOptionalVisibility
1364 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1365 switch (Lex.getKind()) {
1366 default: Res = GlobalValue::DefaultVisibility; return false;
1367 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1368 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1369 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1375 /// ParseOptionalDLLStorageClass
1380 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1381 switch (Lex.getKind()) {
1382 default: Res = GlobalValue::DefaultStorageClass; return false;
1383 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1384 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1390 /// ParseOptionalCallingConv
1394 /// ::= 'kw_intel_ocl_bicc'
1396 /// ::= 'x86_stdcallcc'
1397 /// ::= 'x86_fastcallcc'
1398 /// ::= 'x86_thiscallcc'
1399 /// ::= 'arm_apcscc'
1400 /// ::= 'arm_aapcscc'
1401 /// ::= 'arm_aapcs_vfpcc'
1402 /// ::= 'msp430_intrcc'
1403 /// ::= 'ptx_kernel'
1404 /// ::= 'ptx_device'
1406 /// ::= 'spir_kernel'
1407 /// ::= 'x86_64_sysvcc'
1408 /// ::= 'x86_64_win64cc'
1409 /// ::= 'webkit_jscc'
1411 /// ::= 'preserve_mostcc'
1412 /// ::= 'preserve_allcc'
1415 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1416 switch (Lex.getKind()) {
1417 default: CC = CallingConv::C; return false;
1418 case lltok::kw_ccc: CC = CallingConv::C; break;
1419 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1420 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1421 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1422 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1423 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1424 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1425 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1426 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1427 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1428 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1429 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1430 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1431 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1432 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1433 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1434 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1435 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1436 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1437 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1438 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1439 case lltok::kw_cc: {
1440 unsigned ArbitraryCC;
1442 if (ParseUInt32(ArbitraryCC))
1444 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1453 /// ParseInstructionMetadata
1454 /// ::= !dbg !42 (',' !dbg !57)*
1455 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1456 PerFunctionState *PFS) {
1458 if (Lex.getKind() != lltok::MetadataVar)
1459 return TokError("expected metadata after comma");
1461 std::string Name = Lex.getStrVal();
1462 unsigned MDK = M->getMDKindID(Name);
1466 SMLoc Loc = Lex.getLoc();
1468 if (ParseToken(lltok::exclaim, "expected '!' here"))
1471 // This code is similar to that of ParseMetadataValue, however it needs to
1472 // have special-case code for a forward reference; see the comments on
1473 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1474 // at the top level here.
1475 if (Lex.getKind() == lltok::lbrace) {
1477 if (ParseMetadataListValue(ID, PFS))
1479 assert(ID.Kind == ValID::t_MDNode);
1480 Inst->setMetadata(MDK, ID.MDNodeVal);
1482 unsigned NodeID = 0;
1483 if (ParseMDNodeID(Node, NodeID))
1486 // If we got the node, add it to the instruction.
1487 Inst->setMetadata(MDK, Node);
1489 MDRef R = { Loc, MDK, NodeID };
1490 // Otherwise, remember that this should be resolved later.
1491 ForwardRefInstMetadata[Inst].push_back(R);
1495 if (MDK == LLVMContext::MD_tbaa)
1496 InstsWithTBAATag.push_back(Inst);
1498 // If this is the end of the list, we're done.
1499 } while (EatIfPresent(lltok::comma));
1503 /// ParseOptionalAlignment
1506 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1508 if (!EatIfPresent(lltok::kw_align))
1510 LocTy AlignLoc = Lex.getLoc();
1511 if (ParseUInt32(Alignment)) return true;
1512 if (!isPowerOf2_32(Alignment))
1513 return Error(AlignLoc, "alignment is not a power of two");
1514 if (Alignment > Value::MaximumAlignment)
1515 return Error(AlignLoc, "huge alignments are not supported yet");
1519 /// ParseOptionalCommaAlign
1523 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1525 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1526 bool &AteExtraComma) {
1527 AteExtraComma = false;
1528 while (EatIfPresent(lltok::comma)) {
1529 // Metadata at the end is an early exit.
1530 if (Lex.getKind() == lltok::MetadataVar) {
1531 AteExtraComma = true;
1535 if (Lex.getKind() != lltok::kw_align)
1536 return Error(Lex.getLoc(), "expected metadata or 'align'");
1538 if (ParseOptionalAlignment(Alignment)) return true;
1544 /// ParseScopeAndOrdering
1545 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1548 /// This sets Scope and Ordering to the parsed values.
1549 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1550 AtomicOrdering &Ordering) {
1554 Scope = CrossThread;
1555 if (EatIfPresent(lltok::kw_singlethread))
1556 Scope = SingleThread;
1558 return ParseOrdering(Ordering);
1562 /// ::= AtomicOrdering
1564 /// This sets Ordering to the parsed value.
1565 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1566 switch (Lex.getKind()) {
1567 default: return TokError("Expected ordering on atomic instruction");
1568 case lltok::kw_unordered: Ordering = Unordered; break;
1569 case lltok::kw_monotonic: Ordering = Monotonic; break;
1570 case lltok::kw_acquire: Ordering = Acquire; break;
1571 case lltok::kw_release: Ordering = Release; break;
1572 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1573 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1579 /// ParseOptionalStackAlignment
1581 /// ::= 'alignstack' '(' 4 ')'
1582 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1584 if (!EatIfPresent(lltok::kw_alignstack))
1586 LocTy ParenLoc = Lex.getLoc();
1587 if (!EatIfPresent(lltok::lparen))
1588 return Error(ParenLoc, "expected '('");
1589 LocTy AlignLoc = Lex.getLoc();
1590 if (ParseUInt32(Alignment)) return true;
1591 ParenLoc = Lex.getLoc();
1592 if (!EatIfPresent(lltok::rparen))
1593 return Error(ParenLoc, "expected ')'");
1594 if (!isPowerOf2_32(Alignment))
1595 return Error(AlignLoc, "stack alignment is not a power of two");
1599 /// ParseIndexList - This parses the index list for an insert/extractvalue
1600 /// instruction. This sets AteExtraComma in the case where we eat an extra
1601 /// comma at the end of the line and find that it is followed by metadata.
1602 /// Clients that don't allow metadata can call the version of this function that
1603 /// only takes one argument.
1606 /// ::= (',' uint32)+
1608 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1609 bool &AteExtraComma) {
1610 AteExtraComma = false;
1612 if (Lex.getKind() != lltok::comma)
1613 return TokError("expected ',' as start of index list");
1615 while (EatIfPresent(lltok::comma)) {
1616 if (Lex.getKind() == lltok::MetadataVar) {
1617 AteExtraComma = true;
1621 if (ParseUInt32(Idx)) return true;
1622 Indices.push_back(Idx);
1628 //===----------------------------------------------------------------------===//
1630 //===----------------------------------------------------------------------===//
1632 /// ParseType - Parse a type.
1633 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1634 SMLoc TypeLoc = Lex.getLoc();
1635 switch (Lex.getKind()) {
1637 return TokError("expected type");
1639 // Type ::= 'float' | 'void' (etc)
1640 Result = Lex.getTyVal();
1644 // Type ::= StructType
1645 if (ParseAnonStructType(Result, false))
1648 case lltok::lsquare:
1649 // Type ::= '[' ... ']'
1650 Lex.Lex(); // eat the lsquare.
1651 if (ParseArrayVectorType(Result, false))
1654 case lltok::less: // Either vector or packed struct.
1655 // Type ::= '<' ... '>'
1657 if (Lex.getKind() == lltok::lbrace) {
1658 if (ParseAnonStructType(Result, true) ||
1659 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1661 } else if (ParseArrayVectorType(Result, true))
1664 case lltok::LocalVar: {
1666 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1668 // If the type hasn't been defined yet, create a forward definition and
1669 // remember where that forward def'n was seen (in case it never is defined).
1671 Entry.first = StructType::create(Context, Lex.getStrVal());
1672 Entry.second = Lex.getLoc();
1674 Result = Entry.first;
1679 case lltok::LocalVarID: {
1681 if (Lex.getUIntVal() >= NumberedTypes.size())
1682 NumberedTypes.resize(Lex.getUIntVal()+1);
1683 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1685 // If the type hasn't been defined yet, create a forward definition and
1686 // remember where that forward def'n was seen (in case it never is defined).
1688 Entry.first = StructType::create(Context);
1689 Entry.second = Lex.getLoc();
1691 Result = Entry.first;
1697 // Parse the type suffixes.
1699 switch (Lex.getKind()) {
1702 if (!AllowVoid && Result->isVoidTy())
1703 return Error(TypeLoc, "void type only allowed for function results");
1706 // Type ::= Type '*'
1708 if (Result->isLabelTy())
1709 return TokError("basic block pointers are invalid");
1710 if (Result->isVoidTy())
1711 return TokError("pointers to void are invalid - use i8* instead");
1712 if (!PointerType::isValidElementType(Result))
1713 return TokError("pointer to this type is invalid");
1714 Result = PointerType::getUnqual(Result);
1718 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1719 case lltok::kw_addrspace: {
1720 if (Result->isLabelTy())
1721 return TokError("basic block pointers are invalid");
1722 if (Result->isVoidTy())
1723 return TokError("pointers to void are invalid; use i8* instead");
1724 if (!PointerType::isValidElementType(Result))
1725 return TokError("pointer to this type is invalid");
1727 if (ParseOptionalAddrSpace(AddrSpace) ||
1728 ParseToken(lltok::star, "expected '*' in address space"))
1731 Result = PointerType::get(Result, AddrSpace);
1735 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1737 if (ParseFunctionType(Result))
1744 /// ParseParameterList
1746 /// ::= '(' Arg (',' Arg)* ')'
1748 /// ::= Type OptionalAttributes Value OptionalAttributes
1749 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1750 PerFunctionState &PFS) {
1751 if (ParseToken(lltok::lparen, "expected '(' in call"))
1754 unsigned AttrIndex = 1;
1755 while (Lex.getKind() != lltok::rparen) {
1756 // If this isn't the first argument, we need a comma.
1757 if (!ArgList.empty() &&
1758 ParseToken(lltok::comma, "expected ',' in argument list"))
1761 // Parse the argument.
1763 Type *ArgTy = nullptr;
1764 AttrBuilder ArgAttrs;
1766 if (ParseType(ArgTy, ArgLoc))
1769 // Otherwise, handle normal operands.
1770 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1772 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1777 Lex.Lex(); // Lex the ')'.
1783 /// ParseArgumentList - Parse the argument list for a function type or function
1785 /// ::= '(' ArgTypeListI ')'
1789 /// ::= ArgTypeList ',' '...'
1790 /// ::= ArgType (',' ArgType)*
1792 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1795 assert(Lex.getKind() == lltok::lparen);
1796 Lex.Lex(); // eat the (.
1798 if (Lex.getKind() == lltok::rparen) {
1800 } else if (Lex.getKind() == lltok::dotdotdot) {
1804 LocTy TypeLoc = Lex.getLoc();
1805 Type *ArgTy = nullptr;
1809 if (ParseType(ArgTy) ||
1810 ParseOptionalParamAttrs(Attrs)) return true;
1812 if (ArgTy->isVoidTy())
1813 return Error(TypeLoc, "argument can not have void type");
1815 if (Lex.getKind() == lltok::LocalVar) {
1816 Name = Lex.getStrVal();
1820 if (!FunctionType::isValidArgumentType(ArgTy))
1821 return Error(TypeLoc, "invalid type for function argument");
1823 unsigned AttrIndex = 1;
1824 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1825 AttributeSet::get(ArgTy->getContext(),
1826 AttrIndex++, Attrs), Name));
1828 while (EatIfPresent(lltok::comma)) {
1829 // Handle ... at end of arg list.
1830 if (EatIfPresent(lltok::dotdotdot)) {
1835 // Otherwise must be an argument type.
1836 TypeLoc = Lex.getLoc();
1837 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1839 if (ArgTy->isVoidTy())
1840 return Error(TypeLoc, "argument can not have void type");
1842 if (Lex.getKind() == lltok::LocalVar) {
1843 Name = Lex.getStrVal();
1849 if (!ArgTy->isFirstClassType())
1850 return Error(TypeLoc, "invalid type for function argument");
1852 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1853 AttributeSet::get(ArgTy->getContext(),
1854 AttrIndex++, Attrs),
1859 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1862 /// ParseFunctionType
1863 /// ::= Type ArgumentList OptionalAttrs
1864 bool LLParser::ParseFunctionType(Type *&Result) {
1865 assert(Lex.getKind() == lltok::lparen);
1867 if (!FunctionType::isValidReturnType(Result))
1868 return TokError("invalid function return type");
1870 SmallVector<ArgInfo, 8> ArgList;
1872 if (ParseArgumentList(ArgList, isVarArg))
1875 // Reject names on the arguments lists.
1876 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1877 if (!ArgList[i].Name.empty())
1878 return Error(ArgList[i].Loc, "argument name invalid in function type");
1879 if (ArgList[i].Attrs.hasAttributes(i + 1))
1880 return Error(ArgList[i].Loc,
1881 "argument attributes invalid in function type");
1884 SmallVector<Type*, 16> ArgListTy;
1885 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1886 ArgListTy.push_back(ArgList[i].Ty);
1888 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1892 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1894 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1895 SmallVector<Type*, 8> Elts;
1896 if (ParseStructBody(Elts)) return true;
1898 Result = StructType::get(Context, Elts, Packed);
1902 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1903 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1904 std::pair<Type*, LocTy> &Entry,
1906 // If the type was already defined, diagnose the redefinition.
1907 if (Entry.first && !Entry.second.isValid())
1908 return Error(TypeLoc, "redefinition of type");
1910 // If we have opaque, just return without filling in the definition for the
1911 // struct. This counts as a definition as far as the .ll file goes.
1912 if (EatIfPresent(lltok::kw_opaque)) {
1913 // This type is being defined, so clear the location to indicate this.
1914 Entry.second = SMLoc();
1916 // If this type number has never been uttered, create it.
1918 Entry.first = StructType::create(Context, Name);
1919 ResultTy = Entry.first;
1923 // If the type starts with '<', then it is either a packed struct or a vector.
1924 bool isPacked = EatIfPresent(lltok::less);
1926 // If we don't have a struct, then we have a random type alias, which we
1927 // accept for compatibility with old files. These types are not allowed to be
1928 // forward referenced and not allowed to be recursive.
1929 if (Lex.getKind() != lltok::lbrace) {
1931 return Error(TypeLoc, "forward references to non-struct type");
1935 return ParseArrayVectorType(ResultTy, true);
1936 return ParseType(ResultTy);
1939 // This type is being defined, so clear the location to indicate this.
1940 Entry.second = SMLoc();
1942 // If this type number has never been uttered, create it.
1944 Entry.first = StructType::create(Context, Name);
1946 StructType *STy = cast<StructType>(Entry.first);
1948 SmallVector<Type*, 8> Body;
1949 if (ParseStructBody(Body) ||
1950 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1953 STy->setBody(Body, isPacked);
1959 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1962 /// ::= '{' Type (',' Type)* '}'
1963 /// ::= '<' '{' '}' '>'
1964 /// ::= '<' '{' Type (',' Type)* '}' '>'
1965 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1966 assert(Lex.getKind() == lltok::lbrace);
1967 Lex.Lex(); // Consume the '{'
1969 // Handle the empty struct.
1970 if (EatIfPresent(lltok::rbrace))
1973 LocTy EltTyLoc = Lex.getLoc();
1975 if (ParseType(Ty)) return true;
1978 if (!StructType::isValidElementType(Ty))
1979 return Error(EltTyLoc, "invalid element type for struct");
1981 while (EatIfPresent(lltok::comma)) {
1982 EltTyLoc = Lex.getLoc();
1983 if (ParseType(Ty)) return true;
1985 if (!StructType::isValidElementType(Ty))
1986 return Error(EltTyLoc, "invalid element type for struct");
1991 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1994 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1995 /// token has already been consumed.
1997 /// ::= '[' APSINTVAL 'x' Types ']'
1998 /// ::= '<' APSINTVAL 'x' Types '>'
1999 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2000 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2001 Lex.getAPSIntVal().getBitWidth() > 64)
2002 return TokError("expected number in address space");
2004 LocTy SizeLoc = Lex.getLoc();
2005 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2008 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2011 LocTy TypeLoc = Lex.getLoc();
2012 Type *EltTy = nullptr;
2013 if (ParseType(EltTy)) return true;
2015 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2016 "expected end of sequential type"))
2021 return Error(SizeLoc, "zero element vector is illegal");
2022 if ((unsigned)Size != Size)
2023 return Error(SizeLoc, "size too large for vector");
2024 if (!VectorType::isValidElementType(EltTy))
2025 return Error(TypeLoc, "invalid vector element type");
2026 Result = VectorType::get(EltTy, unsigned(Size));
2028 if (!ArrayType::isValidElementType(EltTy))
2029 return Error(TypeLoc, "invalid array element type");
2030 Result = ArrayType::get(EltTy, Size);
2035 //===----------------------------------------------------------------------===//
2036 // Function Semantic Analysis.
2037 //===----------------------------------------------------------------------===//
2039 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2041 : P(p), F(f), FunctionNumber(functionNumber) {
2043 // Insert unnamed arguments into the NumberedVals list.
2044 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2047 NumberedVals.push_back(AI);
2050 LLParser::PerFunctionState::~PerFunctionState() {
2051 // If there were any forward referenced non-basicblock values, delete them.
2052 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2053 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2054 if (!isa<BasicBlock>(I->second.first)) {
2055 I->second.first->replaceAllUsesWith(
2056 UndefValue::get(I->second.first->getType()));
2057 delete I->second.first;
2058 I->second.first = nullptr;
2061 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2062 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2063 if (!isa<BasicBlock>(I->second.first)) {
2064 I->second.first->replaceAllUsesWith(
2065 UndefValue::get(I->second.first->getType()));
2066 delete I->second.first;
2067 I->second.first = nullptr;
2071 bool LLParser::PerFunctionState::FinishFunction() {
2072 // Check to see if someone took the address of labels in this block.
2073 if (!P.ForwardRefBlockAddresses.empty()) {
2075 if (!F.getName().empty()) {
2076 FunctionID.Kind = ValID::t_GlobalName;
2077 FunctionID.StrVal = F.getName();
2079 FunctionID.Kind = ValID::t_GlobalID;
2080 FunctionID.UIntVal = FunctionNumber;
2083 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2084 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2085 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2086 // Resolve all these references.
2087 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2090 P.ForwardRefBlockAddresses.erase(FRBAI);
2094 if (!ForwardRefVals.empty())
2095 return P.Error(ForwardRefVals.begin()->second.second,
2096 "use of undefined value '%" + ForwardRefVals.begin()->first +
2098 if (!ForwardRefValIDs.empty())
2099 return P.Error(ForwardRefValIDs.begin()->second.second,
2100 "use of undefined value '%" +
2101 Twine(ForwardRefValIDs.begin()->first) + "'");
2106 /// GetVal - Get a value with the specified name or ID, creating a
2107 /// forward reference record if needed. This can return null if the value
2108 /// exists but does not have the right type.
2109 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2110 Type *Ty, LocTy Loc) {
2111 // Look this name up in the normal function symbol table.
2112 Value *Val = F.getValueSymbolTable().lookup(Name);
2114 // If this is a forward reference for the value, see if we already created a
2115 // forward ref record.
2117 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2118 I = ForwardRefVals.find(Name);
2119 if (I != ForwardRefVals.end())
2120 Val = I->second.first;
2123 // If we have the value in the symbol table or fwd-ref table, return it.
2125 if (Val->getType() == Ty) return Val;
2126 if (Ty->isLabelTy())
2127 P.Error(Loc, "'%" + Name + "' is not a basic block");
2129 P.Error(Loc, "'%" + Name + "' defined with type '" +
2130 getTypeString(Val->getType()) + "'");
2134 // Don't make placeholders with invalid type.
2135 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2136 P.Error(Loc, "invalid use of a non-first-class type");
2140 // Otherwise, create a new forward reference for this value and remember it.
2142 if (Ty->isLabelTy())
2143 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2145 FwdVal = new Argument(Ty, Name);
2147 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2151 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2153 // Look this name up in the normal function symbol table.
2154 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2156 // If this is a forward reference for the value, see if we already created a
2157 // forward ref record.
2159 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2160 I = ForwardRefValIDs.find(ID);
2161 if (I != ForwardRefValIDs.end())
2162 Val = I->second.first;
2165 // If we have the value in the symbol table or fwd-ref table, return it.
2167 if (Val->getType() == Ty) return Val;
2168 if (Ty->isLabelTy())
2169 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2171 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2172 getTypeString(Val->getType()) + "'");
2176 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2177 P.Error(Loc, "invalid use of a non-first-class type");
2181 // Otherwise, create a new forward reference for this value and remember it.
2183 if (Ty->isLabelTy())
2184 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2186 FwdVal = new Argument(Ty);
2188 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2192 /// SetInstName - After an instruction is parsed and inserted into its
2193 /// basic block, this installs its name.
2194 bool LLParser::PerFunctionState::SetInstName(int NameID,
2195 const std::string &NameStr,
2196 LocTy NameLoc, Instruction *Inst) {
2197 // If this instruction has void type, it cannot have a name or ID specified.
2198 if (Inst->getType()->isVoidTy()) {
2199 if (NameID != -1 || !NameStr.empty())
2200 return P.Error(NameLoc, "instructions returning void cannot have a name");
2204 // If this was a numbered instruction, verify that the instruction is the
2205 // expected value and resolve any forward references.
2206 if (NameStr.empty()) {
2207 // If neither a name nor an ID was specified, just use the next ID.
2209 NameID = NumberedVals.size();
2211 if (unsigned(NameID) != NumberedVals.size())
2212 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2213 Twine(NumberedVals.size()) + "'");
2215 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2216 ForwardRefValIDs.find(NameID);
2217 if (FI != ForwardRefValIDs.end()) {
2218 if (FI->second.first->getType() != Inst->getType())
2219 return P.Error(NameLoc, "instruction forward referenced with type '" +
2220 getTypeString(FI->second.first->getType()) + "'");
2221 FI->second.first->replaceAllUsesWith(Inst);
2222 delete FI->second.first;
2223 ForwardRefValIDs.erase(FI);
2226 NumberedVals.push_back(Inst);
2230 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2231 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2232 FI = ForwardRefVals.find(NameStr);
2233 if (FI != ForwardRefVals.end()) {
2234 if (FI->second.first->getType() != Inst->getType())
2235 return P.Error(NameLoc, "instruction forward referenced with type '" +
2236 getTypeString(FI->second.first->getType()) + "'");
2237 FI->second.first->replaceAllUsesWith(Inst);
2238 delete FI->second.first;
2239 ForwardRefVals.erase(FI);
2242 // Set the name on the instruction.
2243 Inst->setName(NameStr);
2245 if (Inst->getName() != NameStr)
2246 return P.Error(NameLoc, "multiple definition of local value named '" +
2251 /// GetBB - Get a basic block with the specified name or ID, creating a
2252 /// forward reference record if needed.
2253 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2255 return cast_or_null<BasicBlock>(GetVal(Name,
2256 Type::getLabelTy(F.getContext()), Loc));
2259 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2260 return cast_or_null<BasicBlock>(GetVal(ID,
2261 Type::getLabelTy(F.getContext()), Loc));
2264 /// DefineBB - Define the specified basic block, which is either named or
2265 /// unnamed. If there is an error, this returns null otherwise it returns
2266 /// the block being defined.
2267 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2271 BB = GetBB(NumberedVals.size(), Loc);
2273 BB = GetBB(Name, Loc);
2274 if (!BB) return nullptr; // Already diagnosed error.
2276 // Move the block to the end of the function. Forward ref'd blocks are
2277 // inserted wherever they happen to be referenced.
2278 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2280 // Remove the block from forward ref sets.
2282 ForwardRefValIDs.erase(NumberedVals.size());
2283 NumberedVals.push_back(BB);
2285 // BB forward references are already in the function symbol table.
2286 ForwardRefVals.erase(Name);
2292 //===----------------------------------------------------------------------===//
2294 //===----------------------------------------------------------------------===//
2296 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2297 /// type implied. For example, if we parse "4" we don't know what integer type
2298 /// it has. The value will later be combined with its type and checked for
2299 /// sanity. PFS is used to convert function-local operands of metadata (since
2300 /// metadata operands are not just parsed here but also converted to values).
2301 /// PFS can be null when we are not parsing metadata values inside a function.
2302 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2303 ID.Loc = Lex.getLoc();
2304 switch (Lex.getKind()) {
2305 default: return TokError("expected value token");
2306 case lltok::GlobalID: // @42
2307 ID.UIntVal = Lex.getUIntVal();
2308 ID.Kind = ValID::t_GlobalID;
2310 case lltok::GlobalVar: // @foo
2311 ID.StrVal = Lex.getStrVal();
2312 ID.Kind = ValID::t_GlobalName;
2314 case lltok::LocalVarID: // %42
2315 ID.UIntVal = Lex.getUIntVal();
2316 ID.Kind = ValID::t_LocalID;
2318 case lltok::LocalVar: // %foo
2319 ID.StrVal = Lex.getStrVal();
2320 ID.Kind = ValID::t_LocalName;
2322 case lltok::exclaim: // !42, !{...}, or !"foo"
2323 return ParseMetadataValue(ID, PFS);
2325 ID.APSIntVal = Lex.getAPSIntVal();
2326 ID.Kind = ValID::t_APSInt;
2328 case lltok::APFloat:
2329 ID.APFloatVal = Lex.getAPFloatVal();
2330 ID.Kind = ValID::t_APFloat;
2332 case lltok::kw_true:
2333 ID.ConstantVal = ConstantInt::getTrue(Context);
2334 ID.Kind = ValID::t_Constant;
2336 case lltok::kw_false:
2337 ID.ConstantVal = ConstantInt::getFalse(Context);
2338 ID.Kind = ValID::t_Constant;
2340 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2341 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2342 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2344 case lltok::lbrace: {
2345 // ValID ::= '{' ConstVector '}'
2347 SmallVector<Constant*, 16> Elts;
2348 if (ParseGlobalValueVector(Elts) ||
2349 ParseToken(lltok::rbrace, "expected end of struct constant"))
2352 ID.ConstantStructElts = new Constant*[Elts.size()];
2353 ID.UIntVal = Elts.size();
2354 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2355 ID.Kind = ValID::t_ConstantStruct;
2359 // ValID ::= '<' ConstVector '>' --> Vector.
2360 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2362 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2364 SmallVector<Constant*, 16> Elts;
2365 LocTy FirstEltLoc = Lex.getLoc();
2366 if (ParseGlobalValueVector(Elts) ||
2368 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2369 ParseToken(lltok::greater, "expected end of constant"))
2372 if (isPackedStruct) {
2373 ID.ConstantStructElts = new Constant*[Elts.size()];
2374 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2375 ID.UIntVal = Elts.size();
2376 ID.Kind = ValID::t_PackedConstantStruct;
2381 return Error(ID.Loc, "constant vector must not be empty");
2383 if (!Elts[0]->getType()->isIntegerTy() &&
2384 !Elts[0]->getType()->isFloatingPointTy() &&
2385 !Elts[0]->getType()->isPointerTy())
2386 return Error(FirstEltLoc,
2387 "vector elements must have integer, pointer or floating point type");
2389 // Verify that all the vector elements have the same type.
2390 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2391 if (Elts[i]->getType() != Elts[0]->getType())
2392 return Error(FirstEltLoc,
2393 "vector element #" + Twine(i) +
2394 " is not of type '" + getTypeString(Elts[0]->getType()));
2396 ID.ConstantVal = ConstantVector::get(Elts);
2397 ID.Kind = ValID::t_Constant;
2400 case lltok::lsquare: { // Array Constant
2402 SmallVector<Constant*, 16> Elts;
2403 LocTy FirstEltLoc = Lex.getLoc();
2404 if (ParseGlobalValueVector(Elts) ||
2405 ParseToken(lltok::rsquare, "expected end of array constant"))
2408 // Handle empty element.
2410 // Use undef instead of an array because it's inconvenient to determine
2411 // the element type at this point, there being no elements to examine.
2412 ID.Kind = ValID::t_EmptyArray;
2416 if (!Elts[0]->getType()->isFirstClassType())
2417 return Error(FirstEltLoc, "invalid array element type: " +
2418 getTypeString(Elts[0]->getType()));
2420 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2422 // Verify all elements are correct type!
2423 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2424 if (Elts[i]->getType() != Elts[0]->getType())
2425 return Error(FirstEltLoc,
2426 "array element #" + Twine(i) +
2427 " is not of type '" + getTypeString(Elts[0]->getType()));
2430 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2431 ID.Kind = ValID::t_Constant;
2434 case lltok::kw_c: // c "foo"
2436 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2438 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2439 ID.Kind = ValID::t_Constant;
2442 case lltok::kw_asm: {
2443 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2445 bool HasSideEffect, AlignStack, AsmDialect;
2447 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2448 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2449 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2450 ParseStringConstant(ID.StrVal) ||
2451 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2452 ParseToken(lltok::StringConstant, "expected constraint string"))
2454 ID.StrVal2 = Lex.getStrVal();
2455 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2456 (unsigned(AsmDialect)<<2);
2457 ID.Kind = ValID::t_InlineAsm;
2461 case lltok::kw_blockaddress: {
2462 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2467 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2469 ParseToken(lltok::comma, "expected comma in block address expression")||
2470 ParseValID(Label) ||
2471 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2474 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2475 return Error(Fn.Loc, "expected function name in blockaddress");
2476 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2477 return Error(Label.Loc, "expected basic block name in blockaddress");
2479 // Make a global variable as a placeholder for this reference.
2480 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2481 false, GlobalValue::InternalLinkage,
2483 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2484 ID.ConstantVal = FwdRef;
2485 ID.Kind = ValID::t_Constant;
2489 case lltok::kw_trunc:
2490 case lltok::kw_zext:
2491 case lltok::kw_sext:
2492 case lltok::kw_fptrunc:
2493 case lltok::kw_fpext:
2494 case lltok::kw_bitcast:
2495 case lltok::kw_addrspacecast:
2496 case lltok::kw_uitofp:
2497 case lltok::kw_sitofp:
2498 case lltok::kw_fptoui:
2499 case lltok::kw_fptosi:
2500 case lltok::kw_inttoptr:
2501 case lltok::kw_ptrtoint: {
2502 unsigned Opc = Lex.getUIntVal();
2503 Type *DestTy = nullptr;
2506 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2507 ParseGlobalTypeAndValue(SrcVal) ||
2508 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2509 ParseType(DestTy) ||
2510 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2512 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2513 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2514 getTypeString(SrcVal->getType()) + "' to '" +
2515 getTypeString(DestTy) + "'");
2516 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2518 ID.Kind = ValID::t_Constant;
2521 case lltok::kw_extractvalue: {
2524 SmallVector<unsigned, 4> Indices;
2525 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2526 ParseGlobalTypeAndValue(Val) ||
2527 ParseIndexList(Indices) ||
2528 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2531 if (!Val->getType()->isAggregateType())
2532 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2533 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2534 return Error(ID.Loc, "invalid indices for extractvalue");
2535 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2536 ID.Kind = ValID::t_Constant;
2539 case lltok::kw_insertvalue: {
2541 Constant *Val0, *Val1;
2542 SmallVector<unsigned, 4> Indices;
2543 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2544 ParseGlobalTypeAndValue(Val0) ||
2545 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2546 ParseGlobalTypeAndValue(Val1) ||
2547 ParseIndexList(Indices) ||
2548 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2550 if (!Val0->getType()->isAggregateType())
2551 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2552 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2553 return Error(ID.Loc, "invalid indices for insertvalue");
2554 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2555 ID.Kind = ValID::t_Constant;
2558 case lltok::kw_icmp:
2559 case lltok::kw_fcmp: {
2560 unsigned PredVal, Opc = Lex.getUIntVal();
2561 Constant *Val0, *Val1;
2563 if (ParseCmpPredicate(PredVal, Opc) ||
2564 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2565 ParseGlobalTypeAndValue(Val0) ||
2566 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2567 ParseGlobalTypeAndValue(Val1) ||
2568 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2571 if (Val0->getType() != Val1->getType())
2572 return Error(ID.Loc, "compare operands must have the same type");
2574 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2576 if (Opc == Instruction::FCmp) {
2577 if (!Val0->getType()->isFPOrFPVectorTy())
2578 return Error(ID.Loc, "fcmp requires floating point operands");
2579 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2581 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2582 if (!Val0->getType()->isIntOrIntVectorTy() &&
2583 !Val0->getType()->getScalarType()->isPointerTy())
2584 return Error(ID.Loc, "icmp requires pointer or integer operands");
2585 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2587 ID.Kind = ValID::t_Constant;
2591 // Binary Operators.
2593 case lltok::kw_fadd:
2595 case lltok::kw_fsub:
2597 case lltok::kw_fmul:
2598 case lltok::kw_udiv:
2599 case lltok::kw_sdiv:
2600 case lltok::kw_fdiv:
2601 case lltok::kw_urem:
2602 case lltok::kw_srem:
2603 case lltok::kw_frem:
2605 case lltok::kw_lshr:
2606 case lltok::kw_ashr: {
2610 unsigned Opc = Lex.getUIntVal();
2611 Constant *Val0, *Val1;
2613 LocTy ModifierLoc = Lex.getLoc();
2614 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2615 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2616 if (EatIfPresent(lltok::kw_nuw))
2618 if (EatIfPresent(lltok::kw_nsw)) {
2620 if (EatIfPresent(lltok::kw_nuw))
2623 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2624 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2625 if (EatIfPresent(lltok::kw_exact))
2628 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2629 ParseGlobalTypeAndValue(Val0) ||
2630 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2631 ParseGlobalTypeAndValue(Val1) ||
2632 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2634 if (Val0->getType() != Val1->getType())
2635 return Error(ID.Loc, "operands of constexpr must have same type");
2636 if (!Val0->getType()->isIntOrIntVectorTy()) {
2638 return Error(ModifierLoc, "nuw only applies to integer operations");
2640 return Error(ModifierLoc, "nsw only applies to integer operations");
2642 // Check that the type is valid for the operator.
2644 case Instruction::Add:
2645 case Instruction::Sub:
2646 case Instruction::Mul:
2647 case Instruction::UDiv:
2648 case Instruction::SDiv:
2649 case Instruction::URem:
2650 case Instruction::SRem:
2651 case Instruction::Shl:
2652 case Instruction::AShr:
2653 case Instruction::LShr:
2654 if (!Val0->getType()->isIntOrIntVectorTy())
2655 return Error(ID.Loc, "constexpr requires integer operands");
2657 case Instruction::FAdd:
2658 case Instruction::FSub:
2659 case Instruction::FMul:
2660 case Instruction::FDiv:
2661 case Instruction::FRem:
2662 if (!Val0->getType()->isFPOrFPVectorTy())
2663 return Error(ID.Loc, "constexpr requires fp operands");
2665 default: llvm_unreachable("Unknown binary operator!");
2668 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2669 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2670 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2671 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2673 ID.Kind = ValID::t_Constant;
2677 // Logical Operations
2680 case lltok::kw_xor: {
2681 unsigned Opc = Lex.getUIntVal();
2682 Constant *Val0, *Val1;
2684 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2685 ParseGlobalTypeAndValue(Val0) ||
2686 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2687 ParseGlobalTypeAndValue(Val1) ||
2688 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2690 if (Val0->getType() != Val1->getType())
2691 return Error(ID.Loc, "operands of constexpr must have same type");
2692 if (!Val0->getType()->isIntOrIntVectorTy())
2693 return Error(ID.Loc,
2694 "constexpr requires integer or integer vector operands");
2695 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2696 ID.Kind = ValID::t_Constant;
2700 case lltok::kw_getelementptr:
2701 case lltok::kw_shufflevector:
2702 case lltok::kw_insertelement:
2703 case lltok::kw_extractelement:
2704 case lltok::kw_select: {
2705 unsigned Opc = Lex.getUIntVal();
2706 SmallVector<Constant*, 16> Elts;
2707 bool InBounds = false;
2709 if (Opc == Instruction::GetElementPtr)
2710 InBounds = EatIfPresent(lltok::kw_inbounds);
2711 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2712 ParseGlobalValueVector(Elts) ||
2713 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2716 if (Opc == Instruction::GetElementPtr) {
2717 if (Elts.size() == 0 ||
2718 !Elts[0]->getType()->getScalarType()->isPointerTy())
2719 return Error(ID.Loc, "getelementptr requires pointer operand");
2721 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2722 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2723 return Error(ID.Loc, "invalid indices for getelementptr");
2724 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2726 } else if (Opc == Instruction::Select) {
2727 if (Elts.size() != 3)
2728 return Error(ID.Loc, "expected three operands to select");
2729 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2731 return Error(ID.Loc, Reason);
2732 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2733 } else if (Opc == Instruction::ShuffleVector) {
2734 if (Elts.size() != 3)
2735 return Error(ID.Loc, "expected three operands to shufflevector");
2736 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2737 return Error(ID.Loc, "invalid operands to shufflevector");
2739 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2740 } else if (Opc == Instruction::ExtractElement) {
2741 if (Elts.size() != 2)
2742 return Error(ID.Loc, "expected two operands to extractelement");
2743 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2744 return Error(ID.Loc, "invalid extractelement operands");
2745 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2747 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2748 if (Elts.size() != 3)
2749 return Error(ID.Loc, "expected three operands to insertelement");
2750 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2751 return Error(ID.Loc, "invalid insertelement operands");
2753 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2756 ID.Kind = ValID::t_Constant;
2765 /// ParseGlobalValue - Parse a global value with the specified type.
2766 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2770 bool Parsed = ParseValID(ID) ||
2771 ConvertValIDToValue(Ty, ID, V, nullptr);
2772 if (V && !(C = dyn_cast<Constant>(V)))
2773 return Error(ID.Loc, "global values must be constants");
2777 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2779 return ParseType(Ty) ||
2780 ParseGlobalValue(Ty, V);
2783 /// ParseGlobalValueVector
2785 /// ::= TypeAndValue (',' TypeAndValue)*
2786 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2788 if (Lex.getKind() == lltok::rbrace ||
2789 Lex.getKind() == lltok::rsquare ||
2790 Lex.getKind() == lltok::greater ||
2791 Lex.getKind() == lltok::rparen)
2795 if (ParseGlobalTypeAndValue(C)) return true;
2798 while (EatIfPresent(lltok::comma)) {
2799 if (ParseGlobalTypeAndValue(C)) return true;
2806 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2807 assert(Lex.getKind() == lltok::lbrace);
2810 SmallVector<Value*, 16> Elts;
2811 if (ParseMDNodeVector(Elts, PFS) ||
2812 ParseToken(lltok::rbrace, "expected end of metadata node"))
2815 ID.MDNodeVal = MDNode::get(Context, Elts);
2816 ID.Kind = ValID::t_MDNode;
2820 /// ParseMetadataValue
2824 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2825 assert(Lex.getKind() == lltok::exclaim);
2830 if (Lex.getKind() == lltok::lbrace)
2831 return ParseMetadataListValue(ID, PFS);
2833 // Standalone metadata reference
2835 if (Lex.getKind() == lltok::APSInt) {
2836 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2837 ID.Kind = ValID::t_MDNode;
2842 // ::= '!' STRINGCONSTANT
2843 if (ParseMDString(ID.MDStringVal)) return true;
2844 ID.Kind = ValID::t_MDString;
2849 //===----------------------------------------------------------------------===//
2850 // Function Parsing.
2851 //===----------------------------------------------------------------------===//
2853 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2854 PerFunctionState *PFS) {
2855 if (Ty->isFunctionTy())
2856 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2859 case ValID::t_LocalID:
2860 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2861 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2862 return V == nullptr;
2863 case ValID::t_LocalName:
2864 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2865 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2866 return V == nullptr;
2867 case ValID::t_InlineAsm: {
2868 PointerType *PTy = dyn_cast<PointerType>(Ty);
2870 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2871 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2872 return Error(ID.Loc, "invalid type for inline asm constraint string");
2873 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2874 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2877 case ValID::t_MDNode:
2878 if (!Ty->isMetadataTy())
2879 return Error(ID.Loc, "metadata value must have metadata type");
2882 case ValID::t_MDString:
2883 if (!Ty->isMetadataTy())
2884 return Error(ID.Loc, "metadata value must have metadata type");
2887 case ValID::t_GlobalName:
2888 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2889 return V == nullptr;
2890 case ValID::t_GlobalID:
2891 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2892 return V == nullptr;
2893 case ValID::t_APSInt:
2894 if (!Ty->isIntegerTy())
2895 return Error(ID.Loc, "integer constant must have integer type");
2896 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2897 V = ConstantInt::get(Context, ID.APSIntVal);
2899 case ValID::t_APFloat:
2900 if (!Ty->isFloatingPointTy() ||
2901 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2902 return Error(ID.Loc, "floating point constant invalid for type");
2904 // The lexer has no type info, so builds all half, float, and double FP
2905 // constants as double. Fix this here. Long double does not need this.
2906 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2909 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2911 else if (Ty->isFloatTy())
2912 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2915 V = ConstantFP::get(Context, ID.APFloatVal);
2917 if (V->getType() != Ty)
2918 return Error(ID.Loc, "floating point constant does not have type '" +
2919 getTypeString(Ty) + "'");
2923 if (!Ty->isPointerTy())
2924 return Error(ID.Loc, "null must be a pointer type");
2925 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2927 case ValID::t_Undef:
2928 // FIXME: LabelTy should not be a first-class type.
2929 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2930 return Error(ID.Loc, "invalid type for undef constant");
2931 V = UndefValue::get(Ty);
2933 case ValID::t_EmptyArray:
2934 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2935 return Error(ID.Loc, "invalid empty array initializer");
2936 V = UndefValue::get(Ty);
2939 // FIXME: LabelTy should not be a first-class type.
2940 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2941 return Error(ID.Loc, "invalid type for null constant");
2942 V = Constant::getNullValue(Ty);
2944 case ValID::t_Constant:
2945 if (ID.ConstantVal->getType() != Ty)
2946 return Error(ID.Loc, "constant expression type mismatch");
2950 case ValID::t_ConstantStruct:
2951 case ValID::t_PackedConstantStruct:
2952 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2953 if (ST->getNumElements() != ID.UIntVal)
2954 return Error(ID.Loc,
2955 "initializer with struct type has wrong # elements");
2956 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2957 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2959 // Verify that the elements are compatible with the structtype.
2960 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2961 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2962 return Error(ID.Loc, "element " + Twine(i) +
2963 " of struct initializer doesn't match struct element type");
2965 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2968 return Error(ID.Loc, "constant expression type mismatch");
2971 llvm_unreachable("Invalid ValID");
2974 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2977 return ParseValID(ID, PFS) ||
2978 ConvertValIDToValue(Ty, ID, V, PFS);
2981 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2983 return ParseType(Ty) ||
2984 ParseValue(Ty, V, PFS);
2987 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2988 PerFunctionState &PFS) {
2991 if (ParseTypeAndValue(V, PFS)) return true;
2992 if (!isa<BasicBlock>(V))
2993 return Error(Loc, "expected a basic block");
2994 BB = cast<BasicBlock>(V);
3000 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3001 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3002 /// OptionalAlign OptGC OptionalPrefix
3003 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3004 // Parse the linkage.
3005 LocTy LinkageLoc = Lex.getLoc();
3008 unsigned Visibility;
3009 unsigned DLLStorageClass;
3010 AttrBuilder RetAttrs;
3012 Type *RetType = nullptr;
3013 LocTy RetTypeLoc = Lex.getLoc();
3014 if (ParseOptionalLinkage(Linkage) ||
3015 ParseOptionalVisibility(Visibility) ||
3016 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3017 ParseOptionalCallingConv(CC) ||
3018 ParseOptionalReturnAttrs(RetAttrs) ||
3019 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3022 // Verify that the linkage is ok.
3023 switch ((GlobalValue::LinkageTypes)Linkage) {
3024 case GlobalValue::ExternalLinkage:
3025 break; // always ok.
3026 case GlobalValue::ExternalWeakLinkage:
3028 return Error(LinkageLoc, "invalid linkage for function definition");
3030 case GlobalValue::PrivateLinkage:
3031 case GlobalValue::InternalLinkage:
3032 case GlobalValue::AvailableExternallyLinkage:
3033 case GlobalValue::LinkOnceAnyLinkage:
3034 case GlobalValue::LinkOnceODRLinkage:
3035 case GlobalValue::WeakAnyLinkage:
3036 case GlobalValue::WeakODRLinkage:
3038 return Error(LinkageLoc, "invalid linkage for function declaration");
3040 case GlobalValue::AppendingLinkage:
3041 case GlobalValue::CommonLinkage:
3042 return Error(LinkageLoc, "invalid function linkage type");
3045 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3046 return Error(LinkageLoc,
3047 "symbol with local linkage must have default visibility");
3049 if (!FunctionType::isValidReturnType(RetType))
3050 return Error(RetTypeLoc, "invalid function return type");
3052 LocTy NameLoc = Lex.getLoc();
3054 std::string FunctionName;
3055 if (Lex.getKind() == lltok::GlobalVar) {
3056 FunctionName = Lex.getStrVal();
3057 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3058 unsigned NameID = Lex.getUIntVal();
3060 if (NameID != NumberedVals.size())
3061 return TokError("function expected to be numbered '%" +
3062 Twine(NumberedVals.size()) + "'");
3064 return TokError("expected function name");
3069 if (Lex.getKind() != lltok::lparen)
3070 return TokError("expected '(' in function argument list");
3072 SmallVector<ArgInfo, 8> ArgList;
3074 AttrBuilder FuncAttrs;
3075 std::vector<unsigned> FwdRefAttrGrps;
3077 std::string Section;
3081 LocTy UnnamedAddrLoc;
3082 Constant *Prefix = nullptr;
3084 if (ParseArgumentList(ArgList, isVarArg) ||
3085 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3087 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3089 (EatIfPresent(lltok::kw_section) &&
3090 ParseStringConstant(Section)) ||
3091 ParseOptionalAlignment(Alignment) ||
3092 (EatIfPresent(lltok::kw_gc) &&
3093 ParseStringConstant(GC)) ||
3094 (EatIfPresent(lltok::kw_prefix) &&
3095 ParseGlobalTypeAndValue(Prefix)))
3098 if (FuncAttrs.contains(Attribute::Builtin))
3099 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3101 // If the alignment was parsed as an attribute, move to the alignment field.
3102 if (FuncAttrs.hasAlignmentAttr()) {
3103 Alignment = FuncAttrs.getAlignment();
3104 FuncAttrs.removeAttribute(Attribute::Alignment);
3107 // Okay, if we got here, the function is syntactically valid. Convert types
3108 // and do semantic checks.
3109 std::vector<Type*> ParamTypeList;
3110 SmallVector<AttributeSet, 8> Attrs;
3112 if (RetAttrs.hasAttributes())
3113 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3114 AttributeSet::ReturnIndex,
3117 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3118 ParamTypeList.push_back(ArgList[i].Ty);
3119 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3120 AttrBuilder B(ArgList[i].Attrs, i + 1);
3121 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3125 if (FuncAttrs.hasAttributes())
3126 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3127 AttributeSet::FunctionIndex,
3130 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3132 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3133 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3136 FunctionType::get(RetType, ParamTypeList, isVarArg);
3137 PointerType *PFT = PointerType::getUnqual(FT);
3140 if (!FunctionName.empty()) {
3141 // If this was a definition of a forward reference, remove the definition
3142 // from the forward reference table and fill in the forward ref.
3143 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3144 ForwardRefVals.find(FunctionName);
3145 if (FRVI != ForwardRefVals.end()) {
3146 Fn = M->getFunction(FunctionName);
3148 return Error(FRVI->second.second, "invalid forward reference to "
3149 "function as global value!");
3150 if (Fn->getType() != PFT)
3151 return Error(FRVI->second.second, "invalid forward reference to "
3152 "function '" + FunctionName + "' with wrong type!");
3154 ForwardRefVals.erase(FRVI);
3155 } else if ((Fn = M->getFunction(FunctionName))) {
3156 // Reject redefinitions.
3157 return Error(NameLoc, "invalid redefinition of function '" +
3158 FunctionName + "'");
3159 } else if (M->getNamedValue(FunctionName)) {
3160 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3164 // If this is a definition of a forward referenced function, make sure the
3166 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3167 = ForwardRefValIDs.find(NumberedVals.size());
3168 if (I != ForwardRefValIDs.end()) {
3169 Fn = cast<Function>(I->second.first);
3170 if (Fn->getType() != PFT)
3171 return Error(NameLoc, "type of definition and forward reference of '@" +
3172 Twine(NumberedVals.size()) + "' disagree");
3173 ForwardRefValIDs.erase(I);
3178 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3179 else // Move the forward-reference to the correct spot in the module.
3180 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3182 if (FunctionName.empty())
3183 NumberedVals.push_back(Fn);
3185 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3186 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3187 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3188 Fn->setCallingConv(CC);
3189 Fn->setAttributes(PAL);
3190 Fn->setUnnamedAddr(UnnamedAddr);
3191 Fn->setAlignment(Alignment);
3192 Fn->setSection(Section);
3193 if (!GC.empty()) Fn->setGC(GC.c_str());
3194 Fn->setPrefixData(Prefix);
3195 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3197 // Add all of the arguments we parsed to the function.
3198 Function::arg_iterator ArgIt = Fn->arg_begin();
3199 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3200 // If the argument has a name, insert it into the argument symbol table.
3201 if (ArgList[i].Name.empty()) continue;
3203 // Set the name, if it conflicted, it will be auto-renamed.
3204 ArgIt->setName(ArgList[i].Name);
3206 if (ArgIt->getName() != ArgList[i].Name)
3207 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3208 ArgList[i].Name + "'");
3215 /// ParseFunctionBody
3216 /// ::= '{' BasicBlock+ '}'
3218 bool LLParser::ParseFunctionBody(Function &Fn) {
3219 if (Lex.getKind() != lltok::lbrace)
3220 return TokError("expected '{' in function body");
3221 Lex.Lex(); // eat the {.
3223 int FunctionNumber = -1;
3224 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3226 PerFunctionState PFS(*this, Fn, FunctionNumber);
3228 // We need at least one basic block.
3229 if (Lex.getKind() == lltok::rbrace)
3230 return TokError("function body requires at least one basic block");
3232 while (Lex.getKind() != lltok::rbrace)
3233 if (ParseBasicBlock(PFS)) return true;
3238 // Verify function is ok.
3239 return PFS.FinishFunction();
3243 /// ::= LabelStr? Instruction*
3244 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3245 // If this basic block starts out with a name, remember it.
3247 LocTy NameLoc = Lex.getLoc();
3248 if (Lex.getKind() == lltok::LabelStr) {
3249 Name = Lex.getStrVal();
3253 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3254 if (!BB) return true;
3256 std::string NameStr;
3258 // Parse the instructions in this block until we get a terminator.
3261 // This instruction may have three possibilities for a name: a) none
3262 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3263 LocTy NameLoc = Lex.getLoc();
3267 if (Lex.getKind() == lltok::LocalVarID) {
3268 NameID = Lex.getUIntVal();
3270 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3272 } else if (Lex.getKind() == lltok::LocalVar) {
3273 NameStr = Lex.getStrVal();
3275 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3279 switch (ParseInstruction(Inst, BB, PFS)) {
3280 default: llvm_unreachable("Unknown ParseInstruction result!");
3281 case InstError: return true;
3283 BB->getInstList().push_back(Inst);
3285 // With a normal result, we check to see if the instruction is followed by
3286 // a comma and metadata.
3287 if (EatIfPresent(lltok::comma))
3288 if (ParseInstructionMetadata(Inst, &PFS))
3291 case InstExtraComma:
3292 BB->getInstList().push_back(Inst);
3294 // If the instruction parser ate an extra comma at the end of it, it
3295 // *must* be followed by metadata.
3296 if (ParseInstructionMetadata(Inst, &PFS))
3301 // Set the name on the instruction.
3302 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3303 } while (!isa<TerminatorInst>(Inst));
3308 //===----------------------------------------------------------------------===//
3309 // Instruction Parsing.
3310 //===----------------------------------------------------------------------===//
3312 /// ParseInstruction - Parse one of the many different instructions.
3314 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3315 PerFunctionState &PFS) {
3316 lltok::Kind Token = Lex.getKind();
3317 if (Token == lltok::Eof)
3318 return TokError("found end of file when expecting more instructions");
3319 LocTy Loc = Lex.getLoc();
3320 unsigned KeywordVal = Lex.getUIntVal();
3321 Lex.Lex(); // Eat the keyword.
3324 default: return Error(Loc, "expected instruction opcode");
3325 // Terminator Instructions.
3326 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3327 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3328 case lltok::kw_br: return ParseBr(Inst, PFS);
3329 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3330 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3331 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3332 case lltok::kw_resume: return ParseResume(Inst, PFS);
3333 // Binary Operators.
3337 case lltok::kw_shl: {
3338 bool NUW = EatIfPresent(lltok::kw_nuw);
3339 bool NSW = EatIfPresent(lltok::kw_nsw);
3340 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3342 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3344 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3345 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3348 case lltok::kw_fadd:
3349 case lltok::kw_fsub:
3350 case lltok::kw_fmul:
3351 case lltok::kw_fdiv:
3352 case lltok::kw_frem: {
3353 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3354 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3358 Inst->setFastMathFlags(FMF);
3362 case lltok::kw_sdiv:
3363 case lltok::kw_udiv:
3364 case lltok::kw_lshr:
3365 case lltok::kw_ashr: {
3366 bool Exact = EatIfPresent(lltok::kw_exact);
3368 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3369 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3373 case lltok::kw_urem:
3374 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3377 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3378 case lltok::kw_icmp:
3379 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3381 case lltok::kw_trunc:
3382 case lltok::kw_zext:
3383 case lltok::kw_sext:
3384 case lltok::kw_fptrunc:
3385 case lltok::kw_fpext:
3386 case lltok::kw_bitcast:
3387 case lltok::kw_addrspacecast:
3388 case lltok::kw_uitofp:
3389 case lltok::kw_sitofp:
3390 case lltok::kw_fptoui:
3391 case lltok::kw_fptosi:
3392 case lltok::kw_inttoptr:
3393 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3395 case lltok::kw_select: return ParseSelect(Inst, PFS);
3396 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3397 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3398 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3399 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3400 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3401 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3403 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3404 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3405 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3407 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3408 case lltok::kw_load: return ParseLoad(Inst, PFS);
3409 case lltok::kw_store: return ParseStore(Inst, PFS);
3410 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3411 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3412 case lltok::kw_fence: return ParseFence(Inst, PFS);
3413 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3414 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3415 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3419 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3420 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3421 if (Opc == Instruction::FCmp) {
3422 switch (Lex.getKind()) {
3423 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3424 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3425 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3426 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3427 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3428 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3429 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3430 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3431 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3432 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3433 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3434 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3435 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3436 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3437 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3438 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3439 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3442 switch (Lex.getKind()) {
3443 default: return TokError("expected icmp predicate (e.g. 'eq')");
3444 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3445 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3446 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3447 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3448 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3449 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3450 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3451 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3452 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3453 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3460 //===----------------------------------------------------------------------===//
3461 // Terminator Instructions.
3462 //===----------------------------------------------------------------------===//
3464 /// ParseRet - Parse a return instruction.
3465 /// ::= 'ret' void (',' !dbg, !1)*
3466 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3467 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3468 PerFunctionState &PFS) {
3469 SMLoc TypeLoc = Lex.getLoc();
3471 if (ParseType(Ty, true /*void allowed*/)) return true;
3473 Type *ResType = PFS.getFunction().getReturnType();
3475 if (Ty->isVoidTy()) {
3476 if (!ResType->isVoidTy())
3477 return Error(TypeLoc, "value doesn't match function result type '" +
3478 getTypeString(ResType) + "'");
3480 Inst = ReturnInst::Create(Context);
3485 if (ParseValue(Ty, RV, PFS)) return true;
3487 if (ResType != RV->getType())
3488 return Error(TypeLoc, "value doesn't match function result type '" +
3489 getTypeString(ResType) + "'");
3491 Inst = ReturnInst::Create(Context, RV);
3497 /// ::= 'br' TypeAndValue
3498 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3499 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3502 BasicBlock *Op1, *Op2;
3503 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3505 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3506 Inst = BranchInst::Create(BB);
3510 if (Op0->getType() != Type::getInt1Ty(Context))
3511 return Error(Loc, "branch condition must have 'i1' type");
3513 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3514 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3515 ParseToken(lltok::comma, "expected ',' after true destination") ||
3516 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3519 Inst = BranchInst::Create(Op1, Op2, Op0);
3525 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3527 /// ::= (TypeAndValue ',' TypeAndValue)*
3528 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3529 LocTy CondLoc, BBLoc;
3531 BasicBlock *DefaultBB;
3532 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3533 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3534 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3535 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3538 if (!Cond->getType()->isIntegerTy())
3539 return Error(CondLoc, "switch condition must have integer type");
3541 // Parse the jump table pairs.
3542 SmallPtrSet<Value*, 32> SeenCases;
3543 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3544 while (Lex.getKind() != lltok::rsquare) {
3548 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3549 ParseToken(lltok::comma, "expected ',' after case value") ||
3550 ParseTypeAndBasicBlock(DestBB, PFS))
3553 if (!SeenCases.insert(Constant))
3554 return Error(CondLoc, "duplicate case value in switch");
3555 if (!isa<ConstantInt>(Constant))
3556 return Error(CondLoc, "case value is not a constant integer");
3558 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3561 Lex.Lex(); // Eat the ']'.
3563 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3564 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3565 SI->addCase(Table[i].first, Table[i].second);
3572 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3573 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3576 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3577 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3578 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3581 if (!Address->getType()->isPointerTy())
3582 return Error(AddrLoc, "indirectbr address must have pointer type");
3584 // Parse the destination list.
3585 SmallVector<BasicBlock*, 16> DestList;
3587 if (Lex.getKind() != lltok::rsquare) {
3589 if (ParseTypeAndBasicBlock(DestBB, PFS))
3591 DestList.push_back(DestBB);
3593 while (EatIfPresent(lltok::comma)) {
3594 if (ParseTypeAndBasicBlock(DestBB, PFS))
3596 DestList.push_back(DestBB);
3600 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3603 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3604 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3605 IBI->addDestination(DestList[i]);
3612 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3613 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3614 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3615 LocTy CallLoc = Lex.getLoc();
3616 AttrBuilder RetAttrs, FnAttrs;
3617 std::vector<unsigned> FwdRefAttrGrps;
3620 Type *RetType = nullptr;
3623 SmallVector<ParamInfo, 16> ArgList;
3625 BasicBlock *NormalBB, *UnwindBB;
3626 if (ParseOptionalCallingConv(CC) ||
3627 ParseOptionalReturnAttrs(RetAttrs) ||
3628 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3629 ParseValID(CalleeID) ||
3630 ParseParameterList(ArgList, PFS) ||
3631 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3633 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3634 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3635 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3636 ParseTypeAndBasicBlock(UnwindBB, PFS))
3639 // If RetType is a non-function pointer type, then this is the short syntax
3640 // for the call, which means that RetType is just the return type. Infer the
3641 // rest of the function argument types from the arguments that are present.
3642 PointerType *PFTy = nullptr;
3643 FunctionType *Ty = nullptr;
3644 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3645 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3646 // Pull out the types of all of the arguments...
3647 std::vector<Type*> ParamTypes;
3648 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3649 ParamTypes.push_back(ArgList[i].V->getType());
3651 if (!FunctionType::isValidReturnType(RetType))
3652 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3654 Ty = FunctionType::get(RetType, ParamTypes, false);
3655 PFTy = PointerType::getUnqual(Ty);
3658 // Look up the callee.
3660 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3662 // Set up the Attribute for the function.
3663 SmallVector<AttributeSet, 8> Attrs;
3664 if (RetAttrs.hasAttributes())
3665 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3666 AttributeSet::ReturnIndex,
3669 SmallVector<Value*, 8> Args;
3671 // Loop through FunctionType's arguments and ensure they are specified
3672 // correctly. Also, gather any parameter attributes.
3673 FunctionType::param_iterator I = Ty->param_begin();
3674 FunctionType::param_iterator E = Ty->param_end();
3675 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3676 Type *ExpectedTy = nullptr;
3679 } else if (!Ty->isVarArg()) {
3680 return Error(ArgList[i].Loc, "too many arguments specified");
3683 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3684 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3685 getTypeString(ExpectedTy) + "'");
3686 Args.push_back(ArgList[i].V);
3687 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3688 AttrBuilder B(ArgList[i].Attrs, i + 1);
3689 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3694 return Error(CallLoc, "not enough parameters specified for call");
3696 if (FnAttrs.hasAttributes())
3697 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3698 AttributeSet::FunctionIndex,
3701 // Finish off the Attribute and check them
3702 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3704 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3705 II->setCallingConv(CC);
3706 II->setAttributes(PAL);
3707 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3713 /// ::= 'resume' TypeAndValue
3714 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3715 Value *Exn; LocTy ExnLoc;
3716 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3719 ResumeInst *RI = ResumeInst::Create(Exn);
3724 //===----------------------------------------------------------------------===//
3725 // Binary Operators.
3726 //===----------------------------------------------------------------------===//
3729 /// ::= ArithmeticOps TypeAndValue ',' Value
3731 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3732 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3733 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3734 unsigned Opc, unsigned OperandType) {
3735 LocTy Loc; Value *LHS, *RHS;
3736 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3737 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3738 ParseValue(LHS->getType(), RHS, PFS))
3742 switch (OperandType) {
3743 default: llvm_unreachable("Unknown operand type!");
3744 case 0: // int or FP.
3745 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3746 LHS->getType()->isFPOrFPVectorTy();
3748 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3749 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3753 return Error(Loc, "invalid operand type for instruction");
3755 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3760 /// ::= ArithmeticOps TypeAndValue ',' Value {
3761 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3763 LocTy Loc; Value *LHS, *RHS;
3764 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3765 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3766 ParseValue(LHS->getType(), RHS, PFS))
3769 if (!LHS->getType()->isIntOrIntVectorTy())
3770 return Error(Loc,"instruction requires integer or integer vector operands");
3772 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3778 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3779 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3780 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3782 // Parse the integer/fp comparison predicate.
3786 if (ParseCmpPredicate(Pred, Opc) ||
3787 ParseTypeAndValue(LHS, Loc, PFS) ||
3788 ParseToken(lltok::comma, "expected ',' after compare value") ||
3789 ParseValue(LHS->getType(), RHS, PFS))
3792 if (Opc == Instruction::FCmp) {
3793 if (!LHS->getType()->isFPOrFPVectorTy())
3794 return Error(Loc, "fcmp requires floating point operands");
3795 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3797 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3798 if (!LHS->getType()->isIntOrIntVectorTy() &&
3799 !LHS->getType()->getScalarType()->isPointerTy())
3800 return Error(Loc, "icmp requires integer operands");
3801 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3806 //===----------------------------------------------------------------------===//
3807 // Other Instructions.
3808 //===----------------------------------------------------------------------===//
3812 /// ::= CastOpc TypeAndValue 'to' Type
3813 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3817 Type *DestTy = nullptr;
3818 if (ParseTypeAndValue(Op, Loc, PFS) ||
3819 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3823 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3824 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3825 return Error(Loc, "invalid cast opcode for cast from '" +
3826 getTypeString(Op->getType()) + "' to '" +
3827 getTypeString(DestTy) + "'");
3829 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3834 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3835 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3837 Value *Op0, *Op1, *Op2;
3838 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3839 ParseToken(lltok::comma, "expected ',' after select condition") ||
3840 ParseTypeAndValue(Op1, PFS) ||
3841 ParseToken(lltok::comma, "expected ',' after select value") ||
3842 ParseTypeAndValue(Op2, PFS))
3845 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3846 return Error(Loc, Reason);
3848 Inst = SelectInst::Create(Op0, Op1, Op2);
3853 /// ::= 'va_arg' TypeAndValue ',' Type
3854 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3856 Type *EltTy = nullptr;
3858 if (ParseTypeAndValue(Op, PFS) ||
3859 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3860 ParseType(EltTy, TypeLoc))
3863 if (!EltTy->isFirstClassType())
3864 return Error(TypeLoc, "va_arg requires operand with first class type");
3866 Inst = new VAArgInst(Op, EltTy);
3870 /// ParseExtractElement
3871 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3872 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3875 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3876 ParseToken(lltok::comma, "expected ',' after extract value") ||
3877 ParseTypeAndValue(Op1, PFS))
3880 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3881 return Error(Loc, "invalid extractelement operands");
3883 Inst = ExtractElementInst::Create(Op0, Op1);
3887 /// ParseInsertElement
3888 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3889 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3891 Value *Op0, *Op1, *Op2;
3892 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3893 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3894 ParseTypeAndValue(Op1, PFS) ||
3895 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3896 ParseTypeAndValue(Op2, PFS))
3899 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3900 return Error(Loc, "invalid insertelement operands");
3902 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3906 /// ParseShuffleVector
3907 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3908 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3910 Value *Op0, *Op1, *Op2;
3911 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3912 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3913 ParseTypeAndValue(Op1, PFS) ||
3914 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3915 ParseTypeAndValue(Op2, PFS))
3918 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3919 return Error(Loc, "invalid shufflevector operands");
3921 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3926 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3927 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3928 Type *Ty = nullptr; LocTy TypeLoc;
3931 if (ParseType(Ty, TypeLoc) ||
3932 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3933 ParseValue(Ty, Op0, PFS) ||
3934 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3935 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3936 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3939 bool AteExtraComma = false;
3940 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3942 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3944 if (!EatIfPresent(lltok::comma))
3947 if (Lex.getKind() == lltok::MetadataVar) {
3948 AteExtraComma = true;
3952 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3953 ParseValue(Ty, Op0, PFS) ||
3954 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3955 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3956 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3960 if (!Ty->isFirstClassType())
3961 return Error(TypeLoc, "phi node must have first class type");
3963 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3964 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3965 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3967 return AteExtraComma ? InstExtraComma : InstNormal;
3971 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3973 /// ::= 'catch' TypeAndValue
3975 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3976 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3977 Type *Ty = nullptr; LocTy TyLoc;
3978 Value *PersFn; LocTy PersFnLoc;
3980 if (ParseType(Ty, TyLoc) ||
3981 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3982 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3985 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3986 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3988 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3989 LandingPadInst::ClauseType CT;
3990 if (EatIfPresent(lltok::kw_catch))
3991 CT = LandingPadInst::Catch;
3992 else if (EatIfPresent(lltok::kw_filter))
3993 CT = LandingPadInst::Filter;
3995 return TokError("expected 'catch' or 'filter' clause type");
3999 if (ParseTypeAndValue(V, VLoc, PFS)) {
4004 // A 'catch' type expects a non-array constant. A filter clause expects an
4006 if (CT == LandingPadInst::Catch) {
4007 if (isa<ArrayType>(V->getType()))
4008 Error(VLoc, "'catch' clause has an invalid type");
4010 if (!isa<ArrayType>(V->getType()))
4011 Error(VLoc, "'filter' clause has an invalid type");
4014 LP->addClause(cast<Constant>(V));
4022 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4023 /// ParameterList OptionalAttrs
4024 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4025 /// ParameterList OptionalAttrs
4026 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4027 /// ParameterList OptionalAttrs
4028 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4029 CallInst::TailCallKind TCK) {
4030 AttrBuilder RetAttrs, FnAttrs;
4031 std::vector<unsigned> FwdRefAttrGrps;
4034 Type *RetType = nullptr;
4037 SmallVector<ParamInfo, 16> ArgList;
4038 LocTy CallLoc = Lex.getLoc();
4040 if ((TCK != CallInst::TCK_None &&
4041 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4042 ParseOptionalCallingConv(CC) ||
4043 ParseOptionalReturnAttrs(RetAttrs) ||
4044 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4045 ParseValID(CalleeID) ||
4046 ParseParameterList(ArgList, PFS) ||
4047 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4051 // If RetType is a non-function pointer type, then this is the short syntax
4052 // for the call, which means that RetType is just the return type. Infer the
4053 // rest of the function argument types from the arguments that are present.
4054 PointerType *PFTy = nullptr;
4055 FunctionType *Ty = nullptr;
4056 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4057 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4058 // Pull out the types of all of the arguments...
4059 std::vector<Type*> ParamTypes;
4060 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4061 ParamTypes.push_back(ArgList[i].V->getType());
4063 if (!FunctionType::isValidReturnType(RetType))
4064 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4066 Ty = FunctionType::get(RetType, ParamTypes, false);
4067 PFTy = PointerType::getUnqual(Ty);
4070 // Look up the callee.
4072 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4074 // Set up the Attribute for the function.
4075 SmallVector<AttributeSet, 8> Attrs;
4076 if (RetAttrs.hasAttributes())
4077 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4078 AttributeSet::ReturnIndex,
4081 SmallVector<Value*, 8> Args;
4083 // Loop through FunctionType's arguments and ensure they are specified
4084 // correctly. Also, gather any parameter attributes.
4085 FunctionType::param_iterator I = Ty->param_begin();
4086 FunctionType::param_iterator E = Ty->param_end();
4087 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4088 Type *ExpectedTy = nullptr;
4091 } else if (!Ty->isVarArg()) {
4092 return Error(ArgList[i].Loc, "too many arguments specified");
4095 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4096 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4097 getTypeString(ExpectedTy) + "'");
4098 Args.push_back(ArgList[i].V);
4099 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4100 AttrBuilder B(ArgList[i].Attrs, i + 1);
4101 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4106 return Error(CallLoc, "not enough parameters specified for call");
4108 if (FnAttrs.hasAttributes())
4109 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4110 AttributeSet::FunctionIndex,
4113 // Finish off the Attribute and check them
4114 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4116 CallInst *CI = CallInst::Create(Callee, Args);
4117 CI->setTailCallKind(TCK);
4118 CI->setCallingConv(CC);
4119 CI->setAttributes(PAL);
4120 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4125 //===----------------------------------------------------------------------===//
4126 // Memory Instructions.
4127 //===----------------------------------------------------------------------===//
4130 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4131 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4132 Value *Size = nullptr;
4134 unsigned Alignment = 0;
4137 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4139 if (ParseType(Ty)) return true;
4141 bool AteExtraComma = false;
4142 if (EatIfPresent(lltok::comma)) {
4143 if (Lex.getKind() == lltok::kw_align) {
4144 if (ParseOptionalAlignment(Alignment)) return true;
4145 } else if (Lex.getKind() == lltok::MetadataVar) {
4146 AteExtraComma = true;
4148 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4149 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4154 if (Size && !Size->getType()->isIntegerTy())
4155 return Error(SizeLoc, "element count must have integer type");
4157 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4158 AI->setUsedWithInAlloca(IsInAlloca);
4160 return AteExtraComma ? InstExtraComma : InstNormal;
4164 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4165 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4166 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4167 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4168 Value *Val; LocTy Loc;
4169 unsigned Alignment = 0;
4170 bool AteExtraComma = false;
4171 bool isAtomic = false;
4172 AtomicOrdering Ordering = NotAtomic;
4173 SynchronizationScope Scope = CrossThread;
4175 if (Lex.getKind() == lltok::kw_atomic) {
4180 bool isVolatile = false;
4181 if (Lex.getKind() == lltok::kw_volatile) {
4186 if (ParseTypeAndValue(Val, Loc, PFS) ||
4187 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4188 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4191 if (!Val->getType()->isPointerTy() ||
4192 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4193 return Error(Loc, "load operand must be a pointer to a first class type");
4194 if (isAtomic && !Alignment)
4195 return Error(Loc, "atomic load must have explicit non-zero alignment");
4196 if (Ordering == Release || Ordering == AcquireRelease)
4197 return Error(Loc, "atomic load cannot use Release ordering");
4199 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4200 return AteExtraComma ? InstExtraComma : InstNormal;
4205 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4206 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4207 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4208 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4209 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4210 unsigned Alignment = 0;
4211 bool AteExtraComma = false;
4212 bool isAtomic = false;
4213 AtomicOrdering Ordering = NotAtomic;
4214 SynchronizationScope Scope = CrossThread;
4216 if (Lex.getKind() == lltok::kw_atomic) {
4221 bool isVolatile = false;
4222 if (Lex.getKind() == lltok::kw_volatile) {
4227 if (ParseTypeAndValue(Val, Loc, PFS) ||
4228 ParseToken(lltok::comma, "expected ',' after store operand") ||
4229 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4230 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4231 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4234 if (!Ptr->getType()->isPointerTy())
4235 return Error(PtrLoc, "store operand must be a pointer");
4236 if (!Val->getType()->isFirstClassType())
4237 return Error(Loc, "store operand must be a first class value");
4238 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4239 return Error(Loc, "stored value and pointer type do not match");
4240 if (isAtomic && !Alignment)
4241 return Error(Loc, "atomic store must have explicit non-zero alignment");
4242 if (Ordering == Acquire || Ordering == AcquireRelease)
4243 return Error(Loc, "atomic store cannot use Acquire ordering");
4245 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4246 return AteExtraComma ? InstExtraComma : InstNormal;
4250 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4251 /// 'singlethread'? AtomicOrdering AtomicOrdering
4252 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4253 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4254 bool AteExtraComma = false;
4255 AtomicOrdering SuccessOrdering = NotAtomic;
4256 AtomicOrdering FailureOrdering = NotAtomic;
4257 SynchronizationScope Scope = CrossThread;
4258 bool isVolatile = false;
4260 if (EatIfPresent(lltok::kw_volatile))
4263 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4264 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4265 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4266 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4267 ParseTypeAndValue(New, NewLoc, PFS) ||
4268 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4269 ParseOrdering(FailureOrdering))
4272 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4273 return TokError("cmpxchg cannot be unordered");
4274 if (SuccessOrdering < FailureOrdering)
4275 return TokError("cmpxchg must be at least as ordered on success as failure");
4276 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4277 return TokError("cmpxchg failure ordering cannot include release semantics");
4278 if (!Ptr->getType()->isPointerTy())
4279 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4280 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4281 return Error(CmpLoc, "compare value and pointer type do not match");
4282 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4283 return Error(NewLoc, "new value and pointer type do not match");
4284 if (!New->getType()->isIntegerTy())
4285 return Error(NewLoc, "cmpxchg operand must be an integer");
4286 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4287 if (Size < 8 || (Size & (Size - 1)))
4288 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4291 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4292 FailureOrdering, Scope);
4293 CXI->setVolatile(isVolatile);
4295 return AteExtraComma ? InstExtraComma : InstNormal;
4299 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4300 /// 'singlethread'? AtomicOrdering
4301 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4302 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4303 bool AteExtraComma = false;
4304 AtomicOrdering Ordering = NotAtomic;
4305 SynchronizationScope Scope = CrossThread;
4306 bool isVolatile = false;
4307 AtomicRMWInst::BinOp Operation;
4309 if (EatIfPresent(lltok::kw_volatile))
4312 switch (Lex.getKind()) {
4313 default: return TokError("expected binary operation in atomicrmw");
4314 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4315 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4316 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4317 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4318 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4319 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4320 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4321 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4322 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4323 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4324 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4326 Lex.Lex(); // Eat the operation.
4328 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4329 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4330 ParseTypeAndValue(Val, ValLoc, PFS) ||
4331 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4334 if (Ordering == Unordered)
4335 return TokError("atomicrmw cannot be unordered");
4336 if (!Ptr->getType()->isPointerTy())
4337 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4338 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4339 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4340 if (!Val->getType()->isIntegerTy())
4341 return Error(ValLoc, "atomicrmw operand must be an integer");
4342 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4343 if (Size < 8 || (Size & (Size - 1)))
4344 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4347 AtomicRMWInst *RMWI =
4348 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4349 RMWI->setVolatile(isVolatile);
4351 return AteExtraComma ? InstExtraComma : InstNormal;
4355 /// ::= 'fence' 'singlethread'? AtomicOrdering
4356 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4357 AtomicOrdering Ordering = NotAtomic;
4358 SynchronizationScope Scope = CrossThread;
4359 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4362 if (Ordering == Unordered)
4363 return TokError("fence cannot be unordered");
4364 if (Ordering == Monotonic)
4365 return TokError("fence cannot be monotonic");
4367 Inst = new FenceInst(Context, Ordering, Scope);
4371 /// ParseGetElementPtr
4372 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4373 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4374 Value *Ptr = nullptr;
4375 Value *Val = nullptr;
4378 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4380 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4382 Type *BaseType = Ptr->getType();
4383 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4384 if (!BasePointerType)
4385 return Error(Loc, "base of getelementptr must be a pointer");
4387 SmallVector<Value*, 16> Indices;
4388 bool AteExtraComma = false;
4389 while (EatIfPresent(lltok::comma)) {
4390 if (Lex.getKind() == lltok::MetadataVar) {
4391 AteExtraComma = true;
4394 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4395 if (!Val->getType()->getScalarType()->isIntegerTy())
4396 return Error(EltLoc, "getelementptr index must be an integer");
4397 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4398 return Error(EltLoc, "getelementptr index type missmatch");
4399 if (Val->getType()->isVectorTy()) {
4400 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4401 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4402 if (ValNumEl != PtrNumEl)
4403 return Error(EltLoc,
4404 "getelementptr vector index has a wrong number of elements");
4406 Indices.push_back(Val);
4409 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4410 return Error(Loc, "base element of getelementptr must be sized");
4412 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4413 return Error(Loc, "invalid getelementptr indices");
4414 Inst = GetElementPtrInst::Create(Ptr, Indices);
4416 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4417 return AteExtraComma ? InstExtraComma : InstNormal;
4420 /// ParseExtractValue
4421 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4422 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4423 Value *Val; LocTy Loc;
4424 SmallVector<unsigned, 4> Indices;
4426 if (ParseTypeAndValue(Val, Loc, PFS) ||
4427 ParseIndexList(Indices, AteExtraComma))
4430 if (!Val->getType()->isAggregateType())
4431 return Error(Loc, "extractvalue operand must be aggregate type");
4433 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4434 return Error(Loc, "invalid indices for extractvalue");
4435 Inst = ExtractValueInst::Create(Val, Indices);
4436 return AteExtraComma ? InstExtraComma : InstNormal;
4439 /// ParseInsertValue
4440 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4441 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4442 Value *Val0, *Val1; LocTy Loc0, Loc1;
4443 SmallVector<unsigned, 4> Indices;
4445 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4446 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4447 ParseTypeAndValue(Val1, Loc1, PFS) ||
4448 ParseIndexList(Indices, AteExtraComma))
4451 if (!Val0->getType()->isAggregateType())
4452 return Error(Loc0, "insertvalue operand must be aggregate type");
4454 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4455 return Error(Loc0, "invalid indices for insertvalue");
4456 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4457 return AteExtraComma ? InstExtraComma : InstNormal;
4460 //===----------------------------------------------------------------------===//
4461 // Embedded metadata.
4462 //===----------------------------------------------------------------------===//
4464 /// ParseMDNodeVector
4465 /// ::= Element (',' Element)*
4467 /// ::= 'null' | TypeAndValue
4468 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4469 PerFunctionState *PFS) {
4470 // Check for an empty list.
4471 if (Lex.getKind() == lltok::rbrace)
4475 // Null is a special case since it is typeless.
4476 if (EatIfPresent(lltok::kw_null)) {
4477 Elts.push_back(nullptr);
4482 if (ParseTypeAndValue(V, PFS)) return true;
4484 } while (EatIfPresent(lltok::comma));