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/LLVMContext.h"
22 #include "llvm/MDNode.h"
23 #include "llvm/Module.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/raw_ostream.h"
31 /// ValID - Represents a reference of a definition of some sort with no type.
32 /// There are several cases where we have to parse the value but where the
33 /// type can depend on later context. This may either be a numeric reference
34 /// or a symbolic (%var) reference. This is just a discriminated union.
37 t_LocalID, t_GlobalID, // ID in UIntVal.
38 t_LocalName, t_GlobalName, // Name in StrVal.
39 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
40 t_Null, t_Undef, t_Zero, // No value.
41 t_EmptyArray, // No value: []
42 t_Constant, // Value in ConstantVal.
43 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
48 std::string StrVal, StrVal2;
51 Constant *ConstantVal;
52 ValID() : APFloatVal(0.0) {}
56 /// Run: module ::= toplevelentity*
57 bool LLParser::Run() {
61 return ParseTopLevelEntities() ||
62 ValidateEndOfModule();
65 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
67 bool LLParser::ValidateEndOfModule() {
68 if (!ForwardRefTypes.empty())
69 return Error(ForwardRefTypes.begin()->second.second,
70 "use of undefined type named '" +
71 ForwardRefTypes.begin()->first + "'");
72 if (!ForwardRefTypeIDs.empty())
73 return Error(ForwardRefTypeIDs.begin()->second.second,
74 "use of undefined type '%" +
75 utostr(ForwardRefTypeIDs.begin()->first) + "'");
77 if (!ForwardRefVals.empty())
78 return Error(ForwardRefVals.begin()->second.second,
79 "use of undefined value '@" + ForwardRefVals.begin()->first +
82 if (!ForwardRefValIDs.empty())
83 return Error(ForwardRefValIDs.begin()->second.second,
84 "use of undefined value '@" +
85 utostr(ForwardRefValIDs.begin()->first) + "'");
87 // Look for intrinsic functions and CallInst that need to be upgraded
88 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
89 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
94 //===----------------------------------------------------------------------===//
96 //===----------------------------------------------------------------------===//
98 bool LLParser::ParseTopLevelEntities() {
100 switch (Lex.getKind()) {
101 default: return TokError("expected top-level entity");
102 case lltok::Eof: return false;
103 //case lltok::kw_define:
104 case lltok::kw_declare: if (ParseDeclare()) return true; break;
105 case lltok::kw_define: if (ParseDefine()) return true; break;
106 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
107 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
108 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
109 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
110 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
111 case lltok::LocalVar: if (ParseNamedType()) return true; break;
112 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
113 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
115 // The Global variable production with no name can have many different
116 // optional leading prefixes, the production is:
117 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
118 // OptionalAddrSpace ('constant'|'global') ...
119 case lltok::kw_private: // OptionalLinkage
120 case lltok::kw_internal: // OptionalLinkage
121 case lltok::kw_weak: // OptionalLinkage
122 case lltok::kw_weak_odr: // OptionalLinkage
123 case lltok::kw_linkonce: // OptionalLinkage
124 case lltok::kw_linkonce_odr: // OptionalLinkage
125 case lltok::kw_appending: // OptionalLinkage
126 case lltok::kw_dllexport: // OptionalLinkage
127 case lltok::kw_common: // OptionalLinkage
128 case lltok::kw_dllimport: // OptionalLinkage
129 case lltok::kw_extern_weak: // OptionalLinkage
130 case lltok::kw_external: { // OptionalLinkage
131 unsigned Linkage, Visibility;
132 if (ParseOptionalLinkage(Linkage) ||
133 ParseOptionalVisibility(Visibility) ||
134 ParseGlobal("", 0, Linkage, true, Visibility))
138 case lltok::kw_default: // OptionalVisibility
139 case lltok::kw_hidden: // OptionalVisibility
140 case lltok::kw_protected: { // OptionalVisibility
142 if (ParseOptionalVisibility(Visibility) ||
143 ParseGlobal("", 0, 0, false, Visibility))
148 case lltok::kw_thread_local: // OptionalThreadLocal
149 case lltok::kw_addrspace: // OptionalAddrSpace
150 case lltok::kw_constant: // GlobalType
151 case lltok::kw_global: // GlobalType
152 if (ParseGlobal("", 0, 0, false, 0)) return true;
160 /// ::= 'module' 'asm' STRINGCONSTANT
161 bool LLParser::ParseModuleAsm() {
162 assert(Lex.getKind() == lltok::kw_module);
166 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
167 ParseStringConstant(AsmStr)) return true;
169 const std::string &AsmSoFar = M->getModuleInlineAsm();
170 if (AsmSoFar.empty())
171 M->setModuleInlineAsm(AsmStr);
173 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
178 /// ::= 'target' 'triple' '=' STRINGCONSTANT
179 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
180 bool LLParser::ParseTargetDefinition() {
181 assert(Lex.getKind() == lltok::kw_target);
184 default: return TokError("unknown target property");
185 case lltok::kw_triple:
187 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
188 ParseStringConstant(Str))
190 M->setTargetTriple(Str);
192 case lltok::kw_datalayout:
194 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
195 ParseStringConstant(Str))
197 M->setDataLayout(Str);
203 /// ::= 'deplibs' '=' '[' ']'
204 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
205 bool LLParser::ParseDepLibs() {
206 assert(Lex.getKind() == lltok::kw_deplibs);
208 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
209 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
212 if (EatIfPresent(lltok::rsquare))
216 if (ParseStringConstant(Str)) return true;
219 while (EatIfPresent(lltok::comma)) {
220 if (ParseStringConstant(Str)) return true;
224 return ParseToken(lltok::rsquare, "expected ']' at end of list");
229 bool LLParser::ParseUnnamedType() {
230 assert(Lex.getKind() == lltok::kw_type);
231 LocTy TypeLoc = Lex.getLoc();
232 Lex.Lex(); // eat kw_type
234 PATypeHolder Ty(Type::VoidTy);
235 if (ParseType(Ty)) return true;
237 unsigned TypeID = NumberedTypes.size();
239 // See if this type was previously referenced.
240 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
241 FI = ForwardRefTypeIDs.find(TypeID);
242 if (FI != ForwardRefTypeIDs.end()) {
243 if (FI->second.first.get() == Ty)
244 return Error(TypeLoc, "self referential type is invalid");
246 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
247 Ty = FI->second.first.get();
248 ForwardRefTypeIDs.erase(FI);
251 NumberedTypes.push_back(Ty);
257 /// ::= LocalVar '=' 'type' type
258 bool LLParser::ParseNamedType() {
259 std::string Name = Lex.getStrVal();
260 LocTy NameLoc = Lex.getLoc();
261 Lex.Lex(); // eat LocalVar.
263 PATypeHolder Ty(Type::VoidTy);
265 if (ParseToken(lltok::equal, "expected '=' after name") ||
266 ParseToken(lltok::kw_type, "expected 'type' after name") ||
270 // Set the type name, checking for conflicts as we do so.
271 bool AlreadyExists = M->addTypeName(Name, Ty);
272 if (!AlreadyExists) return false;
274 // See if this type is a forward reference. We need to eagerly resolve
275 // types to allow recursive type redefinitions below.
276 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
277 FI = ForwardRefTypes.find(Name);
278 if (FI != ForwardRefTypes.end()) {
279 if (FI->second.first.get() == Ty)
280 return Error(NameLoc, "self referential type is invalid");
282 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
283 Ty = FI->second.first.get();
284 ForwardRefTypes.erase(FI);
287 // Inserting a name that is already defined, get the existing name.
288 const Type *Existing = M->getTypeByName(Name);
289 assert(Existing && "Conflict but no matching type?!");
291 // Otherwise, this is an attempt to redefine a type. That's okay if
292 // the redefinition is identical to the original.
293 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
294 if (Existing == Ty) return false;
296 // Any other kind of (non-equivalent) redefinition is an error.
297 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
298 Ty->getDescription() + "'");
303 /// ::= 'declare' FunctionHeader
304 bool LLParser::ParseDeclare() {
305 assert(Lex.getKind() == lltok::kw_declare);
309 return ParseFunctionHeader(F, false);
313 /// ::= 'define' FunctionHeader '{' ...
314 bool LLParser::ParseDefine() {
315 assert(Lex.getKind() == lltok::kw_define);
319 return ParseFunctionHeader(F, true) ||
320 ParseFunctionBody(*F);
326 bool LLParser::ParseGlobalType(bool &IsConstant) {
327 if (Lex.getKind() == lltok::kw_constant)
329 else if (Lex.getKind() == lltok::kw_global)
333 return TokError("expected 'global' or 'constant'");
339 /// ParseNamedGlobal:
340 /// GlobalVar '=' OptionalVisibility ALIAS ...
341 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
342 bool LLParser::ParseNamedGlobal() {
343 assert(Lex.getKind() == lltok::GlobalVar);
344 LocTy NameLoc = Lex.getLoc();
345 std::string Name = Lex.getStrVal();
349 unsigned Linkage, Visibility;
350 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
351 ParseOptionalLinkage(Linkage, HasLinkage) ||
352 ParseOptionalVisibility(Visibility))
355 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
356 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
357 return ParseAlias(Name, NameLoc, Visibility);
360 /// ParseStandaloneMetadata:
362 bool LLParser::ParseStandaloneMetadata() {
363 assert(Lex.getKind() == lltok::Metadata);
365 unsigned MetadataID = 0;
366 if (ParseUInt32(MetadataID))
368 if (MetadataCache.find(MetadataID) != MetadataCache.end())
369 return TokError("Metadata id is already used");
370 if (ParseToken(lltok::equal, "expected '=' here"))
375 PATypeHolder Ty(Type::VoidTy);
376 if (ParseGlobalType(IsConstant) ||
377 ParseType(Ty, TyLoc))
381 if (ParseGlobalValue(Ty, Init))
384 MetadataCache[MetadataID] = Init;
389 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
392 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
393 /// ::= 'getelementptr' '(' ... ')'
395 /// Everything through visibility has already been parsed.
397 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
398 unsigned Visibility) {
399 assert(Lex.getKind() == lltok::kw_alias);
402 LocTy LinkageLoc = Lex.getLoc();
403 if (ParseOptionalLinkage(Linkage))
406 if (Linkage != GlobalValue::ExternalLinkage &&
407 Linkage != GlobalValue::WeakAnyLinkage &&
408 Linkage != GlobalValue::WeakODRLinkage &&
409 Linkage != GlobalValue::InternalLinkage &&
410 Linkage != GlobalValue::PrivateLinkage)
411 return Error(LinkageLoc, "invalid linkage type for alias");
414 LocTy AliaseeLoc = Lex.getLoc();
415 if (Lex.getKind() != lltok::kw_bitcast &&
416 Lex.getKind() != lltok::kw_getelementptr) {
417 if (ParseGlobalTypeAndValue(Aliasee)) return true;
419 // The bitcast dest type is not present, it is implied by the dest type.
421 if (ParseValID(ID)) return true;
422 if (ID.Kind != ValID::t_Constant)
423 return Error(AliaseeLoc, "invalid aliasee");
424 Aliasee = ID.ConstantVal;
427 if (!isa<PointerType>(Aliasee->getType()))
428 return Error(AliaseeLoc, "alias must have pointer type");
430 // Okay, create the alias but do not insert it into the module yet.
431 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
432 (GlobalValue::LinkageTypes)Linkage, Name,
434 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
436 // See if this value already exists in the symbol table. If so, it is either
437 // a redefinition or a definition of a forward reference.
438 if (GlobalValue *Val =
439 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
440 // See if this was a redefinition. If so, there is no entry in
442 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
443 I = ForwardRefVals.find(Name);
444 if (I == ForwardRefVals.end())
445 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
447 // Otherwise, this was a definition of forward ref. Verify that types
449 if (Val->getType() != GA->getType())
450 return Error(NameLoc,
451 "forward reference and definition of alias have different types");
453 // If they agree, just RAUW the old value with the alias and remove the
455 Val->replaceAllUsesWith(GA);
456 Val->eraseFromParent();
457 ForwardRefVals.erase(I);
460 // Insert into the module, we know its name won't collide now.
461 M->getAliasList().push_back(GA);
462 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
468 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
469 /// OptionalAddrSpace GlobalType Type Const
470 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
471 /// OptionalAddrSpace GlobalType Type Const
473 /// Everything through visibility has been parsed already.
475 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
476 unsigned Linkage, bool HasLinkage,
477 unsigned Visibility) {
479 bool ThreadLocal, IsConstant;
482 PATypeHolder Ty(Type::VoidTy);
483 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
484 ParseOptionalAddrSpace(AddrSpace) ||
485 ParseGlobalType(IsConstant) ||
486 ParseType(Ty, TyLoc))
489 // If the linkage is specified and is external, then no initializer is
492 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
493 Linkage != GlobalValue::ExternalWeakLinkage &&
494 Linkage != GlobalValue::ExternalLinkage)) {
495 if (ParseGlobalValue(Ty, Init))
499 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
500 return Error(TyLoc, "invalid type for global variable");
502 GlobalVariable *GV = 0;
504 // See if the global was forward referenced, if so, use the global.
506 if ((GV = M->getGlobalVariable(Name, true)) &&
507 !ForwardRefVals.erase(Name))
508 return Error(NameLoc, "redefinition of global '@" + Name + "'");
510 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
511 I = ForwardRefValIDs.find(NumberedVals.size());
512 if (I != ForwardRefValIDs.end()) {
513 GV = cast<GlobalVariable>(I->second.first);
514 ForwardRefValIDs.erase(I);
519 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
520 M, false, AddrSpace);
522 if (GV->getType()->getElementType() != Ty)
524 "forward reference and definition of global have different types");
526 // Move the forward-reference to the correct spot in the module.
527 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
531 NumberedVals.push_back(GV);
533 // Set the parsed properties on the global.
535 GV->setInitializer(Init);
536 GV->setConstant(IsConstant);
537 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
538 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
539 GV->setThreadLocal(ThreadLocal);
541 // Parse attributes on the global.
542 while (Lex.getKind() == lltok::comma) {
545 if (Lex.getKind() == lltok::kw_section) {
547 GV->setSection(Lex.getStrVal());
548 if (ParseToken(lltok::StringConstant, "expected global section string"))
550 } else if (Lex.getKind() == lltok::kw_align) {
552 if (ParseOptionalAlignment(Alignment)) return true;
553 GV->setAlignment(Alignment);
555 TokError("unknown global variable property!");
563 //===----------------------------------------------------------------------===//
564 // GlobalValue Reference/Resolution Routines.
565 //===----------------------------------------------------------------------===//
567 /// GetGlobalVal - Get a value with the specified name or ID, creating a
568 /// forward reference record if needed. This can return null if the value
569 /// exists but does not have the right type.
570 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
572 const PointerType *PTy = dyn_cast<PointerType>(Ty);
574 Error(Loc, "global variable reference must have pointer type");
578 // Look this name up in the normal function symbol table.
580 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
582 // If this is a forward reference for the value, see if we already created a
583 // forward ref record.
585 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
586 I = ForwardRefVals.find(Name);
587 if (I != ForwardRefVals.end())
588 Val = I->second.first;
591 // If we have the value in the symbol table or fwd-ref table, return it.
593 if (Val->getType() == Ty) return Val;
594 Error(Loc, "'@" + Name + "' defined with type '" +
595 Val->getType()->getDescription() + "'");
599 // Otherwise, create a new forward reference for this value and remember it.
601 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
602 // Function types can return opaque but functions can't.
603 if (isa<OpaqueType>(FT->getReturnType())) {
604 Error(Loc, "function may not return opaque type");
608 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
610 FwdVal = new GlobalVariable(PTy->getElementType(), false,
611 GlobalValue::ExternalWeakLinkage, 0, Name, M);
614 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
618 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
619 const PointerType *PTy = dyn_cast<PointerType>(Ty);
621 Error(Loc, "global variable reference must have pointer type");
625 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
627 // If this is a forward reference for the value, see if we already created a
628 // forward ref record.
630 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
631 I = ForwardRefValIDs.find(ID);
632 if (I != ForwardRefValIDs.end())
633 Val = I->second.first;
636 // If we have the value in the symbol table or fwd-ref table, return it.
638 if (Val->getType() == Ty) return Val;
639 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
640 Val->getType()->getDescription() + "'");
644 // Otherwise, create a new forward reference for this value and remember it.
646 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
647 // Function types can return opaque but functions can't.
648 if (isa<OpaqueType>(FT->getReturnType())) {
649 Error(Loc, "function may not return opaque type");
652 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
654 FwdVal = new GlobalVariable(PTy->getElementType(), false,
655 GlobalValue::ExternalWeakLinkage, 0, "", M);
658 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
663 //===----------------------------------------------------------------------===//
665 //===----------------------------------------------------------------------===//
667 /// ParseToken - If the current token has the specified kind, eat it and return
668 /// success. Otherwise, emit the specified error and return failure.
669 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
670 if (Lex.getKind() != T)
671 return TokError(ErrMsg);
676 /// ParseStringConstant
677 /// ::= StringConstant
678 bool LLParser::ParseStringConstant(std::string &Result) {
679 if (Lex.getKind() != lltok::StringConstant)
680 return TokError("expected string constant");
681 Result = Lex.getStrVal();
688 bool LLParser::ParseUInt32(unsigned &Val) {
689 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
690 return TokError("expected integer");
691 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
692 if (Val64 != unsigned(Val64))
693 return TokError("expected 32-bit integer (too large)");
700 /// ParseOptionalAddrSpace
702 /// := 'addrspace' '(' uint32 ')'
703 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
705 if (!EatIfPresent(lltok::kw_addrspace))
707 return ParseToken(lltok::lparen, "expected '(' in address space") ||
708 ParseUInt32(AddrSpace) ||
709 ParseToken(lltok::rparen, "expected ')' in address space");
712 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
713 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
714 /// 2: function attr.
715 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
716 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
717 Attrs = Attribute::None;
718 LocTy AttrLoc = Lex.getLoc();
721 switch (Lex.getKind()) {
724 // Treat these as signext/zeroext if they occur in the argument list after
725 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
726 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
728 // FIXME: REMOVE THIS IN LLVM 3.0
730 if (Lex.getKind() == lltok::kw_sext)
731 Attrs |= Attribute::SExt;
733 Attrs |= Attribute::ZExt;
737 default: // End of attributes.
738 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
739 return Error(AttrLoc, "invalid use of function-only attribute");
741 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
742 return Error(AttrLoc, "invalid use of parameter-only attribute");
745 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
746 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
747 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
748 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
749 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
750 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
751 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
752 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
754 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
755 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
756 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
757 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
758 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
759 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
760 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
761 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
762 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
763 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
764 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
766 case lltok::kw_align: {
768 if (ParseOptionalAlignment(Alignment))
770 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
778 /// ParseOptionalLinkage
785 /// ::= 'linkonce_odr'
790 /// ::= 'extern_weak'
792 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
794 switch (Lex.getKind()) {
795 default: Res = GlobalValue::ExternalLinkage; return false;
796 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
797 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
798 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
799 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
800 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
801 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
802 case lltok::kw_available_externally:
803 Res = GlobalValue::AvailableExternallyLinkage;
805 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
806 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
807 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
808 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
809 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
810 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
817 /// ParseOptionalVisibility
823 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
824 switch (Lex.getKind()) {
825 default: Res = GlobalValue::DefaultVisibility; return false;
826 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
827 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
828 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
834 /// ParseOptionalCallingConv
839 /// ::= 'x86_stdcallcc'
840 /// ::= 'x86_fastcallcc'
842 /// ::= 'arm_aapcscc'
843 /// ::= 'arm_aapcs_vfpcc'
846 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
847 switch (Lex.getKind()) {
848 default: CC = CallingConv::C; return false;
849 case lltok::kw_ccc: CC = CallingConv::C; break;
850 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
851 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
852 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
853 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
854 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
855 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
856 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
857 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
863 /// ParseOptionalAlignment
866 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
868 if (!EatIfPresent(lltok::kw_align))
870 LocTy AlignLoc = Lex.getLoc();
871 if (ParseUInt32(Alignment)) return true;
872 if (!isPowerOf2_32(Alignment))
873 return Error(AlignLoc, "alignment is not a power of two");
877 /// ParseOptionalCommaAlignment
879 /// ::= ',' 'align' 4
880 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
882 if (!EatIfPresent(lltok::comma))
884 return ParseToken(lltok::kw_align, "expected 'align'") ||
885 ParseUInt32(Alignment);
889 /// ::= (',' uint32)+
890 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
891 if (Lex.getKind() != lltok::comma)
892 return TokError("expected ',' as start of index list");
894 while (EatIfPresent(lltok::comma)) {
896 if (ParseUInt32(Idx)) return true;
897 Indices.push_back(Idx);
903 //===----------------------------------------------------------------------===//
905 //===----------------------------------------------------------------------===//
907 /// ParseType - Parse and resolve a full type.
908 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
909 LocTy TypeLoc = Lex.getLoc();
910 if (ParseTypeRec(Result)) return true;
912 // Verify no unresolved uprefs.
914 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
916 if (!AllowVoid && Result.get() == Type::VoidTy)
917 return Error(TypeLoc, "void type only allowed for function results");
922 /// HandleUpRefs - Every time we finish a new layer of types, this function is
923 /// called. It loops through the UpRefs vector, which is a list of the
924 /// currently active types. For each type, if the up-reference is contained in
925 /// the newly completed type, we decrement the level count. When the level
926 /// count reaches zero, the up-referenced type is the type that is passed in:
927 /// thus we can complete the cycle.
929 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
930 // If Ty isn't abstract, or if there are no up-references in it, then there is
931 // nothing to resolve here.
932 if (!ty->isAbstract() || UpRefs.empty()) return ty;
936 errs() << "Type '" << Ty->getDescription()
937 << "' newly formed. Resolving upreferences.\n"
938 << UpRefs.size() << " upreferences active!\n";
941 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
942 // to zero), we resolve them all together before we resolve them to Ty. At
943 // the end of the loop, if there is anything to resolve to Ty, it will be in
945 OpaqueType *TypeToResolve = 0;
947 for (unsigned i = 0; i != UpRefs.size(); ++i) {
948 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
950 std::find(Ty->subtype_begin(), Ty->subtype_end(),
951 UpRefs[i].LastContainedTy) != Ty->subtype_end();
954 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
955 << UpRefs[i].LastContainedTy->getDescription() << ") = "
956 << (ContainsType ? "true" : "false")
957 << " level=" << UpRefs[i].NestingLevel << "\n";
962 // Decrement level of upreference
963 unsigned Level = --UpRefs[i].NestingLevel;
964 UpRefs[i].LastContainedTy = Ty;
966 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
971 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
974 TypeToResolve = UpRefs[i].UpRefTy;
976 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
977 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
978 --i; // Do not skip the next element.
982 TypeToResolve->refineAbstractTypeTo(Ty);
988 /// ParseTypeRec - The recursive function used to process the internal
989 /// implementation details of types.
990 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
991 switch (Lex.getKind()) {
993 return TokError("expected type");
995 // TypeRec ::= 'float' | 'void' (etc)
996 Result = Lex.getTyVal();
999 case lltok::kw_opaque:
1000 // TypeRec ::= 'opaque'
1001 Result = Context.getOpaqueType();
1005 // TypeRec ::= '{' ... '}'
1006 if (ParseStructType(Result, false))
1009 case lltok::lsquare:
1010 // TypeRec ::= '[' ... ']'
1011 Lex.Lex(); // eat the lsquare.
1012 if (ParseArrayVectorType(Result, false))
1015 case lltok::less: // Either vector or packed struct.
1016 // TypeRec ::= '<' ... '>'
1018 if (Lex.getKind() == lltok::lbrace) {
1019 if (ParseStructType(Result, true) ||
1020 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1022 } else if (ParseArrayVectorType(Result, true))
1025 case lltok::LocalVar:
1026 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1028 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1031 Result = Context.getOpaqueType();
1032 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1033 std::make_pair(Result,
1035 M->addTypeName(Lex.getStrVal(), Result.get());
1040 case lltok::LocalVarID:
1042 if (Lex.getUIntVal() < NumberedTypes.size())
1043 Result = NumberedTypes[Lex.getUIntVal()];
1045 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1046 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1047 if (I != ForwardRefTypeIDs.end())
1048 Result = I->second.first;
1050 Result = Context.getOpaqueType();
1051 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1052 std::make_pair(Result,
1058 case lltok::backslash: {
1059 // TypeRec ::= '\' 4
1062 if (ParseUInt32(Val)) return true;
1063 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1064 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1070 // Parse the type suffixes.
1072 switch (Lex.getKind()) {
1074 default: return false;
1076 // TypeRec ::= TypeRec '*'
1078 if (Result.get() == Type::LabelTy)
1079 return TokError("basic block pointers are invalid");
1080 if (Result.get() == Type::VoidTy)
1081 return TokError("pointers to void are invalid; use i8* instead");
1082 if (!PointerType::isValidElementType(Result.get()))
1083 return TokError("pointer to this type is invalid");
1084 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1088 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1089 case lltok::kw_addrspace: {
1090 if (Result.get() == Type::LabelTy)
1091 return TokError("basic block pointers are invalid");
1092 if (Result.get() == Type::VoidTy)
1093 return TokError("pointers to void are invalid; use i8* instead");
1094 if (!PointerType::isValidElementType(Result.get()))
1095 return TokError("pointer to this type is invalid");
1097 if (ParseOptionalAddrSpace(AddrSpace) ||
1098 ParseToken(lltok::star, "expected '*' in address space"))
1101 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1105 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1107 if (ParseFunctionType(Result))
1114 /// ParseParameterList
1116 /// ::= '(' Arg (',' Arg)* ')'
1118 /// ::= Type OptionalAttributes Value OptionalAttributes
1119 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1120 PerFunctionState &PFS) {
1121 if (ParseToken(lltok::lparen, "expected '(' in call"))
1124 while (Lex.getKind() != lltok::rparen) {
1125 // If this isn't the first argument, we need a comma.
1126 if (!ArgList.empty() &&
1127 ParseToken(lltok::comma, "expected ',' in argument list"))
1130 // Parse the argument.
1132 PATypeHolder ArgTy(Type::VoidTy);
1133 unsigned ArgAttrs1, ArgAttrs2;
1135 if (ParseType(ArgTy, ArgLoc) ||
1136 ParseOptionalAttrs(ArgAttrs1, 0) ||
1137 ParseValue(ArgTy, V, PFS) ||
1138 // FIXME: Should not allow attributes after the argument, remove this in
1140 ParseOptionalAttrs(ArgAttrs2, 3))
1142 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1145 Lex.Lex(); // Lex the ')'.
1151 /// ParseArgumentList - Parse the argument list for a function type or function
1152 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1153 /// ::= '(' ArgTypeListI ')'
1157 /// ::= ArgTypeList ',' '...'
1158 /// ::= ArgType (',' ArgType)*
1160 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1161 bool &isVarArg, bool inType) {
1163 assert(Lex.getKind() == lltok::lparen);
1164 Lex.Lex(); // eat the (.
1166 if (Lex.getKind() == lltok::rparen) {
1168 } else if (Lex.getKind() == lltok::dotdotdot) {
1172 LocTy TypeLoc = Lex.getLoc();
1173 PATypeHolder ArgTy(Type::VoidTy);
1177 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1178 // types (such as a function returning a pointer to itself). If parsing a
1179 // function prototype, we require fully resolved types.
1180 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1181 ParseOptionalAttrs(Attrs, 0)) return true;
1183 if (ArgTy == Type::VoidTy)
1184 return Error(TypeLoc, "argument can not have void type");
1186 if (Lex.getKind() == lltok::LocalVar ||
1187 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1188 Name = Lex.getStrVal();
1192 if (!FunctionType::isValidArgumentType(ArgTy))
1193 return Error(TypeLoc, "invalid type for function argument");
1195 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1197 while (EatIfPresent(lltok::comma)) {
1198 // Handle ... at end of arg list.
1199 if (EatIfPresent(lltok::dotdotdot)) {
1204 // Otherwise must be an argument type.
1205 TypeLoc = Lex.getLoc();
1206 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1207 ParseOptionalAttrs(Attrs, 0)) return true;
1209 if (ArgTy == Type::VoidTy)
1210 return Error(TypeLoc, "argument can not have void type");
1212 if (Lex.getKind() == lltok::LocalVar ||
1213 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1214 Name = Lex.getStrVal();
1220 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1221 return Error(TypeLoc, "invalid type for function argument");
1223 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1227 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1230 /// ParseFunctionType
1231 /// ::= Type ArgumentList OptionalAttrs
1232 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1233 assert(Lex.getKind() == lltok::lparen);
1235 if (!FunctionType::isValidReturnType(Result))
1236 return TokError("invalid function return type");
1238 std::vector<ArgInfo> ArgList;
1241 if (ParseArgumentList(ArgList, isVarArg, true) ||
1242 // FIXME: Allow, but ignore attributes on function types!
1243 // FIXME: Remove in LLVM 3.0
1244 ParseOptionalAttrs(Attrs, 2))
1247 // Reject names on the arguments lists.
1248 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1249 if (!ArgList[i].Name.empty())
1250 return Error(ArgList[i].Loc, "argument name invalid in function type");
1251 if (!ArgList[i].Attrs != 0) {
1252 // Allow but ignore attributes on function types; this permits
1254 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1258 std::vector<const Type*> ArgListTy;
1259 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1260 ArgListTy.push_back(ArgList[i].Type);
1262 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1263 ArgListTy, isVarArg));
1267 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1270 /// ::= '{' TypeRec (',' TypeRec)* '}'
1271 /// ::= '<' '{' '}' '>'
1272 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1273 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1274 assert(Lex.getKind() == lltok::lbrace);
1275 Lex.Lex(); // Consume the '{'
1277 if (EatIfPresent(lltok::rbrace)) {
1278 Result = Context.getStructType(Packed);
1282 std::vector<PATypeHolder> ParamsList;
1283 LocTy EltTyLoc = Lex.getLoc();
1284 if (ParseTypeRec(Result)) return true;
1285 ParamsList.push_back(Result);
1287 if (Result == Type::VoidTy)
1288 return Error(EltTyLoc, "struct element can not have void type");
1289 if (!StructType::isValidElementType(Result))
1290 return Error(EltTyLoc, "invalid element type for struct");
1292 while (EatIfPresent(lltok::comma)) {
1293 EltTyLoc = Lex.getLoc();
1294 if (ParseTypeRec(Result)) return true;
1296 if (Result == Type::VoidTy)
1297 return Error(EltTyLoc, "struct element can not have void type");
1298 if (!StructType::isValidElementType(Result))
1299 return Error(EltTyLoc, "invalid element type for struct");
1301 ParamsList.push_back(Result);
1304 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1307 std::vector<const Type*> ParamsListTy;
1308 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1309 ParamsListTy.push_back(ParamsList[i].get());
1310 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1314 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1315 /// token has already been consumed.
1317 /// ::= '[' APSINTVAL 'x' Types ']'
1318 /// ::= '<' APSINTVAL 'x' Types '>'
1319 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1320 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1321 Lex.getAPSIntVal().getBitWidth() > 64)
1322 return TokError("expected number in address space");
1324 LocTy SizeLoc = Lex.getLoc();
1325 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1328 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1331 LocTy TypeLoc = Lex.getLoc();
1332 PATypeHolder EltTy(Type::VoidTy);
1333 if (ParseTypeRec(EltTy)) return true;
1335 if (EltTy == Type::VoidTy)
1336 return Error(TypeLoc, "array and vector element type cannot be void");
1338 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1339 "expected end of sequential type"))
1344 return Error(SizeLoc, "zero element vector is illegal");
1345 if ((unsigned)Size != Size)
1346 return Error(SizeLoc, "size too large for vector");
1347 if (!VectorType::isValidElementType(EltTy))
1348 return Error(TypeLoc, "vector element type must be fp or integer");
1349 Result = Context.getVectorType(EltTy, unsigned(Size));
1351 if (!ArrayType::isValidElementType(EltTy))
1352 return Error(TypeLoc, "invalid array element type");
1353 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1358 //===----------------------------------------------------------------------===//
1359 // Function Semantic Analysis.
1360 //===----------------------------------------------------------------------===//
1362 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1365 // Insert unnamed arguments into the NumberedVals list.
1366 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1369 NumberedVals.push_back(AI);
1372 LLParser::PerFunctionState::~PerFunctionState() {
1373 // If there were any forward referenced non-basicblock values, delete them.
1374 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1375 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1376 if (!isa<BasicBlock>(I->second.first)) {
1377 I->second.first->replaceAllUsesWith(
1378 P.getContext().getUndef(I->second.first->getType()));
1379 delete I->second.first;
1380 I->second.first = 0;
1383 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1384 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1385 if (!isa<BasicBlock>(I->second.first)) {
1386 I->second.first->replaceAllUsesWith(
1387 P.getContext().getUndef(I->second.first->getType()));
1388 delete I->second.first;
1389 I->second.first = 0;
1393 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1394 if (!ForwardRefVals.empty())
1395 return P.Error(ForwardRefVals.begin()->second.second,
1396 "use of undefined value '%" + ForwardRefVals.begin()->first +
1398 if (!ForwardRefValIDs.empty())
1399 return P.Error(ForwardRefValIDs.begin()->second.second,
1400 "use of undefined value '%" +
1401 utostr(ForwardRefValIDs.begin()->first) + "'");
1406 /// GetVal - Get a value with the specified name or ID, creating a
1407 /// forward reference record if needed. This can return null if the value
1408 /// exists but does not have the right type.
1409 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1410 const Type *Ty, LocTy Loc) {
1411 // Look this name up in the normal function symbol table.
1412 Value *Val = F.getValueSymbolTable().lookup(Name);
1414 // If this is a forward reference for the value, see if we already created a
1415 // forward ref record.
1417 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1418 I = ForwardRefVals.find(Name);
1419 if (I != ForwardRefVals.end())
1420 Val = I->second.first;
1423 // If we have the value in the symbol table or fwd-ref table, return it.
1425 if (Val->getType() == Ty) return Val;
1426 if (Ty == Type::LabelTy)
1427 P.Error(Loc, "'%" + Name + "' is not a basic block");
1429 P.Error(Loc, "'%" + Name + "' defined with type '" +
1430 Val->getType()->getDescription() + "'");
1434 // Don't make placeholders with invalid type.
1435 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1436 P.Error(Loc, "invalid use of a non-first-class type");
1440 // Otherwise, create a new forward reference for this value and remember it.
1442 if (Ty == Type::LabelTy)
1443 FwdVal = BasicBlock::Create(Name, &F);
1445 FwdVal = new Argument(Ty, Name);
1447 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1451 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1453 // Look this name up in the normal function symbol table.
1454 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1456 // If this is a forward reference for the value, see if we already created a
1457 // forward ref record.
1459 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1460 I = ForwardRefValIDs.find(ID);
1461 if (I != ForwardRefValIDs.end())
1462 Val = I->second.first;
1465 // If we have the value in the symbol table or fwd-ref table, return it.
1467 if (Val->getType() == Ty) return Val;
1468 if (Ty == Type::LabelTy)
1469 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1471 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1472 Val->getType()->getDescription() + "'");
1476 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1477 P.Error(Loc, "invalid use of a non-first-class type");
1481 // Otherwise, create a new forward reference for this value and remember it.
1483 if (Ty == Type::LabelTy)
1484 FwdVal = BasicBlock::Create("", &F);
1486 FwdVal = new Argument(Ty);
1488 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1492 /// SetInstName - After an instruction is parsed and inserted into its
1493 /// basic block, this installs its name.
1494 bool LLParser::PerFunctionState::SetInstName(int NameID,
1495 const std::string &NameStr,
1496 LocTy NameLoc, Instruction *Inst) {
1497 // If this instruction has void type, it cannot have a name or ID specified.
1498 if (Inst->getType() == Type::VoidTy) {
1499 if (NameID != -1 || !NameStr.empty())
1500 return P.Error(NameLoc, "instructions returning void cannot have a name");
1504 // If this was a numbered instruction, verify that the instruction is the
1505 // expected value and resolve any forward references.
1506 if (NameStr.empty()) {
1507 // If neither a name nor an ID was specified, just use the next ID.
1509 NameID = NumberedVals.size();
1511 if (unsigned(NameID) != NumberedVals.size())
1512 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1513 utostr(NumberedVals.size()) + "'");
1515 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1516 ForwardRefValIDs.find(NameID);
1517 if (FI != ForwardRefValIDs.end()) {
1518 if (FI->second.first->getType() != Inst->getType())
1519 return P.Error(NameLoc, "instruction forward referenced with type '" +
1520 FI->second.first->getType()->getDescription() + "'");
1521 FI->second.first->replaceAllUsesWith(Inst);
1522 ForwardRefValIDs.erase(FI);
1525 NumberedVals.push_back(Inst);
1529 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1530 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1531 FI = ForwardRefVals.find(NameStr);
1532 if (FI != ForwardRefVals.end()) {
1533 if (FI->second.first->getType() != Inst->getType())
1534 return P.Error(NameLoc, "instruction forward referenced with type '" +
1535 FI->second.first->getType()->getDescription() + "'");
1536 FI->second.first->replaceAllUsesWith(Inst);
1537 ForwardRefVals.erase(FI);
1540 // Set the name on the instruction.
1541 Inst->setName(NameStr);
1543 if (Inst->getNameStr() != NameStr)
1544 return P.Error(NameLoc, "multiple definition of local value named '" +
1549 /// GetBB - Get a basic block with the specified name or ID, creating a
1550 /// forward reference record if needed.
1551 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1553 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1556 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1557 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1560 /// DefineBB - Define the specified basic block, which is either named or
1561 /// unnamed. If there is an error, this returns null otherwise it returns
1562 /// the block being defined.
1563 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1567 BB = GetBB(NumberedVals.size(), Loc);
1569 BB = GetBB(Name, Loc);
1570 if (BB == 0) return 0; // Already diagnosed error.
1572 // Move the block to the end of the function. Forward ref'd blocks are
1573 // inserted wherever they happen to be referenced.
1574 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1576 // Remove the block from forward ref sets.
1578 ForwardRefValIDs.erase(NumberedVals.size());
1579 NumberedVals.push_back(BB);
1581 // BB forward references are already in the function symbol table.
1582 ForwardRefVals.erase(Name);
1588 //===----------------------------------------------------------------------===//
1590 //===----------------------------------------------------------------------===//
1592 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1593 /// type implied. For example, if we parse "4" we don't know what integer type
1594 /// it has. The value will later be combined with its type and checked for
1596 bool LLParser::ParseValID(ValID &ID) {
1597 ID.Loc = Lex.getLoc();
1598 switch (Lex.getKind()) {
1599 default: return TokError("expected value token");
1600 case lltok::GlobalID: // @42
1601 ID.UIntVal = Lex.getUIntVal();
1602 ID.Kind = ValID::t_GlobalID;
1604 case lltok::GlobalVar: // @foo
1605 ID.StrVal = Lex.getStrVal();
1606 ID.Kind = ValID::t_GlobalName;
1608 case lltok::LocalVarID: // %42
1609 ID.UIntVal = Lex.getUIntVal();
1610 ID.Kind = ValID::t_LocalID;
1612 case lltok::LocalVar: // %foo
1613 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1614 ID.StrVal = Lex.getStrVal();
1615 ID.Kind = ValID::t_LocalName;
1617 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1618 ID.Kind = ValID::t_Constant;
1620 if (Lex.getKind() == lltok::lbrace) {
1621 SmallVector<Value*, 16> Elts;
1622 if (ParseMDNodeVector(Elts) ||
1623 ParseToken(lltok::rbrace, "expected end of metadata node"))
1626 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
1630 // Standalone metadata reference
1631 // !{ ..., !42, ... }
1633 if (!ParseUInt32(MID)) {
1634 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
1635 if (I == MetadataCache.end())
1636 return TokError("Unknown metadata reference");
1637 ID.ConstantVal = I->second;
1642 // ::= '!' STRINGCONSTANT
1644 if (ParseStringConstant(Str)) return true;
1646 ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
1650 ID.APSIntVal = Lex.getAPSIntVal();
1651 ID.Kind = ValID::t_APSInt;
1653 case lltok::APFloat:
1654 ID.APFloatVal = Lex.getAPFloatVal();
1655 ID.Kind = ValID::t_APFloat;
1657 case lltok::kw_true:
1658 ID.ConstantVal = Context.getConstantIntTrue();
1659 ID.Kind = ValID::t_Constant;
1661 case lltok::kw_false:
1662 ID.ConstantVal = Context.getConstantIntFalse();
1663 ID.Kind = ValID::t_Constant;
1665 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1666 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1667 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1669 case lltok::lbrace: {
1670 // ValID ::= '{' ConstVector '}'
1672 SmallVector<Constant*, 16> Elts;
1673 if (ParseGlobalValueVector(Elts) ||
1674 ParseToken(lltok::rbrace, "expected end of struct constant"))
1677 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
1678 ID.Kind = ValID::t_Constant;
1682 // ValID ::= '<' ConstVector '>' --> Vector.
1683 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1685 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1687 SmallVector<Constant*, 16> Elts;
1688 LocTy FirstEltLoc = Lex.getLoc();
1689 if (ParseGlobalValueVector(Elts) ||
1691 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1692 ParseToken(lltok::greater, "expected end of constant"))
1695 if (isPackedStruct) {
1697 Context.getConstantStruct(Elts.data(), Elts.size(), true);
1698 ID.Kind = ValID::t_Constant;
1703 return Error(ID.Loc, "constant vector must not be empty");
1705 if (!Elts[0]->getType()->isInteger() &&
1706 !Elts[0]->getType()->isFloatingPoint())
1707 return Error(FirstEltLoc,
1708 "vector elements must have integer or floating point type");
1710 // Verify that all the vector elements have the same type.
1711 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1712 if (Elts[i]->getType() != Elts[0]->getType())
1713 return Error(FirstEltLoc,
1714 "vector element #" + utostr(i) +
1715 " is not of type '" + Elts[0]->getType()->getDescription());
1717 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
1718 ID.Kind = ValID::t_Constant;
1721 case lltok::lsquare: { // Array Constant
1723 SmallVector<Constant*, 16> Elts;
1724 LocTy FirstEltLoc = Lex.getLoc();
1725 if (ParseGlobalValueVector(Elts) ||
1726 ParseToken(lltok::rsquare, "expected end of array constant"))
1729 // Handle empty element.
1731 // Use undef instead of an array because it's inconvenient to determine
1732 // the element type at this point, there being no elements to examine.
1733 ID.Kind = ValID::t_EmptyArray;
1737 if (!Elts[0]->getType()->isFirstClassType())
1738 return Error(FirstEltLoc, "invalid array element type: " +
1739 Elts[0]->getType()->getDescription());
1741 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1743 // Verify all elements are correct type!
1744 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1745 if (Elts[i]->getType() != Elts[0]->getType())
1746 return Error(FirstEltLoc,
1747 "array element #" + utostr(i) +
1748 " is not of type '" +Elts[0]->getType()->getDescription());
1751 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
1752 ID.Kind = ValID::t_Constant;
1755 case lltok::kw_c: // c "foo"
1757 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
1758 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1759 ID.Kind = ValID::t_Constant;
1762 case lltok::kw_asm: {
1763 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1766 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1767 ParseStringConstant(ID.StrVal) ||
1768 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1769 ParseToken(lltok::StringConstant, "expected constraint string"))
1771 ID.StrVal2 = Lex.getStrVal();
1772 ID.UIntVal = HasSideEffect;
1773 ID.Kind = ValID::t_InlineAsm;
1777 case lltok::kw_trunc:
1778 case lltok::kw_zext:
1779 case lltok::kw_sext:
1780 case lltok::kw_fptrunc:
1781 case lltok::kw_fpext:
1782 case lltok::kw_bitcast:
1783 case lltok::kw_uitofp:
1784 case lltok::kw_sitofp:
1785 case lltok::kw_fptoui:
1786 case lltok::kw_fptosi:
1787 case lltok::kw_inttoptr:
1788 case lltok::kw_ptrtoint: {
1789 unsigned Opc = Lex.getUIntVal();
1790 PATypeHolder DestTy(Type::VoidTy);
1793 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1794 ParseGlobalTypeAndValue(SrcVal) ||
1795 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1796 ParseType(DestTy) ||
1797 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1799 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1800 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1801 SrcVal->getType()->getDescription() + "' to '" +
1802 DestTy->getDescription() + "'");
1803 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1805 ID.Kind = ValID::t_Constant;
1808 case lltok::kw_extractvalue: {
1811 SmallVector<unsigned, 4> Indices;
1812 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1813 ParseGlobalTypeAndValue(Val) ||
1814 ParseIndexList(Indices) ||
1815 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1817 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1818 return Error(ID.Loc, "extractvalue operand must be array or struct");
1819 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1821 return Error(ID.Loc, "invalid indices for extractvalue");
1823 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
1824 ID.Kind = ValID::t_Constant;
1827 case lltok::kw_insertvalue: {
1829 Constant *Val0, *Val1;
1830 SmallVector<unsigned, 4> Indices;
1831 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1832 ParseGlobalTypeAndValue(Val0) ||
1833 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1834 ParseGlobalTypeAndValue(Val1) ||
1835 ParseIndexList(Indices) ||
1836 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1838 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1839 return Error(ID.Loc, "extractvalue operand must be array or struct");
1840 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1842 return Error(ID.Loc, "invalid indices for insertvalue");
1843 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1844 Indices.data(), Indices.size());
1845 ID.Kind = ValID::t_Constant;
1848 case lltok::kw_icmp:
1849 case lltok::kw_fcmp:
1850 case lltok::kw_vicmp:
1851 case lltok::kw_vfcmp: {
1852 unsigned PredVal, Opc = Lex.getUIntVal();
1853 Constant *Val0, *Val1;
1855 if (ParseCmpPredicate(PredVal, Opc) ||
1856 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1857 ParseGlobalTypeAndValue(Val0) ||
1858 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1859 ParseGlobalTypeAndValue(Val1) ||
1860 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1863 if (Val0->getType() != Val1->getType())
1864 return Error(ID.Loc, "compare operands must have the same type");
1866 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1868 if (Opc == Instruction::FCmp) {
1869 if (!Val0->getType()->isFPOrFPVector())
1870 return Error(ID.Loc, "fcmp requires floating point operands");
1871 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
1872 } else if (Opc == Instruction::ICmp) {
1873 if (!Val0->getType()->isIntOrIntVector() &&
1874 !isa<PointerType>(Val0->getType()))
1875 return Error(ID.Loc, "icmp requires pointer or integer operands");
1876 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
1877 } else if (Opc == Instruction::VFCmp) {
1878 // FIXME: REMOVE VFCMP Support
1879 if (!Val0->getType()->isFPOrFPVector() ||
1880 !isa<VectorType>(Val0->getType()))
1881 return Error(ID.Loc, "vfcmp requires vector floating point operands");
1882 ID.ConstantVal = Context.getConstantExprVFCmp(Pred, Val0, Val1);
1883 } else if (Opc == Instruction::VICmp) {
1884 // FIXME: REMOVE VICMP Support
1885 if (!Val0->getType()->isIntOrIntVector() ||
1886 !isa<VectorType>(Val0->getType()))
1887 return Error(ID.Loc, "vicmp requires vector floating point operands");
1888 ID.ConstantVal = Context.getConstantExprVICmp(Pred, Val0, Val1);
1890 ID.Kind = ValID::t_Constant;
1894 // Binary Operators.
1896 case lltok::kw_fadd:
1898 case lltok::kw_fsub:
1900 case lltok::kw_fmul:
1901 case lltok::kw_udiv:
1902 case lltok::kw_sdiv:
1903 case lltok::kw_fdiv:
1904 case lltok::kw_urem:
1905 case lltok::kw_srem:
1906 case lltok::kw_frem: {
1907 unsigned Opc = Lex.getUIntVal();
1908 Constant *Val0, *Val1;
1910 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1911 ParseGlobalTypeAndValue(Val0) ||
1912 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1913 ParseGlobalTypeAndValue(Val1) ||
1914 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1916 if (Val0->getType() != Val1->getType())
1917 return Error(ID.Loc, "operands of constexpr must have same type");
1918 if (!Val0->getType()->isIntOrIntVector() &&
1919 !Val0->getType()->isFPOrFPVector())
1920 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1921 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1922 ID.Kind = ValID::t_Constant;
1926 // Logical Operations
1928 case lltok::kw_lshr:
1929 case lltok::kw_ashr:
1932 case lltok::kw_xor: {
1933 unsigned Opc = Lex.getUIntVal();
1934 Constant *Val0, *Val1;
1936 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1937 ParseGlobalTypeAndValue(Val0) ||
1938 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1939 ParseGlobalTypeAndValue(Val1) ||
1940 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1942 if (Val0->getType() != Val1->getType())
1943 return Error(ID.Loc, "operands of constexpr must have same type");
1944 if (!Val0->getType()->isIntOrIntVector())
1945 return Error(ID.Loc,
1946 "constexpr requires integer or integer vector operands");
1947 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1948 ID.Kind = ValID::t_Constant;
1952 case lltok::kw_getelementptr:
1953 case lltok::kw_shufflevector:
1954 case lltok::kw_insertelement:
1955 case lltok::kw_extractelement:
1956 case lltok::kw_select: {
1957 unsigned Opc = Lex.getUIntVal();
1958 SmallVector<Constant*, 16> Elts;
1960 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1961 ParseGlobalValueVector(Elts) ||
1962 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1965 if (Opc == Instruction::GetElementPtr) {
1966 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1967 return Error(ID.Loc, "getelementptr requires pointer operand");
1969 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1970 (Value**)&Elts[1], Elts.size()-1))
1971 return Error(ID.Loc, "invalid indices for getelementptr");
1972 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
1973 &Elts[1], Elts.size()-1);
1974 } else if (Opc == Instruction::Select) {
1975 if (Elts.size() != 3)
1976 return Error(ID.Loc, "expected three operands to select");
1977 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1979 return Error(ID.Loc, Reason);
1980 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
1981 } else if (Opc == Instruction::ShuffleVector) {
1982 if (Elts.size() != 3)
1983 return Error(ID.Loc, "expected three operands to shufflevector");
1984 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1985 return Error(ID.Loc, "invalid operands to shufflevector");
1987 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
1988 } else if (Opc == Instruction::ExtractElement) {
1989 if (Elts.size() != 2)
1990 return Error(ID.Loc, "expected two operands to extractelement");
1991 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1992 return Error(ID.Loc, "invalid extractelement operands");
1993 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
1995 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1996 if (Elts.size() != 3)
1997 return Error(ID.Loc, "expected three operands to insertelement");
1998 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1999 return Error(ID.Loc, "invalid insertelement operands");
2001 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
2004 ID.Kind = ValID::t_Constant;
2013 /// ParseGlobalValue - Parse a global value with the specified type.
2014 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2017 return ParseValID(ID) ||
2018 ConvertGlobalValIDToValue(Ty, ID, V);
2021 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2023 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2025 if (isa<FunctionType>(Ty))
2026 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2029 default: assert(0 && "Unknown ValID!");
2030 case ValID::t_LocalID:
2031 case ValID::t_LocalName:
2032 return Error(ID.Loc, "invalid use of function-local name");
2033 case ValID::t_InlineAsm:
2034 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2035 case ValID::t_GlobalName:
2036 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2038 case ValID::t_GlobalID:
2039 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2041 case ValID::t_APSInt:
2042 if (!isa<IntegerType>(Ty))
2043 return Error(ID.Loc, "integer constant must have integer type");
2044 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2045 V = Context.getConstantInt(ID.APSIntVal);
2047 case ValID::t_APFloat:
2048 if (!Ty->isFloatingPoint() ||
2049 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2050 return Error(ID.Loc, "floating point constant invalid for type");
2052 // The lexer has no type info, so builds all float and double FP constants
2053 // as double. Fix this here. Long double does not need this.
2054 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2055 Ty == Type::FloatTy) {
2057 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2060 V = Context.getConstantFP(ID.APFloatVal);
2062 if (V->getType() != Ty)
2063 return Error(ID.Loc, "floating point constant does not have type '" +
2064 Ty->getDescription() + "'");
2068 if (!isa<PointerType>(Ty))
2069 return Error(ID.Loc, "null must be a pointer type");
2070 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2072 case ValID::t_Undef:
2073 // FIXME: LabelTy should not be a first-class type.
2074 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2075 !isa<OpaqueType>(Ty))
2076 return Error(ID.Loc, "invalid type for undef constant");
2077 V = Context.getUndef(Ty);
2079 case ValID::t_EmptyArray:
2080 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2081 return Error(ID.Loc, "invalid empty array initializer");
2082 V = Context.getUndef(Ty);
2085 // FIXME: LabelTy should not be a first-class type.
2086 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2087 return Error(ID.Loc, "invalid type for null constant");
2088 V = Context.getNullValue(Ty);
2090 case ValID::t_Constant:
2091 if (ID.ConstantVal->getType() != Ty)
2092 return Error(ID.Loc, "constant expression type mismatch");
2098 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2099 PATypeHolder Type(Type::VoidTy);
2100 return ParseType(Type) ||
2101 ParseGlobalValue(Type, V);
2104 /// ParseGlobalValueVector
2106 /// ::= TypeAndValue (',' TypeAndValue)*
2107 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2109 if (Lex.getKind() == lltok::rbrace ||
2110 Lex.getKind() == lltok::rsquare ||
2111 Lex.getKind() == lltok::greater ||
2112 Lex.getKind() == lltok::rparen)
2116 if (ParseGlobalTypeAndValue(C)) return true;
2119 while (EatIfPresent(lltok::comma)) {
2120 if (ParseGlobalTypeAndValue(C)) return true;
2128 //===----------------------------------------------------------------------===//
2129 // Function Parsing.
2130 //===----------------------------------------------------------------------===//
2132 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2133 PerFunctionState &PFS) {
2134 if (ID.Kind == ValID::t_LocalID)
2135 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2136 else if (ID.Kind == ValID::t_LocalName)
2137 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2138 else if (ID.Kind == ValID::t_InlineAsm) {
2139 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2140 const FunctionType *FTy =
2141 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2142 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2143 return Error(ID.Loc, "invalid type for inline asm constraint string");
2144 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2148 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2156 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2159 return ParseValID(ID) ||
2160 ConvertValIDToValue(Ty, ID, V, PFS);
2163 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2164 PATypeHolder T(Type::VoidTy);
2165 return ParseType(T) ||
2166 ParseValue(T, V, PFS);
2170 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2171 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2172 /// OptionalAlign OptGC
2173 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2174 // Parse the linkage.
2175 LocTy LinkageLoc = Lex.getLoc();
2178 unsigned Visibility, CC, RetAttrs;
2179 PATypeHolder RetType(Type::VoidTy);
2180 LocTy RetTypeLoc = Lex.getLoc();
2181 if (ParseOptionalLinkage(Linkage) ||
2182 ParseOptionalVisibility(Visibility) ||
2183 ParseOptionalCallingConv(CC) ||
2184 ParseOptionalAttrs(RetAttrs, 1) ||
2185 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2188 // Verify that the linkage is ok.
2189 switch ((GlobalValue::LinkageTypes)Linkage) {
2190 case GlobalValue::ExternalLinkage:
2191 break; // always ok.
2192 case GlobalValue::DLLImportLinkage:
2193 case GlobalValue::ExternalWeakLinkage:
2195 return Error(LinkageLoc, "invalid linkage for function definition");
2197 case GlobalValue::PrivateLinkage:
2198 case GlobalValue::InternalLinkage:
2199 case GlobalValue::AvailableExternallyLinkage:
2200 case GlobalValue::LinkOnceAnyLinkage:
2201 case GlobalValue::LinkOnceODRLinkage:
2202 case GlobalValue::WeakAnyLinkage:
2203 case GlobalValue::WeakODRLinkage:
2204 case GlobalValue::DLLExportLinkage:
2206 return Error(LinkageLoc, "invalid linkage for function declaration");
2208 case GlobalValue::AppendingLinkage:
2209 case GlobalValue::GhostLinkage:
2210 case GlobalValue::CommonLinkage:
2211 return Error(LinkageLoc, "invalid function linkage type");
2214 if (!FunctionType::isValidReturnType(RetType) ||
2215 isa<OpaqueType>(RetType))
2216 return Error(RetTypeLoc, "invalid function return type");
2218 LocTy NameLoc = Lex.getLoc();
2220 std::string FunctionName;
2221 if (Lex.getKind() == lltok::GlobalVar) {
2222 FunctionName = Lex.getStrVal();
2223 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2224 unsigned NameID = Lex.getUIntVal();
2226 if (NameID != NumberedVals.size())
2227 return TokError("function expected to be numbered '%" +
2228 utostr(NumberedVals.size()) + "'");
2230 return TokError("expected function name");
2235 if (Lex.getKind() != lltok::lparen)
2236 return TokError("expected '(' in function argument list");
2238 std::vector<ArgInfo> ArgList;
2241 std::string Section;
2245 if (ParseArgumentList(ArgList, isVarArg, false) ||
2246 ParseOptionalAttrs(FuncAttrs, 2) ||
2247 (EatIfPresent(lltok::kw_section) &&
2248 ParseStringConstant(Section)) ||
2249 ParseOptionalAlignment(Alignment) ||
2250 (EatIfPresent(lltok::kw_gc) &&
2251 ParseStringConstant(GC)))
2254 // If the alignment was parsed as an attribute, move to the alignment field.
2255 if (FuncAttrs & Attribute::Alignment) {
2256 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2257 FuncAttrs &= ~Attribute::Alignment;
2260 // Okay, if we got here, the function is syntactically valid. Convert types
2261 // and do semantic checks.
2262 std::vector<const Type*> ParamTypeList;
2263 SmallVector<AttributeWithIndex, 8> Attrs;
2264 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2266 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2267 if (FuncAttrs & ObsoleteFuncAttrs) {
2268 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2269 FuncAttrs &= ~ObsoleteFuncAttrs;
2272 if (RetAttrs != Attribute::None)
2273 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2275 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2276 ParamTypeList.push_back(ArgList[i].Type);
2277 if (ArgList[i].Attrs != Attribute::None)
2278 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2281 if (FuncAttrs != Attribute::None)
2282 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2284 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2286 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2287 RetType != Type::VoidTy)
2288 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2290 const FunctionType *FT =
2291 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2292 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2295 if (!FunctionName.empty()) {
2296 // If this was a definition of a forward reference, remove the definition
2297 // from the forward reference table and fill in the forward ref.
2298 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2299 ForwardRefVals.find(FunctionName);
2300 if (FRVI != ForwardRefVals.end()) {
2301 Fn = M->getFunction(FunctionName);
2302 ForwardRefVals.erase(FRVI);
2303 } else if ((Fn = M->getFunction(FunctionName))) {
2304 // If this function already exists in the symbol table, then it is
2305 // multiply defined. We accept a few cases for old backwards compat.
2306 // FIXME: Remove this stuff for LLVM 3.0.
2307 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2308 (!Fn->isDeclaration() && isDefine)) {
2309 // If the redefinition has different type or different attributes,
2310 // reject it. If both have bodies, reject it.
2311 return Error(NameLoc, "invalid redefinition of function '" +
2312 FunctionName + "'");
2313 } else if (Fn->isDeclaration()) {
2314 // Make sure to strip off any argument names so we can't get conflicts.
2315 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2321 } else if (FunctionName.empty()) {
2322 // If this is a definition of a forward referenced function, make sure the
2324 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2325 = ForwardRefValIDs.find(NumberedVals.size());
2326 if (I != ForwardRefValIDs.end()) {
2327 Fn = cast<Function>(I->second.first);
2328 if (Fn->getType() != PFT)
2329 return Error(NameLoc, "type of definition and forward reference of '@" +
2330 utostr(NumberedVals.size()) +"' disagree");
2331 ForwardRefValIDs.erase(I);
2336 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2337 else // Move the forward-reference to the correct spot in the module.
2338 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2340 if (FunctionName.empty())
2341 NumberedVals.push_back(Fn);
2343 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2344 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2345 Fn->setCallingConv(CC);
2346 Fn->setAttributes(PAL);
2347 Fn->setAlignment(Alignment);
2348 Fn->setSection(Section);
2349 if (!GC.empty()) Fn->setGC(GC.c_str());
2351 // Add all of the arguments we parsed to the function.
2352 Function::arg_iterator ArgIt = Fn->arg_begin();
2353 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2354 // If the argument has a name, insert it into the argument symbol table.
2355 if (ArgList[i].Name.empty()) continue;
2357 // Set the name, if it conflicted, it will be auto-renamed.
2358 ArgIt->setName(ArgList[i].Name);
2360 if (ArgIt->getNameStr() != ArgList[i].Name)
2361 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2362 ArgList[i].Name + "'");
2369 /// ParseFunctionBody
2370 /// ::= '{' BasicBlock+ '}'
2371 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2373 bool LLParser::ParseFunctionBody(Function &Fn) {
2374 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2375 return TokError("expected '{' in function body");
2376 Lex.Lex(); // eat the {.
2378 PerFunctionState PFS(*this, Fn);
2380 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2381 if (ParseBasicBlock(PFS)) return true;
2386 // Verify function is ok.
2387 return PFS.VerifyFunctionComplete();
2391 /// ::= LabelStr? Instruction*
2392 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2393 // If this basic block starts out with a name, remember it.
2395 LocTy NameLoc = Lex.getLoc();
2396 if (Lex.getKind() == lltok::LabelStr) {
2397 Name = Lex.getStrVal();
2401 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2402 if (BB == 0) return true;
2404 std::string NameStr;
2406 // Parse the instructions in this block until we get a terminator.
2409 // This instruction may have three possibilities for a name: a) none
2410 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2411 LocTy NameLoc = Lex.getLoc();
2415 if (Lex.getKind() == lltok::LocalVarID) {
2416 NameID = Lex.getUIntVal();
2418 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2420 } else if (Lex.getKind() == lltok::LocalVar ||
2421 // FIXME: REMOVE IN LLVM 3.0
2422 Lex.getKind() == lltok::StringConstant) {
2423 NameStr = Lex.getStrVal();
2425 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2429 if (ParseInstruction(Inst, BB, PFS)) return true;
2431 BB->getInstList().push_back(Inst);
2433 // Set the name on the instruction.
2434 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2435 } while (!isa<TerminatorInst>(Inst));
2440 //===----------------------------------------------------------------------===//
2441 // Instruction Parsing.
2442 //===----------------------------------------------------------------------===//
2444 /// ParseInstruction - Parse one of the many different instructions.
2446 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2447 PerFunctionState &PFS) {
2448 lltok::Kind Token = Lex.getKind();
2449 if (Token == lltok::Eof)
2450 return TokError("found end of file when expecting more instructions");
2451 LocTy Loc = Lex.getLoc();
2452 unsigned KeywordVal = Lex.getUIntVal();
2453 Lex.Lex(); // Eat the keyword.
2456 default: return Error(Loc, "expected instruction opcode");
2457 // Terminator Instructions.
2458 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2459 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2460 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2461 case lltok::kw_br: return ParseBr(Inst, PFS);
2462 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2463 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2464 // Binary Operators.
2468 // API compatibility: Accept either integer or floating-point types.
2469 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2470 case lltok::kw_fadd:
2471 case lltok::kw_fsub:
2472 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2474 case lltok::kw_udiv:
2475 case lltok::kw_sdiv:
2476 case lltok::kw_urem:
2477 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2478 case lltok::kw_fdiv:
2479 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2481 case lltok::kw_lshr:
2482 case lltok::kw_ashr:
2485 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2486 case lltok::kw_icmp:
2487 case lltok::kw_fcmp:
2488 case lltok::kw_vicmp:
2489 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
2491 case lltok::kw_trunc:
2492 case lltok::kw_zext:
2493 case lltok::kw_sext:
2494 case lltok::kw_fptrunc:
2495 case lltok::kw_fpext:
2496 case lltok::kw_bitcast:
2497 case lltok::kw_uitofp:
2498 case lltok::kw_sitofp:
2499 case lltok::kw_fptoui:
2500 case lltok::kw_fptosi:
2501 case lltok::kw_inttoptr:
2502 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2504 case lltok::kw_select: return ParseSelect(Inst, PFS);
2505 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2506 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2507 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2508 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2509 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2510 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2511 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2513 case lltok::kw_alloca:
2514 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2515 case lltok::kw_free: return ParseFree(Inst, PFS);
2516 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2517 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2518 case lltok::kw_volatile:
2519 if (EatIfPresent(lltok::kw_load))
2520 return ParseLoad(Inst, PFS, true);
2521 else if (EatIfPresent(lltok::kw_store))
2522 return ParseStore(Inst, PFS, true);
2524 return TokError("expected 'load' or 'store'");
2525 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2526 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2527 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2528 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2532 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2533 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2534 // FIXME: REMOVE vicmp/vfcmp!
2535 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2536 switch (Lex.getKind()) {
2537 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2538 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2539 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2540 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2541 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2542 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2543 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2544 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2545 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2546 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2547 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2548 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2549 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2550 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2551 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2552 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2553 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2556 switch (Lex.getKind()) {
2557 default: TokError("expected icmp predicate (e.g. 'eq')");
2558 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2559 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2560 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2561 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2562 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2563 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2564 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2565 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2566 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2567 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2574 //===----------------------------------------------------------------------===//
2575 // Terminator Instructions.
2576 //===----------------------------------------------------------------------===//
2578 /// ParseRet - Parse a return instruction.
2580 /// ::= 'ret' TypeAndValue
2581 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2582 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2583 PerFunctionState &PFS) {
2584 PATypeHolder Ty(Type::VoidTy);
2585 if (ParseType(Ty, true /*void allowed*/)) return true;
2587 if (Ty == Type::VoidTy) {
2588 Inst = ReturnInst::Create();
2593 if (ParseValue(Ty, RV, PFS)) return true;
2595 // The normal case is one return value.
2596 if (Lex.getKind() == lltok::comma) {
2597 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2598 // of 'ret {i32,i32} {i32 1, i32 2}'
2599 SmallVector<Value*, 8> RVs;
2602 while (EatIfPresent(lltok::comma)) {
2603 if (ParseTypeAndValue(RV, PFS)) return true;
2607 RV = Context.getUndef(PFS.getFunction().getReturnType());
2608 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2609 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2610 BB->getInstList().push_back(I);
2614 Inst = ReturnInst::Create(RV);
2620 /// ::= 'br' TypeAndValue
2621 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2622 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2624 Value *Op0, *Op1, *Op2;
2625 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2627 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2628 Inst = BranchInst::Create(BB);
2632 if (Op0->getType() != Type::Int1Ty)
2633 return Error(Loc, "branch condition must have 'i1' type");
2635 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2636 ParseTypeAndValue(Op1, Loc, PFS) ||
2637 ParseToken(lltok::comma, "expected ',' after true destination") ||
2638 ParseTypeAndValue(Op2, Loc2, PFS))
2641 if (!isa<BasicBlock>(Op1))
2642 return Error(Loc, "true destination of branch must be a basic block");
2643 if (!isa<BasicBlock>(Op2))
2644 return Error(Loc2, "true destination of branch must be a basic block");
2646 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2652 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2654 /// ::= (TypeAndValue ',' TypeAndValue)*
2655 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2656 LocTy CondLoc, BBLoc;
2657 Value *Cond, *DefaultBB;
2658 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2659 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2660 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2661 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2664 if (!isa<IntegerType>(Cond->getType()))
2665 return Error(CondLoc, "switch condition must have integer type");
2666 if (!isa<BasicBlock>(DefaultBB))
2667 return Error(BBLoc, "default destination must be a basic block");
2669 // Parse the jump table pairs.
2670 SmallPtrSet<Value*, 32> SeenCases;
2671 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2672 while (Lex.getKind() != lltok::rsquare) {
2673 Value *Constant, *DestBB;
2675 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2676 ParseToken(lltok::comma, "expected ',' after case value") ||
2677 ParseTypeAndValue(DestBB, BBLoc, PFS))
2680 if (!SeenCases.insert(Constant))
2681 return Error(CondLoc, "duplicate case value in switch");
2682 if (!isa<ConstantInt>(Constant))
2683 return Error(CondLoc, "case value is not a constant integer");
2684 if (!isa<BasicBlock>(DestBB))
2685 return Error(BBLoc, "case destination is not a basic block");
2687 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2688 cast<BasicBlock>(DestBB)));
2691 Lex.Lex(); // Eat the ']'.
2693 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2695 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2696 SI->addCase(Table[i].first, Table[i].second);
2702 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2703 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2704 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2705 LocTy CallLoc = Lex.getLoc();
2706 unsigned CC, RetAttrs, FnAttrs;
2707 PATypeHolder RetType(Type::VoidTy);
2710 SmallVector<ParamInfo, 16> ArgList;
2712 Value *NormalBB, *UnwindBB;
2713 if (ParseOptionalCallingConv(CC) ||
2714 ParseOptionalAttrs(RetAttrs, 1) ||
2715 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2716 ParseValID(CalleeID) ||
2717 ParseParameterList(ArgList, PFS) ||
2718 ParseOptionalAttrs(FnAttrs, 2) ||
2719 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2720 ParseTypeAndValue(NormalBB, PFS) ||
2721 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2722 ParseTypeAndValue(UnwindBB, PFS))
2725 if (!isa<BasicBlock>(NormalBB))
2726 return Error(CallLoc, "normal destination is not a basic block");
2727 if (!isa<BasicBlock>(UnwindBB))
2728 return Error(CallLoc, "unwind destination is not a basic block");
2730 // If RetType is a non-function pointer type, then this is the short syntax
2731 // for the call, which means that RetType is just the return type. Infer the
2732 // rest of the function argument types from the arguments that are present.
2733 const PointerType *PFTy = 0;
2734 const FunctionType *Ty = 0;
2735 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2736 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2737 // Pull out the types of all of the arguments...
2738 std::vector<const Type*> ParamTypes;
2739 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2740 ParamTypes.push_back(ArgList[i].V->getType());
2742 if (!FunctionType::isValidReturnType(RetType))
2743 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2745 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2746 PFTy = Context.getPointerTypeUnqual(Ty);
2749 // Look up the callee.
2751 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2753 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2754 // function attributes.
2755 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2756 if (FnAttrs & ObsoleteFuncAttrs) {
2757 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2758 FnAttrs &= ~ObsoleteFuncAttrs;
2761 // Set up the Attributes for the function.
2762 SmallVector<AttributeWithIndex, 8> Attrs;
2763 if (RetAttrs != Attribute::None)
2764 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2766 SmallVector<Value*, 8> Args;
2768 // Loop through FunctionType's arguments and ensure they are specified
2769 // correctly. Also, gather any parameter attributes.
2770 FunctionType::param_iterator I = Ty->param_begin();
2771 FunctionType::param_iterator E = Ty->param_end();
2772 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2773 const Type *ExpectedTy = 0;
2776 } else if (!Ty->isVarArg()) {
2777 return Error(ArgList[i].Loc, "too many arguments specified");
2780 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2781 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2782 ExpectedTy->getDescription() + "'");
2783 Args.push_back(ArgList[i].V);
2784 if (ArgList[i].Attrs != Attribute::None)
2785 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2789 return Error(CallLoc, "not enough parameters specified for call");
2791 if (FnAttrs != Attribute::None)
2792 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2794 // Finish off the Attributes and check them
2795 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2797 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2798 cast<BasicBlock>(UnwindBB),
2799 Args.begin(), Args.end());
2800 II->setCallingConv(CC);
2801 II->setAttributes(PAL);
2808 //===----------------------------------------------------------------------===//
2809 // Binary Operators.
2810 //===----------------------------------------------------------------------===//
2813 /// ::= ArithmeticOps TypeAndValue ',' Value
2815 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2816 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2817 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2818 unsigned Opc, unsigned OperandType) {
2819 LocTy Loc; Value *LHS, *RHS;
2820 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2821 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2822 ParseValue(LHS->getType(), RHS, PFS))
2826 switch (OperandType) {
2827 default: assert(0 && "Unknown operand type!");
2828 case 0: // int or FP.
2829 Valid = LHS->getType()->isIntOrIntVector() ||
2830 LHS->getType()->isFPOrFPVector();
2832 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2833 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2837 return Error(Loc, "invalid operand type for instruction");
2839 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2844 /// ::= ArithmeticOps TypeAndValue ',' Value {
2845 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2847 LocTy Loc; Value *LHS, *RHS;
2848 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2849 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2850 ParseValue(LHS->getType(), RHS, PFS))
2853 if (!LHS->getType()->isIntOrIntVector())
2854 return Error(Loc,"instruction requires integer or integer vector operands");
2856 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2862 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2863 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2864 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2865 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2866 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2868 // Parse the integer/fp comparison predicate.
2872 if (ParseCmpPredicate(Pred, Opc) ||
2873 ParseTypeAndValue(LHS, Loc, PFS) ||
2874 ParseToken(lltok::comma, "expected ',' after compare value") ||
2875 ParseValue(LHS->getType(), RHS, PFS))
2878 if (Opc == Instruction::FCmp) {
2879 if (!LHS->getType()->isFPOrFPVector())
2880 return Error(Loc, "fcmp requires floating point operands");
2881 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2882 } else if (Opc == Instruction::ICmp) {
2883 if (!LHS->getType()->isIntOrIntVector() &&
2884 !isa<PointerType>(LHS->getType()))
2885 return Error(Loc, "icmp requires integer operands");
2886 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2887 } else if (Opc == Instruction::VFCmp) {
2888 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2889 return Error(Loc, "vfcmp requires vector floating point operands");
2890 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2891 } else if (Opc == Instruction::VICmp) {
2892 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2893 return Error(Loc, "vicmp requires vector floating point operands");
2894 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2899 //===----------------------------------------------------------------------===//
2900 // Other Instructions.
2901 //===----------------------------------------------------------------------===//
2905 /// ::= CastOpc TypeAndValue 'to' Type
2906 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2908 LocTy Loc; Value *Op;
2909 PATypeHolder DestTy(Type::VoidTy);
2910 if (ParseTypeAndValue(Op, Loc, PFS) ||
2911 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2915 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2916 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
2917 return Error(Loc, "invalid cast opcode for cast from '" +
2918 Op->getType()->getDescription() + "' to '" +
2919 DestTy->getDescription() + "'");
2921 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2926 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2927 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2929 Value *Op0, *Op1, *Op2;
2930 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2931 ParseToken(lltok::comma, "expected ',' after select condition") ||
2932 ParseTypeAndValue(Op1, PFS) ||
2933 ParseToken(lltok::comma, "expected ',' after select value") ||
2934 ParseTypeAndValue(Op2, PFS))
2937 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2938 return Error(Loc, Reason);
2940 Inst = SelectInst::Create(Op0, Op1, Op2);
2945 /// ::= 'va_arg' TypeAndValue ',' Type
2946 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2948 PATypeHolder EltTy(Type::VoidTy);
2950 if (ParseTypeAndValue(Op, PFS) ||
2951 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2952 ParseType(EltTy, TypeLoc))
2955 if (!EltTy->isFirstClassType())
2956 return Error(TypeLoc, "va_arg requires operand with first class type");
2958 Inst = new VAArgInst(Op, EltTy);
2962 /// ParseExtractElement
2963 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2964 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2967 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2968 ParseToken(lltok::comma, "expected ',' after extract value") ||
2969 ParseTypeAndValue(Op1, PFS))
2972 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2973 return Error(Loc, "invalid extractelement operands");
2975 Inst = new ExtractElementInst(Op0, Op1);
2979 /// ParseInsertElement
2980 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2981 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2983 Value *Op0, *Op1, *Op2;
2984 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2985 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2986 ParseTypeAndValue(Op1, PFS) ||
2987 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2988 ParseTypeAndValue(Op2, PFS))
2991 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2992 return Error(Loc, "invalid extractelement operands");
2994 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2998 /// ParseShuffleVector
2999 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3000 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3002 Value *Op0, *Op1, *Op2;
3003 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3004 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3005 ParseTypeAndValue(Op1, PFS) ||
3006 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3007 ParseTypeAndValue(Op2, PFS))
3010 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3011 return Error(Loc, "invalid extractelement operands");
3013 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3018 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3019 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3020 PATypeHolder Ty(Type::VoidTy);
3022 LocTy TypeLoc = Lex.getLoc();
3024 if (ParseType(Ty) ||
3025 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3026 ParseValue(Ty, Op0, PFS) ||
3027 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3028 ParseValue(Type::LabelTy, Op1, PFS) ||
3029 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3032 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3034 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3036 if (!EatIfPresent(lltok::comma))
3039 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3040 ParseValue(Ty, Op0, PFS) ||
3041 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3042 ParseValue(Type::LabelTy, Op1, PFS) ||
3043 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3047 if (!Ty->isFirstClassType())
3048 return Error(TypeLoc, "phi node must have first class type");
3050 PHINode *PN = PHINode::Create(Ty);
3051 PN->reserveOperandSpace(PHIVals.size());
3052 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3053 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3059 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3060 /// ParameterList OptionalAttrs
3061 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3063 unsigned CC, RetAttrs, FnAttrs;
3064 PATypeHolder RetType(Type::VoidTy);
3067 SmallVector<ParamInfo, 16> ArgList;
3068 LocTy CallLoc = Lex.getLoc();
3070 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3071 ParseOptionalCallingConv(CC) ||
3072 ParseOptionalAttrs(RetAttrs, 1) ||
3073 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3074 ParseValID(CalleeID) ||
3075 ParseParameterList(ArgList, PFS) ||
3076 ParseOptionalAttrs(FnAttrs, 2))
3079 // If RetType is a non-function pointer type, then this is the short syntax
3080 // for the call, which means that RetType is just the return type. Infer the
3081 // rest of the function argument types from the arguments that are present.
3082 const PointerType *PFTy = 0;
3083 const FunctionType *Ty = 0;
3084 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3085 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3086 // Pull out the types of all of the arguments...
3087 std::vector<const Type*> ParamTypes;
3088 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3089 ParamTypes.push_back(ArgList[i].V->getType());
3091 if (!FunctionType::isValidReturnType(RetType))
3092 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3094 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3095 PFTy = Context.getPointerTypeUnqual(Ty);
3098 // Look up the callee.
3100 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3102 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3103 // function attributes.
3104 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3105 if (FnAttrs & ObsoleteFuncAttrs) {
3106 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3107 FnAttrs &= ~ObsoleteFuncAttrs;
3110 // Set up the Attributes for the function.
3111 SmallVector<AttributeWithIndex, 8> Attrs;
3112 if (RetAttrs != Attribute::None)
3113 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3115 SmallVector<Value*, 8> Args;
3117 // Loop through FunctionType's arguments and ensure they are specified
3118 // correctly. Also, gather any parameter attributes.
3119 FunctionType::param_iterator I = Ty->param_begin();
3120 FunctionType::param_iterator E = Ty->param_end();
3121 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3122 const Type *ExpectedTy = 0;
3125 } else if (!Ty->isVarArg()) {
3126 return Error(ArgList[i].Loc, "too many arguments specified");
3129 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3130 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3131 ExpectedTy->getDescription() + "'");
3132 Args.push_back(ArgList[i].V);
3133 if (ArgList[i].Attrs != Attribute::None)
3134 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3138 return Error(CallLoc, "not enough parameters specified for call");
3140 if (FnAttrs != Attribute::None)
3141 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3143 // Finish off the Attributes and check them
3144 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3146 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3147 CI->setTailCall(isTail);
3148 CI->setCallingConv(CC);
3149 CI->setAttributes(PAL);
3154 //===----------------------------------------------------------------------===//
3155 // Memory Instructions.
3156 //===----------------------------------------------------------------------===//
3159 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3160 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3161 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3163 PATypeHolder Ty(Type::VoidTy);
3166 unsigned Alignment = 0;
3167 if (ParseType(Ty)) return true;
3169 if (EatIfPresent(lltok::comma)) {
3170 if (Lex.getKind() == lltok::kw_align) {
3171 if (ParseOptionalAlignment(Alignment)) return true;
3172 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3173 ParseOptionalCommaAlignment(Alignment)) {
3178 if (Size && Size->getType() != Type::Int32Ty)
3179 return Error(SizeLoc, "element count must be i32");
3181 if (Opc == Instruction::Malloc)
3182 Inst = new MallocInst(Ty, Size, Alignment);
3184 Inst = new AllocaInst(Ty, Size, Alignment);
3189 /// ::= 'free' TypeAndValue
3190 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3191 Value *Val; LocTy Loc;
3192 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3193 if (!isa<PointerType>(Val->getType()))
3194 return Error(Loc, "operand to free must be a pointer");
3195 Inst = new FreeInst(Val);
3200 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3201 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3203 Value *Val; LocTy Loc;
3205 if (ParseTypeAndValue(Val, Loc, PFS) ||
3206 ParseOptionalCommaAlignment(Alignment))
3209 if (!isa<PointerType>(Val->getType()) ||
3210 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3211 return Error(Loc, "load operand must be a pointer to a first class type");
3213 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3218 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3219 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3221 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3223 if (ParseTypeAndValue(Val, Loc, PFS) ||
3224 ParseToken(lltok::comma, "expected ',' after store operand") ||
3225 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3226 ParseOptionalCommaAlignment(Alignment))
3229 if (!isa<PointerType>(Ptr->getType()))
3230 return Error(PtrLoc, "store operand must be a pointer");
3231 if (!Val->getType()->isFirstClassType())
3232 return Error(Loc, "store operand must be a first class value");
3233 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3234 return Error(Loc, "stored value and pointer type do not match");
3236 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3241 /// ::= 'getresult' TypeAndValue ',' i32
3242 /// FIXME: Remove support for getresult in LLVM 3.0
3243 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3244 Value *Val; LocTy ValLoc, EltLoc;
3246 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3247 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3248 ParseUInt32(Element, EltLoc))
3251 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3252 return Error(ValLoc, "getresult inst requires an aggregate operand");
3253 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3254 return Error(EltLoc, "invalid getresult index for value");
3255 Inst = ExtractValueInst::Create(Val, Element);
3259 /// ParseGetElementPtr
3260 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3261 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3262 Value *Ptr, *Val; LocTy Loc, EltLoc;
3263 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3265 if (!isa<PointerType>(Ptr->getType()))
3266 return Error(Loc, "base of getelementptr must be a pointer");
3268 SmallVector<Value*, 16> Indices;
3269 while (EatIfPresent(lltok::comma)) {
3270 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3271 if (!isa<IntegerType>(Val->getType()))
3272 return Error(EltLoc, "getelementptr index must be an integer");
3273 Indices.push_back(Val);
3276 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3277 Indices.begin(), Indices.end()))
3278 return Error(Loc, "invalid getelementptr indices");
3279 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3283 /// ParseExtractValue
3284 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3285 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3286 Value *Val; LocTy Loc;
3287 SmallVector<unsigned, 4> Indices;
3288 if (ParseTypeAndValue(Val, Loc, PFS) ||
3289 ParseIndexList(Indices))
3292 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3293 return Error(Loc, "extractvalue operand must be array or struct");
3295 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3297 return Error(Loc, "invalid indices for extractvalue");
3298 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3302 /// ParseInsertValue
3303 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3304 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3305 Value *Val0, *Val1; LocTy Loc0, Loc1;
3306 SmallVector<unsigned, 4> Indices;
3307 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3308 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3309 ParseTypeAndValue(Val1, Loc1, PFS) ||
3310 ParseIndexList(Indices))
3313 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3314 return Error(Loc0, "extractvalue operand must be array or struct");
3316 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3318 return Error(Loc0, "invalid indices for insertvalue");
3319 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3323 //===----------------------------------------------------------------------===//
3324 // Embedded metadata.
3325 //===----------------------------------------------------------------------===//
3327 /// ParseMDNodeVector
3328 /// ::= Element (',' Element)*
3330 /// ::= 'null' | TypeAndValue
3331 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3332 assert(Lex.getKind() == lltok::lbrace);
3336 if (Lex.getKind() == lltok::kw_null) {
3341 if (ParseGlobalTypeAndValue(C)) return true;
3345 } while (EatIfPresent(lltok::comma));