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/ValueSymbolTable.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Support/raw_ostream.h"
29 /// ValID - Represents a reference of a definition of some sort with no type.
30 /// There are several cases where we have to parse the value but where the
31 /// type can depend on later context. This may either be a numeric reference
32 /// or a symbolic (%var) reference. This is just a discriminated union.
35 t_LocalID, t_GlobalID, // ID in UIntVal.
36 t_LocalName, t_GlobalName, // Name in StrVal.
37 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
38 t_Null, t_Undef, t_Zero, // No value.
39 t_EmptyArray, // No value: []
40 t_Constant, // Value in ConstantVal.
41 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
46 std::string StrVal, StrVal2;
49 Constant *ConstantVal;
50 ValID() : APFloatVal(0.0) {}
54 /// Run: module ::= toplevelentity*
55 bool LLParser::Run() {
59 return ParseTopLevelEntities() ||
60 ValidateEndOfModule();
63 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
65 bool LLParser::ValidateEndOfModule() {
66 if (!ForwardRefTypes.empty())
67 return Error(ForwardRefTypes.begin()->second.second,
68 "use of undefined type named '" +
69 ForwardRefTypes.begin()->first + "'");
70 if (!ForwardRefTypeIDs.empty())
71 return Error(ForwardRefTypeIDs.begin()->second.second,
72 "use of undefined type '%" +
73 utostr(ForwardRefTypeIDs.begin()->first) + "'");
75 if (!ForwardRefVals.empty())
76 return Error(ForwardRefVals.begin()->second.second,
77 "use of undefined value '@" + ForwardRefVals.begin()->first +
80 if (!ForwardRefValIDs.empty())
81 return Error(ForwardRefValIDs.begin()->second.second,
82 "use of undefined value '@" +
83 utostr(ForwardRefValIDs.begin()->first) + "'");
85 // Look for intrinsic functions and CallInst that need to be upgraded
86 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
87 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
92 //===----------------------------------------------------------------------===//
94 //===----------------------------------------------------------------------===//
96 bool LLParser::ParseTopLevelEntities() {
98 switch (Lex.getKind()) {
99 default: return TokError("expected top-level entity");
100 case lltok::Eof: return false;
101 //case lltok::kw_define:
102 case lltok::kw_declare: if (ParseDeclare()) return true; break;
103 case lltok::kw_define: if (ParseDefine()) return true; break;
104 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
105 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
106 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
107 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
108 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
109 case lltok::LocalVar: if (ParseNamedType()) return true; break;
110 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
112 // The Global variable production with no name can have many different
113 // optional leading prefixes, the production is:
114 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
115 // OptionalAddrSpace ('constant'|'global') ...
116 case lltok::kw_private: // OptionalLinkage
117 case lltok::kw_internal: // OptionalLinkage
118 case lltok::kw_weak: // OptionalLinkage
119 case lltok::kw_linkonce: // OptionalLinkage
120 case lltok::kw_appending: // OptionalLinkage
121 case lltok::kw_dllexport: // OptionalLinkage
122 case lltok::kw_common: // OptionalLinkage
123 case lltok::kw_dllimport: // OptionalLinkage
124 case lltok::kw_extern_weak: // OptionalLinkage
125 case lltok::kw_external: { // OptionalLinkage
126 unsigned Linkage, Visibility;
127 if (ParseOptionalLinkage(Linkage) ||
128 ParseOptionalVisibility(Visibility) ||
129 ParseGlobal("", 0, Linkage, true, Visibility))
133 case lltok::kw_default: // OptionalVisibility
134 case lltok::kw_hidden: // OptionalVisibility
135 case lltok::kw_protected: { // OptionalVisibility
137 if (ParseOptionalVisibility(Visibility) ||
138 ParseGlobal("", 0, 0, false, Visibility))
143 case lltok::kw_thread_local: // OptionalThreadLocal
144 case lltok::kw_addrspace: // OptionalAddrSpace
145 case lltok::kw_constant: // GlobalType
146 case lltok::kw_global: // GlobalType
147 if (ParseGlobal("", 0, 0, false, 0)) return true;
155 /// ::= 'module' 'asm' STRINGCONSTANT
156 bool LLParser::ParseModuleAsm() {
157 assert(Lex.getKind() == lltok::kw_module);
161 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
162 ParseStringConstant(AsmStr)) return true;
164 const std::string &AsmSoFar = M->getModuleInlineAsm();
165 if (AsmSoFar.empty())
166 M->setModuleInlineAsm(AsmStr);
168 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
173 /// ::= 'target' 'triple' '=' STRINGCONSTANT
174 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
175 bool LLParser::ParseTargetDefinition() {
176 assert(Lex.getKind() == lltok::kw_target);
179 default: return TokError("unknown target property");
180 case lltok::kw_triple:
182 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
183 ParseStringConstant(Str))
185 M->setTargetTriple(Str);
187 case lltok::kw_datalayout:
189 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
190 ParseStringConstant(Str))
192 M->setDataLayout(Str);
198 /// ::= 'deplibs' '=' '[' ']'
199 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
200 bool LLParser::ParseDepLibs() {
201 assert(Lex.getKind() == lltok::kw_deplibs);
203 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
204 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
207 if (EatIfPresent(lltok::rsquare))
211 if (ParseStringConstant(Str)) return true;
214 while (EatIfPresent(lltok::comma)) {
215 if (ParseStringConstant(Str)) return true;
219 return ParseToken(lltok::rsquare, "expected ']' at end of list");
224 bool LLParser::ParseUnnamedType() {
225 assert(Lex.getKind() == lltok::kw_type);
226 LocTy TypeLoc = Lex.getLoc();
227 Lex.Lex(); // eat kw_type
229 PATypeHolder Ty(Type::VoidTy);
230 if (ParseType(Ty)) return true;
232 unsigned TypeID = NumberedTypes.size();
234 // We don't allow assigning names to void type
235 if (Ty == Type::VoidTy)
236 return Error(TypeLoc, "can't assign name to the void type");
238 // See if this type was previously referenced.
239 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
240 FI = ForwardRefTypeIDs.find(TypeID);
241 if (FI != ForwardRefTypeIDs.end()) {
242 if (FI->second.first.get() == Ty)
243 return Error(TypeLoc, "self referential type is invalid");
245 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
246 Ty = FI->second.first.get();
247 ForwardRefTypeIDs.erase(FI);
250 NumberedTypes.push_back(Ty);
256 /// ::= LocalVar '=' 'type' type
257 bool LLParser::ParseNamedType() {
258 std::string Name = Lex.getStrVal();
259 LocTy NameLoc = Lex.getLoc();
260 Lex.Lex(); // eat LocalVar.
262 PATypeHolder Ty(Type::VoidTy);
264 if (ParseToken(lltok::equal, "expected '=' after name") ||
265 ParseToken(lltok::kw_type, "expected 'type' after name") ||
269 // We don't allow assigning names to void type
270 if (Ty == Type::VoidTy)
271 return Error(NameLoc, "can't assign name '" + Name + "' to the void type");
273 // Set the type name, checking for conflicts as we do so.
274 bool AlreadyExists = M->addTypeName(Name, Ty);
275 if (!AlreadyExists) return false;
277 // See if this type is a forward reference. We need to eagerly resolve
278 // types to allow recursive type redefinitions below.
279 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
280 FI = ForwardRefTypes.find(Name);
281 if (FI != ForwardRefTypes.end()) {
282 if (FI->second.first.get() == Ty)
283 return Error(NameLoc, "self referential type is invalid");
285 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
286 Ty = FI->second.first.get();
287 ForwardRefTypes.erase(FI);
290 // Inserting a name that is already defined, get the existing name.
291 const Type *Existing = M->getTypeByName(Name);
292 assert(Existing && "Conflict but no matching type?!");
294 // Otherwise, this is an attempt to redefine a type. That's okay if
295 // the redefinition is identical to the original.
296 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
297 if (Existing == Ty) return false;
299 // Any other kind of (non-equivalent) redefinition is an error.
300 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
301 Ty->getDescription() + "'");
306 /// ::= 'declare' FunctionHeader
307 bool LLParser::ParseDeclare() {
308 assert(Lex.getKind() == lltok::kw_declare);
312 return ParseFunctionHeader(F, false);
316 /// ::= 'define' FunctionHeader '{' ...
317 bool LLParser::ParseDefine() {
318 assert(Lex.getKind() == lltok::kw_define);
322 return ParseFunctionHeader(F, true) ||
323 ParseFunctionBody(*F);
329 bool LLParser::ParseGlobalType(bool &IsConstant) {
330 if (Lex.getKind() == lltok::kw_constant)
332 else if (Lex.getKind() == lltok::kw_global)
336 return TokError("expected 'global' or 'constant'");
342 /// ParseNamedGlobal:
343 /// GlobalVar '=' OptionalVisibility ALIAS ...
344 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
345 bool LLParser::ParseNamedGlobal() {
346 assert(Lex.getKind() == lltok::GlobalVar);
347 LocTy NameLoc = Lex.getLoc();
348 std::string Name = Lex.getStrVal();
352 unsigned Linkage, Visibility;
353 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
354 ParseOptionalLinkage(Linkage, HasLinkage) ||
355 ParseOptionalVisibility(Visibility))
358 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
359 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
360 return ParseAlias(Name, NameLoc, Visibility);
364 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
366 /// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
368 /// Everything through visibility has already been parsed.
370 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
371 unsigned Visibility) {
372 assert(Lex.getKind() == lltok::kw_alias);
375 LocTy LinkageLoc = Lex.getLoc();
376 if (ParseOptionalLinkage(Linkage))
379 if (Linkage != GlobalValue::ExternalLinkage &&
380 Linkage != GlobalValue::WeakLinkage &&
381 Linkage != GlobalValue::InternalLinkage &&
382 Linkage != GlobalValue::PrivateLinkage)
383 return Error(LinkageLoc, "invalid linkage type for alias");
386 LocTy AliaseeLoc = Lex.getLoc();
387 if (Lex.getKind() != lltok::kw_bitcast) {
388 if (ParseGlobalTypeAndValue(Aliasee)) return true;
390 // The bitcast dest type is not present, it is implied by the dest type.
392 if (ParseValID(ID)) return true;
393 if (ID.Kind != ValID::t_Constant)
394 return Error(AliaseeLoc, "invalid aliasee");
395 Aliasee = ID.ConstantVal;
398 if (!isa<PointerType>(Aliasee->getType()))
399 return Error(AliaseeLoc, "alias must have pointer type");
401 // Okay, create the alias but do not insert it into the module yet.
402 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
403 (GlobalValue::LinkageTypes)Linkage, Name,
405 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
407 // See if this value already exists in the symbol table. If so, it is either
408 // a redefinition or a definition of a forward reference.
409 if (GlobalValue *Val =
410 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
411 // See if this was a redefinition. If so, there is no entry in
413 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
414 I = ForwardRefVals.find(Name);
415 if (I == ForwardRefVals.end())
416 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
418 // Otherwise, this was a definition of forward ref. Verify that types
420 if (Val->getType() != GA->getType())
421 return Error(NameLoc,
422 "forward reference and definition of alias have different types");
424 // If they agree, just RAUW the old value with the alias and remove the
426 Val->replaceAllUsesWith(GA);
427 Val->eraseFromParent();
428 ForwardRefVals.erase(I);
431 // Insert into the module, we know its name won't collide now.
432 M->getAliasList().push_back(GA);
433 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
439 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
440 /// OptionalAddrSpace GlobalType Type Const
441 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
442 /// OptionalAddrSpace GlobalType Type Const
444 /// Everything through visibility has been parsed already.
446 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
447 unsigned Linkage, bool HasLinkage,
448 unsigned Visibility) {
450 bool ThreadLocal, IsConstant;
453 PATypeHolder Ty(Type::VoidTy);
454 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
455 ParseOptionalAddrSpace(AddrSpace) ||
456 ParseGlobalType(IsConstant) ||
457 ParseType(Ty, TyLoc))
460 // If the linkage is specified and is external, then no initializer is
463 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
464 Linkage != GlobalValue::ExternalWeakLinkage &&
465 Linkage != GlobalValue::ExternalLinkage)) {
466 if (ParseGlobalValue(Ty, Init))
470 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || Ty == Type::VoidTy)
471 return Error(TyLoc, "invalid type for global variable");
473 GlobalVariable *GV = 0;
475 // See if the global was forward referenced, if so, use the global.
477 if ((GV = M->getGlobalVariable(Name, true)) &&
478 !ForwardRefVals.erase(Name))
479 return Error(NameLoc, "redefinition of global '@" + Name + "'");
481 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
482 I = ForwardRefValIDs.find(NumberedVals.size());
483 if (I != ForwardRefValIDs.end()) {
484 GV = cast<GlobalVariable>(I->second.first);
485 ForwardRefValIDs.erase(I);
490 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
491 M, false, AddrSpace);
493 if (GV->getType()->getElementType() != Ty)
495 "forward reference and definition of global have different types");
497 // Move the forward-reference to the correct spot in the module.
498 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
502 NumberedVals.push_back(GV);
504 // Set the parsed properties on the global.
506 GV->setInitializer(Init);
507 GV->setConstant(IsConstant);
508 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
509 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
510 GV->setThreadLocal(ThreadLocal);
512 // Parse attributes on the global.
513 while (Lex.getKind() == lltok::comma) {
516 if (Lex.getKind() == lltok::kw_section) {
518 GV->setSection(Lex.getStrVal());
519 if (ParseToken(lltok::StringConstant, "expected global section string"))
521 } else if (Lex.getKind() == lltok::kw_align) {
523 if (ParseOptionalAlignment(Alignment)) return true;
524 GV->setAlignment(Alignment);
526 TokError("unknown global variable property!");
534 //===----------------------------------------------------------------------===//
535 // GlobalValue Reference/Resolution Routines.
536 //===----------------------------------------------------------------------===//
538 /// GetGlobalVal - Get a value with the specified name or ID, creating a
539 /// forward reference record if needed. This can return null if the value
540 /// exists but does not have the right type.
541 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
543 const PointerType *PTy = dyn_cast<PointerType>(Ty);
545 Error(Loc, "global variable reference must have pointer type");
549 // Look this name up in the normal function symbol table.
551 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
553 // If this is a forward reference for the value, see if we already created a
554 // forward ref record.
556 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
557 I = ForwardRefVals.find(Name);
558 if (I != ForwardRefVals.end())
559 Val = I->second.first;
562 // If we have the value in the symbol table or fwd-ref table, return it.
564 if (Val->getType() == Ty) return Val;
565 Error(Loc, "'@" + Name + "' defined with type '" +
566 Val->getType()->getDescription() + "'");
570 // Otherwise, create a new forward reference for this value and remember it.
572 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
573 // Function types can return opaque but functions can't.
574 if (isa<OpaqueType>(FT->getReturnType())) {
575 Error(Loc, "function may not return opaque type");
579 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
581 FwdVal = new GlobalVariable(PTy->getElementType(), false,
582 GlobalValue::ExternalWeakLinkage, 0, Name, M);
585 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
589 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
590 const PointerType *PTy = dyn_cast<PointerType>(Ty);
592 Error(Loc, "global variable reference must have pointer type");
596 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
598 // If this is a forward reference for the value, see if we already created a
599 // forward ref record.
601 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
602 I = ForwardRefValIDs.find(ID);
603 if (I != ForwardRefValIDs.end())
604 Val = I->second.first;
607 // If we have the value in the symbol table or fwd-ref table, return it.
609 if (Val->getType() == Ty) return Val;
610 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
611 Val->getType()->getDescription() + "'");
615 // Otherwise, create a new forward reference for this value and remember it.
617 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
618 // Function types can return opaque but functions can't.
619 if (isa<OpaqueType>(FT->getReturnType())) {
620 Error(Loc, "function may not return opaque type");
623 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
625 FwdVal = new GlobalVariable(PTy->getElementType(), false,
626 GlobalValue::ExternalWeakLinkage, 0, "", M);
629 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
634 //===----------------------------------------------------------------------===//
636 //===----------------------------------------------------------------------===//
638 /// ParseToken - If the current token has the specified kind, eat it and return
639 /// success. Otherwise, emit the specified error and return failure.
640 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
641 if (Lex.getKind() != T)
642 return TokError(ErrMsg);
647 /// ParseStringConstant
648 /// ::= StringConstant
649 bool LLParser::ParseStringConstant(std::string &Result) {
650 if (Lex.getKind() != lltok::StringConstant)
651 return TokError("expected string constant");
652 Result = Lex.getStrVal();
659 bool LLParser::ParseUInt32(unsigned &Val) {
660 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
661 return TokError("expected integer");
662 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
663 if (Val64 != unsigned(Val64))
664 return TokError("expected 32-bit integer (too large)");
671 /// ParseOptionalAddrSpace
673 /// := 'addrspace' '(' uint32 ')'
674 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
676 if (!EatIfPresent(lltok::kw_addrspace))
678 return ParseToken(lltok::lparen, "expected '(' in address space") ||
679 ParseUInt32(AddrSpace) ||
680 ParseToken(lltok::rparen, "expected ')' in address space");
683 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
684 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
685 /// 2: function attr.
686 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
687 Attrs = Attribute::None;
688 LocTy AttrLoc = Lex.getLoc();
691 switch (Lex.getKind()) {
694 // Treat these as signext/zeroext unless they are function attrs.
695 // FIXME: REMOVE THIS IN LLVM 3.0
697 if (Lex.getKind() == lltok::kw_sext)
698 Attrs |= Attribute::SExt;
700 Attrs |= Attribute::ZExt;
704 default: // End of attributes.
705 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
706 return Error(AttrLoc, "invalid use of function-only attribute");
708 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
709 return Error(AttrLoc, "invalid use of parameter-only attribute");
712 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
713 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
714 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
715 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
716 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
717 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
718 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
719 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
721 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
722 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
723 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
724 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
725 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
726 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
727 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
728 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
729 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
732 case lltok::kw_align: {
734 if (ParseOptionalAlignment(Alignment))
736 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
744 /// ParseOptionalLinkage
754 /// ::= 'extern_weak'
756 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
758 switch (Lex.getKind()) {
759 default: Res = GlobalValue::ExternalLinkage; return false;
760 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
761 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
762 case lltok::kw_weak: Res = GlobalValue::WeakLinkage; break;
763 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceLinkage; break;
764 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
765 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
766 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
767 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
768 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
769 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
776 /// ParseOptionalVisibility
782 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
783 switch (Lex.getKind()) {
784 default: Res = GlobalValue::DefaultVisibility; return false;
785 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
786 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
787 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
793 /// ParseOptionalCallingConv
798 /// ::= 'x86_stdcallcc'
799 /// ::= 'x86_fastcallcc'
802 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
803 switch (Lex.getKind()) {
804 default: CC = CallingConv::C; return false;
805 case lltok::kw_ccc: CC = CallingConv::C; break;
806 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
807 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
808 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
809 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
810 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
816 /// ParseOptionalAlignment
819 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
821 if (!EatIfPresent(lltok::kw_align))
823 LocTy AlignLoc = Lex.getLoc();
824 if (ParseUInt32(Alignment)) return true;
825 if (!isPowerOf2_32(Alignment))
826 return Error(AlignLoc, "alignment is not a power of two");
830 /// ParseOptionalCommaAlignment
832 /// ::= ',' 'align' 4
833 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
835 if (!EatIfPresent(lltok::comma))
837 return ParseToken(lltok::kw_align, "expected 'align'") ||
838 ParseUInt32(Alignment);
842 /// ::= (',' uint32)+
843 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
844 if (Lex.getKind() != lltok::comma)
845 return TokError("expected ',' as start of index list");
847 while (EatIfPresent(lltok::comma)) {
849 if (ParseUInt32(Idx)) return true;
850 Indices.push_back(Idx);
856 //===----------------------------------------------------------------------===//
858 //===----------------------------------------------------------------------===//
860 /// ParseType - Parse and resolve a full type.
861 bool LLParser::ParseType(PATypeHolder &Result) {
862 if (ParseTypeRec(Result)) return true;
864 // Verify no unresolved uprefs.
866 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
871 /// HandleUpRefs - Every time we finish a new layer of types, this function is
872 /// called. It loops through the UpRefs vector, which is a list of the
873 /// currently active types. For each type, if the up-reference is contained in
874 /// the newly completed type, we decrement the level count. When the level
875 /// count reaches zero, the up-referenced type is the type that is passed in:
876 /// thus we can complete the cycle.
878 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
879 // If Ty isn't abstract, or if there are no up-references in it, then there is
880 // nothing to resolve here.
881 if (!ty->isAbstract() || UpRefs.empty()) return ty;
885 errs() << "Type '" << Ty->getDescription()
886 << "' newly formed. Resolving upreferences.\n"
887 << UpRefs.size() << " upreferences active!\n";
890 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
891 // to zero), we resolve them all together before we resolve them to Ty. At
892 // the end of the loop, if there is anything to resolve to Ty, it will be in
894 OpaqueType *TypeToResolve = 0;
896 for (unsigned i = 0; i != UpRefs.size(); ++i) {
897 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
899 std::find(Ty->subtype_begin(), Ty->subtype_end(),
900 UpRefs[i].LastContainedTy) != Ty->subtype_end();
903 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
904 << UpRefs[i].LastContainedTy->getDescription() << ") = "
905 << (ContainsType ? "true" : "false")
906 << " level=" << UpRefs[i].NestingLevel << "\n";
911 // Decrement level of upreference
912 unsigned Level = --UpRefs[i].NestingLevel;
913 UpRefs[i].LastContainedTy = Ty;
915 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
920 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
923 TypeToResolve = UpRefs[i].UpRefTy;
925 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
926 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
927 --i; // Do not skip the next element.
931 TypeToResolve->refineAbstractTypeTo(Ty);
937 /// ParseTypeRec - The recursive function used to process the internal
938 /// implementation details of types.
939 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
940 switch (Lex.getKind()) {
942 return TokError("expected type");
944 // TypeRec ::= 'float' | 'void' (etc)
945 Result = Lex.getTyVal();
948 case lltok::kw_opaque:
949 // TypeRec ::= 'opaque'
950 Result = OpaqueType::get();
954 // TypeRec ::= '{' ... '}'
955 if (ParseStructType(Result, false))
959 // TypeRec ::= '[' ... ']'
960 Lex.Lex(); // eat the lsquare.
961 if (ParseArrayVectorType(Result, false))
964 case lltok::less: // Either vector or packed struct.
965 // TypeRec ::= '<' ... '>'
967 if (Lex.getKind() == lltok::lbrace) {
968 if (ParseStructType(Result, true) ||
969 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
971 } else if (ParseArrayVectorType(Result, true))
974 case lltok::LocalVar:
975 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
977 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
980 Result = OpaqueType::get();
981 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
982 std::make_pair(Result,
984 M->addTypeName(Lex.getStrVal(), Result.get());
989 case lltok::LocalVarID:
991 if (Lex.getUIntVal() < NumberedTypes.size())
992 Result = NumberedTypes[Lex.getUIntVal()];
994 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
995 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
996 if (I != ForwardRefTypeIDs.end())
997 Result = I->second.first;
999 Result = OpaqueType::get();
1000 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1001 std::make_pair(Result,
1007 case lltok::backslash: {
1008 // TypeRec ::= '\' 4
1011 if (ParseUInt32(Val)) return true;
1012 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1013 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1019 // Parse the type suffixes.
1021 switch (Lex.getKind()) {
1023 default: return false;
1025 // TypeRec ::= TypeRec '*'
1027 if (Result.get() == Type::LabelTy)
1028 return TokError("basic block pointers are invalid");
1029 if (Result.get() == Type::VoidTy)
1030 return TokError("pointers to void are invalid; use i8* instead");
1031 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1035 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1036 case lltok::kw_addrspace: {
1037 if (Result.get() == Type::LabelTy)
1038 return TokError("basic block pointers are invalid");
1039 if (Result.get() == Type::VoidTy)
1040 return TokError("pointers to void are invalid; use i8* instead");
1042 if (ParseOptionalAddrSpace(AddrSpace) ||
1043 ParseToken(lltok::star, "expected '*' in address space"))
1046 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1050 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1052 if (ParseFunctionType(Result))
1059 /// ParseParameterList
1061 /// ::= '(' Arg (',' Arg)* ')'
1063 /// ::= Type OptionalAttributes Value OptionalAttributes
1064 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1065 PerFunctionState &PFS) {
1066 if (ParseToken(lltok::lparen, "expected '(' in call"))
1069 while (Lex.getKind() != lltok::rparen) {
1070 // If this isn't the first argument, we need a comma.
1071 if (!ArgList.empty() &&
1072 ParseToken(lltok::comma, "expected ',' in argument list"))
1075 // Parse the argument.
1077 PATypeHolder ArgTy(Type::VoidTy);
1078 unsigned ArgAttrs1, ArgAttrs2;
1080 if (ParseType(ArgTy, ArgLoc) ||
1081 ParseOptionalAttrs(ArgAttrs1, 0) ||
1082 ParseValue(ArgTy, V, PFS) ||
1083 // FIXME: Should not allow attributes after the argument, remove this in
1085 ParseOptionalAttrs(ArgAttrs2, 0))
1087 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1090 Lex.Lex(); // Lex the ')'.
1096 /// ParseArgumentList - Parse the argument list for a function type or function
1097 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1098 /// ::= '(' ArgTypeListI ')'
1102 /// ::= ArgTypeList ',' '...'
1103 /// ::= ArgType (',' ArgType)*
1105 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1106 bool &isVarArg, bool inType) {
1108 assert(Lex.getKind() == lltok::lparen);
1109 Lex.Lex(); // eat the (.
1111 if (Lex.getKind() == lltok::rparen) {
1113 } else if (Lex.getKind() == lltok::dotdotdot) {
1117 LocTy TypeLoc = Lex.getLoc();
1118 PATypeHolder ArgTy(Type::VoidTy);
1122 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1123 // types (such as a function returning a pointer to itself). If parsing a
1124 // function prototype, we require fully resolved types.
1125 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1126 ParseOptionalAttrs(Attrs, 0)) return true;
1128 if (Lex.getKind() == lltok::LocalVar ||
1129 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1130 Name = Lex.getStrVal();
1134 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1135 return Error(TypeLoc, "invalid type for function argument");
1137 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1139 while (EatIfPresent(lltok::comma)) {
1140 // Handle ... at end of arg list.
1141 if (EatIfPresent(lltok::dotdotdot)) {
1146 // Otherwise must be an argument type.
1147 TypeLoc = Lex.getLoc();
1148 if (ParseTypeRec(ArgTy) ||
1149 ParseOptionalAttrs(Attrs, 0)) return true;
1151 if (Lex.getKind() == lltok::LocalVar ||
1152 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1153 Name = Lex.getStrVal();
1159 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1160 return Error(TypeLoc, "invalid type for function argument");
1162 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1166 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1169 /// ParseFunctionType
1170 /// ::= Type ArgumentList OptionalAttrs
1171 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1172 assert(Lex.getKind() == lltok::lparen);
1174 if (!FunctionType::isValidReturnType(Result))
1175 return TokError("invalid function return type");
1177 std::vector<ArgInfo> ArgList;
1180 if (ParseArgumentList(ArgList, isVarArg, true) ||
1181 // FIXME: Allow, but ignore attributes on function types!
1182 // FIXME: Remove in LLVM 3.0
1183 ParseOptionalAttrs(Attrs, 2))
1186 // Reject names on the arguments lists.
1187 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1188 if (!ArgList[i].Name.empty())
1189 return Error(ArgList[i].Loc, "argument name invalid in function type");
1190 if (!ArgList[i].Attrs != 0) {
1191 // Allow but ignore attributes on function types; this permits
1193 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1197 std::vector<const Type*> ArgListTy;
1198 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1199 ArgListTy.push_back(ArgList[i].Type);
1201 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1205 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1208 /// ::= '{' TypeRec (',' TypeRec)* '}'
1209 /// ::= '<' '{' '}' '>'
1210 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1211 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1212 assert(Lex.getKind() == lltok::lbrace);
1213 Lex.Lex(); // Consume the '{'
1215 if (EatIfPresent(lltok::rbrace)) {
1216 Result = StructType::get(std::vector<const Type*>(), Packed);
1220 std::vector<PATypeHolder> ParamsList;
1221 if (ParseTypeRec(Result)) return true;
1222 ParamsList.push_back(Result);
1224 while (EatIfPresent(lltok::comma)) {
1225 if (ParseTypeRec(Result)) return true;
1226 ParamsList.push_back(Result);
1229 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1232 std::vector<const Type*> ParamsListTy;
1233 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1234 ParamsListTy.push_back(ParamsList[i].get());
1235 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1239 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1240 /// token has already been consumed.
1242 /// ::= '[' APSINTVAL 'x' Types ']'
1243 /// ::= '<' APSINTVAL 'x' Types '>'
1244 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1245 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1246 Lex.getAPSIntVal().getBitWidth() > 64)
1247 return TokError("expected number in address space");
1249 LocTy SizeLoc = Lex.getLoc();
1250 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1253 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1256 LocTy TypeLoc = Lex.getLoc();
1257 PATypeHolder EltTy(Type::VoidTy);
1258 if (ParseTypeRec(EltTy)) return true;
1260 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1261 "expected end of sequential type"))
1266 return Error(SizeLoc, "zero element vector is illegal");
1267 if ((unsigned)Size != Size)
1268 return Error(SizeLoc, "size too large for vector");
1269 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1270 return Error(TypeLoc, "vector element type must be fp or integer");
1271 Result = VectorType::get(EltTy, unsigned(Size));
1273 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1274 return Error(TypeLoc, "invalid array element type");
1275 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1280 //===----------------------------------------------------------------------===//
1281 // Function Semantic Analysis.
1282 //===----------------------------------------------------------------------===//
1284 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1287 // Insert unnamed arguments into the NumberedVals list.
1288 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1291 NumberedVals.push_back(AI);
1294 LLParser::PerFunctionState::~PerFunctionState() {
1295 // If there were any forward referenced non-basicblock values, delete them.
1296 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1297 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1298 if (!isa<BasicBlock>(I->second.first)) {
1299 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1301 delete I->second.first;
1302 I->second.first = 0;
1305 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1306 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1307 if (!isa<BasicBlock>(I->second.first)) {
1308 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1310 delete I->second.first;
1311 I->second.first = 0;
1315 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1316 if (!ForwardRefVals.empty())
1317 return P.Error(ForwardRefVals.begin()->second.second,
1318 "use of undefined value '%" + ForwardRefVals.begin()->first +
1320 if (!ForwardRefValIDs.empty())
1321 return P.Error(ForwardRefValIDs.begin()->second.second,
1322 "use of undefined value '%" +
1323 utostr(ForwardRefValIDs.begin()->first) + "'");
1328 /// GetVal - Get a value with the specified name or ID, creating a
1329 /// forward reference record if needed. This can return null if the value
1330 /// exists but does not have the right type.
1331 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1332 const Type *Ty, LocTy Loc) {
1333 // Look this name up in the normal function symbol table.
1334 Value *Val = F.getValueSymbolTable().lookup(Name);
1336 // If this is a forward reference for the value, see if we already created a
1337 // forward ref record.
1339 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1340 I = ForwardRefVals.find(Name);
1341 if (I != ForwardRefVals.end())
1342 Val = I->second.first;
1345 // If we have the value in the symbol table or fwd-ref table, return it.
1347 if (Val->getType() == Ty) return Val;
1348 if (Ty == Type::LabelTy)
1349 P.Error(Loc, "'%" + Name + "' is not a basic block");
1351 P.Error(Loc, "'%" + Name + "' defined with type '" +
1352 Val->getType()->getDescription() + "'");
1356 // Don't make placeholders with invalid type.
1357 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1358 P.Error(Loc, "invalid use of a non-first-class type");
1362 // Otherwise, create a new forward reference for this value and remember it.
1364 if (Ty == Type::LabelTy)
1365 FwdVal = BasicBlock::Create(Name, &F);
1367 FwdVal = new Argument(Ty, Name);
1369 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1373 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1375 // Look this name up in the normal function symbol table.
1376 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1378 // If this is a forward reference for the value, see if we already created a
1379 // forward ref record.
1381 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1382 I = ForwardRefValIDs.find(ID);
1383 if (I != ForwardRefValIDs.end())
1384 Val = I->second.first;
1387 // If we have the value in the symbol table or fwd-ref table, return it.
1389 if (Val->getType() == Ty) return Val;
1390 if (Ty == Type::LabelTy)
1391 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1393 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1394 Val->getType()->getDescription() + "'");
1398 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1399 P.Error(Loc, "invalid use of a non-first-class type");
1403 // Otherwise, create a new forward reference for this value and remember it.
1405 if (Ty == Type::LabelTy)
1406 FwdVal = BasicBlock::Create("", &F);
1408 FwdVal = new Argument(Ty);
1410 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1414 /// SetInstName - After an instruction is parsed and inserted into its
1415 /// basic block, this installs its name.
1416 bool LLParser::PerFunctionState::SetInstName(int NameID,
1417 const std::string &NameStr,
1418 LocTy NameLoc, Instruction *Inst) {
1419 // If this instruction has void type, it cannot have a name or ID specified.
1420 if (Inst->getType() == Type::VoidTy) {
1421 if (NameID != -1 || !NameStr.empty())
1422 return P.Error(NameLoc, "instructions returning void cannot have a name");
1426 // If this was a numbered instruction, verify that the instruction is the
1427 // expected value and resolve any forward references.
1428 if (NameStr.empty()) {
1429 // If neither a name nor an ID was specified, just use the next ID.
1431 NameID = NumberedVals.size();
1433 if (unsigned(NameID) != NumberedVals.size())
1434 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1435 utostr(NumberedVals.size()) + "'");
1437 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1438 ForwardRefValIDs.find(NameID);
1439 if (FI != ForwardRefValIDs.end()) {
1440 if (FI->second.first->getType() != Inst->getType())
1441 return P.Error(NameLoc, "instruction forward referenced with type '" +
1442 FI->second.first->getType()->getDescription() + "'");
1443 FI->second.first->replaceAllUsesWith(Inst);
1444 ForwardRefValIDs.erase(FI);
1447 NumberedVals.push_back(Inst);
1451 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1452 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1453 FI = ForwardRefVals.find(NameStr);
1454 if (FI != ForwardRefVals.end()) {
1455 if (FI->second.first->getType() != Inst->getType())
1456 return P.Error(NameLoc, "instruction forward referenced with type '" +
1457 FI->second.first->getType()->getDescription() + "'");
1458 FI->second.first->replaceAllUsesWith(Inst);
1459 ForwardRefVals.erase(FI);
1462 // Set the name on the instruction.
1463 Inst->setName(NameStr);
1465 if (Inst->getNameStr() != NameStr)
1466 return P.Error(NameLoc, "multiple definition of local value named '" +
1471 /// GetBB - Get a basic block with the specified name or ID, creating a
1472 /// forward reference record if needed.
1473 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1475 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1478 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1479 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1482 /// DefineBB - Define the specified basic block, which is either named or
1483 /// unnamed. If there is an error, this returns null otherwise it returns
1484 /// the block being defined.
1485 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1489 BB = GetBB(NumberedVals.size(), Loc);
1491 BB = GetBB(Name, Loc);
1492 if (BB == 0) return 0; // Already diagnosed error.
1494 // Move the block to the end of the function. Forward ref'd blocks are
1495 // inserted wherever they happen to be referenced.
1496 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1498 // Remove the block from forward ref sets.
1500 ForwardRefValIDs.erase(NumberedVals.size());
1501 NumberedVals.push_back(BB);
1503 // BB forward references are already in the function symbol table.
1504 ForwardRefVals.erase(Name);
1510 //===----------------------------------------------------------------------===//
1512 //===----------------------------------------------------------------------===//
1514 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1515 /// type implied. For example, if we parse "4" we don't know what integer type
1516 /// it has. The value will later be combined with its type and checked for
1518 bool LLParser::ParseValID(ValID &ID) {
1519 ID.Loc = Lex.getLoc();
1520 switch (Lex.getKind()) {
1521 default: return TokError("expected value token");
1522 case lltok::GlobalID: // @42
1523 ID.UIntVal = Lex.getUIntVal();
1524 ID.Kind = ValID::t_GlobalID;
1526 case lltok::GlobalVar: // @foo
1527 ID.StrVal = Lex.getStrVal();
1528 ID.Kind = ValID::t_GlobalName;
1530 case lltok::LocalVarID: // %42
1531 ID.UIntVal = Lex.getUIntVal();
1532 ID.Kind = ValID::t_LocalID;
1534 case lltok::LocalVar: // %foo
1535 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1536 ID.StrVal = Lex.getStrVal();
1537 ID.Kind = ValID::t_LocalName;
1540 ID.APSIntVal = Lex.getAPSIntVal();
1541 ID.Kind = ValID::t_APSInt;
1543 case lltok::APFloat:
1544 ID.APFloatVal = Lex.getAPFloatVal();
1545 ID.Kind = ValID::t_APFloat;
1547 case lltok::kw_true:
1548 ID.ConstantVal = ConstantInt::getTrue();
1549 ID.Kind = ValID::t_Constant;
1551 case lltok::kw_false:
1552 ID.ConstantVal = ConstantInt::getFalse();
1553 ID.Kind = ValID::t_Constant;
1555 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1556 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1557 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1559 case lltok::lbrace: {
1560 // ValID ::= '{' ConstVector '}'
1562 SmallVector<Constant*, 16> Elts;
1563 if (ParseGlobalValueVector(Elts) ||
1564 ParseToken(lltok::rbrace, "expected end of struct constant"))
1567 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1568 ID.Kind = ValID::t_Constant;
1572 // ValID ::= '<' ConstVector '>' --> Vector.
1573 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1575 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1577 SmallVector<Constant*, 16> Elts;
1578 LocTy FirstEltLoc = Lex.getLoc();
1579 if (ParseGlobalValueVector(Elts) ||
1581 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1582 ParseToken(lltok::greater, "expected end of constant"))
1585 if (isPackedStruct) {
1586 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1587 ID.Kind = ValID::t_Constant;
1592 return Error(ID.Loc, "constant vector must not be empty");
1594 if (!Elts[0]->getType()->isInteger() &&
1595 !Elts[0]->getType()->isFloatingPoint())
1596 return Error(FirstEltLoc,
1597 "vector elements must have integer or floating point type");
1599 // Verify that all the vector elements have the same type.
1600 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1601 if (Elts[i]->getType() != Elts[0]->getType())
1602 return Error(FirstEltLoc,
1603 "vector element #" + utostr(i) +
1604 " is not of type '" + Elts[0]->getType()->getDescription());
1606 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1607 ID.Kind = ValID::t_Constant;
1610 case lltok::lsquare: { // Array Constant
1612 SmallVector<Constant*, 16> Elts;
1613 LocTy FirstEltLoc = Lex.getLoc();
1614 if (ParseGlobalValueVector(Elts) ||
1615 ParseToken(lltok::rsquare, "expected end of array constant"))
1618 // Handle empty element.
1620 // Use undef instead of an array because it's inconvenient to determine
1621 // the element type at this point, there being no elements to examine.
1622 ID.Kind = ValID::t_EmptyArray;
1626 if (!Elts[0]->getType()->isFirstClassType())
1627 return Error(FirstEltLoc, "invalid array element type: " +
1628 Elts[0]->getType()->getDescription());
1630 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1632 // Verify all elements are correct type!
1633 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1634 if (Elts[i]->getType() != Elts[0]->getType())
1635 return Error(FirstEltLoc,
1636 "array element #" + utostr(i) +
1637 " is not of type '" +Elts[0]->getType()->getDescription());
1640 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1641 ID.Kind = ValID::t_Constant;
1644 case lltok::kw_c: // c "foo"
1646 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1647 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1648 ID.Kind = ValID::t_Constant;
1651 case lltok::kw_asm: {
1652 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1655 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1656 ParseStringConstant(ID.StrVal) ||
1657 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1658 ParseToken(lltok::StringConstant, "expected constraint string"))
1660 ID.StrVal2 = Lex.getStrVal();
1661 ID.UIntVal = HasSideEffect;
1662 ID.Kind = ValID::t_InlineAsm;
1666 case lltok::kw_trunc:
1667 case lltok::kw_zext:
1668 case lltok::kw_sext:
1669 case lltok::kw_fptrunc:
1670 case lltok::kw_fpext:
1671 case lltok::kw_bitcast:
1672 case lltok::kw_uitofp:
1673 case lltok::kw_sitofp:
1674 case lltok::kw_fptoui:
1675 case lltok::kw_fptosi:
1676 case lltok::kw_inttoptr:
1677 case lltok::kw_ptrtoint: {
1678 unsigned Opc = Lex.getUIntVal();
1679 PATypeHolder DestTy(Type::VoidTy);
1682 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1683 ParseGlobalTypeAndValue(SrcVal) ||
1684 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1685 ParseType(DestTy) ||
1686 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1688 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1689 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1690 SrcVal->getType()->getDescription() + "' to '" +
1691 DestTy->getDescription() + "'");
1692 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1694 ID.Kind = ValID::t_Constant;
1697 case lltok::kw_extractvalue: {
1700 SmallVector<unsigned, 4> Indices;
1701 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1702 ParseGlobalTypeAndValue(Val) ||
1703 ParseIndexList(Indices) ||
1704 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1706 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1707 return Error(ID.Loc, "extractvalue operand must be array or struct");
1708 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1710 return Error(ID.Loc, "invalid indices for extractvalue");
1711 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1712 &Indices[0], Indices.size());
1713 ID.Kind = ValID::t_Constant;
1716 case lltok::kw_insertvalue: {
1718 Constant *Val0, *Val1;
1719 SmallVector<unsigned, 4> Indices;
1720 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1721 ParseGlobalTypeAndValue(Val0) ||
1722 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1723 ParseGlobalTypeAndValue(Val1) ||
1724 ParseIndexList(Indices) ||
1725 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1727 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1728 return Error(ID.Loc, "extractvalue operand must be array or struct");
1729 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1731 return Error(ID.Loc, "invalid indices for insertvalue");
1732 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1733 &Indices[0], Indices.size());
1734 ID.Kind = ValID::t_Constant;
1737 case lltok::kw_icmp:
1738 case lltok::kw_fcmp:
1739 case lltok::kw_vicmp:
1740 case lltok::kw_vfcmp: {
1741 unsigned PredVal, Opc = Lex.getUIntVal();
1742 Constant *Val0, *Val1;
1744 if (ParseCmpPredicate(PredVal, Opc) ||
1745 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1746 ParseGlobalTypeAndValue(Val0) ||
1747 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1748 ParseGlobalTypeAndValue(Val1) ||
1749 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1752 if (Val0->getType() != Val1->getType())
1753 return Error(ID.Loc, "compare operands must have the same type");
1755 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1757 if (Opc == Instruction::FCmp) {
1758 if (!Val0->getType()->isFPOrFPVector())
1759 return Error(ID.Loc, "fcmp requires floating point operands");
1760 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1761 } else if (Opc == Instruction::ICmp) {
1762 if (!Val0->getType()->isIntOrIntVector() &&
1763 !isa<PointerType>(Val0->getType()))
1764 return Error(ID.Loc, "icmp requires pointer or integer operands");
1765 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1766 } else if (Opc == Instruction::VFCmp) {
1767 // FIXME: REMOVE VFCMP Support
1768 if (!Val0->getType()->isFPOrFPVector() ||
1769 !isa<VectorType>(Val0->getType()))
1770 return Error(ID.Loc, "vfcmp requires vector floating point operands");
1771 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1772 } else if (Opc == Instruction::VICmp) {
1773 // FIXME: REMOVE VICMP Support
1774 if (!Val0->getType()->isIntOrIntVector() ||
1775 !isa<VectorType>(Val0->getType()))
1776 return Error(ID.Loc, "vicmp requires vector floating point operands");
1777 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1779 ID.Kind = ValID::t_Constant;
1783 // Binary Operators.
1787 case lltok::kw_udiv:
1788 case lltok::kw_sdiv:
1789 case lltok::kw_fdiv:
1790 case lltok::kw_urem:
1791 case lltok::kw_srem:
1792 case lltok::kw_frem: {
1793 unsigned Opc = Lex.getUIntVal();
1794 Constant *Val0, *Val1;
1796 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1797 ParseGlobalTypeAndValue(Val0) ||
1798 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1799 ParseGlobalTypeAndValue(Val1) ||
1800 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1802 if (Val0->getType() != Val1->getType())
1803 return Error(ID.Loc, "operands of constexpr must have same type");
1804 if (!Val0->getType()->isIntOrIntVector() &&
1805 !Val0->getType()->isFPOrFPVector())
1806 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1807 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1808 ID.Kind = ValID::t_Constant;
1812 // Logical Operations
1814 case lltok::kw_lshr:
1815 case lltok::kw_ashr:
1818 case lltok::kw_xor: {
1819 unsigned Opc = Lex.getUIntVal();
1820 Constant *Val0, *Val1;
1822 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1823 ParseGlobalTypeAndValue(Val0) ||
1824 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1825 ParseGlobalTypeAndValue(Val1) ||
1826 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1828 if (Val0->getType() != Val1->getType())
1829 return Error(ID.Loc, "operands of constexpr must have same type");
1830 if (!Val0->getType()->isIntOrIntVector())
1831 return Error(ID.Loc,
1832 "constexpr requires integer or integer vector operands");
1833 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1834 ID.Kind = ValID::t_Constant;
1838 case lltok::kw_getelementptr:
1839 case lltok::kw_shufflevector:
1840 case lltok::kw_insertelement:
1841 case lltok::kw_extractelement:
1842 case lltok::kw_select: {
1843 unsigned Opc = Lex.getUIntVal();
1844 SmallVector<Constant*, 16> Elts;
1846 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1847 ParseGlobalValueVector(Elts) ||
1848 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1851 if (Opc == Instruction::GetElementPtr) {
1852 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1853 return Error(ID.Loc, "getelementptr requires pointer operand");
1855 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1856 (Value**)&Elts[1], Elts.size()-1))
1857 return Error(ID.Loc, "invalid indices for getelementptr");
1858 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1859 &Elts[1], Elts.size()-1);
1860 } else if (Opc == Instruction::Select) {
1861 if (Elts.size() != 3)
1862 return Error(ID.Loc, "expected three operands to select");
1863 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1865 return Error(ID.Loc, Reason);
1866 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1867 } else if (Opc == Instruction::ShuffleVector) {
1868 if (Elts.size() != 3)
1869 return Error(ID.Loc, "expected three operands to shufflevector");
1870 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1871 return Error(ID.Loc, "invalid operands to shufflevector");
1872 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1873 } else if (Opc == Instruction::ExtractElement) {
1874 if (Elts.size() != 2)
1875 return Error(ID.Loc, "expected two operands to extractelement");
1876 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1877 return Error(ID.Loc, "invalid extractelement operands");
1878 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1880 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1881 if (Elts.size() != 3)
1882 return Error(ID.Loc, "expected three operands to insertelement");
1883 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1884 return Error(ID.Loc, "invalid insertelement operands");
1885 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1888 ID.Kind = ValID::t_Constant;
1897 /// ParseGlobalValue - Parse a global value with the specified type.
1898 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1901 return ParseValID(ID) ||
1902 ConvertGlobalValIDToValue(Ty, ID, V);
1905 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1907 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1909 if (isa<FunctionType>(Ty))
1910 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1913 default: assert(0 && "Unknown ValID!");
1914 case ValID::t_LocalID:
1915 case ValID::t_LocalName:
1916 return Error(ID.Loc, "invalid use of function-local name");
1917 case ValID::t_InlineAsm:
1918 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1919 case ValID::t_GlobalName:
1920 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1922 case ValID::t_GlobalID:
1923 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1925 case ValID::t_APSInt:
1926 if (!isa<IntegerType>(Ty))
1927 return Error(ID.Loc, "integer constant must have integer type");
1928 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1929 V = ConstantInt::get(ID.APSIntVal);
1931 case ValID::t_APFloat:
1932 if (!Ty->isFloatingPoint() ||
1933 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1934 return Error(ID.Loc, "floating point constant invalid for type");
1936 // The lexer has no type info, so builds all float and double FP constants
1937 // as double. Fix this here. Long double does not need this.
1938 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1939 Ty == Type::FloatTy) {
1941 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1944 V = ConstantFP::get(ID.APFloatVal);
1946 if (V->getType() != Ty)
1947 return Error(ID.Loc, "floating point constant does not have type '" +
1948 Ty->getDescription() + "'");
1952 if (!isa<PointerType>(Ty))
1953 return Error(ID.Loc, "null must be a pointer type");
1954 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1956 case ValID::t_Undef:
1957 // FIXME: LabelTy should not be a first-class type.
1958 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
1959 !isa<OpaqueType>(Ty))
1960 return Error(ID.Loc, "invalid type for undef constant");
1961 V = UndefValue::get(Ty);
1963 case ValID::t_EmptyArray:
1964 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
1965 return Error(ID.Loc, "invalid empty array initializer");
1966 V = UndefValue::get(Ty);
1969 // FIXME: LabelTy should not be a first-class type.
1970 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
1971 return Error(ID.Loc, "invalid type for null constant");
1972 V = Constant::getNullValue(Ty);
1974 case ValID::t_Constant:
1975 if (ID.ConstantVal->getType() != Ty)
1976 return Error(ID.Loc, "constant expression type mismatch");
1982 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
1983 PATypeHolder Type(Type::VoidTy);
1984 return ParseType(Type) ||
1985 ParseGlobalValue(Type, V);
1988 /// ParseGlobalValueVector
1990 /// ::= TypeAndValue (',' TypeAndValue)*
1991 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
1993 if (Lex.getKind() == lltok::rbrace ||
1994 Lex.getKind() == lltok::rsquare ||
1995 Lex.getKind() == lltok::greater ||
1996 Lex.getKind() == lltok::rparen)
2000 if (ParseGlobalTypeAndValue(C)) return true;
2003 while (EatIfPresent(lltok::comma)) {
2004 if (ParseGlobalTypeAndValue(C)) return true;
2012 //===----------------------------------------------------------------------===//
2013 // Function Parsing.
2014 //===----------------------------------------------------------------------===//
2016 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2017 PerFunctionState &PFS) {
2018 if (ID.Kind == ValID::t_LocalID)
2019 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2020 else if (ID.Kind == ValID::t_LocalName)
2021 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2022 else if (ID.Kind == ValID::t_InlineAsm) {
2023 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2024 const FunctionType *FTy =
2025 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2026 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2027 return Error(ID.Loc, "invalid type for inline asm constraint string");
2028 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2032 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2040 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2043 return ParseValID(ID) ||
2044 ConvertValIDToValue(Ty, ID, V, PFS);
2047 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2048 PATypeHolder T(Type::VoidTy);
2049 return ParseType(T) ||
2050 ParseValue(T, V, PFS);
2054 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2055 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2056 /// OptionalAlign OptGC
2057 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2058 // Parse the linkage.
2059 LocTy LinkageLoc = Lex.getLoc();
2062 unsigned Visibility, CC, RetAttrs;
2063 PATypeHolder RetType(Type::VoidTy);
2064 LocTy RetTypeLoc = Lex.getLoc();
2065 if (ParseOptionalLinkage(Linkage) ||
2066 ParseOptionalVisibility(Visibility) ||
2067 ParseOptionalCallingConv(CC) ||
2068 ParseOptionalAttrs(RetAttrs, 1) ||
2069 ParseType(RetType, RetTypeLoc))
2072 // Verify that the linkage is ok.
2073 switch ((GlobalValue::LinkageTypes)Linkage) {
2074 case GlobalValue::ExternalLinkage:
2075 break; // always ok.
2076 case GlobalValue::DLLImportLinkage:
2077 case GlobalValue::ExternalWeakLinkage:
2079 return Error(LinkageLoc, "invalid linkage for function definition");
2081 case GlobalValue::PrivateLinkage:
2082 case GlobalValue::InternalLinkage:
2083 case GlobalValue::LinkOnceLinkage:
2084 case GlobalValue::WeakLinkage:
2085 case GlobalValue::DLLExportLinkage:
2087 return Error(LinkageLoc, "invalid linkage for function declaration");
2089 case GlobalValue::AppendingLinkage:
2090 case GlobalValue::GhostLinkage:
2091 case GlobalValue::CommonLinkage:
2092 return Error(LinkageLoc, "invalid function linkage type");
2095 if (!FunctionType::isValidReturnType(RetType) ||
2096 isa<OpaqueType>(RetType))
2097 return Error(RetTypeLoc, "invalid function return type");
2099 LocTy NameLoc = Lex.getLoc();
2101 std::string FunctionName;
2102 if (Lex.getKind() == lltok::GlobalVar) {
2103 FunctionName = Lex.getStrVal();
2104 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2105 unsigned NameID = Lex.getUIntVal();
2107 if (NameID != NumberedVals.size())
2108 return TokError("function expected to be numbered '%" +
2109 utostr(NumberedVals.size()) + "'");
2111 return TokError("expected function name");
2116 if (Lex.getKind() != lltok::lparen)
2117 return TokError("expected '(' in function argument list");
2119 std::vector<ArgInfo> ArgList;
2122 std::string Section;
2126 if (ParseArgumentList(ArgList, isVarArg, false) ||
2127 ParseOptionalAttrs(FuncAttrs, 2) ||
2128 (EatIfPresent(lltok::kw_section) &&
2129 ParseStringConstant(Section)) ||
2130 ParseOptionalAlignment(Alignment) ||
2131 (EatIfPresent(lltok::kw_gc) &&
2132 ParseStringConstant(GC)))
2135 // If the alignment was parsed as an attribute, move to the alignment field.
2136 if (FuncAttrs & Attribute::Alignment) {
2137 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2138 FuncAttrs &= ~Attribute::Alignment;
2141 // Okay, if we got here, the function is syntactically valid. Convert types
2142 // and do semantic checks.
2143 std::vector<const Type*> ParamTypeList;
2144 SmallVector<AttributeWithIndex, 8> Attrs;
2145 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2147 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2148 if (FuncAttrs & ObsoleteFuncAttrs) {
2149 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2150 FuncAttrs &= ~ObsoleteFuncAttrs;
2153 if (RetAttrs != Attribute::None)
2154 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2156 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2157 ParamTypeList.push_back(ArgList[i].Type);
2158 if (ArgList[i].Attrs != Attribute::None)
2159 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2162 if (FuncAttrs != Attribute::None)
2163 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2165 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2167 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2168 const PointerType *PFT = PointerType::getUnqual(FT);
2171 if (!FunctionName.empty()) {
2172 // If this was a definition of a forward reference, remove the definition
2173 // from the forward reference table and fill in the forward ref.
2174 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2175 ForwardRefVals.find(FunctionName);
2176 if (FRVI != ForwardRefVals.end()) {
2177 Fn = M->getFunction(FunctionName);
2178 ForwardRefVals.erase(FRVI);
2179 } else if ((Fn = M->getFunction(FunctionName))) {
2180 // If this function already exists in the symbol table, then it is
2181 // multiply defined. We accept a few cases for old backwards compat.
2182 // FIXME: Remove this stuff for LLVM 3.0.
2183 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2184 (!Fn->isDeclaration() && isDefine)) {
2185 // If the redefinition has different type or different attributes,
2186 // reject it. If both have bodies, reject it.
2187 return Error(NameLoc, "invalid redefinition of function '" +
2188 FunctionName + "'");
2189 } else if (Fn->isDeclaration()) {
2190 // Make sure to strip off any argument names so we can't get conflicts.
2191 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2197 } else if (FunctionName.empty()) {
2198 // If this is a definition of a forward referenced function, make sure the
2200 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2201 = ForwardRefValIDs.find(NumberedVals.size());
2202 if (I != ForwardRefValIDs.end()) {
2203 Fn = cast<Function>(I->second.first);
2204 if (Fn->getType() != PFT)
2205 return Error(NameLoc, "type of definition and forward reference of '@" +
2206 utostr(NumberedVals.size()) +"' disagree");
2207 ForwardRefValIDs.erase(I);
2212 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2213 else // Move the forward-reference to the correct spot in the module.
2214 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2216 if (FunctionName.empty())
2217 NumberedVals.push_back(Fn);
2219 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2220 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2221 Fn->setCallingConv(CC);
2222 Fn->setAttributes(PAL);
2223 Fn->setAlignment(Alignment);
2224 Fn->setSection(Section);
2225 if (!GC.empty()) Fn->setGC(GC.c_str());
2227 // Add all of the arguments we parsed to the function.
2228 Function::arg_iterator ArgIt = Fn->arg_begin();
2229 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2230 // If the argument has a name, insert it into the argument symbol table.
2231 if (ArgList[i].Name.empty()) continue;
2233 // Set the name, if it conflicted, it will be auto-renamed.
2234 ArgIt->setName(ArgList[i].Name);
2236 if (ArgIt->getNameStr() != ArgList[i].Name)
2237 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2238 ArgList[i].Name + "'");
2245 /// ParseFunctionBody
2246 /// ::= '{' BasicBlock+ '}'
2247 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2249 bool LLParser::ParseFunctionBody(Function &Fn) {
2250 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2251 return TokError("expected '{' in function body");
2252 Lex.Lex(); // eat the {.
2254 PerFunctionState PFS(*this, Fn);
2256 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2257 if (ParseBasicBlock(PFS)) return true;
2262 // Verify function is ok.
2263 return PFS.VerifyFunctionComplete();
2267 /// ::= LabelStr? Instruction*
2268 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2269 // If this basic block starts out with a name, remember it.
2271 LocTy NameLoc = Lex.getLoc();
2272 if (Lex.getKind() == lltok::LabelStr) {
2273 Name = Lex.getStrVal();
2277 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2278 if (BB == 0) return true;
2280 std::string NameStr;
2282 // Parse the instructions in this block until we get a terminator.
2285 // This instruction may have three possibilities for a name: a) none
2286 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2287 LocTy NameLoc = Lex.getLoc();
2291 if (Lex.getKind() == lltok::LocalVarID) {
2292 NameID = Lex.getUIntVal();
2294 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2296 } else if (Lex.getKind() == lltok::LocalVar ||
2297 // FIXME: REMOVE IN LLVM 3.0
2298 Lex.getKind() == lltok::StringConstant) {
2299 NameStr = Lex.getStrVal();
2301 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2305 if (ParseInstruction(Inst, BB, PFS)) return true;
2307 BB->getInstList().push_back(Inst);
2309 // Set the name on the instruction.
2310 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2311 } while (!isa<TerminatorInst>(Inst));
2316 //===----------------------------------------------------------------------===//
2317 // Instruction Parsing.
2318 //===----------------------------------------------------------------------===//
2320 /// ParseInstruction - Parse one of the many different instructions.
2322 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2323 PerFunctionState &PFS) {
2324 lltok::Kind Token = Lex.getKind();
2325 if (Token == lltok::Eof)
2326 return TokError("found end of file when expecting more instructions");
2327 LocTy Loc = Lex.getLoc();
2328 unsigned KeywordVal = Lex.getUIntVal();
2329 Lex.Lex(); // Eat the keyword.
2332 default: return Error(Loc, "expected instruction opcode");
2333 // Terminator Instructions.
2334 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2335 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2336 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2337 case lltok::kw_br: return ParseBr(Inst, PFS);
2338 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2339 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2340 // Binary Operators.
2343 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2345 case lltok::kw_udiv:
2346 case lltok::kw_sdiv:
2347 case lltok::kw_urem:
2348 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2349 case lltok::kw_fdiv:
2350 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2352 case lltok::kw_lshr:
2353 case lltok::kw_ashr:
2356 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2357 case lltok::kw_icmp:
2358 case lltok::kw_fcmp:
2359 case lltok::kw_vicmp:
2360 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
2362 case lltok::kw_trunc:
2363 case lltok::kw_zext:
2364 case lltok::kw_sext:
2365 case lltok::kw_fptrunc:
2366 case lltok::kw_fpext:
2367 case lltok::kw_bitcast:
2368 case lltok::kw_uitofp:
2369 case lltok::kw_sitofp:
2370 case lltok::kw_fptoui:
2371 case lltok::kw_fptosi:
2372 case lltok::kw_inttoptr:
2373 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2375 case lltok::kw_select: return ParseSelect(Inst, PFS);
2376 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2377 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2378 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2379 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2380 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2381 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2382 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2384 case lltok::kw_alloca:
2385 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2386 case lltok::kw_free: return ParseFree(Inst, PFS);
2387 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2388 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2389 case lltok::kw_volatile:
2390 if (EatIfPresent(lltok::kw_load))
2391 return ParseLoad(Inst, PFS, true);
2392 else if (EatIfPresent(lltok::kw_store))
2393 return ParseStore(Inst, PFS, true);
2395 return TokError("expected 'load' or 'store'");
2396 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2397 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2398 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2399 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2403 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2404 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2405 // FIXME: REMOVE vicmp/vfcmp!
2406 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2407 switch (Lex.getKind()) {
2408 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2409 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2410 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2411 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2412 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2413 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2414 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2415 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2416 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2417 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2418 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2419 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2420 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2421 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2422 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2423 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2424 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2427 switch (Lex.getKind()) {
2428 default: TokError("expected icmp predicate (e.g. 'eq')");
2429 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2430 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2431 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2432 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2433 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2434 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2435 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2436 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2437 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2438 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2445 //===----------------------------------------------------------------------===//
2446 // Terminator Instructions.
2447 //===----------------------------------------------------------------------===//
2449 /// ParseRet - Parse a return instruction.
2451 /// ::= 'ret' TypeAndValue
2452 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2453 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2454 PerFunctionState &PFS) {
2455 PATypeHolder Ty(Type::VoidTy);
2456 if (ParseType(Ty)) return true;
2458 if (Ty == Type::VoidTy) {
2459 Inst = ReturnInst::Create();
2464 if (ParseValue(Ty, RV, PFS)) return true;
2466 // The normal case is one return value.
2467 if (Lex.getKind() == lltok::comma) {
2468 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2469 // of 'ret {i32,i32} {i32 1, i32 2}'
2470 SmallVector<Value*, 8> RVs;
2473 while (EatIfPresent(lltok::comma)) {
2474 if (ParseTypeAndValue(RV, PFS)) return true;
2478 RV = UndefValue::get(PFS.getFunction().getReturnType());
2479 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2480 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2481 BB->getInstList().push_back(I);
2485 Inst = ReturnInst::Create(RV);
2491 /// ::= 'br' TypeAndValue
2492 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2493 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2495 Value *Op0, *Op1, *Op2;
2496 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2498 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2499 Inst = BranchInst::Create(BB);
2503 if (Op0->getType() != Type::Int1Ty)
2504 return Error(Loc, "branch condition must have 'i1' type");
2506 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2507 ParseTypeAndValue(Op1, Loc, PFS) ||
2508 ParseToken(lltok::comma, "expected ',' after true destination") ||
2509 ParseTypeAndValue(Op2, Loc2, PFS))
2512 if (!isa<BasicBlock>(Op1))
2513 return Error(Loc, "true destination of branch must be a basic block");
2514 if (!isa<BasicBlock>(Op2))
2515 return Error(Loc2, "true destination of branch must be a basic block");
2517 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2523 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2525 /// ::= (TypeAndValue ',' TypeAndValue)*
2526 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2527 LocTy CondLoc, BBLoc;
2528 Value *Cond, *DefaultBB;
2529 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2530 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2531 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2532 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2535 if (!isa<IntegerType>(Cond->getType()))
2536 return Error(CondLoc, "switch condition must have integer type");
2537 if (!isa<BasicBlock>(DefaultBB))
2538 return Error(BBLoc, "default destination must be a basic block");
2540 // Parse the jump table pairs.
2541 SmallPtrSet<Value*, 32> SeenCases;
2542 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2543 while (Lex.getKind() != lltok::rsquare) {
2544 Value *Constant, *DestBB;
2546 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2547 ParseToken(lltok::comma, "expected ',' after case value") ||
2548 ParseTypeAndValue(DestBB, BBLoc, PFS))
2551 if (!SeenCases.insert(Constant))
2552 return Error(CondLoc, "duplicate case value in switch");
2553 if (!isa<ConstantInt>(Constant))
2554 return Error(CondLoc, "case value is not a constant integer");
2555 if (!isa<BasicBlock>(DestBB))
2556 return Error(BBLoc, "case destination is not a basic block");
2558 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2559 cast<BasicBlock>(DestBB)));
2562 Lex.Lex(); // Eat the ']'.
2564 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2566 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2567 SI->addCase(Table[i].first, Table[i].second);
2573 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2574 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2575 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2576 LocTy CallLoc = Lex.getLoc();
2577 unsigned CC, RetAttrs, FnAttrs;
2578 PATypeHolder RetType(Type::VoidTy);
2581 SmallVector<ParamInfo, 16> ArgList;
2583 Value *NormalBB, *UnwindBB;
2584 if (ParseOptionalCallingConv(CC) ||
2585 ParseOptionalAttrs(RetAttrs, 1) ||
2586 ParseType(RetType, RetTypeLoc) ||
2587 ParseValID(CalleeID) ||
2588 ParseParameterList(ArgList, PFS) ||
2589 ParseOptionalAttrs(FnAttrs, 2) ||
2590 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2591 ParseTypeAndValue(NormalBB, PFS) ||
2592 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2593 ParseTypeAndValue(UnwindBB, PFS))
2596 if (!isa<BasicBlock>(NormalBB))
2597 return Error(CallLoc, "normal destination is not a basic block");
2598 if (!isa<BasicBlock>(UnwindBB))
2599 return Error(CallLoc, "unwind destination is not a basic block");
2601 // If RetType is a non-function pointer type, then this is the short syntax
2602 // for the call, which means that RetType is just the return type. Infer the
2603 // rest of the function argument types from the arguments that are present.
2604 const PointerType *PFTy = 0;
2605 const FunctionType *Ty = 0;
2606 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2607 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2608 // Pull out the types of all of the arguments...
2609 std::vector<const Type*> ParamTypes;
2610 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2611 ParamTypes.push_back(ArgList[i].V->getType());
2613 if (!FunctionType::isValidReturnType(RetType))
2614 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2616 Ty = FunctionType::get(RetType, ParamTypes, false);
2617 PFTy = PointerType::getUnqual(Ty);
2620 // Look up the callee.
2622 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2624 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2625 // function attributes.
2626 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2627 if (FnAttrs & ObsoleteFuncAttrs) {
2628 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2629 FnAttrs &= ~ObsoleteFuncAttrs;
2632 // Set up the Attributes for the function.
2633 SmallVector<AttributeWithIndex, 8> Attrs;
2634 if (RetAttrs != Attribute::None)
2635 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2637 SmallVector<Value*, 8> Args;
2639 // Loop through FunctionType's arguments and ensure they are specified
2640 // correctly. Also, gather any parameter attributes.
2641 FunctionType::param_iterator I = Ty->param_begin();
2642 FunctionType::param_iterator E = Ty->param_end();
2643 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2644 const Type *ExpectedTy = 0;
2647 } else if (!Ty->isVarArg()) {
2648 return Error(ArgList[i].Loc, "too many arguments specified");
2651 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2652 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2653 ExpectedTy->getDescription() + "'");
2654 Args.push_back(ArgList[i].V);
2655 if (ArgList[i].Attrs != Attribute::None)
2656 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2660 return Error(CallLoc, "not enough parameters specified for call");
2662 if (FnAttrs != Attribute::None)
2663 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2665 // Finish off the Attributes and check them
2666 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2668 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2669 cast<BasicBlock>(UnwindBB),
2670 Args.begin(), Args.end());
2671 II->setCallingConv(CC);
2672 II->setAttributes(PAL);
2679 //===----------------------------------------------------------------------===//
2680 // Binary Operators.
2681 //===----------------------------------------------------------------------===//
2684 /// ::= ArithmeticOps TypeAndValue ',' Value
2686 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2687 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2688 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2689 unsigned Opc, unsigned OperandType) {
2690 LocTy Loc; Value *LHS, *RHS;
2691 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2692 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2693 ParseValue(LHS->getType(), RHS, PFS))
2697 switch (OperandType) {
2698 default: assert(0 && "Unknown operand type!");
2699 case 0: // int or FP.
2700 Valid = LHS->getType()->isIntOrIntVector() ||
2701 LHS->getType()->isFPOrFPVector();
2703 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2704 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2708 return Error(Loc, "invalid operand type for instruction");
2710 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2715 /// ::= ArithmeticOps TypeAndValue ',' Value {
2716 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2718 LocTy Loc; Value *LHS, *RHS;
2719 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2720 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2721 ParseValue(LHS->getType(), RHS, PFS))
2724 if (!LHS->getType()->isIntOrIntVector())
2725 return Error(Loc,"instruction requires integer or integer vector operands");
2727 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2733 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2734 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2735 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2736 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2737 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2739 // Parse the integer/fp comparison predicate.
2743 if (ParseCmpPredicate(Pred, Opc) ||
2744 ParseTypeAndValue(LHS, Loc, PFS) ||
2745 ParseToken(lltok::comma, "expected ',' after compare value") ||
2746 ParseValue(LHS->getType(), RHS, PFS))
2749 if (Opc == Instruction::FCmp) {
2750 if (!LHS->getType()->isFPOrFPVector())
2751 return Error(Loc, "fcmp requires floating point operands");
2752 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2753 } else if (Opc == Instruction::ICmp) {
2754 if (!LHS->getType()->isIntOrIntVector() &&
2755 !isa<PointerType>(LHS->getType()))
2756 return Error(Loc, "icmp requires integer operands");
2757 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2758 } else if (Opc == Instruction::VFCmp) {
2759 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2760 return Error(Loc, "vfcmp requires vector floating point operands");
2761 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2762 } else if (Opc == Instruction::VICmp) {
2763 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2764 return Error(Loc, "vicmp requires vector floating point operands");
2765 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2770 //===----------------------------------------------------------------------===//
2771 // Other Instructions.
2772 //===----------------------------------------------------------------------===//
2776 /// ::= CastOpc TypeAndValue 'to' Type
2777 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2779 LocTy Loc; Value *Op;
2780 PATypeHolder DestTy(Type::VoidTy);
2781 if (ParseTypeAndValue(Op, Loc, PFS) ||
2782 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2786 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2787 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
2788 return Error(Loc, "invalid cast opcode for cast from '" +
2789 Op->getType()->getDescription() + "' to '" +
2790 DestTy->getDescription() + "'");
2792 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2797 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2798 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2800 Value *Op0, *Op1, *Op2;
2801 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2802 ParseToken(lltok::comma, "expected ',' after select condition") ||
2803 ParseTypeAndValue(Op1, PFS) ||
2804 ParseToken(lltok::comma, "expected ',' after select value") ||
2805 ParseTypeAndValue(Op2, PFS))
2808 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2809 return Error(Loc, Reason);
2811 Inst = SelectInst::Create(Op0, Op1, Op2);
2816 /// ::= 'va_arg' TypeAndValue ',' Type
2817 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2819 PATypeHolder EltTy(Type::VoidTy);
2821 if (ParseTypeAndValue(Op, PFS) ||
2822 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2823 ParseType(EltTy, TypeLoc))
2826 if (!EltTy->isFirstClassType())
2827 return Error(TypeLoc, "va_arg requires operand with first class type");
2829 Inst = new VAArgInst(Op, EltTy);
2833 /// ParseExtractElement
2834 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2835 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2838 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2839 ParseToken(lltok::comma, "expected ',' after extract value") ||
2840 ParseTypeAndValue(Op1, PFS))
2843 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2844 return Error(Loc, "invalid extractelement operands");
2846 Inst = new ExtractElementInst(Op0, Op1);
2850 /// ParseInsertElement
2851 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2852 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2854 Value *Op0, *Op1, *Op2;
2855 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2856 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2857 ParseTypeAndValue(Op1, PFS) ||
2858 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2859 ParseTypeAndValue(Op2, PFS))
2862 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2863 return Error(Loc, "invalid extractelement operands");
2865 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2869 /// ParseShuffleVector
2870 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2871 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2873 Value *Op0, *Op1, *Op2;
2874 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2875 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2876 ParseTypeAndValue(Op1, PFS) ||
2877 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2878 ParseTypeAndValue(Op2, PFS))
2881 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2882 return Error(Loc, "invalid extractelement operands");
2884 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2889 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2890 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2891 PATypeHolder Ty(Type::VoidTy);
2893 LocTy TypeLoc = Lex.getLoc();
2895 if (ParseType(Ty) ||
2896 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2897 ParseValue(Ty, Op0, PFS) ||
2898 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2899 ParseValue(Type::LabelTy, Op1, PFS) ||
2900 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2903 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2905 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2907 if (!EatIfPresent(lltok::comma))
2910 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2911 ParseValue(Ty, Op0, PFS) ||
2912 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2913 ParseValue(Type::LabelTy, Op1, PFS) ||
2914 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2918 if (!Ty->isFirstClassType())
2919 return Error(TypeLoc, "phi node must have first class type");
2921 PHINode *PN = PHINode::Create(Ty);
2922 PN->reserveOperandSpace(PHIVals.size());
2923 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2924 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2930 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2931 /// ParameterList OptionalAttrs
2932 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2934 unsigned CC, RetAttrs, FnAttrs;
2935 PATypeHolder RetType(Type::VoidTy);
2938 SmallVector<ParamInfo, 16> ArgList;
2939 LocTy CallLoc = Lex.getLoc();
2941 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2942 ParseOptionalCallingConv(CC) ||
2943 ParseOptionalAttrs(RetAttrs, 1) ||
2944 ParseType(RetType, RetTypeLoc) ||
2945 ParseValID(CalleeID) ||
2946 ParseParameterList(ArgList, PFS) ||
2947 ParseOptionalAttrs(FnAttrs, 2))
2950 // If RetType is a non-function pointer type, then this is the short syntax
2951 // for the call, which means that RetType is just the return type. Infer the
2952 // rest of the function argument types from the arguments that are present.
2953 const PointerType *PFTy = 0;
2954 const FunctionType *Ty = 0;
2955 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2956 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2957 // Pull out the types of all of the arguments...
2958 std::vector<const Type*> ParamTypes;
2959 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2960 ParamTypes.push_back(ArgList[i].V->getType());
2962 if (!FunctionType::isValidReturnType(RetType))
2963 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2965 Ty = FunctionType::get(RetType, ParamTypes, false);
2966 PFTy = PointerType::getUnqual(Ty);
2969 // Look up the callee.
2971 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2973 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2974 // function attributes.
2975 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2976 if (FnAttrs & ObsoleteFuncAttrs) {
2977 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2978 FnAttrs &= ~ObsoleteFuncAttrs;
2981 // Set up the Attributes for the function.
2982 SmallVector<AttributeWithIndex, 8> Attrs;
2983 if (RetAttrs != Attribute::None)
2984 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2986 SmallVector<Value*, 8> Args;
2988 // Loop through FunctionType's arguments and ensure they are specified
2989 // correctly. Also, gather any parameter attributes.
2990 FunctionType::param_iterator I = Ty->param_begin();
2991 FunctionType::param_iterator E = Ty->param_end();
2992 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2993 const Type *ExpectedTy = 0;
2996 } else if (!Ty->isVarArg()) {
2997 return Error(ArgList[i].Loc, "too many arguments specified");
3000 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3001 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3002 ExpectedTy->getDescription() + "'");
3003 Args.push_back(ArgList[i].V);
3004 if (ArgList[i].Attrs != Attribute::None)
3005 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3009 return Error(CallLoc, "not enough parameters specified for call");
3011 if (FnAttrs != Attribute::None)
3012 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3014 // Finish off the Attributes and check them
3015 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3017 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3018 CI->setTailCall(isTail);
3019 CI->setCallingConv(CC);
3020 CI->setAttributes(PAL);
3025 //===----------------------------------------------------------------------===//
3026 // Memory Instructions.
3027 //===----------------------------------------------------------------------===//
3030 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3031 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3032 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3034 PATypeHolder Ty(Type::VoidTy);
3037 unsigned Alignment = 0;
3038 if (ParseType(Ty)) return true;
3040 if (EatIfPresent(lltok::comma)) {
3041 if (Lex.getKind() == lltok::kw_align) {
3042 if (ParseOptionalAlignment(Alignment)) return true;
3043 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3044 ParseOptionalCommaAlignment(Alignment)) {
3049 if (Size && Size->getType() != Type::Int32Ty)
3050 return Error(SizeLoc, "element count must be i32");
3052 if (Opc == Instruction::Malloc)
3053 Inst = new MallocInst(Ty, Size, Alignment);
3055 Inst = new AllocaInst(Ty, Size, Alignment);
3060 /// ::= 'free' TypeAndValue
3061 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3062 Value *Val; LocTy Loc;
3063 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3064 if (!isa<PointerType>(Val->getType()))
3065 return Error(Loc, "operand to free must be a pointer");
3066 Inst = new FreeInst(Val);
3071 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3072 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3074 Value *Val; LocTy Loc;
3076 if (ParseTypeAndValue(Val, Loc, PFS) ||
3077 ParseOptionalCommaAlignment(Alignment))
3080 if (!isa<PointerType>(Val->getType()) ||
3081 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3082 return Error(Loc, "load operand must be a pointer to a first class type");
3084 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3089 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3090 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3092 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3094 if (ParseTypeAndValue(Val, Loc, PFS) ||
3095 ParseToken(lltok::comma, "expected ',' after store operand") ||
3096 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3097 ParseOptionalCommaAlignment(Alignment))
3100 if (!isa<PointerType>(Ptr->getType()))
3101 return Error(PtrLoc, "store operand must be a pointer");
3102 if (!Val->getType()->isFirstClassType())
3103 return Error(Loc, "store operand must be a first class value");
3104 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3105 return Error(Loc, "stored value and pointer type do not match");
3107 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3112 /// ::= 'getresult' TypeAndValue ',' uint
3113 /// FIXME: Remove support for getresult in LLVM 3.0
3114 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3115 Value *Val; LocTy ValLoc, EltLoc;
3117 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3118 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3119 ParseUInt32(Element, EltLoc))
3122 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3123 return Error(ValLoc, "getresult inst requires an aggregate operand");
3124 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3125 return Error(EltLoc, "invalid getresult index for value");
3126 Inst = ExtractValueInst::Create(Val, Element);
3130 /// ParseGetElementPtr
3131 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3132 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3133 Value *Ptr, *Val; LocTy Loc, EltLoc;
3134 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3136 if (!isa<PointerType>(Ptr->getType()))
3137 return Error(Loc, "base of getelementptr must be a pointer");
3139 SmallVector<Value*, 16> Indices;
3140 while (EatIfPresent(lltok::comma)) {
3141 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3142 if (!isa<IntegerType>(Val->getType()))
3143 return Error(EltLoc, "getelementptr index must be an integer");
3144 Indices.push_back(Val);
3147 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3148 Indices.begin(), Indices.end()))
3149 return Error(Loc, "invalid getelementptr indices");
3150 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3154 /// ParseExtractValue
3155 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3156 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3157 Value *Val; LocTy Loc;
3158 SmallVector<unsigned, 4> Indices;
3159 if (ParseTypeAndValue(Val, Loc, PFS) ||
3160 ParseIndexList(Indices))
3163 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3164 return Error(Loc, "extractvalue operand must be array or struct");
3166 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3168 return Error(Loc, "invalid indices for extractvalue");
3169 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3173 /// ParseInsertValue
3174 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3175 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3176 Value *Val0, *Val1; LocTy Loc0, Loc1;
3177 SmallVector<unsigned, 4> Indices;
3178 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3179 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3180 ParseTypeAndValue(Val1, Loc1, PFS) ||
3181 ParseIndexList(Indices))
3184 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3185 return Error(Loc0, "extractvalue operand must be array or struct");
3187 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3189 return Error(Loc0, "invalid indices for insertvalue");
3190 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());