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)
335 return TokError("expected 'global' or 'constant'");
340 /// ParseNamedGlobal:
341 /// GlobalVar '=' OptionalVisibility ALIAS ...
342 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
343 bool LLParser::ParseNamedGlobal() {
344 assert(Lex.getKind() == lltok::GlobalVar);
345 LocTy NameLoc = Lex.getLoc();
346 std::string Name = Lex.getStrVal();
350 unsigned Linkage, Visibility;
351 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
352 ParseOptionalLinkage(Linkage, HasLinkage) ||
353 ParseOptionalVisibility(Visibility))
356 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
357 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
358 return ParseAlias(Name, NameLoc, Visibility);
362 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
364 /// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
366 /// Everything through visibility has already been parsed.
368 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
369 unsigned Visibility) {
370 assert(Lex.getKind() == lltok::kw_alias);
373 LocTy LinkageLoc = Lex.getLoc();
374 if (ParseOptionalLinkage(Linkage))
377 if (Linkage != GlobalValue::ExternalLinkage &&
378 Linkage != GlobalValue::WeakLinkage &&
379 Linkage != GlobalValue::InternalLinkage &&
380 Linkage != GlobalValue::PrivateLinkage)
381 return Error(LinkageLoc, "invalid linkage type for alias");
384 LocTy AliaseeLoc = Lex.getLoc();
385 if (Lex.getKind() != lltok::kw_bitcast) {
386 if (ParseGlobalTypeAndValue(Aliasee)) return true;
388 // The bitcast dest type is not present, it is implied by the dest type.
390 if (ParseValID(ID)) return true;
391 if (ID.Kind != ValID::t_Constant)
392 return Error(AliaseeLoc, "invalid aliasee");
393 Aliasee = ID.ConstantVal;
396 if (!isa<PointerType>(Aliasee->getType()))
397 return Error(AliaseeLoc, "alias must have pointer type");
399 // Okay, create the alias but do not insert it into the module yet.
400 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
401 (GlobalValue::LinkageTypes)Linkage, Name,
403 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
405 // See if this value already exists in the symbol table. If so, it is either
406 // a redefinition or a definition of a forward reference.
407 if (GlobalValue *Val =
408 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
409 // See if this was a redefinition. If so, there is no entry in
411 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
412 I = ForwardRefVals.find(Name);
413 if (I == ForwardRefVals.end())
414 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
416 // Otherwise, this was a definition of forward ref. Verify that types
418 if (Val->getType() != GA->getType())
419 return Error(NameLoc,
420 "forward reference and definition of alias have different types");
422 // If they agree, just RAUW the old value with the alias and remove the
424 Val->replaceAllUsesWith(GA);
425 Val->eraseFromParent();
426 ForwardRefVals.erase(I);
429 // Insert into the module, we know its name won't collide now.
430 M->getAliasList().push_back(GA);
431 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
437 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
438 /// OptionalAddrSpace GlobalType Type Const
439 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
440 /// OptionalAddrSpace GlobalType Type Const
442 /// Everything through visibility has been parsed already.
444 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
445 unsigned Linkage, bool HasLinkage,
446 unsigned Visibility) {
448 bool ThreadLocal, IsConstant;
451 PATypeHolder Ty(Type::VoidTy);
452 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
453 ParseOptionalAddrSpace(AddrSpace) ||
454 ParseGlobalType(IsConstant) ||
455 ParseType(Ty, TyLoc))
458 // If the linkage is specified and is external, then no initializer is
461 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
462 Linkage != GlobalValue::ExternalWeakLinkage &&
463 Linkage != GlobalValue::ExternalLinkage)) {
464 if (ParseGlobalValue(Ty, Init))
468 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
469 return Error(TyLoc, "invald type for global variable");
471 GlobalVariable *GV = 0;
473 // See if the global was forward referenced, if so, use the global.
475 if ((GV = M->getGlobalVariable(Name, true)) &&
476 !ForwardRefVals.erase(Name))
477 return Error(NameLoc, "redefinition of global '@" + Name + "'");
479 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
480 I = ForwardRefValIDs.find(NumberedVals.size());
481 if (I != ForwardRefValIDs.end()) {
482 GV = cast<GlobalVariable>(I->second.first);
483 ForwardRefValIDs.erase(I);
488 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
489 M, false, AddrSpace);
491 if (GV->getType()->getElementType() != Ty)
493 "forward reference and definition of global have different types");
495 // Move the forward-reference to the correct spot in the module.
496 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
500 NumberedVals.push_back(GV);
502 // Set the parsed properties on the global.
504 GV->setInitializer(Init);
505 GV->setConstant(IsConstant);
506 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
507 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
508 GV->setThreadLocal(ThreadLocal);
510 // Parse attributes on the global.
511 while (Lex.getKind() == lltok::comma) {
514 if (Lex.getKind() == lltok::kw_section) {
516 GV->setSection(Lex.getStrVal());
517 if (ParseToken(lltok::StringConstant, "expected global section string"))
519 } else if (Lex.getKind() == lltok::kw_align) {
521 if (ParseOptionalAlignment(Alignment)) return true;
522 GV->setAlignment(Alignment);
524 TokError("unknown global variable property!");
532 //===----------------------------------------------------------------------===//
533 // GlobalValue Reference/Resolution Routines.
534 //===----------------------------------------------------------------------===//
536 /// GetGlobalVal - Get a value with the specified name or ID, creating a
537 /// forward reference record if needed. This can return null if the value
538 /// exists but does not have the right type.
539 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
541 const PointerType *PTy = dyn_cast<PointerType>(Ty);
543 Error(Loc, "global variable reference must have pointer type");
547 // Look this name up in the normal function symbol table.
549 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
551 // If this is a forward reference for the value, see if we already created a
552 // forward ref record.
554 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
555 I = ForwardRefVals.find(Name);
556 if (I != ForwardRefVals.end())
557 Val = I->second.first;
560 // If we have the value in the symbol table or fwd-ref table, return it.
562 if (Val->getType() == Ty) return Val;
563 Error(Loc, "'@" + Name + "' defined with type '" +
564 Val->getType()->getDescription() + "'");
568 // Otherwise, create a new forward reference for this value and remember it.
570 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
571 // Function types can return opaque but functions can't.
572 if (isa<OpaqueType>(FT->getReturnType())) {
573 Error(Loc, "function may not return opaque type");
577 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
579 FwdVal = new GlobalVariable(PTy->getElementType(), false,
580 GlobalValue::ExternalWeakLinkage, 0, Name, M);
583 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
587 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
588 const PointerType *PTy = dyn_cast<PointerType>(Ty);
590 Error(Loc, "global variable reference must have pointer type");
594 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
596 // If this is a forward reference for the value, see if we already created a
597 // forward ref record.
599 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
600 I = ForwardRefValIDs.find(ID);
601 if (I != ForwardRefValIDs.end())
602 Val = I->second.first;
605 // If we have the value in the symbol table or fwd-ref table, return it.
607 if (Val->getType() == Ty) return Val;
608 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
609 Val->getType()->getDescription() + "'");
613 // Otherwise, create a new forward reference for this value and remember it.
615 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
616 // Function types can return opaque but functions can't.
617 if (isa<OpaqueType>(FT->getReturnType())) {
618 Error(Loc, "function may not return opaque type");
621 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
623 FwdVal = new GlobalVariable(PTy->getElementType(), false,
624 GlobalValue::ExternalWeakLinkage, 0, "", M);
627 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
632 //===----------------------------------------------------------------------===//
634 //===----------------------------------------------------------------------===//
636 /// ParseToken - If the current token has the specified kind, eat it and return
637 /// success. Otherwise, emit the specified error and return failure.
638 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
639 if (Lex.getKind() != T)
640 return TokError(ErrMsg);
645 /// ParseStringConstant
646 /// ::= StringConstant
647 bool LLParser::ParseStringConstant(std::string &Result) {
648 if (Lex.getKind() != lltok::StringConstant)
649 return TokError("expected string constant");
650 Result = Lex.getStrVal();
657 bool LLParser::ParseUInt32(unsigned &Val) {
658 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
659 return TokError("expected integer");
660 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
661 if (Val64 != unsigned(Val64))
662 return TokError("expected 32-bit integer (too large)");
669 /// ParseOptionalAddrSpace
671 /// := 'addrspace' '(' uint32 ')'
672 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
674 if (!EatIfPresent(lltok::kw_addrspace))
676 return ParseToken(lltok::lparen, "expected '(' in address space") ||
677 ParseUInt32(AddrSpace) ||
678 ParseToken(lltok::rparen, "expected ')' in address space");
681 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
682 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
683 /// 2: function attr.
684 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
685 Attrs = Attribute::None;
686 LocTy AttrLoc = Lex.getLoc();
689 switch (Lex.getKind()) {
692 // Treat these as signext/zeroext unless they are function attrs.
693 // FIXME: REMOVE THIS IN LLVM 3.0
695 if (Lex.getKind() == lltok::kw_sext)
696 Attrs |= Attribute::SExt;
698 Attrs |= Attribute::ZExt;
702 default: // End of attributes.
703 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
704 return Error(AttrLoc, "invalid use of function-only attribute");
706 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
707 return Error(AttrLoc, "invalid use of parameter-only attribute");
710 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
711 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
712 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
713 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
714 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
715 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
716 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
717 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
719 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
720 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
721 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
722 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
723 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
724 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
725 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
726 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
727 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
730 case lltok::kw_align: {
732 if (ParseOptionalAlignment(Alignment))
734 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
742 /// ParseOptionalLinkage
752 /// ::= 'extern_weak'
754 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
756 switch (Lex.getKind()) {
757 default: Res = GlobalValue::ExternalLinkage; return false;
758 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
759 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
760 case lltok::kw_weak: Res = GlobalValue::WeakLinkage; break;
761 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceLinkage; break;
762 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
763 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
764 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
765 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
766 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
767 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
774 /// ParseOptionalVisibility
780 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
781 switch (Lex.getKind()) {
782 default: Res = GlobalValue::DefaultVisibility; return false;
783 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
784 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
785 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
791 /// ParseOptionalCallingConv
796 /// ::= 'x86_stdcallcc'
797 /// ::= 'x86_fastcallcc'
800 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
801 switch (Lex.getKind()) {
802 default: CC = CallingConv::C; return false;
803 case lltok::kw_ccc: CC = CallingConv::C; break;
804 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
805 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
806 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
807 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
808 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
814 /// ParseOptionalAlignment
817 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
819 if (!EatIfPresent(lltok::kw_align))
821 LocTy AlignLoc = Lex.getLoc();
822 if (ParseUInt32(Alignment)) return true;
823 if (!isPowerOf2_32(Alignment))
824 return Error(AlignLoc, "alignment is not a power of two");
828 /// ParseOptionalCommaAlignment
830 /// ::= ',' 'align' 4
831 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
833 if (!EatIfPresent(lltok::comma))
835 return ParseToken(lltok::kw_align, "expected 'align'") ||
836 ParseUInt32(Alignment);
840 /// ::= (',' uint32)+
841 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
842 if (Lex.getKind() != lltok::comma)
843 return TokError("expected ',' as start of index list");
845 while (EatIfPresent(lltok::comma)) {
847 if (ParseUInt32(Idx)) return true;
848 Indices.push_back(Idx);
854 //===----------------------------------------------------------------------===//
856 //===----------------------------------------------------------------------===//
858 /// ParseType - Parse and resolve a full type.
859 bool LLParser::ParseType(PATypeHolder &Result) {
860 if (ParseTypeRec(Result)) return true;
862 // Verify no unresolved uprefs.
864 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
869 /// HandleUpRefs - Every time we finish a new layer of types, this function is
870 /// called. It loops through the UpRefs vector, which is a list of the
871 /// currently active types. For each type, if the up-reference is contained in
872 /// the newly completed type, we decrement the level count. When the level
873 /// count reaches zero, the up-referenced type is the type that is passed in:
874 /// thus we can complete the cycle.
876 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
877 // If Ty isn't abstract, or if there are no up-references in it, then there is
878 // nothing to resolve here.
879 if (!ty->isAbstract() || UpRefs.empty()) return ty;
883 errs() << "Type '" << Ty->getDescription()
884 << "' newly formed. Resolving upreferences.\n"
885 << UpRefs.size() << " upreferences active!\n";
888 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
889 // to zero), we resolve them all together before we resolve them to Ty. At
890 // the end of the loop, if there is anything to resolve to Ty, it will be in
892 OpaqueType *TypeToResolve = 0;
894 for (unsigned i = 0; i != UpRefs.size(); ++i) {
895 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
897 std::find(Ty->subtype_begin(), Ty->subtype_end(),
898 UpRefs[i].LastContainedTy) != Ty->subtype_end();
901 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
902 << UpRefs[i].LastContainedTy->getDescription() << ") = "
903 << (ContainsType ? "true" : "false")
904 << " level=" << UpRefs[i].NestingLevel << "\n";
909 // Decrement level of upreference
910 unsigned Level = --UpRefs[i].NestingLevel;
911 UpRefs[i].LastContainedTy = Ty;
913 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
918 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
921 TypeToResolve = UpRefs[i].UpRefTy;
923 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
924 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
925 --i; // Do not skip the next element.
929 TypeToResolve->refineAbstractTypeTo(Ty);
935 /// ParseTypeRec - The recursive function used to process the internal
936 /// implementation details of types.
937 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
938 switch (Lex.getKind()) {
940 return TokError("expected type");
942 // TypeRec ::= 'float' | 'void' (etc)
943 Result = Lex.getTyVal();
946 case lltok::kw_opaque:
947 // TypeRec ::= 'opaque'
948 Result = OpaqueType::get();
952 // TypeRec ::= '{' ... '}'
953 if (ParseStructType(Result, false))
957 // TypeRec ::= '[' ... ']'
958 Lex.Lex(); // eat the lsquare.
959 if (ParseArrayVectorType(Result, false))
962 case lltok::less: // Either vector or packed struct.
963 // TypeRec ::= '<' ... '>'
965 if (Lex.getKind() == lltok::lbrace) {
966 if (ParseStructType(Result, true) ||
967 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
969 } else if (ParseArrayVectorType(Result, true))
972 case lltok::LocalVar:
973 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
975 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
978 Result = OpaqueType::get();
979 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
980 std::make_pair(Result,
982 M->addTypeName(Lex.getStrVal(), Result.get());
987 case lltok::LocalVarID:
989 if (Lex.getUIntVal() < NumberedTypes.size())
990 Result = NumberedTypes[Lex.getUIntVal()];
992 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
993 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
994 if (I != ForwardRefTypeIDs.end())
995 Result = I->second.first;
997 Result = OpaqueType::get();
998 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
999 std::make_pair(Result,
1005 case lltok::backslash: {
1006 // TypeRec ::= '\' 4
1009 if (ParseUInt32(Val)) return true;
1010 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1011 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1017 // Parse the type suffixes.
1019 switch (Lex.getKind()) {
1021 default: return false;
1023 // TypeRec ::= TypeRec '*'
1025 if (Result.get() == Type::LabelTy)
1026 return TokError("basic block pointers are invalid");
1027 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1031 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1032 case lltok::kw_addrspace: {
1033 if (Result.get() == Type::LabelTy)
1034 return TokError("basic block pointers are invalid");
1036 if (ParseOptionalAddrSpace(AddrSpace) ||
1037 ParseToken(lltok::star, "expected '*' in address space"))
1040 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1044 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1046 if (ParseFunctionType(Result))
1053 /// ParseParameterList
1055 /// ::= '(' Arg (',' Arg)* ')'
1057 /// ::= Type OptionalAttributes Value OptionalAttributes
1058 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1059 PerFunctionState &PFS) {
1060 if (ParseToken(lltok::lparen, "expected '(' in call"))
1063 while (Lex.getKind() != lltok::rparen) {
1064 // If this isn't the first argument, we need a comma.
1065 if (!ArgList.empty() &&
1066 ParseToken(lltok::comma, "expected ',' in argument list"))
1069 // Parse the argument.
1071 PATypeHolder ArgTy(Type::VoidTy);
1072 unsigned ArgAttrs1, ArgAttrs2;
1074 if (ParseType(ArgTy, ArgLoc) ||
1075 ParseOptionalAttrs(ArgAttrs1, 0) ||
1076 ParseValue(ArgTy, V, PFS) ||
1077 // FIXME: Should not allow attributes after the argument, remove this in
1079 ParseOptionalAttrs(ArgAttrs2, 0))
1081 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1084 Lex.Lex(); // Lex the ')'.
1090 /// ParseArgumentList - Parse the argument list for a function type or function
1091 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1092 /// ::= '(' ArgTypeListI ')'
1096 /// ::= ArgTypeList ',' '...'
1097 /// ::= ArgType (',' ArgType)*
1099 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1100 bool &isVarArg, bool inType) {
1102 assert(Lex.getKind() == lltok::lparen);
1103 Lex.Lex(); // eat the (.
1105 if (Lex.getKind() == lltok::rparen) {
1107 } else if (Lex.getKind() == lltok::dotdotdot) {
1111 LocTy TypeLoc = Lex.getLoc();
1112 PATypeHolder ArgTy(Type::VoidTy);
1116 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1117 // types (such as a function returning a pointer to itself). If parsing a
1118 // function prototype, we require fully resolved types.
1119 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1120 ParseOptionalAttrs(Attrs, 0)) return true;
1122 if (Lex.getKind() == lltok::LocalVar ||
1123 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1124 Name = Lex.getStrVal();
1128 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1129 return Error(TypeLoc, "invalid type for function argument");
1131 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1133 while (EatIfPresent(lltok::comma)) {
1134 // Handle ... at end of arg list.
1135 if (EatIfPresent(lltok::dotdotdot)) {
1140 // Otherwise must be an argument type.
1141 TypeLoc = Lex.getLoc();
1142 if (ParseTypeRec(ArgTy) ||
1143 ParseOptionalAttrs(Attrs, 0)) return true;
1145 if (Lex.getKind() == lltok::LocalVar ||
1146 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1147 Name = Lex.getStrVal();
1153 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1154 return Error(TypeLoc, "invalid type for function argument");
1156 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1160 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1163 /// ParseFunctionType
1164 /// ::= Type ArgumentList OptionalAttrs
1165 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1166 assert(Lex.getKind() == lltok::lparen);
1168 if (!FunctionType::isValidReturnType(Result))
1169 return TokError("invalid function return type");
1171 std::vector<ArgInfo> ArgList;
1174 if (ParseArgumentList(ArgList, isVarArg, true) ||
1175 // FIXME: Allow, but ignore attributes on function types!
1176 // FIXME: Remove in LLVM 3.0
1177 ParseOptionalAttrs(Attrs, 2))
1180 // Reject names on the arguments lists.
1181 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1182 if (!ArgList[i].Name.empty())
1183 return Error(ArgList[i].Loc, "argument name invalid in function type");
1184 if (!ArgList[i].Attrs != 0) {
1185 // Allow but ignore attributes on function types; this permits
1187 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1191 std::vector<const Type*> ArgListTy;
1192 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1193 ArgListTy.push_back(ArgList[i].Type);
1195 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1199 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1202 /// ::= '{' TypeRec (',' TypeRec)* '}'
1203 /// ::= '<' '{' '}' '>'
1204 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1205 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1206 assert(Lex.getKind() == lltok::lbrace);
1207 Lex.Lex(); // Consume the '{'
1209 if (EatIfPresent(lltok::rbrace)) {
1210 Result = StructType::get(std::vector<const Type*>(), Packed);
1214 std::vector<PATypeHolder> ParamsList;
1215 if (ParseTypeRec(Result)) return true;
1216 ParamsList.push_back(Result);
1218 while (EatIfPresent(lltok::comma)) {
1219 if (ParseTypeRec(Result)) return true;
1220 ParamsList.push_back(Result);
1223 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1226 std::vector<const Type*> ParamsListTy;
1227 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1228 ParamsListTy.push_back(ParamsList[i].get());
1229 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1233 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1234 /// token has already been consumed.
1236 /// ::= '[' APSINTVAL 'x' Types ']'
1237 /// ::= '<' APSINTVAL 'x' Types '>'
1238 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1239 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1240 Lex.getAPSIntVal().getBitWidth() > 64)
1241 return TokError("expected number in address space");
1243 LocTy SizeLoc = Lex.getLoc();
1244 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1247 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1250 LocTy TypeLoc = Lex.getLoc();
1251 PATypeHolder EltTy(Type::VoidTy);
1252 if (ParseTypeRec(EltTy)) return true;
1254 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1255 "expected end of sequential type"))
1259 if ((unsigned)Size != Size)
1260 return Error(SizeLoc, "size too large for vector");
1261 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1262 return Error(TypeLoc, "vector element type must be fp or integer");
1263 Result = VectorType::get(EltTy, unsigned(Size));
1265 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1266 return Error(TypeLoc, "invalid array element type");
1267 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1272 //===----------------------------------------------------------------------===//
1273 // Function Semantic Analysis.
1274 //===----------------------------------------------------------------------===//
1276 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1279 // Insert unnamed arguments into the NumberedVals list.
1280 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1283 NumberedVals.push_back(AI);
1286 LLParser::PerFunctionState::~PerFunctionState() {
1287 // If there were any forward referenced non-basicblock values, delete them.
1288 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1289 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1290 if (!isa<BasicBlock>(I->second.first)) {
1291 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1293 delete I->second.first;
1294 I->second.first = 0;
1297 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1298 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1299 if (!isa<BasicBlock>(I->second.first)) {
1300 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1302 delete I->second.first;
1303 I->second.first = 0;
1307 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1308 if (!ForwardRefVals.empty())
1309 return P.Error(ForwardRefVals.begin()->second.second,
1310 "use of undefined value '%" + ForwardRefVals.begin()->first +
1312 if (!ForwardRefValIDs.empty())
1313 return P.Error(ForwardRefValIDs.begin()->second.second,
1314 "use of undefined value '%" +
1315 utostr(ForwardRefValIDs.begin()->first) + "'");
1320 /// GetVal - Get a value with the specified name or ID, creating a
1321 /// forward reference record if needed. This can return null if the value
1322 /// exists but does not have the right type.
1323 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1324 const Type *Ty, LocTy Loc) {
1325 // Look this name up in the normal function symbol table.
1326 Value *Val = F.getValueSymbolTable().lookup(Name);
1328 // If this is a forward reference for the value, see if we already created a
1329 // forward ref record.
1331 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1332 I = ForwardRefVals.find(Name);
1333 if (I != ForwardRefVals.end())
1334 Val = I->second.first;
1337 // If we have the value in the symbol table or fwd-ref table, return it.
1339 if (Val->getType() == Ty) return Val;
1340 if (Ty == Type::LabelTy)
1341 P.Error(Loc, "'%" + Name + "' is not a basic block");
1343 P.Error(Loc, "'%" + Name + "' defined with type '" +
1344 Val->getType()->getDescription() + "'");
1348 // Don't make placeholders with invalid type.
1349 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1350 P.Error(Loc, "invalid use of a non-first-class type");
1354 // Otherwise, create a new forward reference for this value and remember it.
1356 if (Ty == Type::LabelTy)
1357 FwdVal = BasicBlock::Create(Name, &F);
1359 FwdVal = new Argument(Ty, Name);
1361 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1365 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1367 // Look this name up in the normal function symbol table.
1368 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1370 // If this is a forward reference for the value, see if we already created a
1371 // forward ref record.
1373 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1374 I = ForwardRefValIDs.find(ID);
1375 if (I != ForwardRefValIDs.end())
1376 Val = I->second.first;
1379 // If we have the value in the symbol table or fwd-ref table, return it.
1381 if (Val->getType() == Ty) return Val;
1382 if (Ty == Type::LabelTy)
1383 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1385 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1386 Val->getType()->getDescription() + "'");
1390 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1391 P.Error(Loc, "invalid use of a non-first-class type");
1395 // Otherwise, create a new forward reference for this value and remember it.
1397 if (Ty == Type::LabelTy)
1398 FwdVal = BasicBlock::Create("", &F);
1400 FwdVal = new Argument(Ty);
1402 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1406 /// SetInstName - After an instruction is parsed and inserted into its
1407 /// basic block, this installs its name.
1408 bool LLParser::PerFunctionState::SetInstName(int NameID,
1409 const std::string &NameStr,
1410 LocTy NameLoc, Instruction *Inst) {
1411 // If this instruction has void type, it cannot have a name or ID specified.
1412 if (Inst->getType() == Type::VoidTy) {
1413 if (NameID != -1 || !NameStr.empty())
1414 return P.Error(NameLoc, "instructions returning void cannot have a name");
1418 // If this was a numbered instruction, verify that the instruction is the
1419 // expected value and resolve any forward references.
1420 if (NameStr.empty()) {
1421 // If neither a name nor an ID was specified, just use the next ID.
1423 NameID = NumberedVals.size();
1425 if (unsigned(NameID) != NumberedVals.size())
1426 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1427 utostr(NumberedVals.size()) + "'");
1429 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1430 ForwardRefValIDs.find(NameID);
1431 if (FI != ForwardRefValIDs.end()) {
1432 if (FI->second.first->getType() != Inst->getType())
1433 return P.Error(NameLoc, "instruction forward referenced with type '" +
1434 FI->second.first->getType()->getDescription() + "'");
1435 FI->second.first->replaceAllUsesWith(Inst);
1436 ForwardRefValIDs.erase(FI);
1439 NumberedVals.push_back(Inst);
1443 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1444 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1445 FI = ForwardRefVals.find(NameStr);
1446 if (FI != ForwardRefVals.end()) {
1447 if (FI->second.first->getType() != Inst->getType())
1448 return P.Error(NameLoc, "instruction forward referenced with type '" +
1449 FI->second.first->getType()->getDescription() + "'");
1450 FI->second.first->replaceAllUsesWith(Inst);
1451 ForwardRefVals.erase(FI);
1454 // Set the name on the instruction.
1455 Inst->setName(NameStr);
1457 if (Inst->getNameStr() != NameStr)
1458 return P.Error(NameLoc, "multiple definition of local value named '" +
1463 /// GetBB - Get a basic block with the specified name or ID, creating a
1464 /// forward reference record if needed.
1465 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1467 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1470 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1471 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1474 /// DefineBB - Define the specified basic block, which is either named or
1475 /// unnamed. If there is an error, this returns null otherwise it returns
1476 /// the block being defined.
1477 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1481 BB = GetBB(NumberedVals.size(), Loc);
1483 BB = GetBB(Name, Loc);
1484 if (BB == 0) return 0; // Already diagnosed error.
1486 // Move the block to the end of the function. Forward ref'd blocks are
1487 // inserted wherever they happen to be referenced.
1488 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1490 // Remove the block from forward ref sets.
1492 ForwardRefValIDs.erase(NumberedVals.size());
1493 NumberedVals.push_back(BB);
1495 // BB forward references are already in the function symbol table.
1496 ForwardRefVals.erase(Name);
1502 //===----------------------------------------------------------------------===//
1504 //===----------------------------------------------------------------------===//
1506 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1507 /// type implied. For example, if we parse "4" we don't know what integer type
1508 /// it has. The value will later be combined with its type and checked for
1510 bool LLParser::ParseValID(ValID &ID) {
1511 ID.Loc = Lex.getLoc();
1512 switch (Lex.getKind()) {
1513 default: return TokError("expected value token");
1514 case lltok::GlobalID: // @42
1515 ID.UIntVal = Lex.getUIntVal();
1516 ID.Kind = ValID::t_GlobalID;
1518 case lltok::GlobalVar: // @foo
1519 ID.StrVal = Lex.getStrVal();
1520 ID.Kind = ValID::t_GlobalName;
1522 case lltok::LocalVarID: // %42
1523 ID.UIntVal = Lex.getUIntVal();
1524 ID.Kind = ValID::t_LocalID;
1526 case lltok::LocalVar: // %foo
1527 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1528 ID.StrVal = Lex.getStrVal();
1529 ID.Kind = ValID::t_LocalName;
1532 ID.APSIntVal = Lex.getAPSIntVal();
1533 ID.Kind = ValID::t_APSInt;
1535 case lltok::APFloat:
1536 ID.APFloatVal = Lex.getAPFloatVal();
1537 ID.Kind = ValID::t_APFloat;
1539 case lltok::kw_true:
1540 ID.ConstantVal = ConstantInt::getTrue();
1541 ID.Kind = ValID::t_Constant;
1543 case lltok::kw_false:
1544 ID.ConstantVal = ConstantInt::getFalse();
1545 ID.Kind = ValID::t_Constant;
1547 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1548 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1549 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1551 case lltok::lbrace: {
1552 // ValID ::= '{' ConstVector '}'
1554 SmallVector<Constant*, 16> Elts;
1555 if (ParseGlobalValueVector(Elts) ||
1556 ParseToken(lltok::rbrace, "expected end of struct constant"))
1559 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1560 ID.Kind = ValID::t_Constant;
1564 // ValID ::= '<' ConstVector '>' --> Vector.
1565 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1567 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1569 SmallVector<Constant*, 16> Elts;
1570 LocTy FirstEltLoc = Lex.getLoc();
1571 if (ParseGlobalValueVector(Elts) ||
1573 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1574 ParseToken(lltok::greater, "expected end of constant"))
1577 if (isPackedStruct) {
1578 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1579 ID.Kind = ValID::t_Constant;
1584 return Error(ID.Loc, "constant vector must not be empty");
1586 if (!Elts[0]->getType()->isInteger() &&
1587 !Elts[0]->getType()->isFloatingPoint())
1588 return Error(FirstEltLoc,
1589 "vector elements must have integer or floating point type");
1591 // Verify that all the vector elements have the same type.
1592 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1593 if (Elts[i]->getType() != Elts[0]->getType())
1594 return Error(FirstEltLoc,
1595 "vector element #" + utostr(i) +
1596 " is not of type '" + Elts[0]->getType()->getDescription());
1598 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1599 ID.Kind = ValID::t_Constant;
1602 case lltok::lsquare: { // Array Constant
1604 SmallVector<Constant*, 16> Elts;
1605 LocTy FirstEltLoc = Lex.getLoc();
1606 if (ParseGlobalValueVector(Elts) ||
1607 ParseToken(lltok::rsquare, "expected end of array constant"))
1610 // Handle empty element.
1612 // Use undef instead of an array because it's inconvenient to determine
1613 // the element type at this point, there being no elements to examine.
1614 ID.Kind = ValID::t_EmptyArray;
1618 if (!Elts[0]->getType()->isFirstClassType())
1619 return Error(FirstEltLoc, "invalid array element type: " +
1620 Elts[0]->getType()->getDescription());
1622 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1624 // Verify all elements are correct type!
1625 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1626 if (Elts[i]->getType() != Elts[0]->getType())
1627 return Error(FirstEltLoc,
1628 "array element #" + utostr(i) +
1629 " is not of type '" +Elts[0]->getType()->getDescription());
1632 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1633 ID.Kind = ValID::t_Constant;
1636 case lltok::kw_c: // c "foo"
1638 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1639 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1640 ID.Kind = ValID::t_Constant;
1643 case lltok::kw_asm: {
1644 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1647 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1648 ParseStringConstant(ID.StrVal) ||
1649 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1650 ParseToken(lltok::StringConstant, "expected constraint string"))
1652 ID.StrVal2 = Lex.getStrVal();
1653 ID.UIntVal = HasSideEffect;
1654 ID.Kind = ValID::t_InlineAsm;
1658 case lltok::kw_trunc:
1659 case lltok::kw_zext:
1660 case lltok::kw_sext:
1661 case lltok::kw_fptrunc:
1662 case lltok::kw_fpext:
1663 case lltok::kw_bitcast:
1664 case lltok::kw_uitofp:
1665 case lltok::kw_sitofp:
1666 case lltok::kw_fptoui:
1667 case lltok::kw_fptosi:
1668 case lltok::kw_inttoptr:
1669 case lltok::kw_ptrtoint: {
1670 unsigned Opc = Lex.getUIntVal();
1671 PATypeHolder DestTy(Type::VoidTy);
1674 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1675 ParseGlobalTypeAndValue(SrcVal) ||
1676 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1677 ParseType(DestTy) ||
1678 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1680 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1681 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1682 SrcVal->getType()->getDescription() + "' to '" +
1683 DestTy->getDescription() + "'");
1684 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1686 ID.Kind = ValID::t_Constant;
1689 case lltok::kw_extractvalue: {
1692 SmallVector<unsigned, 4> Indices;
1693 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1694 ParseGlobalTypeAndValue(Val) ||
1695 ParseIndexList(Indices) ||
1696 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1698 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1699 return Error(ID.Loc, "extractvalue operand must be array or struct");
1700 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1702 return Error(ID.Loc, "invalid indices for extractvalue");
1703 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1704 &Indices[0], Indices.size());
1705 ID.Kind = ValID::t_Constant;
1708 case lltok::kw_insertvalue: {
1710 Constant *Val0, *Val1;
1711 SmallVector<unsigned, 4> Indices;
1712 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1713 ParseGlobalTypeAndValue(Val0) ||
1714 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1715 ParseGlobalTypeAndValue(Val1) ||
1716 ParseIndexList(Indices) ||
1717 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1719 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1720 return Error(ID.Loc, "extractvalue operand must be array or struct");
1721 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1723 return Error(ID.Loc, "invalid indices for insertvalue");
1724 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1725 &Indices[0], Indices.size());
1726 ID.Kind = ValID::t_Constant;
1729 case lltok::kw_icmp:
1730 case lltok::kw_fcmp:
1731 case lltok::kw_vicmp:
1732 case lltok::kw_vfcmp: {
1733 unsigned PredVal, Opc = Lex.getUIntVal();
1734 Constant *Val0, *Val1;
1736 if (ParseCmpPredicate(PredVal, Opc) ||
1737 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1738 ParseGlobalTypeAndValue(Val0) ||
1739 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1740 ParseGlobalTypeAndValue(Val1) ||
1741 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1744 if (Val0->getType() != Val1->getType())
1745 return Error(ID.Loc, "compare operands must have the same type");
1747 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1749 if (Opc == Instruction::FCmp) {
1750 if (!Val0->getType()->isFPOrFPVector())
1751 return Error(ID.Loc, "fcmp requires floating point operands");
1752 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1753 } else if (Opc == Instruction::ICmp) {
1754 if (!Val0->getType()->isIntOrIntVector() &&
1755 !isa<PointerType>(Val0->getType()))
1756 return Error(ID.Loc, "icmp requires pointer or integer operands");
1757 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1758 } else if (Opc == Instruction::VFCmp) {
1759 // FIXME: REMOVE VFCMP Support
1760 if (!Val0->getType()->isFPOrFPVector() ||
1761 !isa<VectorType>(Val0->getType()))
1762 return Error(ID.Loc, "vfcmp requires vector floating point operands");
1763 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1764 } else if (Opc == Instruction::VICmp) {
1765 // FIXME: REMOVE VICMP Support
1766 if (!Val0->getType()->isIntOrIntVector() ||
1767 !isa<VectorType>(Val0->getType()))
1768 return Error(ID.Loc, "vicmp requires vector floating point operands");
1769 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1771 ID.Kind = ValID::t_Constant;
1775 // Binary Operators.
1779 case lltok::kw_udiv:
1780 case lltok::kw_sdiv:
1781 case lltok::kw_fdiv:
1782 case lltok::kw_urem:
1783 case lltok::kw_srem:
1784 case lltok::kw_frem: {
1785 unsigned Opc = Lex.getUIntVal();
1786 Constant *Val0, *Val1;
1788 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1789 ParseGlobalTypeAndValue(Val0) ||
1790 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1791 ParseGlobalTypeAndValue(Val1) ||
1792 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1794 if (Val0->getType() != Val1->getType())
1795 return Error(ID.Loc, "operands of constexpr must have same type");
1796 if (!Val0->getType()->isIntOrIntVector() &&
1797 !Val0->getType()->isFPOrFPVector())
1798 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1799 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1800 ID.Kind = ValID::t_Constant;
1804 // Logical Operations
1806 case lltok::kw_lshr:
1807 case lltok::kw_ashr:
1810 case lltok::kw_xor: {
1811 unsigned Opc = Lex.getUIntVal();
1812 Constant *Val0, *Val1;
1814 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1815 ParseGlobalTypeAndValue(Val0) ||
1816 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1817 ParseGlobalTypeAndValue(Val1) ||
1818 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1820 if (Val0->getType() != Val1->getType())
1821 return Error(ID.Loc, "operands of constexpr must have same type");
1822 if (!Val0->getType()->isIntOrIntVector())
1823 return Error(ID.Loc,
1824 "constexpr requires integer or integer vector operands");
1825 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1826 ID.Kind = ValID::t_Constant;
1830 case lltok::kw_getelementptr:
1831 case lltok::kw_shufflevector:
1832 case lltok::kw_insertelement:
1833 case lltok::kw_extractelement:
1834 case lltok::kw_select: {
1835 unsigned Opc = Lex.getUIntVal();
1836 SmallVector<Constant*, 16> Elts;
1838 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1839 ParseGlobalValueVector(Elts) ||
1840 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1843 if (Opc == Instruction::GetElementPtr) {
1844 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1845 return Error(ID.Loc, "getelementptr requires pointer operand");
1847 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1848 (Value**)&Elts[1], Elts.size()-1))
1849 return Error(ID.Loc, "invalid indices for getelementptr");
1850 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1851 &Elts[1], Elts.size()-1);
1852 } else if (Opc == Instruction::Select) {
1853 if (Elts.size() != 3)
1854 return Error(ID.Loc, "expected three operands to select");
1855 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1857 return Error(ID.Loc, Reason);
1858 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1859 } else if (Opc == Instruction::ShuffleVector) {
1860 if (Elts.size() != 3)
1861 return Error(ID.Loc, "expected three operands to shufflevector");
1862 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1863 return Error(ID.Loc, "invalid operands to shufflevector");
1864 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1865 } else if (Opc == Instruction::ExtractElement) {
1866 if (Elts.size() != 2)
1867 return Error(ID.Loc, "expected two operands to extractelement");
1868 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1869 return Error(ID.Loc, "invalid extractelement operands");
1870 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1872 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1873 if (Elts.size() != 3)
1874 return Error(ID.Loc, "expected three operands to insertelement");
1875 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1876 return Error(ID.Loc, "invalid insertelement operands");
1877 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1880 ID.Kind = ValID::t_Constant;
1889 /// ParseGlobalValue - Parse a global value with the specified type.
1890 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1893 return ParseValID(ID) ||
1894 ConvertGlobalValIDToValue(Ty, ID, V);
1897 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1899 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1901 if (isa<FunctionType>(Ty))
1902 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1905 default: assert(0 && "Unknown ValID!");
1906 case ValID::t_LocalID:
1907 case ValID::t_LocalName:
1908 return Error(ID.Loc, "invalid use of function-local name");
1909 case ValID::t_InlineAsm:
1910 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1911 case ValID::t_GlobalName:
1912 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1914 case ValID::t_GlobalID:
1915 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1917 case ValID::t_APSInt:
1918 if (!isa<IntegerType>(Ty))
1919 return Error(ID.Loc, "integer constant must have integer type");
1920 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1921 V = ConstantInt::get(ID.APSIntVal);
1923 case ValID::t_APFloat:
1924 if (!Ty->isFloatingPoint() ||
1925 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1926 return Error(ID.Loc, "floating point constant invalid for type");
1928 // The lexer has no type info, so builds all float and double FP constants
1929 // as double. Fix this here. Long double does not need this.
1930 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1931 Ty == Type::FloatTy) {
1933 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1936 V = ConstantFP::get(ID.APFloatVal);
1938 if (V->getType() != Ty)
1939 return Error(ID.Loc, "floating point constant does not have type '" +
1940 Ty->getDescription() + "'");
1944 if (!isa<PointerType>(Ty))
1945 return Error(ID.Loc, "null must be a pointer type");
1946 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1948 case ValID::t_Undef:
1949 // FIXME: LabelTy should not be a first-class type.
1950 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
1951 !isa<OpaqueType>(Ty))
1952 return Error(ID.Loc, "invalid type for undef constant");
1953 V = UndefValue::get(Ty);
1955 case ValID::t_EmptyArray:
1956 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
1957 return Error(ID.Loc, "invalid empty array initializer");
1958 V = UndefValue::get(Ty);
1961 // FIXME: LabelTy should not be a first-class type.
1962 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
1963 return Error(ID.Loc, "invalid type for null constant");
1964 V = Constant::getNullValue(Ty);
1966 case ValID::t_Constant:
1967 if (ID.ConstantVal->getType() != Ty)
1968 return Error(ID.Loc, "constant expression type mismatch");
1974 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
1975 PATypeHolder Type(Type::VoidTy);
1976 return ParseType(Type) ||
1977 ParseGlobalValue(Type, V);
1980 /// ParseGlobalValueVector
1982 /// ::= TypeAndValue (',' TypeAndValue)*
1983 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
1985 if (Lex.getKind() == lltok::rbrace ||
1986 Lex.getKind() == lltok::rsquare ||
1987 Lex.getKind() == lltok::greater ||
1988 Lex.getKind() == lltok::rparen)
1992 if (ParseGlobalTypeAndValue(C)) return true;
1995 while (EatIfPresent(lltok::comma)) {
1996 if (ParseGlobalTypeAndValue(C)) return true;
2004 //===----------------------------------------------------------------------===//
2005 // Function Parsing.
2006 //===----------------------------------------------------------------------===//
2008 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2009 PerFunctionState &PFS) {
2010 if (ID.Kind == ValID::t_LocalID)
2011 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2012 else if (ID.Kind == ValID::t_LocalName)
2013 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2014 else if (ID.Kind == ValID::t_InlineAsm) {
2015 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2016 const FunctionType *FTy =
2017 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2018 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2019 return Error(ID.Loc, "invalid type for inline asm constraint string");
2020 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2024 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2032 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2035 return ParseValID(ID) ||
2036 ConvertValIDToValue(Ty, ID, V, PFS);
2039 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2040 PATypeHolder T(Type::VoidTy);
2041 return ParseType(T) ||
2042 ParseValue(T, V, PFS);
2046 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2047 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2048 /// OptionalAlign OptGC
2049 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2050 // Parse the linkage.
2051 LocTy LinkageLoc = Lex.getLoc();
2054 unsigned Visibility, CC, RetAttrs;
2055 PATypeHolder RetType(Type::VoidTy);
2056 LocTy RetTypeLoc = Lex.getLoc();
2057 if (ParseOptionalLinkage(Linkage) ||
2058 ParseOptionalVisibility(Visibility) ||
2059 ParseOptionalCallingConv(CC) ||
2060 ParseOptionalAttrs(RetAttrs, 1) ||
2061 ParseType(RetType, RetTypeLoc))
2064 // Verify that the linkage is ok.
2065 switch ((GlobalValue::LinkageTypes)Linkage) {
2066 case GlobalValue::ExternalLinkage:
2067 break; // always ok.
2068 case GlobalValue::DLLImportLinkage:
2069 case GlobalValue::ExternalWeakLinkage:
2071 return Error(LinkageLoc, "invalid linkage for function definition");
2073 case GlobalValue::PrivateLinkage:
2074 case GlobalValue::InternalLinkage:
2075 case GlobalValue::LinkOnceLinkage:
2076 case GlobalValue::WeakLinkage:
2077 case GlobalValue::DLLExportLinkage:
2079 return Error(LinkageLoc, "invalid linkage for function declaration");
2081 case GlobalValue::AppendingLinkage:
2082 case GlobalValue::GhostLinkage:
2083 case GlobalValue::CommonLinkage:
2084 return Error(LinkageLoc, "invalid function linkage type");
2087 if (!FunctionType::isValidReturnType(RetType) ||
2088 isa<OpaqueType>(RetType))
2089 return Error(RetTypeLoc, "invalid function return type");
2091 if (Lex.getKind() != lltok::GlobalVar)
2092 return TokError("expected function name");
2094 LocTy NameLoc = Lex.getLoc();
2095 std::string FunctionName = Lex.getStrVal();
2098 if (Lex.getKind() != lltok::lparen)
2099 return TokError("expected '(' in function argument list");
2101 std::vector<ArgInfo> ArgList;
2104 std::string Section;
2108 if (ParseArgumentList(ArgList, isVarArg, false) ||
2109 ParseOptionalAttrs(FuncAttrs, 2) ||
2110 (EatIfPresent(lltok::kw_section) &&
2111 ParseStringConstant(Section)) ||
2112 ParseOptionalAlignment(Alignment) ||
2113 (EatIfPresent(lltok::kw_gc) &&
2114 ParseStringConstant(GC)))
2117 // If the alignment was parsed as an attribute, move to the alignment field.
2118 if (FuncAttrs & Attribute::Alignment) {
2119 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2120 FuncAttrs &= ~Attribute::Alignment;
2123 // Okay, if we got here, the function is syntactically valid. Convert types
2124 // and do semantic checks.
2125 std::vector<const Type*> ParamTypeList;
2126 SmallVector<AttributeWithIndex, 8> Attrs;
2127 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2129 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2130 if (FuncAttrs & ObsoleteFuncAttrs) {
2131 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2132 FuncAttrs &= ~ObsoleteFuncAttrs;
2135 if (RetAttrs != Attribute::None)
2136 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2138 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2139 ParamTypeList.push_back(ArgList[i].Type);
2140 if (ArgList[i].Attrs != Attribute::None)
2141 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2144 if (FuncAttrs != Attribute::None)
2145 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2147 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2149 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2150 const PointerType *PFT = PointerType::getUnqual(FT);
2153 if (!FunctionName.empty()) {
2154 // If this was a definition of a forward reference, remove the definition
2155 // from the forward reference table and fill in the forward ref.
2156 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2157 ForwardRefVals.find(FunctionName);
2158 if (FRVI != ForwardRefVals.end()) {
2159 Fn = M->getFunction(FunctionName);
2160 ForwardRefVals.erase(FRVI);
2161 } else if ((Fn = M->getFunction(FunctionName))) {
2162 // If this function already exists in the symbol table, then it is
2163 // multiply defined. We accept a few cases for old backwards compat.
2164 // FIXME: Remove this stuff for LLVM 3.0.
2165 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2166 (!Fn->isDeclaration() && isDefine)) {
2167 // If the redefinition has different type or different attributes,
2168 // reject it. If both have bodies, reject it.
2169 return Error(NameLoc, "invalid redefinition of function '" +
2170 FunctionName + "'");
2171 } else if (Fn->isDeclaration()) {
2172 // Make sure to strip off any argument names so we can't get conflicts.
2173 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2179 } else if (FunctionName.empty()) {
2180 // If this is a definition of a forward referenced function, make sure the
2182 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2183 = ForwardRefValIDs.find(NumberedVals.size());
2184 if (I != ForwardRefValIDs.end()) {
2185 Fn = cast<Function>(I->second.first);
2186 if (Fn->getType() != PFT)
2187 return Error(NameLoc, "type of definition and forward reference of '@" +
2188 utostr(NumberedVals.size()) +"' disagree");
2189 ForwardRefValIDs.erase(I);
2194 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2195 else // Move the forward-reference to the correct spot in the module.
2196 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2198 if (FunctionName.empty())
2199 NumberedVals.push_back(Fn);
2201 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2202 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2203 Fn->setCallingConv(CC);
2204 Fn->setAttributes(PAL);
2205 Fn->setAlignment(Alignment);
2206 Fn->setSection(Section);
2207 if (!GC.empty()) Fn->setGC(GC.c_str());
2209 // Add all of the arguments we parsed to the function.
2210 Function::arg_iterator ArgIt = Fn->arg_begin();
2211 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2212 // If the argument has a name, insert it into the argument symbol table.
2213 if (ArgList[i].Name.empty()) continue;
2215 // Set the name, if it conflicted, it will be auto-renamed.
2216 ArgIt->setName(ArgList[i].Name);
2218 if (ArgIt->getNameStr() != ArgList[i].Name)
2219 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2220 ArgList[i].Name + "'");
2227 /// ParseFunctionBody
2228 /// ::= '{' BasicBlock+ '}'
2229 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2231 bool LLParser::ParseFunctionBody(Function &Fn) {
2232 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2233 return TokError("expected '{' in function body");
2234 Lex.Lex(); // eat the {.
2236 PerFunctionState PFS(*this, Fn);
2238 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2239 if (ParseBasicBlock(PFS)) return true;
2244 // Verify function is ok.
2245 return PFS.VerifyFunctionComplete();
2249 /// ::= LabelStr? Instruction*
2250 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2251 // If this basic block starts out with a name, remember it.
2253 LocTy NameLoc = Lex.getLoc();
2254 if (Lex.getKind() == lltok::LabelStr) {
2255 Name = Lex.getStrVal();
2259 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2260 if (BB == 0) return true;
2262 std::string NameStr;
2264 // Parse the instructions in this block until we get a terminator.
2267 // This instruction may have three possibilities for a name: a) none
2268 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2269 LocTy NameLoc = Lex.getLoc();
2273 if (Lex.getKind() == lltok::LocalVarID) {
2274 NameID = Lex.getUIntVal();
2276 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2278 } else if (Lex.getKind() == lltok::LocalVar ||
2279 // FIXME: REMOVE IN LLVM 3.0
2280 Lex.getKind() == lltok::StringConstant) {
2281 NameStr = Lex.getStrVal();
2283 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2287 if (ParseInstruction(Inst, BB, PFS)) return true;
2289 BB->getInstList().push_back(Inst);
2291 // Set the name on the instruction.
2292 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2293 } while (!isa<TerminatorInst>(Inst));
2298 //===----------------------------------------------------------------------===//
2299 // Instruction Parsing.
2300 //===----------------------------------------------------------------------===//
2302 /// ParseInstruction - Parse one of the many different instructions.
2304 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2305 PerFunctionState &PFS) {
2306 lltok::Kind Token = Lex.getKind();
2307 if (Token == lltok::Eof)
2308 return TokError("found end of file when expecting more instructions");
2309 LocTy Loc = Lex.getLoc();
2310 Lex.Lex(); // Eat the keyword.
2313 default: return Error(Loc, "expected instruction opcode");
2314 // Terminator Instructions.
2315 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2316 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2317 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2318 case lltok::kw_br: return ParseBr(Inst, PFS);
2319 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2320 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2321 // Binary Operators.
2324 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 0);
2326 case lltok::kw_udiv:
2327 case lltok::kw_sdiv:
2328 case lltok::kw_urem:
2329 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 1);
2330 case lltok::kw_fdiv:
2331 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal(), 2);
2333 case lltok::kw_lshr:
2334 case lltok::kw_ashr:
2337 case lltok::kw_xor: return ParseLogical(Inst, PFS, Lex.getUIntVal());
2338 case lltok::kw_icmp:
2339 case lltok::kw_fcmp:
2340 case lltok::kw_vicmp:
2341 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, Lex.getUIntVal());
2343 case lltok::kw_trunc:
2344 case lltok::kw_zext:
2345 case lltok::kw_sext:
2346 case lltok::kw_fptrunc:
2347 case lltok::kw_fpext:
2348 case lltok::kw_bitcast:
2349 case lltok::kw_uitofp:
2350 case lltok::kw_sitofp:
2351 case lltok::kw_fptoui:
2352 case lltok::kw_fptosi:
2353 case lltok::kw_inttoptr:
2354 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, Lex.getUIntVal());
2356 case lltok::kw_select: return ParseSelect(Inst, PFS);
2357 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2358 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2359 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2360 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2361 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2362 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2363 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2365 case lltok::kw_alloca:
2366 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, Lex.getUIntVal());
2367 case lltok::kw_free: return ParseFree(Inst, PFS);
2368 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2369 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2370 case lltok::kw_volatile:
2371 if (EatIfPresent(lltok::kw_load))
2372 return ParseLoad(Inst, PFS, true);
2373 else if (EatIfPresent(lltok::kw_store))
2374 return ParseStore(Inst, PFS, true);
2376 return TokError("expected 'load' or 'store'");
2377 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2378 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2379 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2380 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2384 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2385 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2386 // FIXME: REMOVE vicmp/vfcmp!
2387 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2388 switch (Lex.getKind()) {
2389 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2390 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2391 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2392 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2393 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2394 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2395 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2396 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2397 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2398 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2399 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2400 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2401 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2402 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2403 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2404 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2405 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2408 switch (Lex.getKind()) {
2409 default: TokError("expected icmp predicate (e.g. 'eq')");
2410 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2411 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2412 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2413 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2414 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2415 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2416 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2417 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2418 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2419 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2426 //===----------------------------------------------------------------------===//
2427 // Terminator Instructions.
2428 //===----------------------------------------------------------------------===//
2430 /// ParseRet - Parse a return instruction.
2432 /// ::= 'ret' TypeAndValue
2433 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2434 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2435 PerFunctionState &PFS) {
2436 PATypeHolder Ty(Type::VoidTy);
2437 if (ParseType(Ty)) return true;
2439 if (Ty == Type::VoidTy) {
2440 Inst = ReturnInst::Create();
2445 if (ParseValue(Ty, RV, PFS)) return true;
2447 // The normal case is one return value.
2448 if (Lex.getKind() == lltok::comma) {
2449 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2450 // of 'ret {i32,i32} {i32 1, i32 2}'
2451 SmallVector<Value*, 8> RVs;
2454 while (EatIfPresent(lltok::comma)) {
2455 if (ParseTypeAndValue(RV, PFS)) return true;
2459 RV = UndefValue::get(PFS.getFunction().getReturnType());
2460 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2461 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2462 BB->getInstList().push_back(I);
2466 Inst = ReturnInst::Create(RV);
2472 /// ::= 'br' TypeAndValue
2473 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2474 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2476 Value *Op0, *Op1, *Op2;
2477 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2479 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2480 Inst = BranchInst::Create(BB);
2484 if (Op0->getType() != Type::Int1Ty)
2485 return Error(Loc, "branch condition must have 'i1' type");
2487 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2488 ParseTypeAndValue(Op1, Loc, PFS) ||
2489 ParseToken(lltok::comma, "expected ',' after true destination") ||
2490 ParseTypeAndValue(Op2, Loc2, PFS))
2493 if (!isa<BasicBlock>(Op1))
2494 return Error(Loc, "true destination of branch must be a basic block");
2495 if (!isa<BasicBlock>(Op2))
2496 return Error(Loc2, "true destination of branch must be a basic block");
2498 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2504 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2506 /// ::= (TypeAndValue ',' TypeAndValue)*
2507 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2508 LocTy CondLoc, BBLoc;
2509 Value *Cond, *DefaultBB;
2510 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2511 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2512 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2513 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2516 if (!isa<IntegerType>(Cond->getType()))
2517 return Error(CondLoc, "switch condition must have integer type");
2518 if (!isa<BasicBlock>(DefaultBB))
2519 return Error(BBLoc, "default destination must be a basic block");
2521 // Parse the jump table pairs.
2522 SmallPtrSet<Value*, 32> SeenCases;
2523 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2524 while (Lex.getKind() != lltok::rsquare) {
2525 Value *Constant, *DestBB;
2527 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2528 ParseToken(lltok::comma, "expected ',' after case value") ||
2529 ParseTypeAndValue(DestBB, BBLoc, PFS))
2532 if (!SeenCases.insert(Constant))
2533 return Error(CondLoc, "duplicate case value in switch");
2534 if (!isa<ConstantInt>(Constant))
2535 return Error(CondLoc, "case value is not a constant integer");
2536 if (!isa<BasicBlock>(DestBB))
2537 return Error(BBLoc, "case destination is not a basic block");
2539 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2540 cast<BasicBlock>(DestBB)));
2543 Lex.Lex(); // Eat the ']'.
2545 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2547 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2548 SI->addCase(Table[i].first, Table[i].second);
2554 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2555 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2556 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2557 LocTy CallLoc = Lex.getLoc();
2558 unsigned CC, RetAttrs, FnAttrs;
2559 PATypeHolder RetType(Type::VoidTy);
2562 SmallVector<ParamInfo, 16> ArgList;
2564 Value *NormalBB, *UnwindBB;
2565 if (ParseOptionalCallingConv(CC) ||
2566 ParseOptionalAttrs(RetAttrs, 1) ||
2567 ParseType(RetType, RetTypeLoc) ||
2568 ParseValID(CalleeID) ||
2569 ParseParameterList(ArgList, PFS) ||
2570 ParseOptionalAttrs(FnAttrs, 2) ||
2571 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2572 ParseTypeAndValue(NormalBB, PFS) ||
2573 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2574 ParseTypeAndValue(UnwindBB, PFS))
2577 if (!isa<BasicBlock>(NormalBB))
2578 return Error(CallLoc, "normal destination is not a basic block");
2579 if (!isa<BasicBlock>(UnwindBB))
2580 return Error(CallLoc, "unwind destination is not a basic block");
2582 // If RetType is a non-function pointer type, then this is the short syntax
2583 // for the call, which means that RetType is just the return type. Infer the
2584 // rest of the function argument types from the arguments that are present.
2585 const PointerType *PFTy = 0;
2586 const FunctionType *Ty = 0;
2587 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2588 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2589 // Pull out the types of all of the arguments...
2590 std::vector<const Type*> ParamTypes;
2591 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2592 ParamTypes.push_back(ArgList[i].V->getType());
2594 if (!FunctionType::isValidReturnType(RetType))
2595 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2597 Ty = FunctionType::get(RetType, ParamTypes, false);
2598 PFTy = PointerType::getUnqual(Ty);
2601 // Look up the callee.
2603 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2605 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2606 // function attributes.
2607 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2608 if (FnAttrs & ObsoleteFuncAttrs) {
2609 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2610 FnAttrs &= ~ObsoleteFuncAttrs;
2613 // Set up the Attributes for the function.
2614 SmallVector<AttributeWithIndex, 8> Attrs;
2615 if (RetAttrs != Attribute::None)
2616 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2618 SmallVector<Value*, 8> Args;
2620 // Loop through FunctionType's arguments and ensure they are specified
2621 // correctly. Also, gather any parameter attributes.
2622 FunctionType::param_iterator I = Ty->param_begin();
2623 FunctionType::param_iterator E = Ty->param_end();
2624 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2625 const Type *ExpectedTy = 0;
2628 } else if (!Ty->isVarArg()) {
2629 return Error(ArgList[i].Loc, "too many arguments specified");
2632 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2633 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2634 ExpectedTy->getDescription() + "'");
2635 Args.push_back(ArgList[i].V);
2636 if (ArgList[i].Attrs != Attribute::None)
2637 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2641 return Error(CallLoc, "not enough parameters specified for call");
2643 if (FnAttrs != Attribute::None)
2644 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2646 // Finish off the Attributes and check them
2647 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2649 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2650 cast<BasicBlock>(UnwindBB),
2651 Args.begin(), Args.end());
2652 II->setCallingConv(CC);
2653 II->setAttributes(PAL);
2660 //===----------------------------------------------------------------------===//
2661 // Binary Operators.
2662 //===----------------------------------------------------------------------===//
2665 /// ::= ArithmeticOps TypeAndValue ',' Value
2667 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2668 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2669 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2670 unsigned Opc, unsigned OperandType) {
2671 LocTy Loc; Value *LHS, *RHS;
2672 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2673 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2674 ParseValue(LHS->getType(), RHS, PFS))
2678 switch (OperandType) {
2679 default: assert(0 && "Unknown operand type!");
2680 case 0: // int or FP.
2681 Valid = LHS->getType()->isIntOrIntVector() ||
2682 LHS->getType()->isFPOrFPVector();
2684 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2685 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2689 return Error(Loc, "invalid operand type for instruction");
2691 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2696 /// ::= ArithmeticOps TypeAndValue ',' Value {
2697 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2699 LocTy Loc; Value *LHS, *RHS;
2700 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2701 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2702 ParseValue(LHS->getType(), RHS, PFS))
2705 if (!LHS->getType()->isIntOrIntVector())
2706 return Error(Loc,"instruction requires integer or integer vector operands");
2708 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2714 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2715 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2716 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2717 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2718 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2720 // Parse the integer/fp comparison predicate.
2724 if (ParseCmpPredicate(Pred, Opc) ||
2725 ParseTypeAndValue(LHS, Loc, PFS) ||
2726 ParseToken(lltok::comma, "expected ',' after compare value") ||
2727 ParseValue(LHS->getType(), RHS, PFS))
2730 if (Opc == Instruction::FCmp) {
2731 if (!LHS->getType()->isFPOrFPVector())
2732 return Error(Loc, "fcmp requires floating point operands");
2733 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2734 } else if (Opc == Instruction::ICmp) {
2735 if (!LHS->getType()->isIntOrIntVector() &&
2736 !isa<PointerType>(LHS->getType()))
2737 return Error(Loc, "icmp requires integer operands");
2738 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2739 } else if (Opc == Instruction::VFCmp) {
2740 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2741 return Error(Loc, "vfcmp requires vector floating point operands");
2742 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2743 } else if (Opc == Instruction::VICmp) {
2744 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2745 return Error(Loc, "vicmp requires vector floating point operands");
2746 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2751 //===----------------------------------------------------------------------===//
2752 // Other Instructions.
2753 //===----------------------------------------------------------------------===//
2757 /// ::= CastOpc TypeAndValue 'to' Type
2758 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2760 LocTy Loc; Value *Op;
2761 PATypeHolder DestTy(Type::VoidTy);
2762 if (ParseTypeAndValue(Op, Loc, PFS) ||
2763 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2767 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy))
2768 return Error(Loc, "invalid cast opcode for cast from '" +
2769 Op->getType()->getDescription() + "' to '" +
2770 DestTy->getDescription() + "'");
2771 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2776 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2777 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2779 Value *Op0, *Op1, *Op2;
2780 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2781 ParseToken(lltok::comma, "expected ',' after select condition") ||
2782 ParseTypeAndValue(Op1, PFS) ||
2783 ParseToken(lltok::comma, "expected ',' after select value") ||
2784 ParseTypeAndValue(Op2, PFS))
2787 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2788 return Error(Loc, Reason);
2790 Inst = SelectInst::Create(Op0, Op1, Op2);
2795 /// ::= 'va_arg' TypeAndValue ',' Type
2796 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2798 PATypeHolder EltTy(Type::VoidTy);
2800 if (ParseTypeAndValue(Op, PFS) ||
2801 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2802 ParseType(EltTy, TypeLoc))
2805 if (!EltTy->isFirstClassType())
2806 return Error(TypeLoc, "va_arg requires operand with first class type");
2808 Inst = new VAArgInst(Op, EltTy);
2812 /// ParseExtractElement
2813 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2814 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2817 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2818 ParseToken(lltok::comma, "expected ',' after extract value") ||
2819 ParseTypeAndValue(Op1, PFS))
2822 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2823 return Error(Loc, "invalid extractelement operands");
2825 Inst = new ExtractElementInst(Op0, Op1);
2829 /// ParseInsertElement
2830 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2831 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2833 Value *Op0, *Op1, *Op2;
2834 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2835 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2836 ParseTypeAndValue(Op1, PFS) ||
2837 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2838 ParseTypeAndValue(Op2, PFS))
2841 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2842 return Error(Loc, "invalid extractelement operands");
2844 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2848 /// ParseShuffleVector
2849 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2850 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2852 Value *Op0, *Op1, *Op2;
2853 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2854 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2855 ParseTypeAndValue(Op1, PFS) ||
2856 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2857 ParseTypeAndValue(Op2, PFS))
2860 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2861 return Error(Loc, "invalid extractelement operands");
2863 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2868 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2869 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2870 PATypeHolder Ty(Type::VoidTy);
2872 LocTy TypeLoc = Lex.getLoc();
2874 if (ParseType(Ty) ||
2875 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2876 ParseValue(Ty, Op0, PFS) ||
2877 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2878 ParseValue(Type::LabelTy, Op1, PFS) ||
2879 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2882 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2884 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2886 if (!EatIfPresent(lltok::comma))
2889 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2890 ParseValue(Ty, Op0, PFS) ||
2891 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2892 ParseValue(Type::LabelTy, Op1, PFS) ||
2893 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2897 if (!Ty->isFirstClassType())
2898 return Error(TypeLoc, "phi node must have first class type");
2900 PHINode *PN = PHINode::Create(Ty);
2901 PN->reserveOperandSpace(PHIVals.size());
2902 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2903 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2909 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2910 /// ParameterList OptionalAttrs
2911 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2913 unsigned CC, RetAttrs, FnAttrs;
2914 PATypeHolder RetType(Type::VoidTy);
2917 SmallVector<ParamInfo, 16> ArgList;
2918 LocTy CallLoc = Lex.getLoc();
2920 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2921 ParseOptionalCallingConv(CC) ||
2922 ParseOptionalAttrs(RetAttrs, 1) ||
2923 ParseType(RetType, RetTypeLoc) ||
2924 ParseValID(CalleeID) ||
2925 ParseParameterList(ArgList, PFS) ||
2926 ParseOptionalAttrs(FnAttrs, 2))
2929 // If RetType is a non-function pointer type, then this is the short syntax
2930 // for the call, which means that RetType is just the return type. Infer the
2931 // rest of the function argument types from the arguments that are present.
2932 const PointerType *PFTy = 0;
2933 const FunctionType *Ty = 0;
2934 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2935 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2936 // Pull out the types of all of the arguments...
2937 std::vector<const Type*> ParamTypes;
2938 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2939 ParamTypes.push_back(ArgList[i].V->getType());
2941 if (!FunctionType::isValidReturnType(RetType))
2942 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2944 Ty = FunctionType::get(RetType, ParamTypes, false);
2945 PFTy = PointerType::getUnqual(Ty);
2948 // Look up the callee.
2950 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2952 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2953 // function attributes.
2954 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2955 if (FnAttrs & ObsoleteFuncAttrs) {
2956 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2957 FnAttrs &= ~ObsoleteFuncAttrs;
2960 // Set up the Attributes for the function.
2961 SmallVector<AttributeWithIndex, 8> Attrs;
2962 if (RetAttrs != Attribute::None)
2963 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2965 SmallVector<Value*, 8> Args;
2967 // Loop through FunctionType's arguments and ensure they are specified
2968 // correctly. Also, gather any parameter attributes.
2969 FunctionType::param_iterator I = Ty->param_begin();
2970 FunctionType::param_iterator E = Ty->param_end();
2971 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2972 const Type *ExpectedTy = 0;
2975 } else if (!Ty->isVarArg()) {
2976 return Error(ArgList[i].Loc, "too many arguments specified");
2979 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2980 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2981 ExpectedTy->getDescription() + "'");
2982 Args.push_back(ArgList[i].V);
2983 if (ArgList[i].Attrs != Attribute::None)
2984 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2988 return Error(CallLoc, "not enough parameters specified for call");
2990 if (FnAttrs != Attribute::None)
2991 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2993 // Finish off the Attributes and check them
2994 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2996 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
2997 CI->setTailCall(isTail);
2998 CI->setCallingConv(CC);
2999 CI->setAttributes(PAL);
3004 //===----------------------------------------------------------------------===//
3005 // Memory Instructions.
3006 //===----------------------------------------------------------------------===//
3009 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3010 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3011 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3013 PATypeHolder Ty(Type::VoidTy);
3016 unsigned Alignment = 0;
3017 if (ParseType(Ty)) return true;
3019 if (EatIfPresent(lltok::comma)) {
3020 if (Lex.getKind() == lltok::kw_align) {
3021 if (ParseOptionalAlignment(Alignment)) return true;
3022 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3023 ParseOptionalCommaAlignment(Alignment)) {
3028 if (Size && Size->getType() != Type::Int32Ty)
3029 return Error(SizeLoc, "element count must be i32");
3031 if (Opc == Instruction::Malloc)
3032 Inst = new MallocInst(Ty, Size, Alignment);
3034 Inst = new AllocaInst(Ty, Size, Alignment);
3039 /// ::= 'free' TypeAndValue
3040 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3041 Value *Val; LocTy Loc;
3042 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3043 if (!isa<PointerType>(Val->getType()))
3044 return Error(Loc, "operand to free must be a pointer");
3045 Inst = new FreeInst(Val);
3050 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3051 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3053 Value *Val; LocTy Loc;
3055 if (ParseTypeAndValue(Val, Loc, PFS) ||
3056 ParseOptionalCommaAlignment(Alignment))
3059 if (!isa<PointerType>(Val->getType()) ||
3060 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3061 return Error(Loc, "load operand must be a pointer to a first class type");
3063 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3068 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3069 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3071 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3073 if (ParseTypeAndValue(Val, Loc, PFS) ||
3074 ParseToken(lltok::comma, "expected ',' after store operand") ||
3075 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3076 ParseOptionalCommaAlignment(Alignment))
3079 if (!isa<PointerType>(Ptr->getType()))
3080 return Error(PtrLoc, "store operand must be a pointer");
3081 if (!Val->getType()->isFirstClassType())
3082 return Error(Loc, "store operand must be a first class value");
3083 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3084 return Error(Loc, "stored value and pointer type do not match");
3086 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3091 /// ::= 'getresult' TypeAndValue ',' uint
3092 /// FIXME: Remove support for getresult in LLVM 3.0
3093 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3094 Value *Val; LocTy ValLoc, EltLoc;
3096 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3097 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3098 ParseUInt32(Element, EltLoc))
3101 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3102 return Error(ValLoc, "getresult inst requires an aggregate operand");
3103 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3104 return Error(EltLoc, "invalid getresult index for value");
3105 Inst = ExtractValueInst::Create(Val, Element);
3109 /// ParseGetElementPtr
3110 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3111 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3112 Value *Ptr, *Val; LocTy Loc, EltLoc;
3113 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3115 if (!isa<PointerType>(Ptr->getType()))
3116 return Error(Loc, "base of getelementptr must be a pointer");
3118 SmallVector<Value*, 16> Indices;
3119 while (EatIfPresent(lltok::comma)) {
3120 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3121 if (!isa<IntegerType>(Val->getType()))
3122 return Error(EltLoc, "getelementptr index must be an integer");
3123 Indices.push_back(Val);
3126 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3127 Indices.begin(), Indices.end()))
3128 return Error(Loc, "invalid getelementptr indices");
3129 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3133 /// ParseExtractValue
3134 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3135 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3136 Value *Val; LocTy Loc;
3137 SmallVector<unsigned, 4> Indices;
3138 if (ParseTypeAndValue(Val, Loc, PFS) ||
3139 ParseIndexList(Indices))
3142 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3143 return Error(Loc, "extractvalue operand must be array or struct");
3145 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3147 return Error(Loc, "invalid indices for extractvalue");
3148 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3152 /// ParseInsertValue
3153 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3154 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3155 Value *Val0, *Val1; LocTy Loc0, Loc1;
3156 SmallVector<unsigned, 4> Indices;
3157 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3158 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3159 ParseTypeAndValue(Val1, Loc1, PFS) ||
3160 ParseIndexList(Indices))
3163 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3164 return Error(Loc0, "extractvalue operand must be array or struct");
3166 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3168 return Error(Loc0, "invalid indices for insertvalue");
3169 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());