1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/ValueSymbolTable.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Support/raw_ostream.h"
29 /// ValID - Represents a reference of a definition of some sort with no type.
30 /// There are several cases where we have to parse the value but where the
31 /// type can depend on later context. This may either be a numeric reference
32 /// or a symbolic (%var) reference. This is just a discriminated union.
35 t_LocalID, t_GlobalID, // ID in UIntVal.
36 t_LocalName, t_GlobalName, // Name in StrVal.
37 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
38 t_Null, t_Undef, t_Zero, // No value.
39 t_EmptyArray, // No value: []
40 t_Constant, // Value in ConstantVal.
41 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
46 std::string StrVal, StrVal2;
49 Constant *ConstantVal;
50 ValID() : APFloatVal(0.0) {}
54 /// Run: module ::= toplevelentity*
55 bool LLParser::Run() {
59 return ParseTopLevelEntities() ||
60 ValidateEndOfModule();
63 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
65 bool LLParser::ValidateEndOfModule() {
66 if (!ForwardRefTypes.empty())
67 return Error(ForwardRefTypes.begin()->second.second,
68 "use of undefined type named '" +
69 ForwardRefTypes.begin()->first + "'");
70 if (!ForwardRefTypeIDs.empty())
71 return Error(ForwardRefTypeIDs.begin()->second.second,
72 "use of undefined type '%" +
73 utostr(ForwardRefTypeIDs.begin()->first) + "'");
75 if (!ForwardRefVals.empty())
76 return Error(ForwardRefVals.begin()->second.second,
77 "use of undefined value '@" + ForwardRefVals.begin()->first +
80 if (!ForwardRefValIDs.empty())
81 return Error(ForwardRefValIDs.begin()->second.second,
82 "use of undefined value '@" +
83 utostr(ForwardRefValIDs.begin()->first) + "'");
85 // Look for intrinsic functions and CallInst that need to be upgraded
86 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
87 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
92 //===----------------------------------------------------------------------===//
94 //===----------------------------------------------------------------------===//
96 bool LLParser::ParseTopLevelEntities() {
98 switch (Lex.getKind()) {
99 default: return TokError("expected top-level entity");
100 case lltok::Eof: return false;
101 //case lltok::kw_define:
102 case lltok::kw_declare: if (ParseDeclare()) return true; break;
103 case lltok::kw_define: if (ParseDefine()) return true; break;
104 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
105 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
106 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
107 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
108 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
109 case lltok::LocalVar: if (ParseNamedType()) return true; break;
110 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
112 // The Global variable production with no name can have many different
113 // optional leading prefixes, the production is:
114 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
115 // OptionalAddrSpace ('constant'|'global') ...
116 case lltok::kw_internal: // OptionalLinkage
117 case lltok::kw_weak: // OptionalLinkage
118 case lltok::kw_linkonce: // OptionalLinkage
119 case lltok::kw_appending: // OptionalLinkage
120 case lltok::kw_dllexport: // OptionalLinkage
121 case lltok::kw_common: // OptionalLinkage
122 case lltok::kw_dllimport: // OptionalLinkage
123 case lltok::kw_extern_weak: // OptionalLinkage
124 case lltok::kw_external: { // OptionalLinkage
125 unsigned Linkage, Visibility;
126 if (ParseOptionalLinkage(Linkage) ||
127 ParseOptionalVisibility(Visibility) ||
128 ParseGlobal("", 0, Linkage, true, Visibility))
132 case lltok::kw_default: // OptionalVisibility
133 case lltok::kw_hidden: // OptionalVisibility
134 case lltok::kw_protected: { // OptionalVisibility
136 if (ParseOptionalVisibility(Visibility) ||
137 ParseGlobal("", 0, 0, false, Visibility))
142 case lltok::kw_thread_local: // OptionalThreadLocal
143 case lltok::kw_addrspace: // OptionalAddrSpace
144 case lltok::kw_constant: // GlobalType
145 case lltok::kw_global: // GlobalType
146 if (ParseGlobal("", 0, 0, false, 0)) return true;
154 /// ::= 'module' 'asm' STRINGCONSTANT
155 bool LLParser::ParseModuleAsm() {
156 assert(Lex.getKind() == lltok::kw_module);
160 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
161 ParseStringConstant(AsmStr)) return true;
163 const std::string &AsmSoFar = M->getModuleInlineAsm();
164 if (AsmSoFar.empty())
165 M->setModuleInlineAsm(AsmStr);
167 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
172 /// ::= 'target' 'triple' '=' STRINGCONSTANT
173 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
174 bool LLParser::ParseTargetDefinition() {
175 assert(Lex.getKind() == lltok::kw_target);
178 default: return TokError("unknown target property");
179 case lltok::kw_triple:
181 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
182 ParseStringConstant(Str))
184 M->setTargetTriple(Str);
186 case lltok::kw_datalayout:
188 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
189 ParseStringConstant(Str))
191 M->setDataLayout(Str);
197 /// ::= 'deplibs' '=' '[' ']'
198 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
199 bool LLParser::ParseDepLibs() {
200 assert(Lex.getKind() == lltok::kw_deplibs);
202 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
203 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
206 if (EatIfPresent(lltok::rsquare))
210 if (ParseStringConstant(Str)) return true;
213 while (EatIfPresent(lltok::comma)) {
214 if (ParseStringConstant(Str)) return true;
218 return ParseToken(lltok::rsquare, "expected ']' at end of list");
223 bool LLParser::ParseUnnamedType() {
224 assert(Lex.getKind() == lltok::kw_type);
225 LocTy TypeLoc = Lex.getLoc();
226 Lex.Lex(); // eat kw_type
228 PATypeHolder Ty(Type::VoidTy);
229 if (ParseType(Ty)) return true;
231 unsigned TypeID = NumberedTypes.size();
233 // We don't allow assigning names to void type
234 if (Ty == Type::VoidTy)
235 return Error(TypeLoc, "can't assign name to the void type");
237 // See if this type was previously referenced.
238 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
239 FI = ForwardRefTypeIDs.find(TypeID);
240 if (FI != ForwardRefTypeIDs.end()) {
241 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
242 Ty = FI->second.first.get();
243 ForwardRefTypeIDs.erase(FI);
246 NumberedTypes.push_back(Ty);
252 /// ::= LocalVar '=' 'type' type
253 bool LLParser::ParseNamedType() {
254 std::string Name = Lex.getStrVal();
255 LocTy NameLoc = Lex.getLoc();
256 Lex.Lex(); // eat LocalVar.
258 PATypeHolder Ty(Type::VoidTy);
260 if (ParseToken(lltok::equal, "expected '=' after name") ||
261 ParseToken(lltok::kw_type, "expected 'type' after name") ||
265 // We don't allow assigning names to void type
266 if (Ty == Type::VoidTy)
267 return Error(NameLoc, "can't assign name '" + Name + "' to the void type");
269 // Set the type name, checking for conflicts as we do so.
270 bool AlreadyExists = M->addTypeName(Name, Ty);
271 if (!AlreadyExists) return false;
273 // See if this type is a forward reference. We need to eagerly resolve
274 // types to allow recursive type redefinitions below.
275 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
276 FI = ForwardRefTypes.find(Name);
277 if (FI != ForwardRefTypes.end()) {
278 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
279 Ty = FI->second.first.get();
280 ForwardRefTypes.erase(FI);
283 // Inserting a name that is already defined, get the existing name.
284 const Type *Existing = M->getTypeByName(Name);
285 assert(Existing && "Conflict but no matching type?!");
287 // Otherwise, this is an attempt to redefine a type. That's okay if
288 // the redefinition is identical to the original.
289 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
290 if (Existing == Ty) return false;
292 // Any other kind of (non-equivalent) redefinition is an error.
293 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
294 Ty->getDescription() + "'");
299 /// ::= 'declare' FunctionHeader
300 bool LLParser::ParseDeclare() {
301 assert(Lex.getKind() == lltok::kw_declare);
305 return ParseFunctionHeader(F, false);
309 /// ::= 'define' FunctionHeader '{' ...
310 bool LLParser::ParseDefine() {
311 assert(Lex.getKind() == lltok::kw_define);
315 return ParseFunctionHeader(F, true) ||
316 ParseFunctionBody(*F);
322 bool LLParser::ParseGlobalType(bool &IsConstant) {
323 if (Lex.getKind() == lltok::kw_constant)
325 else if (Lex.getKind() == lltok::kw_global)
328 return TokError("expected 'global' or 'constant'");
333 /// ParseNamedGlobal:
334 /// GlobalVar '=' OptionalVisibility ALIAS ...
335 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
336 bool LLParser::ParseNamedGlobal() {
337 assert(Lex.getKind() == lltok::GlobalVar);
338 LocTy NameLoc = Lex.getLoc();
339 std::string Name = Lex.getStrVal();
343 unsigned Linkage, Visibility;
344 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
345 ParseOptionalLinkage(Linkage, HasLinkage) ||
346 ParseOptionalVisibility(Visibility))
349 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
350 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
351 return ParseAlias(Name, NameLoc, Visibility);
355 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
357 /// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
359 /// Everything through visibility has already been parsed.
361 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
362 unsigned Visibility) {
363 assert(Lex.getKind() == lltok::kw_alias);
366 LocTy LinkageLoc = Lex.getLoc();
367 if (ParseOptionalLinkage(Linkage))
370 if (Linkage != GlobalValue::ExternalLinkage &&
371 Linkage != GlobalValue::WeakLinkage &&
372 Linkage != GlobalValue::InternalLinkage)
373 return Error(LinkageLoc, "invalid linkage type for alias");
376 LocTy AliaseeLoc = Lex.getLoc();
377 if (Lex.getKind() != lltok::kw_bitcast) {
378 if (ParseGlobalTypeAndValue(Aliasee)) return true;
380 // The bitcast dest type is not present, it is implied by the dest type.
382 if (ParseValID(ID)) return true;
383 if (ID.Kind != ValID::t_Constant)
384 return Error(AliaseeLoc, "invalid aliasee");
385 Aliasee = ID.ConstantVal;
388 if (!isa<PointerType>(Aliasee->getType()))
389 return Error(AliaseeLoc, "alias must have pointer type");
391 // Okay, create the alias but do not insert it into the module yet.
392 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
393 (GlobalValue::LinkageTypes)Linkage, Name,
395 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
397 // See if this value already exists in the symbol table. If so, it is either
398 // a redefinition or a definition of a forward reference.
399 if (GlobalValue *Val =
400 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
401 // See if this was a redefinition. If so, there is no entry in
403 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
404 I = ForwardRefVals.find(Name);
405 if (I == ForwardRefVals.end())
406 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
408 // Otherwise, this was a definition of forward ref. Verify that types
410 if (Val->getType() != GA->getType())
411 return Error(NameLoc,
412 "forward reference and definition of alias have different types");
414 // If they agree, just RAUW the old value with the alias and remove the
416 Val->replaceAllUsesWith(GA);
417 Val->eraseFromParent();
418 ForwardRefVals.erase(I);
421 // Insert into the module, we know its name won't collide now.
422 M->getAliasList().push_back(GA);
423 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
429 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
430 /// OptionalAddrSpace GlobalType Type Const
431 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
432 /// OptionalAddrSpace GlobalType Type Const
434 /// Everything through visibility has been parsed already.
436 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
437 unsigned Linkage, bool HasLinkage,
438 unsigned Visibility) {
440 bool ThreadLocal, IsConstant;
443 PATypeHolder Ty(Type::VoidTy);
444 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
445 ParseOptionalAddrSpace(AddrSpace) ||
446 ParseGlobalType(IsConstant) ||
447 ParseType(Ty, TyLoc))
450 // If the linkage is specified and is external, then no initializer is
453 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
454 Linkage != GlobalValue::ExternalWeakLinkage &&
455 Linkage != GlobalValue::ExternalLinkage)) {
456 if (ParseGlobalValue(Ty, Init))
460 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
461 return Error(TyLoc, "invald type for global variable");
463 GlobalVariable *GV = 0;
465 // See if the global was forward referenced, if so, use the global.
466 if (!Name.empty() && (GV = M->getGlobalVariable(Name, true))) {
467 if (!ForwardRefVals.erase(Name))
468 return Error(NameLoc, "redefinition of global '@" + Name + "'");
470 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
471 I = ForwardRefValIDs.find(NumberedVals.size());
472 if (I != ForwardRefValIDs.end()) {
473 GV = cast<GlobalVariable>(I->second.first);
474 ForwardRefValIDs.erase(I);
479 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
480 M, false, AddrSpace);
482 if (GV->getType()->getElementType() != Ty)
484 "forward reference and definition of global have different types");
486 // Move the forward-reference to the correct spot in the module.
487 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
491 NumberedVals.push_back(GV);
493 // Set the parsed properties on the global.
495 GV->setInitializer(Init);
496 GV->setConstant(IsConstant);
497 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
498 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
499 GV->setThreadLocal(ThreadLocal);
501 // Parse attributes on the global.
502 while (Lex.getKind() == lltok::comma) {
505 if (Lex.getKind() == lltok::kw_section) {
507 GV->setSection(Lex.getStrVal());
508 if (ParseToken(lltok::StringConstant, "expected global section string"))
510 } else if (Lex.getKind() == lltok::kw_align) {
512 if (ParseOptionalAlignment(Alignment)) return true;
513 GV->setAlignment(Alignment);
515 TokError("unknown global variable property!");
523 //===----------------------------------------------------------------------===//
524 // GlobalValue Reference/Resolution Routines.
525 //===----------------------------------------------------------------------===//
527 /// GetGlobalVal - Get a value with the specified name or ID, creating a
528 /// forward reference record if needed. This can return null if the value
529 /// exists but does not have the right type.
530 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
532 const PointerType *PTy = dyn_cast<PointerType>(Ty);
534 Error(Loc, "global variable reference must have pointer type");
538 // Look this name up in the normal function symbol table.
540 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
542 // If this is a forward reference for the value, see if we already created a
543 // forward ref record.
545 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
546 I = ForwardRefVals.find(Name);
547 if (I != ForwardRefVals.end())
548 Val = I->second.first;
551 // If we have the value in the symbol table or fwd-ref table, return it.
553 if (Val->getType() == Ty) return Val;
554 Error(Loc, "'@" + Name + "' defined with type '" +
555 Val->getType()->getDescription() + "'");
559 // Otherwise, create a new forward reference for this value and remember it.
561 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
562 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
564 FwdVal = new GlobalVariable(PTy->getElementType(), false,
565 GlobalValue::ExternalWeakLinkage, 0, Name, M);
567 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
571 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
572 const PointerType *PTy = dyn_cast<PointerType>(Ty);
574 Error(Loc, "global variable reference must have pointer type");
578 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
580 // If this is a forward reference for the value, see if we already created a
581 // forward ref record.
583 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
584 I = ForwardRefValIDs.find(ID);
585 if (I != ForwardRefValIDs.end())
586 Val = I->second.first;
589 // If we have the value in the symbol table or fwd-ref table, return it.
591 if (Val->getType() == Ty) return Val;
592 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
593 Val->getType()->getDescription() + "'");
597 // Otherwise, create a new forward reference for this value and remember it.
599 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
600 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
602 FwdVal = new GlobalVariable(PTy->getElementType(), false,
603 GlobalValue::ExternalWeakLinkage, 0, "", M);
605 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
610 //===----------------------------------------------------------------------===//
612 //===----------------------------------------------------------------------===//
614 /// ParseToken - If the current token has the specified kind, eat it and return
615 /// success. Otherwise, emit the specified error and return failure.
616 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
617 if (Lex.getKind() != T)
618 return TokError(ErrMsg);
623 /// ParseStringConstant
624 /// ::= StringConstant
625 bool LLParser::ParseStringConstant(std::string &Result) {
626 if (Lex.getKind() != lltok::StringConstant)
627 return TokError("expected string constant");
628 Result = Lex.getStrVal();
635 bool LLParser::ParseUInt32(unsigned &Val) {
636 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
637 return TokError("expected integer");
638 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
639 if (Val64 != unsigned(Val64))
640 return TokError("expected 32-bit integer (too large)");
647 /// ParseOptionalAddrSpace
649 /// := 'addrspace' '(' uint32 ')'
650 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
652 if (!EatIfPresent(lltok::kw_addrspace))
654 return ParseToken(lltok::lparen, "expected '(' in address space") ||
655 ParseUInt32(AddrSpace) ||
656 ParseToken(lltok::rparen, "expected ')' in address space");
659 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
660 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
661 /// 2: function attr.
662 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
663 Attrs = Attribute::None;
664 LocTy AttrLoc = Lex.getLoc();
667 switch (Lex.getKind()) {
670 // Treat these as signext/zeroext unless they are function attrs.
671 // FIXME: REMOVE THIS IN LLVM 3.0
673 if (Lex.getKind() == lltok::kw_sext)
674 Attrs |= Attribute::SExt;
676 Attrs |= Attribute::ZExt;
680 default: // End of attributes.
681 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
682 return Error(AttrLoc, "invalid use of function-only attribute");
684 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
685 return Error(AttrLoc, "invalid use of parameter-only attribute");
688 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
689 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
690 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
691 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
692 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
693 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
694 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
695 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
697 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
698 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
699 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
700 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
701 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
702 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
703 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
704 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
705 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
708 case lltok::kw_align: {
710 if (ParseOptionalAlignment(Alignment))
712 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
720 /// ParseOptionalLinkage
729 /// ::= 'extern_weak'
731 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
733 switch (Lex.getKind()) {
734 default: Res = GlobalValue::ExternalLinkage; return false;
735 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
736 case lltok::kw_weak: Res = GlobalValue::WeakLinkage; break;
737 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceLinkage; break;
738 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
739 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
740 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
741 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
742 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
743 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
750 /// ParseOptionalVisibility
756 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
757 switch (Lex.getKind()) {
758 default: Res = GlobalValue::DefaultVisibility; return false;
759 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
760 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
761 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
767 /// ParseOptionalCallingConv
772 /// ::= 'x86_stdcallcc'
773 /// ::= 'x86_fastcallcc'
776 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
777 switch (Lex.getKind()) {
778 default: CC = CallingConv::C; return false;
779 case lltok::kw_ccc: CC = CallingConv::C; break;
780 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
781 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
782 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
783 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
784 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
790 /// ParseOptionalAlignment
793 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
795 if (!EatIfPresent(lltok::kw_align))
797 LocTy AlignLoc = Lex.getLoc();
798 if (ParseUInt32(Alignment)) return true;
799 if (!isPowerOf2_32(Alignment))
800 return Error(AlignLoc, "alignment is not a power of two");
804 /// ParseOptionalCommaAlignment
806 /// ::= ',' 'align' 4
807 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
809 if (!EatIfPresent(lltok::comma))
811 return ParseToken(lltok::kw_align, "expected 'align'") ||
812 ParseUInt32(Alignment);
816 /// ::= (',' uint32)+
817 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
818 if (Lex.getKind() != lltok::comma)
819 return TokError("expected ',' as start of index list");
821 while (EatIfPresent(lltok::comma)) {
823 if (ParseUInt32(Idx)) return true;
824 Indices.push_back(Idx);
830 //===----------------------------------------------------------------------===//
832 //===----------------------------------------------------------------------===//
834 /// ParseType - Parse and resolve a full type.
835 bool LLParser::ParseType(PATypeHolder &Result) {
836 if (ParseTypeRec(Result)) return true;
838 // Verify no unresolved uprefs.
840 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
845 /// HandleUpRefs - Every time we finish a new layer of types, this function is
846 /// called. It loops through the UpRefs vector, which is a list of the
847 /// currently active types. For each type, if the up-reference is contained in
848 /// the newly completed type, we decrement the level count. When the level
849 /// count reaches zero, the up-referenced type is the type that is passed in:
850 /// thus we can complete the cycle.
852 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
853 // If Ty isn't abstract, or if there are no up-references in it, then there is
854 // nothing to resolve here.
855 if (!ty->isAbstract() || UpRefs.empty()) return ty;
859 errs() << "Type '" << Ty->getDescription()
860 << "' newly formed. Resolving upreferences.\n"
861 << UpRefs.size() << " upreferences active!\n";
864 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
865 // to zero), we resolve them all together before we resolve them to Ty. At
866 // the end of the loop, if there is anything to resolve to Ty, it will be in
868 OpaqueType *TypeToResolve = 0;
870 for (unsigned i = 0; i != UpRefs.size(); ++i) {
871 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
873 std::find(Ty->subtype_begin(), Ty->subtype_end(),
874 UpRefs[i].LastContainedTy) != Ty->subtype_end();
877 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
878 << UpRefs[i].LastContainedTy->getDescription() << ") = "
879 << (ContainsType ? "true" : "false")
880 << " level=" << UpRefs[i].NestingLevel << "\n";
885 // Decrement level of upreference
886 unsigned Level = --UpRefs[i].NestingLevel;
887 UpRefs[i].LastContainedTy = Ty;
889 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
894 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
897 TypeToResolve = UpRefs[i].UpRefTy;
899 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
900 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
901 --i; // Do not skip the next element.
905 TypeToResolve->refineAbstractTypeTo(Ty);
911 /// ParseTypeRec - The recursive function used to process the internal
912 /// implementation details of types.
913 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
914 switch (Lex.getKind()) {
916 return TokError("expected type");
918 // TypeRec ::= 'float' | 'void' (etc)
919 Result = Lex.getTyVal();
922 case lltok::kw_opaque:
923 // TypeRec ::= 'opaque'
924 Result = OpaqueType::get();
928 // TypeRec ::= '{' ... '}'
929 if (ParseStructType(Result, false))
933 // TypeRec ::= '[' ... ']'
934 Lex.Lex(); // eat the lsquare.
935 if (ParseArrayVectorType(Result, false))
938 case lltok::less: // Either vector or packed struct.
939 // TypeRec ::= '<' ... '>'
941 if (Lex.getKind() == lltok::lbrace) {
942 if (ParseStructType(Result, true) ||
943 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
945 } else if (ParseArrayVectorType(Result, true))
948 case lltok::LocalVar:
949 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
951 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
954 Result = OpaqueType::get();
955 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
956 std::make_pair(Result,
958 M->addTypeName(Lex.getStrVal(), Result.get());
963 case lltok::LocalVarID:
965 if (Lex.getUIntVal() < NumberedTypes.size())
966 Result = NumberedTypes[Lex.getUIntVal()];
968 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
969 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
970 if (I != ForwardRefTypeIDs.end())
971 Result = I->second.first;
973 Result = OpaqueType::get();
974 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
975 std::make_pair(Result,
981 case lltok::backslash: {
985 if (ParseUInt32(Val)) return true;
986 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
987 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
993 // Parse the type suffixes.
995 switch (Lex.getKind()) {
997 default: return false;
999 // TypeRec ::= TypeRec '*'
1001 if (Result.get() == Type::LabelTy)
1002 return TokError("basic block pointers are invalid");
1003 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1007 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1008 case lltok::kw_addrspace: {
1009 if (Result.get() == Type::LabelTy)
1010 return TokError("basic block pointers are invalid");
1012 if (ParseOptionalAddrSpace(AddrSpace) ||
1013 ParseToken(lltok::star, "expected '*' in address space"))
1016 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1020 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1022 if (ParseFunctionType(Result))
1029 /// ParseParameterList
1031 /// ::= '(' Arg (',' Arg)* ')'
1033 /// ::= Type OptionalAttributes Value OptionalAttributes
1034 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1035 PerFunctionState &PFS) {
1036 if (ParseToken(lltok::lparen, "expected '(' in call"))
1039 while (Lex.getKind() != lltok::rparen) {
1040 // If this isn't the first argument, we need a comma.
1041 if (!ArgList.empty() &&
1042 ParseToken(lltok::comma, "expected ',' in argument list"))
1045 // Parse the argument.
1047 PATypeHolder ArgTy(Type::VoidTy);
1048 unsigned ArgAttrs1, ArgAttrs2;
1050 if (ParseType(ArgTy, ArgLoc) ||
1051 ParseOptionalAttrs(ArgAttrs1, 0) ||
1052 ParseValue(ArgTy, V, PFS) ||
1053 // FIXME: Should not allow attributes after the argument, remove this in
1055 ParseOptionalAttrs(ArgAttrs2, 0))
1057 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1060 Lex.Lex(); // Lex the ')'.
1066 /// ParseArgumentList
1067 /// ::= '(' ArgTypeListI ')'
1071 /// ::= ArgTypeList ',' '...'
1072 /// ::= ArgType (',' ArgType)*
1073 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1076 assert(Lex.getKind() == lltok::lparen);
1077 Lex.Lex(); // eat the (.
1079 if (Lex.getKind() == lltok::rparen) {
1081 } else if (Lex.getKind() == lltok::dotdotdot) {
1085 LocTy TypeLoc = Lex.getLoc();
1086 PATypeHolder ArgTy(Type::VoidTy);
1090 if (ParseTypeRec(ArgTy) ||
1091 ParseOptionalAttrs(Attrs, 0)) return true;
1093 if (Lex.getKind() == lltok::LocalVar ||
1094 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1095 Name = Lex.getStrVal();
1099 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1100 return Error(TypeLoc, "invalid type for function argument");
1102 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1104 while (EatIfPresent(lltok::comma)) {
1105 // Handle ... at end of arg list.
1106 if (EatIfPresent(lltok::dotdotdot)) {
1111 // Otherwise must be an argument type.
1112 TypeLoc = Lex.getLoc();
1113 if (ParseTypeRec(ArgTy) ||
1114 ParseOptionalAttrs(Attrs, 0)) return true;
1116 if (Lex.getKind() == lltok::LocalVar ||
1117 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1118 Name = Lex.getStrVal();
1124 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1125 return Error(TypeLoc, "invalid type for function argument");
1127 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1131 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1134 /// ParseFunctionType
1135 /// ::= Type ArgumentList OptionalAttrs
1136 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1137 assert(Lex.getKind() == lltok::lparen);
1139 if (!FunctionType::isValidReturnType(Result))
1140 return TokError("invalid function return type");
1142 std::vector<ArgInfo> ArgList;
1145 if (ParseArgumentList(ArgList, isVarArg) ||
1146 // FIXME: Allow, but ignore attributes on function types!
1147 // FIXME: Remove in LLVM 3.0
1148 ParseOptionalAttrs(Attrs, 2))
1151 // Reject names on the arguments lists.
1152 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1153 if (!ArgList[i].Name.empty())
1154 return Error(ArgList[i].Loc, "argument name invalid in function type");
1155 if (!ArgList[i].Attrs != 0) {
1156 // Allow but ignore attributes on function types; this permits
1158 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1162 std::vector<const Type*> ArgListTy;
1163 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1164 ArgListTy.push_back(ArgList[i].Type);
1166 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1170 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1173 /// ::= '{' TypeRec (',' TypeRec)* '}'
1174 /// ::= '<' '{' '}' '>'
1175 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1176 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1177 assert(Lex.getKind() == lltok::lbrace);
1178 Lex.Lex(); // Consume the '{'
1180 if (EatIfPresent(lltok::rbrace)) {
1181 Result = StructType::get(std::vector<const Type*>(), Packed);
1185 std::vector<PATypeHolder> ParamsList;
1186 if (ParseTypeRec(Result)) return true;
1187 ParamsList.push_back(Result);
1189 while (EatIfPresent(lltok::comma)) {
1190 if (ParseTypeRec(Result)) return true;
1191 ParamsList.push_back(Result);
1194 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1197 std::vector<const Type*> ParamsListTy;
1198 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1199 ParamsListTy.push_back(ParamsList[i].get());
1200 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1204 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1205 /// token has already been consumed.
1207 /// ::= '[' APSINTVAL 'x' Types ']'
1208 /// ::= '<' APSINTVAL 'x' Types '>'
1209 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1210 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1211 Lex.getAPSIntVal().getBitWidth() > 64)
1212 return TokError("expected number in address space");
1214 LocTy SizeLoc = Lex.getLoc();
1215 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1218 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1221 LocTy TypeLoc = Lex.getLoc();
1222 PATypeHolder EltTy(Type::VoidTy);
1223 if (ParseTypeRec(EltTy)) return true;
1225 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1226 "expected end of sequential type"))
1230 if ((unsigned)Size != Size)
1231 return Error(SizeLoc, "size too large for vector");
1232 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1233 return Error(TypeLoc, "vector element type must be fp or integer");
1234 Result = VectorType::get(EltTy, unsigned(Size));
1236 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1237 return Error(TypeLoc, "invalid array element type");
1238 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1243 //===----------------------------------------------------------------------===//
1244 // Function Semantic Analysis.
1245 //===----------------------------------------------------------------------===//
1247 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1250 // Insert unnamed arguments into the NumberedVals list.
1251 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1254 NumberedVals.push_back(AI);
1257 LLParser::PerFunctionState::~PerFunctionState() {
1258 // If there were any forward referenced non-basicblock values, delete them.
1259 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1260 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1261 if (!isa<BasicBlock>(I->second.first)) {
1262 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1264 delete I->second.first;
1265 I->second.first = 0;
1268 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1269 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1270 if (!isa<BasicBlock>(I->second.first)) {
1271 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1273 delete I->second.first;
1274 I->second.first = 0;
1278 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1279 if (!ForwardRefVals.empty())
1280 return P.Error(ForwardRefVals.begin()->second.second,
1281 "use of undefined value '%" + ForwardRefVals.begin()->first +
1283 if (!ForwardRefValIDs.empty())
1284 return P.Error(ForwardRefValIDs.begin()->second.second,
1285 "use of undefined value '%" +
1286 utostr(ForwardRefValIDs.begin()->first) + "'");
1291 /// GetVal - Get a value with the specified name or ID, creating a
1292 /// forward reference record if needed. This can return null if the value
1293 /// exists but does not have the right type.
1294 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1295 const Type *Ty, LocTy Loc) {
1296 // Look this name up in the normal function symbol table.
1297 Value *Val = F.getValueSymbolTable().lookup(Name);
1299 // If this is a forward reference for the value, see if we already created a
1300 // forward ref record.
1302 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1303 I = ForwardRefVals.find(Name);
1304 if (I != ForwardRefVals.end())
1305 Val = I->second.first;
1308 // If we have the value in the symbol table or fwd-ref table, return it.
1310 if (Val->getType() == Ty) return Val;
1311 if (Ty == Type::LabelTy)
1312 P.Error(Loc, "'%" + Name + "' is not a basic block");
1314 P.Error(Loc, "'%" + Name + "' defined with type '" +
1315 Val->getType()->getDescription() + "'");
1319 // Don't make placeholders with invalid type.
1320 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1321 P.Error(Loc, "invalid use of a non-first-class type");
1325 // Otherwise, create a new forward reference for this value and remember it.
1327 if (Ty == Type::LabelTy)
1328 FwdVal = BasicBlock::Create(Name, &F);
1330 FwdVal = new Argument(Ty, Name);
1332 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1336 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1338 // Look this name up in the normal function symbol table.
1339 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1341 // If this is a forward reference for the value, see if we already created a
1342 // forward ref record.
1344 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1345 I = ForwardRefValIDs.find(ID);
1346 if (I != ForwardRefValIDs.end())
1347 Val = I->second.first;
1350 // If we have the value in the symbol table or fwd-ref table, return it.
1352 if (Val->getType() == Ty) return Val;
1353 if (Ty == Type::LabelTy)
1354 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1356 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1357 Val->getType()->getDescription() + "'");
1361 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1362 P.Error(Loc, "invalid use of a non-first-class type");
1366 // Otherwise, create a new forward reference for this value and remember it.
1368 if (Ty == Type::LabelTy)
1369 FwdVal = BasicBlock::Create("", &F);
1371 FwdVal = new Argument(Ty);
1373 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1377 /// SetInstName - After an instruction is parsed and inserted into its
1378 /// basic block, this installs its name.
1379 bool LLParser::PerFunctionState::SetInstName(int NameID,
1380 const std::string &NameStr,
1381 LocTy NameLoc, Instruction *Inst) {
1382 // If this instruction has void type, it cannot have a name or ID specified.
1383 if (Inst->getType() == Type::VoidTy) {
1384 if (NameID != -1 || !NameStr.empty())
1385 return P.Error(NameLoc, "instructions returning void cannot have a name");
1389 // If this was a numbered instruction, verify that the instruction is the
1390 // expected value and resolve any forward references.
1391 if (NameStr.empty()) {
1392 // If neither a name nor an ID was specified, just use the next ID.
1394 NameID = NumberedVals.size();
1396 if (unsigned(NameID) != NumberedVals.size())
1397 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1398 utostr(NumberedVals.size()) + "'");
1400 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1401 ForwardRefValIDs.find(NameID);
1402 if (FI != ForwardRefValIDs.end()) {
1403 if (FI->second.first->getType() != Inst->getType())
1404 return P.Error(NameLoc, "instruction forward referenced with type '" +
1405 FI->second.first->getType()->getDescription() + "'");
1406 FI->second.first->replaceAllUsesWith(Inst);
1407 ForwardRefValIDs.erase(FI);
1410 NumberedVals.push_back(Inst);
1414 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1415 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1416 FI = ForwardRefVals.find(NameStr);
1417 if (FI != ForwardRefVals.end()) {
1418 if (FI->second.first->getType() != Inst->getType())
1419 return P.Error(NameLoc, "instruction forward referenced with type '" +
1420 FI->second.first->getType()->getDescription() + "'");
1421 FI->second.first->replaceAllUsesWith(Inst);
1422 ForwardRefVals.erase(FI);
1425 // Set the name on the instruction.
1426 Inst->setName(NameStr);
1428 if (Inst->getNameStr() != NameStr)
1429 return P.Error(NameLoc, "multiple definition of local value named '" +
1434 /// GetBB - Get a basic block with the specified name or ID, creating a
1435 /// forward reference record if needed.
1436 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1438 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1441 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1442 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1445 /// DefineBB - Define the specified basic block, which is either named or
1446 /// unnamed. If there is an error, this returns null otherwise it returns
1447 /// the block being defined.
1448 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1452 BB = GetBB(NumberedVals.size(), Loc);
1454 BB = GetBB(Name, Loc);
1455 if (BB == 0) return 0; // Already diagnosed error.
1457 // Move the block to the end of the function. Forward ref'd blocks are
1458 // inserted wherever they happen to be referenced.
1459 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1461 // Remove the block from forward ref sets.
1463 ForwardRefValIDs.erase(NumberedVals.size());
1464 NumberedVals.push_back(BB);
1466 // BB forward references are already in the function symbol table.
1467 ForwardRefVals.erase(Name);
1473 //===----------------------------------------------------------------------===//
1475 //===----------------------------------------------------------------------===//
1477 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1478 /// type implied. For example, if we parse "4" we don't know what integer type
1479 /// it has. The value will later be combined with its type and checked for
1481 bool LLParser::ParseValID(ValID &ID) {
1482 ID.Loc = Lex.getLoc();
1483 switch (Lex.getKind()) {
1484 default: return TokError("expected value token");
1485 case lltok::GlobalID: // @42
1486 ID.UIntVal = Lex.getUIntVal();
1487 ID.Kind = ValID::t_GlobalID;
1489 case lltok::GlobalVar: // @foo
1490 ID.StrVal = Lex.getStrVal();
1491 ID.Kind = ValID::t_GlobalName;
1493 case lltok::LocalVarID: // %42
1494 ID.UIntVal = Lex.getUIntVal();
1495 ID.Kind = ValID::t_LocalID;
1497 case lltok::LocalVar: // %foo
1498 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1499 ID.StrVal = Lex.getStrVal();
1500 ID.Kind = ValID::t_LocalName;
1503 ID.APSIntVal = Lex.getAPSIntVal();
1504 ID.Kind = ValID::t_APSInt;
1506 case lltok::APFloat:
1507 ID.APFloatVal = Lex.getAPFloatVal();
1508 ID.Kind = ValID::t_APFloat;
1510 case lltok::kw_true:
1511 ID.ConstantVal = ConstantInt::getTrue();
1512 ID.Kind = ValID::t_Constant;
1514 case lltok::kw_false:
1515 ID.ConstantVal = ConstantInt::getFalse();
1516 ID.Kind = ValID::t_Constant;
1518 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1519 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1520 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1522 case lltok::lbrace: {
1523 // ValID ::= '{' ConstVector '}'
1525 SmallVector<Constant*, 16> Elts;
1526 if (ParseGlobalValueVector(Elts) ||
1527 ParseToken(lltok::rbrace, "expected end of struct constant"))
1530 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1531 ID.Kind = ValID::t_Constant;
1535 // ValID ::= '<' ConstVector '>' --> Vector.
1536 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1538 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1540 SmallVector<Constant*, 16> Elts;
1541 LocTy FirstEltLoc = Lex.getLoc();
1542 if (ParseGlobalValueVector(Elts) ||
1544 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1545 ParseToken(lltok::greater, "expected end of constant"))
1548 if (isPackedStruct) {
1549 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1550 ID.Kind = ValID::t_Constant;
1555 return Error(ID.Loc, "constant vector must not be empty");
1557 if (!Elts[0]->getType()->isInteger() &&
1558 !Elts[0]->getType()->isFloatingPoint())
1559 return Error(FirstEltLoc,
1560 "vector elements must have integer or floating point type");
1562 // Verify that all the vector elements have the same type.
1563 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1564 if (Elts[i]->getType() != Elts[0]->getType())
1565 return Error(FirstEltLoc,
1566 "vector element #" + utostr(i) +
1567 " is not of type '" + Elts[0]->getType()->getDescription());
1569 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1570 ID.Kind = ValID::t_Constant;
1573 case lltok::lsquare: { // Array Constant
1575 SmallVector<Constant*, 16> Elts;
1576 LocTy FirstEltLoc = Lex.getLoc();
1577 if (ParseGlobalValueVector(Elts) ||
1578 ParseToken(lltok::rsquare, "expected end of array constant"))
1581 // Handle empty element.
1583 // Use undef instead of an array because it's inconvenient to determine
1584 // the element type at this point, there being no elements to examine.
1585 ID.Kind = ValID::t_EmptyArray;
1589 if (!Elts[0]->getType()->isFirstClassType())
1590 return Error(FirstEltLoc, "invalid array element type: " +
1591 Elts[0]->getType()->getDescription());
1593 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1595 // Verify all elements are correct type!
1596 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1597 if (Elts[i]->getType() != Elts[0]->getType())
1598 return Error(FirstEltLoc,
1599 "array element #" + utostr(i) +
1600 " is not of type '" +Elts[0]->getType()->getDescription());
1603 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1604 ID.Kind = ValID::t_Constant;
1607 case lltok::kw_c: // c "foo"
1609 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1610 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1611 ID.Kind = ValID::t_Constant;
1614 case lltok::kw_asm: {
1615 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1618 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1619 ParseStringConstant(ID.StrVal) ||
1620 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1621 ParseToken(lltok::StringConstant, "expected constraint string"))
1623 ID.StrVal2 = Lex.getStrVal();
1624 ID.UIntVal = HasSideEffect;
1625 ID.Kind = ValID::t_InlineAsm;
1629 case lltok::kw_trunc:
1630 case lltok::kw_zext:
1631 case lltok::kw_sext:
1632 case lltok::kw_fptrunc:
1633 case lltok::kw_fpext:
1634 case lltok::kw_bitcast:
1635 case lltok::kw_uitofp:
1636 case lltok::kw_sitofp:
1637 case lltok::kw_fptoui:
1638 case lltok::kw_fptosi:
1639 case lltok::kw_inttoptr:
1640 case lltok::kw_ptrtoint: {
1641 unsigned Opc = Lex.getUIntVal();
1642 PATypeHolder DestTy(Type::VoidTy);
1645 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1646 ParseGlobalTypeAndValue(SrcVal) ||
1647 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1648 ParseType(DestTy) ||
1649 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1651 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1652 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1653 SrcVal->getType()->getDescription() + "' to '" +
1654 DestTy->getDescription() + "'");
1655 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1657 ID.Kind = ValID::t_Constant;
1660 case lltok::kw_extractvalue: {
1663 SmallVector<unsigned, 4> Indices;
1664 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1665 ParseGlobalTypeAndValue(Val) ||
1666 ParseIndexList(Indices) ||
1667 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1669 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1670 return Error(ID.Loc, "extractvalue operand must be array or struct");
1671 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1673 return Error(ID.Loc, "invalid indices for extractvalue");
1674 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1675 &Indices[0], Indices.size());
1676 ID.Kind = ValID::t_Constant;
1679 case lltok::kw_insertvalue: {
1681 Constant *Val0, *Val1;
1682 SmallVector<unsigned, 4> Indices;
1683 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1684 ParseGlobalTypeAndValue(Val0) ||
1685 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1686 ParseGlobalTypeAndValue(Val1) ||
1687 ParseIndexList(Indices) ||
1688 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1690 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1691 return Error(ID.Loc, "extractvalue operand must be array or struct");
1692 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1694 return Error(ID.Loc, "invalid indices for insertvalue");
1695 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1696 &Indices[0], Indices.size());
1697 ID.Kind = ValID::t_Constant;
1700 case lltok::kw_icmp:
1701 case lltok::kw_fcmp:
1702 case lltok::kw_vicmp:
1703 case lltok::kw_vfcmp: {
1704 unsigned PredVal, Opc = Lex.getUIntVal();
1705 Constant *Val0, *Val1;
1707 if (ParseCmpPredicate(PredVal, Opc) ||
1708 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1709 ParseGlobalTypeAndValue(Val0) ||
1710 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1711 ParseGlobalTypeAndValue(Val1) ||
1712 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1715 if (Val0->getType() != Val1->getType())
1716 return Error(ID.Loc, "compare operands must have the same type");
1718 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1720 if (Opc == Instruction::FCmp) {
1721 if (!Val0->getType()->isFPOrFPVector())
1722 return Error(ID.Loc, "fcmp requires floating point operands");
1723 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1724 } else if (Opc == Instruction::ICmp) {
1725 if (!Val0->getType()->isIntOrIntVector() &&
1726 !isa<PointerType>(Val0->getType()))
1727 return Error(ID.Loc, "icmp requires pointer or integer operands");
1728 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1729 } else if (Opc == Instruction::VFCmp) {
1730 // FIXME: REMOVE VFCMP Support
1731 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1732 } else if (Opc == Instruction::VICmp) {
1733 // FIXME: REMOVE VFCMP Support
1734 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1736 ID.Kind = ValID::t_Constant;
1740 // Binary Operators.
1744 case lltok::kw_udiv:
1745 case lltok::kw_sdiv:
1746 case lltok::kw_fdiv:
1747 case lltok::kw_urem:
1748 case lltok::kw_srem:
1749 case lltok::kw_frem: {
1750 unsigned Opc = Lex.getUIntVal();
1751 Constant *Val0, *Val1;
1753 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1754 ParseGlobalTypeAndValue(Val0) ||
1755 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1756 ParseGlobalTypeAndValue(Val1) ||
1757 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1759 if (Val0->getType() != Val1->getType())
1760 return Error(ID.Loc, "operands of constexpr must have same type");
1761 if (!Val0->getType()->isIntOrIntVector() &&
1762 !Val0->getType()->isFPOrFPVector())
1763 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1764 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1765 ID.Kind = ValID::t_Constant;
1769 // Logical Operations
1771 case lltok::kw_lshr:
1772 case lltok::kw_ashr:
1775 case lltok::kw_xor: {
1776 unsigned Opc = Lex.getUIntVal();
1777 Constant *Val0, *Val1;
1779 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1780 ParseGlobalTypeAndValue(Val0) ||
1781 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1782 ParseGlobalTypeAndValue(Val1) ||
1783 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1785 if (Val0->getType() != Val1->getType())
1786 return Error(ID.Loc, "operands of constexpr must have same type");
1787 if (!Val0->getType()->isIntOrIntVector())
1788 return Error(ID.Loc,
1789 "constexpr requires integer or integer vector operands");
1790 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1791 ID.Kind = ValID::t_Constant;
1795 case lltok::kw_getelementptr:
1796 case lltok::kw_shufflevector:
1797 case lltok::kw_insertelement:
1798 case lltok::kw_extractelement:
1799 case lltok::kw_select: {
1800 unsigned Opc = Lex.getUIntVal();
1801 SmallVector<Constant*, 16> Elts;
1803 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1804 ParseGlobalValueVector(Elts) ||
1805 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1808 if (Opc == Instruction::GetElementPtr) {
1809 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1810 return Error(ID.Loc, "getelementptr requires pointer operand");
1812 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1813 (Value**)&Elts[1], Elts.size()-1))
1814 return Error(ID.Loc, "invalid indices for getelementptr");
1815 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1816 &Elts[1], Elts.size()-1);
1817 } else if (Opc == Instruction::Select) {
1818 if (Elts.size() != 3)
1819 return Error(ID.Loc, "expected three operands to select");
1820 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1822 return Error(ID.Loc, Reason);
1823 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1824 } else if (Opc == Instruction::ShuffleVector) {
1825 if (Elts.size() != 3)
1826 return Error(ID.Loc, "expected three operands to shufflevector");
1827 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1828 return Error(ID.Loc, "invalid operands to shufflevector");
1829 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1830 } else if (Opc == Instruction::ExtractElement) {
1831 if (Elts.size() != 2)
1832 return Error(ID.Loc, "expected two operands to extractelement");
1833 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1834 return Error(ID.Loc, "invalid extractelement operands");
1835 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1837 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1838 if (Elts.size() != 3)
1839 return Error(ID.Loc, "expected three operands to insertelement");
1840 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1841 return Error(ID.Loc, "invalid insertelement operands");
1842 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1845 ID.Kind = ValID::t_Constant;
1854 /// ParseGlobalValue - Parse a global value with the specified type.
1855 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1858 return ParseValID(ID) ||
1859 ConvertGlobalValIDToValue(Ty, ID, V);
1862 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1864 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1866 if (isa<FunctionType>(Ty))
1867 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1870 default: assert(0 && "Unknown ValID!");
1871 case ValID::t_LocalID:
1872 case ValID::t_LocalName:
1873 return Error(ID.Loc, "invalid use of function-local name");
1874 case ValID::t_InlineAsm:
1875 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1876 case ValID::t_GlobalName:
1877 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1879 case ValID::t_GlobalID:
1880 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1882 case ValID::t_APSInt:
1883 if (!isa<IntegerType>(Ty))
1884 return Error(ID.Loc, "integer constant must have integer type");
1885 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1886 V = ConstantInt::get(ID.APSIntVal);
1888 case ValID::t_APFloat:
1889 if (!Ty->isFloatingPoint() ||
1890 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1891 return Error(ID.Loc, "floating point constant invalid for type");
1893 // The lexer has no type info, so builds all float and double FP constants
1894 // as double. Fix this here. Long double does not need this.
1895 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1896 Ty == Type::FloatTy) {
1898 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1901 V = ConstantFP::get(ID.APFloatVal);
1904 if (!isa<PointerType>(Ty))
1905 return Error(ID.Loc, "null must be a pointer type");
1906 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1908 case ValID::t_Undef:
1909 // FIXME: LabelTy should not be a first-class type.
1910 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
1911 return Error(ID.Loc, "invalid type for undef constant");
1912 V = UndefValue::get(Ty);
1914 case ValID::t_EmptyArray:
1915 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
1916 return Error(ID.Loc, "invalid empty array initializer");
1917 V = UndefValue::get(Ty);
1920 // FIXME: LabelTy should not be a first-class type.
1921 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
1922 return Error(ID.Loc, "invalid type for null constant");
1923 V = Constant::getNullValue(Ty);
1925 case ValID::t_Constant:
1926 if (ID.ConstantVal->getType() != Ty)
1927 return Error(ID.Loc, "constant expression type mismatch");
1933 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
1934 PATypeHolder Type(Type::VoidTy);
1935 return ParseType(Type) ||
1936 ParseGlobalValue(Type, V);
1939 /// ParseGlobalValueVector
1941 /// ::= TypeAndValue (',' TypeAndValue)*
1942 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
1944 if (Lex.getKind() == lltok::rbrace ||
1945 Lex.getKind() == lltok::rsquare ||
1946 Lex.getKind() == lltok::greater ||
1947 Lex.getKind() == lltok::rparen)
1951 if (ParseGlobalTypeAndValue(C)) return true;
1954 while (EatIfPresent(lltok::comma)) {
1955 if (ParseGlobalTypeAndValue(C)) return true;
1963 //===----------------------------------------------------------------------===//
1964 // Function Parsing.
1965 //===----------------------------------------------------------------------===//
1967 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
1968 PerFunctionState &PFS) {
1969 if (ID.Kind == ValID::t_LocalID)
1970 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
1971 else if (ID.Kind == ValID::t_LocalName)
1972 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
1973 else if (ID.Kind == ValID::ValID::t_InlineAsm) {
1974 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1975 const FunctionType *FTy =
1976 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1977 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
1978 return Error(ID.Loc, "invalid type for inline asm constraint string");
1979 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
1983 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
1991 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
1994 return ParseValID(ID) ||
1995 ConvertValIDToValue(Ty, ID, V, PFS);
1998 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
1999 PATypeHolder T(Type::VoidTy);
2000 return ParseType(T) ||
2001 ParseValue(T, V, PFS);
2005 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2006 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2007 /// OptionalAlign OptGC
2008 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2009 // Parse the linkage.
2010 LocTy LinkageLoc = Lex.getLoc();
2013 unsigned Visibility, CC, RetAttrs;
2014 PATypeHolder RetType(Type::VoidTy);
2015 LocTy RetTypeLoc = Lex.getLoc();
2016 if (ParseOptionalLinkage(Linkage) ||
2017 ParseOptionalVisibility(Visibility) ||
2018 ParseOptionalCallingConv(CC) ||
2019 ParseOptionalAttrs(RetAttrs, 1) ||
2020 ParseType(RetType, RetTypeLoc))
2023 // Verify that the linkage is ok.
2024 switch ((GlobalValue::LinkageTypes)Linkage) {
2025 case GlobalValue::ExternalLinkage:
2026 break; // always ok.
2027 case GlobalValue::DLLImportLinkage:
2028 case GlobalValue::ExternalWeakLinkage:
2030 return Error(LinkageLoc, "invalid linkage for function definition");
2032 case GlobalValue::InternalLinkage:
2033 case GlobalValue::LinkOnceLinkage:
2034 case GlobalValue::WeakLinkage:
2035 case GlobalValue::DLLExportLinkage:
2037 return Error(LinkageLoc, "invalid linkage for function declaration");
2039 case GlobalValue::AppendingLinkage:
2040 case GlobalValue::GhostLinkage:
2041 case GlobalValue::CommonLinkage:
2042 return Error(LinkageLoc, "invalid function linkage type");
2045 if (!FunctionType::isValidReturnType(RetType) ||
2046 isa<OpaqueType>(RetType))
2047 return Error(RetTypeLoc, "invalid function return type");
2049 if (Lex.getKind() != lltok::GlobalVar)
2050 return TokError("expected function name");
2052 LocTy NameLoc = Lex.getLoc();
2053 std::string FunctionName = Lex.getStrVal();
2056 if (Lex.getKind() != lltok::lparen)
2057 return TokError("expected '(' in function argument list");
2059 std::vector<ArgInfo> ArgList;
2062 std::string Section;
2066 if (ParseArgumentList(ArgList, isVarArg) ||
2067 ParseOptionalAttrs(FuncAttrs, 2) ||
2068 (EatIfPresent(lltok::kw_section) &&
2069 ParseStringConstant(Section)) ||
2070 ParseOptionalAlignment(Alignment) ||
2071 (EatIfPresent(lltok::kw_gc) &&
2072 ParseStringConstant(GC)))
2075 // If the alignment was parsed as an attribute, move to the alignment field.
2076 if (FuncAttrs & Attribute::Alignment) {
2077 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2078 FuncAttrs &= ~Attribute::Alignment;
2081 // Okay, if we got here, the function is syntactically valid. Convert types
2082 // and do semantic checks.
2083 std::vector<const Type*> ParamTypeList;
2084 SmallVector<AttributeWithIndex, 8> Attrs;
2085 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2087 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2088 if (FuncAttrs & ObsoleteFuncAttrs) {
2089 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2090 FuncAttrs &= ~ObsoleteFuncAttrs;
2093 if (RetAttrs != Attribute::None)
2094 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2096 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2097 ParamTypeList.push_back(ArgList[i].Type);
2098 if (ArgList[i].Attrs != Attribute::None)
2099 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2102 if (FuncAttrs != Attribute::None)
2103 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2105 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2107 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2108 const PointerType *PFT = PointerType::getUnqual(FT);
2111 if (!FunctionName.empty()) {
2112 // If this was a definition of a forward reference, remove the definition
2113 // from the forward reference table and fill in the forward ref.
2114 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2115 ForwardRefVals.find(FunctionName);
2116 if (FRVI != ForwardRefVals.end()) {
2117 Fn = M->getFunction(FunctionName);
2118 ForwardRefVals.erase(FRVI);
2119 } else if ((Fn = M->getFunction(FunctionName))) {
2120 // If this function already exists in the symbol table, then it is
2121 // multiply defined. We accept a few cases for old backwards compat.
2122 // FIXME: Remove this stuff for LLVM 3.0.
2123 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2124 (!Fn->isDeclaration() && isDefine)) {
2125 // If the redefinition has different type or different attributes,
2126 // reject it. If both have bodies, reject it.
2127 return Error(NameLoc, "invalid redefinition of function '" +
2128 FunctionName + "'");
2129 } else if (Fn->isDeclaration()) {
2130 // Make sure to strip off any argument names so we can't get conflicts.
2131 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2137 } else if (FunctionName.empty()) {
2138 // If this is a definition of a forward referenced function, make sure the
2140 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2141 = ForwardRefValIDs.find(NumberedVals.size());
2142 if (I != ForwardRefValIDs.end()) {
2143 Fn = cast<Function>(I->second.first);
2144 if (Fn->getType() != PFT)
2145 return Error(NameLoc, "type of definition and forward reference of '@" +
2146 utostr(NumberedVals.size()) +"' disagree");
2147 ForwardRefValIDs.erase(I);
2152 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2153 else // Move the forward-reference to the correct spot in the module.
2154 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2156 if (FunctionName.empty())
2157 NumberedVals.push_back(Fn);
2159 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2160 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2161 Fn->setCallingConv(CC);
2162 Fn->setAttributes(PAL);
2163 Fn->setAlignment(Alignment);
2164 Fn->setSection(Section);
2165 if (!GC.empty()) Fn->setGC(GC.c_str());
2167 // Add all of the arguments we parsed to the function.
2168 Function::arg_iterator ArgIt = Fn->arg_begin();
2169 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2170 // If the argument has a name, insert it into the argument symbol table.
2171 if (ArgList[i].Name.empty()) continue;
2173 // Set the name, if it conflicted, it will be auto-renamed.
2174 ArgIt->setName(ArgList[i].Name);
2176 if (ArgIt->getNameStr() != ArgList[i].Name)
2177 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2178 ArgList[i].Name + "'");
2185 /// ParseFunctionBody
2186 /// ::= '{' BasicBlock+ '}'
2187 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2189 bool LLParser::ParseFunctionBody(Function &Fn) {
2190 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2191 return TokError("expected '{' in function body");
2192 Lex.Lex(); // eat the {.
2194 PerFunctionState PFS(*this, Fn);
2196 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2197 if (ParseBasicBlock(PFS)) return true;
2202 // Verify function is ok.
2203 return PFS.VerifyFunctionComplete();
2207 /// ::= LabelStr? Instruction*
2208 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2209 // If this basic block starts out with a name, remember it.
2211 LocTy NameLoc = Lex.getLoc();
2212 if (Lex.getKind() == lltok::LabelStr) {
2213 Name = Lex.getStrVal();
2217 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2218 if (BB == 0) return true;
2220 std::string NameStr;
2222 // Parse the instructions in this block until we get a terminator.
2225 // This instruction may have three possibilities for a name: a) none
2226 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2227 LocTy NameLoc = Lex.getLoc();
2231 if (Lex.getKind() == lltok::LocalVarID) {
2232 NameID = Lex.getUIntVal();
2234 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2236 } else if (Lex.getKind() == lltok::LocalVar ||
2237 // FIXME: REMOVE IN LLVM 3.0
2238 Lex.getKind() == lltok::StringConstant) {
2239 NameStr = Lex.getStrVal();
2241 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2245 if (ParseInstruction(Inst, BB, PFS)) return true;
2247 BB->getInstList().push_back(Inst);
2249 // Set the name on the instruction.
2250 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2251 } while (!isa<TerminatorInst>(Inst));
2256 //===----------------------------------------------------------------------===//
2257 // Instruction Parsing.
2258 //===----------------------------------------------------------------------===//
2260 /// ParseInstruction - Parse one of the many different instructions.
2262 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2263 PerFunctionState &PFS) {
2264 lltok::Kind Token = Lex.getKind();
2265 if (Token == lltok::Eof)
2266 return TokError("found end of file when expecting more instructions");
2267 LocTy Loc = Lex.getLoc();
2268 Lex.Lex(); // Eat the keyword.
2271 default: return Error(Loc, "expected instruction opcode");
2272 // Terminator Instructions.
2273 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2274 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2275 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2276 case lltok::kw_br: return ParseBr(Inst, PFS);
2277 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2278 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2279 // Binary Operators.
2283 case lltok::kw_udiv:
2284 case lltok::kw_sdiv:
2285 case lltok::kw_fdiv:
2286 case lltok::kw_urem:
2287 case lltok::kw_srem:
2288 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, Lex.getUIntVal());
2290 case lltok::kw_lshr:
2291 case lltok::kw_ashr:
2294 case lltok::kw_xor: return ParseLogical(Inst, PFS, Lex.getUIntVal());
2295 case lltok::kw_icmp:
2296 case lltok::kw_fcmp:
2297 case lltok::kw_vicmp:
2298 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, Lex.getUIntVal());
2300 case lltok::kw_trunc:
2301 case lltok::kw_zext:
2302 case lltok::kw_sext:
2303 case lltok::kw_fptrunc:
2304 case lltok::kw_fpext:
2305 case lltok::kw_bitcast:
2306 case lltok::kw_uitofp:
2307 case lltok::kw_sitofp:
2308 case lltok::kw_fptoui:
2309 case lltok::kw_fptosi:
2310 case lltok::kw_inttoptr:
2311 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, Lex.getUIntVal());
2313 case lltok::kw_select: return ParseSelect(Inst, PFS);
2314 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2315 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2316 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2317 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2318 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2319 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2320 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2322 case lltok::kw_alloca:
2323 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, Lex.getUIntVal());
2324 case lltok::kw_free: return ParseFree(Inst, PFS);
2325 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2326 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2327 case lltok::kw_volatile:
2328 if (EatIfPresent(lltok::kw_load))
2329 return ParseLoad(Inst, PFS, true);
2330 else if (EatIfPresent(lltok::kw_store))
2331 return ParseStore(Inst, PFS, true);
2333 return TokError("expected 'load' or 'store'");
2334 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2335 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2336 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2337 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2341 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2342 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2343 // FIXME: REMOVE vicmp/vfcmp!
2344 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2345 switch (Lex.getKind()) {
2346 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2347 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2348 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2349 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2350 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2351 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2352 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2353 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2354 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2355 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2356 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2357 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2358 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2359 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2360 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2361 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2362 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2365 switch (Lex.getKind()) {
2366 default: TokError("expected icmp predicate (e.g. 'eq')");
2367 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2368 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2369 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2370 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2371 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2372 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2373 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2374 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2375 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2376 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2383 //===----------------------------------------------------------------------===//
2384 // Terminator Instructions.
2385 //===----------------------------------------------------------------------===//
2387 /// ParseRet - Parse a return instruction.
2389 /// ::= 'ret' TypeAndValue
2390 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2391 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2392 PerFunctionState &PFS) {
2393 PATypeHolder Ty(Type::VoidTy);
2394 if (ParseType(Ty)) return true;
2396 if (Ty == Type::VoidTy) {
2397 Inst = ReturnInst::Create();
2402 if (ParseValue(Ty, RV, PFS)) return true;
2404 // The normal case is one return value.
2405 if (Lex.getKind() == lltok::comma) {
2406 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2407 // of 'ret {i32,i32} {i32 1, i32 2}'
2408 SmallVector<Value*, 8> RVs;
2411 while (EatIfPresent(lltok::comma)) {
2412 if (ParseTypeAndValue(RV, PFS)) return true;
2416 RV = UndefValue::get(PFS.getFunction().getReturnType());
2417 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2418 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2419 BB->getInstList().push_back(I);
2423 Inst = ReturnInst::Create(RV);
2429 /// ::= 'br' TypeAndValue
2430 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2431 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2433 Value *Op0, *Op1, *Op2;
2434 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2436 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2437 Inst = BranchInst::Create(BB);
2441 if (Op0->getType() != Type::Int1Ty)
2442 return Error(Loc, "branch condition must have 'i1' type");
2444 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2445 ParseTypeAndValue(Op1, Loc, PFS) ||
2446 ParseToken(lltok::comma, "expected ',' after true destination") ||
2447 ParseTypeAndValue(Op2, Loc2, PFS))
2450 if (!isa<BasicBlock>(Op1))
2451 return Error(Loc, "true destination of branch must be a basic block");
2452 if (!isa<BasicBlock>(Op2))
2453 return Error(Loc2, "true destination of branch must be a basic block");
2455 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2461 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2463 /// ::= (TypeAndValue ',' TypeAndValue)*
2464 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2465 LocTy CondLoc, BBLoc;
2466 Value *Cond, *DefaultBB;
2467 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2468 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2469 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2470 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2473 if (!isa<IntegerType>(Cond->getType()))
2474 return Error(CondLoc, "switch condition must have integer type");
2475 if (!isa<BasicBlock>(DefaultBB))
2476 return Error(BBLoc, "default destination must be a basic block");
2478 // Parse the jump table pairs.
2479 SmallPtrSet<Value*, 32> SeenCases;
2480 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2481 while (Lex.getKind() != lltok::rsquare) {
2482 Value *Constant, *DestBB;
2484 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2485 ParseToken(lltok::comma, "expected ',' after case value") ||
2486 ParseTypeAndValue(DestBB, BBLoc, PFS))
2489 if (!SeenCases.insert(Constant))
2490 return Error(CondLoc, "duplicate case value in switch");
2491 if (!isa<ConstantInt>(Constant))
2492 return Error(CondLoc, "case value is not a constant integer");
2493 if (!isa<BasicBlock>(DestBB))
2494 return Error(BBLoc, "case destination is not a basic block");
2496 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2497 cast<BasicBlock>(DestBB)));
2500 Lex.Lex(); // Eat the ']'.
2502 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2504 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2505 SI->addCase(Table[i].first, Table[i].second);
2511 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2512 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2513 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2514 LocTy CallLoc = Lex.getLoc();
2515 unsigned CC, RetAttrs, FnAttrs;
2516 PATypeHolder RetType(Type::VoidTy);
2519 SmallVector<ParamInfo, 16> ArgList;
2521 Value *NormalBB, *UnwindBB;
2522 if (ParseOptionalCallingConv(CC) ||
2523 ParseOptionalAttrs(RetAttrs, 1) ||
2524 ParseType(RetType, RetTypeLoc) ||
2525 ParseValID(CalleeID) ||
2526 ParseParameterList(ArgList, PFS) ||
2527 ParseOptionalAttrs(FnAttrs, 2) ||
2528 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2529 ParseTypeAndValue(NormalBB, PFS) ||
2530 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2531 ParseTypeAndValue(UnwindBB, PFS))
2534 if (!isa<BasicBlock>(NormalBB))
2535 return Error(CallLoc, "normal destination is not a basic block");
2536 if (!isa<BasicBlock>(UnwindBB))
2537 return Error(CallLoc, "unwind destination is not a basic block");
2539 // If RetType is a non-function pointer type, then this is the short syntax
2540 // for the call, which means that RetType is just the return type. Infer the
2541 // rest of the function argument types from the arguments that are present.
2542 const PointerType *PFTy = 0;
2543 const FunctionType *Ty = 0;
2544 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2545 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2546 // Pull out the types of all of the arguments...
2547 std::vector<const Type*> ParamTypes;
2548 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2549 ParamTypes.push_back(ArgList[i].V->getType());
2551 if (!FunctionType::isValidReturnType(RetType))
2552 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2554 Ty = FunctionType::get(RetType, ParamTypes, false);
2555 PFTy = PointerType::getUnqual(Ty);
2558 // Look up the callee.
2560 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2562 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2563 // function attributes.
2564 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2565 if (FnAttrs & ObsoleteFuncAttrs) {
2566 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2567 FnAttrs &= ~ObsoleteFuncAttrs;
2570 // Set up the Attributes for the function.
2571 SmallVector<AttributeWithIndex, 8> Attrs;
2572 if (RetAttrs != Attribute::None)
2573 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2575 SmallVector<Value*, 8> Args;
2577 // Loop through FunctionType's arguments and ensure they are specified
2578 // correctly. Also, gather any parameter attributes.
2579 FunctionType::param_iterator I = Ty->param_begin();
2580 FunctionType::param_iterator E = Ty->param_end();
2581 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2582 const Type *ExpectedTy = 0;
2585 } else if (!Ty->isVarArg()) {
2586 return Error(ArgList[i].Loc, "too many arguments specified");
2589 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2590 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2591 ExpectedTy->getDescription() + "'");
2592 Args.push_back(ArgList[i].V);
2593 if (ArgList[i].Attrs != Attribute::None)
2594 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2598 return Error(CallLoc, "not enough parameters specified for call");
2600 if (FnAttrs != Attribute::None)
2601 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2603 // Finish off the Attributes and check them
2604 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2606 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2607 cast<BasicBlock>(UnwindBB),
2608 Args.begin(), Args.end());
2609 II->setCallingConv(CC);
2610 II->setAttributes(PAL);
2617 //===----------------------------------------------------------------------===//
2618 // Binary Operators.
2619 //===----------------------------------------------------------------------===//
2622 /// ::= ArithmeticOps TypeAndValue ',' Value {
2623 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2625 LocTy Loc; Value *LHS, *RHS;
2626 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2627 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2628 ParseValue(LHS->getType(), RHS, PFS))
2631 if (!isa<IntegerType>(LHS->getType()) && !LHS->getType()->isFloatingPoint() &&
2632 !isa<VectorType>(LHS->getType()))
2633 return Error(Loc, "instruction requires integer, fp, or vector operands");
2635 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2640 /// ::= ArithmeticOps TypeAndValue ',' Value {
2641 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2643 LocTy Loc; Value *LHS, *RHS;
2644 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2645 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2646 ParseValue(LHS->getType(), RHS, PFS))
2649 if (!LHS->getType()->isIntOrIntVector())
2650 return Error(Loc,"instruction requires integer or integer vector operands");
2652 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2658 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2659 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2660 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2661 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2662 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2664 // Parse the integer/fp comparison predicate.
2668 if (ParseCmpPredicate(Pred, Opc) ||
2669 ParseTypeAndValue(LHS, Loc, PFS) ||
2670 ParseToken(lltok::comma, "expected ',' after compare value") ||
2671 ParseValue(LHS->getType(), RHS, PFS))
2674 if (Opc == Instruction::FCmp) {
2675 if (!LHS->getType()->isFPOrFPVector())
2676 return Error(Loc, "fcmp requires floating point operands");
2677 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2678 } else if (Opc == Instruction::ICmp) {
2679 if (!LHS->getType()->isIntOrIntVector() &&
2680 !isa<PointerType>(LHS->getType()))
2681 return Error(Loc, "icmp requires integer operands");
2682 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2683 } else if (Opc == Instruction::VFCmp) {
2684 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2685 return Error(Loc, "vfcmp requires vector floating point operands");
2686 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2687 } else if (Opc == Instruction::VICmp) {
2688 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2689 return Error(Loc, "vicmp requires vector floating point operands");
2690 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2695 //===----------------------------------------------------------------------===//
2696 // Other Instructions.
2697 //===----------------------------------------------------------------------===//
2701 /// ::= CastOpc TypeAndValue 'to' Type
2702 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2704 LocTy Loc; Value *Op;
2705 PATypeHolder DestTy(Type::VoidTy);
2706 if (ParseTypeAndValue(Op, Loc, PFS) ||
2707 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2711 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy))
2712 return Error(Loc, "invalid cast opcode for cast from '" +
2713 Op->getType()->getDescription() + "' to '" +
2714 DestTy->getDescription() + "'");
2715 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2720 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2721 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2723 Value *Op0, *Op1, *Op2;
2724 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2725 ParseToken(lltok::comma, "expected ',' after select condition") ||
2726 ParseTypeAndValue(Op1, PFS) ||
2727 ParseToken(lltok::comma, "expected ',' after select value") ||
2728 ParseTypeAndValue(Op2, PFS))
2731 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2732 return Error(Loc, Reason);
2734 Inst = SelectInst::Create(Op0, Op1, Op2);
2739 /// ::= 'va_arg' TypeAndValue ',' Type
2740 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2742 PATypeHolder EltTy(Type::VoidTy);
2744 if (ParseTypeAndValue(Op, PFS) ||
2745 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2746 ParseType(EltTy, TypeLoc))
2749 if (!EltTy->isFirstClassType())
2750 return Error(TypeLoc, "va_arg requires operand with first class type");
2752 Inst = new VAArgInst(Op, EltTy);
2756 /// ParseExtractElement
2757 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2758 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2761 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2762 ParseToken(lltok::comma, "expected ',' after extract value") ||
2763 ParseTypeAndValue(Op1, PFS))
2766 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2767 return Error(Loc, "invalid extractelement operands");
2769 Inst = new ExtractElementInst(Op0, Op1);
2773 /// ParseInsertElement
2774 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2775 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2777 Value *Op0, *Op1, *Op2;
2778 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2779 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2780 ParseTypeAndValue(Op1, PFS) ||
2781 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2782 ParseTypeAndValue(Op2, PFS))
2785 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2786 return Error(Loc, "invalid extractelement operands");
2788 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2792 /// ParseShuffleVector
2793 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2794 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2796 Value *Op0, *Op1, *Op2;
2797 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2798 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2799 ParseTypeAndValue(Op1, PFS) ||
2800 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2801 ParseTypeAndValue(Op2, PFS))
2804 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2805 return Error(Loc, "invalid extractelement operands");
2807 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2812 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2813 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2814 PATypeHolder Ty(Type::VoidTy);
2816 LocTy TypeLoc = Lex.getLoc();
2818 if (ParseType(Ty) ||
2819 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2820 ParseValue(Ty, Op0, PFS) ||
2821 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2822 ParseValue(Type::LabelTy, Op1, PFS) ||
2823 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2826 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2828 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2830 if (!EatIfPresent(lltok::comma))
2833 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2834 ParseValue(Ty, Op0, PFS) ||
2835 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2836 ParseValue(Type::LabelTy, Op1, PFS) ||
2837 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2841 if (!Ty->isFirstClassType())
2842 return Error(TypeLoc, "phi node must have first class type");
2844 PHINode *PN = PHINode::Create(Ty);
2845 PN->reserveOperandSpace(PHIVals.size());
2846 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2847 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2853 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2854 /// ParameterList OptionalAttrs
2855 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2857 unsigned CC, RetAttrs, FnAttrs;
2858 PATypeHolder RetType(Type::VoidTy);
2861 SmallVector<ParamInfo, 16> ArgList;
2862 LocTy CallLoc = Lex.getLoc();
2864 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2865 ParseOptionalCallingConv(CC) ||
2866 ParseOptionalAttrs(RetAttrs, 1) ||
2867 ParseType(RetType, RetTypeLoc) ||
2868 ParseValID(CalleeID) ||
2869 ParseParameterList(ArgList, PFS) ||
2870 ParseOptionalAttrs(FnAttrs, 2))
2873 // If RetType is a non-function pointer type, then this is the short syntax
2874 // for the call, which means that RetType is just the return type. Infer the
2875 // rest of the function argument types from the arguments that are present.
2876 const PointerType *PFTy = 0;
2877 const FunctionType *Ty = 0;
2878 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2879 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2880 // Pull out the types of all of the arguments...
2881 std::vector<const Type*> ParamTypes;
2882 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2883 ParamTypes.push_back(ArgList[i].V->getType());
2885 if (!FunctionType::isValidReturnType(RetType))
2886 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2888 Ty = FunctionType::get(RetType, ParamTypes, false);
2889 PFTy = PointerType::getUnqual(Ty);
2892 // Look up the callee.
2894 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2896 // Check for call to invalid intrinsic to avoid crashing later.
2897 if (Function *F = dyn_cast<Function>(Callee)) {
2898 if (F->hasName() && F->getNameLen() >= 5 &&
2899 !strncmp(F->getValueName()->getKeyData(), "llvm.", 5) &&
2900 !F->getIntrinsicID(true))
2901 return Error(CallLoc, "Call to invalid LLVM intrinsic function '" +
2902 F->getNameStr() + "'");
2905 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2906 // function attributes.
2907 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2908 if (FnAttrs & ObsoleteFuncAttrs) {
2909 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2910 FnAttrs &= ~ObsoleteFuncAttrs;
2913 // Set up the Attributes for the function.
2914 SmallVector<AttributeWithIndex, 8> Attrs;
2915 if (RetAttrs != Attribute::None)
2916 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2918 SmallVector<Value*, 8> Args;
2920 // Loop through FunctionType's arguments and ensure they are specified
2921 // correctly. Also, gather any parameter attributes.
2922 FunctionType::param_iterator I = Ty->param_begin();
2923 FunctionType::param_iterator E = Ty->param_end();
2924 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2925 const Type *ExpectedTy = 0;
2928 } else if (!Ty->isVarArg()) {
2929 return Error(ArgList[i].Loc, "too many arguments specified");
2932 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2933 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2934 ExpectedTy->getDescription() + "'");
2935 Args.push_back(ArgList[i].V);
2936 if (ArgList[i].Attrs != Attribute::None)
2937 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2941 return Error(CallLoc, "not enough parameters specified for call");
2943 if (FnAttrs != Attribute::None)
2944 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2946 // Finish off the Attributes and check them
2947 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2949 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
2950 CI->setTailCall(isTail);
2951 CI->setCallingConv(CC);
2952 CI->setAttributes(PAL);
2957 //===----------------------------------------------------------------------===//
2958 // Memory Instructions.
2959 //===----------------------------------------------------------------------===//
2962 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
2963 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
2964 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
2966 PATypeHolder Ty(Type::VoidTy);
2969 unsigned Alignment = 0;
2970 if (ParseType(Ty)) return true;
2972 if (EatIfPresent(lltok::comma)) {
2973 if (Lex.getKind() == lltok::kw_align) {
2974 if (ParseOptionalAlignment(Alignment)) return true;
2975 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
2976 ParseOptionalCommaAlignment(Alignment)) {
2981 if (Size && Size->getType() != Type::Int32Ty)
2982 return Error(SizeLoc, "element count must be i32");
2984 if (Opc == Instruction::Malloc)
2985 Inst = new MallocInst(Ty, Size, Alignment);
2987 Inst = new AllocaInst(Ty, Size, Alignment);
2992 /// ::= 'free' TypeAndValue
2993 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
2994 Value *Val; LocTy Loc;
2995 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
2996 if (!isa<PointerType>(Val->getType()))
2997 return Error(Loc, "operand to free must be a pointer");
2998 Inst = new FreeInst(Val);
3003 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3004 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3006 Value *Val; LocTy Loc;
3008 if (ParseTypeAndValue(Val, Loc, PFS) ||
3009 ParseOptionalCommaAlignment(Alignment))
3012 if (!isa<PointerType>(Val->getType()) ||
3013 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3014 return Error(Loc, "load operand must be a pointer to a first class type");
3016 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3021 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3022 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3024 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3026 if (ParseTypeAndValue(Val, Loc, PFS) ||
3027 ParseToken(lltok::comma, "expected ',' after store operand") ||
3028 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3029 ParseOptionalCommaAlignment(Alignment))
3032 if (!isa<PointerType>(Ptr->getType()))
3033 return Error(PtrLoc, "store operand must be a pointer");
3034 if (!Val->getType()->isFirstClassType())
3035 return Error(Loc, "store operand must be a first class value");
3036 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3037 return Error(Loc, "stored value and pointer type do not match");
3039 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3044 /// ::= 'getresult' TypeAndValue ',' uint
3045 /// FIXME: Remove support for getresult in LLVM 3.0
3046 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3047 Value *Val; LocTy ValLoc, EltLoc;
3049 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3050 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3051 ParseUInt32(Element, EltLoc))
3054 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3055 return Error(ValLoc, "getresult inst requires an aggregate operand");
3056 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3057 return Error(EltLoc, "invalid getresult index for value");
3058 Inst = ExtractValueInst::Create(Val, Element);
3062 /// ParseGetElementPtr
3063 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3064 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3065 Value *Ptr, *Val; LocTy Loc, EltLoc;
3066 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3068 if (!isa<PointerType>(Ptr->getType()))
3069 return Error(Loc, "base of getelementptr must be a pointer");
3071 SmallVector<Value*, 16> Indices;
3072 while (EatIfPresent(lltok::comma)) {
3073 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3074 if (!isa<IntegerType>(Val->getType()))
3075 return Error(EltLoc, "getelementptr index must be an integer");
3076 Indices.push_back(Val);
3079 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3080 Indices.begin(), Indices.end()))
3081 return Error(Loc, "invalid getelementptr indices");
3082 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3086 /// ParseExtractValue
3087 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3088 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3089 Value *Val; LocTy Loc;
3090 SmallVector<unsigned, 4> Indices;
3091 if (ParseTypeAndValue(Val, Loc, PFS) ||
3092 ParseIndexList(Indices))
3095 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3096 return Error(Loc, "extractvalue operand must be array or struct");
3098 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3100 return Error(Loc, "invalid indices for extractvalue");
3101 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3105 /// ParseInsertValue
3106 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3107 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3108 Value *Val0, *Val1; LocTy Loc0, Loc1;
3109 SmallVector<unsigned, 4> Indices;
3110 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3111 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3112 ParseTypeAndValue(Val1, Loc1, PFS) ||
3113 ParseIndexList(Indices))
3116 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3117 return Error(Loc0, "extractvalue operand must be array or struct");
3119 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3121 return Error(Loc0, "invalid indices for insertvalue");
3122 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());