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_Constant, // Value in ConstantVal.
40 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
45 std::string StrVal, StrVal2;
48 Constant *ConstantVal;
49 ValID() : APFloatVal(0.0) {}
53 /// Run: module ::= toplevelentity*
54 Module *LLParser::Run() {
55 M = new Module(Lex.getFilename());
60 if (ParseTopLevelEntities() ||
61 ValidateEndOfModule()) {
69 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
71 bool LLParser::ValidateEndOfModule() {
72 if (!ForwardRefTypes.empty())
73 return Error(ForwardRefTypes.begin()->second.second,
74 "use of undefined type named '" +
75 ForwardRefTypes.begin()->first + "'");
76 if (!ForwardRefTypeIDs.empty())
77 return Error(ForwardRefTypeIDs.begin()->second.second,
78 "use of undefined type '%" +
79 utostr(ForwardRefTypeIDs.begin()->first) + "'");
81 if (!ForwardRefVals.empty())
82 return Error(ForwardRefVals.begin()->second.second,
83 "use of undefined value '@" + ForwardRefVals.begin()->first +
86 if (!ForwardRefValIDs.empty())
87 return Error(ForwardRefValIDs.begin()->second.second,
88 "use of undefined value '@" +
89 utostr(ForwardRefValIDs.begin()->first) + "'");
91 // Look for intrinsic functions and CallInst that need to be upgraded
92 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
93 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
98 //===----------------------------------------------------------------------===//
100 //===----------------------------------------------------------------------===//
102 bool LLParser::ParseTopLevelEntities() {
104 switch (Lex.getKind()) {
105 default: return TokError("expected top-level entity");
106 case lltok::Eof: return false;
107 //case lltok::kw_define:
108 case lltok::kw_declare: if (ParseDeclare()) return true; break;
109 case lltok::kw_define: if (ParseDefine()) return true; break;
110 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
111 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
112 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
113 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
114 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
115 case lltok::LocalVar: if (ParseNamedType()) return true; break;
116 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
118 // The Global variable production with no name can have many different
119 // optional leading prefixes, the production is:
120 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
121 // OptionalAddrSpace ('constant'|'global') ...
122 case lltok::kw_internal: // OptionalLinkage
123 case lltok::kw_weak: // OptionalLinkage
124 case lltok::kw_linkonce: // OptionalLinkage
125 case lltok::kw_appending: // OptionalLinkage
126 case lltok::kw_dllexport: // OptionalLinkage
127 case lltok::kw_common: // OptionalLinkage
128 case lltok::kw_dllimport: // OptionalLinkage
129 case lltok::kw_extern_weak: // OptionalLinkage
130 case lltok::kw_external: { // OptionalLinkage
131 unsigned Linkage, Visibility;
132 if (ParseOptionalLinkage(Linkage) ||
133 ParseOptionalVisibility(Visibility) ||
134 ParseGlobal("", 0, Linkage, true, Visibility))
138 case lltok::kw_default: // OptionalVisibility
139 case lltok::kw_hidden: // OptionalVisibility
140 case lltok::kw_protected: { // OptionalVisibility
142 if (ParseOptionalVisibility(Visibility) ||
143 ParseGlobal("", 0, 0, false, Visibility))
148 case lltok::kw_thread_local: // OptionalThreadLocal
149 case lltok::kw_addrspace: // OptionalAddrSpace
150 case lltok::kw_constant: // GlobalType
151 case lltok::kw_global: // GlobalType
152 if (ParseGlobal("", 0, 0, false, 0)) return true;
160 /// ::= 'module' 'asm' STRINGCONSTANT
161 bool LLParser::ParseModuleAsm() {
162 assert(Lex.getKind() == lltok::kw_module);
166 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
167 ParseStringConstant(AsmStr)) return true;
169 const std::string &AsmSoFar = M->getModuleInlineAsm();
170 if (AsmSoFar.empty())
171 M->setModuleInlineAsm(AsmStr);
173 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
178 /// ::= 'target' 'triple' '=' STRINGCONSTANT
179 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
180 bool LLParser::ParseTargetDefinition() {
181 assert(Lex.getKind() == lltok::kw_target);
184 default: return TokError("unknown target property");
185 case lltok::kw_triple:
187 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
188 ParseStringConstant(Str))
190 M->setTargetTriple(Str);
192 case lltok::kw_datalayout:
194 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
195 ParseStringConstant(Str))
197 M->setDataLayout(Str);
203 /// ::= 'deplibs' '=' '[' ']'
204 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
205 bool LLParser::ParseDepLibs() {
206 assert(Lex.getKind() == lltok::kw_deplibs);
208 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
209 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
212 if (EatIfPresent(lltok::rsquare))
216 if (ParseStringConstant(Str)) return true;
219 while (EatIfPresent(lltok::comma)) {
220 if (ParseStringConstant(Str)) return true;
224 return ParseToken(lltok::rsquare, "expected ']' at end of list");
229 bool LLParser::ParseUnnamedType() {
230 assert(Lex.getKind() == lltok::kw_type);
231 LocTy TypeLoc = Lex.getLoc();
232 Lex.Lex(); // eat kw_type
234 PATypeHolder Ty(Type::VoidTy);
235 if (ParseType(Ty)) return true;
237 unsigned TypeID = NumberedTypes.size();
239 // We don't allow assigning names to void type
240 if (Ty == Type::VoidTy)
241 return Error(TypeLoc, "can't assign name to the void type");
243 // See if this type was previously referenced.
244 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
245 FI = ForwardRefTypeIDs.find(TypeID);
246 if (FI != ForwardRefTypeIDs.end()) {
247 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
248 Ty = FI->second.first.get();
249 ForwardRefTypeIDs.erase(FI);
252 NumberedTypes.push_back(Ty);
258 /// ::= LocalVar '=' 'type' type
259 bool LLParser::ParseNamedType() {
260 std::string Name = Lex.getStrVal();
261 LocTy NameLoc = Lex.getLoc();
262 Lex.Lex(); // eat LocalVar.
264 PATypeHolder Ty(Type::VoidTy);
266 if (ParseToken(lltok::equal, "expected '=' after name") ||
267 ParseToken(lltok::kw_type, "expected 'type' after name") ||
271 // We don't allow assigning names to void type
272 if (Ty == Type::VoidTy)
273 return Error(NameLoc, "can't assign name '" + Name + "' to the void type");
275 // Set the type name, checking for conflicts as we do so.
276 bool AlreadyExists = M->addTypeName(Name, Ty);
277 if (!AlreadyExists) return false;
279 // See if this type is a forward reference. We need to eagerly resolve
280 // types to allow recursive type redefinitions below.
281 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
282 FI = ForwardRefTypes.find(Name);
283 if (FI != ForwardRefTypes.end()) {
284 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
285 Ty = FI->second.first.get();
286 ForwardRefTypes.erase(FI);
289 // Inserting a name that is already defined, get the existing name.
290 const Type *Existing = M->getTypeByName(Name);
291 assert(Existing && "Conflict but no matching type?!");
293 // Otherwise, this is an attempt to redefine a type. That's okay if
294 // the redefinition is identical to the original.
295 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
296 if (Existing == Ty) return false;
298 // Any other kind of (non-equivalent) redefinition is an error.
299 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
300 Ty->getDescription() + "'");
305 /// ::= 'declare' FunctionHeader
306 bool LLParser::ParseDeclare() {
307 assert(Lex.getKind() == lltok::kw_declare);
311 return ParseFunctionHeader(F, false);
315 /// ::= 'define' FunctionHeader '{' ...
316 bool LLParser::ParseDefine() {
317 assert(Lex.getKind() == lltok::kw_define);
321 return ParseFunctionHeader(F, true) ||
322 ParseFunctionBody(*F);
328 bool LLParser::ParseGlobalType(bool &IsConstant) {
329 if (Lex.getKind() == lltok::kw_constant)
331 else if (Lex.getKind() == lltok::kw_global)
334 return TokError("expected 'global' or 'constant'");
339 /// ParseNamedGlobal:
340 /// GlobalVar '=' OptionalVisibility ALIAS ...
341 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
342 bool LLParser::ParseNamedGlobal() {
343 assert(Lex.getKind() == lltok::GlobalVar);
344 LocTy NameLoc = Lex.getLoc();
345 std::string Name = Lex.getStrVal();
349 unsigned Linkage, Visibility;
350 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
351 ParseOptionalLinkage(Linkage, HasLinkage) ||
352 ParseOptionalVisibility(Visibility))
355 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
356 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
357 return ParseAlias(Name, NameLoc, Visibility);
361 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
363 /// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
365 /// Everything through visibility has already been parsed.
367 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
368 unsigned Visibility) {
369 assert(Lex.getKind() == lltok::kw_alias);
372 LocTy LinkageLoc = Lex.getLoc();
373 if (ParseOptionalLinkage(Linkage))
376 if (Linkage != GlobalValue::ExternalLinkage &&
377 Linkage != GlobalValue::WeakLinkage &&
378 Linkage != GlobalValue::InternalLinkage)
379 return Error(LinkageLoc, "invalid linkage type for alias");
382 LocTy AliaseeLoc = Lex.getLoc();
383 if (Lex.getKind() != lltok::kw_bitcast) {
384 if (ParseGlobalTypeAndValue(Aliasee)) return true;
386 // The bitcast dest type is not present, it is implied by the dest type.
388 if (ParseValID(ID)) return true;
389 if (ID.Kind != ValID::t_Constant)
390 return Error(AliaseeLoc, "invalid aliasee");
391 Aliasee = ID.ConstantVal;
394 if (!isa<PointerType>(Aliasee->getType()))
395 return Error(AliaseeLoc, "alias must have pointer type");
397 // Okay, create the alias but do not insert it into the module yet.
398 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
399 (GlobalValue::LinkageTypes)Linkage, Name,
401 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
403 // See if this value already exists in the symbol table. If so, it is either
404 // a redefinition or a definition of a forward reference.
405 if (GlobalValue *Val =
406 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
407 // See if this was a redefinition. If so, there is no entry in
409 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
410 I = ForwardRefVals.find(Name);
411 if (I == ForwardRefVals.end())
412 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
414 // Otherwise, this was a definition of forward ref. Verify that types
416 if (Val->getType() != GA->getType())
417 return Error(NameLoc,
418 "forward reference and definition of alias have different types");
420 // If they agree, just RAUW the old value with the alias and remove the
422 Val->replaceAllUsesWith(GA);
423 Val->eraseFromParent();
424 ForwardRefVals.erase(I);
427 // Insert into the module, we know its name won't collide now.
428 M->getAliasList().push_back(GA);
429 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
435 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
436 /// OptionalAddrSpace GlobalType Type Const
437 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
438 /// OptionalAddrSpace GlobalType Type Const
440 /// Everything through visibility has been parsed already.
442 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
443 unsigned Linkage, bool HasLinkage,
444 unsigned Visibility) {
446 bool ThreadLocal, IsConstant;
449 PATypeHolder Ty(Type::VoidTy);
450 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
451 ParseOptionalAddrSpace(AddrSpace) ||
452 ParseGlobalType(IsConstant) ||
453 ParseType(Ty, TyLoc))
456 // If the linkage is specified and is external, then no initializer is
459 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
460 Linkage != GlobalValue::ExternalWeakLinkage &&
461 Linkage != GlobalValue::ExternalLinkage)) {
462 if (ParseGlobalValue(Ty, Init))
466 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
467 return Error(TyLoc, "invald type for global variable");
469 GlobalVariable *GV = 0;
471 // See if the global was forward referenced, if so, use the global.
472 if (!Name.empty() && (GV = M->getGlobalVariable(Name, true))) {
473 if (!ForwardRefVals.erase(Name))
474 return Error(NameLoc, "redefinition of global '@" + Name + "'");
476 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
477 I = ForwardRefValIDs.find(NumberedVals.size());
478 if (I != ForwardRefValIDs.end()) {
479 GV = cast<GlobalVariable>(I->second.first);
480 ForwardRefValIDs.erase(I);
485 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
486 M, false, AddrSpace);
488 if (GV->getType()->getElementType() != Ty)
490 "forward reference and definition of global have different types");
492 // Move the forward-reference to the correct spot in the module.
493 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
497 NumberedVals.push_back(GV);
499 // Set the parsed properties on the global.
501 GV->setInitializer(Init);
502 GV->setConstant(IsConstant);
503 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
504 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
505 GV->setThreadLocal(ThreadLocal);
507 // Parse attributes on the global.
508 while (Lex.getKind() == lltok::comma) {
511 if (Lex.getKind() == lltok::kw_section) {
513 GV->setSection(Lex.getStrVal());
514 if (ParseToken(lltok::StringConstant, "expected global section string"))
516 } else if (Lex.getKind() == lltok::kw_align) {
518 if (ParseOptionalAlignment(Alignment)) return true;
519 GV->setAlignment(Alignment);
521 TokError("unknown global variable property!");
529 //===----------------------------------------------------------------------===//
530 // GlobalValue Reference/Resolution Routines.
531 //===----------------------------------------------------------------------===//
533 /// GetGlobalVal - Get a value with the specified name or ID, creating a
534 /// forward reference record if needed. This can return null if the value
535 /// exists but does not have the right type.
536 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
538 const PointerType *PTy = dyn_cast<PointerType>(Ty);
540 Error(Loc, "global variable reference must have pointer type");
544 // Look this name up in the normal function symbol table.
546 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
548 // If this is a forward reference for the value, see if we already created a
549 // forward ref record.
551 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
552 I = ForwardRefVals.find(Name);
553 if (I != ForwardRefVals.end())
554 Val = I->second.first;
557 // If we have the value in the symbol table or fwd-ref table, return it.
559 if (Val->getType() == Ty) return Val;
560 Error(Loc, "'@" + Name + "' defined with type '" +
561 Val->getType()->getDescription() + "'");
565 // Otherwise, create a new forward reference for this value and remember it.
567 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
568 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
570 FwdVal = new GlobalVariable(PTy->getElementType(), false,
571 GlobalValue::ExternalWeakLinkage, 0, Name, M);
573 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
577 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
578 const PointerType *PTy = dyn_cast<PointerType>(Ty);
580 Error(Loc, "global variable reference must have pointer type");
584 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
586 // If this is a forward reference for the value, see if we already created a
587 // forward ref record.
589 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
590 I = ForwardRefValIDs.find(ID);
591 if (I != ForwardRefValIDs.end())
592 Val = I->second.first;
595 // If we have the value in the symbol table or fwd-ref table, return it.
597 if (Val->getType() == Ty) return Val;
598 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
599 Val->getType()->getDescription() + "'");
603 // Otherwise, create a new forward reference for this value and remember it.
605 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
606 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
608 FwdVal = new GlobalVariable(PTy->getElementType(), false,
609 GlobalValue::ExternalWeakLinkage, 0, "", M);
611 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
616 //===----------------------------------------------------------------------===//
618 //===----------------------------------------------------------------------===//
620 /// ParseToken - If the current token has the specified kind, eat it and return
621 /// success. Otherwise, emit the specified error and return failure.
622 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
623 if (Lex.getKind() != T)
624 return TokError(ErrMsg);
629 /// ParseStringConstant
630 /// ::= StringConstant
631 bool LLParser::ParseStringConstant(std::string &Result) {
632 if (Lex.getKind() != lltok::StringConstant)
633 return TokError("expected string constant");
634 Result = Lex.getStrVal();
641 bool LLParser::ParseUInt32(unsigned &Val) {
642 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
643 return TokError("expected integer");
644 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
645 if (Val64 != unsigned(Val64))
646 return TokError("expected 32-bit integer (too large)");
653 /// ParseOptionalAddrSpace
655 /// := 'addrspace' '(' uint32 ')'
656 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
658 if (!EatIfPresent(lltok::kw_addrspace))
660 return ParseToken(lltok::lparen, "expected '(' in address space") ||
661 ParseUInt32(AddrSpace) ||
662 ParseToken(lltok::rparen, "expected ')' in address space");
665 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
666 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
667 /// 2: function attr.
668 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
669 Attrs = Attribute::None;
670 LocTy AttrLoc = Lex.getLoc();
673 switch (Lex.getKind()) {
676 // Treat these as signext/zeroext unless they are function attrs.
677 // FIXME: REMOVE THIS IN LLVM 3.0
679 if (Lex.getKind() == lltok::kw_sext)
680 Attrs |= Attribute::SExt;
682 Attrs |= Attribute::ZExt;
686 default: // End of attributes.
687 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
688 return Error(AttrLoc, "invalid use of function-only attribute");
690 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
691 return Error(AttrLoc, "invalid use of parameter-only attribute");
694 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
695 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
696 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
697 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
698 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
699 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
700 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
701 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
703 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
704 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
705 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
706 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
707 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
708 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
709 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
710 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
711 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
714 case lltok::kw_align: {
716 if (ParseOptionalAlignment(Alignment))
718 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
726 /// ParseOptionalLinkage
735 /// ::= 'extern_weak'
737 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
739 switch (Lex.getKind()) {
740 default: Res = GlobalValue::ExternalLinkage; return false;
741 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
742 case lltok::kw_weak: Res = GlobalValue::WeakLinkage; break;
743 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceLinkage; break;
744 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
745 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
746 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
747 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
748 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
749 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
756 /// ParseOptionalVisibility
762 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
763 switch (Lex.getKind()) {
764 default: Res = GlobalValue::DefaultVisibility; return false;
765 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
766 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
767 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
773 /// ParseOptionalCallingConv
778 /// ::= 'x86_stdcallcc'
779 /// ::= 'x86_fastcallcc'
782 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
783 switch (Lex.getKind()) {
784 default: CC = CallingConv::C; return false;
785 case lltok::kw_ccc: CC = CallingConv::C; break;
786 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
787 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
788 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
789 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
790 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
796 /// ParseOptionalAlignment
799 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
801 if (!EatIfPresent(lltok::kw_align))
803 return ParseUInt32(Alignment);
806 /// ParseOptionalCommaAlignment
808 /// ::= ',' 'align' 4
809 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
811 if (!EatIfPresent(lltok::comma))
813 return ParseToken(lltok::kw_align, "expected 'align'") ||
814 ParseUInt32(Alignment);
818 /// ::= (',' uint32)+
819 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
820 if (Lex.getKind() != lltok::comma)
821 return TokError("expected ',' as start of index list");
823 while (EatIfPresent(lltok::comma)) {
825 if (ParseUInt32(Idx)) return true;
826 Indices.push_back(Idx);
832 //===----------------------------------------------------------------------===//
834 //===----------------------------------------------------------------------===//
836 /// ParseType - Parse and resolve a full type.
837 bool LLParser::ParseType(PATypeHolder &Result) {
838 if (ParseTypeRec(Result)) return true;
840 // Verify no unresolved uprefs.
842 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
847 /// HandleUpRefs - Every time we finish a new layer of types, this function is
848 /// called. It loops through the UpRefs vector, which is a list of the
849 /// currently active types. For each type, if the up-reference is contained in
850 /// the newly completed type, we decrement the level count. When the level
851 /// count reaches zero, the up-referenced type is the type that is passed in:
852 /// thus we can complete the cycle.
854 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
855 // If Ty isn't abstract, or if there are no up-references in it, then there is
856 // nothing to resolve here.
857 if (!ty->isAbstract() || UpRefs.empty()) return ty;
861 errs() << "Type '" << Ty->getDescription()
862 << "' newly formed. Resolving upreferences.\n"
863 << UpRefs.size() << " upreferences active!\n";
866 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
867 // to zero), we resolve them all together before we resolve them to Ty. At
868 // the end of the loop, if there is anything to resolve to Ty, it will be in
870 OpaqueType *TypeToResolve = 0;
872 for (unsigned i = 0; i != UpRefs.size(); ++i) {
873 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
875 std::find(Ty->subtype_begin(), Ty->subtype_end(),
876 UpRefs[i].LastContainedTy) != Ty->subtype_end();
879 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
880 << UpRefs[i].LastContainedTy->getDescription() << ") = "
881 << (ContainsType ? "true" : "false")
882 << " level=" << UpRefs[i].NestingLevel << "\n";
887 // Decrement level of upreference
888 unsigned Level = --UpRefs[i].NestingLevel;
889 UpRefs[i].LastContainedTy = Ty;
891 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
896 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
899 TypeToResolve = UpRefs[i].UpRefTy;
901 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
902 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
903 --i; // Do not skip the next element.
907 TypeToResolve->refineAbstractTypeTo(Ty);
913 /// ParseTypeRec - The recursive function used to process the internal
914 /// implementation details of types.
915 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
916 switch (Lex.getKind()) {
918 return TokError("expected type");
920 // TypeRec ::= 'float' | 'void' (etc)
921 Result = Lex.getTyVal();
924 case lltok::kw_opaque:
925 // TypeRec ::= 'opaque'
926 Result = OpaqueType::get();
930 // TypeRec ::= '{' ... '}'
931 if (ParseStructType(Result, false))
935 // TypeRec ::= '[' ... ']'
936 Lex.Lex(); // eat the lsquare.
937 if (ParseArrayVectorType(Result, false))
940 case lltok::less: // Either vector or packed struct.
941 // TypeRec ::= '<' ... '>'
943 if (Lex.getKind() == lltok::lbrace) {
944 if (ParseStructType(Result, true) ||
945 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
947 } else if (ParseArrayVectorType(Result, true))
950 case lltok::LocalVar:
951 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
953 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
956 Result = OpaqueType::get();
957 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
958 std::make_pair(Result,
960 M->addTypeName(Lex.getStrVal(), Result.get());
965 case lltok::LocalVarID:
967 if (Lex.getUIntVal() < NumberedTypes.size())
968 Result = NumberedTypes[Lex.getUIntVal()];
970 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
971 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
972 if (I != ForwardRefTypeIDs.end())
973 Result = I->second.first;
975 Result = OpaqueType::get();
976 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
977 std::make_pair(Result,
983 case lltok::backslash: {
987 if (ParseUInt32(Val)) return true;
988 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
989 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
995 // Parse the type suffixes.
997 switch (Lex.getKind()) {
999 default: return false;
1001 // TypeRec ::= TypeRec '*'
1003 if (Result.get() == Type::LabelTy)
1004 return TokError("basic block pointers are invalid");
1005 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1009 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1010 case lltok::kw_addrspace: {
1011 if (Result.get() == Type::LabelTy)
1012 return TokError("basic block pointers are invalid");
1014 if (ParseOptionalAddrSpace(AddrSpace) ||
1015 ParseToken(lltok::star, "expected '*' in address space"))
1018 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1022 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1024 if (ParseFunctionType(Result))
1031 /// ParseParameterList
1033 /// ::= '(' Arg (',' Arg)* ')'
1035 /// ::= Type OptionalAttributes Value OptionalAttributes
1036 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1037 PerFunctionState &PFS) {
1038 if (ParseToken(lltok::lparen, "expected '(' in call"))
1041 while (Lex.getKind() != lltok::rparen) {
1042 // If this isn't the first argument, we need a comma.
1043 if (!ArgList.empty() &&
1044 ParseToken(lltok::comma, "expected ',' in argument list"))
1047 // Parse the argument.
1049 PATypeHolder ArgTy(Type::VoidTy);
1050 unsigned ArgAttrs1, ArgAttrs2;
1052 if (ParseType(ArgTy, ArgLoc) ||
1053 ParseOptionalAttrs(ArgAttrs1, 0) ||
1054 ParseValue(ArgTy, V, PFS) ||
1055 // FIXME: Should not allow attributes after the argument, remove this in
1057 ParseOptionalAttrs(ArgAttrs2, 0))
1059 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1062 Lex.Lex(); // Lex the ')'.
1068 /// ParseArgumentList
1069 /// ::= '(' ArgTypeListI ')'
1073 /// ::= ArgTypeList ',' '...'
1074 /// ::= ArgType (',' ArgType)*
1075 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1078 assert(Lex.getKind() == lltok::lparen);
1079 Lex.Lex(); // eat the (.
1081 if (Lex.getKind() == lltok::rparen) {
1083 } else if (Lex.getKind() == lltok::dotdotdot) {
1087 LocTy TypeLoc = Lex.getLoc();
1088 PATypeHolder ArgTy(Type::VoidTy);
1092 if (ParseTypeRec(ArgTy) ||
1093 ParseOptionalAttrs(Attrs, 0)) return true;
1095 if (Lex.getKind() == lltok::LocalVar ||
1096 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1097 Name = Lex.getStrVal();
1101 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1102 return Error(TypeLoc, "invalid type for function argument");
1104 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1106 while (EatIfPresent(lltok::comma)) {
1107 // Handle ... at end of arg list.
1108 if (EatIfPresent(lltok::dotdotdot)) {
1113 // Otherwise must be an argument type.
1114 TypeLoc = Lex.getLoc();
1115 if (ParseTypeRec(ArgTy) ||
1116 ParseOptionalAttrs(Attrs, 0)) return true;
1118 if (Lex.getKind() == lltok::LocalVar ||
1119 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1120 Name = Lex.getStrVal();
1126 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1127 return Error(TypeLoc, "invalid type for function argument");
1129 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1133 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1136 /// ParseFunctionType
1137 /// ::= Type ArgumentList OptionalAttrs
1138 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1139 assert(Lex.getKind() == lltok::lparen);
1141 std::vector<ArgInfo> ArgList;
1144 if (ParseArgumentList(ArgList, isVarArg) ||
1145 // FIXME: Allow, but ignore attributes on function types!
1146 // FIXME: Remove in LLVM 3.0
1147 ParseOptionalAttrs(Attrs, 2))
1150 // Reject names on the arguments lists.
1151 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1152 if (!ArgList[i].Name.empty())
1153 return Error(ArgList[i].Loc, "argument name invalid in function type");
1154 if (!ArgList[i].Attrs != 0) {
1155 // Allow but ignore attributes on function types; this permits
1157 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1161 std::vector<const Type*> ArgListTy;
1162 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1163 ArgListTy.push_back(ArgList[i].Type);
1165 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1169 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1172 /// ::= '{' TypeRec (',' TypeRec)* '}'
1173 /// ::= '<' '{' '}' '>'
1174 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1175 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1176 assert(Lex.getKind() == lltok::lbrace);
1177 Lex.Lex(); // Consume the '{'
1179 if (EatIfPresent(lltok::rbrace)) {
1180 Result = StructType::get(std::vector<const Type*>(), Packed);
1184 std::vector<PATypeHolder> ParamsList;
1185 if (ParseTypeRec(Result)) return true;
1186 ParamsList.push_back(Result);
1188 while (EatIfPresent(lltok::comma)) {
1189 if (ParseTypeRec(Result)) return true;
1190 ParamsList.push_back(Result);
1193 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1196 std::vector<const Type*> ParamsListTy;
1197 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1198 ParamsListTy.push_back(ParamsList[i].get());
1199 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1203 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1204 /// token has already been consumed.
1206 /// ::= '[' APSINTVAL 'x' Types ']'
1207 /// ::= '<' APSINTVAL 'x' Types '>'
1208 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1209 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1210 Lex.getAPSIntVal().getBitWidth() > 64)
1211 return TokError("expected number in address space");
1213 LocTy SizeLoc = Lex.getLoc();
1214 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1217 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1220 LocTy TypeLoc = Lex.getLoc();
1221 PATypeHolder EltTy(Type::VoidTy);
1222 if (ParseTypeRec(EltTy)) return true;
1224 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1225 "expected end of sequential type"))
1229 if ((unsigned)Size != Size)
1230 return Error(SizeLoc, "size too large for vector");
1231 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1232 return Error(TypeLoc, "vector element type must be fp or integer");
1233 Result = VectorType::get(EltTy, unsigned(Size));
1235 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1236 return Error(TypeLoc, "invalid array element type");
1237 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1242 //===----------------------------------------------------------------------===//
1243 // Function Semantic Analysis.
1244 //===----------------------------------------------------------------------===//
1246 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1249 // Insert unnamed arguments into the NumberedVals list.
1250 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1253 NumberedVals.push_back(AI);
1256 LLParser::PerFunctionState::~PerFunctionState() {
1257 // If there were any forward referenced non-basicblock values, delete them.
1258 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1259 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1260 if (!isa<BasicBlock>(I->second.first)) {
1261 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1263 delete I->second.first;
1264 I->second.first = 0;
1267 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1268 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1269 if (!isa<BasicBlock>(I->second.first)) {
1270 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1272 delete I->second.first;
1273 I->second.first = 0;
1277 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1278 if (!ForwardRefVals.empty())
1279 return P.Error(ForwardRefVals.begin()->second.second,
1280 "use of undefined value '%" + ForwardRefVals.begin()->first +
1282 if (!ForwardRefValIDs.empty())
1283 return P.Error(ForwardRefValIDs.begin()->second.second,
1284 "use of undefined value '%" +
1285 utostr(ForwardRefValIDs.begin()->first) + "'");
1290 /// GetVal - Get a value with the specified name or ID, creating a
1291 /// forward reference record if needed. This can return null if the value
1292 /// exists but does not have the right type.
1293 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1294 const Type *Ty, LocTy Loc) {
1295 // Look this name up in the normal function symbol table.
1296 Value *Val = F.getValueSymbolTable().lookup(Name);
1298 // If this is a forward reference for the value, see if we already created a
1299 // forward ref record.
1301 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1302 I = ForwardRefVals.find(Name);
1303 if (I != ForwardRefVals.end())
1304 Val = I->second.first;
1307 // If we have the value in the symbol table or fwd-ref table, return it.
1309 if (Val->getType() == Ty) return Val;
1310 if (Ty == Type::LabelTy)
1311 P.Error(Loc, "'%" + Name + "' is not a basic block");
1313 P.Error(Loc, "'%" + Name + "' defined with type '" +
1314 Val->getType()->getDescription() + "'");
1318 // Don't make placeholders with invalid type.
1319 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1320 P.Error(Loc, "invalid use of a non-first-class type");
1324 // Otherwise, create a new forward reference for this value and remember it.
1326 if (Ty == Type::LabelTy)
1327 FwdVal = BasicBlock::Create(Name, &F);
1329 FwdVal = new Argument(Ty, Name);
1331 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1335 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1337 // Look this name up in the normal function symbol table.
1338 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1340 // If this is a forward reference for the value, see if we already created a
1341 // forward ref record.
1343 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1344 I = ForwardRefValIDs.find(ID);
1345 if (I != ForwardRefValIDs.end())
1346 Val = I->second.first;
1349 // If we have the value in the symbol table or fwd-ref table, return it.
1351 if (Val->getType() == Ty) return Val;
1352 if (Ty == Type::LabelTy)
1353 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1355 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1356 Val->getType()->getDescription() + "'");
1360 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1361 P.Error(Loc, "invalid use of a non-first-class type");
1365 // Otherwise, create a new forward reference for this value and remember it.
1367 if (Ty == Type::LabelTy)
1368 FwdVal = BasicBlock::Create("", &F);
1370 FwdVal = new Argument(Ty);
1372 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1376 /// SetInstName - After an instruction is parsed and inserted into its
1377 /// basic block, this installs its name.
1378 bool LLParser::PerFunctionState::SetInstName(int NameID,
1379 const std::string &NameStr,
1380 LocTy NameLoc, Instruction *Inst) {
1381 // If this instruction has void type, it cannot have a name or ID specified.
1382 if (Inst->getType() == Type::VoidTy) {
1383 if (NameID != -1 || !NameStr.empty())
1384 return P.Error(NameLoc, "instructions returning void cannot have a name");
1388 // If this was a numbered instruction, verify that the instruction is the
1389 // expected value and resolve any forward references.
1390 if (NameStr.empty()) {
1391 // If neither a name nor an ID was specified, just use the next ID.
1393 NameID = NumberedVals.size();
1395 if (unsigned(NameID) != NumberedVals.size())
1396 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1397 utostr(NumberedVals.size()) + "'");
1399 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1400 ForwardRefValIDs.find(NameID);
1401 if (FI != ForwardRefValIDs.end()) {
1402 if (FI->second.first->getType() != Inst->getType())
1403 return P.Error(NameLoc, "instruction forward referenced with type '" +
1404 FI->second.first->getType()->getDescription() + "'");
1405 FI->second.first->replaceAllUsesWith(Inst);
1406 ForwardRefValIDs.erase(FI);
1409 NumberedVals.push_back(Inst);
1413 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1414 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1415 FI = ForwardRefVals.find(NameStr);
1416 if (FI != ForwardRefVals.end()) {
1417 if (FI->second.first->getType() != Inst->getType())
1418 return P.Error(NameLoc, "instruction forward referenced with type '" +
1419 FI->second.first->getType()->getDescription() + "'");
1420 FI->second.first->replaceAllUsesWith(Inst);
1421 ForwardRefVals.erase(FI);
1424 // Set the name on the instruction.
1425 Inst->setName(NameStr);
1427 if (Inst->getNameStr() != NameStr)
1428 return P.Error(NameLoc, "multiple definition of local value named '" +
1433 /// GetBB - Get a basic block with the specified name or ID, creating a
1434 /// forward reference record if needed.
1435 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1437 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1440 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1441 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1444 /// DefineBB - Define the specified basic block, which is either named or
1445 /// unnamed. If there is an error, this returns null otherwise it returns
1446 /// the block being defined.
1447 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1451 BB = GetBB(NumberedVals.size(), Loc);
1453 BB = GetBB(Name, Loc);
1454 if (BB == 0) return 0; // Already diagnosed error.
1456 // Move the block to the end of the function. Forward ref'd blocks are
1457 // inserted wherever they happen to be referenced.
1458 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1460 // Remove the block from forward ref sets.
1462 ForwardRefValIDs.erase(NumberedVals.size());
1463 NumberedVals.push_back(BB);
1465 // BB forward references are already in the function symbol table.
1466 ForwardRefVals.erase(Name);
1472 //===----------------------------------------------------------------------===//
1474 //===----------------------------------------------------------------------===//
1476 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1477 /// type implied. For example, if we parse "4" we don't know what integer type
1478 /// it has. The value will later be combined with its type and checked for
1480 bool LLParser::ParseValID(ValID &ID) {
1481 ID.Loc = Lex.getLoc();
1482 switch (Lex.getKind()) {
1483 default: return TokError("expected value token");
1484 case lltok::GlobalID: // @42
1485 ID.UIntVal = Lex.getUIntVal();
1486 ID.Kind = ValID::t_GlobalID;
1488 case lltok::GlobalVar: // @foo
1489 ID.StrVal = Lex.getStrVal();
1490 ID.Kind = ValID::t_GlobalName;
1492 case lltok::LocalVarID: // %42
1493 ID.UIntVal = Lex.getUIntVal();
1494 ID.Kind = ValID::t_LocalID;
1496 case lltok::LocalVar: // %foo
1497 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1498 ID.StrVal = Lex.getStrVal();
1499 ID.Kind = ValID::t_LocalName;
1502 ID.APSIntVal = Lex.getAPSIntVal();
1503 ID.Kind = ValID::t_APSInt;
1505 case lltok::APFloat:
1506 ID.APFloatVal = Lex.getAPFloatVal();
1507 ID.Kind = ValID::t_APFloat;
1509 case lltok::kw_true:
1510 ID.ConstantVal = ConstantInt::getTrue();
1511 ID.Kind = ValID::t_Constant;
1513 case lltok::kw_false:
1514 ID.ConstantVal = ConstantInt::getFalse();
1515 ID.Kind = ValID::t_Constant;
1517 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1518 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1519 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1521 case lltok::lbrace: {
1522 // ValID ::= '{' ConstVector '}'
1524 SmallVector<Constant*, 16> Elts;
1525 if (ParseGlobalValueVector(Elts) ||
1526 ParseToken(lltok::rbrace, "expected end of struct constant"))
1529 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1530 ID.Kind = ValID::t_Constant;
1534 // ValID ::= '<' ConstVector '>' --> Vector.
1535 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1537 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1539 SmallVector<Constant*, 16> Elts;
1540 LocTy FirstEltLoc = Lex.getLoc();
1541 if (ParseGlobalValueVector(Elts) ||
1543 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1544 ParseToken(lltok::greater, "expected end of constant"))
1547 if (isPackedStruct) {
1548 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1549 ID.Kind = ValID::t_Constant;
1554 return Error(ID.Loc, "constant vector must not be empty");
1556 if (!Elts[0]->getType()->isInteger() &&
1557 !Elts[0]->getType()->isFloatingPoint())
1558 return Error(FirstEltLoc,
1559 "vector elements must have integer or floating point type");
1561 // Verify that all the vector elements have the same type.
1562 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1563 if (Elts[i]->getType() != Elts[0]->getType())
1564 return Error(FirstEltLoc,
1565 "vector element #" + utostr(i) +
1566 " is not of type '" + Elts[0]->getType()->getDescription());
1568 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1569 ID.Kind = ValID::t_Constant;
1572 case lltok::lsquare: { // Array Constant
1574 SmallVector<Constant*, 16> Elts;
1575 LocTy FirstEltLoc = Lex.getLoc();
1576 if (ParseGlobalValueVector(Elts) ||
1577 ParseToken(lltok::rsquare, "expected end of array constant"))
1580 // Handle empty element.
1582 // Use undef instead of an array because it's inconvenient to determine
1583 // the element type at this point, there being no elements to examine.
1584 ID.Kind = ValID::t_Undef;
1588 if (!Elts[0]->getType()->isFirstClassType())
1589 return Error(FirstEltLoc, "invalid array element type: " +
1590 Elts[0]->getType()->getDescription());
1592 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1594 // Verify all elements are correct type!
1595 for (unsigned i = i, e = Elts.size() ; i != e; ++i) {
1596 if (Elts[i]->getType() != Elts[0]->getType())
1597 return Error(FirstEltLoc,
1598 "array element #" + utostr(i) +
1599 " is not of type '" +Elts[0]->getType()->getDescription());
1602 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1603 ID.Kind = ValID::t_Constant;
1606 case lltok::kw_c: // c "foo"
1608 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1609 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1610 ID.Kind = ValID::t_Constant;
1613 case lltok::kw_asm: {
1614 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1617 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1618 ParseStringConstant(ID.StrVal) ||
1619 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1620 ParseToken(lltok::StringConstant, "expected constraint string"))
1622 ID.StrVal2 = Lex.getStrVal();
1623 ID.UIntVal = HasSideEffect;
1624 ID.Kind = ValID::t_InlineAsm;
1628 case lltok::kw_trunc:
1629 case lltok::kw_zext:
1630 case lltok::kw_sext:
1631 case lltok::kw_fptrunc:
1632 case lltok::kw_fpext:
1633 case lltok::kw_bitcast:
1634 case lltok::kw_uitofp:
1635 case lltok::kw_sitofp:
1636 case lltok::kw_fptoui:
1637 case lltok::kw_fptosi:
1638 case lltok::kw_inttoptr:
1639 case lltok::kw_ptrtoint: {
1640 unsigned Opc = Lex.getUIntVal();
1641 PATypeHolder DestTy(Type::VoidTy);
1644 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1645 ParseGlobalTypeAndValue(SrcVal) ||
1646 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1647 ParseType(DestTy) ||
1648 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1650 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1651 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1652 SrcVal->getType()->getDescription() + "' to '" +
1653 DestTy->getDescription() + "'");
1654 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1656 ID.Kind = ValID::t_Constant;
1659 case lltok::kw_extractvalue: {
1662 SmallVector<unsigned, 4> Indices;
1663 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1664 ParseGlobalTypeAndValue(Val) ||
1665 ParseIndexList(Indices) ||
1666 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1668 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1669 return Error(ID.Loc, "extractvalue operand must be array or struct");
1670 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1672 return Error(ID.Loc, "invalid indices for extractvalue");
1673 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1674 &Indices[0], Indices.size());
1675 ID.Kind = ValID::t_Constant;
1678 case lltok::kw_insertvalue: {
1680 Constant *Val0, *Val1;
1681 SmallVector<unsigned, 4> Indices;
1682 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1683 ParseGlobalTypeAndValue(Val0) ||
1684 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1685 ParseGlobalTypeAndValue(Val1) ||
1686 ParseIndexList(Indices) ||
1687 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1689 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1690 return Error(ID.Loc, "extractvalue operand must be array or struct");
1691 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1693 return Error(ID.Loc, "invalid indices for insertvalue");
1694 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1695 &Indices[0], Indices.size());
1696 ID.Kind = ValID::t_Constant;
1699 case lltok::kw_icmp:
1700 case lltok::kw_fcmp:
1701 case lltok::kw_vicmp:
1702 case lltok::kw_vfcmp: {
1703 unsigned PredVal, Opc = Lex.getUIntVal();
1704 Constant *Val0, *Val1;
1706 if (ParseCmpPredicate(PredVal, Opc) ||
1707 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1708 ParseGlobalTypeAndValue(Val0) ||
1709 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1710 ParseGlobalTypeAndValue(Val1) ||
1711 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1714 if (Val0->getType() != Val1->getType())
1715 return Error(ID.Loc, "compare operands must have the same type");
1717 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1719 if (Opc == Instruction::FCmp) {
1720 if (!Val0->getType()->isFPOrFPVector())
1721 return Error(ID.Loc, "fcmp requires floating point operands");
1722 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1723 } else if (Opc == Instruction::ICmp) {
1724 if (!Val0->getType()->isIntOrIntVector() &&
1725 !isa<PointerType>(Val0->getType()))
1726 return Error(ID.Loc, "icmp requires pointer or integer operands");
1727 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1728 } else if (Opc == Instruction::VFCmp) {
1729 // FIXME: REMOVE VFCMP Support
1730 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1731 } else if (Opc == Instruction::VICmp) {
1732 // FIXME: REMOVE VFCMP Support
1733 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1735 ID.Kind = ValID::t_Constant;
1739 // Binary Operators.
1743 case lltok::kw_udiv:
1744 case lltok::kw_sdiv:
1745 case lltok::kw_fdiv:
1746 case lltok::kw_urem:
1747 case lltok::kw_srem:
1748 case lltok::kw_frem: {
1749 unsigned Opc = Lex.getUIntVal();
1750 Constant *Val0, *Val1;
1752 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1753 ParseGlobalTypeAndValue(Val0) ||
1754 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1755 ParseGlobalTypeAndValue(Val1) ||
1756 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1758 if (Val0->getType() != Val1->getType())
1759 return Error(ID.Loc, "operands of constexpr must have same type");
1760 if (!Val0->getType()->isIntOrIntVector() &&
1761 !Val0->getType()->isFPOrFPVector())
1762 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1763 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1764 ID.Kind = ValID::t_Constant;
1768 // Logical Operations
1770 case lltok::kw_lshr:
1771 case lltok::kw_ashr:
1774 case lltok::kw_xor: {
1775 unsigned Opc = Lex.getUIntVal();
1776 Constant *Val0, *Val1;
1778 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1779 ParseGlobalTypeAndValue(Val0) ||
1780 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1781 ParseGlobalTypeAndValue(Val1) ||
1782 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1784 if (Val0->getType() != Val1->getType())
1785 return Error(ID.Loc, "operands of constexpr must have same type");
1786 if (!Val0->getType()->isIntOrIntVector())
1787 return Error(ID.Loc,
1788 "constexpr requires integer or integer vector operands");
1789 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1790 ID.Kind = ValID::t_Constant;
1794 case lltok::kw_getelementptr:
1795 case lltok::kw_shufflevector:
1796 case lltok::kw_insertelement:
1797 case lltok::kw_extractelement:
1798 case lltok::kw_select: {
1799 unsigned Opc = Lex.getUIntVal();
1800 SmallVector<Constant*, 16> Elts;
1802 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1803 ParseGlobalValueVector(Elts) ||
1804 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1807 if (Opc == Instruction::GetElementPtr) {
1808 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1809 return Error(ID.Loc, "getelementptr requires pointer operand");
1811 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1812 (Value**)&Elts[1], Elts.size()-1))
1813 return Error(ID.Loc, "invalid indices for getelementptr");
1814 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1815 &Elts[1], Elts.size()-1);
1816 } else if (Opc == Instruction::Select) {
1817 if (Elts.size() != 3)
1818 return Error(ID.Loc, "expected three operands to select");
1819 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1821 return Error(ID.Loc, Reason);
1822 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1823 } else if (Opc == Instruction::ShuffleVector) {
1824 if (Elts.size() != 3)
1825 return Error(ID.Loc, "expected three operands to shufflevector");
1826 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1827 return Error(ID.Loc, "invalid operands to shufflevector");
1828 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1829 } else if (Opc == Instruction::ExtractElement) {
1830 if (Elts.size() != 2)
1831 return Error(ID.Loc, "expected two operands to extractelement");
1832 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1833 return Error(ID.Loc, "invalid extractelement operands");
1834 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1836 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1837 if (Elts.size() != 3)
1838 return Error(ID.Loc, "expected three operands to insertelement");
1839 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1840 return Error(ID.Loc, "invalid insertelement operands");
1841 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1844 ID.Kind = ValID::t_Constant;
1853 /// ParseGlobalValue - Parse a global value with the specified type.
1854 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1857 return ParseValID(ID) ||
1858 ConvertGlobalValIDToValue(Ty, ID, V);
1861 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1863 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1865 if (isa<FunctionType>(Ty))
1866 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1869 default: assert(0 && "Unknown ValID!");
1870 case ValID::t_LocalID:
1871 case ValID::t_LocalName:
1872 return Error(ID.Loc, "invalid use of function-local name");
1873 case ValID::t_InlineAsm:
1874 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1875 case ValID::t_GlobalName:
1876 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1878 case ValID::t_GlobalID:
1879 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1881 case ValID::t_APSInt:
1882 if (!isa<IntegerType>(Ty))
1883 return Error(ID.Loc, "integer constant must have integer type");
1884 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1885 V = ConstantInt::get(ID.APSIntVal);
1887 case ValID::t_APFloat:
1888 if (!Ty->isFloatingPoint() ||
1889 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1890 return Error(ID.Loc, "floating point constant invalid for type");
1892 // The lexer has no type info, so builds all float and double FP constants
1893 // as double. Fix this here. Long double does not need this.
1894 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1895 Ty == Type::FloatTy) {
1897 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1900 V = ConstantFP::get(ID.APFloatVal);
1903 if (!isa<PointerType>(Ty))
1904 return Error(ID.Loc, "null must be a pointer type");
1905 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1907 case ValID::t_Undef:
1908 V = UndefValue::get(Ty);
1911 if (!Ty->isFirstClassType())
1912 return Error(ID.Loc, "invalid type for null constant");
1913 V = Constant::getNullValue(Ty);
1915 case ValID::t_Constant:
1916 if (ID.ConstantVal->getType() != Ty)
1917 return Error(ID.Loc, "constant expression type mismatch");
1923 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
1924 PATypeHolder Type(Type::VoidTy);
1925 return ParseType(Type) ||
1926 ParseGlobalValue(Type, V);
1929 /// ParseGlobalValueVector
1931 /// ::= TypeAndValue (',' TypeAndValue)*
1932 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
1934 if (Lex.getKind() == lltok::rbrace ||
1935 Lex.getKind() == lltok::rsquare ||
1936 Lex.getKind() == lltok::greater ||
1937 Lex.getKind() == lltok::rparen)
1941 if (ParseGlobalTypeAndValue(C)) return true;
1944 while (EatIfPresent(lltok::comma)) {
1945 if (ParseGlobalTypeAndValue(C)) return true;
1953 //===----------------------------------------------------------------------===//
1954 // Function Parsing.
1955 //===----------------------------------------------------------------------===//
1957 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
1958 PerFunctionState &PFS) {
1959 if (ID.Kind == ValID::t_LocalID)
1960 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
1961 else if (ID.Kind == ValID::t_LocalName)
1962 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
1963 else if (ID.Kind == ValID::ValID::t_InlineAsm) {
1964 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1965 const FunctionType *FTy =
1966 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1967 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
1968 return Error(ID.Loc, "invalid type for inline asm constraint string");
1969 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
1973 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
1981 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
1984 return ParseValID(ID) ||
1985 ConvertValIDToValue(Ty, ID, V, PFS);
1988 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
1989 PATypeHolder T(Type::VoidTy);
1990 return ParseType(T) ||
1991 ParseValue(T, V, PFS);
1995 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
1996 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
1997 /// OptionalAlign OptGC
1998 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
1999 // Parse the linkage.
2000 LocTy LinkageLoc = Lex.getLoc();
2003 unsigned Visibility, CC, RetAttrs;
2004 PATypeHolder RetType(Type::VoidTy);
2005 LocTy RetTypeLoc = Lex.getLoc();
2006 if (ParseOptionalLinkage(Linkage) ||
2007 ParseOptionalVisibility(Visibility) ||
2008 ParseOptionalCallingConv(CC) ||
2009 ParseOptionalAttrs(RetAttrs, 1) ||
2010 ParseType(RetType, RetTypeLoc))
2013 // Verify that the linkage is ok.
2014 switch ((GlobalValue::LinkageTypes)Linkage) {
2015 case GlobalValue::ExternalLinkage:
2016 break; // always ok.
2017 case GlobalValue::DLLImportLinkage:
2018 case GlobalValue::ExternalWeakLinkage:
2020 return Error(LinkageLoc, "invalid linkage for function definition");
2022 case GlobalValue::InternalLinkage:
2023 case GlobalValue::LinkOnceLinkage:
2024 case GlobalValue::WeakLinkage:
2025 case GlobalValue::DLLExportLinkage:
2027 return Error(LinkageLoc, "invalid linkage for function declaration");
2029 case GlobalValue::AppendingLinkage:
2030 case GlobalValue::GhostLinkage:
2031 case GlobalValue::CommonLinkage:
2032 return Error(LinkageLoc, "invalid function linkage type");
2035 if (!FunctionType::isValidReturnType(RetType))
2036 return Error(RetTypeLoc, "invalid function return type");
2038 if (Lex.getKind() != lltok::GlobalVar)
2039 return TokError("expected function name");
2041 LocTy NameLoc = Lex.getLoc();
2042 std::string FunctionName = Lex.getStrVal();
2045 if (Lex.getKind() != lltok::lparen)
2046 return TokError("expected '(' in function argument list");
2048 std::vector<ArgInfo> ArgList;
2051 std::string Section;
2055 if (ParseArgumentList(ArgList, isVarArg) ||
2056 ParseOptionalAttrs(FuncAttrs, 2) ||
2057 (EatIfPresent(lltok::kw_section) &&
2058 ParseStringConstant(Section)) ||
2059 ParseOptionalAlignment(Alignment) ||
2060 (EatIfPresent(lltok::kw_gc) &&
2061 ParseStringConstant(GC)))
2064 // If the alignment was parsed as an attribute, move to the alignment field.
2065 if (FuncAttrs & Attribute::Alignment) {
2066 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2067 FuncAttrs &= ~Attribute::Alignment;
2070 // Okay, if we got here, the function is syntactically valid. Convert types
2071 // and do semantic checks.
2072 std::vector<const Type*> ParamTypeList;
2073 SmallVector<AttributeWithIndex, 8> Attrs;
2074 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2076 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2077 if (FuncAttrs & ObsoleteFuncAttrs) {
2078 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2079 FuncAttrs &= ~ObsoleteFuncAttrs;
2082 if (RetAttrs != Attribute::None)
2083 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2085 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2086 ParamTypeList.push_back(ArgList[i].Type);
2087 if (ArgList[i].Attrs != Attribute::None)
2088 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2091 if (FuncAttrs != Attribute::None)
2092 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2094 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2096 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2097 const PointerType *PFT = PointerType::getUnqual(FT);
2100 if (!FunctionName.empty()) {
2101 // If this was a definition of a forward reference, remove the definition
2102 // from the forward reference table and fill in the forward ref.
2103 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2104 ForwardRefVals.find(FunctionName);
2105 if (FRVI != ForwardRefVals.end()) {
2106 Fn = M->getFunction(FunctionName);
2107 ForwardRefVals.erase(FRVI);
2108 } else if ((Fn = M->getFunction(FunctionName))) {
2109 // If this function already exists in the symbol table, then it is
2110 // multiply defined. We accept a few cases for old backwards compat.
2111 // FIXME: Remove this stuff for LLVM 3.0.
2112 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2113 (!Fn->isDeclaration() && isDefine)) {
2114 // If the redefinition has different type or different attributes,
2115 // reject it. If both have bodies, reject it.
2116 return Error(NameLoc, "invalid redefinition of function '" +
2117 FunctionName + "'");
2118 } else if (Fn->isDeclaration()) {
2119 // Make sure to strip off any argument names so we can't get conflicts.
2120 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2126 } else if (FunctionName.empty()) {
2127 // If this is a definition of a forward referenced function, make sure the
2129 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2130 = ForwardRefValIDs.find(NumberedVals.size());
2131 if (I != ForwardRefValIDs.end()) {
2132 Fn = cast<Function>(I->second.first);
2133 if (Fn->getType() != PFT)
2134 return Error(NameLoc, "type of definition and forward reference of '@" +
2135 utostr(NumberedVals.size()) +"' disagree");
2136 ForwardRefValIDs.erase(I);
2141 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2142 else // Move the forward-reference to the correct spot in the module.
2143 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2145 if (FunctionName.empty())
2146 NumberedVals.push_back(Fn);
2148 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2149 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2150 Fn->setCallingConv(CC);
2151 Fn->setAttributes(PAL);
2152 Fn->setAlignment(Alignment);
2153 Fn->setSection(Section);
2154 if (!GC.empty()) Fn->setGC(GC.c_str());
2156 // Add all of the arguments we parsed to the function.
2157 Function::arg_iterator ArgIt = Fn->arg_begin();
2158 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2159 // If the argument has a name, insert it into the argument symbol table.
2160 if (ArgList[i].Name.empty()) continue;
2162 // Set the name, if it conflicted, it will be auto-renamed.
2163 ArgIt->setName(ArgList[i].Name);
2165 if (ArgIt->getNameStr() != ArgList[i].Name)
2166 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2167 ArgList[i].Name + "'");
2174 /// ParseFunctionBody
2175 /// ::= '{' BasicBlock+ '}'
2176 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2178 bool LLParser::ParseFunctionBody(Function &Fn) {
2179 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2180 return TokError("expected '{' in function body");
2181 Lex.Lex(); // eat the {.
2183 PerFunctionState PFS(*this, Fn);
2185 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2186 if (ParseBasicBlock(PFS)) return true;
2191 // Verify function is ok.
2192 return PFS.VerifyFunctionComplete();
2196 /// ::= LabelStr? Instruction*
2197 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2198 // If this basic block starts out with a name, remember it.
2200 LocTy NameLoc = Lex.getLoc();
2201 if (Lex.getKind() == lltok::LabelStr) {
2202 Name = Lex.getStrVal();
2206 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2207 if (BB == 0) return true;
2209 std::string NameStr;
2211 // Parse the instructions in this block until we get a terminator.
2214 // This instruction may have three possibilities for a name: a) none
2215 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2216 LocTy NameLoc = Lex.getLoc();
2220 if (Lex.getKind() == lltok::LocalVarID) {
2221 NameID = Lex.getUIntVal();
2223 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2225 } else if (Lex.getKind() == lltok::LocalVar ||
2226 // FIXME: REMOVE IN LLVM 3.0
2227 Lex.getKind() == lltok::StringConstant) {
2228 NameStr = Lex.getStrVal();
2230 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2234 if (ParseInstruction(Inst, BB, PFS)) return true;
2236 BB->getInstList().push_back(Inst);
2238 // Set the name on the instruction.
2239 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2240 } while (!isa<TerminatorInst>(Inst));
2245 //===----------------------------------------------------------------------===//
2246 // Instruction Parsing.
2247 //===----------------------------------------------------------------------===//
2249 /// ParseInstruction - Parse one of the many different instructions.
2251 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2252 PerFunctionState &PFS) {
2253 lltok::Kind Token = Lex.getKind();
2254 if (Token == lltok::Eof)
2255 return TokError("found end of file when expecting more instructions");
2256 LocTy Loc = Lex.getLoc();
2257 Lex.Lex(); // Eat the keyword.
2260 default: return Error(Loc, "expected instruction opcode");
2261 // Terminator Instructions.
2262 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2263 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2264 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2265 case lltok::kw_br: return ParseBr(Inst, PFS);
2266 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2267 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2268 // Binary Operators.
2272 case lltok::kw_udiv:
2273 case lltok::kw_sdiv:
2274 case lltok::kw_fdiv:
2275 case lltok::kw_urem:
2276 case lltok::kw_srem:
2277 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal());
2279 case lltok::kw_lshr:
2280 case lltok::kw_ashr:
2283 case lltok::kw_xor: return ParseLogical(Inst, PFS, Lex.getUIntVal());
2284 case lltok::kw_icmp:
2285 case lltok::kw_fcmp:
2286 case lltok::kw_vicmp:
2287 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, Lex.getUIntVal());
2289 case lltok::kw_trunc:
2290 case lltok::kw_zext:
2291 case lltok::kw_sext:
2292 case lltok::kw_fptrunc:
2293 case lltok::kw_fpext:
2294 case lltok::kw_bitcast:
2295 case lltok::kw_uitofp:
2296 case lltok::kw_sitofp:
2297 case lltok::kw_fptoui:
2298 case lltok::kw_fptosi:
2299 case lltok::kw_inttoptr:
2300 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, Lex.getUIntVal());
2302 case lltok::kw_select: return ParseSelect(Inst, PFS);
2303 case lltok::kw_va_arg: return ParseVAArg(Inst, PFS);
2304 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2305 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2306 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2307 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2308 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2309 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2311 case lltok::kw_alloca:
2312 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, Lex.getUIntVal());
2313 case lltok::kw_free: return ParseFree(Inst, PFS);
2314 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2315 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2316 case lltok::kw_volatile:
2317 if (EatIfPresent(lltok::kw_load))
2318 return ParseLoad(Inst, PFS, true);
2319 else if (EatIfPresent(lltok::kw_store))
2320 return ParseStore(Inst, PFS, true);
2322 return TokError("expected 'load' or 'store'");
2323 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2324 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2325 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2326 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2330 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2331 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2332 // FIXME: REMOVE vicmp/vfcmp!
2333 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2334 switch (Lex.getKind()) {
2335 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2336 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2337 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2338 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2339 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2340 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2341 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2342 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2343 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2344 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2345 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2346 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2347 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2348 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2349 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2350 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2351 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2354 switch (Lex.getKind()) {
2355 default: TokError("expected icmp predicate (e.g. 'eq')");
2356 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2357 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2358 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2359 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2360 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2361 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2362 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2363 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2364 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2365 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2372 //===----------------------------------------------------------------------===//
2373 // Terminator Instructions.
2374 //===----------------------------------------------------------------------===//
2376 /// ParseRet - Parse a return instruction.
2378 /// ::= 'ret' TypeAndValue
2379 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2380 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2381 PerFunctionState &PFS) {
2382 PATypeHolder Ty(Type::VoidTy);
2383 if (ParseType(Ty)) return true;
2385 if (Ty == Type::VoidTy) {
2386 Inst = ReturnInst::Create();
2391 if (ParseValue(Ty, RV, PFS)) return true;
2393 // The normal case is one return value.
2394 if (Lex.getKind() == lltok::comma) {
2395 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2396 // of 'ret {i32,i32} {i32 1, i32 2}'
2397 SmallVector<Value*, 8> RVs;
2400 while (EatIfPresent(lltok::comma)) {
2401 if (ParseTypeAndValue(RV, PFS)) return true;
2405 RV = UndefValue::get(PFS.getFunction().getReturnType());
2406 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2407 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2408 BB->getInstList().push_back(I);
2412 Inst = ReturnInst::Create(RV);
2418 /// ::= 'br' TypeAndValue
2419 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2420 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2422 Value *Op0, *Op1, *Op2;
2423 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2425 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2426 Inst = BranchInst::Create(BB);
2430 if (Op0->getType() != Type::Int1Ty)
2431 return Error(Loc, "branch condition must have 'i1' type");
2433 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2434 ParseTypeAndValue(Op1, Loc, PFS) ||
2435 ParseToken(lltok::comma, "expected ',' after true destination") ||
2436 ParseTypeAndValue(Op2, Loc2, PFS))
2439 if (!isa<BasicBlock>(Op1))
2440 return Error(Loc, "true destination of branch must be a basic block");
2441 if (!isa<BasicBlock>(Op2))
2442 return Error(Loc2, "true destination of branch must be a basic block");
2444 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2450 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2452 /// ::= (TypeAndValue ',' TypeAndValue)*
2453 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2454 LocTy CondLoc, BBLoc;
2455 Value *Cond, *DefaultBB;
2456 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2457 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2458 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2459 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2462 if (!isa<IntegerType>(Cond->getType()))
2463 return Error(CondLoc, "switch condition must have integer type");
2464 if (!isa<BasicBlock>(DefaultBB))
2465 return Error(BBLoc, "default destination must be a basic block");
2467 // Parse the jump table pairs.
2468 SmallPtrSet<Value*, 32> SeenCases;
2469 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2470 while (Lex.getKind() != lltok::rsquare) {
2471 Value *Constant, *DestBB;
2473 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2474 ParseToken(lltok::comma, "expected ',' after case value") ||
2475 ParseTypeAndValue(DestBB, BBLoc, PFS))
2478 if (!SeenCases.insert(Constant))
2479 return Error(CondLoc, "duplicate case value in switch");
2480 if (!isa<ConstantInt>(Constant))
2481 return Error(CondLoc, "case value is not a constant integer");
2482 if (!isa<BasicBlock>(DestBB))
2483 return Error(BBLoc, "case destination is not a basic block");
2485 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2486 cast<BasicBlock>(DestBB)));
2489 Lex.Lex(); // Eat the ']'.
2491 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2493 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2494 SI->addCase(Table[i].first, Table[i].second);
2500 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2501 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2502 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2503 LocTy CallLoc = Lex.getLoc();
2504 unsigned CC, RetAttrs, FnAttrs;
2505 PATypeHolder RetType(Type::VoidTy);
2508 SmallVector<ParamInfo, 16> ArgList;
2510 Value *NormalBB, *UnwindBB;
2511 if (ParseOptionalCallingConv(CC) ||
2512 ParseOptionalAttrs(RetAttrs, 1) ||
2513 ParseType(RetType, RetTypeLoc) ||
2514 ParseValID(CalleeID) ||
2515 ParseParameterList(ArgList, PFS) ||
2516 ParseOptionalAttrs(FnAttrs, 2) ||
2517 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2518 ParseTypeAndValue(NormalBB, PFS) ||
2519 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2520 ParseTypeAndValue(UnwindBB, PFS))
2523 if (!isa<BasicBlock>(NormalBB))
2524 return Error(CallLoc, "normal destination is not a basic block");
2525 if (!isa<BasicBlock>(UnwindBB))
2526 return Error(CallLoc, "unwind destination is not a basic block");
2528 // If RetType is a non-function pointer type, then this is the short syntax
2529 // for the call, which means that RetType is just the return type. Infer the
2530 // rest of the function argument types from the arguments that are present.
2531 const PointerType *PFTy = 0;
2532 const FunctionType *Ty = 0;
2533 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2534 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2535 // Pull out the types of all of the arguments...
2536 std::vector<const Type*> ParamTypes;
2537 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2538 ParamTypes.push_back(ArgList[i].V->getType());
2540 if (!FunctionType::isValidReturnType(RetType))
2541 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2543 Ty = FunctionType::get(RetType, ParamTypes, false);
2544 PFTy = PointerType::getUnqual(Ty);
2547 // Look up the callee.
2549 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2551 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2552 // function attributes.
2553 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2554 if (FnAttrs & ObsoleteFuncAttrs) {
2555 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2556 FnAttrs &= ~ObsoleteFuncAttrs;
2559 // Set up the Attributes for the function.
2560 SmallVector<AttributeWithIndex, 8> Attrs;
2561 if (RetAttrs != Attribute::None)
2562 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2564 SmallVector<Value*, 8> Args;
2566 // Loop through FunctionType's arguments and ensure they are specified
2567 // correctly. Also, gather any parameter attributes.
2568 FunctionType::param_iterator I = Ty->param_begin();
2569 FunctionType::param_iterator E = Ty->param_end();
2570 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2571 const Type *ExpectedTy = 0;
2574 } else if (!Ty->isVarArg()) {
2575 return Error(ArgList[i].Loc, "too many arguments specified");
2578 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2579 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2580 ExpectedTy->getDescription() + "'");
2581 Args.push_back(ArgList[i].V);
2582 if (ArgList[i].Attrs != Attribute::None)
2583 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2587 return Error(CallLoc, "not enough parameters specified for call");
2589 if (FnAttrs != Attribute::None)
2590 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2592 // Finish off the Attributes and check them
2593 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2595 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2596 cast<BasicBlock>(UnwindBB),
2597 Args.begin(), Args.end());
2598 II->setCallingConv(CC);
2599 II->setAttributes(PAL);
2606 //===----------------------------------------------------------------------===//
2607 // Binary Operators.
2608 //===----------------------------------------------------------------------===//
2611 /// ::= ArithmeticOps TypeAndValue ',' Value {
2612 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2614 LocTy Loc; Value *LHS, *RHS;
2615 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2616 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2617 ParseValue(LHS->getType(), RHS, PFS))
2620 if (!isa<IntegerType>(LHS->getType()) && !LHS->getType()->isFloatingPoint() &&
2621 !isa<VectorType>(LHS->getType()))
2622 return Error(Loc, "instruction requires integer, fp, or vector operands");
2624 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2629 /// ::= ArithmeticOps TypeAndValue ',' Value {
2630 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2632 LocTy Loc; Value *LHS, *RHS;
2633 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2634 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2635 ParseValue(LHS->getType(), RHS, PFS))
2638 if (!LHS->getType()->isIntOrIntVector())
2639 return Error(Loc,"instruction requires integer or integer vector operands");
2641 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2647 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2648 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2649 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2650 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2651 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2653 // Parse the integer/fp comparison predicate.
2657 if (ParseCmpPredicate(Pred, Opc) ||
2658 ParseTypeAndValue(LHS, Loc, PFS) ||
2659 ParseToken(lltok::comma, "expected ',' after compare value") ||
2660 ParseValue(LHS->getType(), RHS, PFS))
2663 if (Opc == Instruction::FCmp) {
2664 if (!LHS->getType()->isFPOrFPVector())
2665 return Error(Loc, "fcmp requires floating point operands");
2666 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2667 } else if (Opc == Instruction::ICmp) {
2668 if (!LHS->getType()->isIntOrIntVector() &&
2669 !isa<PointerType>(LHS->getType()))
2670 return Error(Loc, "icmp requires integer operands");
2671 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2672 } else if (Opc == Instruction::VFCmp) {
2673 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2674 } else if (Opc == Instruction::VICmp) {
2675 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2680 //===----------------------------------------------------------------------===//
2681 // Other Instructions.
2682 //===----------------------------------------------------------------------===//
2686 /// ::= CastOpc TypeAndValue 'to' Type
2687 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2689 LocTy Loc; Value *Op;
2690 PATypeHolder DestTy(Type::VoidTy);
2691 if (ParseTypeAndValue(Op, Loc, PFS) ||
2692 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2696 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy))
2697 return Error(Loc, "invalid cast opcode for cast from '" +
2698 Op->getType()->getDescription() + "' to '" +
2699 DestTy->getDescription() + "'");
2700 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2705 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2706 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2708 Value *Op0, *Op1, *Op2;
2709 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2710 ParseToken(lltok::comma, "expected ',' after select condition") ||
2711 ParseTypeAndValue(Op1, PFS) ||
2712 ParseToken(lltok::comma, "expected ',' after select value") ||
2713 ParseTypeAndValue(Op2, PFS))
2716 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2717 return Error(Loc, Reason);
2719 Inst = SelectInst::Create(Op0, Op1, Op2);
2724 /// ::= 'vaarg' TypeAndValue ',' Type
2725 bool LLParser::ParseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
2727 PATypeHolder EltTy(Type::VoidTy);
2728 if (ParseTypeAndValue(Op, PFS) ||
2729 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2733 Inst = new VAArgInst(Op, EltTy);
2737 /// ParseExtractElement
2738 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2739 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2742 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2743 ParseToken(lltok::comma, "expected ',' after extract value") ||
2744 ParseTypeAndValue(Op1, PFS))
2747 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2748 return Error(Loc, "invalid extractelement operands");
2750 Inst = new ExtractElementInst(Op0, Op1);
2754 /// ParseInsertElement
2755 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2756 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2758 Value *Op0, *Op1, *Op2;
2759 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2760 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2761 ParseTypeAndValue(Op1, PFS) ||
2762 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2763 ParseTypeAndValue(Op2, PFS))
2766 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2767 return Error(Loc, "invalid extractelement operands");
2769 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2773 /// ParseShuffleVector
2774 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2775 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2777 Value *Op0, *Op1, *Op2;
2778 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2779 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2780 ParseTypeAndValue(Op1, PFS) ||
2781 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2782 ParseTypeAndValue(Op2, PFS))
2785 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2786 return Error(Loc, "invalid extractelement operands");
2788 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2793 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2794 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2795 PATypeHolder Ty(Type::VoidTy);
2797 LocTy TypeLoc = Lex.getLoc();
2799 if (ParseType(Ty) ||
2800 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2801 ParseValue(Ty, Op0, PFS) ||
2802 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2803 ParseValue(Type::LabelTy, Op1, PFS) ||
2804 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2807 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2809 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2811 if (!EatIfPresent(lltok::comma))
2814 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2815 ParseValue(Ty, Op0, PFS) ||
2816 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2817 ParseValue(Type::LabelTy, Op1, PFS) ||
2818 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2822 if (!Ty->isFirstClassType())
2823 return Error(TypeLoc, "phi node must have first class type");
2825 PHINode *PN = PHINode::Create(Ty);
2826 PN->reserveOperandSpace(PHIVals.size());
2827 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2828 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2834 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2835 /// ParameterList OptionalAttrs
2836 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2838 unsigned CC, RetAttrs, FnAttrs;
2839 PATypeHolder RetType(Type::VoidTy);
2842 SmallVector<ParamInfo, 16> ArgList;
2843 LocTy CallLoc = Lex.getLoc();
2845 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2846 ParseOptionalCallingConv(CC) ||
2847 ParseOptionalAttrs(RetAttrs, 1) ||
2848 ParseType(RetType, RetTypeLoc) ||
2849 ParseValID(CalleeID) ||
2850 ParseParameterList(ArgList, PFS) ||
2851 ParseOptionalAttrs(FnAttrs, 2))
2854 // If RetType is a non-function pointer type, then this is the short syntax
2855 // for the call, which means that RetType is just the return type. Infer the
2856 // rest of the function argument types from the arguments that are present.
2857 const PointerType *PFTy = 0;
2858 const FunctionType *Ty = 0;
2859 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2860 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2861 // Pull out the types of all of the arguments...
2862 std::vector<const Type*> ParamTypes;
2863 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2864 ParamTypes.push_back(ArgList[i].V->getType());
2866 if (!FunctionType::isValidReturnType(RetType))
2867 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2869 Ty = FunctionType::get(RetType, ParamTypes, false);
2870 PFTy = PointerType::getUnqual(Ty);
2873 // Look up the callee.
2875 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2877 // Check for call to invalid intrinsic to avoid crashing later.
2878 if (Function *F = dyn_cast<Function>(Callee)) {
2879 if (F->hasName() && F->getNameLen() >= 5 &&
2880 !strncmp(F->getValueName()->getKeyData(), "llvm.", 5) &&
2881 !F->getIntrinsicID(true))
2882 return Error(CallLoc, "Call to invalid LLVM intrinsic function '" +
2883 F->getNameStr() + "'");
2886 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2887 // function attributes.
2888 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2889 if (FnAttrs & ObsoleteFuncAttrs) {
2890 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2891 FnAttrs &= ~ObsoleteFuncAttrs;
2894 // Set up the Attributes for the function.
2895 SmallVector<AttributeWithIndex, 8> Attrs;
2896 if (RetAttrs != Attribute::None)
2897 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2899 SmallVector<Value*, 8> Args;
2901 // Loop through FunctionType's arguments and ensure they are specified
2902 // correctly. Also, gather any parameter attributes.
2903 FunctionType::param_iterator I = Ty->param_begin();
2904 FunctionType::param_iterator E = Ty->param_end();
2905 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2906 const Type *ExpectedTy = 0;
2909 } else if (!Ty->isVarArg()) {
2910 return Error(ArgList[i].Loc, "too many arguments specified");
2913 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2914 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2915 ExpectedTy->getDescription() + "'");
2916 Args.push_back(ArgList[i].V);
2917 if (ArgList[i].Attrs != Attribute::None)
2918 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2922 return Error(CallLoc, "not enough parameters specified for call");
2924 if (FnAttrs != Attribute::None)
2925 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2927 // Finish off the Attributes and check them
2928 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2930 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
2931 CI->setTailCall(isTail);
2932 CI->setCallingConv(CC);
2933 CI->setAttributes(PAL);
2938 //===----------------------------------------------------------------------===//
2939 // Memory Instructions.
2940 //===----------------------------------------------------------------------===//
2943 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
2944 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
2945 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
2947 PATypeHolder Ty(Type::VoidTy);
2950 unsigned Alignment = 0;
2951 if (ParseType(Ty)) return true;
2953 if (EatIfPresent(lltok::comma)) {
2954 if (Lex.getKind() == lltok::kw_align) {
2955 if (ParseOptionalAlignment(Alignment)) return true;
2956 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
2957 ParseOptionalCommaAlignment(Alignment)) {
2962 if (Size && Size->getType() != Type::Int32Ty)
2963 return Error(SizeLoc, "element count must be i32");
2965 if (Opc == Instruction::Malloc)
2966 Inst = new MallocInst(Ty, Size, Alignment);
2968 Inst = new AllocaInst(Ty, Size, Alignment);
2973 /// ::= 'free' TypeAndValue
2974 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
2975 Value *Val; LocTy Loc;
2976 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
2977 if (!isa<PointerType>(Val->getType()))
2978 return Error(Loc, "operand to free must be a pointer");
2979 Inst = new FreeInst(Val);
2984 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
2985 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
2987 Value *Val; LocTy Loc;
2989 if (ParseTypeAndValue(Val, Loc, PFS) ||
2990 ParseOptionalCommaAlignment(Alignment))
2993 if (!isa<PointerType>(Val->getType()) ||
2994 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
2995 return Error(Loc, "load operand must be a pointer to a first class type");
2997 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3002 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3003 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3005 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3007 if (ParseTypeAndValue(Val, Loc, PFS) ||
3008 ParseToken(lltok::comma, "expected ',' after store operand") ||
3009 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3010 ParseOptionalCommaAlignment(Alignment))
3013 if (!isa<PointerType>(Ptr->getType()))
3014 return Error(PtrLoc, "store operand must be a pointer");
3015 if (!Val->getType()->isFirstClassType())
3016 return Error(Loc, "store operand must be a first class value");
3017 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3018 return Error(Loc, "stored value and pointer type do not match");
3020 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3025 /// ::= 'getresult' TypeAndValue ',' uint
3026 /// FIXME: Remove support for getresult in LLVM 3.0
3027 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3028 Value *Val; LocTy ValLoc, EltLoc;
3030 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3031 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3032 ParseUInt32(Element, EltLoc))
3035 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3036 return Error(ValLoc, "getresult inst requires an aggregate operand");
3037 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3038 return Error(EltLoc, "invalid getresult index for value");
3039 Inst = ExtractValueInst::Create(Val, Element);
3043 /// ParseGetElementPtr
3044 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3045 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3046 Value *Ptr, *Val; LocTy Loc, EltLoc;
3047 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3049 if (!isa<PointerType>(Ptr->getType()))
3050 return Error(Loc, "base of getelementptr must be a pointer");
3052 SmallVector<Value*, 16> Indices;
3053 while (EatIfPresent(lltok::comma)) {
3054 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3055 if (!isa<IntegerType>(Val->getType()))
3056 return Error(EltLoc, "getelementptr index must be an integer");
3057 Indices.push_back(Val);
3060 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3061 Indices.begin(), Indices.end()))
3062 return Error(Loc, "invalid getelementptr indices");
3063 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3067 /// ParseExtractValue
3068 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3069 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3070 Value *Val; LocTy Loc;
3071 SmallVector<unsigned, 4> Indices;
3072 if (ParseTypeAndValue(Val, Loc, PFS) ||
3073 ParseIndexList(Indices))
3076 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3077 return Error(Loc, "extractvalue operand must be array or struct");
3079 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3081 return Error(Loc, "invalid indices for extractvalue");
3082 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3086 /// ParseInsertValue
3087 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3088 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3089 Value *Val0, *Val1; LocTy Loc0, Loc1;
3090 SmallVector<unsigned, 4> Indices;
3091 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3092 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3093 ParseTypeAndValue(Val1, Loc1, PFS) ||
3094 ParseIndexList(Indices))
3097 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3098 return Error(Loc0, "extractvalue operand must be array or struct");
3100 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3102 return Error(Loc0, "invalid indices for insertvalue");
3103 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());