1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/ValueSymbolTable.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Support/raw_ostream.h"
29 /// ValID - Represents a reference of a definition of some sort with no type.
30 /// There are several cases where we have to parse the value but where the
31 /// type can depend on later context. This may either be a numeric reference
32 /// or a symbolic (%var) reference. This is just a discriminated union.
35 t_LocalID, t_GlobalID, // ID in UIntVal.
36 t_LocalName, t_GlobalName, // Name in StrVal.
37 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
38 t_Null, t_Undef, t_Zero, // No value.
39 t_EmptyArray, // No value: []
40 t_Constant, // Value in ConstantVal.
41 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
46 std::string StrVal, StrVal2;
49 Constant *ConstantVal;
50 ValID() : APFloatVal(0.0) {}
54 /// Run: module ::= toplevelentity*
55 bool LLParser::Run() {
59 return ParseTopLevelEntities() ||
60 ValidateEndOfModule();
63 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
65 bool LLParser::ValidateEndOfModule() {
66 if (!ForwardRefTypes.empty())
67 return Error(ForwardRefTypes.begin()->second.second,
68 "use of undefined type named '" +
69 ForwardRefTypes.begin()->first + "'");
70 if (!ForwardRefTypeIDs.empty())
71 return Error(ForwardRefTypeIDs.begin()->second.second,
72 "use of undefined type '%" +
73 utostr(ForwardRefTypeIDs.begin()->first) + "'");
75 if (!ForwardRefVals.empty())
76 return Error(ForwardRefVals.begin()->second.second,
77 "use of undefined value '@" + ForwardRefVals.begin()->first +
80 if (!ForwardRefValIDs.empty())
81 return Error(ForwardRefValIDs.begin()->second.second,
82 "use of undefined value '@" +
83 utostr(ForwardRefValIDs.begin()->first) + "'");
85 // Look for intrinsic functions and CallInst that need to be upgraded
86 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
87 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
92 //===----------------------------------------------------------------------===//
94 //===----------------------------------------------------------------------===//
96 bool LLParser::ParseTopLevelEntities() {
98 switch (Lex.getKind()) {
99 default: return TokError("expected top-level entity");
100 case lltok::Eof: return false;
101 //case lltok::kw_define:
102 case lltok::kw_declare: if (ParseDeclare()) return true; break;
103 case lltok::kw_define: if (ParseDefine()) return true; break;
104 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
105 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
106 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
107 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
108 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
109 case lltok::LocalVar: if (ParseNamedType()) return true; break;
110 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
112 // The Global variable production with no name can have many different
113 // optional leading prefixes, the production is:
114 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
115 // OptionalAddrSpace ('constant'|'global') ...
116 case lltok::kw_private: // OptionalLinkage
117 case lltok::kw_internal: // OptionalLinkage
118 case lltok::kw_weak: // OptionalLinkage
119 case lltok::kw_weak_odr: // OptionalLinkage
120 case lltok::kw_linkonce: // OptionalLinkage
121 case lltok::kw_linkonce_odr: // OptionalLinkage
122 case lltok::kw_appending: // OptionalLinkage
123 case lltok::kw_dllexport: // OptionalLinkage
124 case lltok::kw_common: // OptionalLinkage
125 case lltok::kw_dllimport: // OptionalLinkage
126 case lltok::kw_extern_weak: // OptionalLinkage
127 case lltok::kw_external: { // OptionalLinkage
128 unsigned Linkage, Visibility;
129 if (ParseOptionalLinkage(Linkage) ||
130 ParseOptionalVisibility(Visibility) ||
131 ParseGlobal("", 0, Linkage, true, Visibility))
135 case lltok::kw_default: // OptionalVisibility
136 case lltok::kw_hidden: // OptionalVisibility
137 case lltok::kw_protected: { // OptionalVisibility
139 if (ParseOptionalVisibility(Visibility) ||
140 ParseGlobal("", 0, 0, false, Visibility))
145 case lltok::kw_thread_local: // OptionalThreadLocal
146 case lltok::kw_addrspace: // OptionalAddrSpace
147 case lltok::kw_constant: // GlobalType
148 case lltok::kw_global: // GlobalType
149 if (ParseGlobal("", 0, 0, false, 0)) return true;
157 /// ::= 'module' 'asm' STRINGCONSTANT
158 bool LLParser::ParseModuleAsm() {
159 assert(Lex.getKind() == lltok::kw_module);
163 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
164 ParseStringConstant(AsmStr)) return true;
166 const std::string &AsmSoFar = M->getModuleInlineAsm();
167 if (AsmSoFar.empty())
168 M->setModuleInlineAsm(AsmStr);
170 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
175 /// ::= 'target' 'triple' '=' STRINGCONSTANT
176 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
177 bool LLParser::ParseTargetDefinition() {
178 assert(Lex.getKind() == lltok::kw_target);
181 default: return TokError("unknown target property");
182 case lltok::kw_triple:
184 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
185 ParseStringConstant(Str))
187 M->setTargetTriple(Str);
189 case lltok::kw_datalayout:
191 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
192 ParseStringConstant(Str))
194 M->setDataLayout(Str);
200 /// ::= 'deplibs' '=' '[' ']'
201 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
202 bool LLParser::ParseDepLibs() {
203 assert(Lex.getKind() == lltok::kw_deplibs);
205 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
206 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
209 if (EatIfPresent(lltok::rsquare))
213 if (ParseStringConstant(Str)) return true;
216 while (EatIfPresent(lltok::comma)) {
217 if (ParseStringConstant(Str)) return true;
221 return ParseToken(lltok::rsquare, "expected ']' at end of list");
226 bool LLParser::ParseUnnamedType() {
227 assert(Lex.getKind() == lltok::kw_type);
228 LocTy TypeLoc = Lex.getLoc();
229 Lex.Lex(); // eat kw_type
231 PATypeHolder Ty(Type::VoidTy);
232 if (ParseType(Ty)) return true;
234 unsigned TypeID = NumberedTypes.size();
236 // See if this type was previously referenced.
237 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
238 FI = ForwardRefTypeIDs.find(TypeID);
239 if (FI != ForwardRefTypeIDs.end()) {
240 if (FI->second.first.get() == Ty)
241 return Error(TypeLoc, "self referential type is invalid");
243 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
244 Ty = FI->second.first.get();
245 ForwardRefTypeIDs.erase(FI);
248 NumberedTypes.push_back(Ty);
254 /// ::= LocalVar '=' 'type' type
255 bool LLParser::ParseNamedType() {
256 std::string Name = Lex.getStrVal();
257 LocTy NameLoc = Lex.getLoc();
258 Lex.Lex(); // eat LocalVar.
260 PATypeHolder Ty(Type::VoidTy);
262 if (ParseToken(lltok::equal, "expected '=' after name") ||
263 ParseToken(lltok::kw_type, "expected 'type' after name") ||
267 // Set the type name, checking for conflicts as we do so.
268 bool AlreadyExists = M->addTypeName(Name, Ty);
269 if (!AlreadyExists) return false;
271 // See if this type is a forward reference. We need to eagerly resolve
272 // types to allow recursive type redefinitions below.
273 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
274 FI = ForwardRefTypes.find(Name);
275 if (FI != ForwardRefTypes.end()) {
276 if (FI->second.first.get() == Ty)
277 return Error(NameLoc, "self referential type is invalid");
279 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
280 Ty = FI->second.first.get();
281 ForwardRefTypes.erase(FI);
284 // Inserting a name that is already defined, get the existing name.
285 const Type *Existing = M->getTypeByName(Name);
286 assert(Existing && "Conflict but no matching type?!");
288 // Otherwise, this is an attempt to redefine a type. That's okay if
289 // the redefinition is identical to the original.
290 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
291 if (Existing == Ty) return false;
293 // Any other kind of (non-equivalent) redefinition is an error.
294 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
295 Ty->getDescription() + "'");
300 /// ::= 'declare' FunctionHeader
301 bool LLParser::ParseDeclare() {
302 assert(Lex.getKind() == lltok::kw_declare);
306 return ParseFunctionHeader(F, false);
310 /// ::= 'define' FunctionHeader '{' ...
311 bool LLParser::ParseDefine() {
312 assert(Lex.getKind() == lltok::kw_define);
316 return ParseFunctionHeader(F, true) ||
317 ParseFunctionBody(*F);
323 bool LLParser::ParseGlobalType(bool &IsConstant) {
324 if (Lex.getKind() == lltok::kw_constant)
326 else if (Lex.getKind() == lltok::kw_global)
330 return TokError("expected 'global' or 'constant'");
336 /// ParseNamedGlobal:
337 /// GlobalVar '=' OptionalVisibility ALIAS ...
338 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
339 bool LLParser::ParseNamedGlobal() {
340 assert(Lex.getKind() == lltok::GlobalVar);
341 LocTy NameLoc = Lex.getLoc();
342 std::string Name = Lex.getStrVal();
346 unsigned Linkage, Visibility;
347 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
348 ParseOptionalLinkage(Linkage, HasLinkage) ||
349 ParseOptionalVisibility(Visibility))
352 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
353 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
354 return ParseAlias(Name, NameLoc, Visibility);
358 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
360 /// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
362 /// Everything through visibility has already been parsed.
364 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
365 unsigned Visibility) {
366 assert(Lex.getKind() == lltok::kw_alias);
369 LocTy LinkageLoc = Lex.getLoc();
370 if (ParseOptionalLinkage(Linkage))
373 if (Linkage != GlobalValue::ExternalLinkage &&
374 Linkage != GlobalValue::WeakAnyLinkage &&
375 Linkage != GlobalValue::WeakODRLinkage &&
376 Linkage != GlobalValue::InternalLinkage &&
377 Linkage != GlobalValue::PrivateLinkage)
378 return Error(LinkageLoc, "invalid linkage type for alias");
381 LocTy AliaseeLoc = Lex.getLoc();
382 if (Lex.getKind() != lltok::kw_bitcast) {
383 if (ParseGlobalTypeAndValue(Aliasee)) return true;
385 // The bitcast dest type is not present, it is implied by the dest type.
387 if (ParseValID(ID)) return true;
388 if (ID.Kind != ValID::t_Constant)
389 return Error(AliaseeLoc, "invalid aliasee");
390 Aliasee = ID.ConstantVal;
393 if (!isa<PointerType>(Aliasee->getType()))
394 return Error(AliaseeLoc, "alias must have pointer type");
396 // Okay, create the alias but do not insert it into the module yet.
397 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
398 (GlobalValue::LinkageTypes)Linkage, Name,
400 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
402 // See if this value already exists in the symbol table. If so, it is either
403 // a redefinition or a definition of a forward reference.
404 if (GlobalValue *Val =
405 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
406 // See if this was a redefinition. If so, there is no entry in
408 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
409 I = ForwardRefVals.find(Name);
410 if (I == ForwardRefVals.end())
411 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
413 // Otherwise, this was a definition of forward ref. Verify that types
415 if (Val->getType() != GA->getType())
416 return Error(NameLoc,
417 "forward reference and definition of alias have different types");
419 // If they agree, just RAUW the old value with the alias and remove the
421 Val->replaceAllUsesWith(GA);
422 Val->eraseFromParent();
423 ForwardRefVals.erase(I);
426 // Insert into the module, we know its name won't collide now.
427 M->getAliasList().push_back(GA);
428 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
434 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
435 /// OptionalAddrSpace GlobalType Type Const
436 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
437 /// OptionalAddrSpace GlobalType Type Const
439 /// Everything through visibility has been parsed already.
441 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
442 unsigned Linkage, bool HasLinkage,
443 unsigned Visibility) {
445 bool ThreadLocal, IsConstant;
448 PATypeHolder Ty(Type::VoidTy);
449 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
450 ParseOptionalAddrSpace(AddrSpace) ||
451 ParseGlobalType(IsConstant) ||
452 ParseType(Ty, TyLoc))
455 // If the linkage is specified and is external, then no initializer is
458 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
459 Linkage != GlobalValue::ExternalWeakLinkage &&
460 Linkage != GlobalValue::ExternalLinkage)) {
461 if (ParseGlobalValue(Ty, Init))
465 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
466 return Error(TyLoc, "invalid type for global variable");
468 GlobalVariable *GV = 0;
470 // See if the global was forward referenced, if so, use the global.
472 if ((GV = M->getGlobalVariable(Name, true)) &&
473 !ForwardRefVals.erase(Name))
474 return Error(NameLoc, "redefinition of global '@" + Name + "'");
476 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
477 I = ForwardRefValIDs.find(NumberedVals.size());
478 if (I != ForwardRefValIDs.end()) {
479 GV = cast<GlobalVariable>(I->second.first);
480 ForwardRefValIDs.erase(I);
485 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
486 M, false, AddrSpace);
488 if (GV->getType()->getElementType() != Ty)
490 "forward reference and definition of global have different types");
492 // Move the forward-reference to the correct spot in the module.
493 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
497 NumberedVals.push_back(GV);
499 // Set the parsed properties on the global.
501 GV->setInitializer(Init);
502 GV->setConstant(IsConstant);
503 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
504 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
505 GV->setThreadLocal(ThreadLocal);
507 // Parse attributes on the global.
508 while (Lex.getKind() == lltok::comma) {
511 if (Lex.getKind() == lltok::kw_section) {
513 GV->setSection(Lex.getStrVal());
514 if (ParseToken(lltok::StringConstant, "expected global section string"))
516 } else if (Lex.getKind() == lltok::kw_align) {
518 if (ParseOptionalAlignment(Alignment)) return true;
519 GV->setAlignment(Alignment);
521 TokError("unknown global variable property!");
529 //===----------------------------------------------------------------------===//
530 // GlobalValue Reference/Resolution Routines.
531 //===----------------------------------------------------------------------===//
533 /// GetGlobalVal - Get a value with the specified name or ID, creating a
534 /// forward reference record if needed. This can return null if the value
535 /// exists but does not have the right type.
536 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
538 const PointerType *PTy = dyn_cast<PointerType>(Ty);
540 Error(Loc, "global variable reference must have pointer type");
544 // Look this name up in the normal function symbol table.
546 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
548 // If this is a forward reference for the value, see if we already created a
549 // forward ref record.
551 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
552 I = ForwardRefVals.find(Name);
553 if (I != ForwardRefVals.end())
554 Val = I->second.first;
557 // If we have the value in the symbol table or fwd-ref table, return it.
559 if (Val->getType() == Ty) return Val;
560 Error(Loc, "'@" + Name + "' defined with type '" +
561 Val->getType()->getDescription() + "'");
565 // Otherwise, create a new forward reference for this value and remember it.
567 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
568 // Function types can return opaque but functions can't.
569 if (isa<OpaqueType>(FT->getReturnType())) {
570 Error(Loc, "function may not return opaque type");
574 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
576 FwdVal = new GlobalVariable(PTy->getElementType(), false,
577 GlobalValue::ExternalWeakLinkage, 0, Name, M);
580 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
584 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
585 const PointerType *PTy = dyn_cast<PointerType>(Ty);
587 Error(Loc, "global variable reference must have pointer type");
591 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
593 // If this is a forward reference for the value, see if we already created a
594 // forward ref record.
596 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
597 I = ForwardRefValIDs.find(ID);
598 if (I != ForwardRefValIDs.end())
599 Val = I->second.first;
602 // If we have the value in the symbol table or fwd-ref table, return it.
604 if (Val->getType() == Ty) return Val;
605 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
606 Val->getType()->getDescription() + "'");
610 // Otherwise, create a new forward reference for this value and remember it.
612 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
613 // Function types can return opaque but functions can't.
614 if (isa<OpaqueType>(FT->getReturnType())) {
615 Error(Loc, "function may not return opaque type");
618 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
620 FwdVal = new GlobalVariable(PTy->getElementType(), false,
621 GlobalValue::ExternalWeakLinkage, 0, "", M);
624 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
629 //===----------------------------------------------------------------------===//
631 //===----------------------------------------------------------------------===//
633 /// ParseToken - If the current token has the specified kind, eat it and return
634 /// success. Otherwise, emit the specified error and return failure.
635 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
636 if (Lex.getKind() != T)
637 return TokError(ErrMsg);
642 /// ParseStringConstant
643 /// ::= StringConstant
644 bool LLParser::ParseStringConstant(std::string &Result) {
645 if (Lex.getKind() != lltok::StringConstant)
646 return TokError("expected string constant");
647 Result = Lex.getStrVal();
654 bool LLParser::ParseUInt32(unsigned &Val) {
655 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
656 return TokError("expected integer");
657 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
658 if (Val64 != unsigned(Val64))
659 return TokError("expected 32-bit integer (too large)");
666 /// ParseOptionalAddrSpace
668 /// := 'addrspace' '(' uint32 ')'
669 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
671 if (!EatIfPresent(lltok::kw_addrspace))
673 return ParseToken(lltok::lparen, "expected '(' in address space") ||
674 ParseUInt32(AddrSpace) ||
675 ParseToken(lltok::rparen, "expected ')' in address space");
678 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
679 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
680 /// 2: function attr.
681 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
682 Attrs = Attribute::None;
683 LocTy AttrLoc = Lex.getLoc();
686 switch (Lex.getKind()) {
689 // Treat these as signext/zeroext unless they are function attrs.
690 // FIXME: REMOVE THIS IN LLVM 3.0
692 if (Lex.getKind() == lltok::kw_sext)
693 Attrs |= Attribute::SExt;
695 Attrs |= Attribute::ZExt;
699 default: // End of attributes.
700 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
701 return Error(AttrLoc, "invalid use of function-only attribute");
703 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
704 return Error(AttrLoc, "invalid use of parameter-only attribute");
707 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
708 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
709 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
710 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
711 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
712 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
713 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
714 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
716 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
717 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
718 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
719 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
720 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
721 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
722 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
723 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
724 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
727 case lltok::kw_align: {
729 if (ParseOptionalAlignment(Alignment))
731 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
739 /// ParseOptionalLinkage
746 /// ::= 'linkonce_odr'
751 /// ::= 'extern_weak'
753 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
755 switch (Lex.getKind()) {
756 default: Res = GlobalValue::ExternalLinkage; return false;
757 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
758 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
759 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
760 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
761 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
762 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
763 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
764 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
765 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
766 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
767 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
768 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
775 /// ParseOptionalVisibility
781 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
782 switch (Lex.getKind()) {
783 default: Res = GlobalValue::DefaultVisibility; return false;
784 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
785 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
786 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
792 /// ParseOptionalCallingConv
797 /// ::= 'x86_stdcallcc'
798 /// ::= 'x86_fastcallcc'
801 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
802 switch (Lex.getKind()) {
803 default: CC = CallingConv::C; return false;
804 case lltok::kw_ccc: CC = CallingConv::C; break;
805 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
806 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
807 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
808 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
809 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
815 /// ParseOptionalAlignment
818 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
820 if (!EatIfPresent(lltok::kw_align))
822 LocTy AlignLoc = Lex.getLoc();
823 if (ParseUInt32(Alignment)) return true;
824 if (!isPowerOf2_32(Alignment))
825 return Error(AlignLoc, "alignment is not a power of two");
829 /// ParseOptionalCommaAlignment
831 /// ::= ',' 'align' 4
832 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
834 if (!EatIfPresent(lltok::comma))
836 return ParseToken(lltok::kw_align, "expected 'align'") ||
837 ParseUInt32(Alignment);
841 /// ::= (',' uint32)+
842 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
843 if (Lex.getKind() != lltok::comma)
844 return TokError("expected ',' as start of index list");
846 while (EatIfPresent(lltok::comma)) {
848 if (ParseUInt32(Idx)) return true;
849 Indices.push_back(Idx);
855 //===----------------------------------------------------------------------===//
857 //===----------------------------------------------------------------------===//
859 /// ParseType - Parse and resolve a full type.
860 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
861 LocTy TypeLoc = Lex.getLoc();
862 if (ParseTypeRec(Result)) return true;
864 // Verify no unresolved uprefs.
866 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
868 if (!AllowVoid && Result.get() == Type::VoidTy)
869 return Error(TypeLoc, "void type only allowed for function results");
874 /// HandleUpRefs - Every time we finish a new layer of types, this function is
875 /// called. It loops through the UpRefs vector, which is a list of the
876 /// currently active types. For each type, if the up-reference is contained in
877 /// the newly completed type, we decrement the level count. When the level
878 /// count reaches zero, the up-referenced type is the type that is passed in:
879 /// thus we can complete the cycle.
881 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
882 // If Ty isn't abstract, or if there are no up-references in it, then there is
883 // nothing to resolve here.
884 if (!ty->isAbstract() || UpRefs.empty()) return ty;
888 errs() << "Type '" << Ty->getDescription()
889 << "' newly formed. Resolving upreferences.\n"
890 << UpRefs.size() << " upreferences active!\n";
893 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
894 // to zero), we resolve them all together before we resolve them to Ty. At
895 // the end of the loop, if there is anything to resolve to Ty, it will be in
897 OpaqueType *TypeToResolve = 0;
899 for (unsigned i = 0; i != UpRefs.size(); ++i) {
900 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
902 std::find(Ty->subtype_begin(), Ty->subtype_end(),
903 UpRefs[i].LastContainedTy) != Ty->subtype_end();
906 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
907 << UpRefs[i].LastContainedTy->getDescription() << ") = "
908 << (ContainsType ? "true" : "false")
909 << " level=" << UpRefs[i].NestingLevel << "\n";
914 // Decrement level of upreference
915 unsigned Level = --UpRefs[i].NestingLevel;
916 UpRefs[i].LastContainedTy = Ty;
918 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
923 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
926 TypeToResolve = UpRefs[i].UpRefTy;
928 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
929 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
930 --i; // Do not skip the next element.
934 TypeToResolve->refineAbstractTypeTo(Ty);
940 /// ParseTypeRec - The recursive function used to process the internal
941 /// implementation details of types.
942 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
943 switch (Lex.getKind()) {
945 return TokError("expected type");
947 // TypeRec ::= 'float' | 'void' (etc)
948 Result = Lex.getTyVal();
951 case lltok::kw_opaque:
952 // TypeRec ::= 'opaque'
953 Result = OpaqueType::get();
957 // TypeRec ::= '{' ... '}'
958 if (ParseStructType(Result, false))
962 // TypeRec ::= '[' ... ']'
963 Lex.Lex(); // eat the lsquare.
964 if (ParseArrayVectorType(Result, false))
967 case lltok::less: // Either vector or packed struct.
968 // TypeRec ::= '<' ... '>'
970 if (Lex.getKind() == lltok::lbrace) {
971 if (ParseStructType(Result, true) ||
972 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
974 } else if (ParseArrayVectorType(Result, true))
977 case lltok::LocalVar:
978 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
980 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
983 Result = OpaqueType::get();
984 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
985 std::make_pair(Result,
987 M->addTypeName(Lex.getStrVal(), Result.get());
992 case lltok::LocalVarID:
994 if (Lex.getUIntVal() < NumberedTypes.size())
995 Result = NumberedTypes[Lex.getUIntVal()];
997 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
998 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
999 if (I != ForwardRefTypeIDs.end())
1000 Result = I->second.first;
1002 Result = OpaqueType::get();
1003 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1004 std::make_pair(Result,
1010 case lltok::backslash: {
1011 // TypeRec ::= '\' 4
1014 if (ParseUInt32(Val)) return true;
1015 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1016 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1022 // Parse the type suffixes.
1024 switch (Lex.getKind()) {
1026 default: return false;
1028 // TypeRec ::= TypeRec '*'
1030 if (Result.get() == Type::LabelTy)
1031 return TokError("basic block pointers are invalid");
1032 if (Result.get() == Type::VoidTy)
1033 return TokError("pointers to void are invalid; use i8* instead");
1034 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1038 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1039 case lltok::kw_addrspace: {
1040 if (Result.get() == Type::LabelTy)
1041 return TokError("basic block pointers are invalid");
1042 if (Result.get() == Type::VoidTy)
1043 return TokError("pointers to void are invalid; use i8* instead");
1045 if (ParseOptionalAddrSpace(AddrSpace) ||
1046 ParseToken(lltok::star, "expected '*' in address space"))
1049 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1053 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1055 if (ParseFunctionType(Result))
1062 /// ParseParameterList
1064 /// ::= '(' Arg (',' Arg)* ')'
1066 /// ::= Type OptionalAttributes Value OptionalAttributes
1067 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1068 PerFunctionState &PFS) {
1069 if (ParseToken(lltok::lparen, "expected '(' in call"))
1072 while (Lex.getKind() != lltok::rparen) {
1073 // If this isn't the first argument, we need a comma.
1074 if (!ArgList.empty() &&
1075 ParseToken(lltok::comma, "expected ',' in argument list"))
1078 // Parse the argument.
1080 PATypeHolder ArgTy(Type::VoidTy);
1081 unsigned ArgAttrs1, ArgAttrs2;
1083 if (ParseType(ArgTy, ArgLoc) ||
1084 ParseOptionalAttrs(ArgAttrs1, 0) ||
1085 ParseValue(ArgTy, V, PFS) ||
1086 // FIXME: Should not allow attributes after the argument, remove this in
1088 ParseOptionalAttrs(ArgAttrs2, 0))
1090 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1093 Lex.Lex(); // Lex the ')'.
1099 /// ParseArgumentList - Parse the argument list for a function type or function
1100 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1101 /// ::= '(' ArgTypeListI ')'
1105 /// ::= ArgTypeList ',' '...'
1106 /// ::= ArgType (',' ArgType)*
1108 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1109 bool &isVarArg, bool inType) {
1111 assert(Lex.getKind() == lltok::lparen);
1112 Lex.Lex(); // eat the (.
1114 if (Lex.getKind() == lltok::rparen) {
1116 } else if (Lex.getKind() == lltok::dotdotdot) {
1120 LocTy TypeLoc = Lex.getLoc();
1121 PATypeHolder ArgTy(Type::VoidTy);
1125 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1126 // types (such as a function returning a pointer to itself). If parsing a
1127 // function prototype, we require fully resolved types.
1128 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1129 ParseOptionalAttrs(Attrs, 0)) return true;
1131 if (ArgTy == Type::VoidTy)
1132 return Error(TypeLoc, "argument can not have void type");
1134 if (Lex.getKind() == lltok::LocalVar ||
1135 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1136 Name = Lex.getStrVal();
1140 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1141 return Error(TypeLoc, "invalid type for function argument");
1143 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1145 while (EatIfPresent(lltok::comma)) {
1146 // Handle ... at end of arg list.
1147 if (EatIfPresent(lltok::dotdotdot)) {
1152 // Otherwise must be an argument type.
1153 TypeLoc = Lex.getLoc();
1154 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1155 ParseOptionalAttrs(Attrs, 0)) return true;
1157 if (ArgTy == Type::VoidTy)
1158 return Error(TypeLoc, "argument can not have void type");
1160 if (Lex.getKind() == lltok::LocalVar ||
1161 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1162 Name = Lex.getStrVal();
1168 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1169 return Error(TypeLoc, "invalid type for function argument");
1171 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1175 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1178 /// ParseFunctionType
1179 /// ::= Type ArgumentList OptionalAttrs
1180 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1181 assert(Lex.getKind() == lltok::lparen);
1183 if (!FunctionType::isValidReturnType(Result))
1184 return TokError("invalid function return type");
1186 std::vector<ArgInfo> ArgList;
1189 if (ParseArgumentList(ArgList, isVarArg, true) ||
1190 // FIXME: Allow, but ignore attributes on function types!
1191 // FIXME: Remove in LLVM 3.0
1192 ParseOptionalAttrs(Attrs, 2))
1195 // Reject names on the arguments lists.
1196 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1197 if (!ArgList[i].Name.empty())
1198 return Error(ArgList[i].Loc, "argument name invalid in function type");
1199 if (!ArgList[i].Attrs != 0) {
1200 // Allow but ignore attributes on function types; this permits
1202 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1206 std::vector<const Type*> ArgListTy;
1207 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1208 ArgListTy.push_back(ArgList[i].Type);
1210 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1214 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1217 /// ::= '{' TypeRec (',' TypeRec)* '}'
1218 /// ::= '<' '{' '}' '>'
1219 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1220 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1221 assert(Lex.getKind() == lltok::lbrace);
1222 Lex.Lex(); // Consume the '{'
1224 if (EatIfPresent(lltok::rbrace)) {
1225 Result = StructType::get(std::vector<const Type*>(), Packed);
1229 std::vector<PATypeHolder> ParamsList;
1230 LocTy EltTyLoc = Lex.getLoc();
1231 if (ParseTypeRec(Result)) return true;
1232 ParamsList.push_back(Result);
1234 if (Result == Type::VoidTy)
1235 return Error(EltTyLoc, "struct element can not have void type");
1237 while (EatIfPresent(lltok::comma)) {
1238 EltTyLoc = Lex.getLoc();
1239 if (ParseTypeRec(Result)) return true;
1241 if (Result == Type::VoidTy)
1242 return Error(EltTyLoc, "struct element can not have void type");
1244 ParamsList.push_back(Result);
1247 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1250 std::vector<const Type*> ParamsListTy;
1251 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1252 ParamsListTy.push_back(ParamsList[i].get());
1253 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1257 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1258 /// token has already been consumed.
1260 /// ::= '[' APSINTVAL 'x' Types ']'
1261 /// ::= '<' APSINTVAL 'x' Types '>'
1262 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1263 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1264 Lex.getAPSIntVal().getBitWidth() > 64)
1265 return TokError("expected number in address space");
1267 LocTy SizeLoc = Lex.getLoc();
1268 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1271 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1274 LocTy TypeLoc = Lex.getLoc();
1275 PATypeHolder EltTy(Type::VoidTy);
1276 if (ParseTypeRec(EltTy)) return true;
1278 if (EltTy == Type::VoidTy)
1279 return Error(TypeLoc, "array and vector element type cannot be void");
1281 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1282 "expected end of sequential type"))
1287 return Error(SizeLoc, "zero element vector is illegal");
1288 if ((unsigned)Size != Size)
1289 return Error(SizeLoc, "size too large for vector");
1290 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1291 return Error(TypeLoc, "vector element type must be fp or integer");
1292 Result = VectorType::get(EltTy, unsigned(Size));
1294 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1295 return Error(TypeLoc, "invalid array element type");
1296 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1301 //===----------------------------------------------------------------------===//
1302 // Function Semantic Analysis.
1303 //===----------------------------------------------------------------------===//
1305 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1308 // Insert unnamed arguments into the NumberedVals list.
1309 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1312 NumberedVals.push_back(AI);
1315 LLParser::PerFunctionState::~PerFunctionState() {
1316 // If there were any forward referenced non-basicblock values, delete them.
1317 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1318 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1319 if (!isa<BasicBlock>(I->second.first)) {
1320 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1322 delete I->second.first;
1323 I->second.first = 0;
1326 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1327 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1328 if (!isa<BasicBlock>(I->second.first)) {
1329 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1331 delete I->second.first;
1332 I->second.first = 0;
1336 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1337 if (!ForwardRefVals.empty())
1338 return P.Error(ForwardRefVals.begin()->second.second,
1339 "use of undefined value '%" + ForwardRefVals.begin()->first +
1341 if (!ForwardRefValIDs.empty())
1342 return P.Error(ForwardRefValIDs.begin()->second.second,
1343 "use of undefined value '%" +
1344 utostr(ForwardRefValIDs.begin()->first) + "'");
1349 /// GetVal - Get a value with the specified name or ID, creating a
1350 /// forward reference record if needed. This can return null if the value
1351 /// exists but does not have the right type.
1352 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1353 const Type *Ty, LocTy Loc) {
1354 // Look this name up in the normal function symbol table.
1355 Value *Val = F.getValueSymbolTable().lookup(Name);
1357 // If this is a forward reference for the value, see if we already created a
1358 // forward ref record.
1360 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1361 I = ForwardRefVals.find(Name);
1362 if (I != ForwardRefVals.end())
1363 Val = I->second.first;
1366 // If we have the value in the symbol table or fwd-ref table, return it.
1368 if (Val->getType() == Ty) return Val;
1369 if (Ty == Type::LabelTy)
1370 P.Error(Loc, "'%" + Name + "' is not a basic block");
1372 P.Error(Loc, "'%" + Name + "' defined with type '" +
1373 Val->getType()->getDescription() + "'");
1377 // Don't make placeholders with invalid type.
1378 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1379 P.Error(Loc, "invalid use of a non-first-class type");
1383 // Otherwise, create a new forward reference for this value and remember it.
1385 if (Ty == Type::LabelTy)
1386 FwdVal = BasicBlock::Create(Name, &F);
1388 FwdVal = new Argument(Ty, Name);
1390 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1394 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1396 // Look this name up in the normal function symbol table.
1397 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1399 // If this is a forward reference for the value, see if we already created a
1400 // forward ref record.
1402 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1403 I = ForwardRefValIDs.find(ID);
1404 if (I != ForwardRefValIDs.end())
1405 Val = I->second.first;
1408 // If we have the value in the symbol table or fwd-ref table, return it.
1410 if (Val->getType() == Ty) return Val;
1411 if (Ty == Type::LabelTy)
1412 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1414 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1415 Val->getType()->getDescription() + "'");
1419 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1420 P.Error(Loc, "invalid use of a non-first-class type");
1424 // Otherwise, create a new forward reference for this value and remember it.
1426 if (Ty == Type::LabelTy)
1427 FwdVal = BasicBlock::Create("", &F);
1429 FwdVal = new Argument(Ty);
1431 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1435 /// SetInstName - After an instruction is parsed and inserted into its
1436 /// basic block, this installs its name.
1437 bool LLParser::PerFunctionState::SetInstName(int NameID,
1438 const std::string &NameStr,
1439 LocTy NameLoc, Instruction *Inst) {
1440 // If this instruction has void type, it cannot have a name or ID specified.
1441 if (Inst->getType() == Type::VoidTy) {
1442 if (NameID != -1 || !NameStr.empty())
1443 return P.Error(NameLoc, "instructions returning void cannot have a name");
1447 // If this was a numbered instruction, verify that the instruction is the
1448 // expected value and resolve any forward references.
1449 if (NameStr.empty()) {
1450 // If neither a name nor an ID was specified, just use the next ID.
1452 NameID = NumberedVals.size();
1454 if (unsigned(NameID) != NumberedVals.size())
1455 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1456 utostr(NumberedVals.size()) + "'");
1458 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1459 ForwardRefValIDs.find(NameID);
1460 if (FI != ForwardRefValIDs.end()) {
1461 if (FI->second.first->getType() != Inst->getType())
1462 return P.Error(NameLoc, "instruction forward referenced with type '" +
1463 FI->second.first->getType()->getDescription() + "'");
1464 FI->second.first->replaceAllUsesWith(Inst);
1465 ForwardRefValIDs.erase(FI);
1468 NumberedVals.push_back(Inst);
1472 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1473 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1474 FI = ForwardRefVals.find(NameStr);
1475 if (FI != ForwardRefVals.end()) {
1476 if (FI->second.first->getType() != Inst->getType())
1477 return P.Error(NameLoc, "instruction forward referenced with type '" +
1478 FI->second.first->getType()->getDescription() + "'");
1479 FI->second.first->replaceAllUsesWith(Inst);
1480 ForwardRefVals.erase(FI);
1483 // Set the name on the instruction.
1484 Inst->setName(NameStr);
1486 if (Inst->getNameStr() != NameStr)
1487 return P.Error(NameLoc, "multiple definition of local value named '" +
1492 /// GetBB - Get a basic block with the specified name or ID, creating a
1493 /// forward reference record if needed.
1494 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1496 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1499 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1500 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1503 /// DefineBB - Define the specified basic block, which is either named or
1504 /// unnamed. If there is an error, this returns null otherwise it returns
1505 /// the block being defined.
1506 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1510 BB = GetBB(NumberedVals.size(), Loc);
1512 BB = GetBB(Name, Loc);
1513 if (BB == 0) return 0; // Already diagnosed error.
1515 // Move the block to the end of the function. Forward ref'd blocks are
1516 // inserted wherever they happen to be referenced.
1517 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1519 // Remove the block from forward ref sets.
1521 ForwardRefValIDs.erase(NumberedVals.size());
1522 NumberedVals.push_back(BB);
1524 // BB forward references are already in the function symbol table.
1525 ForwardRefVals.erase(Name);
1531 //===----------------------------------------------------------------------===//
1533 //===----------------------------------------------------------------------===//
1535 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1536 /// type implied. For example, if we parse "4" we don't know what integer type
1537 /// it has. The value will later be combined with its type and checked for
1539 bool LLParser::ParseValID(ValID &ID) {
1540 ID.Loc = Lex.getLoc();
1541 switch (Lex.getKind()) {
1542 default: return TokError("expected value token");
1543 case lltok::GlobalID: // @42
1544 ID.UIntVal = Lex.getUIntVal();
1545 ID.Kind = ValID::t_GlobalID;
1547 case lltok::GlobalVar: // @foo
1548 ID.StrVal = Lex.getStrVal();
1549 ID.Kind = ValID::t_GlobalName;
1551 case lltok::LocalVarID: // %42
1552 ID.UIntVal = Lex.getUIntVal();
1553 ID.Kind = ValID::t_LocalID;
1555 case lltok::LocalVar: // %foo
1556 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1557 ID.StrVal = Lex.getStrVal();
1558 ID.Kind = ValID::t_LocalName;
1561 ID.APSIntVal = Lex.getAPSIntVal();
1562 ID.Kind = ValID::t_APSInt;
1564 case lltok::APFloat:
1565 ID.APFloatVal = Lex.getAPFloatVal();
1566 ID.Kind = ValID::t_APFloat;
1568 case lltok::kw_true:
1569 ID.ConstantVal = ConstantInt::getTrue();
1570 ID.Kind = ValID::t_Constant;
1572 case lltok::kw_false:
1573 ID.ConstantVal = ConstantInt::getFalse();
1574 ID.Kind = ValID::t_Constant;
1576 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1577 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1578 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1580 case lltok::lbrace: {
1581 // ValID ::= '{' ConstVector '}'
1583 SmallVector<Constant*, 16> Elts;
1584 if (ParseGlobalValueVector(Elts) ||
1585 ParseToken(lltok::rbrace, "expected end of struct constant"))
1588 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1589 ID.Kind = ValID::t_Constant;
1593 // ValID ::= '<' ConstVector '>' --> Vector.
1594 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1596 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1598 SmallVector<Constant*, 16> Elts;
1599 LocTy FirstEltLoc = Lex.getLoc();
1600 if (ParseGlobalValueVector(Elts) ||
1602 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1603 ParseToken(lltok::greater, "expected end of constant"))
1606 if (isPackedStruct) {
1607 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1608 ID.Kind = ValID::t_Constant;
1613 return Error(ID.Loc, "constant vector must not be empty");
1615 if (!Elts[0]->getType()->isInteger() &&
1616 !Elts[0]->getType()->isFloatingPoint())
1617 return Error(FirstEltLoc,
1618 "vector elements must have integer or floating point type");
1620 // Verify that all the vector elements have the same type.
1621 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1622 if (Elts[i]->getType() != Elts[0]->getType())
1623 return Error(FirstEltLoc,
1624 "vector element #" + utostr(i) +
1625 " is not of type '" + Elts[0]->getType()->getDescription());
1627 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1628 ID.Kind = ValID::t_Constant;
1631 case lltok::lsquare: { // Array Constant
1633 SmallVector<Constant*, 16> Elts;
1634 LocTy FirstEltLoc = Lex.getLoc();
1635 if (ParseGlobalValueVector(Elts) ||
1636 ParseToken(lltok::rsquare, "expected end of array constant"))
1639 // Handle empty element.
1641 // Use undef instead of an array because it's inconvenient to determine
1642 // the element type at this point, there being no elements to examine.
1643 ID.Kind = ValID::t_EmptyArray;
1647 if (!Elts[0]->getType()->isFirstClassType())
1648 return Error(FirstEltLoc, "invalid array element type: " +
1649 Elts[0]->getType()->getDescription());
1651 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1653 // Verify all elements are correct type!
1654 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1655 if (Elts[i]->getType() != Elts[0]->getType())
1656 return Error(FirstEltLoc,
1657 "array element #" + utostr(i) +
1658 " is not of type '" +Elts[0]->getType()->getDescription());
1661 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1662 ID.Kind = ValID::t_Constant;
1665 case lltok::kw_c: // c "foo"
1667 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1668 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1669 ID.Kind = ValID::t_Constant;
1672 case lltok::kw_asm: {
1673 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1676 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1677 ParseStringConstant(ID.StrVal) ||
1678 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1679 ParseToken(lltok::StringConstant, "expected constraint string"))
1681 ID.StrVal2 = Lex.getStrVal();
1682 ID.UIntVal = HasSideEffect;
1683 ID.Kind = ValID::t_InlineAsm;
1687 case lltok::kw_trunc:
1688 case lltok::kw_zext:
1689 case lltok::kw_sext:
1690 case lltok::kw_fptrunc:
1691 case lltok::kw_fpext:
1692 case lltok::kw_bitcast:
1693 case lltok::kw_uitofp:
1694 case lltok::kw_sitofp:
1695 case lltok::kw_fptoui:
1696 case lltok::kw_fptosi:
1697 case lltok::kw_inttoptr:
1698 case lltok::kw_ptrtoint: {
1699 unsigned Opc = Lex.getUIntVal();
1700 PATypeHolder DestTy(Type::VoidTy);
1703 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1704 ParseGlobalTypeAndValue(SrcVal) ||
1705 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1706 ParseType(DestTy) ||
1707 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1709 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1710 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1711 SrcVal->getType()->getDescription() + "' to '" +
1712 DestTy->getDescription() + "'");
1713 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1715 ID.Kind = ValID::t_Constant;
1718 case lltok::kw_extractvalue: {
1721 SmallVector<unsigned, 4> Indices;
1722 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1723 ParseGlobalTypeAndValue(Val) ||
1724 ParseIndexList(Indices) ||
1725 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1727 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1728 return Error(ID.Loc, "extractvalue operand must be array or struct");
1729 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1731 return Error(ID.Loc, "invalid indices for extractvalue");
1732 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1733 &Indices[0], Indices.size());
1734 ID.Kind = ValID::t_Constant;
1737 case lltok::kw_insertvalue: {
1739 Constant *Val0, *Val1;
1740 SmallVector<unsigned, 4> Indices;
1741 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1742 ParseGlobalTypeAndValue(Val0) ||
1743 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1744 ParseGlobalTypeAndValue(Val1) ||
1745 ParseIndexList(Indices) ||
1746 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1748 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1749 return Error(ID.Loc, "extractvalue operand must be array or struct");
1750 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1752 return Error(ID.Loc, "invalid indices for insertvalue");
1753 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1754 &Indices[0], Indices.size());
1755 ID.Kind = ValID::t_Constant;
1758 case lltok::kw_icmp:
1759 case lltok::kw_fcmp:
1760 case lltok::kw_vicmp:
1761 case lltok::kw_vfcmp: {
1762 unsigned PredVal, Opc = Lex.getUIntVal();
1763 Constant *Val0, *Val1;
1765 if (ParseCmpPredicate(PredVal, Opc) ||
1766 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1767 ParseGlobalTypeAndValue(Val0) ||
1768 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1769 ParseGlobalTypeAndValue(Val1) ||
1770 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1773 if (Val0->getType() != Val1->getType())
1774 return Error(ID.Loc, "compare operands must have the same type");
1776 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1778 if (Opc == Instruction::FCmp) {
1779 if (!Val0->getType()->isFPOrFPVector())
1780 return Error(ID.Loc, "fcmp requires floating point operands");
1781 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1782 } else if (Opc == Instruction::ICmp) {
1783 if (!Val0->getType()->isIntOrIntVector() &&
1784 !isa<PointerType>(Val0->getType()))
1785 return Error(ID.Loc, "icmp requires pointer or integer operands");
1786 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1787 } else if (Opc == Instruction::VFCmp) {
1788 // FIXME: REMOVE VFCMP Support
1789 if (!Val0->getType()->isFPOrFPVector() ||
1790 !isa<VectorType>(Val0->getType()))
1791 return Error(ID.Loc, "vfcmp requires vector floating point operands");
1792 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1793 } else if (Opc == Instruction::VICmp) {
1794 // FIXME: REMOVE VICMP Support
1795 if (!Val0->getType()->isIntOrIntVector() ||
1796 !isa<VectorType>(Val0->getType()))
1797 return Error(ID.Loc, "vicmp requires vector floating point operands");
1798 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1800 ID.Kind = ValID::t_Constant;
1804 // Binary Operators.
1808 case lltok::kw_udiv:
1809 case lltok::kw_sdiv:
1810 case lltok::kw_fdiv:
1811 case lltok::kw_urem:
1812 case lltok::kw_srem:
1813 case lltok::kw_frem: {
1814 unsigned Opc = Lex.getUIntVal();
1815 Constant *Val0, *Val1;
1817 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1818 ParseGlobalTypeAndValue(Val0) ||
1819 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1820 ParseGlobalTypeAndValue(Val1) ||
1821 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1823 if (Val0->getType() != Val1->getType())
1824 return Error(ID.Loc, "operands of constexpr must have same type");
1825 if (!Val0->getType()->isIntOrIntVector() &&
1826 !Val0->getType()->isFPOrFPVector())
1827 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1828 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1829 ID.Kind = ValID::t_Constant;
1833 // Logical Operations
1835 case lltok::kw_lshr:
1836 case lltok::kw_ashr:
1839 case lltok::kw_xor: {
1840 unsigned Opc = Lex.getUIntVal();
1841 Constant *Val0, *Val1;
1843 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1844 ParseGlobalTypeAndValue(Val0) ||
1845 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1846 ParseGlobalTypeAndValue(Val1) ||
1847 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1849 if (Val0->getType() != Val1->getType())
1850 return Error(ID.Loc, "operands of constexpr must have same type");
1851 if (!Val0->getType()->isIntOrIntVector())
1852 return Error(ID.Loc,
1853 "constexpr requires integer or integer vector operands");
1854 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1855 ID.Kind = ValID::t_Constant;
1859 case lltok::kw_getelementptr:
1860 case lltok::kw_shufflevector:
1861 case lltok::kw_insertelement:
1862 case lltok::kw_extractelement:
1863 case lltok::kw_select: {
1864 unsigned Opc = Lex.getUIntVal();
1865 SmallVector<Constant*, 16> Elts;
1867 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1868 ParseGlobalValueVector(Elts) ||
1869 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1872 if (Opc == Instruction::GetElementPtr) {
1873 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1874 return Error(ID.Loc, "getelementptr requires pointer operand");
1876 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1877 (Value**)&Elts[1], Elts.size()-1))
1878 return Error(ID.Loc, "invalid indices for getelementptr");
1879 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1880 &Elts[1], Elts.size()-1);
1881 } else if (Opc == Instruction::Select) {
1882 if (Elts.size() != 3)
1883 return Error(ID.Loc, "expected three operands to select");
1884 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1886 return Error(ID.Loc, Reason);
1887 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1888 } else if (Opc == Instruction::ShuffleVector) {
1889 if (Elts.size() != 3)
1890 return Error(ID.Loc, "expected three operands to shufflevector");
1891 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1892 return Error(ID.Loc, "invalid operands to shufflevector");
1893 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1894 } else if (Opc == Instruction::ExtractElement) {
1895 if (Elts.size() != 2)
1896 return Error(ID.Loc, "expected two operands to extractelement");
1897 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1898 return Error(ID.Loc, "invalid extractelement operands");
1899 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1901 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1902 if (Elts.size() != 3)
1903 return Error(ID.Loc, "expected three operands to insertelement");
1904 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1905 return Error(ID.Loc, "invalid insertelement operands");
1906 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1909 ID.Kind = ValID::t_Constant;
1918 /// ParseGlobalValue - Parse a global value with the specified type.
1919 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1922 return ParseValID(ID) ||
1923 ConvertGlobalValIDToValue(Ty, ID, V);
1926 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1928 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1930 if (isa<FunctionType>(Ty))
1931 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1934 default: assert(0 && "Unknown ValID!");
1935 case ValID::t_LocalID:
1936 case ValID::t_LocalName:
1937 return Error(ID.Loc, "invalid use of function-local name");
1938 case ValID::t_InlineAsm:
1939 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1940 case ValID::t_GlobalName:
1941 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1943 case ValID::t_GlobalID:
1944 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1946 case ValID::t_APSInt:
1947 if (!isa<IntegerType>(Ty))
1948 return Error(ID.Loc, "integer constant must have integer type");
1949 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1950 V = ConstantInt::get(ID.APSIntVal);
1952 case ValID::t_APFloat:
1953 if (!Ty->isFloatingPoint() ||
1954 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1955 return Error(ID.Loc, "floating point constant invalid for type");
1957 // The lexer has no type info, so builds all float and double FP constants
1958 // as double. Fix this here. Long double does not need this.
1959 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1960 Ty == Type::FloatTy) {
1962 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1965 V = ConstantFP::get(ID.APFloatVal);
1967 if (V->getType() != Ty)
1968 return Error(ID.Loc, "floating point constant does not have type '" +
1969 Ty->getDescription() + "'");
1973 if (!isa<PointerType>(Ty))
1974 return Error(ID.Loc, "null must be a pointer type");
1975 V = ConstantPointerNull::get(cast<PointerType>(Ty));
1977 case ValID::t_Undef:
1978 // FIXME: LabelTy should not be a first-class type.
1979 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
1980 !isa<OpaqueType>(Ty))
1981 return Error(ID.Loc, "invalid type for undef constant");
1982 V = UndefValue::get(Ty);
1984 case ValID::t_EmptyArray:
1985 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
1986 return Error(ID.Loc, "invalid empty array initializer");
1987 V = UndefValue::get(Ty);
1990 // FIXME: LabelTy should not be a first-class type.
1991 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
1992 return Error(ID.Loc, "invalid type for null constant");
1993 V = Constant::getNullValue(Ty);
1995 case ValID::t_Constant:
1996 if (ID.ConstantVal->getType() != Ty)
1997 return Error(ID.Loc, "constant expression type mismatch");
2003 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2004 PATypeHolder Type(Type::VoidTy);
2005 return ParseType(Type) ||
2006 ParseGlobalValue(Type, V);
2009 /// ParseGlobalValueVector
2011 /// ::= TypeAndValue (',' TypeAndValue)*
2012 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2014 if (Lex.getKind() == lltok::rbrace ||
2015 Lex.getKind() == lltok::rsquare ||
2016 Lex.getKind() == lltok::greater ||
2017 Lex.getKind() == lltok::rparen)
2021 if (ParseGlobalTypeAndValue(C)) return true;
2024 while (EatIfPresent(lltok::comma)) {
2025 if (ParseGlobalTypeAndValue(C)) return true;
2033 //===----------------------------------------------------------------------===//
2034 // Function Parsing.
2035 //===----------------------------------------------------------------------===//
2037 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2038 PerFunctionState &PFS) {
2039 if (ID.Kind == ValID::t_LocalID)
2040 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2041 else if (ID.Kind == ValID::t_LocalName)
2042 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2043 else if (ID.Kind == ValID::t_InlineAsm) {
2044 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2045 const FunctionType *FTy =
2046 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2047 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2048 return Error(ID.Loc, "invalid type for inline asm constraint string");
2049 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2053 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2061 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2064 return ParseValID(ID) ||
2065 ConvertValIDToValue(Ty, ID, V, PFS);
2068 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2069 PATypeHolder T(Type::VoidTy);
2070 return ParseType(T) ||
2071 ParseValue(T, V, PFS);
2075 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2076 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2077 /// OptionalAlign OptGC
2078 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2079 // Parse the linkage.
2080 LocTy LinkageLoc = Lex.getLoc();
2083 unsigned Visibility, CC, RetAttrs;
2084 PATypeHolder RetType(Type::VoidTy);
2085 LocTy RetTypeLoc = Lex.getLoc();
2086 if (ParseOptionalLinkage(Linkage) ||
2087 ParseOptionalVisibility(Visibility) ||
2088 ParseOptionalCallingConv(CC) ||
2089 ParseOptionalAttrs(RetAttrs, 1) ||
2090 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2093 // Verify that the linkage is ok.
2094 switch ((GlobalValue::LinkageTypes)Linkage) {
2095 case GlobalValue::ExternalLinkage:
2096 break; // always ok.
2097 case GlobalValue::DLLImportLinkage:
2098 case GlobalValue::ExternalWeakLinkage:
2100 return Error(LinkageLoc, "invalid linkage for function definition");
2102 case GlobalValue::PrivateLinkage:
2103 case GlobalValue::InternalLinkage:
2104 case GlobalValue::LinkOnceAnyLinkage:
2105 case GlobalValue::LinkOnceODRLinkage:
2106 case GlobalValue::WeakAnyLinkage:
2107 case GlobalValue::WeakODRLinkage:
2108 case GlobalValue::DLLExportLinkage:
2110 return Error(LinkageLoc, "invalid linkage for function declaration");
2112 case GlobalValue::AppendingLinkage:
2113 case GlobalValue::GhostLinkage:
2114 case GlobalValue::CommonLinkage:
2115 return Error(LinkageLoc, "invalid function linkage type");
2118 if (!FunctionType::isValidReturnType(RetType) ||
2119 isa<OpaqueType>(RetType))
2120 return Error(RetTypeLoc, "invalid function return type");
2122 LocTy NameLoc = Lex.getLoc();
2124 std::string FunctionName;
2125 if (Lex.getKind() == lltok::GlobalVar) {
2126 FunctionName = Lex.getStrVal();
2127 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2128 unsigned NameID = Lex.getUIntVal();
2130 if (NameID != NumberedVals.size())
2131 return TokError("function expected to be numbered '%" +
2132 utostr(NumberedVals.size()) + "'");
2134 return TokError("expected function name");
2139 if (Lex.getKind() != lltok::lparen)
2140 return TokError("expected '(' in function argument list");
2142 std::vector<ArgInfo> ArgList;
2145 std::string Section;
2149 if (ParseArgumentList(ArgList, isVarArg, false) ||
2150 ParseOptionalAttrs(FuncAttrs, 2) ||
2151 (EatIfPresent(lltok::kw_section) &&
2152 ParseStringConstant(Section)) ||
2153 ParseOptionalAlignment(Alignment) ||
2154 (EatIfPresent(lltok::kw_gc) &&
2155 ParseStringConstant(GC)))
2158 // If the alignment was parsed as an attribute, move to the alignment field.
2159 if (FuncAttrs & Attribute::Alignment) {
2160 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2161 FuncAttrs &= ~Attribute::Alignment;
2164 // Okay, if we got here, the function is syntactically valid. Convert types
2165 // and do semantic checks.
2166 std::vector<const Type*> ParamTypeList;
2167 SmallVector<AttributeWithIndex, 8> Attrs;
2168 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2170 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2171 if (FuncAttrs & ObsoleteFuncAttrs) {
2172 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2173 FuncAttrs &= ~ObsoleteFuncAttrs;
2176 if (RetAttrs != Attribute::None)
2177 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2179 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2180 ParamTypeList.push_back(ArgList[i].Type);
2181 if (ArgList[i].Attrs != Attribute::None)
2182 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2185 if (FuncAttrs != Attribute::None)
2186 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2188 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2190 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2191 RetType != Type::VoidTy)
2192 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2194 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2195 const PointerType *PFT = PointerType::getUnqual(FT);
2198 if (!FunctionName.empty()) {
2199 // If this was a definition of a forward reference, remove the definition
2200 // from the forward reference table and fill in the forward ref.
2201 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2202 ForwardRefVals.find(FunctionName);
2203 if (FRVI != ForwardRefVals.end()) {
2204 Fn = M->getFunction(FunctionName);
2205 ForwardRefVals.erase(FRVI);
2206 } else if ((Fn = M->getFunction(FunctionName))) {
2207 // If this function already exists in the symbol table, then it is
2208 // multiply defined. We accept a few cases for old backwards compat.
2209 // FIXME: Remove this stuff for LLVM 3.0.
2210 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2211 (!Fn->isDeclaration() && isDefine)) {
2212 // If the redefinition has different type or different attributes,
2213 // reject it. If both have bodies, reject it.
2214 return Error(NameLoc, "invalid redefinition of function '" +
2215 FunctionName + "'");
2216 } else if (Fn->isDeclaration()) {
2217 // Make sure to strip off any argument names so we can't get conflicts.
2218 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2224 } else if (FunctionName.empty()) {
2225 // If this is a definition of a forward referenced function, make sure the
2227 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2228 = ForwardRefValIDs.find(NumberedVals.size());
2229 if (I != ForwardRefValIDs.end()) {
2230 Fn = cast<Function>(I->second.first);
2231 if (Fn->getType() != PFT)
2232 return Error(NameLoc, "type of definition and forward reference of '@" +
2233 utostr(NumberedVals.size()) +"' disagree");
2234 ForwardRefValIDs.erase(I);
2239 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2240 else // Move the forward-reference to the correct spot in the module.
2241 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2243 if (FunctionName.empty())
2244 NumberedVals.push_back(Fn);
2246 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2247 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2248 Fn->setCallingConv(CC);
2249 Fn->setAttributes(PAL);
2250 Fn->setAlignment(Alignment);
2251 Fn->setSection(Section);
2252 if (!GC.empty()) Fn->setGC(GC.c_str());
2254 // Add all of the arguments we parsed to the function.
2255 Function::arg_iterator ArgIt = Fn->arg_begin();
2256 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2257 // If the argument has a name, insert it into the argument symbol table.
2258 if (ArgList[i].Name.empty()) continue;
2260 // Set the name, if it conflicted, it will be auto-renamed.
2261 ArgIt->setName(ArgList[i].Name);
2263 if (ArgIt->getNameStr() != ArgList[i].Name)
2264 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2265 ArgList[i].Name + "'");
2272 /// ParseFunctionBody
2273 /// ::= '{' BasicBlock+ '}'
2274 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2276 bool LLParser::ParseFunctionBody(Function &Fn) {
2277 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2278 return TokError("expected '{' in function body");
2279 Lex.Lex(); // eat the {.
2281 PerFunctionState PFS(*this, Fn);
2283 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2284 if (ParseBasicBlock(PFS)) return true;
2289 // Verify function is ok.
2290 return PFS.VerifyFunctionComplete();
2294 /// ::= LabelStr? Instruction*
2295 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2296 // If this basic block starts out with a name, remember it.
2298 LocTy NameLoc = Lex.getLoc();
2299 if (Lex.getKind() == lltok::LabelStr) {
2300 Name = Lex.getStrVal();
2304 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2305 if (BB == 0) return true;
2307 std::string NameStr;
2309 // Parse the instructions in this block until we get a terminator.
2312 // This instruction may have three possibilities for a name: a) none
2313 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2314 LocTy NameLoc = Lex.getLoc();
2318 if (Lex.getKind() == lltok::LocalVarID) {
2319 NameID = Lex.getUIntVal();
2321 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2323 } else if (Lex.getKind() == lltok::LocalVar ||
2324 // FIXME: REMOVE IN LLVM 3.0
2325 Lex.getKind() == lltok::StringConstant) {
2326 NameStr = Lex.getStrVal();
2328 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2332 if (ParseInstruction(Inst, BB, PFS)) return true;
2334 BB->getInstList().push_back(Inst);
2336 // Set the name on the instruction.
2337 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2338 } while (!isa<TerminatorInst>(Inst));
2343 //===----------------------------------------------------------------------===//
2344 // Instruction Parsing.
2345 //===----------------------------------------------------------------------===//
2347 /// ParseInstruction - Parse one of the many different instructions.
2349 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2350 PerFunctionState &PFS) {
2351 lltok::Kind Token = Lex.getKind();
2352 if (Token == lltok::Eof)
2353 return TokError("found end of file when expecting more instructions");
2354 LocTy Loc = Lex.getLoc();
2355 unsigned KeywordVal = Lex.getUIntVal();
2356 Lex.Lex(); // Eat the keyword.
2359 default: return Error(Loc, "expected instruction opcode");
2360 // Terminator Instructions.
2361 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2362 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2363 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2364 case lltok::kw_br: return ParseBr(Inst, PFS);
2365 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2366 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2367 // Binary Operators.
2370 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2372 case lltok::kw_udiv:
2373 case lltok::kw_sdiv:
2374 case lltok::kw_urem:
2375 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2376 case lltok::kw_fdiv:
2377 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2379 case lltok::kw_lshr:
2380 case lltok::kw_ashr:
2383 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2384 case lltok::kw_icmp:
2385 case lltok::kw_fcmp:
2386 case lltok::kw_vicmp:
2387 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
2389 case lltok::kw_trunc:
2390 case lltok::kw_zext:
2391 case lltok::kw_sext:
2392 case lltok::kw_fptrunc:
2393 case lltok::kw_fpext:
2394 case lltok::kw_bitcast:
2395 case lltok::kw_uitofp:
2396 case lltok::kw_sitofp:
2397 case lltok::kw_fptoui:
2398 case lltok::kw_fptosi:
2399 case lltok::kw_inttoptr:
2400 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2402 case lltok::kw_select: return ParseSelect(Inst, PFS);
2403 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2404 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2405 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2406 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2407 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2408 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2409 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2411 case lltok::kw_alloca:
2412 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2413 case lltok::kw_free: return ParseFree(Inst, PFS);
2414 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2415 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2416 case lltok::kw_volatile:
2417 if (EatIfPresent(lltok::kw_load))
2418 return ParseLoad(Inst, PFS, true);
2419 else if (EatIfPresent(lltok::kw_store))
2420 return ParseStore(Inst, PFS, true);
2422 return TokError("expected 'load' or 'store'");
2423 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2424 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2425 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2426 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2430 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2431 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2432 // FIXME: REMOVE vicmp/vfcmp!
2433 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2434 switch (Lex.getKind()) {
2435 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2436 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2437 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2438 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2439 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2440 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2441 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2442 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2443 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2444 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2445 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2446 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2447 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2448 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2449 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2450 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2451 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2454 switch (Lex.getKind()) {
2455 default: TokError("expected icmp predicate (e.g. 'eq')");
2456 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2457 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2458 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2459 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2460 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2461 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2462 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2463 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2464 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2465 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2472 //===----------------------------------------------------------------------===//
2473 // Terminator Instructions.
2474 //===----------------------------------------------------------------------===//
2476 /// ParseRet - Parse a return instruction.
2478 /// ::= 'ret' TypeAndValue
2479 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2480 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2481 PerFunctionState &PFS) {
2482 PATypeHolder Ty(Type::VoidTy);
2483 if (ParseType(Ty, true /*void allowed*/)) return true;
2485 if (Ty == Type::VoidTy) {
2486 Inst = ReturnInst::Create();
2491 if (ParseValue(Ty, RV, PFS)) return true;
2493 // The normal case is one return value.
2494 if (Lex.getKind() == lltok::comma) {
2495 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2496 // of 'ret {i32,i32} {i32 1, i32 2}'
2497 SmallVector<Value*, 8> RVs;
2500 while (EatIfPresent(lltok::comma)) {
2501 if (ParseTypeAndValue(RV, PFS)) return true;
2505 RV = UndefValue::get(PFS.getFunction().getReturnType());
2506 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2507 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2508 BB->getInstList().push_back(I);
2512 Inst = ReturnInst::Create(RV);
2518 /// ::= 'br' TypeAndValue
2519 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2520 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2522 Value *Op0, *Op1, *Op2;
2523 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2525 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2526 Inst = BranchInst::Create(BB);
2530 if (Op0->getType() != Type::Int1Ty)
2531 return Error(Loc, "branch condition must have 'i1' type");
2533 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2534 ParseTypeAndValue(Op1, Loc, PFS) ||
2535 ParseToken(lltok::comma, "expected ',' after true destination") ||
2536 ParseTypeAndValue(Op2, Loc2, PFS))
2539 if (!isa<BasicBlock>(Op1))
2540 return Error(Loc, "true destination of branch must be a basic block");
2541 if (!isa<BasicBlock>(Op2))
2542 return Error(Loc2, "true destination of branch must be a basic block");
2544 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2550 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2552 /// ::= (TypeAndValue ',' TypeAndValue)*
2553 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2554 LocTy CondLoc, BBLoc;
2555 Value *Cond, *DefaultBB;
2556 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2557 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2558 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2559 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2562 if (!isa<IntegerType>(Cond->getType()))
2563 return Error(CondLoc, "switch condition must have integer type");
2564 if (!isa<BasicBlock>(DefaultBB))
2565 return Error(BBLoc, "default destination must be a basic block");
2567 // Parse the jump table pairs.
2568 SmallPtrSet<Value*, 32> SeenCases;
2569 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2570 while (Lex.getKind() != lltok::rsquare) {
2571 Value *Constant, *DestBB;
2573 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2574 ParseToken(lltok::comma, "expected ',' after case value") ||
2575 ParseTypeAndValue(DestBB, BBLoc, PFS))
2578 if (!SeenCases.insert(Constant))
2579 return Error(CondLoc, "duplicate case value in switch");
2580 if (!isa<ConstantInt>(Constant))
2581 return Error(CondLoc, "case value is not a constant integer");
2582 if (!isa<BasicBlock>(DestBB))
2583 return Error(BBLoc, "case destination is not a basic block");
2585 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2586 cast<BasicBlock>(DestBB)));
2589 Lex.Lex(); // Eat the ']'.
2591 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2593 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2594 SI->addCase(Table[i].first, Table[i].second);
2600 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2601 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2602 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2603 LocTy CallLoc = Lex.getLoc();
2604 unsigned CC, RetAttrs, FnAttrs;
2605 PATypeHolder RetType(Type::VoidTy);
2608 SmallVector<ParamInfo, 16> ArgList;
2610 Value *NormalBB, *UnwindBB;
2611 if (ParseOptionalCallingConv(CC) ||
2612 ParseOptionalAttrs(RetAttrs, 1) ||
2613 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2614 ParseValID(CalleeID) ||
2615 ParseParameterList(ArgList, PFS) ||
2616 ParseOptionalAttrs(FnAttrs, 2) ||
2617 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2618 ParseTypeAndValue(NormalBB, PFS) ||
2619 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2620 ParseTypeAndValue(UnwindBB, PFS))
2623 if (!isa<BasicBlock>(NormalBB))
2624 return Error(CallLoc, "normal destination is not a basic block");
2625 if (!isa<BasicBlock>(UnwindBB))
2626 return Error(CallLoc, "unwind destination is not a basic block");
2628 // If RetType is a non-function pointer type, then this is the short syntax
2629 // for the call, which means that RetType is just the return type. Infer the
2630 // rest of the function argument types from the arguments that are present.
2631 const PointerType *PFTy = 0;
2632 const FunctionType *Ty = 0;
2633 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2634 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2635 // Pull out the types of all of the arguments...
2636 std::vector<const Type*> ParamTypes;
2637 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2638 ParamTypes.push_back(ArgList[i].V->getType());
2640 if (!FunctionType::isValidReturnType(RetType))
2641 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2643 Ty = FunctionType::get(RetType, ParamTypes, false);
2644 PFTy = PointerType::getUnqual(Ty);
2647 // Look up the callee.
2649 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2651 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2652 // function attributes.
2653 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2654 if (FnAttrs & ObsoleteFuncAttrs) {
2655 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2656 FnAttrs &= ~ObsoleteFuncAttrs;
2659 // Set up the Attributes for the function.
2660 SmallVector<AttributeWithIndex, 8> Attrs;
2661 if (RetAttrs != Attribute::None)
2662 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2664 SmallVector<Value*, 8> Args;
2666 // Loop through FunctionType's arguments and ensure they are specified
2667 // correctly. Also, gather any parameter attributes.
2668 FunctionType::param_iterator I = Ty->param_begin();
2669 FunctionType::param_iterator E = Ty->param_end();
2670 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2671 const Type *ExpectedTy = 0;
2674 } else if (!Ty->isVarArg()) {
2675 return Error(ArgList[i].Loc, "too many arguments specified");
2678 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2679 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2680 ExpectedTy->getDescription() + "'");
2681 Args.push_back(ArgList[i].V);
2682 if (ArgList[i].Attrs != Attribute::None)
2683 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2687 return Error(CallLoc, "not enough parameters specified for call");
2689 if (FnAttrs != Attribute::None)
2690 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2692 // Finish off the Attributes and check them
2693 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2695 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2696 cast<BasicBlock>(UnwindBB),
2697 Args.begin(), Args.end());
2698 II->setCallingConv(CC);
2699 II->setAttributes(PAL);
2706 //===----------------------------------------------------------------------===//
2707 // Binary Operators.
2708 //===----------------------------------------------------------------------===//
2711 /// ::= ArithmeticOps TypeAndValue ',' Value
2713 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2714 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2715 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2716 unsigned Opc, unsigned OperandType) {
2717 LocTy Loc; Value *LHS, *RHS;
2718 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2719 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2720 ParseValue(LHS->getType(), RHS, PFS))
2724 switch (OperandType) {
2725 default: assert(0 && "Unknown operand type!");
2726 case 0: // int or FP.
2727 Valid = LHS->getType()->isIntOrIntVector() ||
2728 LHS->getType()->isFPOrFPVector();
2730 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2731 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2735 return Error(Loc, "invalid operand type for instruction");
2737 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2742 /// ::= ArithmeticOps TypeAndValue ',' Value {
2743 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2745 LocTy Loc; Value *LHS, *RHS;
2746 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2747 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2748 ParseValue(LHS->getType(), RHS, PFS))
2751 if (!LHS->getType()->isIntOrIntVector())
2752 return Error(Loc,"instruction requires integer or integer vector operands");
2754 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2760 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2761 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2762 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2763 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2764 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2766 // Parse the integer/fp comparison predicate.
2770 if (ParseCmpPredicate(Pred, Opc) ||
2771 ParseTypeAndValue(LHS, Loc, PFS) ||
2772 ParseToken(lltok::comma, "expected ',' after compare value") ||
2773 ParseValue(LHS->getType(), RHS, PFS))
2776 if (Opc == Instruction::FCmp) {
2777 if (!LHS->getType()->isFPOrFPVector())
2778 return Error(Loc, "fcmp requires floating point operands");
2779 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2780 } else if (Opc == Instruction::ICmp) {
2781 if (!LHS->getType()->isIntOrIntVector() &&
2782 !isa<PointerType>(LHS->getType()))
2783 return Error(Loc, "icmp requires integer operands");
2784 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2785 } else if (Opc == Instruction::VFCmp) {
2786 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2787 return Error(Loc, "vfcmp requires vector floating point operands");
2788 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2789 } else if (Opc == Instruction::VICmp) {
2790 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2791 return Error(Loc, "vicmp requires vector floating point operands");
2792 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2797 //===----------------------------------------------------------------------===//
2798 // Other Instructions.
2799 //===----------------------------------------------------------------------===//
2803 /// ::= CastOpc TypeAndValue 'to' Type
2804 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2806 LocTy Loc; Value *Op;
2807 PATypeHolder DestTy(Type::VoidTy);
2808 if (ParseTypeAndValue(Op, Loc, PFS) ||
2809 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2813 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2814 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
2815 return Error(Loc, "invalid cast opcode for cast from '" +
2816 Op->getType()->getDescription() + "' to '" +
2817 DestTy->getDescription() + "'");
2819 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2824 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2825 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2827 Value *Op0, *Op1, *Op2;
2828 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2829 ParseToken(lltok::comma, "expected ',' after select condition") ||
2830 ParseTypeAndValue(Op1, PFS) ||
2831 ParseToken(lltok::comma, "expected ',' after select value") ||
2832 ParseTypeAndValue(Op2, PFS))
2835 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2836 return Error(Loc, Reason);
2838 Inst = SelectInst::Create(Op0, Op1, Op2);
2843 /// ::= 'va_arg' TypeAndValue ',' Type
2844 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2846 PATypeHolder EltTy(Type::VoidTy);
2848 if (ParseTypeAndValue(Op, PFS) ||
2849 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2850 ParseType(EltTy, TypeLoc))
2853 if (!EltTy->isFirstClassType())
2854 return Error(TypeLoc, "va_arg requires operand with first class type");
2856 Inst = new VAArgInst(Op, EltTy);
2860 /// ParseExtractElement
2861 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2862 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2865 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2866 ParseToken(lltok::comma, "expected ',' after extract value") ||
2867 ParseTypeAndValue(Op1, PFS))
2870 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2871 return Error(Loc, "invalid extractelement operands");
2873 Inst = new ExtractElementInst(Op0, Op1);
2877 /// ParseInsertElement
2878 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2879 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2881 Value *Op0, *Op1, *Op2;
2882 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2883 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2884 ParseTypeAndValue(Op1, PFS) ||
2885 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2886 ParseTypeAndValue(Op2, PFS))
2889 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2890 return Error(Loc, "invalid extractelement operands");
2892 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2896 /// ParseShuffleVector
2897 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2898 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2900 Value *Op0, *Op1, *Op2;
2901 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2902 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2903 ParseTypeAndValue(Op1, PFS) ||
2904 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2905 ParseTypeAndValue(Op2, PFS))
2908 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2909 return Error(Loc, "invalid extractelement operands");
2911 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2916 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2917 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2918 PATypeHolder Ty(Type::VoidTy);
2920 LocTy TypeLoc = Lex.getLoc();
2922 if (ParseType(Ty) ||
2923 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2924 ParseValue(Ty, Op0, PFS) ||
2925 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2926 ParseValue(Type::LabelTy, Op1, PFS) ||
2927 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2930 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2932 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2934 if (!EatIfPresent(lltok::comma))
2937 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2938 ParseValue(Ty, Op0, PFS) ||
2939 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2940 ParseValue(Type::LabelTy, Op1, PFS) ||
2941 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2945 if (!Ty->isFirstClassType())
2946 return Error(TypeLoc, "phi node must have first class type");
2948 PHINode *PN = PHINode::Create(Ty);
2949 PN->reserveOperandSpace(PHIVals.size());
2950 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2951 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2957 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2958 /// ParameterList OptionalAttrs
2959 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2961 unsigned CC, RetAttrs, FnAttrs;
2962 PATypeHolder RetType(Type::VoidTy);
2965 SmallVector<ParamInfo, 16> ArgList;
2966 LocTy CallLoc = Lex.getLoc();
2968 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
2969 ParseOptionalCallingConv(CC) ||
2970 ParseOptionalAttrs(RetAttrs, 1) ||
2971 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2972 ParseValID(CalleeID) ||
2973 ParseParameterList(ArgList, PFS) ||
2974 ParseOptionalAttrs(FnAttrs, 2))
2977 // If RetType is a non-function pointer type, then this is the short syntax
2978 // for the call, which means that RetType is just the return type. Infer the
2979 // rest of the function argument types from the arguments that are present.
2980 const PointerType *PFTy = 0;
2981 const FunctionType *Ty = 0;
2982 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2983 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2984 // Pull out the types of all of the arguments...
2985 std::vector<const Type*> ParamTypes;
2986 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2987 ParamTypes.push_back(ArgList[i].V->getType());
2989 if (!FunctionType::isValidReturnType(RetType))
2990 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2992 Ty = FunctionType::get(RetType, ParamTypes, false);
2993 PFTy = PointerType::getUnqual(Ty);
2996 // Look up the callee.
2998 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3000 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3001 // function attributes.
3002 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3003 if (FnAttrs & ObsoleteFuncAttrs) {
3004 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3005 FnAttrs &= ~ObsoleteFuncAttrs;
3008 // Set up the Attributes for the function.
3009 SmallVector<AttributeWithIndex, 8> Attrs;
3010 if (RetAttrs != Attribute::None)
3011 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3013 SmallVector<Value*, 8> Args;
3015 // Loop through FunctionType's arguments and ensure they are specified
3016 // correctly. Also, gather any parameter attributes.
3017 FunctionType::param_iterator I = Ty->param_begin();
3018 FunctionType::param_iterator E = Ty->param_end();
3019 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3020 const Type *ExpectedTy = 0;
3023 } else if (!Ty->isVarArg()) {
3024 return Error(ArgList[i].Loc, "too many arguments specified");
3027 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3028 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3029 ExpectedTy->getDescription() + "'");
3030 Args.push_back(ArgList[i].V);
3031 if (ArgList[i].Attrs != Attribute::None)
3032 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3036 return Error(CallLoc, "not enough parameters specified for call");
3038 if (FnAttrs != Attribute::None)
3039 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3041 // Finish off the Attributes and check them
3042 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3044 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3045 CI->setTailCall(isTail);
3046 CI->setCallingConv(CC);
3047 CI->setAttributes(PAL);
3052 //===----------------------------------------------------------------------===//
3053 // Memory Instructions.
3054 //===----------------------------------------------------------------------===//
3057 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3058 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3059 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3061 PATypeHolder Ty(Type::VoidTy);
3064 unsigned Alignment = 0;
3065 if (ParseType(Ty)) return true;
3067 if (EatIfPresent(lltok::comma)) {
3068 if (Lex.getKind() == lltok::kw_align) {
3069 if (ParseOptionalAlignment(Alignment)) return true;
3070 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3071 ParseOptionalCommaAlignment(Alignment)) {
3076 if (Size && Size->getType() != Type::Int32Ty)
3077 return Error(SizeLoc, "element count must be i32");
3079 if (Opc == Instruction::Malloc)
3080 Inst = new MallocInst(Ty, Size, Alignment);
3082 Inst = new AllocaInst(Ty, Size, Alignment);
3087 /// ::= 'free' TypeAndValue
3088 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3089 Value *Val; LocTy Loc;
3090 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3091 if (!isa<PointerType>(Val->getType()))
3092 return Error(Loc, "operand to free must be a pointer");
3093 Inst = new FreeInst(Val);
3098 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3099 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3101 Value *Val; LocTy Loc;
3103 if (ParseTypeAndValue(Val, Loc, PFS) ||
3104 ParseOptionalCommaAlignment(Alignment))
3107 if (!isa<PointerType>(Val->getType()) ||
3108 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3109 return Error(Loc, "load operand must be a pointer to a first class type");
3111 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3116 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3117 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3119 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3121 if (ParseTypeAndValue(Val, Loc, PFS) ||
3122 ParseToken(lltok::comma, "expected ',' after store operand") ||
3123 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3124 ParseOptionalCommaAlignment(Alignment))
3127 if (!isa<PointerType>(Ptr->getType()))
3128 return Error(PtrLoc, "store operand must be a pointer");
3129 if (!Val->getType()->isFirstClassType())
3130 return Error(Loc, "store operand must be a first class value");
3131 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3132 return Error(Loc, "stored value and pointer type do not match");
3134 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3139 /// ::= 'getresult' TypeAndValue ',' uint
3140 /// FIXME: Remove support for getresult in LLVM 3.0
3141 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3142 Value *Val; LocTy ValLoc, EltLoc;
3144 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3145 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3146 ParseUInt32(Element, EltLoc))
3149 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3150 return Error(ValLoc, "getresult inst requires an aggregate operand");
3151 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3152 return Error(EltLoc, "invalid getresult index for value");
3153 Inst = ExtractValueInst::Create(Val, Element);
3157 /// ParseGetElementPtr
3158 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3159 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3160 Value *Ptr, *Val; LocTy Loc, EltLoc;
3161 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3163 if (!isa<PointerType>(Ptr->getType()))
3164 return Error(Loc, "base of getelementptr must be a pointer");
3166 SmallVector<Value*, 16> Indices;
3167 while (EatIfPresent(lltok::comma)) {
3168 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3169 if (!isa<IntegerType>(Val->getType()))
3170 return Error(EltLoc, "getelementptr index must be an integer");
3171 Indices.push_back(Val);
3174 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3175 Indices.begin(), Indices.end()))
3176 return Error(Loc, "invalid getelementptr indices");
3177 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3181 /// ParseExtractValue
3182 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3183 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3184 Value *Val; LocTy Loc;
3185 SmallVector<unsigned, 4> Indices;
3186 if (ParseTypeAndValue(Val, Loc, PFS) ||
3187 ParseIndexList(Indices))
3190 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3191 return Error(Loc, "extractvalue operand must be array or struct");
3193 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3195 return Error(Loc, "invalid indices for extractvalue");
3196 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3200 /// ParseInsertValue
3201 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3202 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3203 Value *Val0, *Val1; LocTy Loc0, Loc1;
3204 SmallVector<unsigned, 4> Indices;
3205 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3206 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3207 ParseTypeAndValue(Val1, Loc1, PFS) ||
3208 ParseIndexList(Indices))
3211 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3212 return Error(Loc0, "extractvalue operand must be array or struct");
3214 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3216 return Error(Loc0, "invalid indices for insertvalue");
3217 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());