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/Operator.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
33 /// ValID - Represents a reference of a definition of some sort with no type.
34 /// There are several cases where we have to parse the value but where the
35 /// type can depend on later context. This may either be a numeric reference
36 /// or a symbolic (%var) reference. This is just a discriminated union.
39 t_LocalID, t_GlobalID, // ID in UIntVal.
40 t_LocalName, t_GlobalName, // Name in StrVal.
41 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
42 t_Null, t_Undef, t_Zero, // No value.
43 t_EmptyArray, // No value: []
44 t_Constant, // Value in ConstantVal.
45 t_InlineAsm, // Value in StrVal/StrVal2/UIntVal.
46 t_Metadata // Value in MetadataVal.
51 std::string StrVal, StrVal2;
54 Constant *ConstantVal;
55 MetadataBase *MetadataVal;
56 ValID() : APFloatVal(0.0) {}
60 /// Run: module ::= toplevelentity*
61 bool LLParser::Run() {
65 return ParseTopLevelEntities() ||
66 ValidateEndOfModule();
69 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
71 bool LLParser::ValidateEndOfModule() {
72 if (!ForwardRefTypes.empty())
73 return Error(ForwardRefTypes.begin()->second.second,
74 "use of undefined type named '" +
75 ForwardRefTypes.begin()->first + "'");
76 if (!ForwardRefTypeIDs.empty())
77 return Error(ForwardRefTypeIDs.begin()->second.second,
78 "use of undefined type '%" +
79 utostr(ForwardRefTypeIDs.begin()->first) + "'");
81 if (!ForwardRefVals.empty())
82 return Error(ForwardRefVals.begin()->second.second,
83 "use of undefined value '@" + ForwardRefVals.begin()->first +
86 if (!ForwardRefValIDs.empty())
87 return Error(ForwardRefValIDs.begin()->second.second,
88 "use of undefined value '@" +
89 utostr(ForwardRefValIDs.begin()->first) + "'");
91 if (!ForwardRefMDNodes.empty())
92 return Error(ForwardRefMDNodes.begin()->second.second,
93 "use of undefined metadata '!" +
94 utostr(ForwardRefMDNodes.begin()->first) + "'");
97 // Look for intrinsic functions and CallInst that need to be upgraded
98 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
99 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
104 //===----------------------------------------------------------------------===//
105 // Top-Level Entities
106 //===----------------------------------------------------------------------===//
108 bool LLParser::ParseTopLevelEntities() {
110 switch (Lex.getKind()) {
111 default: return TokError("expected top-level entity");
112 case lltok::Eof: return false;
113 //case lltok::kw_define:
114 case lltok::kw_declare: if (ParseDeclare()) return true; break;
115 case lltok::kw_define: if (ParseDefine()) return true; break;
116 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
117 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
118 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
119 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
120 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
121 case lltok::LocalVar: if (ParseNamedType()) return true; break;
122 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
123 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
125 // The Global variable production with no name can have many different
126 // optional leading prefixes, the production is:
127 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
128 // OptionalAddrSpace ('constant'|'global') ...
129 case lltok::kw_private : // OptionalLinkage
130 case lltok::kw_linker_private: // OptionalLinkage
131 case lltok::kw_internal: // OptionalLinkage
132 case lltok::kw_weak: // OptionalLinkage
133 case lltok::kw_weak_odr: // OptionalLinkage
134 case lltok::kw_linkonce: // OptionalLinkage
135 case lltok::kw_linkonce_odr: // OptionalLinkage
136 case lltok::kw_appending: // OptionalLinkage
137 case lltok::kw_dllexport: // OptionalLinkage
138 case lltok::kw_common: // OptionalLinkage
139 case lltok::kw_dllimport: // OptionalLinkage
140 case lltok::kw_extern_weak: // OptionalLinkage
141 case lltok::kw_external: { // OptionalLinkage
142 unsigned Linkage, Visibility;
143 if (ParseOptionalLinkage(Linkage) ||
144 ParseOptionalVisibility(Visibility) ||
145 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
149 case lltok::kw_default: // OptionalVisibility
150 case lltok::kw_hidden: // OptionalVisibility
151 case lltok::kw_protected: { // OptionalVisibility
153 if (ParseOptionalVisibility(Visibility) ||
154 ParseGlobal("", SMLoc(), 0, false, Visibility))
159 case lltok::kw_thread_local: // OptionalThreadLocal
160 case lltok::kw_addrspace: // OptionalAddrSpace
161 case lltok::kw_constant: // GlobalType
162 case lltok::kw_global: // GlobalType
163 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
171 /// ::= 'module' 'asm' STRINGCONSTANT
172 bool LLParser::ParseModuleAsm() {
173 assert(Lex.getKind() == lltok::kw_module);
177 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
178 ParseStringConstant(AsmStr)) return true;
180 const std::string &AsmSoFar = M->getModuleInlineAsm();
181 if (AsmSoFar.empty())
182 M->setModuleInlineAsm(AsmStr);
184 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
189 /// ::= 'target' 'triple' '=' STRINGCONSTANT
190 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
191 bool LLParser::ParseTargetDefinition() {
192 assert(Lex.getKind() == lltok::kw_target);
195 default: return TokError("unknown target property");
196 case lltok::kw_triple:
198 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
199 ParseStringConstant(Str))
201 M->setTargetTriple(Str);
203 case lltok::kw_datalayout:
205 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
206 ParseStringConstant(Str))
208 M->setDataLayout(Str);
214 /// ::= 'deplibs' '=' '[' ']'
215 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
216 bool LLParser::ParseDepLibs() {
217 assert(Lex.getKind() == lltok::kw_deplibs);
219 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
220 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
223 if (EatIfPresent(lltok::rsquare))
227 if (ParseStringConstant(Str)) return true;
230 while (EatIfPresent(lltok::comma)) {
231 if (ParseStringConstant(Str)) return true;
235 return ParseToken(lltok::rsquare, "expected ']' at end of list");
240 bool LLParser::ParseUnnamedType() {
241 assert(Lex.getKind() == lltok::kw_type);
242 LocTy TypeLoc = Lex.getLoc();
243 Lex.Lex(); // eat kw_type
245 PATypeHolder Ty(Type::VoidTy);
246 if (ParseType(Ty)) return true;
248 unsigned TypeID = NumberedTypes.size();
250 // See if this type was previously referenced.
251 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
252 FI = ForwardRefTypeIDs.find(TypeID);
253 if (FI != ForwardRefTypeIDs.end()) {
254 if (FI->second.first.get() == Ty)
255 return Error(TypeLoc, "self referential type is invalid");
257 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
258 Ty = FI->second.first.get();
259 ForwardRefTypeIDs.erase(FI);
262 NumberedTypes.push_back(Ty);
268 /// ::= LocalVar '=' 'type' type
269 bool LLParser::ParseNamedType() {
270 std::string Name = Lex.getStrVal();
271 LocTy NameLoc = Lex.getLoc();
272 Lex.Lex(); // eat LocalVar.
274 PATypeHolder Ty(Type::VoidTy);
276 if (ParseToken(lltok::equal, "expected '=' after name") ||
277 ParseToken(lltok::kw_type, "expected 'type' after name") ||
281 // Set the type name, checking for conflicts as we do so.
282 bool AlreadyExists = M->addTypeName(Name, Ty);
283 if (!AlreadyExists) return false;
285 // See if this type is a forward reference. We need to eagerly resolve
286 // types to allow recursive type redefinitions below.
287 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
288 FI = ForwardRefTypes.find(Name);
289 if (FI != ForwardRefTypes.end()) {
290 if (FI->second.first.get() == Ty)
291 return Error(NameLoc, "self referential type is invalid");
293 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
294 Ty = FI->second.first.get();
295 ForwardRefTypes.erase(FI);
298 // Inserting a name that is already defined, get the existing name.
299 const Type *Existing = M->getTypeByName(Name);
300 assert(Existing && "Conflict but no matching type?!");
302 // Otherwise, this is an attempt to redefine a type. That's okay if
303 // the redefinition is identical to the original.
304 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
305 if (Existing == Ty) return false;
307 // Any other kind of (non-equivalent) redefinition is an error.
308 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
309 Ty->getDescription() + "'");
314 /// ::= 'declare' FunctionHeader
315 bool LLParser::ParseDeclare() {
316 assert(Lex.getKind() == lltok::kw_declare);
320 return ParseFunctionHeader(F, false);
324 /// ::= 'define' FunctionHeader '{' ...
325 bool LLParser::ParseDefine() {
326 assert(Lex.getKind() == lltok::kw_define);
330 return ParseFunctionHeader(F, true) ||
331 ParseFunctionBody(*F);
337 bool LLParser::ParseGlobalType(bool &IsConstant) {
338 if (Lex.getKind() == lltok::kw_constant)
340 else if (Lex.getKind() == lltok::kw_global)
344 return TokError("expected 'global' or 'constant'");
350 /// ParseNamedGlobal:
351 /// GlobalVar '=' OptionalVisibility ALIAS ...
352 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
353 bool LLParser::ParseNamedGlobal() {
354 assert(Lex.getKind() == lltok::GlobalVar);
355 LocTy NameLoc = Lex.getLoc();
356 std::string Name = Lex.getStrVal();
360 unsigned Linkage, Visibility;
361 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
362 ParseOptionalLinkage(Linkage, HasLinkage) ||
363 ParseOptionalVisibility(Visibility))
366 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
367 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
368 return ParseAlias(Name, NameLoc, Visibility);
372 // ::= '!' STRINGCONSTANT
373 bool LLParser::ParseMDString(MetadataBase *&MDS) {
375 if (ParseStringConstant(Str)) return true;
376 MDS = Context.getMDString(Str.data(), Str.size());
381 // ::= '!' MDNodeNumber
382 bool LLParser::ParseMDNode(MetadataBase *&Node) {
383 // !{ ..., !42, ... }
385 if (ParseUInt32(MID)) return true;
387 // Check existing MDNode.
388 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
389 if (I != MetadataCache.end()) {
394 // Check known forward references.
395 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
396 FI = ForwardRefMDNodes.find(MID);
397 if (FI != ForwardRefMDNodes.end()) {
398 Node = FI->second.first;
402 // Create MDNode forward reference
403 SmallVector<Value *, 1> Elts;
404 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
405 Elts.push_back(Context.getMDString(FwdRefName));
406 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
407 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
412 /// ParseStandaloneMetadata:
414 bool LLParser::ParseStandaloneMetadata() {
415 assert(Lex.getKind() == lltok::Metadata);
417 unsigned MetadataID = 0;
418 if (ParseUInt32(MetadataID))
420 if (MetadataCache.find(MetadataID) != MetadataCache.end())
421 return TokError("Metadata id is already used");
422 if (ParseToken(lltok::equal, "expected '=' here"))
426 PATypeHolder Ty(Type::VoidTy);
427 if (ParseType(Ty, TyLoc))
430 if (Lex.getKind() != lltok::Metadata)
431 return TokError("Expected metadata here");
434 if (Lex.getKind() != lltok::lbrace)
435 return TokError("Expected '{' here");
437 SmallVector<Value *, 16> Elts;
438 if (ParseMDNodeVector(Elts)
439 || ParseToken(lltok::rbrace, "exected end of metadata node"))
442 MDNode *Init = Context.getMDNode(Elts.data(), Elts.size());
443 MetadataCache[MetadataID] = Init;
444 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
445 FI = ForwardRefMDNodes.find(MetadataID);
446 if (FI != ForwardRefMDNodes.end()) {
447 MDNode *FwdNode = cast<MDNode>(FI->second.first);
448 FwdNode->replaceAllUsesWith(Init);
449 ForwardRefMDNodes.erase(FI);
456 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
459 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
460 /// ::= 'getelementptr' '(' ... ')'
462 /// Everything through visibility has already been parsed.
464 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
465 unsigned Visibility) {
466 assert(Lex.getKind() == lltok::kw_alias);
469 LocTy LinkageLoc = Lex.getLoc();
470 if (ParseOptionalLinkage(Linkage))
473 if (Linkage != GlobalValue::ExternalLinkage &&
474 Linkage != GlobalValue::WeakAnyLinkage &&
475 Linkage != GlobalValue::WeakODRLinkage &&
476 Linkage != GlobalValue::InternalLinkage &&
477 Linkage != GlobalValue::PrivateLinkage &&
478 Linkage != GlobalValue::LinkerPrivateLinkage)
479 return Error(LinkageLoc, "invalid linkage type for alias");
482 LocTy AliaseeLoc = Lex.getLoc();
483 if (Lex.getKind() != lltok::kw_bitcast &&
484 Lex.getKind() != lltok::kw_getelementptr) {
485 if (ParseGlobalTypeAndValue(Aliasee)) return true;
487 // The bitcast dest type is not present, it is implied by the dest type.
489 if (ParseValID(ID)) return true;
490 if (ID.Kind != ValID::t_Constant)
491 return Error(AliaseeLoc, "invalid aliasee");
492 Aliasee = ID.ConstantVal;
495 if (!isa<PointerType>(Aliasee->getType()))
496 return Error(AliaseeLoc, "alias must have pointer type");
498 // Okay, create the alias but do not insert it into the module yet.
499 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
500 (GlobalValue::LinkageTypes)Linkage, Name,
502 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
504 // See if this value already exists in the symbol table. If so, it is either
505 // a redefinition or a definition of a forward reference.
506 if (GlobalValue *Val =
507 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
508 // See if this was a redefinition. If so, there is no entry in
510 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
511 I = ForwardRefVals.find(Name);
512 if (I == ForwardRefVals.end())
513 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
515 // Otherwise, this was a definition of forward ref. Verify that types
517 if (Val->getType() != GA->getType())
518 return Error(NameLoc,
519 "forward reference and definition of alias have different types");
521 // If they agree, just RAUW the old value with the alias and remove the
523 Val->replaceAllUsesWith(GA);
524 Val->eraseFromParent();
525 ForwardRefVals.erase(I);
528 // Insert into the module, we know its name won't collide now.
529 M->getAliasList().push_back(GA);
530 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
536 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
537 /// OptionalAddrSpace GlobalType Type Const
538 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
539 /// OptionalAddrSpace GlobalType Type Const
541 /// Everything through visibility has been parsed already.
543 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
544 unsigned Linkage, bool HasLinkage,
545 unsigned Visibility) {
547 bool ThreadLocal, IsConstant;
550 PATypeHolder Ty(Type::VoidTy);
551 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
552 ParseOptionalAddrSpace(AddrSpace) ||
553 ParseGlobalType(IsConstant) ||
554 ParseType(Ty, TyLoc))
557 // If the linkage is specified and is external, then no initializer is
560 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
561 Linkage != GlobalValue::ExternalWeakLinkage &&
562 Linkage != GlobalValue::ExternalLinkage)) {
563 if (ParseGlobalValue(Ty, Init))
567 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
568 return Error(TyLoc, "invalid type for global variable");
570 GlobalVariable *GV = 0;
572 // See if the global was forward referenced, if so, use the global.
574 if ((GV = M->getGlobalVariable(Name, true)) &&
575 !ForwardRefVals.erase(Name))
576 return Error(NameLoc, "redefinition of global '@" + Name + "'");
578 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
579 I = ForwardRefValIDs.find(NumberedVals.size());
580 if (I != ForwardRefValIDs.end()) {
581 GV = cast<GlobalVariable>(I->second.first);
582 ForwardRefValIDs.erase(I);
587 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
588 Name, 0, false, AddrSpace);
590 if (GV->getType()->getElementType() != Ty)
592 "forward reference and definition of global have different types");
594 // Move the forward-reference to the correct spot in the module.
595 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
599 NumberedVals.push_back(GV);
601 // Set the parsed properties on the global.
603 GV->setInitializer(Init);
604 GV->setConstant(IsConstant);
605 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
606 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
607 GV->setThreadLocal(ThreadLocal);
609 // Parse attributes on the global.
610 while (Lex.getKind() == lltok::comma) {
613 if (Lex.getKind() == lltok::kw_section) {
615 GV->setSection(Lex.getStrVal());
616 if (ParseToken(lltok::StringConstant, "expected global section string"))
618 } else if (Lex.getKind() == lltok::kw_align) {
620 if (ParseOptionalAlignment(Alignment)) return true;
621 GV->setAlignment(Alignment);
623 TokError("unknown global variable property!");
631 //===----------------------------------------------------------------------===//
632 // GlobalValue Reference/Resolution Routines.
633 //===----------------------------------------------------------------------===//
635 /// GetGlobalVal - Get a value with the specified name or ID, creating a
636 /// forward reference record if needed. This can return null if the value
637 /// exists but does not have the right type.
638 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
640 const PointerType *PTy = dyn_cast<PointerType>(Ty);
642 Error(Loc, "global variable reference must have pointer type");
646 // Look this name up in the normal function symbol table.
648 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
650 // If this is a forward reference for the value, see if we already created a
651 // forward ref record.
653 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
654 I = ForwardRefVals.find(Name);
655 if (I != ForwardRefVals.end())
656 Val = I->second.first;
659 // If we have the value in the symbol table or fwd-ref table, return it.
661 if (Val->getType() == Ty) return Val;
662 Error(Loc, "'@" + Name + "' defined with type '" +
663 Val->getType()->getDescription() + "'");
667 // Otherwise, create a new forward reference for this value and remember it.
669 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
670 // Function types can return opaque but functions can't.
671 if (isa<OpaqueType>(FT->getReturnType())) {
672 Error(Loc, "function may not return opaque type");
676 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
678 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
679 GlobalValue::ExternalWeakLinkage, 0, Name);
682 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
686 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
687 const PointerType *PTy = dyn_cast<PointerType>(Ty);
689 Error(Loc, "global variable reference must have pointer type");
693 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
695 // If this is a forward reference for the value, see if we already created a
696 // forward ref record.
698 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
699 I = ForwardRefValIDs.find(ID);
700 if (I != ForwardRefValIDs.end())
701 Val = I->second.first;
704 // If we have the value in the symbol table or fwd-ref table, return it.
706 if (Val->getType() == Ty) return Val;
707 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
708 Val->getType()->getDescription() + "'");
712 // Otherwise, create a new forward reference for this value and remember it.
714 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
715 // Function types can return opaque but functions can't.
716 if (isa<OpaqueType>(FT->getReturnType())) {
717 Error(Loc, "function may not return opaque type");
720 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
722 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
723 GlobalValue::ExternalWeakLinkage, 0, "");
726 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
731 //===----------------------------------------------------------------------===//
733 //===----------------------------------------------------------------------===//
735 /// ParseToken - If the current token has the specified kind, eat it and return
736 /// success. Otherwise, emit the specified error and return failure.
737 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
738 if (Lex.getKind() != T)
739 return TokError(ErrMsg);
744 /// ParseStringConstant
745 /// ::= StringConstant
746 bool LLParser::ParseStringConstant(std::string &Result) {
747 if (Lex.getKind() != lltok::StringConstant)
748 return TokError("expected string constant");
749 Result = Lex.getStrVal();
756 bool LLParser::ParseUInt32(unsigned &Val) {
757 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
758 return TokError("expected integer");
759 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
760 if (Val64 != unsigned(Val64))
761 return TokError("expected 32-bit integer (too large)");
768 /// ParseOptionalAddrSpace
770 /// := 'addrspace' '(' uint32 ')'
771 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
773 if (!EatIfPresent(lltok::kw_addrspace))
775 return ParseToken(lltok::lparen, "expected '(' in address space") ||
776 ParseUInt32(AddrSpace) ||
777 ParseToken(lltok::rparen, "expected ')' in address space");
780 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
781 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
782 /// 2: function attr.
783 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
784 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
785 Attrs = Attribute::None;
786 LocTy AttrLoc = Lex.getLoc();
789 switch (Lex.getKind()) {
792 // Treat these as signext/zeroext if they occur in the argument list after
793 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
794 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
796 // FIXME: REMOVE THIS IN LLVM 3.0
798 if (Lex.getKind() == lltok::kw_sext)
799 Attrs |= Attribute::SExt;
801 Attrs |= Attribute::ZExt;
805 default: // End of attributes.
806 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
807 return Error(AttrLoc, "invalid use of function-only attribute");
809 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
810 return Error(AttrLoc, "invalid use of parameter-only attribute");
813 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
814 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
815 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
816 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
817 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
818 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
819 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
820 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
822 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
823 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
824 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
825 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
826 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
827 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
828 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
829 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
830 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
831 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
832 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
833 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
835 case lltok::kw_align: {
837 if (ParseOptionalAlignment(Alignment))
839 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
847 /// ParseOptionalLinkage
850 /// ::= 'linker_private'
855 /// ::= 'linkonce_odr'
860 /// ::= 'extern_weak'
862 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
864 switch (Lex.getKind()) {
865 default: Res=GlobalValue::ExternalLinkage; return false;
866 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
867 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
868 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
869 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
870 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
871 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
872 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
873 case lltok::kw_available_externally:
874 Res = GlobalValue::AvailableExternallyLinkage;
876 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
877 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
878 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
879 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
880 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
881 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
888 /// ParseOptionalVisibility
894 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
895 switch (Lex.getKind()) {
896 default: Res = GlobalValue::DefaultVisibility; return false;
897 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
898 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
899 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
905 /// ParseOptionalCallingConv
910 /// ::= 'x86_stdcallcc'
911 /// ::= 'x86_fastcallcc'
913 /// ::= 'arm_aapcscc'
914 /// ::= 'arm_aapcs_vfpcc'
917 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
918 switch (Lex.getKind()) {
919 default: CC = CallingConv::C; return false;
920 case lltok::kw_ccc: CC = CallingConv::C; break;
921 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
922 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
923 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
924 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
925 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
926 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
927 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
928 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
934 /// ParseOptionalAlignment
937 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
939 if (!EatIfPresent(lltok::kw_align))
941 LocTy AlignLoc = Lex.getLoc();
942 if (ParseUInt32(Alignment)) return true;
943 if (!isPowerOf2_32(Alignment))
944 return Error(AlignLoc, "alignment is not a power of two");
948 /// ParseOptionalCommaAlignment
950 /// ::= ',' 'align' 4
951 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
953 if (!EatIfPresent(lltok::comma))
955 return ParseToken(lltok::kw_align, "expected 'align'") ||
956 ParseUInt32(Alignment);
960 /// ::= (',' uint32)+
961 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
962 if (Lex.getKind() != lltok::comma)
963 return TokError("expected ',' as start of index list");
965 while (EatIfPresent(lltok::comma)) {
967 if (ParseUInt32(Idx)) return true;
968 Indices.push_back(Idx);
974 //===----------------------------------------------------------------------===//
976 //===----------------------------------------------------------------------===//
978 /// ParseType - Parse and resolve a full type.
979 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
980 LocTy TypeLoc = Lex.getLoc();
981 if (ParseTypeRec(Result)) return true;
983 // Verify no unresolved uprefs.
985 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
987 if (!AllowVoid && Result.get() == Type::VoidTy)
988 return Error(TypeLoc, "void type only allowed for function results");
993 /// HandleUpRefs - Every time we finish a new layer of types, this function is
994 /// called. It loops through the UpRefs vector, which is a list of the
995 /// currently active types. For each type, if the up-reference is contained in
996 /// the newly completed type, we decrement the level count. When the level
997 /// count reaches zero, the up-referenced type is the type that is passed in:
998 /// thus we can complete the cycle.
1000 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1001 // If Ty isn't abstract, or if there are no up-references in it, then there is
1002 // nothing to resolve here.
1003 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1005 PATypeHolder Ty(ty);
1007 errs() << "Type '" << Ty->getDescription()
1008 << "' newly formed. Resolving upreferences.\n"
1009 << UpRefs.size() << " upreferences active!\n";
1012 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1013 // to zero), we resolve them all together before we resolve them to Ty. At
1014 // the end of the loop, if there is anything to resolve to Ty, it will be in
1016 OpaqueType *TypeToResolve = 0;
1018 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1019 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1021 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1022 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1025 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1026 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1027 << (ContainsType ? "true" : "false")
1028 << " level=" << UpRefs[i].NestingLevel << "\n";
1033 // Decrement level of upreference
1034 unsigned Level = --UpRefs[i].NestingLevel;
1035 UpRefs[i].LastContainedTy = Ty;
1037 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1042 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1045 TypeToResolve = UpRefs[i].UpRefTy;
1047 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1048 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1049 --i; // Do not skip the next element.
1053 TypeToResolve->refineAbstractTypeTo(Ty);
1059 /// ParseTypeRec - The recursive function used to process the internal
1060 /// implementation details of types.
1061 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1062 switch (Lex.getKind()) {
1064 return TokError("expected type");
1066 // TypeRec ::= 'float' | 'void' (etc)
1067 Result = Lex.getTyVal();
1070 case lltok::kw_opaque:
1071 // TypeRec ::= 'opaque'
1072 Result = Context.getOpaqueType();
1076 // TypeRec ::= '{' ... '}'
1077 if (ParseStructType(Result, false))
1080 case lltok::lsquare:
1081 // TypeRec ::= '[' ... ']'
1082 Lex.Lex(); // eat the lsquare.
1083 if (ParseArrayVectorType(Result, false))
1086 case lltok::less: // Either vector or packed struct.
1087 // TypeRec ::= '<' ... '>'
1089 if (Lex.getKind() == lltok::lbrace) {
1090 if (ParseStructType(Result, true) ||
1091 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1093 } else if (ParseArrayVectorType(Result, true))
1096 case lltok::LocalVar:
1097 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1099 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1102 Result = Context.getOpaqueType();
1103 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1104 std::make_pair(Result,
1106 M->addTypeName(Lex.getStrVal(), Result.get());
1111 case lltok::LocalVarID:
1113 if (Lex.getUIntVal() < NumberedTypes.size())
1114 Result = NumberedTypes[Lex.getUIntVal()];
1116 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1117 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1118 if (I != ForwardRefTypeIDs.end())
1119 Result = I->second.first;
1121 Result = Context.getOpaqueType();
1122 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1123 std::make_pair(Result,
1129 case lltok::backslash: {
1130 // TypeRec ::= '\' 4
1133 if (ParseUInt32(Val)) return true;
1134 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1135 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1141 // Parse the type suffixes.
1143 switch (Lex.getKind()) {
1145 default: return false;
1147 // TypeRec ::= TypeRec '*'
1149 if (Result.get() == Type::LabelTy)
1150 return TokError("basic block pointers are invalid");
1151 if (Result.get() == Type::VoidTy)
1152 return TokError("pointers to void are invalid; use i8* instead");
1153 if (!PointerType::isValidElementType(Result.get()))
1154 return TokError("pointer to this type is invalid");
1155 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1159 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1160 case lltok::kw_addrspace: {
1161 if (Result.get() == Type::LabelTy)
1162 return TokError("basic block pointers are invalid");
1163 if (Result.get() == Type::VoidTy)
1164 return TokError("pointers to void are invalid; use i8* instead");
1165 if (!PointerType::isValidElementType(Result.get()))
1166 return TokError("pointer to this type is invalid");
1168 if (ParseOptionalAddrSpace(AddrSpace) ||
1169 ParseToken(lltok::star, "expected '*' in address space"))
1172 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1176 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1178 if (ParseFunctionType(Result))
1185 /// ParseParameterList
1187 /// ::= '(' Arg (',' Arg)* ')'
1189 /// ::= Type OptionalAttributes Value OptionalAttributes
1190 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1191 PerFunctionState &PFS) {
1192 if (ParseToken(lltok::lparen, "expected '(' in call"))
1195 while (Lex.getKind() != lltok::rparen) {
1196 // If this isn't the first argument, we need a comma.
1197 if (!ArgList.empty() &&
1198 ParseToken(lltok::comma, "expected ',' in argument list"))
1201 // Parse the argument.
1203 PATypeHolder ArgTy(Type::VoidTy);
1204 unsigned ArgAttrs1, ArgAttrs2;
1206 if (ParseType(ArgTy, ArgLoc) ||
1207 ParseOptionalAttrs(ArgAttrs1, 0) ||
1208 ParseValue(ArgTy, V, PFS) ||
1209 // FIXME: Should not allow attributes after the argument, remove this in
1211 ParseOptionalAttrs(ArgAttrs2, 3))
1213 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1216 Lex.Lex(); // Lex the ')'.
1222 /// ParseArgumentList - Parse the argument list for a function type or function
1223 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1224 /// ::= '(' ArgTypeListI ')'
1228 /// ::= ArgTypeList ',' '...'
1229 /// ::= ArgType (',' ArgType)*
1231 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1232 bool &isVarArg, bool inType) {
1234 assert(Lex.getKind() == lltok::lparen);
1235 Lex.Lex(); // eat the (.
1237 if (Lex.getKind() == lltok::rparen) {
1239 } else if (Lex.getKind() == lltok::dotdotdot) {
1243 LocTy TypeLoc = Lex.getLoc();
1244 PATypeHolder ArgTy(Type::VoidTy);
1248 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1249 // types (such as a function returning a pointer to itself). If parsing a
1250 // function prototype, we require fully resolved types.
1251 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1252 ParseOptionalAttrs(Attrs, 0)) return true;
1254 if (ArgTy == Type::VoidTy)
1255 return Error(TypeLoc, "argument can not have void type");
1257 if (Lex.getKind() == lltok::LocalVar ||
1258 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1259 Name = Lex.getStrVal();
1263 if (!FunctionType::isValidArgumentType(ArgTy))
1264 return Error(TypeLoc, "invalid type for function argument");
1266 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1268 while (EatIfPresent(lltok::comma)) {
1269 // Handle ... at end of arg list.
1270 if (EatIfPresent(lltok::dotdotdot)) {
1275 // Otherwise must be an argument type.
1276 TypeLoc = Lex.getLoc();
1277 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1278 ParseOptionalAttrs(Attrs, 0)) return true;
1280 if (ArgTy == Type::VoidTy)
1281 return Error(TypeLoc, "argument can not have void type");
1283 if (Lex.getKind() == lltok::LocalVar ||
1284 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1285 Name = Lex.getStrVal();
1291 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1292 return Error(TypeLoc, "invalid type for function argument");
1294 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1298 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1301 /// ParseFunctionType
1302 /// ::= Type ArgumentList OptionalAttrs
1303 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1304 assert(Lex.getKind() == lltok::lparen);
1306 if (!FunctionType::isValidReturnType(Result))
1307 return TokError("invalid function return type");
1309 std::vector<ArgInfo> ArgList;
1312 if (ParseArgumentList(ArgList, isVarArg, true) ||
1313 // FIXME: Allow, but ignore attributes on function types!
1314 // FIXME: Remove in LLVM 3.0
1315 ParseOptionalAttrs(Attrs, 2))
1318 // Reject names on the arguments lists.
1319 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1320 if (!ArgList[i].Name.empty())
1321 return Error(ArgList[i].Loc, "argument name invalid in function type");
1322 if (!ArgList[i].Attrs != 0) {
1323 // Allow but ignore attributes on function types; this permits
1325 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1329 std::vector<const Type*> ArgListTy;
1330 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1331 ArgListTy.push_back(ArgList[i].Type);
1333 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1334 ArgListTy, isVarArg));
1338 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1341 /// ::= '{' TypeRec (',' TypeRec)* '}'
1342 /// ::= '<' '{' '}' '>'
1343 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1344 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1345 assert(Lex.getKind() == lltok::lbrace);
1346 Lex.Lex(); // Consume the '{'
1348 if (EatIfPresent(lltok::rbrace)) {
1349 Result = Context.getStructType(Packed);
1353 std::vector<PATypeHolder> ParamsList;
1354 LocTy EltTyLoc = Lex.getLoc();
1355 if (ParseTypeRec(Result)) return true;
1356 ParamsList.push_back(Result);
1358 if (Result == Type::VoidTy)
1359 return Error(EltTyLoc, "struct element can not have void type");
1360 if (!StructType::isValidElementType(Result))
1361 return Error(EltTyLoc, "invalid element type for struct");
1363 while (EatIfPresent(lltok::comma)) {
1364 EltTyLoc = Lex.getLoc();
1365 if (ParseTypeRec(Result)) return true;
1367 if (Result == Type::VoidTy)
1368 return Error(EltTyLoc, "struct element can not have void type");
1369 if (!StructType::isValidElementType(Result))
1370 return Error(EltTyLoc, "invalid element type for struct");
1372 ParamsList.push_back(Result);
1375 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1378 std::vector<const Type*> ParamsListTy;
1379 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1380 ParamsListTy.push_back(ParamsList[i].get());
1381 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1385 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1386 /// token has already been consumed.
1388 /// ::= '[' APSINTVAL 'x' Types ']'
1389 /// ::= '<' APSINTVAL 'x' Types '>'
1390 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1391 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1392 Lex.getAPSIntVal().getBitWidth() > 64)
1393 return TokError("expected number in address space");
1395 LocTy SizeLoc = Lex.getLoc();
1396 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1399 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1402 LocTy TypeLoc = Lex.getLoc();
1403 PATypeHolder EltTy(Type::VoidTy);
1404 if (ParseTypeRec(EltTy)) return true;
1406 if (EltTy == Type::VoidTy)
1407 return Error(TypeLoc, "array and vector element type cannot be void");
1409 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1410 "expected end of sequential type"))
1415 return Error(SizeLoc, "zero element vector is illegal");
1416 if ((unsigned)Size != Size)
1417 return Error(SizeLoc, "size too large for vector");
1418 if (!VectorType::isValidElementType(EltTy))
1419 return Error(TypeLoc, "vector element type must be fp or integer");
1420 Result = Context.getVectorType(EltTy, unsigned(Size));
1422 if (!ArrayType::isValidElementType(EltTy))
1423 return Error(TypeLoc, "invalid array element type");
1424 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1429 //===----------------------------------------------------------------------===//
1430 // Function Semantic Analysis.
1431 //===----------------------------------------------------------------------===//
1433 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1436 // Insert unnamed arguments into the NumberedVals list.
1437 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1440 NumberedVals.push_back(AI);
1443 LLParser::PerFunctionState::~PerFunctionState() {
1444 // If there were any forward referenced non-basicblock values, delete them.
1445 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1446 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1447 if (!isa<BasicBlock>(I->second.first)) {
1448 I->second.first->replaceAllUsesWith(
1449 P.getContext().getUndef(I->second.first->getType()));
1450 delete I->second.first;
1451 I->second.first = 0;
1454 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1455 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1456 if (!isa<BasicBlock>(I->second.first)) {
1457 I->second.first->replaceAllUsesWith(
1458 P.getContext().getUndef(I->second.first->getType()));
1459 delete I->second.first;
1460 I->second.first = 0;
1464 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1465 if (!ForwardRefVals.empty())
1466 return P.Error(ForwardRefVals.begin()->second.second,
1467 "use of undefined value '%" + ForwardRefVals.begin()->first +
1469 if (!ForwardRefValIDs.empty())
1470 return P.Error(ForwardRefValIDs.begin()->second.second,
1471 "use of undefined value '%" +
1472 utostr(ForwardRefValIDs.begin()->first) + "'");
1477 /// GetVal - Get a value with the specified name or ID, creating a
1478 /// forward reference record if needed. This can return null if the value
1479 /// exists but does not have the right type.
1480 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1481 const Type *Ty, LocTy Loc) {
1482 // Look this name up in the normal function symbol table.
1483 Value *Val = F.getValueSymbolTable().lookup(Name);
1485 // If this is a forward reference for the value, see if we already created a
1486 // forward ref record.
1488 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1489 I = ForwardRefVals.find(Name);
1490 if (I != ForwardRefVals.end())
1491 Val = I->second.first;
1494 // If we have the value in the symbol table or fwd-ref table, return it.
1496 if (Val->getType() == Ty) return Val;
1497 if (Ty == Type::LabelTy)
1498 P.Error(Loc, "'%" + Name + "' is not a basic block");
1500 P.Error(Loc, "'%" + Name + "' defined with type '" +
1501 Val->getType()->getDescription() + "'");
1505 // Don't make placeholders with invalid type.
1506 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1507 P.Error(Loc, "invalid use of a non-first-class type");
1511 // Otherwise, create a new forward reference for this value and remember it.
1513 if (Ty == Type::LabelTy)
1514 FwdVal = BasicBlock::Create(Name, &F);
1516 FwdVal = new Argument(Ty, Name);
1518 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1522 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1524 // Look this name up in the normal function symbol table.
1525 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1527 // If this is a forward reference for the value, see if we already created a
1528 // forward ref record.
1530 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1531 I = ForwardRefValIDs.find(ID);
1532 if (I != ForwardRefValIDs.end())
1533 Val = I->second.first;
1536 // If we have the value in the symbol table or fwd-ref table, return it.
1538 if (Val->getType() == Ty) return Val;
1539 if (Ty == Type::LabelTy)
1540 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1542 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1543 Val->getType()->getDescription() + "'");
1547 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1548 P.Error(Loc, "invalid use of a non-first-class type");
1552 // Otherwise, create a new forward reference for this value and remember it.
1554 if (Ty == Type::LabelTy)
1555 FwdVal = BasicBlock::Create("", &F);
1557 FwdVal = new Argument(Ty);
1559 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1563 /// SetInstName - After an instruction is parsed and inserted into its
1564 /// basic block, this installs its name.
1565 bool LLParser::PerFunctionState::SetInstName(int NameID,
1566 const std::string &NameStr,
1567 LocTy NameLoc, Instruction *Inst) {
1568 // If this instruction has void type, it cannot have a name or ID specified.
1569 if (Inst->getType() == Type::VoidTy) {
1570 if (NameID != -1 || !NameStr.empty())
1571 return P.Error(NameLoc, "instructions returning void cannot have a name");
1575 // If this was a numbered instruction, verify that the instruction is the
1576 // expected value and resolve any forward references.
1577 if (NameStr.empty()) {
1578 // If neither a name nor an ID was specified, just use the next ID.
1580 NameID = NumberedVals.size();
1582 if (unsigned(NameID) != NumberedVals.size())
1583 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1584 utostr(NumberedVals.size()) + "'");
1586 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1587 ForwardRefValIDs.find(NameID);
1588 if (FI != ForwardRefValIDs.end()) {
1589 if (FI->second.first->getType() != Inst->getType())
1590 return P.Error(NameLoc, "instruction forward referenced with type '" +
1591 FI->second.first->getType()->getDescription() + "'");
1592 FI->second.first->replaceAllUsesWith(Inst);
1593 ForwardRefValIDs.erase(FI);
1596 NumberedVals.push_back(Inst);
1600 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1601 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1602 FI = ForwardRefVals.find(NameStr);
1603 if (FI != ForwardRefVals.end()) {
1604 if (FI->second.first->getType() != Inst->getType())
1605 return P.Error(NameLoc, "instruction forward referenced with type '" +
1606 FI->second.first->getType()->getDescription() + "'");
1607 FI->second.first->replaceAllUsesWith(Inst);
1608 ForwardRefVals.erase(FI);
1611 // Set the name on the instruction.
1612 Inst->setName(NameStr);
1614 if (Inst->getNameStr() != NameStr)
1615 return P.Error(NameLoc, "multiple definition of local value named '" +
1620 /// GetBB - Get a basic block with the specified name or ID, creating a
1621 /// forward reference record if needed.
1622 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1624 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1627 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1628 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1631 /// DefineBB - Define the specified basic block, which is either named or
1632 /// unnamed. If there is an error, this returns null otherwise it returns
1633 /// the block being defined.
1634 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1638 BB = GetBB(NumberedVals.size(), Loc);
1640 BB = GetBB(Name, Loc);
1641 if (BB == 0) return 0; // Already diagnosed error.
1643 // Move the block to the end of the function. Forward ref'd blocks are
1644 // inserted wherever they happen to be referenced.
1645 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1647 // Remove the block from forward ref sets.
1649 ForwardRefValIDs.erase(NumberedVals.size());
1650 NumberedVals.push_back(BB);
1652 // BB forward references are already in the function symbol table.
1653 ForwardRefVals.erase(Name);
1659 //===----------------------------------------------------------------------===//
1661 //===----------------------------------------------------------------------===//
1663 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1664 /// type implied. For example, if we parse "4" we don't know what integer type
1665 /// it has. The value will later be combined with its type and checked for
1667 bool LLParser::ParseValID(ValID &ID) {
1668 ID.Loc = Lex.getLoc();
1669 switch (Lex.getKind()) {
1670 default: return TokError("expected value token");
1671 case lltok::GlobalID: // @42
1672 ID.UIntVal = Lex.getUIntVal();
1673 ID.Kind = ValID::t_GlobalID;
1675 case lltok::GlobalVar: // @foo
1676 ID.StrVal = Lex.getStrVal();
1677 ID.Kind = ValID::t_GlobalName;
1679 case lltok::LocalVarID: // %42
1680 ID.UIntVal = Lex.getUIntVal();
1681 ID.Kind = ValID::t_LocalID;
1683 case lltok::LocalVar: // %foo
1684 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1685 ID.StrVal = Lex.getStrVal();
1686 ID.Kind = ValID::t_LocalName;
1688 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1689 ID.Kind = ValID::t_Metadata;
1691 if (Lex.getKind() == lltok::lbrace) {
1692 SmallVector<Value*, 16> Elts;
1693 if (ParseMDNodeVector(Elts) ||
1694 ParseToken(lltok::rbrace, "expected end of metadata node"))
1697 ID.MetadataVal = Context.getMDNode(Elts.data(), Elts.size());
1701 // Standalone metadata reference
1702 // !{ ..., !42, ... }
1703 if (!ParseMDNode(ID.MetadataVal))
1707 // ::= '!' STRINGCONSTANT
1708 if (ParseMDString(ID.MetadataVal)) return true;
1709 ID.Kind = ValID::t_Metadata;
1713 ID.APSIntVal = Lex.getAPSIntVal();
1714 ID.Kind = ValID::t_APSInt;
1716 case lltok::APFloat:
1717 ID.APFloatVal = Lex.getAPFloatVal();
1718 ID.Kind = ValID::t_APFloat;
1720 case lltok::kw_true:
1721 ID.ConstantVal = Context.getTrue();
1722 ID.Kind = ValID::t_Constant;
1724 case lltok::kw_false:
1725 ID.ConstantVal = Context.getFalse();
1726 ID.Kind = ValID::t_Constant;
1728 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1729 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1730 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1732 case lltok::lbrace: {
1733 // ValID ::= '{' ConstVector '}'
1735 SmallVector<Constant*, 16> Elts;
1736 if (ParseGlobalValueVector(Elts) ||
1737 ParseToken(lltok::rbrace, "expected end of struct constant"))
1740 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
1741 ID.Kind = ValID::t_Constant;
1745 // ValID ::= '<' ConstVector '>' --> Vector.
1746 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1748 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1750 SmallVector<Constant*, 16> Elts;
1751 LocTy FirstEltLoc = Lex.getLoc();
1752 if (ParseGlobalValueVector(Elts) ||
1754 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1755 ParseToken(lltok::greater, "expected end of constant"))
1758 if (isPackedStruct) {
1760 Context.getConstantStruct(Elts.data(), Elts.size(), true);
1761 ID.Kind = ValID::t_Constant;
1766 return Error(ID.Loc, "constant vector must not be empty");
1768 if (!Elts[0]->getType()->isInteger() &&
1769 !Elts[0]->getType()->isFloatingPoint())
1770 return Error(FirstEltLoc,
1771 "vector elements must have integer or floating point type");
1773 // Verify that all the vector elements have the same type.
1774 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1775 if (Elts[i]->getType() != Elts[0]->getType())
1776 return Error(FirstEltLoc,
1777 "vector element #" + utostr(i) +
1778 " is not of type '" + Elts[0]->getType()->getDescription());
1780 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
1781 ID.Kind = ValID::t_Constant;
1784 case lltok::lsquare: { // Array Constant
1786 SmallVector<Constant*, 16> Elts;
1787 LocTy FirstEltLoc = Lex.getLoc();
1788 if (ParseGlobalValueVector(Elts) ||
1789 ParseToken(lltok::rsquare, "expected end of array constant"))
1792 // Handle empty element.
1794 // Use undef instead of an array because it's inconvenient to determine
1795 // the element type at this point, there being no elements to examine.
1796 ID.Kind = ValID::t_EmptyArray;
1800 if (!Elts[0]->getType()->isFirstClassType())
1801 return Error(FirstEltLoc, "invalid array element type: " +
1802 Elts[0]->getType()->getDescription());
1804 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1806 // Verify all elements are correct type!
1807 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1808 if (Elts[i]->getType() != Elts[0]->getType())
1809 return Error(FirstEltLoc,
1810 "array element #" + utostr(i) +
1811 " is not of type '" +Elts[0]->getType()->getDescription());
1814 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
1815 ID.Kind = ValID::t_Constant;
1818 case lltok::kw_c: // c "foo"
1820 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
1821 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1822 ID.Kind = ValID::t_Constant;
1825 case lltok::kw_asm: {
1826 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1829 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1830 ParseStringConstant(ID.StrVal) ||
1831 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1832 ParseToken(lltok::StringConstant, "expected constraint string"))
1834 ID.StrVal2 = Lex.getStrVal();
1835 ID.UIntVal = HasSideEffect;
1836 ID.Kind = ValID::t_InlineAsm;
1840 case lltok::kw_trunc:
1841 case lltok::kw_zext:
1842 case lltok::kw_sext:
1843 case lltok::kw_fptrunc:
1844 case lltok::kw_fpext:
1845 case lltok::kw_bitcast:
1846 case lltok::kw_uitofp:
1847 case lltok::kw_sitofp:
1848 case lltok::kw_fptoui:
1849 case lltok::kw_fptosi:
1850 case lltok::kw_inttoptr:
1851 case lltok::kw_ptrtoint: {
1852 unsigned Opc = Lex.getUIntVal();
1853 PATypeHolder DestTy(Type::VoidTy);
1856 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1857 ParseGlobalTypeAndValue(SrcVal) ||
1858 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1859 ParseType(DestTy) ||
1860 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1862 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1863 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1864 SrcVal->getType()->getDescription() + "' to '" +
1865 DestTy->getDescription() + "'");
1866 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1868 ID.Kind = ValID::t_Constant;
1871 case lltok::kw_extractvalue: {
1874 SmallVector<unsigned, 4> Indices;
1875 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1876 ParseGlobalTypeAndValue(Val) ||
1877 ParseIndexList(Indices) ||
1878 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1880 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1881 return Error(ID.Loc, "extractvalue operand must be array or struct");
1882 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1884 return Error(ID.Loc, "invalid indices for extractvalue");
1886 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
1887 ID.Kind = ValID::t_Constant;
1890 case lltok::kw_insertvalue: {
1892 Constant *Val0, *Val1;
1893 SmallVector<unsigned, 4> Indices;
1894 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1895 ParseGlobalTypeAndValue(Val0) ||
1896 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1897 ParseGlobalTypeAndValue(Val1) ||
1898 ParseIndexList(Indices) ||
1899 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1901 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1902 return Error(ID.Loc, "extractvalue operand must be array or struct");
1903 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1905 return Error(ID.Loc, "invalid indices for insertvalue");
1906 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1907 Indices.data(), Indices.size());
1908 ID.Kind = ValID::t_Constant;
1911 case lltok::kw_icmp:
1912 case lltok::kw_fcmp: {
1913 unsigned PredVal, Opc = Lex.getUIntVal();
1914 Constant *Val0, *Val1;
1916 if (ParseCmpPredicate(PredVal, Opc) ||
1917 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1918 ParseGlobalTypeAndValue(Val0) ||
1919 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1920 ParseGlobalTypeAndValue(Val1) ||
1921 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1924 if (Val0->getType() != Val1->getType())
1925 return Error(ID.Loc, "compare operands must have the same type");
1927 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1929 if (Opc == Instruction::FCmp) {
1930 if (!Val0->getType()->isFPOrFPVector())
1931 return Error(ID.Loc, "fcmp requires floating point operands");
1932 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
1934 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
1935 if (!Val0->getType()->isIntOrIntVector() &&
1936 !isa<PointerType>(Val0->getType()))
1937 return Error(ID.Loc, "icmp requires pointer or integer operands");
1938 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
1940 ID.Kind = ValID::t_Constant;
1944 // Binary Operators.
1946 case lltok::kw_fadd:
1948 case lltok::kw_fsub:
1950 case lltok::kw_fmul:
1951 case lltok::kw_udiv:
1952 case lltok::kw_sdiv:
1953 case lltok::kw_fdiv:
1954 case lltok::kw_urem:
1955 case lltok::kw_srem:
1956 case lltok::kw_frem: {
1957 unsigned Opc = Lex.getUIntVal();
1958 Constant *Val0, *Val1;
1960 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1961 ParseGlobalTypeAndValue(Val0) ||
1962 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1963 ParseGlobalTypeAndValue(Val1) ||
1964 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1966 if (Val0->getType() != Val1->getType())
1967 return Error(ID.Loc, "operands of constexpr must have same type");
1968 if (!Val0->getType()->isIntOrIntVector() &&
1969 !Val0->getType()->isFPOrFPVector())
1970 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1971 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1972 ID.Kind = ValID::t_Constant;
1976 // Logical Operations
1978 case lltok::kw_lshr:
1979 case lltok::kw_ashr:
1982 case lltok::kw_xor: {
1983 unsigned Opc = Lex.getUIntVal();
1984 Constant *Val0, *Val1;
1986 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1987 ParseGlobalTypeAndValue(Val0) ||
1988 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1989 ParseGlobalTypeAndValue(Val1) ||
1990 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1992 if (Val0->getType() != Val1->getType())
1993 return Error(ID.Loc, "operands of constexpr must have same type");
1994 if (!Val0->getType()->isIntOrIntVector())
1995 return Error(ID.Loc,
1996 "constexpr requires integer or integer vector operands");
1997 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1998 ID.Kind = ValID::t_Constant;
2002 case lltok::kw_getelementptr:
2003 case lltok::kw_shufflevector:
2004 case lltok::kw_insertelement:
2005 case lltok::kw_extractelement:
2006 case lltok::kw_select: {
2007 unsigned Opc = Lex.getUIntVal();
2008 SmallVector<Constant*, 16> Elts;
2010 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2011 ParseGlobalValueVector(Elts) ||
2012 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2015 if (Opc == Instruction::GetElementPtr) {
2016 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2017 return Error(ID.Loc, "getelementptr requires pointer operand");
2019 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2020 (Value**)(Elts.data() + 1),
2022 return Error(ID.Loc, "invalid indices for getelementptr");
2023 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
2024 Elts.data() + 1, Elts.size() - 1);
2025 } else if (Opc == Instruction::Select) {
2026 if (Elts.size() != 3)
2027 return Error(ID.Loc, "expected three operands to select");
2028 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2030 return Error(ID.Loc, Reason);
2031 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
2032 } else if (Opc == Instruction::ShuffleVector) {
2033 if (Elts.size() != 3)
2034 return Error(ID.Loc, "expected three operands to shufflevector");
2035 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2036 return Error(ID.Loc, "invalid operands to shufflevector");
2038 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
2039 } else if (Opc == Instruction::ExtractElement) {
2040 if (Elts.size() != 2)
2041 return Error(ID.Loc, "expected two operands to extractelement");
2042 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2043 return Error(ID.Loc, "invalid extractelement operands");
2044 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
2046 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2047 if (Elts.size() != 3)
2048 return Error(ID.Loc, "expected three operands to insertelement");
2049 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2050 return Error(ID.Loc, "invalid insertelement operands");
2052 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
2055 ID.Kind = ValID::t_Constant;
2058 case lltok::kw_nuw: {
2060 bool AlsoSigned = EatIfPresent(lltok::kw_nsw);
2061 if (Lex.getKind() != lltok::kw_add &&
2062 Lex.getKind() != lltok::kw_sub &&
2063 Lex.getKind() != lltok::kw_mul)
2064 return TokError("expected 'add', 'sub', or 'mul'");
2065 bool Result = LLParser::ParseValID(ID);
2067 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2068 ->setHasNoUnsignedOverflow(true);
2070 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2071 ->setHasNoSignedOverflow(true);
2075 case lltok::kw_nsw: {
2077 bool AlsoUnsigned = EatIfPresent(lltok::kw_nuw);
2078 if (Lex.getKind() != lltok::kw_add &&
2079 Lex.getKind() != lltok::kw_sub &&
2080 Lex.getKind() != lltok::kw_mul)
2081 return TokError("expected 'add', 'sub', or 'mul'");
2082 bool Result = LLParser::ParseValID(ID);
2084 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2085 ->setHasNoSignedOverflow(true);
2087 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2088 ->setHasNoUnsignedOverflow(true);
2092 case lltok::kw_exact: {
2094 if (Lex.getKind() != lltok::kw_sdiv)
2095 return TokError("expected 'sdiv'");
2096 bool Result = LLParser::ParseValID(ID);
2098 cast<SDivOperator>(ID.ConstantVal)->setIsExact(true);
2107 /// ParseGlobalValue - Parse a global value with the specified type.
2108 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2111 return ParseValID(ID) ||
2112 ConvertGlobalValIDToValue(Ty, ID, V);
2115 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2117 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2119 if (isa<FunctionType>(Ty))
2120 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2123 default: llvm_unreachable("Unknown ValID!");
2124 case ValID::t_Metadata:
2125 return Error(ID.Loc, "invalid use of metadata");
2126 case ValID::t_LocalID:
2127 case ValID::t_LocalName:
2128 return Error(ID.Loc, "invalid use of function-local name");
2129 case ValID::t_InlineAsm:
2130 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2131 case ValID::t_GlobalName:
2132 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2134 case ValID::t_GlobalID:
2135 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2137 case ValID::t_APSInt:
2138 if (!isa<IntegerType>(Ty))
2139 return Error(ID.Loc, "integer constant must have integer type");
2140 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2141 V = Context.getConstantInt(ID.APSIntVal);
2143 case ValID::t_APFloat:
2144 if (!Ty->isFloatingPoint() ||
2145 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2146 return Error(ID.Loc, "floating point constant invalid for type");
2148 // The lexer has no type info, so builds all float and double FP constants
2149 // as double. Fix this here. Long double does not need this.
2150 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2151 Ty == Type::FloatTy) {
2153 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2156 V = Context.getConstantFP(ID.APFloatVal);
2158 if (V->getType() != Ty)
2159 return Error(ID.Loc, "floating point constant does not have type '" +
2160 Ty->getDescription() + "'");
2164 if (!isa<PointerType>(Ty))
2165 return Error(ID.Loc, "null must be a pointer type");
2166 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2168 case ValID::t_Undef:
2169 // FIXME: LabelTy should not be a first-class type.
2170 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2171 !isa<OpaqueType>(Ty))
2172 return Error(ID.Loc, "invalid type for undef constant");
2173 V = Context.getUndef(Ty);
2175 case ValID::t_EmptyArray:
2176 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2177 return Error(ID.Loc, "invalid empty array initializer");
2178 V = Context.getUndef(Ty);
2181 // FIXME: LabelTy should not be a first-class type.
2182 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2183 return Error(ID.Loc, "invalid type for null constant");
2184 V = Context.getNullValue(Ty);
2186 case ValID::t_Constant:
2187 if (ID.ConstantVal->getType() != Ty)
2188 return Error(ID.Loc, "constant expression type mismatch");
2194 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2195 PATypeHolder Type(Type::VoidTy);
2196 return ParseType(Type) ||
2197 ParseGlobalValue(Type, V);
2200 /// ParseGlobalValueVector
2202 /// ::= TypeAndValue (',' TypeAndValue)*
2203 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2205 if (Lex.getKind() == lltok::rbrace ||
2206 Lex.getKind() == lltok::rsquare ||
2207 Lex.getKind() == lltok::greater ||
2208 Lex.getKind() == lltok::rparen)
2212 if (ParseGlobalTypeAndValue(C)) return true;
2215 while (EatIfPresent(lltok::comma)) {
2216 if (ParseGlobalTypeAndValue(C)) return true;
2224 //===----------------------------------------------------------------------===//
2225 // Function Parsing.
2226 //===----------------------------------------------------------------------===//
2228 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2229 PerFunctionState &PFS) {
2230 if (ID.Kind == ValID::t_LocalID)
2231 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2232 else if (ID.Kind == ValID::t_LocalName)
2233 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2234 else if (ID.Kind == ValID::t_InlineAsm) {
2235 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2236 const FunctionType *FTy =
2237 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2238 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2239 return Error(ID.Loc, "invalid type for inline asm constraint string");
2240 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2242 } else if (ID.Kind == ValID::t_Metadata) {
2246 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2254 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2257 return ParseValID(ID) ||
2258 ConvertValIDToValue(Ty, ID, V, PFS);
2261 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2262 PATypeHolder T(Type::VoidTy);
2263 return ParseType(T) ||
2264 ParseValue(T, V, PFS);
2268 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2269 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2270 /// OptionalAlign OptGC
2271 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2272 // Parse the linkage.
2273 LocTy LinkageLoc = Lex.getLoc();
2276 unsigned Visibility, CC, RetAttrs;
2277 PATypeHolder RetType(Type::VoidTy);
2278 LocTy RetTypeLoc = Lex.getLoc();
2279 if (ParseOptionalLinkage(Linkage) ||
2280 ParseOptionalVisibility(Visibility) ||
2281 ParseOptionalCallingConv(CC) ||
2282 ParseOptionalAttrs(RetAttrs, 1) ||
2283 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2286 // Verify that the linkage is ok.
2287 switch ((GlobalValue::LinkageTypes)Linkage) {
2288 case GlobalValue::ExternalLinkage:
2289 break; // always ok.
2290 case GlobalValue::DLLImportLinkage:
2291 case GlobalValue::ExternalWeakLinkage:
2293 return Error(LinkageLoc, "invalid linkage for function definition");
2295 case GlobalValue::PrivateLinkage:
2296 case GlobalValue::LinkerPrivateLinkage:
2297 case GlobalValue::InternalLinkage:
2298 case GlobalValue::AvailableExternallyLinkage:
2299 case GlobalValue::LinkOnceAnyLinkage:
2300 case GlobalValue::LinkOnceODRLinkage:
2301 case GlobalValue::WeakAnyLinkage:
2302 case GlobalValue::WeakODRLinkage:
2303 case GlobalValue::DLLExportLinkage:
2305 return Error(LinkageLoc, "invalid linkage for function declaration");
2307 case GlobalValue::AppendingLinkage:
2308 case GlobalValue::GhostLinkage:
2309 case GlobalValue::CommonLinkage:
2310 return Error(LinkageLoc, "invalid function linkage type");
2313 if (!FunctionType::isValidReturnType(RetType) ||
2314 isa<OpaqueType>(RetType))
2315 return Error(RetTypeLoc, "invalid function return type");
2317 LocTy NameLoc = Lex.getLoc();
2319 std::string FunctionName;
2320 if (Lex.getKind() == lltok::GlobalVar) {
2321 FunctionName = Lex.getStrVal();
2322 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2323 unsigned NameID = Lex.getUIntVal();
2325 if (NameID != NumberedVals.size())
2326 return TokError("function expected to be numbered '%" +
2327 utostr(NumberedVals.size()) + "'");
2329 return TokError("expected function name");
2334 if (Lex.getKind() != lltok::lparen)
2335 return TokError("expected '(' in function argument list");
2337 std::vector<ArgInfo> ArgList;
2340 std::string Section;
2344 if (ParseArgumentList(ArgList, isVarArg, false) ||
2345 ParseOptionalAttrs(FuncAttrs, 2) ||
2346 (EatIfPresent(lltok::kw_section) &&
2347 ParseStringConstant(Section)) ||
2348 ParseOptionalAlignment(Alignment) ||
2349 (EatIfPresent(lltok::kw_gc) &&
2350 ParseStringConstant(GC)))
2353 // If the alignment was parsed as an attribute, move to the alignment field.
2354 if (FuncAttrs & Attribute::Alignment) {
2355 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2356 FuncAttrs &= ~Attribute::Alignment;
2359 // Okay, if we got here, the function is syntactically valid. Convert types
2360 // and do semantic checks.
2361 std::vector<const Type*> ParamTypeList;
2362 SmallVector<AttributeWithIndex, 8> Attrs;
2363 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2365 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2366 if (FuncAttrs & ObsoleteFuncAttrs) {
2367 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2368 FuncAttrs &= ~ObsoleteFuncAttrs;
2371 if (RetAttrs != Attribute::None)
2372 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2374 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2375 ParamTypeList.push_back(ArgList[i].Type);
2376 if (ArgList[i].Attrs != Attribute::None)
2377 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2380 if (FuncAttrs != Attribute::None)
2381 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2383 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2385 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2386 RetType != Type::VoidTy)
2387 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2389 const FunctionType *FT =
2390 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2391 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2394 if (!FunctionName.empty()) {
2395 // If this was a definition of a forward reference, remove the definition
2396 // from the forward reference table and fill in the forward ref.
2397 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2398 ForwardRefVals.find(FunctionName);
2399 if (FRVI != ForwardRefVals.end()) {
2400 Fn = M->getFunction(FunctionName);
2401 ForwardRefVals.erase(FRVI);
2402 } else if ((Fn = M->getFunction(FunctionName))) {
2403 // If this function already exists in the symbol table, then it is
2404 // multiply defined. We accept a few cases for old backwards compat.
2405 // FIXME: Remove this stuff for LLVM 3.0.
2406 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2407 (!Fn->isDeclaration() && isDefine)) {
2408 // If the redefinition has different type or different attributes,
2409 // reject it. If both have bodies, reject it.
2410 return Error(NameLoc, "invalid redefinition of function '" +
2411 FunctionName + "'");
2412 } else if (Fn->isDeclaration()) {
2413 // Make sure to strip off any argument names so we can't get conflicts.
2414 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2420 } else if (FunctionName.empty()) {
2421 // If this is a definition of a forward referenced function, make sure the
2423 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2424 = ForwardRefValIDs.find(NumberedVals.size());
2425 if (I != ForwardRefValIDs.end()) {
2426 Fn = cast<Function>(I->second.first);
2427 if (Fn->getType() != PFT)
2428 return Error(NameLoc, "type of definition and forward reference of '@" +
2429 utostr(NumberedVals.size()) +"' disagree");
2430 ForwardRefValIDs.erase(I);
2435 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2436 else // Move the forward-reference to the correct spot in the module.
2437 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2439 if (FunctionName.empty())
2440 NumberedVals.push_back(Fn);
2442 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2443 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2444 Fn->setCallingConv(CC);
2445 Fn->setAttributes(PAL);
2446 Fn->setAlignment(Alignment);
2447 Fn->setSection(Section);
2448 if (!GC.empty()) Fn->setGC(GC.c_str());
2450 // Add all of the arguments we parsed to the function.
2451 Function::arg_iterator ArgIt = Fn->arg_begin();
2452 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2453 // If the argument has a name, insert it into the argument symbol table.
2454 if (ArgList[i].Name.empty()) continue;
2456 // Set the name, if it conflicted, it will be auto-renamed.
2457 ArgIt->setName(ArgList[i].Name);
2459 if (ArgIt->getNameStr() != ArgList[i].Name)
2460 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2461 ArgList[i].Name + "'");
2468 /// ParseFunctionBody
2469 /// ::= '{' BasicBlock+ '}'
2470 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2472 bool LLParser::ParseFunctionBody(Function &Fn) {
2473 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2474 return TokError("expected '{' in function body");
2475 Lex.Lex(); // eat the {.
2477 PerFunctionState PFS(*this, Fn);
2479 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2480 if (ParseBasicBlock(PFS)) return true;
2485 // Verify function is ok.
2486 return PFS.VerifyFunctionComplete();
2490 /// ::= LabelStr? Instruction*
2491 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2492 // If this basic block starts out with a name, remember it.
2494 LocTy NameLoc = Lex.getLoc();
2495 if (Lex.getKind() == lltok::LabelStr) {
2496 Name = Lex.getStrVal();
2500 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2501 if (BB == 0) return true;
2503 std::string NameStr;
2505 // Parse the instructions in this block until we get a terminator.
2508 // This instruction may have three possibilities for a name: a) none
2509 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2510 LocTy NameLoc = Lex.getLoc();
2514 if (Lex.getKind() == lltok::LocalVarID) {
2515 NameID = Lex.getUIntVal();
2517 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2519 } else if (Lex.getKind() == lltok::LocalVar ||
2520 // FIXME: REMOVE IN LLVM 3.0
2521 Lex.getKind() == lltok::StringConstant) {
2522 NameStr = Lex.getStrVal();
2524 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2528 if (ParseInstruction(Inst, BB, PFS)) return true;
2530 BB->getInstList().push_back(Inst);
2532 // Set the name on the instruction.
2533 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2534 } while (!isa<TerminatorInst>(Inst));
2539 //===----------------------------------------------------------------------===//
2540 // Instruction Parsing.
2541 //===----------------------------------------------------------------------===//
2543 /// ParseInstruction - Parse one of the many different instructions.
2545 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2546 PerFunctionState &PFS) {
2547 lltok::Kind Token = Lex.getKind();
2548 if (Token == lltok::Eof)
2549 return TokError("found end of file when expecting more instructions");
2550 LocTy Loc = Lex.getLoc();
2551 unsigned KeywordVal = Lex.getUIntVal();
2552 Lex.Lex(); // Eat the keyword.
2555 default: return Error(Loc, "expected instruction opcode");
2556 // Terminator Instructions.
2557 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2558 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2559 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2560 case lltok::kw_br: return ParseBr(Inst, PFS);
2561 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2562 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2563 // Binary Operators.
2567 // API compatibility: Accept either integer or floating-point types.
2568 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2569 case lltok::kw_fadd:
2570 case lltok::kw_fsub:
2571 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2573 case lltok::kw_udiv:
2574 case lltok::kw_sdiv:
2575 case lltok::kw_urem:
2576 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2577 case lltok::kw_fdiv:
2578 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2580 case lltok::kw_lshr:
2581 case lltok::kw_ashr:
2584 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2585 case lltok::kw_icmp:
2586 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2588 case lltok::kw_trunc:
2589 case lltok::kw_zext:
2590 case lltok::kw_sext:
2591 case lltok::kw_fptrunc:
2592 case lltok::kw_fpext:
2593 case lltok::kw_bitcast:
2594 case lltok::kw_uitofp:
2595 case lltok::kw_sitofp:
2596 case lltok::kw_fptoui:
2597 case lltok::kw_fptosi:
2598 case lltok::kw_inttoptr:
2599 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2601 case lltok::kw_select: return ParseSelect(Inst, PFS);
2602 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2603 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2604 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2605 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2606 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2607 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2608 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2610 case lltok::kw_alloca:
2611 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2612 case lltok::kw_free: return ParseFree(Inst, PFS);
2613 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2614 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2615 case lltok::kw_volatile:
2616 if (EatIfPresent(lltok::kw_load))
2617 return ParseLoad(Inst, PFS, true);
2618 else if (EatIfPresent(lltok::kw_store))
2619 return ParseStore(Inst, PFS, true);
2621 return TokError("expected 'load' or 'store'");
2622 case lltok::kw_nuw: {
2623 bool AlsoSigned = EatIfPresent(lltok::kw_nsw);
2624 if (Lex.getKind() == lltok::kw_add ||
2625 Lex.getKind() == lltok::kw_sub ||
2626 Lex.getKind() == lltok::kw_mul) {
2628 KeywordVal = Lex.getUIntVal();
2629 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2631 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2633 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2637 return TokError("expected 'add', 'sub', or 'mul'");
2639 case lltok::kw_nsw: {
2640 bool AlsoUnsigned = EatIfPresent(lltok::kw_nuw);
2641 if (Lex.getKind() == lltok::kw_add ||
2642 Lex.getKind() == lltok::kw_sub ||
2643 Lex.getKind() == lltok::kw_mul) {
2645 KeywordVal = Lex.getUIntVal();
2646 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2648 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2650 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2654 return TokError("expected 'add', 'sub', or 'mul'");
2656 case lltok::kw_exact:
2657 if (Lex.getKind() == lltok::kw_sdiv) {
2659 KeywordVal = Lex.getUIntVal();
2660 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2662 cast<SDivOperator>(Inst)->setIsExact(true);
2665 return TokError("expected 'udiv'");
2666 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2667 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2668 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2669 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2673 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2674 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2675 if (Opc == Instruction::FCmp) {
2676 switch (Lex.getKind()) {
2677 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2678 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2679 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2680 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2681 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2682 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2683 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2684 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2685 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2686 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2687 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2688 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2689 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2690 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2691 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2692 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2693 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2696 switch (Lex.getKind()) {
2697 default: TokError("expected icmp predicate (e.g. 'eq')");
2698 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2699 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2700 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2701 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2702 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2703 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2704 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2705 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2706 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2707 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2714 //===----------------------------------------------------------------------===//
2715 // Terminator Instructions.
2716 //===----------------------------------------------------------------------===//
2718 /// ParseRet - Parse a return instruction.
2720 /// ::= 'ret' TypeAndValue
2721 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2722 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2723 PerFunctionState &PFS) {
2724 PATypeHolder Ty(Type::VoidTy);
2725 if (ParseType(Ty, true /*void allowed*/)) return true;
2727 if (Ty == Type::VoidTy) {
2728 Inst = ReturnInst::Create();
2733 if (ParseValue(Ty, RV, PFS)) return true;
2735 // The normal case is one return value.
2736 if (Lex.getKind() == lltok::comma) {
2737 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2738 // of 'ret {i32,i32} {i32 1, i32 2}'
2739 SmallVector<Value*, 8> RVs;
2742 while (EatIfPresent(lltok::comma)) {
2743 if (ParseTypeAndValue(RV, PFS)) return true;
2747 RV = Context.getUndef(PFS.getFunction().getReturnType());
2748 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2749 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2750 BB->getInstList().push_back(I);
2754 Inst = ReturnInst::Create(RV);
2760 /// ::= 'br' TypeAndValue
2761 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2762 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2764 Value *Op0, *Op1, *Op2;
2765 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2767 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2768 Inst = BranchInst::Create(BB);
2772 if (Op0->getType() != Type::Int1Ty)
2773 return Error(Loc, "branch condition must have 'i1' type");
2775 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2776 ParseTypeAndValue(Op1, Loc, PFS) ||
2777 ParseToken(lltok::comma, "expected ',' after true destination") ||
2778 ParseTypeAndValue(Op2, Loc2, PFS))
2781 if (!isa<BasicBlock>(Op1))
2782 return Error(Loc, "true destination of branch must be a basic block");
2783 if (!isa<BasicBlock>(Op2))
2784 return Error(Loc2, "true destination of branch must be a basic block");
2786 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2792 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2794 /// ::= (TypeAndValue ',' TypeAndValue)*
2795 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2796 LocTy CondLoc, BBLoc;
2797 Value *Cond, *DefaultBB;
2798 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2799 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2800 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2801 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2804 if (!isa<IntegerType>(Cond->getType()))
2805 return Error(CondLoc, "switch condition must have integer type");
2806 if (!isa<BasicBlock>(DefaultBB))
2807 return Error(BBLoc, "default destination must be a basic block");
2809 // Parse the jump table pairs.
2810 SmallPtrSet<Value*, 32> SeenCases;
2811 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2812 while (Lex.getKind() != lltok::rsquare) {
2813 Value *Constant, *DestBB;
2815 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2816 ParseToken(lltok::comma, "expected ',' after case value") ||
2817 ParseTypeAndValue(DestBB, BBLoc, PFS))
2820 if (!SeenCases.insert(Constant))
2821 return Error(CondLoc, "duplicate case value in switch");
2822 if (!isa<ConstantInt>(Constant))
2823 return Error(CondLoc, "case value is not a constant integer");
2824 if (!isa<BasicBlock>(DestBB))
2825 return Error(BBLoc, "case destination is not a basic block");
2827 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2828 cast<BasicBlock>(DestBB)));
2831 Lex.Lex(); // Eat the ']'.
2833 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2835 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2836 SI->addCase(Table[i].first, Table[i].second);
2842 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2843 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2844 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2845 LocTy CallLoc = Lex.getLoc();
2846 unsigned CC, RetAttrs, FnAttrs;
2847 PATypeHolder RetType(Type::VoidTy);
2850 SmallVector<ParamInfo, 16> ArgList;
2852 Value *NormalBB, *UnwindBB;
2853 if (ParseOptionalCallingConv(CC) ||
2854 ParseOptionalAttrs(RetAttrs, 1) ||
2855 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2856 ParseValID(CalleeID) ||
2857 ParseParameterList(ArgList, PFS) ||
2858 ParseOptionalAttrs(FnAttrs, 2) ||
2859 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2860 ParseTypeAndValue(NormalBB, PFS) ||
2861 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2862 ParseTypeAndValue(UnwindBB, PFS))
2865 if (!isa<BasicBlock>(NormalBB))
2866 return Error(CallLoc, "normal destination is not a basic block");
2867 if (!isa<BasicBlock>(UnwindBB))
2868 return Error(CallLoc, "unwind destination is not a basic block");
2870 // If RetType is a non-function pointer type, then this is the short syntax
2871 // for the call, which means that RetType is just the return type. Infer the
2872 // rest of the function argument types from the arguments that are present.
2873 const PointerType *PFTy = 0;
2874 const FunctionType *Ty = 0;
2875 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2876 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2877 // Pull out the types of all of the arguments...
2878 std::vector<const Type*> ParamTypes;
2879 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2880 ParamTypes.push_back(ArgList[i].V->getType());
2882 if (!FunctionType::isValidReturnType(RetType))
2883 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2885 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2886 PFTy = Context.getPointerTypeUnqual(Ty);
2889 // Look up the callee.
2891 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2893 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2894 // function attributes.
2895 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2896 if (FnAttrs & ObsoleteFuncAttrs) {
2897 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2898 FnAttrs &= ~ObsoleteFuncAttrs;
2901 // Set up the Attributes for the function.
2902 SmallVector<AttributeWithIndex, 8> Attrs;
2903 if (RetAttrs != Attribute::None)
2904 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2906 SmallVector<Value*, 8> Args;
2908 // Loop through FunctionType's arguments and ensure they are specified
2909 // correctly. Also, gather any parameter attributes.
2910 FunctionType::param_iterator I = Ty->param_begin();
2911 FunctionType::param_iterator E = Ty->param_end();
2912 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2913 const Type *ExpectedTy = 0;
2916 } else if (!Ty->isVarArg()) {
2917 return Error(ArgList[i].Loc, "too many arguments specified");
2920 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2921 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2922 ExpectedTy->getDescription() + "'");
2923 Args.push_back(ArgList[i].V);
2924 if (ArgList[i].Attrs != Attribute::None)
2925 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2929 return Error(CallLoc, "not enough parameters specified for call");
2931 if (FnAttrs != Attribute::None)
2932 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2934 // Finish off the Attributes and check them
2935 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2937 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2938 cast<BasicBlock>(UnwindBB),
2939 Args.begin(), Args.end());
2940 II->setCallingConv(CC);
2941 II->setAttributes(PAL);
2948 //===----------------------------------------------------------------------===//
2949 // Binary Operators.
2950 //===----------------------------------------------------------------------===//
2953 /// ::= ArithmeticOps TypeAndValue ',' Value
2955 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2956 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2957 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2958 unsigned Opc, unsigned OperandType) {
2959 LocTy Loc; Value *LHS, *RHS;
2960 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2961 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2962 ParseValue(LHS->getType(), RHS, PFS))
2966 switch (OperandType) {
2967 default: llvm_unreachable("Unknown operand type!");
2968 case 0: // int or FP.
2969 Valid = LHS->getType()->isIntOrIntVector() ||
2970 LHS->getType()->isFPOrFPVector();
2972 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2973 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2977 return Error(Loc, "invalid operand type for instruction");
2979 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2984 /// ::= ArithmeticOps TypeAndValue ',' Value {
2985 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2987 LocTy Loc; Value *LHS, *RHS;
2988 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2989 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2990 ParseValue(LHS->getType(), RHS, PFS))
2993 if (!LHS->getType()->isIntOrIntVector())
2994 return Error(Loc,"instruction requires integer or integer vector operands");
2996 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3002 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3003 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3004 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3006 // Parse the integer/fp comparison predicate.
3010 if (ParseCmpPredicate(Pred, Opc) ||
3011 ParseTypeAndValue(LHS, Loc, PFS) ||
3012 ParseToken(lltok::comma, "expected ',' after compare value") ||
3013 ParseValue(LHS->getType(), RHS, PFS))
3016 if (Opc == Instruction::FCmp) {
3017 if (!LHS->getType()->isFPOrFPVector())
3018 return Error(Loc, "fcmp requires floating point operands");
3019 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3021 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3022 if (!LHS->getType()->isIntOrIntVector() &&
3023 !isa<PointerType>(LHS->getType()))
3024 return Error(Loc, "icmp requires integer operands");
3025 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3030 //===----------------------------------------------------------------------===//
3031 // Other Instructions.
3032 //===----------------------------------------------------------------------===//
3036 /// ::= CastOpc TypeAndValue 'to' Type
3037 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3039 LocTy Loc; Value *Op;
3040 PATypeHolder DestTy(Type::VoidTy);
3041 if (ParseTypeAndValue(Op, Loc, PFS) ||
3042 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3046 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3047 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3048 return Error(Loc, "invalid cast opcode for cast from '" +
3049 Op->getType()->getDescription() + "' to '" +
3050 DestTy->getDescription() + "'");
3052 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3057 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3058 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3060 Value *Op0, *Op1, *Op2;
3061 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3062 ParseToken(lltok::comma, "expected ',' after select condition") ||
3063 ParseTypeAndValue(Op1, PFS) ||
3064 ParseToken(lltok::comma, "expected ',' after select value") ||
3065 ParseTypeAndValue(Op2, PFS))
3068 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3069 return Error(Loc, Reason);
3071 Inst = SelectInst::Create(Op0, Op1, Op2);
3076 /// ::= 'va_arg' TypeAndValue ',' Type
3077 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3079 PATypeHolder EltTy(Type::VoidTy);
3081 if (ParseTypeAndValue(Op, PFS) ||
3082 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3083 ParseType(EltTy, TypeLoc))
3086 if (!EltTy->isFirstClassType())
3087 return Error(TypeLoc, "va_arg requires operand with first class type");
3089 Inst = new VAArgInst(Op, EltTy);
3093 /// ParseExtractElement
3094 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3095 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3098 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3099 ParseToken(lltok::comma, "expected ',' after extract value") ||
3100 ParseTypeAndValue(Op1, PFS))
3103 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3104 return Error(Loc, "invalid extractelement operands");
3106 Inst = new ExtractElementInst(Op0, Op1);
3110 /// ParseInsertElement
3111 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3112 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3114 Value *Op0, *Op1, *Op2;
3115 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3116 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3117 ParseTypeAndValue(Op1, PFS) ||
3118 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3119 ParseTypeAndValue(Op2, PFS))
3122 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3123 return Error(Loc, "invalid insertelement operands");
3125 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3129 /// ParseShuffleVector
3130 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3131 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3133 Value *Op0, *Op1, *Op2;
3134 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3135 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3136 ParseTypeAndValue(Op1, PFS) ||
3137 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3138 ParseTypeAndValue(Op2, PFS))
3141 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3142 return Error(Loc, "invalid extractelement operands");
3144 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3149 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3150 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3151 PATypeHolder Ty(Type::VoidTy);
3153 LocTy TypeLoc = Lex.getLoc();
3155 if (ParseType(Ty) ||
3156 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3157 ParseValue(Ty, Op0, PFS) ||
3158 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3159 ParseValue(Type::LabelTy, Op1, PFS) ||
3160 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3163 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3165 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3167 if (!EatIfPresent(lltok::comma))
3170 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3171 ParseValue(Ty, Op0, PFS) ||
3172 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3173 ParseValue(Type::LabelTy, Op1, PFS) ||
3174 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3178 if (!Ty->isFirstClassType())
3179 return Error(TypeLoc, "phi node must have first class type");
3181 PHINode *PN = PHINode::Create(Ty);
3182 PN->reserveOperandSpace(PHIVals.size());
3183 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3184 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3190 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3191 /// ParameterList OptionalAttrs
3192 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3194 unsigned CC, RetAttrs, FnAttrs;
3195 PATypeHolder RetType(Type::VoidTy);
3198 SmallVector<ParamInfo, 16> ArgList;
3199 LocTy CallLoc = Lex.getLoc();
3201 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3202 ParseOptionalCallingConv(CC) ||
3203 ParseOptionalAttrs(RetAttrs, 1) ||
3204 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3205 ParseValID(CalleeID) ||
3206 ParseParameterList(ArgList, PFS) ||
3207 ParseOptionalAttrs(FnAttrs, 2))
3210 // If RetType is a non-function pointer type, then this is the short syntax
3211 // for the call, which means that RetType is just the return type. Infer the
3212 // rest of the function argument types from the arguments that are present.
3213 const PointerType *PFTy = 0;
3214 const FunctionType *Ty = 0;
3215 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3216 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3217 // Pull out the types of all of the arguments...
3218 std::vector<const Type*> ParamTypes;
3219 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3220 ParamTypes.push_back(ArgList[i].V->getType());
3222 if (!FunctionType::isValidReturnType(RetType))
3223 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3225 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3226 PFTy = Context.getPointerTypeUnqual(Ty);
3229 // Look up the callee.
3231 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3233 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3234 // function attributes.
3235 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3236 if (FnAttrs & ObsoleteFuncAttrs) {
3237 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3238 FnAttrs &= ~ObsoleteFuncAttrs;
3241 // Set up the Attributes for the function.
3242 SmallVector<AttributeWithIndex, 8> Attrs;
3243 if (RetAttrs != Attribute::None)
3244 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3246 SmallVector<Value*, 8> Args;
3248 // Loop through FunctionType's arguments and ensure they are specified
3249 // correctly. Also, gather any parameter attributes.
3250 FunctionType::param_iterator I = Ty->param_begin();
3251 FunctionType::param_iterator E = Ty->param_end();
3252 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3253 const Type *ExpectedTy = 0;
3256 } else if (!Ty->isVarArg()) {
3257 return Error(ArgList[i].Loc, "too many arguments specified");
3260 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3261 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3262 ExpectedTy->getDescription() + "'");
3263 Args.push_back(ArgList[i].V);
3264 if (ArgList[i].Attrs != Attribute::None)
3265 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3269 return Error(CallLoc, "not enough parameters specified for call");
3271 if (FnAttrs != Attribute::None)
3272 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3274 // Finish off the Attributes and check them
3275 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3277 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3278 CI->setTailCall(isTail);
3279 CI->setCallingConv(CC);
3280 CI->setAttributes(PAL);
3285 //===----------------------------------------------------------------------===//
3286 // Memory Instructions.
3287 //===----------------------------------------------------------------------===//
3290 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3291 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3292 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3294 PATypeHolder Ty(Type::VoidTy);
3297 unsigned Alignment = 0;
3298 if (ParseType(Ty)) return true;
3300 if (EatIfPresent(lltok::comma)) {
3301 if (Lex.getKind() == lltok::kw_align) {
3302 if (ParseOptionalAlignment(Alignment)) return true;
3303 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3304 ParseOptionalCommaAlignment(Alignment)) {
3309 if (Size && Size->getType() != Type::Int32Ty)
3310 return Error(SizeLoc, "element count must be i32");
3312 if (Opc == Instruction::Malloc)
3313 Inst = new MallocInst(Ty, Size, Alignment);
3315 Inst = new AllocaInst(Ty, Size, Alignment);
3320 /// ::= 'free' TypeAndValue
3321 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3322 Value *Val; LocTy Loc;
3323 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3324 if (!isa<PointerType>(Val->getType()))
3325 return Error(Loc, "operand to free must be a pointer");
3326 Inst = new FreeInst(Val);
3331 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3332 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3334 Value *Val; LocTy Loc;
3336 if (ParseTypeAndValue(Val, Loc, PFS) ||
3337 ParseOptionalCommaAlignment(Alignment))
3340 if (!isa<PointerType>(Val->getType()) ||
3341 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3342 return Error(Loc, "load operand must be a pointer to a first class type");
3344 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3349 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3350 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3352 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3354 if (ParseTypeAndValue(Val, Loc, PFS) ||
3355 ParseToken(lltok::comma, "expected ',' after store operand") ||
3356 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3357 ParseOptionalCommaAlignment(Alignment))
3360 if (!isa<PointerType>(Ptr->getType()))
3361 return Error(PtrLoc, "store operand must be a pointer");
3362 if (!Val->getType()->isFirstClassType())
3363 return Error(Loc, "store operand must be a first class value");
3364 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3365 return Error(Loc, "stored value and pointer type do not match");
3367 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3372 /// ::= 'getresult' TypeAndValue ',' i32
3373 /// FIXME: Remove support for getresult in LLVM 3.0
3374 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3375 Value *Val; LocTy ValLoc, EltLoc;
3377 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3378 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3379 ParseUInt32(Element, EltLoc))
3382 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3383 return Error(ValLoc, "getresult inst requires an aggregate operand");
3384 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3385 return Error(EltLoc, "invalid getresult index for value");
3386 Inst = ExtractValueInst::Create(Val, Element);
3390 /// ParseGetElementPtr
3391 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3392 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3393 Value *Ptr, *Val; LocTy Loc, EltLoc;
3394 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3396 if (!isa<PointerType>(Ptr->getType()))
3397 return Error(Loc, "base of getelementptr must be a pointer");
3399 SmallVector<Value*, 16> Indices;
3400 while (EatIfPresent(lltok::comma)) {
3401 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3402 if (!isa<IntegerType>(Val->getType()))
3403 return Error(EltLoc, "getelementptr index must be an integer");
3404 Indices.push_back(Val);
3407 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3408 Indices.begin(), Indices.end()))
3409 return Error(Loc, "invalid getelementptr indices");
3410 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3414 /// ParseExtractValue
3415 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3416 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3417 Value *Val; LocTy Loc;
3418 SmallVector<unsigned, 4> Indices;
3419 if (ParseTypeAndValue(Val, Loc, PFS) ||
3420 ParseIndexList(Indices))
3423 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3424 return Error(Loc, "extractvalue operand must be array or struct");
3426 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3428 return Error(Loc, "invalid indices for extractvalue");
3429 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3433 /// ParseInsertValue
3434 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3435 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3436 Value *Val0, *Val1; LocTy Loc0, Loc1;
3437 SmallVector<unsigned, 4> Indices;
3438 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3439 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3440 ParseTypeAndValue(Val1, Loc1, PFS) ||
3441 ParseIndexList(Indices))
3444 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3445 return Error(Loc0, "extractvalue operand must be array or struct");
3447 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3449 return Error(Loc0, "invalid indices for insertvalue");
3450 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3454 //===----------------------------------------------------------------------===//
3455 // Embedded metadata.
3456 //===----------------------------------------------------------------------===//
3458 /// ParseMDNodeVector
3459 /// ::= Element (',' Element)*
3461 /// ::= 'null' | TypeAndValue
3462 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3463 assert(Lex.getKind() == lltok::lbrace);
3467 if (Lex.getKind() == lltok::kw_null) {
3471 PATypeHolder Ty(Type::VoidTy);
3472 if (ParseType(Ty)) return true;
3473 if (Lex.getKind() == lltok::Metadata) {
3475 MetadataBase *Node = 0;
3476 if (!ParseMDNode(Node))
3479 MetadataBase *MDS = 0;
3480 if (ParseMDString(MDS)) return true;
3485 if (ParseGlobalValue(Ty, C)) return true;
3490 } while (EatIfPresent(lltok::comma));