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/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 static std::string getTypeString(Type *T) {
31 raw_string_ostream Tmp(Result);
36 /// Run: module ::= toplevelentity*
37 bool LLParser::Run() {
41 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
45 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47 bool LLParser::ValidateEndOfModule() {
48 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
62 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
65 ForwardRefInstMetadata.clear();
69 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
92 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
93 if (NumberedTypes[i].second.isValid())
94 return Error(NumberedTypes[i].second,
95 "use of undefined type '%" + Twine(i) + "'");
97 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
99 if (I->second.second.isValid())
100 return Error(I->second.second,
101 "use of undefined type named '" + I->getKey() + "'");
103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
111 Twine(ForwardRefValIDs.begin()->first) + "'");
113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
116 Twine(ForwardRefMDNodes.begin()->first) + "'");
119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
126 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
127 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
128 PerFunctionState *PFS) {
129 // Loop over all the references, resolving them.
130 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
133 if (Refs[i].first.Kind == ValID::t_LocalName)
134 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
136 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
137 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
138 return Error(Refs[i].first.Loc,
139 "cannot take address of numeric label after the function is defined");
141 Res = dyn_cast_or_null<BasicBlock>(
142 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
146 return Error(Refs[i].first.Loc,
147 "referenced value is not a basic block");
149 // Get the BlockAddress for this and update references to use it.
150 BlockAddress *BA = BlockAddress::get(TheFn, Res);
151 Refs[i].second->replaceAllUsesWith(BA);
152 Refs[i].second->eraseFromParent();
158 //===----------------------------------------------------------------------===//
159 // Top-Level Entities
160 //===----------------------------------------------------------------------===//
162 bool LLParser::ParseTopLevelEntities() {
164 switch (Lex.getKind()) {
165 default: return TokError("expected top-level entity");
166 case lltok::Eof: return false;
167 case lltok::kw_declare: if (ParseDeclare()) return true; break;
168 case lltok::kw_define: if (ParseDefine()) return true; break;
169 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
171 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
172 case lltok::LocalVar: if (ParseNamedType()) return true; break;
173 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
174 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
175 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
176 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
178 // The Global variable production with no name can have many different
179 // optional leading prefixes, the production is:
180 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
181 // OptionalAddrSpace OptionalUnNammedAddr
182 // ('constant'|'global') ...
183 case lltok::kw_private: // OptionalLinkage
184 case lltok::kw_linker_private: // OptionalLinkage
185 case lltok::kw_linker_private_weak: // OptionalLinkage
186 case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
187 case lltok::kw_internal: // OptionalLinkage
188 case lltok::kw_weak: // OptionalLinkage
189 case lltok::kw_weak_odr: // OptionalLinkage
190 case lltok::kw_linkonce: // OptionalLinkage
191 case lltok::kw_linkonce_odr: // OptionalLinkage
192 case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage
193 case lltok::kw_appending: // OptionalLinkage
194 case lltok::kw_dllexport: // OptionalLinkage
195 case lltok::kw_common: // OptionalLinkage
196 case lltok::kw_dllimport: // OptionalLinkage
197 case lltok::kw_extern_weak: // OptionalLinkage
198 case lltok::kw_external: { // OptionalLinkage
199 unsigned Linkage, Visibility;
200 if (ParseOptionalLinkage(Linkage) ||
201 ParseOptionalVisibility(Visibility) ||
202 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
206 case lltok::kw_default: // OptionalVisibility
207 case lltok::kw_hidden: // OptionalVisibility
208 case lltok::kw_protected: { // OptionalVisibility
210 if (ParseOptionalVisibility(Visibility) ||
211 ParseGlobal("", SMLoc(), 0, false, Visibility))
216 case lltok::kw_thread_local: // OptionalThreadLocal
217 case lltok::kw_addrspace: // OptionalAddrSpace
218 case lltok::kw_constant: // GlobalType
219 case lltok::kw_global: // GlobalType
220 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
228 /// ::= 'module' 'asm' STRINGCONSTANT
229 bool LLParser::ParseModuleAsm() {
230 assert(Lex.getKind() == lltok::kw_module);
234 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
235 ParseStringConstant(AsmStr)) return true;
237 M->appendModuleInlineAsm(AsmStr);
242 /// ::= 'target' 'triple' '=' STRINGCONSTANT
243 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
244 bool LLParser::ParseTargetDefinition() {
245 assert(Lex.getKind() == lltok::kw_target);
248 default: return TokError("unknown target property");
249 case lltok::kw_triple:
251 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
252 ParseStringConstant(Str))
254 M->setTargetTriple(Str);
256 case lltok::kw_datalayout:
258 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
259 ParseStringConstant(Str))
261 M->setDataLayout(Str);
266 /// ParseUnnamedType:
267 /// ::= LocalVarID '=' 'type' type
268 bool LLParser::ParseUnnamedType() {
269 LocTy TypeLoc = Lex.getLoc();
270 unsigned TypeID = Lex.getUIntVal();
271 Lex.Lex(); // eat LocalVarID;
273 if (ParseToken(lltok::equal, "expected '=' after name") ||
274 ParseToken(lltok::kw_type, "expected 'type' after '='"))
277 if (TypeID >= NumberedTypes.size())
278 NumberedTypes.resize(TypeID+1);
281 if (ParseStructDefinition(TypeLoc, "",
282 NumberedTypes[TypeID], Result)) return true;
284 if (!isa<StructType>(Result)) {
285 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
287 return Error(TypeLoc, "non-struct types may not be recursive");
288 Entry.first = Result;
289 Entry.second = SMLoc();
297 /// ::= LocalVar '=' 'type' type
298 bool LLParser::ParseNamedType() {
299 std::string Name = Lex.getStrVal();
300 LocTy NameLoc = Lex.getLoc();
301 Lex.Lex(); // eat LocalVar.
303 if (ParseToken(lltok::equal, "expected '=' after name") ||
304 ParseToken(lltok::kw_type, "expected 'type' after name"))
308 if (ParseStructDefinition(NameLoc, Name,
309 NamedTypes[Name], Result)) return true;
311 if (!isa<StructType>(Result)) {
312 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
314 return Error(NameLoc, "non-struct types may not be recursive");
315 Entry.first = Result;
316 Entry.second = SMLoc();
324 /// ::= 'declare' FunctionHeader
325 bool LLParser::ParseDeclare() {
326 assert(Lex.getKind() == lltok::kw_declare);
330 return ParseFunctionHeader(F, false);
334 /// ::= 'define' FunctionHeader '{' ...
335 bool LLParser::ParseDefine() {
336 assert(Lex.getKind() == lltok::kw_define);
340 return ParseFunctionHeader(F, true) ||
341 ParseFunctionBody(*F);
347 bool LLParser::ParseGlobalType(bool &IsConstant) {
348 if (Lex.getKind() == lltok::kw_constant)
350 else if (Lex.getKind() == lltok::kw_global)
354 return TokError("expected 'global' or 'constant'");
360 /// ParseUnnamedGlobal:
361 /// OptionalVisibility ALIAS ...
362 /// OptionalLinkage OptionalVisibility ... -> global variable
363 /// GlobalID '=' OptionalVisibility ALIAS ...
364 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
365 bool LLParser::ParseUnnamedGlobal() {
366 unsigned VarID = NumberedVals.size();
368 LocTy NameLoc = Lex.getLoc();
370 // Handle the GlobalID form.
371 if (Lex.getKind() == lltok::GlobalID) {
372 if (Lex.getUIntVal() != VarID)
373 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
375 Lex.Lex(); // eat GlobalID;
377 if (ParseToken(lltok::equal, "expected '=' after name"))
382 unsigned Linkage, Visibility;
383 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
384 ParseOptionalVisibility(Visibility))
387 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
388 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
389 return ParseAlias(Name, NameLoc, Visibility);
392 /// ParseNamedGlobal:
393 /// GlobalVar '=' OptionalVisibility ALIAS ...
394 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
395 bool LLParser::ParseNamedGlobal() {
396 assert(Lex.getKind() == lltok::GlobalVar);
397 LocTy NameLoc = Lex.getLoc();
398 std::string Name = Lex.getStrVal();
402 unsigned Linkage, Visibility;
403 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
404 ParseOptionalLinkage(Linkage, HasLinkage) ||
405 ParseOptionalVisibility(Visibility))
408 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
409 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
410 return ParseAlias(Name, NameLoc, Visibility);
414 // ::= '!' STRINGCONSTANT
415 bool LLParser::ParseMDString(MDString *&Result) {
417 if (ParseStringConstant(Str)) return true;
418 Result = MDString::get(Context, Str);
423 // ::= '!' MDNodeNumber
425 /// This version of ParseMDNodeID returns the slot number and null in the case
426 /// of a forward reference.
427 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
428 // !{ ..., !42, ... }
429 if (ParseUInt32(SlotNo)) return true;
431 // Check existing MDNode.
432 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
433 Result = NumberedMetadata[SlotNo];
439 bool LLParser::ParseMDNodeID(MDNode *&Result) {
440 // !{ ..., !42, ... }
442 if (ParseMDNodeID(Result, MID)) return true;
444 // If not a forward reference, just return it now.
445 if (Result) return false;
447 // Otherwise, create MDNode forward reference.
448 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
449 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
451 if (NumberedMetadata.size() <= MID)
452 NumberedMetadata.resize(MID+1);
453 NumberedMetadata[MID] = FwdNode;
458 /// ParseNamedMetadata:
459 /// !foo = !{ !1, !2 }
460 bool LLParser::ParseNamedMetadata() {
461 assert(Lex.getKind() == lltok::MetadataVar);
462 std::string Name = Lex.getStrVal();
465 if (ParseToken(lltok::equal, "expected '=' here") ||
466 ParseToken(lltok::exclaim, "Expected '!' here") ||
467 ParseToken(lltok::lbrace, "Expected '{' here"))
470 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
471 if (Lex.getKind() != lltok::rbrace)
473 if (ParseToken(lltok::exclaim, "Expected '!' here"))
477 if (ParseMDNodeID(N)) return true;
479 } while (EatIfPresent(lltok::comma));
481 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
487 /// ParseStandaloneMetadata:
489 bool LLParser::ParseStandaloneMetadata() {
490 assert(Lex.getKind() == lltok::exclaim);
492 unsigned MetadataID = 0;
496 SmallVector<Value *, 16> Elts;
497 if (ParseUInt32(MetadataID) ||
498 ParseToken(lltok::equal, "expected '=' here") ||
499 ParseType(Ty, TyLoc) ||
500 ParseToken(lltok::exclaim, "Expected '!' here") ||
501 ParseToken(lltok::lbrace, "Expected '{' here") ||
502 ParseMDNodeVector(Elts, NULL) ||
503 ParseToken(lltok::rbrace, "expected end of metadata node"))
506 MDNode *Init = MDNode::get(Context, Elts);
508 // See if this was forward referenced, if so, handle it.
509 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
510 FI = ForwardRefMDNodes.find(MetadataID);
511 if (FI != ForwardRefMDNodes.end()) {
512 MDNode *Temp = FI->second.first;
513 Temp->replaceAllUsesWith(Init);
514 MDNode::deleteTemporary(Temp);
515 ForwardRefMDNodes.erase(FI);
517 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
519 if (MetadataID >= NumberedMetadata.size())
520 NumberedMetadata.resize(MetadataID+1);
522 if (NumberedMetadata[MetadataID] != 0)
523 return TokError("Metadata id is already used");
524 NumberedMetadata[MetadataID] = Init;
531 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
534 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
535 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
537 /// Everything through visibility has already been parsed.
539 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
540 unsigned Visibility) {
541 assert(Lex.getKind() == lltok::kw_alias);
544 LocTy LinkageLoc = Lex.getLoc();
545 if (ParseOptionalLinkage(Linkage))
548 if (Linkage != GlobalValue::ExternalLinkage &&
549 Linkage != GlobalValue::WeakAnyLinkage &&
550 Linkage != GlobalValue::WeakODRLinkage &&
551 Linkage != GlobalValue::InternalLinkage &&
552 Linkage != GlobalValue::PrivateLinkage &&
553 Linkage != GlobalValue::LinkerPrivateLinkage &&
554 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
555 return Error(LinkageLoc, "invalid linkage type for alias");
558 LocTy AliaseeLoc = Lex.getLoc();
559 if (Lex.getKind() != lltok::kw_bitcast &&
560 Lex.getKind() != lltok::kw_getelementptr) {
561 if (ParseGlobalTypeAndValue(Aliasee)) return true;
563 // The bitcast dest type is not present, it is implied by the dest type.
565 if (ParseValID(ID)) return true;
566 if (ID.Kind != ValID::t_Constant)
567 return Error(AliaseeLoc, "invalid aliasee");
568 Aliasee = ID.ConstantVal;
571 if (!Aliasee->getType()->isPointerTy())
572 return Error(AliaseeLoc, "alias must have pointer type");
574 // Okay, create the alias but do not insert it into the module yet.
575 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
576 (GlobalValue::LinkageTypes)Linkage, Name,
578 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
580 // See if this value already exists in the symbol table. If so, it is either
581 // a redefinition or a definition of a forward reference.
582 if (GlobalValue *Val = M->getNamedValue(Name)) {
583 // See if this was a redefinition. If so, there is no entry in
585 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
586 I = ForwardRefVals.find(Name);
587 if (I == ForwardRefVals.end())
588 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
590 // Otherwise, this was a definition of forward ref. Verify that types
592 if (Val->getType() != GA->getType())
593 return Error(NameLoc,
594 "forward reference and definition of alias have different types");
596 // If they agree, just RAUW the old value with the alias and remove the
598 Val->replaceAllUsesWith(GA);
599 Val->eraseFromParent();
600 ForwardRefVals.erase(I);
603 // Insert into the module, we know its name won't collide now.
604 M->getAliasList().push_back(GA);
605 assert(GA->getName() == Name && "Should not be a name conflict!");
611 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
612 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
613 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
614 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
616 /// Everything through visibility has been parsed already.
618 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
619 unsigned Linkage, bool HasLinkage,
620 unsigned Visibility) {
622 bool IsConstant, UnnamedAddr;
623 GlobalVariable::ThreadLocalMode TLM;
624 LocTy UnnamedAddrLoc;
628 if (ParseOptionalThreadLocal(TLM) ||
629 ParseOptionalAddrSpace(AddrSpace) ||
630 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
632 ParseGlobalType(IsConstant) ||
633 ParseType(Ty, TyLoc))
636 // If the linkage is specified and is external, then no initializer is
639 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
640 Linkage != GlobalValue::ExternalWeakLinkage &&
641 Linkage != GlobalValue::ExternalLinkage)) {
642 if (ParseGlobalValue(Ty, Init))
646 if (Ty->isFunctionTy() || Ty->isLabelTy())
647 return Error(TyLoc, "invalid type for global variable");
649 GlobalVariable *GV = 0;
651 // See if the global was forward referenced, if so, use the global.
653 if (GlobalValue *GVal = M->getNamedValue(Name)) {
654 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
655 return Error(NameLoc, "redefinition of global '@" + Name + "'");
656 GV = cast<GlobalVariable>(GVal);
659 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
660 I = ForwardRefValIDs.find(NumberedVals.size());
661 if (I != ForwardRefValIDs.end()) {
662 GV = cast<GlobalVariable>(I->second.first);
663 ForwardRefValIDs.erase(I);
668 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
669 Name, 0, GlobalVariable::NotThreadLocal,
672 if (GV->getType()->getElementType() != Ty)
674 "forward reference and definition of global have different types");
676 // Move the forward-reference to the correct spot in the module.
677 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
681 NumberedVals.push_back(GV);
683 // Set the parsed properties on the global.
685 GV->setInitializer(Init);
686 GV->setConstant(IsConstant);
687 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
688 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
689 GV->setThreadLocalMode(TLM);
690 GV->setUnnamedAddr(UnnamedAddr);
692 // Parse attributes on the global.
693 while (Lex.getKind() == lltok::comma) {
696 if (Lex.getKind() == lltok::kw_section) {
698 GV->setSection(Lex.getStrVal());
699 if (ParseToken(lltok::StringConstant, "expected global section string"))
701 } else if (Lex.getKind() == lltok::kw_align) {
703 if (ParseOptionalAlignment(Alignment)) return true;
704 GV->setAlignment(Alignment);
706 TokError("unknown global variable property!");
714 //===----------------------------------------------------------------------===//
715 // GlobalValue Reference/Resolution Routines.
716 //===----------------------------------------------------------------------===//
718 /// GetGlobalVal - Get a value with the specified name or ID, creating a
719 /// forward reference record if needed. This can return null if the value
720 /// exists but does not have the right type.
721 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
723 PointerType *PTy = dyn_cast<PointerType>(Ty);
725 Error(Loc, "global variable reference must have pointer type");
729 // Look this name up in the normal function symbol table.
731 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
733 // If this is a forward reference for the value, see if we already created a
734 // forward ref record.
736 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
737 I = ForwardRefVals.find(Name);
738 if (I != ForwardRefVals.end())
739 Val = I->second.first;
742 // If we have the value in the symbol table or fwd-ref table, return it.
744 if (Val->getType() == Ty) return Val;
745 Error(Loc, "'@" + Name + "' defined with type '" +
746 getTypeString(Val->getType()) + "'");
750 // Otherwise, create a new forward reference for this value and remember it.
752 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
753 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
755 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
756 GlobalValue::ExternalWeakLinkage, 0, Name,
757 0, GlobalVariable::NotThreadLocal,
758 PTy->getAddressSpace());
760 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
764 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
765 PointerType *PTy = dyn_cast<PointerType>(Ty);
767 Error(Loc, "global variable reference must have pointer type");
771 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
773 // If this is a forward reference for the value, see if we already created a
774 // forward ref record.
776 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
777 I = ForwardRefValIDs.find(ID);
778 if (I != ForwardRefValIDs.end())
779 Val = I->second.first;
782 // If we have the value in the symbol table or fwd-ref table, return it.
784 if (Val->getType() == Ty) return Val;
785 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
786 getTypeString(Val->getType()) + "'");
790 // Otherwise, create a new forward reference for this value and remember it.
792 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
793 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
795 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
796 GlobalValue::ExternalWeakLinkage, 0, "");
798 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
803 //===----------------------------------------------------------------------===//
805 //===----------------------------------------------------------------------===//
807 /// ParseToken - If the current token has the specified kind, eat it and return
808 /// success. Otherwise, emit the specified error and return failure.
809 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
810 if (Lex.getKind() != T)
811 return TokError(ErrMsg);
816 /// ParseStringConstant
817 /// ::= StringConstant
818 bool LLParser::ParseStringConstant(std::string &Result) {
819 if (Lex.getKind() != lltok::StringConstant)
820 return TokError("expected string constant");
821 Result = Lex.getStrVal();
828 bool LLParser::ParseUInt32(unsigned &Val) {
829 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
830 return TokError("expected integer");
831 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
832 if (Val64 != unsigned(Val64))
833 return TokError("expected 32-bit integer (too large)");
840 /// := 'localdynamic'
843 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
844 switch (Lex.getKind()) {
846 return TokError("expected localdynamic, initialexec or localexec");
847 case lltok::kw_localdynamic:
848 TLM = GlobalVariable::LocalDynamicTLSModel;
850 case lltok::kw_initialexec:
851 TLM = GlobalVariable::InitialExecTLSModel;
853 case lltok::kw_localexec:
854 TLM = GlobalVariable::LocalExecTLSModel;
862 /// ParseOptionalThreadLocal
864 /// := 'thread_local'
865 /// := 'thread_local' '(' tlsmodel ')'
866 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
867 TLM = GlobalVariable::NotThreadLocal;
868 if (!EatIfPresent(lltok::kw_thread_local))
871 TLM = GlobalVariable::GeneralDynamicTLSModel;
872 if (Lex.getKind() == lltok::lparen) {
874 return ParseTLSModel(TLM) ||
875 ParseToken(lltok::rparen, "expected ')' after thread local model");
880 /// ParseOptionalAddrSpace
882 /// := 'addrspace' '(' uint32 ')'
883 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
885 if (!EatIfPresent(lltok::kw_addrspace))
887 return ParseToken(lltok::lparen, "expected '(' in address space") ||
888 ParseUInt32(AddrSpace) ||
889 ParseToken(lltok::rparen, "expected ')' in address space");
892 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
893 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
894 /// 2: function attr.
895 bool LLParser::ParseOptionalAttrs(AttrBuilder &B, unsigned AttrKind) {
896 LocTy AttrLoc = Lex.getLoc();
897 bool HaveError = false;
902 lltok::Kind Token = Lex.getKind();
904 default: // End of attributes.
906 case lltok::kw_zeroext: B.addAttribute(Attributes::ZExt); break;
907 case lltok::kw_signext: B.addAttribute(Attributes::SExt); break;
908 case lltok::kw_inreg: B.addAttribute(Attributes::InReg); break;
909 case lltok::kw_sret: B.addAttribute(Attributes::StructRet); break;
910 case lltok::kw_noalias: B.addAttribute(Attributes::NoAlias); break;
911 case lltok::kw_nocapture: B.addAttribute(Attributes::NoCapture); break;
912 case lltok::kw_byval: B.addAttribute(Attributes::ByVal); break;
913 case lltok::kw_nest: B.addAttribute(Attributes::Nest); break;
915 case lltok::kw_noreturn: B.addAttribute(Attributes::NoReturn); break;
916 case lltok::kw_nounwind: B.addAttribute(Attributes::NoUnwind); break;
917 case lltok::kw_uwtable: B.addAttribute(Attributes::UWTable); break;
918 case lltok::kw_returns_twice: B.addAttribute(Attributes::ReturnsTwice); break;
919 case lltok::kw_noinline: B.addAttribute(Attributes::NoInline); break;
920 case lltok::kw_readnone: B.addAttribute(Attributes::ReadNone); break;
921 case lltok::kw_readonly: B.addAttribute(Attributes::ReadOnly); break;
922 case lltok::kw_inlinehint: B.addAttribute(Attributes::InlineHint); break;
923 case lltok::kw_alwaysinline: B.addAttribute(Attributes::AlwaysInline); break;
924 case lltok::kw_optsize: B.addAttribute(Attributes::OptimizeForSize); break;
925 case lltok::kw_ssp: B.addAttribute(Attributes::StackProtect); break;
926 case lltok::kw_sspreq: B.addAttribute(Attributes::StackProtectReq); break;
927 case lltok::kw_noredzone: B.addAttribute(Attributes::NoRedZone); break;
928 case lltok::kw_noimplicitfloat: B.addAttribute(Attributes::NoImplicitFloat); break;
929 case lltok::kw_naked: B.addAttribute(Attributes::Naked); break;
930 case lltok::kw_nonlazybind: B.addAttribute(Attributes::NonLazyBind); break;
931 case lltok::kw_address_safety: B.addAttribute(Attributes::AddressSafety); break;
932 case lltok::kw_minsize: B.addAttribute(Attributes::MinSize); break;
934 case lltok::kw_alignstack: {
936 if (ParseOptionalStackAlignment(Alignment))
938 B.addStackAlignmentAttr(Alignment);
942 case lltok::kw_align: {
944 if (ParseOptionalAlignment(Alignment))
946 B.addAlignmentAttr(Alignment);
952 // Perform some error checking.
956 HaveError |= Error(AttrLoc, "invalid use of attribute on a function");
958 case lltok::kw_align:
959 // As a hack, we allow "align 2" on functions as a synonym for
965 case lltok::kw_nocapture:
966 case lltok::kw_byval:
969 HaveError |= Error(AttrLoc, "invalid use of parameter-only attribute");
973 case lltok::kw_noreturn:
974 case lltok::kw_nounwind:
975 case lltok::kw_readnone:
976 case lltok::kw_readonly:
977 case lltok::kw_noinline:
978 case lltok::kw_alwaysinline:
979 case lltok::kw_optsize:
981 case lltok::kw_sspreq:
982 case lltok::kw_noredzone:
983 case lltok::kw_noimplicitfloat:
984 case lltok::kw_naked:
985 case lltok::kw_inlinehint:
986 case lltok::kw_alignstack:
987 case lltok::kw_uwtable:
988 case lltok::kw_nonlazybind:
989 case lltok::kw_returns_twice:
990 case lltok::kw_address_safety:
991 case lltok::kw_minsize:
993 HaveError |= Error(AttrLoc, "invalid use of function-only attribute");
1001 /// ParseOptionalLinkage
1004 /// ::= 'linker_private'
1005 /// ::= 'linker_private_weak'
1010 /// ::= 'linkonce_odr'
1011 /// ::= 'linkonce_odr_auto_hide'
1012 /// ::= 'available_externally'
1017 /// ::= 'extern_weak'
1019 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1021 switch (Lex.getKind()) {
1022 default: Res=GlobalValue::ExternalLinkage; return false;
1023 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1024 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1025 case lltok::kw_linker_private_weak:
1026 Res = GlobalValue::LinkerPrivateWeakLinkage;
1028 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1029 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1030 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1031 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1032 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1033 case lltok::kw_linkonce_odr_auto_hide:
1034 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1035 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1037 case lltok::kw_available_externally:
1038 Res = GlobalValue::AvailableExternallyLinkage;
1040 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1041 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1042 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1043 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1044 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1045 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1052 /// ParseOptionalVisibility
1058 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1059 switch (Lex.getKind()) {
1060 default: Res = GlobalValue::DefaultVisibility; return false;
1061 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1062 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1063 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1069 /// ParseOptionalCallingConv
1073 /// ::= 'kw_intel_ocl_bicc'
1075 /// ::= 'x86_stdcallcc'
1076 /// ::= 'x86_fastcallcc'
1077 /// ::= 'x86_thiscallcc'
1078 /// ::= 'arm_apcscc'
1079 /// ::= 'arm_aapcscc'
1080 /// ::= 'arm_aapcs_vfpcc'
1081 /// ::= 'msp430_intrcc'
1082 /// ::= 'ptx_kernel'
1083 /// ::= 'ptx_device'
1085 /// ::= 'spir_kernel'
1088 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1089 switch (Lex.getKind()) {
1090 default: CC = CallingConv::C; return false;
1091 case lltok::kw_ccc: CC = CallingConv::C; break;
1092 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1093 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1094 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1095 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1096 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1097 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1098 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1099 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1100 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1101 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1102 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1103 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1104 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1105 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1106 case lltok::kw_cc: {
1107 unsigned ArbitraryCC;
1109 if (ParseUInt32(ArbitraryCC))
1111 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1120 /// ParseInstructionMetadata
1121 /// ::= !dbg !42 (',' !dbg !57)*
1122 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1123 PerFunctionState *PFS) {
1125 if (Lex.getKind() != lltok::MetadataVar)
1126 return TokError("expected metadata after comma");
1128 std::string Name = Lex.getStrVal();
1129 unsigned MDK = M->getMDKindID(Name);
1133 SMLoc Loc = Lex.getLoc();
1135 if (ParseToken(lltok::exclaim, "expected '!' here"))
1138 // This code is similar to that of ParseMetadataValue, however it needs to
1139 // have special-case code for a forward reference; see the comments on
1140 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1141 // at the top level here.
1142 if (Lex.getKind() == lltok::lbrace) {
1144 if (ParseMetadataListValue(ID, PFS))
1146 assert(ID.Kind == ValID::t_MDNode);
1147 Inst->setMetadata(MDK, ID.MDNodeVal);
1149 unsigned NodeID = 0;
1150 if (ParseMDNodeID(Node, NodeID))
1153 // If we got the node, add it to the instruction.
1154 Inst->setMetadata(MDK, Node);
1156 MDRef R = { Loc, MDK, NodeID };
1157 // Otherwise, remember that this should be resolved later.
1158 ForwardRefInstMetadata[Inst].push_back(R);
1162 // If this is the end of the list, we're done.
1163 } while (EatIfPresent(lltok::comma));
1167 /// ParseOptionalAlignment
1170 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1172 if (!EatIfPresent(lltok::kw_align))
1174 LocTy AlignLoc = Lex.getLoc();
1175 if (ParseUInt32(Alignment)) return true;
1176 if (!isPowerOf2_32(Alignment))
1177 return Error(AlignLoc, "alignment is not a power of two");
1178 if (Alignment > Value::MaximumAlignment)
1179 return Error(AlignLoc, "huge alignments are not supported yet");
1183 /// ParseOptionalCommaAlign
1187 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1189 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1190 bool &AteExtraComma) {
1191 AteExtraComma = false;
1192 while (EatIfPresent(lltok::comma)) {
1193 // Metadata at the end is an early exit.
1194 if (Lex.getKind() == lltok::MetadataVar) {
1195 AteExtraComma = true;
1199 if (Lex.getKind() != lltok::kw_align)
1200 return Error(Lex.getLoc(), "expected metadata or 'align'");
1202 if (ParseOptionalAlignment(Alignment)) return true;
1208 /// ParseScopeAndOrdering
1209 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1212 /// This sets Scope and Ordering to the parsed values.
1213 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1214 AtomicOrdering &Ordering) {
1218 Scope = CrossThread;
1219 if (EatIfPresent(lltok::kw_singlethread))
1220 Scope = SingleThread;
1221 switch (Lex.getKind()) {
1222 default: return TokError("Expected ordering on atomic instruction");
1223 case lltok::kw_unordered: Ordering = Unordered; break;
1224 case lltok::kw_monotonic: Ordering = Monotonic; break;
1225 case lltok::kw_acquire: Ordering = Acquire; break;
1226 case lltok::kw_release: Ordering = Release; break;
1227 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1228 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1234 /// ParseOptionalStackAlignment
1236 /// ::= 'alignstack' '(' 4 ')'
1237 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1239 if (!EatIfPresent(lltok::kw_alignstack))
1241 LocTy ParenLoc = Lex.getLoc();
1242 if (!EatIfPresent(lltok::lparen))
1243 return Error(ParenLoc, "expected '('");
1244 LocTy AlignLoc = Lex.getLoc();
1245 if (ParseUInt32(Alignment)) return true;
1246 ParenLoc = Lex.getLoc();
1247 if (!EatIfPresent(lltok::rparen))
1248 return Error(ParenLoc, "expected ')'");
1249 if (!isPowerOf2_32(Alignment))
1250 return Error(AlignLoc, "stack alignment is not a power of two");
1254 /// ParseIndexList - This parses the index list for an insert/extractvalue
1255 /// instruction. This sets AteExtraComma in the case where we eat an extra
1256 /// comma at the end of the line and find that it is followed by metadata.
1257 /// Clients that don't allow metadata can call the version of this function that
1258 /// only takes one argument.
1261 /// ::= (',' uint32)+
1263 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1264 bool &AteExtraComma) {
1265 AteExtraComma = false;
1267 if (Lex.getKind() != lltok::comma)
1268 return TokError("expected ',' as start of index list");
1270 while (EatIfPresent(lltok::comma)) {
1271 if (Lex.getKind() == lltok::MetadataVar) {
1272 AteExtraComma = true;
1276 if (ParseUInt32(Idx)) return true;
1277 Indices.push_back(Idx);
1283 //===----------------------------------------------------------------------===//
1285 //===----------------------------------------------------------------------===//
1287 /// ParseType - Parse a type.
1288 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1289 SMLoc TypeLoc = Lex.getLoc();
1290 switch (Lex.getKind()) {
1292 return TokError("expected type");
1294 // Type ::= 'float' | 'void' (etc)
1295 Result = Lex.getTyVal();
1299 // Type ::= StructType
1300 if (ParseAnonStructType(Result, false))
1303 case lltok::lsquare:
1304 // Type ::= '[' ... ']'
1305 Lex.Lex(); // eat the lsquare.
1306 if (ParseArrayVectorType(Result, false))
1309 case lltok::less: // Either vector or packed struct.
1310 // Type ::= '<' ... '>'
1312 if (Lex.getKind() == lltok::lbrace) {
1313 if (ParseAnonStructType(Result, true) ||
1314 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1316 } else if (ParseArrayVectorType(Result, true))
1319 case lltok::LocalVar: {
1321 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1323 // If the type hasn't been defined yet, create a forward definition and
1324 // remember where that forward def'n was seen (in case it never is defined).
1325 if (Entry.first == 0) {
1326 Entry.first = StructType::create(Context, Lex.getStrVal());
1327 Entry.second = Lex.getLoc();
1329 Result = Entry.first;
1334 case lltok::LocalVarID: {
1336 if (Lex.getUIntVal() >= NumberedTypes.size())
1337 NumberedTypes.resize(Lex.getUIntVal()+1);
1338 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1340 // If the type hasn't been defined yet, create a forward definition and
1341 // remember where that forward def'n was seen (in case it never is defined).
1342 if (Entry.first == 0) {
1343 Entry.first = StructType::create(Context);
1344 Entry.second = Lex.getLoc();
1346 Result = Entry.first;
1352 // Parse the type suffixes.
1354 switch (Lex.getKind()) {
1357 if (!AllowVoid && Result->isVoidTy())
1358 return Error(TypeLoc, "void type only allowed for function results");
1361 // Type ::= Type '*'
1363 if (Result->isLabelTy())
1364 return TokError("basic block pointers are invalid");
1365 if (Result->isVoidTy())
1366 return TokError("pointers to void are invalid - use i8* instead");
1367 if (!PointerType::isValidElementType(Result))
1368 return TokError("pointer to this type is invalid");
1369 Result = PointerType::getUnqual(Result);
1373 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1374 case lltok::kw_addrspace: {
1375 if (Result->isLabelTy())
1376 return TokError("basic block pointers are invalid");
1377 if (Result->isVoidTy())
1378 return TokError("pointers to void are invalid; use i8* instead");
1379 if (!PointerType::isValidElementType(Result))
1380 return TokError("pointer to this type is invalid");
1382 if (ParseOptionalAddrSpace(AddrSpace) ||
1383 ParseToken(lltok::star, "expected '*' in address space"))
1386 Result = PointerType::get(Result, AddrSpace);
1390 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1392 if (ParseFunctionType(Result))
1399 /// ParseParameterList
1401 /// ::= '(' Arg (',' Arg)* ')'
1403 /// ::= Type OptionalAttributes Value OptionalAttributes
1404 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1405 PerFunctionState &PFS) {
1406 if (ParseToken(lltok::lparen, "expected '(' in call"))
1409 while (Lex.getKind() != lltok::rparen) {
1410 // If this isn't the first argument, we need a comma.
1411 if (!ArgList.empty() &&
1412 ParseToken(lltok::comma, "expected ',' in argument list"))
1415 // Parse the argument.
1418 AttrBuilder ArgAttrs;
1420 if (ParseType(ArgTy, ArgLoc))
1423 // Otherwise, handle normal operands.
1424 if (ParseOptionalAttrs(ArgAttrs, 0) || ParseValue(ArgTy, V, PFS))
1426 ArgList.push_back(ParamInfo(ArgLoc, V, Attributes::get(V->getContext(),
1430 Lex.Lex(); // Lex the ')'.
1436 /// ParseArgumentList - Parse the argument list for a function type or function
1438 /// ::= '(' ArgTypeListI ')'
1442 /// ::= ArgTypeList ',' '...'
1443 /// ::= ArgType (',' ArgType)*
1445 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1448 assert(Lex.getKind() == lltok::lparen);
1449 Lex.Lex(); // eat the (.
1451 if (Lex.getKind() == lltok::rparen) {
1453 } else if (Lex.getKind() == lltok::dotdotdot) {
1457 LocTy TypeLoc = Lex.getLoc();
1462 if (ParseType(ArgTy) ||
1463 ParseOptionalAttrs(Attrs, 0)) return true;
1465 if (ArgTy->isVoidTy())
1466 return Error(TypeLoc, "argument can not have void type");
1468 if (Lex.getKind() == lltok::LocalVar) {
1469 Name = Lex.getStrVal();
1473 if (!FunctionType::isValidArgumentType(ArgTy))
1474 return Error(TypeLoc, "invalid type for function argument");
1476 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1477 Attributes::get(ArgTy->getContext(),
1480 while (EatIfPresent(lltok::comma)) {
1481 // Handle ... at end of arg list.
1482 if (EatIfPresent(lltok::dotdotdot)) {
1487 // Otherwise must be an argument type.
1488 TypeLoc = Lex.getLoc();
1489 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
1491 if (ArgTy->isVoidTy())
1492 return Error(TypeLoc, "argument can not have void type");
1494 if (Lex.getKind() == lltok::LocalVar) {
1495 Name = Lex.getStrVal();
1501 if (!ArgTy->isFirstClassType())
1502 return Error(TypeLoc, "invalid type for function argument");
1504 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1505 Attributes::get(ArgTy->getContext(), Attrs),
1510 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1513 /// ParseFunctionType
1514 /// ::= Type ArgumentList OptionalAttrs
1515 bool LLParser::ParseFunctionType(Type *&Result) {
1516 assert(Lex.getKind() == lltok::lparen);
1518 if (!FunctionType::isValidReturnType(Result))
1519 return TokError("invalid function return type");
1521 SmallVector<ArgInfo, 8> ArgList;
1523 if (ParseArgumentList(ArgList, isVarArg))
1526 // Reject names on the arguments lists.
1527 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1528 if (!ArgList[i].Name.empty())
1529 return Error(ArgList[i].Loc, "argument name invalid in function type");
1530 if (ArgList[i].Attrs.hasAttributes())
1531 return Error(ArgList[i].Loc,
1532 "argument attributes invalid in function type");
1535 SmallVector<Type*, 16> ArgListTy;
1536 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1537 ArgListTy.push_back(ArgList[i].Ty);
1539 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1543 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1545 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1546 SmallVector<Type*, 8> Elts;
1547 if (ParseStructBody(Elts)) return true;
1549 Result = StructType::get(Context, Elts, Packed);
1553 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1554 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1555 std::pair<Type*, LocTy> &Entry,
1557 // If the type was already defined, diagnose the redefinition.
1558 if (Entry.first && !Entry.second.isValid())
1559 return Error(TypeLoc, "redefinition of type");
1561 // If we have opaque, just return without filling in the definition for the
1562 // struct. This counts as a definition as far as the .ll file goes.
1563 if (EatIfPresent(lltok::kw_opaque)) {
1564 // This type is being defined, so clear the location to indicate this.
1565 Entry.second = SMLoc();
1567 // If this type number has never been uttered, create it.
1568 if (Entry.first == 0)
1569 Entry.first = StructType::create(Context, Name);
1570 ResultTy = Entry.first;
1574 // If the type starts with '<', then it is either a packed struct or a vector.
1575 bool isPacked = EatIfPresent(lltok::less);
1577 // If we don't have a struct, then we have a random type alias, which we
1578 // accept for compatibility with old files. These types are not allowed to be
1579 // forward referenced and not allowed to be recursive.
1580 if (Lex.getKind() != lltok::lbrace) {
1582 return Error(TypeLoc, "forward references to non-struct type");
1586 return ParseArrayVectorType(ResultTy, true);
1587 return ParseType(ResultTy);
1590 // This type is being defined, so clear the location to indicate this.
1591 Entry.second = SMLoc();
1593 // If this type number has never been uttered, create it.
1594 if (Entry.first == 0)
1595 Entry.first = StructType::create(Context, Name);
1597 StructType *STy = cast<StructType>(Entry.first);
1599 SmallVector<Type*, 8> Body;
1600 if (ParseStructBody(Body) ||
1601 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1604 STy->setBody(Body, isPacked);
1610 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1613 /// ::= '{' Type (',' Type)* '}'
1614 /// ::= '<' '{' '}' '>'
1615 /// ::= '<' '{' Type (',' Type)* '}' '>'
1616 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1617 assert(Lex.getKind() == lltok::lbrace);
1618 Lex.Lex(); // Consume the '{'
1620 // Handle the empty struct.
1621 if (EatIfPresent(lltok::rbrace))
1624 LocTy EltTyLoc = Lex.getLoc();
1626 if (ParseType(Ty)) return true;
1629 if (!StructType::isValidElementType(Ty))
1630 return Error(EltTyLoc, "invalid element type for struct");
1632 while (EatIfPresent(lltok::comma)) {
1633 EltTyLoc = Lex.getLoc();
1634 if (ParseType(Ty)) return true;
1636 if (!StructType::isValidElementType(Ty))
1637 return Error(EltTyLoc, "invalid element type for struct");
1642 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1645 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1646 /// token has already been consumed.
1648 /// ::= '[' APSINTVAL 'x' Types ']'
1649 /// ::= '<' APSINTVAL 'x' Types '>'
1650 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1651 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1652 Lex.getAPSIntVal().getBitWidth() > 64)
1653 return TokError("expected number in address space");
1655 LocTy SizeLoc = Lex.getLoc();
1656 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1659 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1662 LocTy TypeLoc = Lex.getLoc();
1664 if (ParseType(EltTy)) return true;
1666 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1667 "expected end of sequential type"))
1672 return Error(SizeLoc, "zero element vector is illegal");
1673 if ((unsigned)Size != Size)
1674 return Error(SizeLoc, "size too large for vector");
1675 if (!VectorType::isValidElementType(EltTy))
1676 return Error(TypeLoc, "invalid vector element type");
1677 Result = VectorType::get(EltTy, unsigned(Size));
1679 if (!ArrayType::isValidElementType(EltTy))
1680 return Error(TypeLoc, "invalid array element type");
1681 Result = ArrayType::get(EltTy, Size);
1686 //===----------------------------------------------------------------------===//
1687 // Function Semantic Analysis.
1688 //===----------------------------------------------------------------------===//
1690 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1692 : P(p), F(f), FunctionNumber(functionNumber) {
1694 // Insert unnamed arguments into the NumberedVals list.
1695 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1698 NumberedVals.push_back(AI);
1701 LLParser::PerFunctionState::~PerFunctionState() {
1702 // If there were any forward referenced non-basicblock values, delete them.
1703 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1704 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1705 if (!isa<BasicBlock>(I->second.first)) {
1706 I->second.first->replaceAllUsesWith(
1707 UndefValue::get(I->second.first->getType()));
1708 delete I->second.first;
1709 I->second.first = 0;
1712 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1713 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1714 if (!isa<BasicBlock>(I->second.first)) {
1715 I->second.first->replaceAllUsesWith(
1716 UndefValue::get(I->second.first->getType()));
1717 delete I->second.first;
1718 I->second.first = 0;
1722 bool LLParser::PerFunctionState::FinishFunction() {
1723 // Check to see if someone took the address of labels in this block.
1724 if (!P.ForwardRefBlockAddresses.empty()) {
1726 if (!F.getName().empty()) {
1727 FunctionID.Kind = ValID::t_GlobalName;
1728 FunctionID.StrVal = F.getName();
1730 FunctionID.Kind = ValID::t_GlobalID;
1731 FunctionID.UIntVal = FunctionNumber;
1734 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1735 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1736 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1737 // Resolve all these references.
1738 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1741 P.ForwardRefBlockAddresses.erase(FRBAI);
1745 if (!ForwardRefVals.empty())
1746 return P.Error(ForwardRefVals.begin()->second.second,
1747 "use of undefined value '%" + ForwardRefVals.begin()->first +
1749 if (!ForwardRefValIDs.empty())
1750 return P.Error(ForwardRefValIDs.begin()->second.second,
1751 "use of undefined value '%" +
1752 Twine(ForwardRefValIDs.begin()->first) + "'");
1757 /// GetVal - Get a value with the specified name or ID, creating a
1758 /// forward reference record if needed. This can return null if the value
1759 /// exists but does not have the right type.
1760 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1761 Type *Ty, LocTy Loc) {
1762 // Look this name up in the normal function symbol table.
1763 Value *Val = F.getValueSymbolTable().lookup(Name);
1765 // If this is a forward reference for the value, see if we already created a
1766 // forward ref record.
1768 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1769 I = ForwardRefVals.find(Name);
1770 if (I != ForwardRefVals.end())
1771 Val = I->second.first;
1774 // If we have the value in the symbol table or fwd-ref table, return it.
1776 if (Val->getType() == Ty) return Val;
1777 if (Ty->isLabelTy())
1778 P.Error(Loc, "'%" + Name + "' is not a basic block");
1780 P.Error(Loc, "'%" + Name + "' defined with type '" +
1781 getTypeString(Val->getType()) + "'");
1785 // Don't make placeholders with invalid type.
1786 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1787 P.Error(Loc, "invalid use of a non-first-class type");
1791 // Otherwise, create a new forward reference for this value and remember it.
1793 if (Ty->isLabelTy())
1794 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1796 FwdVal = new Argument(Ty, Name);
1798 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1802 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1804 // Look this name up in the normal function symbol table.
1805 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1807 // If this is a forward reference for the value, see if we already created a
1808 // forward ref record.
1810 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1811 I = ForwardRefValIDs.find(ID);
1812 if (I != ForwardRefValIDs.end())
1813 Val = I->second.first;
1816 // If we have the value in the symbol table or fwd-ref table, return it.
1818 if (Val->getType() == Ty) return Val;
1819 if (Ty->isLabelTy())
1820 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1822 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1823 getTypeString(Val->getType()) + "'");
1827 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1828 P.Error(Loc, "invalid use of a non-first-class type");
1832 // Otherwise, create a new forward reference for this value and remember it.
1834 if (Ty->isLabelTy())
1835 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1837 FwdVal = new Argument(Ty);
1839 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1843 /// SetInstName - After an instruction is parsed and inserted into its
1844 /// basic block, this installs its name.
1845 bool LLParser::PerFunctionState::SetInstName(int NameID,
1846 const std::string &NameStr,
1847 LocTy NameLoc, Instruction *Inst) {
1848 // If this instruction has void type, it cannot have a name or ID specified.
1849 if (Inst->getType()->isVoidTy()) {
1850 if (NameID != -1 || !NameStr.empty())
1851 return P.Error(NameLoc, "instructions returning void cannot have a name");
1855 // If this was a numbered instruction, verify that the instruction is the
1856 // expected value and resolve any forward references.
1857 if (NameStr.empty()) {
1858 // If neither a name nor an ID was specified, just use the next ID.
1860 NameID = NumberedVals.size();
1862 if (unsigned(NameID) != NumberedVals.size())
1863 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1864 Twine(NumberedVals.size()) + "'");
1866 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1867 ForwardRefValIDs.find(NameID);
1868 if (FI != ForwardRefValIDs.end()) {
1869 if (FI->second.first->getType() != Inst->getType())
1870 return P.Error(NameLoc, "instruction forward referenced with type '" +
1871 getTypeString(FI->second.first->getType()) + "'");
1872 FI->second.first->replaceAllUsesWith(Inst);
1873 delete FI->second.first;
1874 ForwardRefValIDs.erase(FI);
1877 NumberedVals.push_back(Inst);
1881 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1882 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1883 FI = ForwardRefVals.find(NameStr);
1884 if (FI != ForwardRefVals.end()) {
1885 if (FI->second.first->getType() != Inst->getType())
1886 return P.Error(NameLoc, "instruction forward referenced with type '" +
1887 getTypeString(FI->second.first->getType()) + "'");
1888 FI->second.first->replaceAllUsesWith(Inst);
1889 delete FI->second.first;
1890 ForwardRefVals.erase(FI);
1893 // Set the name on the instruction.
1894 Inst->setName(NameStr);
1896 if (Inst->getName() != NameStr)
1897 return P.Error(NameLoc, "multiple definition of local value named '" +
1902 /// GetBB - Get a basic block with the specified name or ID, creating a
1903 /// forward reference record if needed.
1904 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1906 return cast_or_null<BasicBlock>(GetVal(Name,
1907 Type::getLabelTy(F.getContext()), Loc));
1910 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1911 return cast_or_null<BasicBlock>(GetVal(ID,
1912 Type::getLabelTy(F.getContext()), Loc));
1915 /// DefineBB - Define the specified basic block, which is either named or
1916 /// unnamed. If there is an error, this returns null otherwise it returns
1917 /// the block being defined.
1918 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1922 BB = GetBB(NumberedVals.size(), Loc);
1924 BB = GetBB(Name, Loc);
1925 if (BB == 0) return 0; // Already diagnosed error.
1927 // Move the block to the end of the function. Forward ref'd blocks are
1928 // inserted wherever they happen to be referenced.
1929 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1931 // Remove the block from forward ref sets.
1933 ForwardRefValIDs.erase(NumberedVals.size());
1934 NumberedVals.push_back(BB);
1936 // BB forward references are already in the function symbol table.
1937 ForwardRefVals.erase(Name);
1943 //===----------------------------------------------------------------------===//
1945 //===----------------------------------------------------------------------===//
1947 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1948 /// type implied. For example, if we parse "4" we don't know what integer type
1949 /// it has. The value will later be combined with its type and checked for
1950 /// sanity. PFS is used to convert function-local operands of metadata (since
1951 /// metadata operands are not just parsed here but also converted to values).
1952 /// PFS can be null when we are not parsing metadata values inside a function.
1953 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1954 ID.Loc = Lex.getLoc();
1955 switch (Lex.getKind()) {
1956 default: return TokError("expected value token");
1957 case lltok::GlobalID: // @42
1958 ID.UIntVal = Lex.getUIntVal();
1959 ID.Kind = ValID::t_GlobalID;
1961 case lltok::GlobalVar: // @foo
1962 ID.StrVal = Lex.getStrVal();
1963 ID.Kind = ValID::t_GlobalName;
1965 case lltok::LocalVarID: // %42
1966 ID.UIntVal = Lex.getUIntVal();
1967 ID.Kind = ValID::t_LocalID;
1969 case lltok::LocalVar: // %foo
1970 ID.StrVal = Lex.getStrVal();
1971 ID.Kind = ValID::t_LocalName;
1973 case lltok::exclaim: // !42, !{...}, or !"foo"
1974 return ParseMetadataValue(ID, PFS);
1976 ID.APSIntVal = Lex.getAPSIntVal();
1977 ID.Kind = ValID::t_APSInt;
1979 case lltok::APFloat:
1980 ID.APFloatVal = Lex.getAPFloatVal();
1981 ID.Kind = ValID::t_APFloat;
1983 case lltok::kw_true:
1984 ID.ConstantVal = ConstantInt::getTrue(Context);
1985 ID.Kind = ValID::t_Constant;
1987 case lltok::kw_false:
1988 ID.ConstantVal = ConstantInt::getFalse(Context);
1989 ID.Kind = ValID::t_Constant;
1991 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1992 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1993 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1995 case lltok::lbrace: {
1996 // ValID ::= '{' ConstVector '}'
1998 SmallVector<Constant*, 16> Elts;
1999 if (ParseGlobalValueVector(Elts) ||
2000 ParseToken(lltok::rbrace, "expected end of struct constant"))
2003 ID.ConstantStructElts = new Constant*[Elts.size()];
2004 ID.UIntVal = Elts.size();
2005 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2006 ID.Kind = ValID::t_ConstantStruct;
2010 // ValID ::= '<' ConstVector '>' --> Vector.
2011 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2013 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2015 SmallVector<Constant*, 16> Elts;
2016 LocTy FirstEltLoc = Lex.getLoc();
2017 if (ParseGlobalValueVector(Elts) ||
2019 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2020 ParseToken(lltok::greater, "expected end of constant"))
2023 if (isPackedStruct) {
2024 ID.ConstantStructElts = new Constant*[Elts.size()];
2025 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2026 ID.UIntVal = Elts.size();
2027 ID.Kind = ValID::t_PackedConstantStruct;
2032 return Error(ID.Loc, "constant vector must not be empty");
2034 if (!Elts[0]->getType()->isIntegerTy() &&
2035 !Elts[0]->getType()->isFloatingPointTy() &&
2036 !Elts[0]->getType()->isPointerTy())
2037 return Error(FirstEltLoc,
2038 "vector elements must have integer, pointer or floating point type");
2040 // Verify that all the vector elements have the same type.
2041 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2042 if (Elts[i]->getType() != Elts[0]->getType())
2043 return Error(FirstEltLoc,
2044 "vector element #" + Twine(i) +
2045 " is not of type '" + getTypeString(Elts[0]->getType()));
2047 ID.ConstantVal = ConstantVector::get(Elts);
2048 ID.Kind = ValID::t_Constant;
2051 case lltok::lsquare: { // Array Constant
2053 SmallVector<Constant*, 16> Elts;
2054 LocTy FirstEltLoc = Lex.getLoc();
2055 if (ParseGlobalValueVector(Elts) ||
2056 ParseToken(lltok::rsquare, "expected end of array constant"))
2059 // Handle empty element.
2061 // Use undef instead of an array because it's inconvenient to determine
2062 // the element type at this point, there being no elements to examine.
2063 ID.Kind = ValID::t_EmptyArray;
2067 if (!Elts[0]->getType()->isFirstClassType())
2068 return Error(FirstEltLoc, "invalid array element type: " +
2069 getTypeString(Elts[0]->getType()));
2071 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2073 // Verify all elements are correct type!
2074 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2075 if (Elts[i]->getType() != Elts[0]->getType())
2076 return Error(FirstEltLoc,
2077 "array element #" + Twine(i) +
2078 " is not of type '" + getTypeString(Elts[0]->getType()));
2081 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2082 ID.Kind = ValID::t_Constant;
2085 case lltok::kw_c: // c "foo"
2087 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2089 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2090 ID.Kind = ValID::t_Constant;
2093 case lltok::kw_asm: {
2094 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2095 bool HasSideEffect, AlignStack, AsmDialect;
2097 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2098 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2099 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2100 ParseStringConstant(ID.StrVal) ||
2101 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2102 ParseToken(lltok::StringConstant, "expected constraint string"))
2104 ID.StrVal2 = Lex.getStrVal();
2105 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2106 (unsigned(AsmDialect)<<2);
2107 ID.Kind = ValID::t_InlineAsm;
2111 case lltok::kw_blockaddress: {
2112 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2116 LocTy FnLoc, LabelLoc;
2118 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2120 ParseToken(lltok::comma, "expected comma in block address expression")||
2121 ParseValID(Label) ||
2122 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2125 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2126 return Error(Fn.Loc, "expected function name in blockaddress");
2127 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2128 return Error(Label.Loc, "expected basic block name in blockaddress");
2130 // Make a global variable as a placeholder for this reference.
2131 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2132 false, GlobalValue::InternalLinkage,
2134 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2135 ID.ConstantVal = FwdRef;
2136 ID.Kind = ValID::t_Constant;
2140 case lltok::kw_trunc:
2141 case lltok::kw_zext:
2142 case lltok::kw_sext:
2143 case lltok::kw_fptrunc:
2144 case lltok::kw_fpext:
2145 case lltok::kw_bitcast:
2146 case lltok::kw_uitofp:
2147 case lltok::kw_sitofp:
2148 case lltok::kw_fptoui:
2149 case lltok::kw_fptosi:
2150 case lltok::kw_inttoptr:
2151 case lltok::kw_ptrtoint: {
2152 unsigned Opc = Lex.getUIntVal();
2156 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2157 ParseGlobalTypeAndValue(SrcVal) ||
2158 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2159 ParseType(DestTy) ||
2160 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2162 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2163 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2164 getTypeString(SrcVal->getType()) + "' to '" +
2165 getTypeString(DestTy) + "'");
2166 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2168 ID.Kind = ValID::t_Constant;
2171 case lltok::kw_extractvalue: {
2174 SmallVector<unsigned, 4> Indices;
2175 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2176 ParseGlobalTypeAndValue(Val) ||
2177 ParseIndexList(Indices) ||
2178 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2181 if (!Val->getType()->isAggregateType())
2182 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2183 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2184 return Error(ID.Loc, "invalid indices for extractvalue");
2185 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2186 ID.Kind = ValID::t_Constant;
2189 case lltok::kw_insertvalue: {
2191 Constant *Val0, *Val1;
2192 SmallVector<unsigned, 4> Indices;
2193 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2194 ParseGlobalTypeAndValue(Val0) ||
2195 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2196 ParseGlobalTypeAndValue(Val1) ||
2197 ParseIndexList(Indices) ||
2198 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2200 if (!Val0->getType()->isAggregateType())
2201 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2202 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2203 return Error(ID.Loc, "invalid indices for insertvalue");
2204 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2205 ID.Kind = ValID::t_Constant;
2208 case lltok::kw_icmp:
2209 case lltok::kw_fcmp: {
2210 unsigned PredVal, Opc = Lex.getUIntVal();
2211 Constant *Val0, *Val1;
2213 if (ParseCmpPredicate(PredVal, Opc) ||
2214 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2215 ParseGlobalTypeAndValue(Val0) ||
2216 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2217 ParseGlobalTypeAndValue(Val1) ||
2218 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2221 if (Val0->getType() != Val1->getType())
2222 return Error(ID.Loc, "compare operands must have the same type");
2224 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2226 if (Opc == Instruction::FCmp) {
2227 if (!Val0->getType()->isFPOrFPVectorTy())
2228 return Error(ID.Loc, "fcmp requires floating point operands");
2229 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2231 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2232 if (!Val0->getType()->isIntOrIntVectorTy() &&
2233 !Val0->getType()->getScalarType()->isPointerTy())
2234 return Error(ID.Loc, "icmp requires pointer or integer operands");
2235 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2237 ID.Kind = ValID::t_Constant;
2241 // Binary Operators.
2243 case lltok::kw_fadd:
2245 case lltok::kw_fsub:
2247 case lltok::kw_fmul:
2248 case lltok::kw_udiv:
2249 case lltok::kw_sdiv:
2250 case lltok::kw_fdiv:
2251 case lltok::kw_urem:
2252 case lltok::kw_srem:
2253 case lltok::kw_frem:
2255 case lltok::kw_lshr:
2256 case lltok::kw_ashr: {
2260 unsigned Opc = Lex.getUIntVal();
2261 Constant *Val0, *Val1;
2263 LocTy ModifierLoc = Lex.getLoc();
2264 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2265 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2266 if (EatIfPresent(lltok::kw_nuw))
2268 if (EatIfPresent(lltok::kw_nsw)) {
2270 if (EatIfPresent(lltok::kw_nuw))
2273 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2274 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2275 if (EatIfPresent(lltok::kw_exact))
2278 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2279 ParseGlobalTypeAndValue(Val0) ||
2280 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2281 ParseGlobalTypeAndValue(Val1) ||
2282 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2284 if (Val0->getType() != Val1->getType())
2285 return Error(ID.Loc, "operands of constexpr must have same type");
2286 if (!Val0->getType()->isIntOrIntVectorTy()) {
2288 return Error(ModifierLoc, "nuw only applies to integer operations");
2290 return Error(ModifierLoc, "nsw only applies to integer operations");
2292 // Check that the type is valid for the operator.
2294 case Instruction::Add:
2295 case Instruction::Sub:
2296 case Instruction::Mul:
2297 case Instruction::UDiv:
2298 case Instruction::SDiv:
2299 case Instruction::URem:
2300 case Instruction::SRem:
2301 case Instruction::Shl:
2302 case Instruction::AShr:
2303 case Instruction::LShr:
2304 if (!Val0->getType()->isIntOrIntVectorTy())
2305 return Error(ID.Loc, "constexpr requires integer operands");
2307 case Instruction::FAdd:
2308 case Instruction::FSub:
2309 case Instruction::FMul:
2310 case Instruction::FDiv:
2311 case Instruction::FRem:
2312 if (!Val0->getType()->isFPOrFPVectorTy())
2313 return Error(ID.Loc, "constexpr requires fp operands");
2315 default: llvm_unreachable("Unknown binary operator!");
2318 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2319 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2320 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2321 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2323 ID.Kind = ValID::t_Constant;
2327 // Logical Operations
2330 case lltok::kw_xor: {
2331 unsigned Opc = Lex.getUIntVal();
2332 Constant *Val0, *Val1;
2334 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2335 ParseGlobalTypeAndValue(Val0) ||
2336 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2337 ParseGlobalTypeAndValue(Val1) ||
2338 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2340 if (Val0->getType() != Val1->getType())
2341 return Error(ID.Loc, "operands of constexpr must have same type");
2342 if (!Val0->getType()->isIntOrIntVectorTy())
2343 return Error(ID.Loc,
2344 "constexpr requires integer or integer vector operands");
2345 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2346 ID.Kind = ValID::t_Constant;
2350 case lltok::kw_getelementptr:
2351 case lltok::kw_shufflevector:
2352 case lltok::kw_insertelement:
2353 case lltok::kw_extractelement:
2354 case lltok::kw_select: {
2355 unsigned Opc = Lex.getUIntVal();
2356 SmallVector<Constant*, 16> Elts;
2357 bool InBounds = false;
2359 if (Opc == Instruction::GetElementPtr)
2360 InBounds = EatIfPresent(lltok::kw_inbounds);
2361 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2362 ParseGlobalValueVector(Elts) ||
2363 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2366 if (Opc == Instruction::GetElementPtr) {
2367 if (Elts.size() == 0 ||
2368 !Elts[0]->getType()->getScalarType()->isPointerTy())
2369 return Error(ID.Loc, "getelementptr requires pointer operand");
2371 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2372 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2373 return Error(ID.Loc, "invalid indices for getelementptr");
2374 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2376 } else if (Opc == Instruction::Select) {
2377 if (Elts.size() != 3)
2378 return Error(ID.Loc, "expected three operands to select");
2379 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2381 return Error(ID.Loc, Reason);
2382 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2383 } else if (Opc == Instruction::ShuffleVector) {
2384 if (Elts.size() != 3)
2385 return Error(ID.Loc, "expected three operands to shufflevector");
2386 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2387 return Error(ID.Loc, "invalid operands to shufflevector");
2389 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2390 } else if (Opc == Instruction::ExtractElement) {
2391 if (Elts.size() != 2)
2392 return Error(ID.Loc, "expected two operands to extractelement");
2393 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2394 return Error(ID.Loc, "invalid extractelement operands");
2395 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2397 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2398 if (Elts.size() != 3)
2399 return Error(ID.Loc, "expected three operands to insertelement");
2400 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2401 return Error(ID.Loc, "invalid insertelement operands");
2403 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2406 ID.Kind = ValID::t_Constant;
2415 /// ParseGlobalValue - Parse a global value with the specified type.
2416 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2420 bool Parsed = ParseValID(ID) ||
2421 ConvertValIDToValue(Ty, ID, V, NULL);
2422 if (V && !(C = dyn_cast<Constant>(V)))
2423 return Error(ID.Loc, "global values must be constants");
2427 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2429 return ParseType(Ty) ||
2430 ParseGlobalValue(Ty, V);
2433 /// ParseGlobalValueVector
2435 /// ::= TypeAndValue (',' TypeAndValue)*
2436 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2438 if (Lex.getKind() == lltok::rbrace ||
2439 Lex.getKind() == lltok::rsquare ||
2440 Lex.getKind() == lltok::greater ||
2441 Lex.getKind() == lltok::rparen)
2445 if (ParseGlobalTypeAndValue(C)) return true;
2448 while (EatIfPresent(lltok::comma)) {
2449 if (ParseGlobalTypeAndValue(C)) return true;
2456 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2457 assert(Lex.getKind() == lltok::lbrace);
2460 SmallVector<Value*, 16> Elts;
2461 if (ParseMDNodeVector(Elts, PFS) ||
2462 ParseToken(lltok::rbrace, "expected end of metadata node"))
2465 ID.MDNodeVal = MDNode::get(Context, Elts);
2466 ID.Kind = ValID::t_MDNode;
2470 /// ParseMetadataValue
2474 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2475 assert(Lex.getKind() == lltok::exclaim);
2480 if (Lex.getKind() == lltok::lbrace)
2481 return ParseMetadataListValue(ID, PFS);
2483 // Standalone metadata reference
2485 if (Lex.getKind() == lltok::APSInt) {
2486 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2487 ID.Kind = ValID::t_MDNode;
2492 // ::= '!' STRINGCONSTANT
2493 if (ParseMDString(ID.MDStringVal)) return true;
2494 ID.Kind = ValID::t_MDString;
2499 //===----------------------------------------------------------------------===//
2500 // Function Parsing.
2501 //===----------------------------------------------------------------------===//
2503 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2504 PerFunctionState *PFS) {
2505 if (Ty->isFunctionTy())
2506 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2509 case ValID::t_LocalID:
2510 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2511 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2513 case ValID::t_LocalName:
2514 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2515 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2517 case ValID::t_InlineAsm: {
2518 PointerType *PTy = dyn_cast<PointerType>(Ty);
2520 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2521 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2522 return Error(ID.Loc, "invalid type for inline asm constraint string");
2523 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2524 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2527 case ValID::t_MDNode:
2528 if (!Ty->isMetadataTy())
2529 return Error(ID.Loc, "metadata value must have metadata type");
2532 case ValID::t_MDString:
2533 if (!Ty->isMetadataTy())
2534 return Error(ID.Loc, "metadata value must have metadata type");
2537 case ValID::t_GlobalName:
2538 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2540 case ValID::t_GlobalID:
2541 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2543 case ValID::t_APSInt:
2544 if (!Ty->isIntegerTy())
2545 return Error(ID.Loc, "integer constant must have integer type");
2546 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2547 V = ConstantInt::get(Context, ID.APSIntVal);
2549 case ValID::t_APFloat:
2550 if (!Ty->isFloatingPointTy() ||
2551 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2552 return Error(ID.Loc, "floating point constant invalid for type");
2554 // The lexer has no type info, so builds all half, float, and double FP
2555 // constants as double. Fix this here. Long double does not need this.
2556 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2559 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2561 else if (Ty->isFloatTy())
2562 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2565 V = ConstantFP::get(Context, ID.APFloatVal);
2567 if (V->getType() != Ty)
2568 return Error(ID.Loc, "floating point constant does not have type '" +
2569 getTypeString(Ty) + "'");
2573 if (!Ty->isPointerTy())
2574 return Error(ID.Loc, "null must be a pointer type");
2575 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2577 case ValID::t_Undef:
2578 // FIXME: LabelTy should not be a first-class type.
2579 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2580 return Error(ID.Loc, "invalid type for undef constant");
2581 V = UndefValue::get(Ty);
2583 case ValID::t_EmptyArray:
2584 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2585 return Error(ID.Loc, "invalid empty array initializer");
2586 V = UndefValue::get(Ty);
2589 // FIXME: LabelTy should not be a first-class type.
2590 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2591 return Error(ID.Loc, "invalid type for null constant");
2592 V = Constant::getNullValue(Ty);
2594 case ValID::t_Constant:
2595 if (ID.ConstantVal->getType() != Ty)
2596 return Error(ID.Loc, "constant expression type mismatch");
2600 case ValID::t_ConstantStruct:
2601 case ValID::t_PackedConstantStruct:
2602 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2603 if (ST->getNumElements() != ID.UIntVal)
2604 return Error(ID.Loc,
2605 "initializer with struct type has wrong # elements");
2606 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2607 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2609 // Verify that the elements are compatible with the structtype.
2610 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2611 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2612 return Error(ID.Loc, "element " + Twine(i) +
2613 " of struct initializer doesn't match struct element type");
2615 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2618 return Error(ID.Loc, "constant expression type mismatch");
2621 llvm_unreachable("Invalid ValID");
2624 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2627 return ParseValID(ID, PFS) ||
2628 ConvertValIDToValue(Ty, ID, V, PFS);
2631 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2633 return ParseType(Ty) ||
2634 ParseValue(Ty, V, PFS);
2637 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2638 PerFunctionState &PFS) {
2641 if (ParseTypeAndValue(V, PFS)) return true;
2642 if (!isa<BasicBlock>(V))
2643 return Error(Loc, "expected a basic block");
2644 BB = cast<BasicBlock>(V);
2650 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2651 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2652 /// OptionalAlign OptGC
2653 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2654 // Parse the linkage.
2655 LocTy LinkageLoc = Lex.getLoc();
2658 unsigned Visibility;
2659 AttrBuilder RetAttrs;
2662 LocTy RetTypeLoc = Lex.getLoc();
2663 if (ParseOptionalLinkage(Linkage) ||
2664 ParseOptionalVisibility(Visibility) ||
2665 ParseOptionalCallingConv(CC) ||
2666 ParseOptionalAttrs(RetAttrs, 1) ||
2667 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2670 // Verify that the linkage is ok.
2671 switch ((GlobalValue::LinkageTypes)Linkage) {
2672 case GlobalValue::ExternalLinkage:
2673 break; // always ok.
2674 case GlobalValue::DLLImportLinkage:
2675 case GlobalValue::ExternalWeakLinkage:
2677 return Error(LinkageLoc, "invalid linkage for function definition");
2679 case GlobalValue::PrivateLinkage:
2680 case GlobalValue::LinkerPrivateLinkage:
2681 case GlobalValue::LinkerPrivateWeakLinkage:
2682 case GlobalValue::InternalLinkage:
2683 case GlobalValue::AvailableExternallyLinkage:
2684 case GlobalValue::LinkOnceAnyLinkage:
2685 case GlobalValue::LinkOnceODRLinkage:
2686 case GlobalValue::LinkOnceODRAutoHideLinkage:
2687 case GlobalValue::WeakAnyLinkage:
2688 case GlobalValue::WeakODRLinkage:
2689 case GlobalValue::DLLExportLinkage:
2691 return Error(LinkageLoc, "invalid linkage for function declaration");
2693 case GlobalValue::AppendingLinkage:
2694 case GlobalValue::CommonLinkage:
2695 return Error(LinkageLoc, "invalid function linkage type");
2698 if (!FunctionType::isValidReturnType(RetType))
2699 return Error(RetTypeLoc, "invalid function return type");
2701 LocTy NameLoc = Lex.getLoc();
2703 std::string FunctionName;
2704 if (Lex.getKind() == lltok::GlobalVar) {
2705 FunctionName = Lex.getStrVal();
2706 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2707 unsigned NameID = Lex.getUIntVal();
2709 if (NameID != NumberedVals.size())
2710 return TokError("function expected to be numbered '%" +
2711 Twine(NumberedVals.size()) + "'");
2713 return TokError("expected function name");
2718 if (Lex.getKind() != lltok::lparen)
2719 return TokError("expected '(' in function argument list");
2721 SmallVector<ArgInfo, 8> ArgList;
2723 AttrBuilder FuncAttrs;
2724 std::string Section;
2728 LocTy UnnamedAddrLoc;
2730 if (ParseArgumentList(ArgList, isVarArg) ||
2731 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2733 ParseOptionalAttrs(FuncAttrs, 2) ||
2734 (EatIfPresent(lltok::kw_section) &&
2735 ParseStringConstant(Section)) ||
2736 ParseOptionalAlignment(Alignment) ||
2737 (EatIfPresent(lltok::kw_gc) &&
2738 ParseStringConstant(GC)))
2741 // If the alignment was parsed as an attribute, move to the alignment field.
2742 if (FuncAttrs.hasAlignmentAttr()) {
2743 Alignment = FuncAttrs.getAlignment();
2744 FuncAttrs.removeAttribute(Attributes::Alignment);
2747 // Okay, if we got here, the function is syntactically valid. Convert types
2748 // and do semantic checks.
2749 std::vector<Type*> ParamTypeList;
2750 SmallVector<AttributeWithIndex, 8> Attrs;
2752 if (RetAttrs.hasAttributes())
2754 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
2755 Attributes::get(RetType->getContext(),
2758 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2759 ParamTypeList.push_back(ArgList[i].Ty);
2760 if (ArgList[i].Attrs.hasAttributes())
2761 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2764 if (FuncAttrs.hasAttributes())
2766 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
2767 Attributes::get(RetType->getContext(),
2770 AttrListPtr PAL = AttrListPtr::get(Context, Attrs);
2772 if (PAL.getParamAttributes(1).hasAttribute(Attributes::StructRet) &&
2773 !RetType->isVoidTy())
2774 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2777 FunctionType::get(RetType, ParamTypeList, isVarArg);
2778 PointerType *PFT = PointerType::getUnqual(FT);
2781 if (!FunctionName.empty()) {
2782 // If this was a definition of a forward reference, remove the definition
2783 // from the forward reference table and fill in the forward ref.
2784 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2785 ForwardRefVals.find(FunctionName);
2786 if (FRVI != ForwardRefVals.end()) {
2787 Fn = M->getFunction(FunctionName);
2789 return Error(FRVI->second.second, "invalid forward reference to "
2790 "function as global value!");
2791 if (Fn->getType() != PFT)
2792 return Error(FRVI->second.second, "invalid forward reference to "
2793 "function '" + FunctionName + "' with wrong type!");
2795 ForwardRefVals.erase(FRVI);
2796 } else if ((Fn = M->getFunction(FunctionName))) {
2797 // Reject redefinitions.
2798 return Error(NameLoc, "invalid redefinition of function '" +
2799 FunctionName + "'");
2800 } else if (M->getNamedValue(FunctionName)) {
2801 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2805 // If this is a definition of a forward referenced function, make sure the
2807 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2808 = ForwardRefValIDs.find(NumberedVals.size());
2809 if (I != ForwardRefValIDs.end()) {
2810 Fn = cast<Function>(I->second.first);
2811 if (Fn->getType() != PFT)
2812 return Error(NameLoc, "type of definition and forward reference of '@" +
2813 Twine(NumberedVals.size()) + "' disagree");
2814 ForwardRefValIDs.erase(I);
2819 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2820 else // Move the forward-reference to the correct spot in the module.
2821 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2823 if (FunctionName.empty())
2824 NumberedVals.push_back(Fn);
2826 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2827 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2828 Fn->setCallingConv(CC);
2829 Fn->setAttributes(PAL);
2830 Fn->setUnnamedAddr(UnnamedAddr);
2831 Fn->setAlignment(Alignment);
2832 Fn->setSection(Section);
2833 if (!GC.empty()) Fn->setGC(GC.c_str());
2835 // Add all of the arguments we parsed to the function.
2836 Function::arg_iterator ArgIt = Fn->arg_begin();
2837 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2838 // If the argument has a name, insert it into the argument symbol table.
2839 if (ArgList[i].Name.empty()) continue;
2841 // Set the name, if it conflicted, it will be auto-renamed.
2842 ArgIt->setName(ArgList[i].Name);
2844 if (ArgIt->getName() != ArgList[i].Name)
2845 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2846 ArgList[i].Name + "'");
2853 /// ParseFunctionBody
2854 /// ::= '{' BasicBlock+ '}'
2856 bool LLParser::ParseFunctionBody(Function &Fn) {
2857 if (Lex.getKind() != lltok::lbrace)
2858 return TokError("expected '{' in function body");
2859 Lex.Lex(); // eat the {.
2861 int FunctionNumber = -1;
2862 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2864 PerFunctionState PFS(*this, Fn, FunctionNumber);
2866 // We need at least one basic block.
2867 if (Lex.getKind() == lltok::rbrace)
2868 return TokError("function body requires at least one basic block");
2870 while (Lex.getKind() != lltok::rbrace)
2871 if (ParseBasicBlock(PFS)) return true;
2876 // Verify function is ok.
2877 return PFS.FinishFunction();
2881 /// ::= LabelStr? Instruction*
2882 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2883 // If this basic block starts out with a name, remember it.
2885 LocTy NameLoc = Lex.getLoc();
2886 if (Lex.getKind() == lltok::LabelStr) {
2887 Name = Lex.getStrVal();
2891 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2892 if (BB == 0) return true;
2894 std::string NameStr;
2896 // Parse the instructions in this block until we get a terminator.
2898 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2900 // This instruction may have three possibilities for a name: a) none
2901 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2902 LocTy NameLoc = Lex.getLoc();
2906 if (Lex.getKind() == lltok::LocalVarID) {
2907 NameID = Lex.getUIntVal();
2909 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2911 } else if (Lex.getKind() == lltok::LocalVar) {
2912 NameStr = Lex.getStrVal();
2914 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2918 switch (ParseInstruction(Inst, BB, PFS)) {
2919 default: llvm_unreachable("Unknown ParseInstruction result!");
2920 case InstError: return true;
2922 BB->getInstList().push_back(Inst);
2924 // With a normal result, we check to see if the instruction is followed by
2925 // a comma and metadata.
2926 if (EatIfPresent(lltok::comma))
2927 if (ParseInstructionMetadata(Inst, &PFS))
2930 case InstExtraComma:
2931 BB->getInstList().push_back(Inst);
2933 // If the instruction parser ate an extra comma at the end of it, it
2934 // *must* be followed by metadata.
2935 if (ParseInstructionMetadata(Inst, &PFS))
2940 // Set the name on the instruction.
2941 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2942 } while (!isa<TerminatorInst>(Inst));
2947 //===----------------------------------------------------------------------===//
2948 // Instruction Parsing.
2949 //===----------------------------------------------------------------------===//
2951 /// ParseInstruction - Parse one of the many different instructions.
2953 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2954 PerFunctionState &PFS) {
2955 lltok::Kind Token = Lex.getKind();
2956 if (Token == lltok::Eof)
2957 return TokError("found end of file when expecting more instructions");
2958 LocTy Loc = Lex.getLoc();
2959 unsigned KeywordVal = Lex.getUIntVal();
2960 Lex.Lex(); // Eat the keyword.
2963 default: return Error(Loc, "expected instruction opcode");
2964 // Terminator Instructions.
2965 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2966 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2967 case lltok::kw_br: return ParseBr(Inst, PFS);
2968 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2969 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2970 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2971 case lltok::kw_resume: return ParseResume(Inst, PFS);
2972 // Binary Operators.
2976 case lltok::kw_shl: {
2977 bool NUW = EatIfPresent(lltok::kw_nuw);
2978 bool NSW = EatIfPresent(lltok::kw_nsw);
2979 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2981 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2983 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2984 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2987 case lltok::kw_fadd:
2988 case lltok::kw_fsub:
2989 case lltok::kw_fmul:
2990 case lltok::kw_fdiv:
2991 case lltok::kw_frem: {
2992 FastMathFlags FMF = EatFastMathFlagsIfPresent();
2993 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
2997 Inst->setFastMathFlags(FMF);
3001 case lltok::kw_sdiv:
3002 case lltok::kw_udiv:
3003 case lltok::kw_lshr:
3004 case lltok::kw_ashr: {
3005 bool Exact = EatIfPresent(lltok::kw_exact);
3007 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3008 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3012 case lltok::kw_urem:
3013 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3016 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3017 case lltok::kw_icmp:
3018 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3020 case lltok::kw_trunc:
3021 case lltok::kw_zext:
3022 case lltok::kw_sext:
3023 case lltok::kw_fptrunc:
3024 case lltok::kw_fpext:
3025 case lltok::kw_bitcast:
3026 case lltok::kw_uitofp:
3027 case lltok::kw_sitofp:
3028 case lltok::kw_fptoui:
3029 case lltok::kw_fptosi:
3030 case lltok::kw_inttoptr:
3031 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3033 case lltok::kw_select: return ParseSelect(Inst, PFS);
3034 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3035 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3036 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3037 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3038 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3039 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3040 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3041 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3043 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3044 case lltok::kw_load: return ParseLoad(Inst, PFS);
3045 case lltok::kw_store: return ParseStore(Inst, PFS);
3046 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3047 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3048 case lltok::kw_fence: return ParseFence(Inst, PFS);
3049 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3050 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3051 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3055 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3056 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3057 if (Opc == Instruction::FCmp) {
3058 switch (Lex.getKind()) {
3059 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3060 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3061 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3062 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3063 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3064 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3065 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3066 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3067 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3068 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3069 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3070 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3071 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3072 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3073 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3074 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3075 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3078 switch (Lex.getKind()) {
3079 default: TokError("expected icmp predicate (e.g. 'eq')");
3080 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3081 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3082 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3083 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3084 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3085 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3086 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3087 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3088 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3089 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3096 //===----------------------------------------------------------------------===//
3097 // Terminator Instructions.
3098 //===----------------------------------------------------------------------===//
3100 /// ParseRet - Parse a return instruction.
3101 /// ::= 'ret' void (',' !dbg, !1)*
3102 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3103 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3104 PerFunctionState &PFS) {
3105 SMLoc TypeLoc = Lex.getLoc();
3107 if (ParseType(Ty, true /*void allowed*/)) return true;
3109 Type *ResType = PFS.getFunction().getReturnType();
3111 if (Ty->isVoidTy()) {
3112 if (!ResType->isVoidTy())
3113 return Error(TypeLoc, "value doesn't match function result type '" +
3114 getTypeString(ResType) + "'");
3116 Inst = ReturnInst::Create(Context);
3121 if (ParseValue(Ty, RV, PFS)) return true;
3123 if (ResType != RV->getType())
3124 return Error(TypeLoc, "value doesn't match function result type '" +
3125 getTypeString(ResType) + "'");
3127 Inst = ReturnInst::Create(Context, RV);
3133 /// ::= 'br' TypeAndValue
3134 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3135 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3138 BasicBlock *Op1, *Op2;
3139 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3141 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3142 Inst = BranchInst::Create(BB);
3146 if (Op0->getType() != Type::getInt1Ty(Context))
3147 return Error(Loc, "branch condition must have 'i1' type");
3149 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3150 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3151 ParseToken(lltok::comma, "expected ',' after true destination") ||
3152 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3155 Inst = BranchInst::Create(Op1, Op2, Op0);
3161 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3163 /// ::= (TypeAndValue ',' TypeAndValue)*
3164 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3165 LocTy CondLoc, BBLoc;
3167 BasicBlock *DefaultBB;
3168 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3169 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3170 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3171 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3174 if (!Cond->getType()->isIntegerTy())
3175 return Error(CondLoc, "switch condition must have integer type");
3177 // Parse the jump table pairs.
3178 SmallPtrSet<Value*, 32> SeenCases;
3179 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3180 while (Lex.getKind() != lltok::rsquare) {
3184 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3185 ParseToken(lltok::comma, "expected ',' after case value") ||
3186 ParseTypeAndBasicBlock(DestBB, PFS))
3189 if (!SeenCases.insert(Constant))
3190 return Error(CondLoc, "duplicate case value in switch");
3191 if (!isa<ConstantInt>(Constant))
3192 return Error(CondLoc, "case value is not a constant integer");
3194 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3197 Lex.Lex(); // Eat the ']'.
3199 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3200 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3201 SI->addCase(Table[i].first, Table[i].second);
3208 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3209 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3212 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3213 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3214 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3217 if (!Address->getType()->isPointerTy())
3218 return Error(AddrLoc, "indirectbr address must have pointer type");
3220 // Parse the destination list.
3221 SmallVector<BasicBlock*, 16> DestList;
3223 if (Lex.getKind() != lltok::rsquare) {
3225 if (ParseTypeAndBasicBlock(DestBB, PFS))
3227 DestList.push_back(DestBB);
3229 while (EatIfPresent(lltok::comma)) {
3230 if (ParseTypeAndBasicBlock(DestBB, PFS))
3232 DestList.push_back(DestBB);
3236 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3239 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3240 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3241 IBI->addDestination(DestList[i]);
3248 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3249 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3250 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3251 LocTy CallLoc = Lex.getLoc();
3252 AttrBuilder RetAttrs, FnAttrs;
3257 SmallVector<ParamInfo, 16> ArgList;
3259 BasicBlock *NormalBB, *UnwindBB;
3260 if (ParseOptionalCallingConv(CC) ||
3261 ParseOptionalAttrs(RetAttrs, 1) ||
3262 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3263 ParseValID(CalleeID) ||
3264 ParseParameterList(ArgList, PFS) ||
3265 ParseOptionalAttrs(FnAttrs, 2) ||
3266 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3267 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3268 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3269 ParseTypeAndBasicBlock(UnwindBB, PFS))
3272 // If RetType is a non-function pointer type, then this is the short syntax
3273 // for the call, which means that RetType is just the return type. Infer the
3274 // rest of the function argument types from the arguments that are present.
3275 PointerType *PFTy = 0;
3276 FunctionType *Ty = 0;
3277 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3278 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3279 // Pull out the types of all of the arguments...
3280 std::vector<Type*> ParamTypes;
3281 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3282 ParamTypes.push_back(ArgList[i].V->getType());
3284 if (!FunctionType::isValidReturnType(RetType))
3285 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3287 Ty = FunctionType::get(RetType, ParamTypes, false);
3288 PFTy = PointerType::getUnqual(Ty);
3291 // Look up the callee.
3293 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3295 // Set up the Attributes for the function.
3296 SmallVector<AttributeWithIndex, 8> Attrs;
3297 if (RetAttrs.hasAttributes())
3299 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
3300 Attributes::get(Callee->getContext(),
3303 SmallVector<Value*, 8> Args;
3305 // Loop through FunctionType's arguments and ensure they are specified
3306 // correctly. Also, gather any parameter attributes.
3307 FunctionType::param_iterator I = Ty->param_begin();
3308 FunctionType::param_iterator E = Ty->param_end();
3309 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3310 Type *ExpectedTy = 0;
3313 } else if (!Ty->isVarArg()) {
3314 return Error(ArgList[i].Loc, "too many arguments specified");
3317 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3318 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3319 getTypeString(ExpectedTy) + "'");
3320 Args.push_back(ArgList[i].V);
3321 if (ArgList[i].Attrs.hasAttributes())
3322 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3326 return Error(CallLoc, "not enough parameters specified for call");
3328 if (FnAttrs.hasAttributes())
3330 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
3331 Attributes::get(Callee->getContext(),
3334 // Finish off the Attributes and check them
3335 AttrListPtr PAL = AttrListPtr::get(Context, Attrs);
3337 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3338 II->setCallingConv(CC);
3339 II->setAttributes(PAL);
3345 /// ::= 'resume' TypeAndValue
3346 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3347 Value *Exn; LocTy ExnLoc;
3348 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3351 ResumeInst *RI = ResumeInst::Create(Exn);
3356 //===----------------------------------------------------------------------===//
3357 // Binary Operators.
3358 //===----------------------------------------------------------------------===//
3361 /// ::= ArithmeticOps TypeAndValue ',' Value
3363 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3364 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3365 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3366 unsigned Opc, unsigned OperandType) {
3367 LocTy Loc; Value *LHS, *RHS;
3368 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3369 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3370 ParseValue(LHS->getType(), RHS, PFS))
3374 switch (OperandType) {
3375 default: llvm_unreachable("Unknown operand type!");
3376 case 0: // int or FP.
3377 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3378 LHS->getType()->isFPOrFPVectorTy();
3380 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3381 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3385 return Error(Loc, "invalid operand type for instruction");
3387 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3392 /// ::= ArithmeticOps TypeAndValue ',' Value {
3393 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3395 LocTy Loc; Value *LHS, *RHS;
3396 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3397 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3398 ParseValue(LHS->getType(), RHS, PFS))
3401 if (!LHS->getType()->isIntOrIntVectorTy())
3402 return Error(Loc,"instruction requires integer or integer vector operands");
3404 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3410 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3411 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3412 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3414 // Parse the integer/fp comparison predicate.
3418 if (ParseCmpPredicate(Pred, Opc) ||
3419 ParseTypeAndValue(LHS, Loc, PFS) ||
3420 ParseToken(lltok::comma, "expected ',' after compare value") ||
3421 ParseValue(LHS->getType(), RHS, PFS))
3424 if (Opc == Instruction::FCmp) {
3425 if (!LHS->getType()->isFPOrFPVectorTy())
3426 return Error(Loc, "fcmp requires floating point operands");
3427 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3429 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3430 if (!LHS->getType()->isIntOrIntVectorTy() &&
3431 !LHS->getType()->getScalarType()->isPointerTy())
3432 return Error(Loc, "icmp requires integer operands");
3433 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3438 //===----------------------------------------------------------------------===//
3439 // Other Instructions.
3440 //===----------------------------------------------------------------------===//
3444 /// ::= CastOpc TypeAndValue 'to' Type
3445 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3450 if (ParseTypeAndValue(Op, Loc, PFS) ||
3451 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3455 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3456 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3457 return Error(Loc, "invalid cast opcode for cast from '" +
3458 getTypeString(Op->getType()) + "' to '" +
3459 getTypeString(DestTy) + "'");
3461 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3466 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3467 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3469 Value *Op0, *Op1, *Op2;
3470 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3471 ParseToken(lltok::comma, "expected ',' after select condition") ||
3472 ParseTypeAndValue(Op1, PFS) ||
3473 ParseToken(lltok::comma, "expected ',' after select value") ||
3474 ParseTypeAndValue(Op2, PFS))
3477 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3478 return Error(Loc, Reason);
3480 Inst = SelectInst::Create(Op0, Op1, Op2);
3485 /// ::= 'va_arg' TypeAndValue ',' Type
3486 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3490 if (ParseTypeAndValue(Op, PFS) ||
3491 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3492 ParseType(EltTy, TypeLoc))
3495 if (!EltTy->isFirstClassType())
3496 return Error(TypeLoc, "va_arg requires operand with first class type");
3498 Inst = new VAArgInst(Op, EltTy);
3502 /// ParseExtractElement
3503 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3504 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3507 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3508 ParseToken(lltok::comma, "expected ',' after extract value") ||
3509 ParseTypeAndValue(Op1, PFS))
3512 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3513 return Error(Loc, "invalid extractelement operands");
3515 Inst = ExtractElementInst::Create(Op0, Op1);
3519 /// ParseInsertElement
3520 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3521 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3523 Value *Op0, *Op1, *Op2;
3524 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3525 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3526 ParseTypeAndValue(Op1, PFS) ||
3527 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3528 ParseTypeAndValue(Op2, PFS))
3531 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3532 return Error(Loc, "invalid insertelement operands");
3534 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3538 /// ParseShuffleVector
3539 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3540 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3542 Value *Op0, *Op1, *Op2;
3543 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3544 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3545 ParseTypeAndValue(Op1, PFS) ||
3546 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3547 ParseTypeAndValue(Op2, PFS))
3550 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3551 return Error(Loc, "invalid shufflevector operands");
3553 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3558 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3559 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3560 Type *Ty = 0; LocTy TypeLoc;
3563 if (ParseType(Ty, TypeLoc) ||
3564 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3565 ParseValue(Ty, Op0, PFS) ||
3566 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3567 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3568 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3571 bool AteExtraComma = false;
3572 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3574 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3576 if (!EatIfPresent(lltok::comma))
3579 if (Lex.getKind() == lltok::MetadataVar) {
3580 AteExtraComma = true;
3584 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3585 ParseValue(Ty, Op0, PFS) ||
3586 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3587 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3588 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3592 if (!Ty->isFirstClassType())
3593 return Error(TypeLoc, "phi node must have first class type");
3595 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3596 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3597 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3599 return AteExtraComma ? InstExtraComma : InstNormal;
3603 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3605 /// ::= 'catch' TypeAndValue
3607 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3608 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3609 Type *Ty = 0; LocTy TyLoc;
3610 Value *PersFn; LocTy PersFnLoc;
3612 if (ParseType(Ty, TyLoc) ||
3613 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3614 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3617 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3618 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3620 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3621 LandingPadInst::ClauseType CT;
3622 if (EatIfPresent(lltok::kw_catch))
3623 CT = LandingPadInst::Catch;
3624 else if (EatIfPresent(lltok::kw_filter))
3625 CT = LandingPadInst::Filter;
3627 return TokError("expected 'catch' or 'filter' clause type");
3629 Value *V; LocTy VLoc;
3630 if (ParseTypeAndValue(V, VLoc, PFS)) {
3635 // A 'catch' type expects a non-array constant. A filter clause expects an
3637 if (CT == LandingPadInst::Catch) {
3638 if (isa<ArrayType>(V->getType()))
3639 Error(VLoc, "'catch' clause has an invalid type");
3641 if (!isa<ArrayType>(V->getType()))
3642 Error(VLoc, "'filter' clause has an invalid type");
3653 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3654 /// ParameterList OptionalAttrs
3655 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3657 AttrBuilder RetAttrs, FnAttrs;
3662 SmallVector<ParamInfo, 16> ArgList;
3663 LocTy CallLoc = Lex.getLoc();
3665 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3666 ParseOptionalCallingConv(CC) ||
3667 ParseOptionalAttrs(RetAttrs, 1) ||
3668 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3669 ParseValID(CalleeID) ||
3670 ParseParameterList(ArgList, PFS) ||
3671 ParseOptionalAttrs(FnAttrs, 2))
3674 // If RetType is a non-function pointer type, then this is the short syntax
3675 // for the call, which means that RetType is just the return type. Infer the
3676 // rest of the function argument types from the arguments that are present.
3677 PointerType *PFTy = 0;
3678 FunctionType *Ty = 0;
3679 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3680 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3681 // Pull out the types of all of the arguments...
3682 std::vector<Type*> ParamTypes;
3683 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3684 ParamTypes.push_back(ArgList[i].V->getType());
3686 if (!FunctionType::isValidReturnType(RetType))
3687 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3689 Ty = FunctionType::get(RetType, ParamTypes, false);
3690 PFTy = PointerType::getUnqual(Ty);
3693 // Look up the callee.
3695 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3697 // Set up the Attributes for the function.
3698 SmallVector<AttributeWithIndex, 8> Attrs;
3699 if (RetAttrs.hasAttributes())
3701 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
3702 Attributes::get(Callee->getContext(),
3705 SmallVector<Value*, 8> Args;
3707 // Loop through FunctionType's arguments and ensure they are specified
3708 // correctly. Also, gather any parameter attributes.
3709 FunctionType::param_iterator I = Ty->param_begin();
3710 FunctionType::param_iterator E = Ty->param_end();
3711 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3712 Type *ExpectedTy = 0;
3715 } else if (!Ty->isVarArg()) {
3716 return Error(ArgList[i].Loc, "too many arguments specified");
3719 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3720 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3721 getTypeString(ExpectedTy) + "'");
3722 Args.push_back(ArgList[i].V);
3723 if (ArgList[i].Attrs.hasAttributes())
3724 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3728 return Error(CallLoc, "not enough parameters specified for call");
3730 if (FnAttrs.hasAttributes())
3732 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
3733 Attributes::get(Callee->getContext(),
3736 // Finish off the Attributes and check them
3737 AttrListPtr PAL = AttrListPtr::get(Context, Attrs);
3739 CallInst *CI = CallInst::Create(Callee, Args);
3740 CI->setTailCall(isTail);
3741 CI->setCallingConv(CC);
3742 CI->setAttributes(PAL);
3747 //===----------------------------------------------------------------------===//
3748 // Memory Instructions.
3749 //===----------------------------------------------------------------------===//
3752 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3753 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3756 unsigned Alignment = 0;
3758 if (ParseType(Ty)) return true;
3760 bool AteExtraComma = false;
3761 if (EatIfPresent(lltok::comma)) {
3762 if (Lex.getKind() == lltok::kw_align) {
3763 if (ParseOptionalAlignment(Alignment)) return true;
3764 } else if (Lex.getKind() == lltok::MetadataVar) {
3765 AteExtraComma = true;
3767 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3768 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3773 if (Size && !Size->getType()->isIntegerTy())
3774 return Error(SizeLoc, "element count must have integer type");
3776 Inst = new AllocaInst(Ty, Size, Alignment);
3777 return AteExtraComma ? InstExtraComma : InstNormal;
3781 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3782 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3783 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3784 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
3785 Value *Val; LocTy Loc;
3786 unsigned Alignment = 0;
3787 bool AteExtraComma = false;
3788 bool isAtomic = false;
3789 AtomicOrdering Ordering = NotAtomic;
3790 SynchronizationScope Scope = CrossThread;
3792 if (Lex.getKind() == lltok::kw_atomic) {
3797 bool isVolatile = false;
3798 if (Lex.getKind() == lltok::kw_volatile) {
3803 if (ParseTypeAndValue(Val, Loc, PFS) ||
3804 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3805 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3808 if (!Val->getType()->isPointerTy() ||
3809 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3810 return Error(Loc, "load operand must be a pointer to a first class type");
3811 if (isAtomic && !Alignment)
3812 return Error(Loc, "atomic load must have explicit non-zero alignment");
3813 if (Ordering == Release || Ordering == AcquireRelease)
3814 return Error(Loc, "atomic load cannot use Release ordering");
3816 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
3817 return AteExtraComma ? InstExtraComma : InstNormal;
3822 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3823 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
3824 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3825 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
3826 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3827 unsigned Alignment = 0;
3828 bool AteExtraComma = false;
3829 bool isAtomic = false;
3830 AtomicOrdering Ordering = NotAtomic;
3831 SynchronizationScope Scope = CrossThread;
3833 if (Lex.getKind() == lltok::kw_atomic) {
3838 bool isVolatile = false;
3839 if (Lex.getKind() == lltok::kw_volatile) {
3844 if (ParseTypeAndValue(Val, Loc, PFS) ||
3845 ParseToken(lltok::comma, "expected ',' after store operand") ||
3846 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3847 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3848 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3851 if (!Ptr->getType()->isPointerTy())
3852 return Error(PtrLoc, "store operand must be a pointer");
3853 if (!Val->getType()->isFirstClassType())
3854 return Error(Loc, "store operand must be a first class value");
3855 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3856 return Error(Loc, "stored value and pointer type do not match");
3857 if (isAtomic && !Alignment)
3858 return Error(Loc, "atomic store must have explicit non-zero alignment");
3859 if (Ordering == Acquire || Ordering == AcquireRelease)
3860 return Error(Loc, "atomic store cannot use Acquire ordering");
3862 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
3863 return AteExtraComma ? InstExtraComma : InstNormal;
3867 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3868 /// 'singlethread'? AtomicOrdering
3869 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
3870 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3871 bool AteExtraComma = false;
3872 AtomicOrdering Ordering = NotAtomic;
3873 SynchronizationScope Scope = CrossThread;
3874 bool isVolatile = false;
3876 if (EatIfPresent(lltok::kw_volatile))
3879 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3880 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3881 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3882 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3883 ParseTypeAndValue(New, NewLoc, PFS) ||
3884 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3887 if (Ordering == Unordered)
3888 return TokError("cmpxchg cannot be unordered");
3889 if (!Ptr->getType()->isPointerTy())
3890 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3891 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3892 return Error(CmpLoc, "compare value and pointer type do not match");
3893 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3894 return Error(NewLoc, "new value and pointer type do not match");
3895 if (!New->getType()->isIntegerTy())
3896 return Error(NewLoc, "cmpxchg operand must be an integer");
3897 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3898 if (Size < 8 || (Size & (Size - 1)))
3899 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3902 AtomicCmpXchgInst *CXI =
3903 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3904 CXI->setVolatile(isVolatile);
3906 return AteExtraComma ? InstExtraComma : InstNormal;
3910 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3911 /// 'singlethread'? AtomicOrdering
3912 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
3913 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3914 bool AteExtraComma = false;
3915 AtomicOrdering Ordering = NotAtomic;
3916 SynchronizationScope Scope = CrossThread;
3917 bool isVolatile = false;
3918 AtomicRMWInst::BinOp Operation;
3920 if (EatIfPresent(lltok::kw_volatile))
3923 switch (Lex.getKind()) {
3924 default: return TokError("expected binary operation in atomicrmw");
3925 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3926 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3927 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3928 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3929 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3930 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3931 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3932 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3933 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3934 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3935 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3937 Lex.Lex(); // Eat the operation.
3939 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3940 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3941 ParseTypeAndValue(Val, ValLoc, PFS) ||
3942 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3945 if (Ordering == Unordered)
3946 return TokError("atomicrmw cannot be unordered");
3947 if (!Ptr->getType()->isPointerTy())
3948 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3949 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3950 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3951 if (!Val->getType()->isIntegerTy())
3952 return Error(ValLoc, "atomicrmw operand must be an integer");
3953 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3954 if (Size < 8 || (Size & (Size - 1)))
3955 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3958 AtomicRMWInst *RMWI =
3959 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3960 RMWI->setVolatile(isVolatile);
3962 return AteExtraComma ? InstExtraComma : InstNormal;
3966 /// ::= 'fence' 'singlethread'? AtomicOrdering
3967 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3968 AtomicOrdering Ordering = NotAtomic;
3969 SynchronizationScope Scope = CrossThread;
3970 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3973 if (Ordering == Unordered)
3974 return TokError("fence cannot be unordered");
3975 if (Ordering == Monotonic)
3976 return TokError("fence cannot be monotonic");
3978 Inst = new FenceInst(Context, Ordering, Scope);
3982 /// ParseGetElementPtr
3983 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3984 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3989 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3991 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3993 if (!Ptr->getType()->getScalarType()->isPointerTy())
3994 return Error(Loc, "base of getelementptr must be a pointer");
3996 SmallVector<Value*, 16> Indices;
3997 bool AteExtraComma = false;
3998 while (EatIfPresent(lltok::comma)) {
3999 if (Lex.getKind() == lltok::MetadataVar) {
4000 AteExtraComma = true;
4003 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4004 if (!Val->getType()->getScalarType()->isIntegerTy())
4005 return Error(EltLoc, "getelementptr index must be an integer");
4006 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4007 return Error(EltLoc, "getelementptr index type missmatch");
4008 if (Val->getType()->isVectorTy()) {
4009 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4010 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4011 if (ValNumEl != PtrNumEl)
4012 return Error(EltLoc,
4013 "getelementptr vector index has a wrong number of elements");
4015 Indices.push_back(Val);
4018 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
4019 return Error(Loc, "invalid getelementptr indices");
4020 Inst = GetElementPtrInst::Create(Ptr, Indices);
4022 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4023 return AteExtraComma ? InstExtraComma : InstNormal;
4026 /// ParseExtractValue
4027 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4028 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4029 Value *Val; LocTy Loc;
4030 SmallVector<unsigned, 4> Indices;
4032 if (ParseTypeAndValue(Val, Loc, PFS) ||
4033 ParseIndexList(Indices, AteExtraComma))
4036 if (!Val->getType()->isAggregateType())
4037 return Error(Loc, "extractvalue operand must be aggregate type");
4039 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4040 return Error(Loc, "invalid indices for extractvalue");
4041 Inst = ExtractValueInst::Create(Val, Indices);
4042 return AteExtraComma ? InstExtraComma : InstNormal;
4045 /// ParseInsertValue
4046 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4047 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4048 Value *Val0, *Val1; LocTy Loc0, Loc1;
4049 SmallVector<unsigned, 4> Indices;
4051 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4052 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4053 ParseTypeAndValue(Val1, Loc1, PFS) ||
4054 ParseIndexList(Indices, AteExtraComma))
4057 if (!Val0->getType()->isAggregateType())
4058 return Error(Loc0, "insertvalue operand must be aggregate type");
4060 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4061 return Error(Loc0, "invalid indices for insertvalue");
4062 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4063 return AteExtraComma ? InstExtraComma : InstNormal;
4066 //===----------------------------------------------------------------------===//
4067 // Embedded metadata.
4068 //===----------------------------------------------------------------------===//
4070 /// ParseMDNodeVector
4071 /// ::= Element (',' Element)*
4073 /// ::= 'null' | TypeAndValue
4074 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4075 PerFunctionState *PFS) {
4076 // Check for an empty list.
4077 if (Lex.getKind() == lltok::rbrace)
4081 // Null is a special case since it is typeless.
4082 if (EatIfPresent(lltok::kw_null)) {
4088 if (ParseTypeAndValue(V, PFS)) return true;
4090 } while (EatIfPresent(lltok::comma));