1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/MDNode.h"
23 #include "llvm/Module.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/raw_ostream.h"
31 /// ValID - Represents a reference of a definition of some sort with no type.
32 /// There are several cases where we have to parse the value but where the
33 /// type can depend on later context. This may either be a numeric reference
34 /// or a symbolic (%var) reference. This is just a discriminated union.
37 t_LocalID, t_GlobalID, // ID in UIntVal.
38 t_LocalName, t_GlobalName, // Name in StrVal.
39 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
40 t_Null, t_Undef, t_Zero, // No value.
41 t_EmptyArray, // No value: []
42 t_Constant, // Value in ConstantVal.
43 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
48 std::string StrVal, StrVal2;
51 Constant *ConstantVal;
52 ValID() : APFloatVal(0.0) {}
56 /// Run: module ::= toplevelentity*
57 bool LLParser::Run() {
61 return ParseTopLevelEntities() ||
62 ValidateEndOfModule();
65 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
67 bool LLParser::ValidateEndOfModule() {
68 if (!ForwardRefTypes.empty())
69 return Error(ForwardRefTypes.begin()->second.second,
70 "use of undefined type named '" +
71 ForwardRefTypes.begin()->first + "'");
72 if (!ForwardRefTypeIDs.empty())
73 return Error(ForwardRefTypeIDs.begin()->second.second,
74 "use of undefined type '%" +
75 utostr(ForwardRefTypeIDs.begin()->first) + "'");
77 if (!ForwardRefVals.empty())
78 return Error(ForwardRefVals.begin()->second.second,
79 "use of undefined value '@" + ForwardRefVals.begin()->first +
82 if (!ForwardRefValIDs.empty())
83 return Error(ForwardRefValIDs.begin()->second.second,
84 "use of undefined value '@" +
85 utostr(ForwardRefValIDs.begin()->first) + "'");
87 // Look for intrinsic functions and CallInst that need to be upgraded
88 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
89 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
94 //===----------------------------------------------------------------------===//
96 //===----------------------------------------------------------------------===//
98 bool LLParser::ParseTopLevelEntities() {
100 switch (Lex.getKind()) {
101 default: return TokError("expected top-level entity");
102 case lltok::Eof: return false;
103 //case lltok::kw_define:
104 case lltok::kw_declare: if (ParseDeclare()) return true; break;
105 case lltok::kw_define: if (ParseDefine()) return true; break;
106 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
107 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
108 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
109 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
110 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
111 case lltok::LocalVar: if (ParseNamedType()) return true; break;
112 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
113 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
115 // The Global variable production with no name can have many different
116 // optional leading prefixes, the production is:
117 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
118 // OptionalAddrSpace ('constant'|'global') ...
119 case lltok::kw_private: // OptionalLinkage
120 case lltok::kw_internal: // OptionalLinkage
121 case lltok::kw_weak: // OptionalLinkage
122 case lltok::kw_weak_odr: // OptionalLinkage
123 case lltok::kw_linkonce: // OptionalLinkage
124 case lltok::kw_linkonce_odr: // OptionalLinkage
125 case lltok::kw_appending: // OptionalLinkage
126 case lltok::kw_dllexport: // OptionalLinkage
127 case lltok::kw_common: // OptionalLinkage
128 case lltok::kw_dllimport: // OptionalLinkage
129 case lltok::kw_extern_weak: // OptionalLinkage
130 case lltok::kw_external: { // OptionalLinkage
131 unsigned Linkage, Visibility;
132 if (ParseOptionalLinkage(Linkage) ||
133 ParseOptionalVisibility(Visibility) ||
134 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
138 case lltok::kw_default: // OptionalVisibility
139 case lltok::kw_hidden: // OptionalVisibility
140 case lltok::kw_protected: { // OptionalVisibility
142 if (ParseOptionalVisibility(Visibility) ||
143 ParseGlobal("", SMLoc(), 0, false, Visibility))
148 case lltok::kw_thread_local: // OptionalThreadLocal
149 case lltok::kw_addrspace: // OptionalAddrSpace
150 case lltok::kw_constant: // GlobalType
151 case lltok::kw_global: // GlobalType
152 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
160 /// ::= 'module' 'asm' STRINGCONSTANT
161 bool LLParser::ParseModuleAsm() {
162 assert(Lex.getKind() == lltok::kw_module);
166 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
167 ParseStringConstant(AsmStr)) return true;
169 const std::string &AsmSoFar = M->getModuleInlineAsm();
170 if (AsmSoFar.empty())
171 M->setModuleInlineAsm(AsmStr);
173 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
178 /// ::= 'target' 'triple' '=' STRINGCONSTANT
179 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
180 bool LLParser::ParseTargetDefinition() {
181 assert(Lex.getKind() == lltok::kw_target);
184 default: return TokError("unknown target property");
185 case lltok::kw_triple:
187 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
188 ParseStringConstant(Str))
190 M->setTargetTriple(Str);
192 case lltok::kw_datalayout:
194 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
195 ParseStringConstant(Str))
197 M->setDataLayout(Str);
203 /// ::= 'deplibs' '=' '[' ']'
204 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
205 bool LLParser::ParseDepLibs() {
206 assert(Lex.getKind() == lltok::kw_deplibs);
208 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
209 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
212 if (EatIfPresent(lltok::rsquare))
216 if (ParseStringConstant(Str)) return true;
219 while (EatIfPresent(lltok::comma)) {
220 if (ParseStringConstant(Str)) return true;
224 return ParseToken(lltok::rsquare, "expected ']' at end of list");
229 bool LLParser::ParseUnnamedType() {
230 assert(Lex.getKind() == lltok::kw_type);
231 LocTy TypeLoc = Lex.getLoc();
232 Lex.Lex(); // eat kw_type
234 PATypeHolder Ty(Type::VoidTy);
235 if (ParseType(Ty)) return true;
237 unsigned TypeID = NumberedTypes.size();
239 // See if this type was previously referenced.
240 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
241 FI = ForwardRefTypeIDs.find(TypeID);
242 if (FI != ForwardRefTypeIDs.end()) {
243 if (FI->second.first.get() == Ty)
244 return Error(TypeLoc, "self referential type is invalid");
246 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
247 Ty = FI->second.first.get();
248 ForwardRefTypeIDs.erase(FI);
251 NumberedTypes.push_back(Ty);
257 /// ::= LocalVar '=' 'type' type
258 bool LLParser::ParseNamedType() {
259 std::string Name = Lex.getStrVal();
260 LocTy NameLoc = Lex.getLoc();
261 Lex.Lex(); // eat LocalVar.
263 PATypeHolder Ty(Type::VoidTy);
265 if (ParseToken(lltok::equal, "expected '=' after name") ||
266 ParseToken(lltok::kw_type, "expected 'type' after name") ||
270 // Set the type name, checking for conflicts as we do so.
271 bool AlreadyExists = M->addTypeName(Name, Ty);
272 if (!AlreadyExists) return false;
274 // See if this type is a forward reference. We need to eagerly resolve
275 // types to allow recursive type redefinitions below.
276 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
277 FI = ForwardRefTypes.find(Name);
278 if (FI != ForwardRefTypes.end()) {
279 if (FI->second.first.get() == Ty)
280 return Error(NameLoc, "self referential type is invalid");
282 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
283 Ty = FI->second.first.get();
284 ForwardRefTypes.erase(FI);
287 // Inserting a name that is already defined, get the existing name.
288 const Type *Existing = M->getTypeByName(Name);
289 assert(Existing && "Conflict but no matching type?!");
291 // Otherwise, this is an attempt to redefine a type. That's okay if
292 // the redefinition is identical to the original.
293 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
294 if (Existing == Ty) return false;
296 // Any other kind of (non-equivalent) redefinition is an error.
297 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
298 Ty->getDescription() + "'");
303 /// ::= 'declare' FunctionHeader
304 bool LLParser::ParseDeclare() {
305 assert(Lex.getKind() == lltok::kw_declare);
309 return ParseFunctionHeader(F, false);
313 /// ::= 'define' FunctionHeader '{' ...
314 bool LLParser::ParseDefine() {
315 assert(Lex.getKind() == lltok::kw_define);
319 return ParseFunctionHeader(F, true) ||
320 ParseFunctionBody(*F);
326 bool LLParser::ParseGlobalType(bool &IsConstant) {
327 if (Lex.getKind() == lltok::kw_constant)
329 else if (Lex.getKind() == lltok::kw_global)
333 return TokError("expected 'global' or 'constant'");
339 /// ParseNamedGlobal:
340 /// GlobalVar '=' OptionalVisibility ALIAS ...
341 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
342 bool LLParser::ParseNamedGlobal() {
343 assert(Lex.getKind() == lltok::GlobalVar);
344 LocTy NameLoc = Lex.getLoc();
345 std::string Name = Lex.getStrVal();
349 unsigned Linkage, Visibility;
350 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
351 ParseOptionalLinkage(Linkage, HasLinkage) ||
352 ParseOptionalVisibility(Visibility))
355 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
356 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
357 return ParseAlias(Name, NameLoc, Visibility);
360 /// ParseStandaloneMetadata:
362 bool LLParser::ParseStandaloneMetadata() {
363 assert(Lex.getKind() == lltok::Metadata);
365 unsigned MetadataID = 0;
366 if (ParseUInt32(MetadataID))
368 if (MetadataCache.find(MetadataID) != MetadataCache.end())
369 return TokError("Metadata id is already used");
370 if (ParseToken(lltok::equal, "expected '=' here"))
375 PATypeHolder Ty(Type::VoidTy);
376 if (ParseGlobalType(IsConstant) ||
377 ParseType(Ty, TyLoc))
381 if (ParseGlobalValue(Ty, Init))
384 MetadataCache[MetadataID] = Init;
389 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
392 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
393 /// ::= 'getelementptr' '(' ... ')'
395 /// Everything through visibility has already been parsed.
397 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
398 unsigned Visibility) {
399 assert(Lex.getKind() == lltok::kw_alias);
402 LocTy LinkageLoc = Lex.getLoc();
403 if (ParseOptionalLinkage(Linkage))
406 if (Linkage != GlobalValue::ExternalLinkage &&
407 Linkage != GlobalValue::WeakAnyLinkage &&
408 Linkage != GlobalValue::WeakODRLinkage &&
409 Linkage != GlobalValue::InternalLinkage &&
410 Linkage != GlobalValue::PrivateLinkage)
411 return Error(LinkageLoc, "invalid linkage type for alias");
414 LocTy AliaseeLoc = Lex.getLoc();
415 if (Lex.getKind() != lltok::kw_bitcast &&
416 Lex.getKind() != lltok::kw_getelementptr) {
417 if (ParseGlobalTypeAndValue(Aliasee)) return true;
419 // The bitcast dest type is not present, it is implied by the dest type.
421 if (ParseValID(ID)) return true;
422 if (ID.Kind != ValID::t_Constant)
423 return Error(AliaseeLoc, "invalid aliasee");
424 Aliasee = ID.ConstantVal;
427 if (!isa<PointerType>(Aliasee->getType()))
428 return Error(AliaseeLoc, "alias must have pointer type");
430 // Okay, create the alias but do not insert it into the module yet.
431 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
432 (GlobalValue::LinkageTypes)Linkage, Name,
434 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
436 // See if this value already exists in the symbol table. If so, it is either
437 // a redefinition or a definition of a forward reference.
438 if (GlobalValue *Val =
439 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
440 // See if this was a redefinition. If so, there is no entry in
442 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
443 I = ForwardRefVals.find(Name);
444 if (I == ForwardRefVals.end())
445 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
447 // Otherwise, this was a definition of forward ref. Verify that types
449 if (Val->getType() != GA->getType())
450 return Error(NameLoc,
451 "forward reference and definition of alias have different types");
453 // If they agree, just RAUW the old value with the alias and remove the
455 Val->replaceAllUsesWith(GA);
456 Val->eraseFromParent();
457 ForwardRefVals.erase(I);
460 // Insert into the module, we know its name won't collide now.
461 M->getAliasList().push_back(GA);
462 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
468 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
469 /// OptionalAddrSpace GlobalType Type Const
470 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
471 /// OptionalAddrSpace GlobalType Type Const
473 /// Everything through visibility has been parsed already.
475 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
476 unsigned Linkage, bool HasLinkage,
477 unsigned Visibility) {
479 bool ThreadLocal, IsConstant;
482 PATypeHolder Ty(Type::VoidTy);
483 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
484 ParseOptionalAddrSpace(AddrSpace) ||
485 ParseGlobalType(IsConstant) ||
486 ParseType(Ty, TyLoc))
489 // If the linkage is specified and is external, then no initializer is
492 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
493 Linkage != GlobalValue::ExternalWeakLinkage &&
494 Linkage != GlobalValue::ExternalLinkage)) {
495 if (ParseGlobalValue(Ty, Init))
499 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
500 return Error(TyLoc, "invalid type for global variable");
502 GlobalVariable *GV = 0;
504 // See if the global was forward referenced, if so, use the global.
506 if ((GV = M->getGlobalVariable(Name, true)) &&
507 !ForwardRefVals.erase(Name))
508 return Error(NameLoc, "redefinition of global '@" + Name + "'");
510 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
511 I = ForwardRefValIDs.find(NumberedVals.size());
512 if (I != ForwardRefValIDs.end()) {
513 GV = cast<GlobalVariable>(I->second.first);
514 ForwardRefValIDs.erase(I);
519 GV = new GlobalVariable(Context, Ty, false,
520 GlobalValue::ExternalLinkage, 0, Name,
521 M, false, AddrSpace);
523 if (GV->getType()->getElementType() != Ty)
525 "forward reference and definition of global have different types");
527 // Move the forward-reference to the correct spot in the module.
528 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
532 NumberedVals.push_back(GV);
534 // Set the parsed properties on the global.
536 GV->setInitializer(Init);
537 GV->setConstant(IsConstant);
538 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
539 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
540 GV->setThreadLocal(ThreadLocal);
542 // Parse attributes on the global.
543 while (Lex.getKind() == lltok::comma) {
546 if (Lex.getKind() == lltok::kw_section) {
548 GV->setSection(Lex.getStrVal());
549 if (ParseToken(lltok::StringConstant, "expected global section string"))
551 } else if (Lex.getKind() == lltok::kw_align) {
553 if (ParseOptionalAlignment(Alignment)) return true;
554 GV->setAlignment(Alignment);
556 TokError("unknown global variable property!");
564 //===----------------------------------------------------------------------===//
565 // GlobalValue Reference/Resolution Routines.
566 //===----------------------------------------------------------------------===//
568 /// GetGlobalVal - Get a value with the specified name or ID, creating a
569 /// forward reference record if needed. This can return null if the value
570 /// exists but does not have the right type.
571 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
573 const PointerType *PTy = dyn_cast<PointerType>(Ty);
575 Error(Loc, "global variable reference must have pointer type");
579 // Look this name up in the normal function symbol table.
581 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
583 // If this is a forward reference for the value, see if we already created a
584 // forward ref record.
586 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
587 I = ForwardRefVals.find(Name);
588 if (I != ForwardRefVals.end())
589 Val = I->second.first;
592 // If we have the value in the symbol table or fwd-ref table, return it.
594 if (Val->getType() == Ty) return Val;
595 Error(Loc, "'@" + Name + "' defined with type '" +
596 Val->getType()->getDescription() + "'");
600 // Otherwise, create a new forward reference for this value and remember it.
602 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
603 // Function types can return opaque but functions can't.
604 if (isa<OpaqueType>(FT->getReturnType())) {
605 Error(Loc, "function may not return opaque type");
609 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
611 FwdVal = new GlobalVariable(Context, PTy->getElementType(), false,
612 GlobalValue::ExternalWeakLinkage, 0, Name, M);
615 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
619 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
620 const PointerType *PTy = dyn_cast<PointerType>(Ty);
622 Error(Loc, "global variable reference must have pointer type");
626 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
628 // If this is a forward reference for the value, see if we already created a
629 // forward ref record.
631 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
632 I = ForwardRefValIDs.find(ID);
633 if (I != ForwardRefValIDs.end())
634 Val = I->second.first;
637 // If we have the value in the symbol table or fwd-ref table, return it.
639 if (Val->getType() == Ty) return Val;
640 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
641 Val->getType()->getDescription() + "'");
645 // Otherwise, create a new forward reference for this value and remember it.
647 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
648 // Function types can return opaque but functions can't.
649 if (isa<OpaqueType>(FT->getReturnType())) {
650 Error(Loc, "function may not return opaque type");
653 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
655 FwdVal = new GlobalVariable(Context, PTy->getElementType(), false,
656 GlobalValue::ExternalWeakLinkage, 0, "", M);
659 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
664 //===----------------------------------------------------------------------===//
666 //===----------------------------------------------------------------------===//
668 /// ParseToken - If the current token has the specified kind, eat it and return
669 /// success. Otherwise, emit the specified error and return failure.
670 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
671 if (Lex.getKind() != T)
672 return TokError(ErrMsg);
677 /// ParseStringConstant
678 /// ::= StringConstant
679 bool LLParser::ParseStringConstant(std::string &Result) {
680 if (Lex.getKind() != lltok::StringConstant)
681 return TokError("expected string constant");
682 Result = Lex.getStrVal();
689 bool LLParser::ParseUInt32(unsigned &Val) {
690 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
691 return TokError("expected integer");
692 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
693 if (Val64 != unsigned(Val64))
694 return TokError("expected 32-bit integer (too large)");
701 /// ParseOptionalAddrSpace
703 /// := 'addrspace' '(' uint32 ')'
704 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
706 if (!EatIfPresent(lltok::kw_addrspace))
708 return ParseToken(lltok::lparen, "expected '(' in address space") ||
709 ParseUInt32(AddrSpace) ||
710 ParseToken(lltok::rparen, "expected ')' in address space");
713 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
714 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
715 /// 2: function attr.
716 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
717 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
718 Attrs = Attribute::None;
719 LocTy AttrLoc = Lex.getLoc();
722 switch (Lex.getKind()) {
725 // Treat these as signext/zeroext if they occur in the argument list after
726 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
727 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
729 // FIXME: REMOVE THIS IN LLVM 3.0
731 if (Lex.getKind() == lltok::kw_sext)
732 Attrs |= Attribute::SExt;
734 Attrs |= Attribute::ZExt;
738 default: // End of attributes.
739 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
740 return Error(AttrLoc, "invalid use of function-only attribute");
742 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
743 return Error(AttrLoc, "invalid use of parameter-only attribute");
746 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
747 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
748 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
749 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
750 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
751 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
752 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
753 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
755 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
756 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
757 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
758 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
759 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
760 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
761 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
762 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
763 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
764 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
765 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
767 case lltok::kw_align: {
769 if (ParseOptionalAlignment(Alignment))
771 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
779 /// ParseOptionalLinkage
786 /// ::= 'linkonce_odr'
791 /// ::= 'extern_weak'
793 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
795 switch (Lex.getKind()) {
796 default: Res = GlobalValue::ExternalLinkage; return false;
797 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
798 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
799 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
800 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
801 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
802 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
803 case lltok::kw_available_externally:
804 Res = GlobalValue::AvailableExternallyLinkage;
806 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
807 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
808 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
809 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
810 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
811 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
818 /// ParseOptionalVisibility
824 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
825 switch (Lex.getKind()) {
826 default: Res = GlobalValue::DefaultVisibility; return false;
827 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
828 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
829 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
835 /// ParseOptionalCallingConv
840 /// ::= 'x86_stdcallcc'
841 /// ::= 'x86_fastcallcc'
843 /// ::= 'arm_aapcscc'
844 /// ::= 'arm_aapcs_vfpcc'
847 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
848 switch (Lex.getKind()) {
849 default: CC = CallingConv::C; return false;
850 case lltok::kw_ccc: CC = CallingConv::C; break;
851 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
852 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
853 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
854 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
855 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
856 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
857 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
858 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
864 /// ParseOptionalAlignment
867 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
869 if (!EatIfPresent(lltok::kw_align))
871 LocTy AlignLoc = Lex.getLoc();
872 if (ParseUInt32(Alignment)) return true;
873 if (!isPowerOf2_32(Alignment))
874 return Error(AlignLoc, "alignment is not a power of two");
878 /// ParseOptionalCommaAlignment
880 /// ::= ',' 'align' 4
881 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
883 if (!EatIfPresent(lltok::comma))
885 return ParseToken(lltok::kw_align, "expected 'align'") ||
886 ParseUInt32(Alignment);
890 /// ::= (',' uint32)+
891 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
892 if (Lex.getKind() != lltok::comma)
893 return TokError("expected ',' as start of index list");
895 while (EatIfPresent(lltok::comma)) {
897 if (ParseUInt32(Idx)) return true;
898 Indices.push_back(Idx);
904 //===----------------------------------------------------------------------===//
906 //===----------------------------------------------------------------------===//
908 /// ParseType - Parse and resolve a full type.
909 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
910 LocTy TypeLoc = Lex.getLoc();
911 if (ParseTypeRec(Result)) return true;
913 // Verify no unresolved uprefs.
915 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
917 if (!AllowVoid && Result.get() == Type::VoidTy)
918 return Error(TypeLoc, "void type only allowed for function results");
923 /// HandleUpRefs - Every time we finish a new layer of types, this function is
924 /// called. It loops through the UpRefs vector, which is a list of the
925 /// currently active types. For each type, if the up-reference is contained in
926 /// the newly completed type, we decrement the level count. When the level
927 /// count reaches zero, the up-referenced type is the type that is passed in:
928 /// thus we can complete the cycle.
930 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
931 // If Ty isn't abstract, or if there are no up-references in it, then there is
932 // nothing to resolve here.
933 if (!ty->isAbstract() || UpRefs.empty()) return ty;
937 errs() << "Type '" << Ty->getDescription()
938 << "' newly formed. Resolving upreferences.\n"
939 << UpRefs.size() << " upreferences active!\n";
942 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
943 // to zero), we resolve them all together before we resolve them to Ty. At
944 // the end of the loop, if there is anything to resolve to Ty, it will be in
946 OpaqueType *TypeToResolve = 0;
948 for (unsigned i = 0; i != UpRefs.size(); ++i) {
949 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
951 std::find(Ty->subtype_begin(), Ty->subtype_end(),
952 UpRefs[i].LastContainedTy) != Ty->subtype_end();
955 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
956 << UpRefs[i].LastContainedTy->getDescription() << ") = "
957 << (ContainsType ? "true" : "false")
958 << " level=" << UpRefs[i].NestingLevel << "\n";
963 // Decrement level of upreference
964 unsigned Level = --UpRefs[i].NestingLevel;
965 UpRefs[i].LastContainedTy = Ty;
967 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
972 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
975 TypeToResolve = UpRefs[i].UpRefTy;
977 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
978 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
979 --i; // Do not skip the next element.
983 TypeToResolve->refineAbstractTypeTo(Ty);
989 /// ParseTypeRec - The recursive function used to process the internal
990 /// implementation details of types.
991 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
992 switch (Lex.getKind()) {
994 return TokError("expected type");
996 // TypeRec ::= 'float' | 'void' (etc)
997 Result = Lex.getTyVal();
1000 case lltok::kw_opaque:
1001 // TypeRec ::= 'opaque'
1002 Result = Context.getOpaqueType();
1006 // TypeRec ::= '{' ... '}'
1007 if (ParseStructType(Result, false))
1010 case lltok::lsquare:
1011 // TypeRec ::= '[' ... ']'
1012 Lex.Lex(); // eat the lsquare.
1013 if (ParseArrayVectorType(Result, false))
1016 case lltok::less: // Either vector or packed struct.
1017 // TypeRec ::= '<' ... '>'
1019 if (Lex.getKind() == lltok::lbrace) {
1020 if (ParseStructType(Result, true) ||
1021 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1023 } else if (ParseArrayVectorType(Result, true))
1026 case lltok::LocalVar:
1027 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1029 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1032 Result = Context.getOpaqueType();
1033 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1034 std::make_pair(Result,
1036 M->addTypeName(Lex.getStrVal(), Result.get());
1041 case lltok::LocalVarID:
1043 if (Lex.getUIntVal() < NumberedTypes.size())
1044 Result = NumberedTypes[Lex.getUIntVal()];
1046 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1047 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1048 if (I != ForwardRefTypeIDs.end())
1049 Result = I->second.first;
1051 Result = Context.getOpaqueType();
1052 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1053 std::make_pair(Result,
1059 case lltok::backslash: {
1060 // TypeRec ::= '\' 4
1063 if (ParseUInt32(Val)) return true;
1064 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1065 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1071 // Parse the type suffixes.
1073 switch (Lex.getKind()) {
1075 default: return false;
1077 // TypeRec ::= TypeRec '*'
1079 if (Result.get() == Type::LabelTy)
1080 return TokError("basic block pointers are invalid");
1081 if (Result.get() == Type::VoidTy)
1082 return TokError("pointers to void are invalid; use i8* instead");
1083 if (!PointerType::isValidElementType(Result.get()))
1084 return TokError("pointer to this type is invalid");
1085 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1089 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1090 case lltok::kw_addrspace: {
1091 if (Result.get() == Type::LabelTy)
1092 return TokError("basic block pointers are invalid");
1093 if (Result.get() == Type::VoidTy)
1094 return TokError("pointers to void are invalid; use i8* instead");
1095 if (!PointerType::isValidElementType(Result.get()))
1096 return TokError("pointer to this type is invalid");
1098 if (ParseOptionalAddrSpace(AddrSpace) ||
1099 ParseToken(lltok::star, "expected '*' in address space"))
1102 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1106 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1108 if (ParseFunctionType(Result))
1115 /// ParseParameterList
1117 /// ::= '(' Arg (',' Arg)* ')'
1119 /// ::= Type OptionalAttributes Value OptionalAttributes
1120 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1121 PerFunctionState &PFS) {
1122 if (ParseToken(lltok::lparen, "expected '(' in call"))
1125 while (Lex.getKind() != lltok::rparen) {
1126 // If this isn't the first argument, we need a comma.
1127 if (!ArgList.empty() &&
1128 ParseToken(lltok::comma, "expected ',' in argument list"))
1131 // Parse the argument.
1133 PATypeHolder ArgTy(Type::VoidTy);
1134 unsigned ArgAttrs1, ArgAttrs2;
1136 if (ParseType(ArgTy, ArgLoc) ||
1137 ParseOptionalAttrs(ArgAttrs1, 0) ||
1138 ParseValue(ArgTy, V, PFS) ||
1139 // FIXME: Should not allow attributes after the argument, remove this in
1141 ParseOptionalAttrs(ArgAttrs2, 3))
1143 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1146 Lex.Lex(); // Lex the ')'.
1152 /// ParseArgumentList - Parse the argument list for a function type or function
1153 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1154 /// ::= '(' ArgTypeListI ')'
1158 /// ::= ArgTypeList ',' '...'
1159 /// ::= ArgType (',' ArgType)*
1161 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1162 bool &isVarArg, bool inType) {
1164 assert(Lex.getKind() == lltok::lparen);
1165 Lex.Lex(); // eat the (.
1167 if (Lex.getKind() == lltok::rparen) {
1169 } else if (Lex.getKind() == lltok::dotdotdot) {
1173 LocTy TypeLoc = Lex.getLoc();
1174 PATypeHolder ArgTy(Type::VoidTy);
1178 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1179 // types (such as a function returning a pointer to itself). If parsing a
1180 // function prototype, we require fully resolved types.
1181 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1182 ParseOptionalAttrs(Attrs, 0)) return true;
1184 if (ArgTy == Type::VoidTy)
1185 return Error(TypeLoc, "argument can not have void type");
1187 if (Lex.getKind() == lltok::LocalVar ||
1188 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1189 Name = Lex.getStrVal();
1193 if (!FunctionType::isValidArgumentType(ArgTy))
1194 return Error(TypeLoc, "invalid type for function argument");
1196 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1198 while (EatIfPresent(lltok::comma)) {
1199 // Handle ... at end of arg list.
1200 if (EatIfPresent(lltok::dotdotdot)) {
1205 // Otherwise must be an argument type.
1206 TypeLoc = Lex.getLoc();
1207 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1208 ParseOptionalAttrs(Attrs, 0)) return true;
1210 if (ArgTy == Type::VoidTy)
1211 return Error(TypeLoc, "argument can not have void type");
1213 if (Lex.getKind() == lltok::LocalVar ||
1214 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1215 Name = Lex.getStrVal();
1221 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1222 return Error(TypeLoc, "invalid type for function argument");
1224 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1228 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1231 /// ParseFunctionType
1232 /// ::= Type ArgumentList OptionalAttrs
1233 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1234 assert(Lex.getKind() == lltok::lparen);
1236 if (!FunctionType::isValidReturnType(Result))
1237 return TokError("invalid function return type");
1239 std::vector<ArgInfo> ArgList;
1242 if (ParseArgumentList(ArgList, isVarArg, true) ||
1243 // FIXME: Allow, but ignore attributes on function types!
1244 // FIXME: Remove in LLVM 3.0
1245 ParseOptionalAttrs(Attrs, 2))
1248 // Reject names on the arguments lists.
1249 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1250 if (!ArgList[i].Name.empty())
1251 return Error(ArgList[i].Loc, "argument name invalid in function type");
1252 if (!ArgList[i].Attrs != 0) {
1253 // Allow but ignore attributes on function types; this permits
1255 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1259 std::vector<const Type*> ArgListTy;
1260 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1261 ArgListTy.push_back(ArgList[i].Type);
1263 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1264 ArgListTy, isVarArg));
1268 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1271 /// ::= '{' TypeRec (',' TypeRec)* '}'
1272 /// ::= '<' '{' '}' '>'
1273 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1274 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1275 assert(Lex.getKind() == lltok::lbrace);
1276 Lex.Lex(); // Consume the '{'
1278 if (EatIfPresent(lltok::rbrace)) {
1279 Result = Context.getStructType(Packed);
1283 std::vector<PATypeHolder> ParamsList;
1284 LocTy EltTyLoc = Lex.getLoc();
1285 if (ParseTypeRec(Result)) return true;
1286 ParamsList.push_back(Result);
1288 if (Result == Type::VoidTy)
1289 return Error(EltTyLoc, "struct element can not have void type");
1290 if (!StructType::isValidElementType(Result))
1291 return Error(EltTyLoc, "invalid element type for struct");
1293 while (EatIfPresent(lltok::comma)) {
1294 EltTyLoc = Lex.getLoc();
1295 if (ParseTypeRec(Result)) return true;
1297 if (Result == Type::VoidTy)
1298 return Error(EltTyLoc, "struct element can not have void type");
1299 if (!StructType::isValidElementType(Result))
1300 return Error(EltTyLoc, "invalid element type for struct");
1302 ParamsList.push_back(Result);
1305 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1308 std::vector<const Type*> ParamsListTy;
1309 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1310 ParamsListTy.push_back(ParamsList[i].get());
1311 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1315 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1316 /// token has already been consumed.
1318 /// ::= '[' APSINTVAL 'x' Types ']'
1319 /// ::= '<' APSINTVAL 'x' Types '>'
1320 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1321 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1322 Lex.getAPSIntVal().getBitWidth() > 64)
1323 return TokError("expected number in address space");
1325 LocTy SizeLoc = Lex.getLoc();
1326 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1329 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1332 LocTy TypeLoc = Lex.getLoc();
1333 PATypeHolder EltTy(Type::VoidTy);
1334 if (ParseTypeRec(EltTy)) return true;
1336 if (EltTy == Type::VoidTy)
1337 return Error(TypeLoc, "array and vector element type cannot be void");
1339 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1340 "expected end of sequential type"))
1345 return Error(SizeLoc, "zero element vector is illegal");
1346 if ((unsigned)Size != Size)
1347 return Error(SizeLoc, "size too large for vector");
1348 if (!VectorType::isValidElementType(EltTy))
1349 return Error(TypeLoc, "vector element type must be fp or integer");
1350 Result = Context.getVectorType(EltTy, unsigned(Size));
1352 if (!ArrayType::isValidElementType(EltTy))
1353 return Error(TypeLoc, "invalid array element type");
1354 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1359 //===----------------------------------------------------------------------===//
1360 // Function Semantic Analysis.
1361 //===----------------------------------------------------------------------===//
1363 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1366 // Insert unnamed arguments into the NumberedVals list.
1367 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1370 NumberedVals.push_back(AI);
1373 LLParser::PerFunctionState::~PerFunctionState() {
1374 // If there were any forward referenced non-basicblock values, delete them.
1375 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1376 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1377 if (!isa<BasicBlock>(I->second.first)) {
1378 I->second.first->replaceAllUsesWith(
1379 P.getContext().getUndef(I->second.first->getType()));
1380 delete I->second.first;
1381 I->second.first = 0;
1384 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1385 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1386 if (!isa<BasicBlock>(I->second.first)) {
1387 I->second.first->replaceAllUsesWith(
1388 P.getContext().getUndef(I->second.first->getType()));
1389 delete I->second.first;
1390 I->second.first = 0;
1394 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1395 if (!ForwardRefVals.empty())
1396 return P.Error(ForwardRefVals.begin()->second.second,
1397 "use of undefined value '%" + ForwardRefVals.begin()->first +
1399 if (!ForwardRefValIDs.empty())
1400 return P.Error(ForwardRefValIDs.begin()->second.second,
1401 "use of undefined value '%" +
1402 utostr(ForwardRefValIDs.begin()->first) + "'");
1407 /// GetVal - Get a value with the specified name or ID, creating a
1408 /// forward reference record if needed. This can return null if the value
1409 /// exists but does not have the right type.
1410 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1411 const Type *Ty, LocTy Loc) {
1412 // Look this name up in the normal function symbol table.
1413 Value *Val = F.getValueSymbolTable().lookup(Name);
1415 // If this is a forward reference for the value, see if we already created a
1416 // forward ref record.
1418 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1419 I = ForwardRefVals.find(Name);
1420 if (I != ForwardRefVals.end())
1421 Val = I->second.first;
1424 // If we have the value in the symbol table or fwd-ref table, return it.
1426 if (Val->getType() == Ty) return Val;
1427 if (Ty == Type::LabelTy)
1428 P.Error(Loc, "'%" + Name + "' is not a basic block");
1430 P.Error(Loc, "'%" + Name + "' defined with type '" +
1431 Val->getType()->getDescription() + "'");
1435 // Don't make placeholders with invalid type.
1436 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1437 P.Error(Loc, "invalid use of a non-first-class type");
1441 // Otherwise, create a new forward reference for this value and remember it.
1443 if (Ty == Type::LabelTy)
1444 FwdVal = BasicBlock::Create(Name, &F);
1446 FwdVal = new Argument(Ty, Name);
1448 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1452 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1454 // Look this name up in the normal function symbol table.
1455 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1457 // If this is a forward reference for the value, see if we already created a
1458 // forward ref record.
1460 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1461 I = ForwardRefValIDs.find(ID);
1462 if (I != ForwardRefValIDs.end())
1463 Val = I->second.first;
1466 // If we have the value in the symbol table or fwd-ref table, return it.
1468 if (Val->getType() == Ty) return Val;
1469 if (Ty == Type::LabelTy)
1470 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1472 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1473 Val->getType()->getDescription() + "'");
1477 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1478 P.Error(Loc, "invalid use of a non-first-class type");
1482 // Otherwise, create a new forward reference for this value and remember it.
1484 if (Ty == Type::LabelTy)
1485 FwdVal = BasicBlock::Create("", &F);
1487 FwdVal = new Argument(Ty);
1489 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1493 /// SetInstName - After an instruction is parsed and inserted into its
1494 /// basic block, this installs its name.
1495 bool LLParser::PerFunctionState::SetInstName(int NameID,
1496 const std::string &NameStr,
1497 LocTy NameLoc, Instruction *Inst) {
1498 // If this instruction has void type, it cannot have a name or ID specified.
1499 if (Inst->getType() == Type::VoidTy) {
1500 if (NameID != -1 || !NameStr.empty())
1501 return P.Error(NameLoc, "instructions returning void cannot have a name");
1505 // If this was a numbered instruction, verify that the instruction is the
1506 // expected value and resolve any forward references.
1507 if (NameStr.empty()) {
1508 // If neither a name nor an ID was specified, just use the next ID.
1510 NameID = NumberedVals.size();
1512 if (unsigned(NameID) != NumberedVals.size())
1513 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1514 utostr(NumberedVals.size()) + "'");
1516 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1517 ForwardRefValIDs.find(NameID);
1518 if (FI != ForwardRefValIDs.end()) {
1519 if (FI->second.first->getType() != Inst->getType())
1520 return P.Error(NameLoc, "instruction forward referenced with type '" +
1521 FI->second.first->getType()->getDescription() + "'");
1522 FI->second.first->replaceAllUsesWith(Inst);
1523 ForwardRefValIDs.erase(FI);
1526 NumberedVals.push_back(Inst);
1530 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1531 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1532 FI = ForwardRefVals.find(NameStr);
1533 if (FI != ForwardRefVals.end()) {
1534 if (FI->second.first->getType() != Inst->getType())
1535 return P.Error(NameLoc, "instruction forward referenced with type '" +
1536 FI->second.first->getType()->getDescription() + "'");
1537 FI->second.first->replaceAllUsesWith(Inst);
1538 ForwardRefVals.erase(FI);
1541 // Set the name on the instruction.
1542 Inst->setName(NameStr);
1544 if (Inst->getNameStr() != NameStr)
1545 return P.Error(NameLoc, "multiple definition of local value named '" +
1550 /// GetBB - Get a basic block with the specified name or ID, creating a
1551 /// forward reference record if needed.
1552 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1554 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1557 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1558 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1561 /// DefineBB - Define the specified basic block, which is either named or
1562 /// unnamed. If there is an error, this returns null otherwise it returns
1563 /// the block being defined.
1564 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1568 BB = GetBB(NumberedVals.size(), Loc);
1570 BB = GetBB(Name, Loc);
1571 if (BB == 0) return 0; // Already diagnosed error.
1573 // Move the block to the end of the function. Forward ref'd blocks are
1574 // inserted wherever they happen to be referenced.
1575 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1577 // Remove the block from forward ref sets.
1579 ForwardRefValIDs.erase(NumberedVals.size());
1580 NumberedVals.push_back(BB);
1582 // BB forward references are already in the function symbol table.
1583 ForwardRefVals.erase(Name);
1589 //===----------------------------------------------------------------------===//
1591 //===----------------------------------------------------------------------===//
1593 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1594 /// type implied. For example, if we parse "4" we don't know what integer type
1595 /// it has. The value will later be combined with its type and checked for
1597 bool LLParser::ParseValID(ValID &ID) {
1598 ID.Loc = Lex.getLoc();
1599 switch (Lex.getKind()) {
1600 default: return TokError("expected value token");
1601 case lltok::GlobalID: // @42
1602 ID.UIntVal = Lex.getUIntVal();
1603 ID.Kind = ValID::t_GlobalID;
1605 case lltok::GlobalVar: // @foo
1606 ID.StrVal = Lex.getStrVal();
1607 ID.Kind = ValID::t_GlobalName;
1609 case lltok::LocalVarID: // %42
1610 ID.UIntVal = Lex.getUIntVal();
1611 ID.Kind = ValID::t_LocalID;
1613 case lltok::LocalVar: // %foo
1614 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1615 ID.StrVal = Lex.getStrVal();
1616 ID.Kind = ValID::t_LocalName;
1618 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1619 ID.Kind = ValID::t_Constant;
1621 if (Lex.getKind() == lltok::lbrace) {
1622 SmallVector<Value*, 16> Elts;
1623 if (ParseMDNodeVector(Elts) ||
1624 ParseToken(lltok::rbrace, "expected end of metadata node"))
1627 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
1631 // Standalone metadata reference
1632 // !{ ..., !42, ... }
1634 if (!ParseUInt32(MID)) {
1635 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
1636 if (I == MetadataCache.end())
1637 return TokError("Unknown metadata reference");
1638 ID.ConstantVal = I->second;
1643 // ::= '!' STRINGCONSTANT
1645 if (ParseStringConstant(Str)) return true;
1647 ID.ConstantVal = Context.getMDString(Str.data(), Str.data() + Str.size());
1651 ID.APSIntVal = Lex.getAPSIntVal();
1652 ID.Kind = ValID::t_APSInt;
1654 case lltok::APFloat:
1655 ID.APFloatVal = Lex.getAPFloatVal();
1656 ID.Kind = ValID::t_APFloat;
1658 case lltok::kw_true:
1659 ID.ConstantVal = Context.getConstantIntTrue();
1660 ID.Kind = ValID::t_Constant;
1662 case lltok::kw_false:
1663 ID.ConstantVal = Context.getConstantIntFalse();
1664 ID.Kind = ValID::t_Constant;
1666 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1667 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1668 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1670 case lltok::lbrace: {
1671 // ValID ::= '{' ConstVector '}'
1673 SmallVector<Constant*, 16> Elts;
1674 if (ParseGlobalValueVector(Elts) ||
1675 ParseToken(lltok::rbrace, "expected end of struct constant"))
1678 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
1679 ID.Kind = ValID::t_Constant;
1683 // ValID ::= '<' ConstVector '>' --> Vector.
1684 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1686 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1688 SmallVector<Constant*, 16> Elts;
1689 LocTy FirstEltLoc = Lex.getLoc();
1690 if (ParseGlobalValueVector(Elts) ||
1692 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1693 ParseToken(lltok::greater, "expected end of constant"))
1696 if (isPackedStruct) {
1698 Context.getConstantStruct(Elts.data(), Elts.size(), true);
1699 ID.Kind = ValID::t_Constant;
1704 return Error(ID.Loc, "constant vector must not be empty");
1706 if (!Elts[0]->getType()->isInteger() &&
1707 !Elts[0]->getType()->isFloatingPoint())
1708 return Error(FirstEltLoc,
1709 "vector elements must have integer or floating point type");
1711 // Verify that all the vector elements have the same type.
1712 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1713 if (Elts[i]->getType() != Elts[0]->getType())
1714 return Error(FirstEltLoc,
1715 "vector element #" + utostr(i) +
1716 " is not of type '" + Elts[0]->getType()->getDescription());
1718 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
1719 ID.Kind = ValID::t_Constant;
1722 case lltok::lsquare: { // Array Constant
1724 SmallVector<Constant*, 16> Elts;
1725 LocTy FirstEltLoc = Lex.getLoc();
1726 if (ParseGlobalValueVector(Elts) ||
1727 ParseToken(lltok::rsquare, "expected end of array constant"))
1730 // Handle empty element.
1732 // Use undef instead of an array because it's inconvenient to determine
1733 // the element type at this point, there being no elements to examine.
1734 ID.Kind = ValID::t_EmptyArray;
1738 if (!Elts[0]->getType()->isFirstClassType())
1739 return Error(FirstEltLoc, "invalid array element type: " +
1740 Elts[0]->getType()->getDescription());
1742 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1744 // Verify all elements are correct type!
1745 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1746 if (Elts[i]->getType() != Elts[0]->getType())
1747 return Error(FirstEltLoc,
1748 "array element #" + utostr(i) +
1749 " is not of type '" +Elts[0]->getType()->getDescription());
1752 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
1753 ID.Kind = ValID::t_Constant;
1756 case lltok::kw_c: // c "foo"
1758 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
1759 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1760 ID.Kind = ValID::t_Constant;
1763 case lltok::kw_asm: {
1764 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1767 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1768 ParseStringConstant(ID.StrVal) ||
1769 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1770 ParseToken(lltok::StringConstant, "expected constraint string"))
1772 ID.StrVal2 = Lex.getStrVal();
1773 ID.UIntVal = HasSideEffect;
1774 ID.Kind = ValID::t_InlineAsm;
1778 case lltok::kw_trunc:
1779 case lltok::kw_zext:
1780 case lltok::kw_sext:
1781 case lltok::kw_fptrunc:
1782 case lltok::kw_fpext:
1783 case lltok::kw_bitcast:
1784 case lltok::kw_uitofp:
1785 case lltok::kw_sitofp:
1786 case lltok::kw_fptoui:
1787 case lltok::kw_fptosi:
1788 case lltok::kw_inttoptr:
1789 case lltok::kw_ptrtoint: {
1790 unsigned Opc = Lex.getUIntVal();
1791 PATypeHolder DestTy(Type::VoidTy);
1794 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1795 ParseGlobalTypeAndValue(SrcVal) ||
1796 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1797 ParseType(DestTy) ||
1798 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1800 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1801 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1802 SrcVal->getType()->getDescription() + "' to '" +
1803 DestTy->getDescription() + "'");
1804 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1806 ID.Kind = ValID::t_Constant;
1809 case lltok::kw_extractvalue: {
1812 SmallVector<unsigned, 4> Indices;
1813 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1814 ParseGlobalTypeAndValue(Val) ||
1815 ParseIndexList(Indices) ||
1816 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1818 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1819 return Error(ID.Loc, "extractvalue operand must be array or struct");
1820 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1822 return Error(ID.Loc, "invalid indices for extractvalue");
1824 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
1825 ID.Kind = ValID::t_Constant;
1828 case lltok::kw_insertvalue: {
1830 Constant *Val0, *Val1;
1831 SmallVector<unsigned, 4> Indices;
1832 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1833 ParseGlobalTypeAndValue(Val0) ||
1834 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1835 ParseGlobalTypeAndValue(Val1) ||
1836 ParseIndexList(Indices) ||
1837 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1839 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1840 return Error(ID.Loc, "extractvalue operand must be array or struct");
1841 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1843 return Error(ID.Loc, "invalid indices for insertvalue");
1844 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1845 Indices.data(), Indices.size());
1846 ID.Kind = ValID::t_Constant;
1849 case lltok::kw_icmp:
1850 case lltok::kw_fcmp:
1851 case lltok::kw_vicmp:
1852 case lltok::kw_vfcmp: {
1853 unsigned PredVal, Opc = Lex.getUIntVal();
1854 Constant *Val0, *Val1;
1856 if (ParseCmpPredicate(PredVal, Opc) ||
1857 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1858 ParseGlobalTypeAndValue(Val0) ||
1859 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1860 ParseGlobalTypeAndValue(Val1) ||
1861 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1864 if (Val0->getType() != Val1->getType())
1865 return Error(ID.Loc, "compare operands must have the same type");
1867 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1869 if (Opc == Instruction::FCmp) {
1870 if (!Val0->getType()->isFPOrFPVector())
1871 return Error(ID.Loc, "fcmp requires floating point operands");
1872 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
1873 } else if (Opc == Instruction::ICmp) {
1874 if (!Val0->getType()->isIntOrIntVector() &&
1875 !isa<PointerType>(Val0->getType()))
1876 return Error(ID.Loc, "icmp requires pointer or integer operands");
1877 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
1878 } else if (Opc == Instruction::VFCmp) {
1879 // FIXME: REMOVE VFCMP Support
1880 if (!Val0->getType()->isFPOrFPVector() ||
1881 !isa<VectorType>(Val0->getType()))
1882 return Error(ID.Loc, "vfcmp requires vector floating point operands");
1883 ID.ConstantVal = Context.getConstantExprVFCmp(Pred, Val0, Val1);
1884 } else if (Opc == Instruction::VICmp) {
1885 // FIXME: REMOVE VICMP Support
1886 if (!Val0->getType()->isIntOrIntVector() ||
1887 !isa<VectorType>(Val0->getType()))
1888 return Error(ID.Loc, "vicmp requires vector floating point operands");
1889 ID.ConstantVal = Context.getConstantExprVICmp(Pred, Val0, Val1);
1891 ID.Kind = ValID::t_Constant;
1895 // Binary Operators.
1897 case lltok::kw_fadd:
1899 case lltok::kw_fsub:
1901 case lltok::kw_fmul:
1902 case lltok::kw_udiv:
1903 case lltok::kw_sdiv:
1904 case lltok::kw_fdiv:
1905 case lltok::kw_urem:
1906 case lltok::kw_srem:
1907 case lltok::kw_frem: {
1908 unsigned Opc = Lex.getUIntVal();
1909 Constant *Val0, *Val1;
1911 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1912 ParseGlobalTypeAndValue(Val0) ||
1913 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1914 ParseGlobalTypeAndValue(Val1) ||
1915 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1917 if (Val0->getType() != Val1->getType())
1918 return Error(ID.Loc, "operands of constexpr must have same type");
1919 if (!Val0->getType()->isIntOrIntVector() &&
1920 !Val0->getType()->isFPOrFPVector())
1921 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1922 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1923 ID.Kind = ValID::t_Constant;
1927 // Logical Operations
1929 case lltok::kw_lshr:
1930 case lltok::kw_ashr:
1933 case lltok::kw_xor: {
1934 unsigned Opc = Lex.getUIntVal();
1935 Constant *Val0, *Val1;
1937 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1938 ParseGlobalTypeAndValue(Val0) ||
1939 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1940 ParseGlobalTypeAndValue(Val1) ||
1941 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1943 if (Val0->getType() != Val1->getType())
1944 return Error(ID.Loc, "operands of constexpr must have same type");
1945 if (!Val0->getType()->isIntOrIntVector())
1946 return Error(ID.Loc,
1947 "constexpr requires integer or integer vector operands");
1948 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1949 ID.Kind = ValID::t_Constant;
1953 case lltok::kw_getelementptr:
1954 case lltok::kw_shufflevector:
1955 case lltok::kw_insertelement:
1956 case lltok::kw_extractelement:
1957 case lltok::kw_select: {
1958 unsigned Opc = Lex.getUIntVal();
1959 SmallVector<Constant*, 16> Elts;
1961 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1962 ParseGlobalValueVector(Elts) ||
1963 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1966 if (Opc == Instruction::GetElementPtr) {
1967 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1968 return Error(ID.Loc, "getelementptr requires pointer operand");
1970 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1971 (Value**)&Elts[1], Elts.size()-1))
1972 return Error(ID.Loc, "invalid indices for getelementptr");
1973 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
1974 &Elts[1], Elts.size()-1);
1975 } else if (Opc == Instruction::Select) {
1976 if (Elts.size() != 3)
1977 return Error(ID.Loc, "expected three operands to select");
1978 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1980 return Error(ID.Loc, Reason);
1981 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
1982 } else if (Opc == Instruction::ShuffleVector) {
1983 if (Elts.size() != 3)
1984 return Error(ID.Loc, "expected three operands to shufflevector");
1985 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1986 return Error(ID.Loc, "invalid operands to shufflevector");
1988 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
1989 } else if (Opc == Instruction::ExtractElement) {
1990 if (Elts.size() != 2)
1991 return Error(ID.Loc, "expected two operands to extractelement");
1992 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1993 return Error(ID.Loc, "invalid extractelement operands");
1994 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
1996 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1997 if (Elts.size() != 3)
1998 return Error(ID.Loc, "expected three operands to insertelement");
1999 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2000 return Error(ID.Loc, "invalid insertelement operands");
2002 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
2005 ID.Kind = ValID::t_Constant;
2014 /// ParseGlobalValue - Parse a global value with the specified type.
2015 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2018 return ParseValID(ID) ||
2019 ConvertGlobalValIDToValue(Ty, ID, V);
2022 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2024 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2026 if (isa<FunctionType>(Ty))
2027 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2030 default: assert(0 && "Unknown ValID!");
2031 case ValID::t_LocalID:
2032 case ValID::t_LocalName:
2033 return Error(ID.Loc, "invalid use of function-local name");
2034 case ValID::t_InlineAsm:
2035 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2036 case ValID::t_GlobalName:
2037 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2039 case ValID::t_GlobalID:
2040 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2042 case ValID::t_APSInt:
2043 if (!isa<IntegerType>(Ty))
2044 return Error(ID.Loc, "integer constant must have integer type");
2045 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2046 V = Context.getConstantInt(ID.APSIntVal);
2048 case ValID::t_APFloat:
2049 if (!Ty->isFloatingPoint() ||
2050 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2051 return Error(ID.Loc, "floating point constant invalid for type");
2053 // The lexer has no type info, so builds all float and double FP constants
2054 // as double. Fix this here. Long double does not need this.
2055 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2056 Ty == Type::FloatTy) {
2058 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2061 V = Context.getConstantFP(ID.APFloatVal);
2063 if (V->getType() != Ty)
2064 return Error(ID.Loc, "floating point constant does not have type '" +
2065 Ty->getDescription() + "'");
2069 if (!isa<PointerType>(Ty))
2070 return Error(ID.Loc, "null must be a pointer type");
2071 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2073 case ValID::t_Undef:
2074 // FIXME: LabelTy should not be a first-class type.
2075 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2076 !isa<OpaqueType>(Ty))
2077 return Error(ID.Loc, "invalid type for undef constant");
2078 V = Context.getUndef(Ty);
2080 case ValID::t_EmptyArray:
2081 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2082 return Error(ID.Loc, "invalid empty array initializer");
2083 V = Context.getUndef(Ty);
2086 // FIXME: LabelTy should not be a first-class type.
2087 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2088 return Error(ID.Loc, "invalid type for null constant");
2089 V = Context.getNullValue(Ty);
2091 case ValID::t_Constant:
2092 if (ID.ConstantVal->getType() != Ty)
2093 return Error(ID.Loc, "constant expression type mismatch");
2099 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2100 PATypeHolder Type(Type::VoidTy);
2101 return ParseType(Type) ||
2102 ParseGlobalValue(Type, V);
2105 /// ParseGlobalValueVector
2107 /// ::= TypeAndValue (',' TypeAndValue)*
2108 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2110 if (Lex.getKind() == lltok::rbrace ||
2111 Lex.getKind() == lltok::rsquare ||
2112 Lex.getKind() == lltok::greater ||
2113 Lex.getKind() == lltok::rparen)
2117 if (ParseGlobalTypeAndValue(C)) return true;
2120 while (EatIfPresent(lltok::comma)) {
2121 if (ParseGlobalTypeAndValue(C)) return true;
2129 //===----------------------------------------------------------------------===//
2130 // Function Parsing.
2131 //===----------------------------------------------------------------------===//
2133 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2134 PerFunctionState &PFS) {
2135 if (ID.Kind == ValID::t_LocalID)
2136 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2137 else if (ID.Kind == ValID::t_LocalName)
2138 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2139 else if (ID.Kind == ValID::t_InlineAsm) {
2140 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2141 const FunctionType *FTy =
2142 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2143 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2144 return Error(ID.Loc, "invalid type for inline asm constraint string");
2145 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2149 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2157 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2160 return ParseValID(ID) ||
2161 ConvertValIDToValue(Ty, ID, V, PFS);
2164 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2165 PATypeHolder T(Type::VoidTy);
2166 return ParseType(T) ||
2167 ParseValue(T, V, PFS);
2171 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2172 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2173 /// OptionalAlign OptGC
2174 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2175 // Parse the linkage.
2176 LocTy LinkageLoc = Lex.getLoc();
2179 unsigned Visibility, CC, RetAttrs;
2180 PATypeHolder RetType(Type::VoidTy);
2181 LocTy RetTypeLoc = Lex.getLoc();
2182 if (ParseOptionalLinkage(Linkage) ||
2183 ParseOptionalVisibility(Visibility) ||
2184 ParseOptionalCallingConv(CC) ||
2185 ParseOptionalAttrs(RetAttrs, 1) ||
2186 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2189 // Verify that the linkage is ok.
2190 switch ((GlobalValue::LinkageTypes)Linkage) {
2191 case GlobalValue::ExternalLinkage:
2192 break; // always ok.
2193 case GlobalValue::DLLImportLinkage:
2194 case GlobalValue::ExternalWeakLinkage:
2196 return Error(LinkageLoc, "invalid linkage for function definition");
2198 case GlobalValue::PrivateLinkage:
2199 case GlobalValue::InternalLinkage:
2200 case GlobalValue::AvailableExternallyLinkage:
2201 case GlobalValue::LinkOnceAnyLinkage:
2202 case GlobalValue::LinkOnceODRLinkage:
2203 case GlobalValue::WeakAnyLinkage:
2204 case GlobalValue::WeakODRLinkage:
2205 case GlobalValue::DLLExportLinkage:
2207 return Error(LinkageLoc, "invalid linkage for function declaration");
2209 case GlobalValue::AppendingLinkage:
2210 case GlobalValue::GhostLinkage:
2211 case GlobalValue::CommonLinkage:
2212 return Error(LinkageLoc, "invalid function linkage type");
2215 if (!FunctionType::isValidReturnType(RetType) ||
2216 isa<OpaqueType>(RetType))
2217 return Error(RetTypeLoc, "invalid function return type");
2219 LocTy NameLoc = Lex.getLoc();
2221 std::string FunctionName;
2222 if (Lex.getKind() == lltok::GlobalVar) {
2223 FunctionName = Lex.getStrVal();
2224 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2225 unsigned NameID = Lex.getUIntVal();
2227 if (NameID != NumberedVals.size())
2228 return TokError("function expected to be numbered '%" +
2229 utostr(NumberedVals.size()) + "'");
2231 return TokError("expected function name");
2236 if (Lex.getKind() != lltok::lparen)
2237 return TokError("expected '(' in function argument list");
2239 std::vector<ArgInfo> ArgList;
2242 std::string Section;
2246 if (ParseArgumentList(ArgList, isVarArg, false) ||
2247 ParseOptionalAttrs(FuncAttrs, 2) ||
2248 (EatIfPresent(lltok::kw_section) &&
2249 ParseStringConstant(Section)) ||
2250 ParseOptionalAlignment(Alignment) ||
2251 (EatIfPresent(lltok::kw_gc) &&
2252 ParseStringConstant(GC)))
2255 // If the alignment was parsed as an attribute, move to the alignment field.
2256 if (FuncAttrs & Attribute::Alignment) {
2257 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2258 FuncAttrs &= ~Attribute::Alignment;
2261 // Okay, if we got here, the function is syntactically valid. Convert types
2262 // and do semantic checks.
2263 std::vector<const Type*> ParamTypeList;
2264 SmallVector<AttributeWithIndex, 8> Attrs;
2265 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2267 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2268 if (FuncAttrs & ObsoleteFuncAttrs) {
2269 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2270 FuncAttrs &= ~ObsoleteFuncAttrs;
2273 if (RetAttrs != Attribute::None)
2274 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2276 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2277 ParamTypeList.push_back(ArgList[i].Type);
2278 if (ArgList[i].Attrs != Attribute::None)
2279 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2282 if (FuncAttrs != Attribute::None)
2283 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2285 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2287 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2288 RetType != Type::VoidTy)
2289 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2291 const FunctionType *FT =
2292 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2293 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2296 if (!FunctionName.empty()) {
2297 // If this was a definition of a forward reference, remove the definition
2298 // from the forward reference table and fill in the forward ref.
2299 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2300 ForwardRefVals.find(FunctionName);
2301 if (FRVI != ForwardRefVals.end()) {
2302 Fn = M->getFunction(FunctionName);
2303 ForwardRefVals.erase(FRVI);
2304 } else if ((Fn = M->getFunction(FunctionName))) {
2305 // If this function already exists in the symbol table, then it is
2306 // multiply defined. We accept a few cases for old backwards compat.
2307 // FIXME: Remove this stuff for LLVM 3.0.
2308 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2309 (!Fn->isDeclaration() && isDefine)) {
2310 // If the redefinition has different type or different attributes,
2311 // reject it. If both have bodies, reject it.
2312 return Error(NameLoc, "invalid redefinition of function '" +
2313 FunctionName + "'");
2314 } else if (Fn->isDeclaration()) {
2315 // Make sure to strip off any argument names so we can't get conflicts.
2316 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2322 } else if (FunctionName.empty()) {
2323 // If this is a definition of a forward referenced function, make sure the
2325 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2326 = ForwardRefValIDs.find(NumberedVals.size());
2327 if (I != ForwardRefValIDs.end()) {
2328 Fn = cast<Function>(I->second.first);
2329 if (Fn->getType() != PFT)
2330 return Error(NameLoc, "type of definition and forward reference of '@" +
2331 utostr(NumberedVals.size()) +"' disagree");
2332 ForwardRefValIDs.erase(I);
2337 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2338 else // Move the forward-reference to the correct spot in the module.
2339 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2341 if (FunctionName.empty())
2342 NumberedVals.push_back(Fn);
2344 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2345 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2346 Fn->setCallingConv(CC);
2347 Fn->setAttributes(PAL);
2348 Fn->setAlignment(Alignment);
2349 Fn->setSection(Section);
2350 if (!GC.empty()) Fn->setGC(GC.c_str());
2352 // Add all of the arguments we parsed to the function.
2353 Function::arg_iterator ArgIt = Fn->arg_begin();
2354 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2355 // If the argument has a name, insert it into the argument symbol table.
2356 if (ArgList[i].Name.empty()) continue;
2358 // Set the name, if it conflicted, it will be auto-renamed.
2359 ArgIt->setName(ArgList[i].Name);
2361 if (ArgIt->getNameStr() != ArgList[i].Name)
2362 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2363 ArgList[i].Name + "'");
2370 /// ParseFunctionBody
2371 /// ::= '{' BasicBlock+ '}'
2372 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2374 bool LLParser::ParseFunctionBody(Function &Fn) {
2375 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2376 return TokError("expected '{' in function body");
2377 Lex.Lex(); // eat the {.
2379 PerFunctionState PFS(*this, Fn);
2381 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2382 if (ParseBasicBlock(PFS)) return true;
2387 // Verify function is ok.
2388 return PFS.VerifyFunctionComplete();
2392 /// ::= LabelStr? Instruction*
2393 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2394 // If this basic block starts out with a name, remember it.
2396 LocTy NameLoc = Lex.getLoc();
2397 if (Lex.getKind() == lltok::LabelStr) {
2398 Name = Lex.getStrVal();
2402 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2403 if (BB == 0) return true;
2405 std::string NameStr;
2407 // Parse the instructions in this block until we get a terminator.
2410 // This instruction may have three possibilities for a name: a) none
2411 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2412 LocTy NameLoc = Lex.getLoc();
2416 if (Lex.getKind() == lltok::LocalVarID) {
2417 NameID = Lex.getUIntVal();
2419 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2421 } else if (Lex.getKind() == lltok::LocalVar ||
2422 // FIXME: REMOVE IN LLVM 3.0
2423 Lex.getKind() == lltok::StringConstant) {
2424 NameStr = Lex.getStrVal();
2426 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2430 if (ParseInstruction(Inst, BB, PFS)) return true;
2432 BB->getInstList().push_back(Inst);
2434 // Set the name on the instruction.
2435 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2436 } while (!isa<TerminatorInst>(Inst));
2441 //===----------------------------------------------------------------------===//
2442 // Instruction Parsing.
2443 //===----------------------------------------------------------------------===//
2445 /// ParseInstruction - Parse one of the many different instructions.
2447 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2448 PerFunctionState &PFS) {
2449 lltok::Kind Token = Lex.getKind();
2450 if (Token == lltok::Eof)
2451 return TokError("found end of file when expecting more instructions");
2452 LocTy Loc = Lex.getLoc();
2453 unsigned KeywordVal = Lex.getUIntVal();
2454 Lex.Lex(); // Eat the keyword.
2457 default: return Error(Loc, "expected instruction opcode");
2458 // Terminator Instructions.
2459 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2460 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2461 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2462 case lltok::kw_br: return ParseBr(Inst, PFS);
2463 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2464 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2465 // Binary Operators.
2469 // API compatibility: Accept either integer or floating-point types.
2470 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2471 case lltok::kw_fadd:
2472 case lltok::kw_fsub:
2473 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2475 case lltok::kw_udiv:
2476 case lltok::kw_sdiv:
2477 case lltok::kw_urem:
2478 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2479 case lltok::kw_fdiv:
2480 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2482 case lltok::kw_lshr:
2483 case lltok::kw_ashr:
2486 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2487 case lltok::kw_icmp:
2488 case lltok::kw_fcmp:
2489 case lltok::kw_vicmp:
2490 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
2492 case lltok::kw_trunc:
2493 case lltok::kw_zext:
2494 case lltok::kw_sext:
2495 case lltok::kw_fptrunc:
2496 case lltok::kw_fpext:
2497 case lltok::kw_bitcast:
2498 case lltok::kw_uitofp:
2499 case lltok::kw_sitofp:
2500 case lltok::kw_fptoui:
2501 case lltok::kw_fptosi:
2502 case lltok::kw_inttoptr:
2503 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2505 case lltok::kw_select: return ParseSelect(Inst, PFS);
2506 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2507 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2508 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2509 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2510 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2511 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2512 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2514 case lltok::kw_alloca:
2515 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2516 case lltok::kw_free: return ParseFree(Inst, PFS);
2517 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2518 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2519 case lltok::kw_volatile:
2520 if (EatIfPresent(lltok::kw_load))
2521 return ParseLoad(Inst, PFS, true);
2522 else if (EatIfPresent(lltok::kw_store))
2523 return ParseStore(Inst, PFS, true);
2525 return TokError("expected 'load' or 'store'");
2526 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2527 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2528 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2529 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2533 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2534 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2535 // FIXME: REMOVE vicmp/vfcmp!
2536 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2537 switch (Lex.getKind()) {
2538 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2539 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2540 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2541 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2542 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2543 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2544 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2545 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2546 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2547 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2548 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2549 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2550 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2551 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2552 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2553 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2554 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2557 switch (Lex.getKind()) {
2558 default: TokError("expected icmp predicate (e.g. 'eq')");
2559 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2560 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2561 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2562 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2563 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2564 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2565 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2566 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2567 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2568 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2575 //===----------------------------------------------------------------------===//
2576 // Terminator Instructions.
2577 //===----------------------------------------------------------------------===//
2579 /// ParseRet - Parse a return instruction.
2581 /// ::= 'ret' TypeAndValue
2582 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2583 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2584 PerFunctionState &PFS) {
2585 PATypeHolder Ty(Type::VoidTy);
2586 if (ParseType(Ty, true /*void allowed*/)) return true;
2588 if (Ty == Type::VoidTy) {
2589 Inst = ReturnInst::Create();
2594 if (ParseValue(Ty, RV, PFS)) return true;
2596 // The normal case is one return value.
2597 if (Lex.getKind() == lltok::comma) {
2598 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2599 // of 'ret {i32,i32} {i32 1, i32 2}'
2600 SmallVector<Value*, 8> RVs;
2603 while (EatIfPresent(lltok::comma)) {
2604 if (ParseTypeAndValue(RV, PFS)) return true;
2608 RV = Context.getUndef(PFS.getFunction().getReturnType());
2609 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2610 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2611 BB->getInstList().push_back(I);
2615 Inst = ReturnInst::Create(RV);
2621 /// ::= 'br' TypeAndValue
2622 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2623 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2625 Value *Op0, *Op1, *Op2;
2626 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2628 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2629 Inst = BranchInst::Create(BB);
2633 if (Op0->getType() != Type::Int1Ty)
2634 return Error(Loc, "branch condition must have 'i1' type");
2636 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2637 ParseTypeAndValue(Op1, Loc, PFS) ||
2638 ParseToken(lltok::comma, "expected ',' after true destination") ||
2639 ParseTypeAndValue(Op2, Loc2, PFS))
2642 if (!isa<BasicBlock>(Op1))
2643 return Error(Loc, "true destination of branch must be a basic block");
2644 if (!isa<BasicBlock>(Op2))
2645 return Error(Loc2, "true destination of branch must be a basic block");
2647 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2653 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2655 /// ::= (TypeAndValue ',' TypeAndValue)*
2656 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2657 LocTy CondLoc, BBLoc;
2658 Value *Cond, *DefaultBB;
2659 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2660 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2661 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2662 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2665 if (!isa<IntegerType>(Cond->getType()))
2666 return Error(CondLoc, "switch condition must have integer type");
2667 if (!isa<BasicBlock>(DefaultBB))
2668 return Error(BBLoc, "default destination must be a basic block");
2670 // Parse the jump table pairs.
2671 SmallPtrSet<Value*, 32> SeenCases;
2672 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2673 while (Lex.getKind() != lltok::rsquare) {
2674 Value *Constant, *DestBB;
2676 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2677 ParseToken(lltok::comma, "expected ',' after case value") ||
2678 ParseTypeAndValue(DestBB, BBLoc, PFS))
2681 if (!SeenCases.insert(Constant))
2682 return Error(CondLoc, "duplicate case value in switch");
2683 if (!isa<ConstantInt>(Constant))
2684 return Error(CondLoc, "case value is not a constant integer");
2685 if (!isa<BasicBlock>(DestBB))
2686 return Error(BBLoc, "case destination is not a basic block");
2688 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2689 cast<BasicBlock>(DestBB)));
2692 Lex.Lex(); // Eat the ']'.
2694 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2696 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2697 SI->addCase(Table[i].first, Table[i].second);
2703 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2704 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2705 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2706 LocTy CallLoc = Lex.getLoc();
2707 unsigned CC, RetAttrs, FnAttrs;
2708 PATypeHolder RetType(Type::VoidTy);
2711 SmallVector<ParamInfo, 16> ArgList;
2713 Value *NormalBB, *UnwindBB;
2714 if (ParseOptionalCallingConv(CC) ||
2715 ParseOptionalAttrs(RetAttrs, 1) ||
2716 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2717 ParseValID(CalleeID) ||
2718 ParseParameterList(ArgList, PFS) ||
2719 ParseOptionalAttrs(FnAttrs, 2) ||
2720 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2721 ParseTypeAndValue(NormalBB, PFS) ||
2722 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2723 ParseTypeAndValue(UnwindBB, PFS))
2726 if (!isa<BasicBlock>(NormalBB))
2727 return Error(CallLoc, "normal destination is not a basic block");
2728 if (!isa<BasicBlock>(UnwindBB))
2729 return Error(CallLoc, "unwind destination is not a basic block");
2731 // If RetType is a non-function pointer type, then this is the short syntax
2732 // for the call, which means that RetType is just the return type. Infer the
2733 // rest of the function argument types from the arguments that are present.
2734 const PointerType *PFTy = 0;
2735 const FunctionType *Ty = 0;
2736 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2737 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2738 // Pull out the types of all of the arguments...
2739 std::vector<const Type*> ParamTypes;
2740 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2741 ParamTypes.push_back(ArgList[i].V->getType());
2743 if (!FunctionType::isValidReturnType(RetType))
2744 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2746 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2747 PFTy = Context.getPointerTypeUnqual(Ty);
2750 // Look up the callee.
2752 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2754 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2755 // function attributes.
2756 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2757 if (FnAttrs & ObsoleteFuncAttrs) {
2758 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2759 FnAttrs &= ~ObsoleteFuncAttrs;
2762 // Set up the Attributes for the function.
2763 SmallVector<AttributeWithIndex, 8> Attrs;
2764 if (RetAttrs != Attribute::None)
2765 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2767 SmallVector<Value*, 8> Args;
2769 // Loop through FunctionType's arguments and ensure they are specified
2770 // correctly. Also, gather any parameter attributes.
2771 FunctionType::param_iterator I = Ty->param_begin();
2772 FunctionType::param_iterator E = Ty->param_end();
2773 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2774 const Type *ExpectedTy = 0;
2777 } else if (!Ty->isVarArg()) {
2778 return Error(ArgList[i].Loc, "too many arguments specified");
2781 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2782 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2783 ExpectedTy->getDescription() + "'");
2784 Args.push_back(ArgList[i].V);
2785 if (ArgList[i].Attrs != Attribute::None)
2786 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2790 return Error(CallLoc, "not enough parameters specified for call");
2792 if (FnAttrs != Attribute::None)
2793 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2795 // Finish off the Attributes and check them
2796 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2798 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2799 cast<BasicBlock>(UnwindBB),
2800 Args.begin(), Args.end());
2801 II->setCallingConv(CC);
2802 II->setAttributes(PAL);
2809 //===----------------------------------------------------------------------===//
2810 // Binary Operators.
2811 //===----------------------------------------------------------------------===//
2814 /// ::= ArithmeticOps TypeAndValue ',' Value
2816 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2817 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2818 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2819 unsigned Opc, unsigned OperandType) {
2820 LocTy Loc; Value *LHS, *RHS;
2821 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2822 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2823 ParseValue(LHS->getType(), RHS, PFS))
2827 switch (OperandType) {
2828 default: assert(0 && "Unknown operand type!");
2829 case 0: // int or FP.
2830 Valid = LHS->getType()->isIntOrIntVector() ||
2831 LHS->getType()->isFPOrFPVector();
2833 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2834 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2838 return Error(Loc, "invalid operand type for instruction");
2840 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2845 /// ::= ArithmeticOps TypeAndValue ',' Value {
2846 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2848 LocTy Loc; Value *LHS, *RHS;
2849 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2850 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2851 ParseValue(LHS->getType(), RHS, PFS))
2854 if (!LHS->getType()->isIntOrIntVector())
2855 return Error(Loc,"instruction requires integer or integer vector operands");
2857 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2863 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2864 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2865 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2866 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2867 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2869 // Parse the integer/fp comparison predicate.
2873 if (ParseCmpPredicate(Pred, Opc) ||
2874 ParseTypeAndValue(LHS, Loc, PFS) ||
2875 ParseToken(lltok::comma, "expected ',' after compare value") ||
2876 ParseValue(LHS->getType(), RHS, PFS))
2879 if (Opc == Instruction::FCmp) {
2880 if (!LHS->getType()->isFPOrFPVector())
2881 return Error(Loc, "fcmp requires floating point operands");
2882 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2883 } else if (Opc == Instruction::ICmp) {
2884 if (!LHS->getType()->isIntOrIntVector() &&
2885 !isa<PointerType>(LHS->getType()))
2886 return Error(Loc, "icmp requires integer operands");
2887 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2888 } else if (Opc == Instruction::VFCmp) {
2889 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2890 return Error(Loc, "vfcmp requires vector floating point operands");
2891 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2892 } else if (Opc == Instruction::VICmp) {
2893 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2894 return Error(Loc, "vicmp requires vector floating point operands");
2895 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2900 //===----------------------------------------------------------------------===//
2901 // Other Instructions.
2902 //===----------------------------------------------------------------------===//
2906 /// ::= CastOpc TypeAndValue 'to' Type
2907 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2909 LocTy Loc; Value *Op;
2910 PATypeHolder DestTy(Type::VoidTy);
2911 if (ParseTypeAndValue(Op, Loc, PFS) ||
2912 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2916 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2917 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
2918 return Error(Loc, "invalid cast opcode for cast from '" +
2919 Op->getType()->getDescription() + "' to '" +
2920 DestTy->getDescription() + "'");
2922 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2927 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2928 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2930 Value *Op0, *Op1, *Op2;
2931 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2932 ParseToken(lltok::comma, "expected ',' after select condition") ||
2933 ParseTypeAndValue(Op1, PFS) ||
2934 ParseToken(lltok::comma, "expected ',' after select value") ||
2935 ParseTypeAndValue(Op2, PFS))
2938 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2939 return Error(Loc, Reason);
2941 Inst = SelectInst::Create(Op0, Op1, Op2);
2946 /// ::= 'va_arg' TypeAndValue ',' Type
2947 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2949 PATypeHolder EltTy(Type::VoidTy);
2951 if (ParseTypeAndValue(Op, PFS) ||
2952 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2953 ParseType(EltTy, TypeLoc))
2956 if (!EltTy->isFirstClassType())
2957 return Error(TypeLoc, "va_arg requires operand with first class type");
2959 Inst = new VAArgInst(Op, EltTy);
2963 /// ParseExtractElement
2964 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2965 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2968 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2969 ParseToken(lltok::comma, "expected ',' after extract value") ||
2970 ParseTypeAndValue(Op1, PFS))
2973 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2974 return Error(Loc, "invalid extractelement operands");
2976 Inst = new ExtractElementInst(Op0, Op1);
2980 /// ParseInsertElement
2981 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2982 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2984 Value *Op0, *Op1, *Op2;
2985 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2986 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2987 ParseTypeAndValue(Op1, PFS) ||
2988 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2989 ParseTypeAndValue(Op2, PFS))
2992 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2993 return Error(Loc, "invalid extractelement operands");
2995 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2999 /// ParseShuffleVector
3000 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3001 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3003 Value *Op0, *Op1, *Op2;
3004 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3005 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3006 ParseTypeAndValue(Op1, PFS) ||
3007 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3008 ParseTypeAndValue(Op2, PFS))
3011 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3012 return Error(Loc, "invalid extractelement operands");
3014 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3019 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3020 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3021 PATypeHolder Ty(Type::VoidTy);
3023 LocTy TypeLoc = Lex.getLoc();
3025 if (ParseType(Ty) ||
3026 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3027 ParseValue(Ty, Op0, PFS) ||
3028 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3029 ParseValue(Type::LabelTy, Op1, PFS) ||
3030 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3033 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3035 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3037 if (!EatIfPresent(lltok::comma))
3040 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3041 ParseValue(Ty, Op0, PFS) ||
3042 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3043 ParseValue(Type::LabelTy, Op1, PFS) ||
3044 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3048 if (!Ty->isFirstClassType())
3049 return Error(TypeLoc, "phi node must have first class type");
3051 PHINode *PN = PHINode::Create(Ty);
3052 PN->reserveOperandSpace(PHIVals.size());
3053 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3054 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3060 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3061 /// ParameterList OptionalAttrs
3062 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3064 unsigned CC, RetAttrs, FnAttrs;
3065 PATypeHolder RetType(Type::VoidTy);
3068 SmallVector<ParamInfo, 16> ArgList;
3069 LocTy CallLoc = Lex.getLoc();
3071 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3072 ParseOptionalCallingConv(CC) ||
3073 ParseOptionalAttrs(RetAttrs, 1) ||
3074 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3075 ParseValID(CalleeID) ||
3076 ParseParameterList(ArgList, PFS) ||
3077 ParseOptionalAttrs(FnAttrs, 2))
3080 // If RetType is a non-function pointer type, then this is the short syntax
3081 // for the call, which means that RetType is just the return type. Infer the
3082 // rest of the function argument types from the arguments that are present.
3083 const PointerType *PFTy = 0;
3084 const FunctionType *Ty = 0;
3085 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3086 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3087 // Pull out the types of all of the arguments...
3088 std::vector<const Type*> ParamTypes;
3089 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3090 ParamTypes.push_back(ArgList[i].V->getType());
3092 if (!FunctionType::isValidReturnType(RetType))
3093 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3095 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3096 PFTy = Context.getPointerTypeUnqual(Ty);
3099 // Look up the callee.
3101 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3103 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3104 // function attributes.
3105 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3106 if (FnAttrs & ObsoleteFuncAttrs) {
3107 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3108 FnAttrs &= ~ObsoleteFuncAttrs;
3111 // Set up the Attributes for the function.
3112 SmallVector<AttributeWithIndex, 8> Attrs;
3113 if (RetAttrs != Attribute::None)
3114 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3116 SmallVector<Value*, 8> Args;
3118 // Loop through FunctionType's arguments and ensure they are specified
3119 // correctly. Also, gather any parameter attributes.
3120 FunctionType::param_iterator I = Ty->param_begin();
3121 FunctionType::param_iterator E = Ty->param_end();
3122 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3123 const Type *ExpectedTy = 0;
3126 } else if (!Ty->isVarArg()) {
3127 return Error(ArgList[i].Loc, "too many arguments specified");
3130 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3131 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3132 ExpectedTy->getDescription() + "'");
3133 Args.push_back(ArgList[i].V);
3134 if (ArgList[i].Attrs != Attribute::None)
3135 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3139 return Error(CallLoc, "not enough parameters specified for call");
3141 if (FnAttrs != Attribute::None)
3142 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3144 // Finish off the Attributes and check them
3145 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3147 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3148 CI->setTailCall(isTail);
3149 CI->setCallingConv(CC);
3150 CI->setAttributes(PAL);
3155 //===----------------------------------------------------------------------===//
3156 // Memory Instructions.
3157 //===----------------------------------------------------------------------===//
3160 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3161 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3162 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3164 PATypeHolder Ty(Type::VoidTy);
3167 unsigned Alignment = 0;
3168 if (ParseType(Ty)) return true;
3170 if (EatIfPresent(lltok::comma)) {
3171 if (Lex.getKind() == lltok::kw_align) {
3172 if (ParseOptionalAlignment(Alignment)) return true;
3173 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3174 ParseOptionalCommaAlignment(Alignment)) {
3179 if (Size && Size->getType() != Type::Int32Ty)
3180 return Error(SizeLoc, "element count must be i32");
3182 if (Opc == Instruction::Malloc)
3183 Inst = new MallocInst(Ty, Size, Alignment);
3185 Inst = new AllocaInst(Ty, Size, Alignment);
3190 /// ::= 'free' TypeAndValue
3191 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3192 Value *Val; LocTy Loc;
3193 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3194 if (!isa<PointerType>(Val->getType()))
3195 return Error(Loc, "operand to free must be a pointer");
3196 Inst = new FreeInst(Val);
3201 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3202 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3204 Value *Val; LocTy Loc;
3206 if (ParseTypeAndValue(Val, Loc, PFS) ||
3207 ParseOptionalCommaAlignment(Alignment))
3210 if (!isa<PointerType>(Val->getType()) ||
3211 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3212 return Error(Loc, "load operand must be a pointer to a first class type");
3214 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3219 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3220 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3222 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3224 if (ParseTypeAndValue(Val, Loc, PFS) ||
3225 ParseToken(lltok::comma, "expected ',' after store operand") ||
3226 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3227 ParseOptionalCommaAlignment(Alignment))
3230 if (!isa<PointerType>(Ptr->getType()))
3231 return Error(PtrLoc, "store operand must be a pointer");
3232 if (!Val->getType()->isFirstClassType())
3233 return Error(Loc, "store operand must be a first class value");
3234 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3235 return Error(Loc, "stored value and pointer type do not match");
3237 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3242 /// ::= 'getresult' TypeAndValue ',' i32
3243 /// FIXME: Remove support for getresult in LLVM 3.0
3244 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3245 Value *Val; LocTy ValLoc, EltLoc;
3247 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3248 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3249 ParseUInt32(Element, EltLoc))
3252 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3253 return Error(ValLoc, "getresult inst requires an aggregate operand");
3254 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3255 return Error(EltLoc, "invalid getresult index for value");
3256 Inst = ExtractValueInst::Create(Val, Element);
3260 /// ParseGetElementPtr
3261 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3262 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3263 Value *Ptr, *Val; LocTy Loc, EltLoc;
3264 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3266 if (!isa<PointerType>(Ptr->getType()))
3267 return Error(Loc, "base of getelementptr must be a pointer");
3269 SmallVector<Value*, 16> Indices;
3270 while (EatIfPresent(lltok::comma)) {
3271 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3272 if (!isa<IntegerType>(Val->getType()))
3273 return Error(EltLoc, "getelementptr index must be an integer");
3274 Indices.push_back(Val);
3277 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3278 Indices.begin(), Indices.end()))
3279 return Error(Loc, "invalid getelementptr indices");
3280 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3284 /// ParseExtractValue
3285 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3286 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3287 Value *Val; LocTy Loc;
3288 SmallVector<unsigned, 4> Indices;
3289 if (ParseTypeAndValue(Val, Loc, PFS) ||
3290 ParseIndexList(Indices))
3293 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3294 return Error(Loc, "extractvalue operand must be array or struct");
3296 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3298 return Error(Loc, "invalid indices for extractvalue");
3299 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3303 /// ParseInsertValue
3304 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3305 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3306 Value *Val0, *Val1; LocTy Loc0, Loc1;
3307 SmallVector<unsigned, 4> Indices;
3308 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3309 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3310 ParseTypeAndValue(Val1, Loc1, PFS) ||
3311 ParseIndexList(Indices))
3314 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3315 return Error(Loc0, "extractvalue operand must be array or struct");
3317 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3319 return Error(Loc0, "invalid indices for insertvalue");
3320 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3324 //===----------------------------------------------------------------------===//
3325 // Embedded metadata.
3326 //===----------------------------------------------------------------------===//
3328 /// ParseMDNodeVector
3329 /// ::= Element (',' Element)*
3331 /// ::= 'null' | TypeAndValue
3332 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3333 assert(Lex.getKind() == lltok::lbrace);
3337 if (Lex.getKind() == lltok::kw_null) {
3342 if (ParseGlobalTypeAndValue(C)) return true;
3346 } while (EatIfPresent(lltok::comma));