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.data() + Str.size());
381 // ::= '!' MDNodeNumber
382 bool LLParser::ParseMDNode(Constant *&Node) {
383 // !{ ..., !42, ... }
385 if (ParseUInt32(MID)) return true;
387 // Check existing MDNode.
388 std::map<unsigned, Constant *>::iterator I = MetadataCache.find(MID);
389 if (I != MetadataCache.end()) {
394 // Check known forward references.
395 std::map<unsigned, std::pair<Constant *, 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))
431 if (ParseGlobalValue(Ty, Init))
434 MetadataCache[MetadataID] = Init;
435 std::map<unsigned, std::pair<Constant *, LocTy> >::iterator
436 FI = ForwardRefMDNodes.find(MetadataID);
437 if (FI != ForwardRefMDNodes.end()) {
438 Constant *FwdNode = FI->second.first;
439 FwdNode->replaceAllUsesWith(Init);
440 ForwardRefMDNodes.erase(FI);
447 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
450 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
451 /// ::= 'getelementptr' '(' ... ')'
453 /// Everything through visibility has already been parsed.
455 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
456 unsigned Visibility) {
457 assert(Lex.getKind() == lltok::kw_alias);
460 LocTy LinkageLoc = Lex.getLoc();
461 if (ParseOptionalLinkage(Linkage))
464 if (Linkage != GlobalValue::ExternalLinkage &&
465 Linkage != GlobalValue::WeakAnyLinkage &&
466 Linkage != GlobalValue::WeakODRLinkage &&
467 Linkage != GlobalValue::InternalLinkage &&
468 Linkage != GlobalValue::PrivateLinkage &&
469 Linkage != GlobalValue::LinkerPrivateLinkage)
470 return Error(LinkageLoc, "invalid linkage type for alias");
473 LocTy AliaseeLoc = Lex.getLoc();
474 if (Lex.getKind() != lltok::kw_bitcast &&
475 Lex.getKind() != lltok::kw_getelementptr) {
476 if (ParseGlobalTypeAndValue(Aliasee)) return true;
478 // The bitcast dest type is not present, it is implied by the dest type.
480 if (ParseValID(ID)) return true;
481 if (ID.Kind != ValID::t_Constant)
482 return Error(AliaseeLoc, "invalid aliasee");
483 Aliasee = ID.ConstantVal;
486 if (!isa<PointerType>(Aliasee->getType()))
487 return Error(AliaseeLoc, "alias must have pointer type");
489 // Okay, create the alias but do not insert it into the module yet.
490 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
491 (GlobalValue::LinkageTypes)Linkage, Name,
493 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
495 // See if this value already exists in the symbol table. If so, it is either
496 // a redefinition or a definition of a forward reference.
497 if (GlobalValue *Val =
498 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
499 // See if this was a redefinition. If so, there is no entry in
501 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
502 I = ForwardRefVals.find(Name);
503 if (I == ForwardRefVals.end())
504 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
506 // Otherwise, this was a definition of forward ref. Verify that types
508 if (Val->getType() != GA->getType())
509 return Error(NameLoc,
510 "forward reference and definition of alias have different types");
512 // If they agree, just RAUW the old value with the alias and remove the
514 Val->replaceAllUsesWith(GA);
515 Val->eraseFromParent();
516 ForwardRefVals.erase(I);
519 // Insert into the module, we know its name won't collide now.
520 M->getAliasList().push_back(GA);
521 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
527 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
528 /// OptionalAddrSpace GlobalType Type Const
529 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
530 /// OptionalAddrSpace GlobalType Type Const
532 /// Everything through visibility has been parsed already.
534 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
535 unsigned Linkage, bool HasLinkage,
536 unsigned Visibility) {
538 bool ThreadLocal, IsConstant;
541 PATypeHolder Ty(Type::VoidTy);
542 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
543 ParseOptionalAddrSpace(AddrSpace) ||
544 ParseGlobalType(IsConstant) ||
545 ParseType(Ty, TyLoc))
548 // If the linkage is specified and is external, then no initializer is
551 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
552 Linkage != GlobalValue::ExternalWeakLinkage &&
553 Linkage != GlobalValue::ExternalLinkage)) {
554 if (ParseGlobalValue(Ty, Init))
558 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
559 return Error(TyLoc, "invalid type for global variable");
561 GlobalVariable *GV = 0;
563 // See if the global was forward referenced, if so, use the global.
565 if ((GV = M->getGlobalVariable(Name, true)) &&
566 !ForwardRefVals.erase(Name))
567 return Error(NameLoc, "redefinition of global '@" + Name + "'");
569 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
570 I = ForwardRefValIDs.find(NumberedVals.size());
571 if (I != ForwardRefValIDs.end()) {
572 GV = cast<GlobalVariable>(I->second.first);
573 ForwardRefValIDs.erase(I);
578 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
579 Name, 0, false, AddrSpace);
581 if (GV->getType()->getElementType() != Ty)
583 "forward reference and definition of global have different types");
585 // Move the forward-reference to the correct spot in the module.
586 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
590 NumberedVals.push_back(GV);
592 // Set the parsed properties on the global.
594 GV->setInitializer(Init);
595 GV->setConstant(IsConstant);
596 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
597 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
598 GV->setThreadLocal(ThreadLocal);
600 // Parse attributes on the global.
601 while (Lex.getKind() == lltok::comma) {
604 if (Lex.getKind() == lltok::kw_section) {
606 GV->setSection(Lex.getStrVal());
607 if (ParseToken(lltok::StringConstant, "expected global section string"))
609 } else if (Lex.getKind() == lltok::kw_align) {
611 if (ParseOptionalAlignment(Alignment)) return true;
612 GV->setAlignment(Alignment);
614 TokError("unknown global variable property!");
622 //===----------------------------------------------------------------------===//
623 // GlobalValue Reference/Resolution Routines.
624 //===----------------------------------------------------------------------===//
626 /// GetGlobalVal - Get a value with the specified name or ID, creating a
627 /// forward reference record if needed. This can return null if the value
628 /// exists but does not have the right type.
629 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
631 const PointerType *PTy = dyn_cast<PointerType>(Ty);
633 Error(Loc, "global variable reference must have pointer type");
637 // Look this name up in the normal function symbol table.
639 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
641 // If this is a forward reference for the value, see if we already created a
642 // forward ref record.
644 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
645 I = ForwardRefVals.find(Name);
646 if (I != ForwardRefVals.end())
647 Val = I->second.first;
650 // If we have the value in the symbol table or fwd-ref table, return it.
652 if (Val->getType() == Ty) return Val;
653 Error(Loc, "'@" + Name + "' defined with type '" +
654 Val->getType()->getDescription() + "'");
658 // Otherwise, create a new forward reference for this value and remember it.
660 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
661 // Function types can return opaque but functions can't.
662 if (isa<OpaqueType>(FT->getReturnType())) {
663 Error(Loc, "function may not return opaque type");
667 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
669 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
670 GlobalValue::ExternalWeakLinkage, 0, Name);
673 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
677 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
678 const PointerType *PTy = dyn_cast<PointerType>(Ty);
680 Error(Loc, "global variable reference must have pointer type");
684 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
686 // If this is a forward reference for the value, see if we already created a
687 // forward ref record.
689 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
690 I = ForwardRefValIDs.find(ID);
691 if (I != ForwardRefValIDs.end())
692 Val = I->second.first;
695 // If we have the value in the symbol table or fwd-ref table, return it.
697 if (Val->getType() == Ty) return Val;
698 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
699 Val->getType()->getDescription() + "'");
703 // Otherwise, create a new forward reference for this value and remember it.
705 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
706 // Function types can return opaque but functions can't.
707 if (isa<OpaqueType>(FT->getReturnType())) {
708 Error(Loc, "function may not return opaque type");
711 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
713 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
714 GlobalValue::ExternalWeakLinkage, 0, "");
717 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
722 //===----------------------------------------------------------------------===//
724 //===----------------------------------------------------------------------===//
726 /// ParseToken - If the current token has the specified kind, eat it and return
727 /// success. Otherwise, emit the specified error and return failure.
728 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
729 if (Lex.getKind() != T)
730 return TokError(ErrMsg);
735 /// ParseStringConstant
736 /// ::= StringConstant
737 bool LLParser::ParseStringConstant(std::string &Result) {
738 if (Lex.getKind() != lltok::StringConstant)
739 return TokError("expected string constant");
740 Result = Lex.getStrVal();
747 bool LLParser::ParseUInt32(unsigned &Val) {
748 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
749 return TokError("expected integer");
750 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
751 if (Val64 != unsigned(Val64))
752 return TokError("expected 32-bit integer (too large)");
759 /// ParseOptionalAddrSpace
761 /// := 'addrspace' '(' uint32 ')'
762 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
764 if (!EatIfPresent(lltok::kw_addrspace))
766 return ParseToken(lltok::lparen, "expected '(' in address space") ||
767 ParseUInt32(AddrSpace) ||
768 ParseToken(lltok::rparen, "expected ')' in address space");
771 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
772 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
773 /// 2: function attr.
774 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
775 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
776 Attrs = Attribute::None;
777 LocTy AttrLoc = Lex.getLoc();
780 switch (Lex.getKind()) {
783 // Treat these as signext/zeroext if they occur in the argument list after
784 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
785 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
787 // FIXME: REMOVE THIS IN LLVM 3.0
789 if (Lex.getKind() == lltok::kw_sext)
790 Attrs |= Attribute::SExt;
792 Attrs |= Attribute::ZExt;
796 default: // End of attributes.
797 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
798 return Error(AttrLoc, "invalid use of function-only attribute");
800 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
801 return Error(AttrLoc, "invalid use of parameter-only attribute");
804 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
805 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
806 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
807 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
808 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
809 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
810 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
811 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
813 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
814 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
815 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
816 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
817 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
818 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
819 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
820 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
821 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
822 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
823 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
824 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
826 case lltok::kw_align: {
828 if (ParseOptionalAlignment(Alignment))
830 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
838 /// ParseOptionalLinkage
841 /// ::= 'linker_private'
846 /// ::= 'linkonce_odr'
851 /// ::= 'extern_weak'
853 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
855 switch (Lex.getKind()) {
856 default: Res=GlobalValue::ExternalLinkage; return false;
857 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
858 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
859 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
860 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
861 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
862 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
863 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
864 case lltok::kw_available_externally:
865 Res = GlobalValue::AvailableExternallyLinkage;
867 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
868 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
869 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
870 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
871 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
872 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
879 /// ParseOptionalVisibility
885 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
886 switch (Lex.getKind()) {
887 default: Res = GlobalValue::DefaultVisibility; return false;
888 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
889 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
890 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
896 /// ParseOptionalCallingConv
901 /// ::= 'x86_stdcallcc'
902 /// ::= 'x86_fastcallcc'
904 /// ::= 'arm_aapcscc'
905 /// ::= 'arm_aapcs_vfpcc'
908 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
909 switch (Lex.getKind()) {
910 default: CC = CallingConv::C; return false;
911 case lltok::kw_ccc: CC = CallingConv::C; break;
912 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
913 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
914 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
915 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
916 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
917 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
918 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
919 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
925 /// ParseOptionalAlignment
928 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
930 if (!EatIfPresent(lltok::kw_align))
932 LocTy AlignLoc = Lex.getLoc();
933 if (ParseUInt32(Alignment)) return true;
934 if (!isPowerOf2_32(Alignment))
935 return Error(AlignLoc, "alignment is not a power of two");
939 /// ParseOptionalCommaAlignment
941 /// ::= ',' 'align' 4
942 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
944 if (!EatIfPresent(lltok::comma))
946 return ParseToken(lltok::kw_align, "expected 'align'") ||
947 ParseUInt32(Alignment);
951 /// ::= (',' uint32)+
952 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
953 if (Lex.getKind() != lltok::comma)
954 return TokError("expected ',' as start of index list");
956 while (EatIfPresent(lltok::comma)) {
958 if (ParseUInt32(Idx)) return true;
959 Indices.push_back(Idx);
965 //===----------------------------------------------------------------------===//
967 //===----------------------------------------------------------------------===//
969 /// ParseType - Parse and resolve a full type.
970 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
971 LocTy TypeLoc = Lex.getLoc();
972 if (ParseTypeRec(Result)) return true;
974 // Verify no unresolved uprefs.
976 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
978 if (!AllowVoid && Result.get() == Type::VoidTy)
979 return Error(TypeLoc, "void type only allowed for function results");
984 /// HandleUpRefs - Every time we finish a new layer of types, this function is
985 /// called. It loops through the UpRefs vector, which is a list of the
986 /// currently active types. For each type, if the up-reference is contained in
987 /// the newly completed type, we decrement the level count. When the level
988 /// count reaches zero, the up-referenced type is the type that is passed in:
989 /// thus we can complete the cycle.
991 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
992 // If Ty isn't abstract, or if there are no up-references in it, then there is
993 // nothing to resolve here.
994 if (!ty->isAbstract() || UpRefs.empty()) return ty;
998 errs() << "Type '" << Ty->getDescription()
999 << "' newly formed. Resolving upreferences.\n"
1000 << UpRefs.size() << " upreferences active!\n";
1003 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1004 // to zero), we resolve them all together before we resolve them to Ty. At
1005 // the end of the loop, if there is anything to resolve to Ty, it will be in
1007 OpaqueType *TypeToResolve = 0;
1009 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1010 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1012 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1013 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1016 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1017 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1018 << (ContainsType ? "true" : "false")
1019 << " level=" << UpRefs[i].NestingLevel << "\n";
1024 // Decrement level of upreference
1025 unsigned Level = --UpRefs[i].NestingLevel;
1026 UpRefs[i].LastContainedTy = Ty;
1028 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1033 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1036 TypeToResolve = UpRefs[i].UpRefTy;
1038 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1039 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1040 --i; // Do not skip the next element.
1044 TypeToResolve->refineAbstractTypeTo(Ty);
1050 /// ParseTypeRec - The recursive function used to process the internal
1051 /// implementation details of types.
1052 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1053 switch (Lex.getKind()) {
1055 return TokError("expected type");
1057 // TypeRec ::= 'float' | 'void' (etc)
1058 Result = Lex.getTyVal();
1061 case lltok::kw_opaque:
1062 // TypeRec ::= 'opaque'
1063 Result = Context.getOpaqueType();
1067 // TypeRec ::= '{' ... '}'
1068 if (ParseStructType(Result, false))
1071 case lltok::lsquare:
1072 // TypeRec ::= '[' ... ']'
1073 Lex.Lex(); // eat the lsquare.
1074 if (ParseArrayVectorType(Result, false))
1077 case lltok::less: // Either vector or packed struct.
1078 // TypeRec ::= '<' ... '>'
1080 if (Lex.getKind() == lltok::lbrace) {
1081 if (ParseStructType(Result, true) ||
1082 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1084 } else if (ParseArrayVectorType(Result, true))
1087 case lltok::LocalVar:
1088 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1090 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1093 Result = Context.getOpaqueType();
1094 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1095 std::make_pair(Result,
1097 M->addTypeName(Lex.getStrVal(), Result.get());
1102 case lltok::LocalVarID:
1104 if (Lex.getUIntVal() < NumberedTypes.size())
1105 Result = NumberedTypes[Lex.getUIntVal()];
1107 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1108 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1109 if (I != ForwardRefTypeIDs.end())
1110 Result = I->second.first;
1112 Result = Context.getOpaqueType();
1113 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1114 std::make_pair(Result,
1120 case lltok::backslash: {
1121 // TypeRec ::= '\' 4
1124 if (ParseUInt32(Val)) return true;
1125 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1126 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1132 // Parse the type suffixes.
1134 switch (Lex.getKind()) {
1136 default: return false;
1138 // TypeRec ::= TypeRec '*'
1140 if (Result.get() == Type::LabelTy)
1141 return TokError("basic block pointers are invalid");
1142 if (Result.get() == Type::VoidTy)
1143 return TokError("pointers to void are invalid; use i8* instead");
1144 if (!PointerType::isValidElementType(Result.get()))
1145 return TokError("pointer to this type is invalid");
1146 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1150 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1151 case lltok::kw_addrspace: {
1152 if (Result.get() == Type::LabelTy)
1153 return TokError("basic block pointers are invalid");
1154 if (Result.get() == Type::VoidTy)
1155 return TokError("pointers to void are invalid; use i8* instead");
1156 if (!PointerType::isValidElementType(Result.get()))
1157 return TokError("pointer to this type is invalid");
1159 if (ParseOptionalAddrSpace(AddrSpace) ||
1160 ParseToken(lltok::star, "expected '*' in address space"))
1163 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1167 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1169 if (ParseFunctionType(Result))
1176 /// ParseParameterList
1178 /// ::= '(' Arg (',' Arg)* ')'
1180 /// ::= Type OptionalAttributes Value OptionalAttributes
1181 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1182 PerFunctionState &PFS) {
1183 if (ParseToken(lltok::lparen, "expected '(' in call"))
1186 while (Lex.getKind() != lltok::rparen) {
1187 // If this isn't the first argument, we need a comma.
1188 if (!ArgList.empty() &&
1189 ParseToken(lltok::comma, "expected ',' in argument list"))
1192 // Parse the argument.
1194 PATypeHolder ArgTy(Type::VoidTy);
1195 unsigned ArgAttrs1, ArgAttrs2;
1197 if (ParseType(ArgTy, ArgLoc) ||
1198 ParseOptionalAttrs(ArgAttrs1, 0) ||
1199 ParseValue(ArgTy, V, PFS) ||
1200 // FIXME: Should not allow attributes after the argument, remove this in
1202 ParseOptionalAttrs(ArgAttrs2, 3))
1204 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1207 Lex.Lex(); // Lex the ')'.
1213 /// ParseArgumentList - Parse the argument list for a function type or function
1214 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1215 /// ::= '(' ArgTypeListI ')'
1219 /// ::= ArgTypeList ',' '...'
1220 /// ::= ArgType (',' ArgType)*
1222 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1223 bool &isVarArg, bool inType) {
1225 assert(Lex.getKind() == lltok::lparen);
1226 Lex.Lex(); // eat the (.
1228 if (Lex.getKind() == lltok::rparen) {
1230 } else if (Lex.getKind() == lltok::dotdotdot) {
1234 LocTy TypeLoc = Lex.getLoc();
1235 PATypeHolder ArgTy(Type::VoidTy);
1239 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1240 // types (such as a function returning a pointer to itself). If parsing a
1241 // function prototype, we require fully resolved types.
1242 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1243 ParseOptionalAttrs(Attrs, 0)) return true;
1245 if (ArgTy == Type::VoidTy)
1246 return Error(TypeLoc, "argument can not have void type");
1248 if (Lex.getKind() == lltok::LocalVar ||
1249 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1250 Name = Lex.getStrVal();
1254 if (!FunctionType::isValidArgumentType(ArgTy))
1255 return Error(TypeLoc, "invalid type for function argument");
1257 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1259 while (EatIfPresent(lltok::comma)) {
1260 // Handle ... at end of arg list.
1261 if (EatIfPresent(lltok::dotdotdot)) {
1266 // Otherwise must be an argument type.
1267 TypeLoc = Lex.getLoc();
1268 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1269 ParseOptionalAttrs(Attrs, 0)) return true;
1271 if (ArgTy == Type::VoidTy)
1272 return Error(TypeLoc, "argument can not have void type");
1274 if (Lex.getKind() == lltok::LocalVar ||
1275 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1276 Name = Lex.getStrVal();
1282 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1283 return Error(TypeLoc, "invalid type for function argument");
1285 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1289 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1292 /// ParseFunctionType
1293 /// ::= Type ArgumentList OptionalAttrs
1294 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1295 assert(Lex.getKind() == lltok::lparen);
1297 if (!FunctionType::isValidReturnType(Result))
1298 return TokError("invalid function return type");
1300 std::vector<ArgInfo> ArgList;
1303 if (ParseArgumentList(ArgList, isVarArg, true) ||
1304 // FIXME: Allow, but ignore attributes on function types!
1305 // FIXME: Remove in LLVM 3.0
1306 ParseOptionalAttrs(Attrs, 2))
1309 // Reject names on the arguments lists.
1310 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1311 if (!ArgList[i].Name.empty())
1312 return Error(ArgList[i].Loc, "argument name invalid in function type");
1313 if (!ArgList[i].Attrs != 0) {
1314 // Allow but ignore attributes on function types; this permits
1316 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1320 std::vector<const Type*> ArgListTy;
1321 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1322 ArgListTy.push_back(ArgList[i].Type);
1324 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1325 ArgListTy, isVarArg));
1329 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1332 /// ::= '{' TypeRec (',' TypeRec)* '}'
1333 /// ::= '<' '{' '}' '>'
1334 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1335 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1336 assert(Lex.getKind() == lltok::lbrace);
1337 Lex.Lex(); // Consume the '{'
1339 if (EatIfPresent(lltok::rbrace)) {
1340 Result = Context.getStructType(Packed);
1344 std::vector<PATypeHolder> ParamsList;
1345 LocTy EltTyLoc = Lex.getLoc();
1346 if (ParseTypeRec(Result)) return true;
1347 ParamsList.push_back(Result);
1349 if (Result == Type::VoidTy)
1350 return Error(EltTyLoc, "struct element can not have void type");
1351 if (!StructType::isValidElementType(Result))
1352 return Error(EltTyLoc, "invalid element type for struct");
1354 while (EatIfPresent(lltok::comma)) {
1355 EltTyLoc = Lex.getLoc();
1356 if (ParseTypeRec(Result)) return true;
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 ParamsList.push_back(Result);
1366 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1369 std::vector<const Type*> ParamsListTy;
1370 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1371 ParamsListTy.push_back(ParamsList[i].get());
1372 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1376 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1377 /// token has already been consumed.
1379 /// ::= '[' APSINTVAL 'x' Types ']'
1380 /// ::= '<' APSINTVAL 'x' Types '>'
1381 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1382 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1383 Lex.getAPSIntVal().getBitWidth() > 64)
1384 return TokError("expected number in address space");
1386 LocTy SizeLoc = Lex.getLoc();
1387 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1390 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1393 LocTy TypeLoc = Lex.getLoc();
1394 PATypeHolder EltTy(Type::VoidTy);
1395 if (ParseTypeRec(EltTy)) return true;
1397 if (EltTy == Type::VoidTy)
1398 return Error(TypeLoc, "array and vector element type cannot be void");
1400 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1401 "expected end of sequential type"))
1406 return Error(SizeLoc, "zero element vector is illegal");
1407 if ((unsigned)Size != Size)
1408 return Error(SizeLoc, "size too large for vector");
1409 if (!VectorType::isValidElementType(EltTy))
1410 return Error(TypeLoc, "vector element type must be fp or integer");
1411 Result = Context.getVectorType(EltTy, unsigned(Size));
1413 if (!ArrayType::isValidElementType(EltTy))
1414 return Error(TypeLoc, "invalid array element type");
1415 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1420 //===----------------------------------------------------------------------===//
1421 // Function Semantic Analysis.
1422 //===----------------------------------------------------------------------===//
1424 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1427 // Insert unnamed arguments into the NumberedVals list.
1428 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1431 NumberedVals.push_back(AI);
1434 LLParser::PerFunctionState::~PerFunctionState() {
1435 // If there were any forward referenced non-basicblock values, delete them.
1436 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1437 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1438 if (!isa<BasicBlock>(I->second.first)) {
1439 I->second.first->replaceAllUsesWith(
1440 P.getContext().getUndef(I->second.first->getType()));
1441 delete I->second.first;
1442 I->second.first = 0;
1445 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1446 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.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;
1455 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1456 if (!ForwardRefVals.empty())
1457 return P.Error(ForwardRefVals.begin()->second.second,
1458 "use of undefined value '%" + ForwardRefVals.begin()->first +
1460 if (!ForwardRefValIDs.empty())
1461 return P.Error(ForwardRefValIDs.begin()->second.second,
1462 "use of undefined value '%" +
1463 utostr(ForwardRefValIDs.begin()->first) + "'");
1468 /// GetVal - Get a value with the specified name or ID, creating a
1469 /// forward reference record if needed. This can return null if the value
1470 /// exists but does not have the right type.
1471 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1472 const Type *Ty, LocTy Loc) {
1473 // Look this name up in the normal function symbol table.
1474 Value *Val = F.getValueSymbolTable().lookup(Name);
1476 // If this is a forward reference for the value, see if we already created a
1477 // forward ref record.
1479 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1480 I = ForwardRefVals.find(Name);
1481 if (I != ForwardRefVals.end())
1482 Val = I->second.first;
1485 // If we have the value in the symbol table or fwd-ref table, return it.
1487 if (Val->getType() == Ty) return Val;
1488 if (Ty == Type::LabelTy)
1489 P.Error(Loc, "'%" + Name + "' is not a basic block");
1491 P.Error(Loc, "'%" + Name + "' defined with type '" +
1492 Val->getType()->getDescription() + "'");
1496 // Don't make placeholders with invalid type.
1497 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1498 P.Error(Loc, "invalid use of a non-first-class type");
1502 // Otherwise, create a new forward reference for this value and remember it.
1504 if (Ty == Type::LabelTy)
1505 FwdVal = BasicBlock::Create(Name, &F);
1507 FwdVal = new Argument(Ty, Name);
1509 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1513 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1515 // Look this name up in the normal function symbol table.
1516 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1518 // If this is a forward reference for the value, see if we already created a
1519 // forward ref record.
1521 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1522 I = ForwardRefValIDs.find(ID);
1523 if (I != ForwardRefValIDs.end())
1524 Val = I->second.first;
1527 // If we have the value in the symbol table or fwd-ref table, return it.
1529 if (Val->getType() == Ty) return Val;
1530 if (Ty == Type::LabelTy)
1531 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1533 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1534 Val->getType()->getDescription() + "'");
1538 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1539 P.Error(Loc, "invalid use of a non-first-class type");
1543 // Otherwise, create a new forward reference for this value and remember it.
1545 if (Ty == Type::LabelTy)
1546 FwdVal = BasicBlock::Create("", &F);
1548 FwdVal = new Argument(Ty);
1550 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1554 /// SetInstName - After an instruction is parsed and inserted into its
1555 /// basic block, this installs its name.
1556 bool LLParser::PerFunctionState::SetInstName(int NameID,
1557 const std::string &NameStr,
1558 LocTy NameLoc, Instruction *Inst) {
1559 // If this instruction has void type, it cannot have a name or ID specified.
1560 if (Inst->getType() == Type::VoidTy) {
1561 if (NameID != -1 || !NameStr.empty())
1562 return P.Error(NameLoc, "instructions returning void cannot have a name");
1566 // If this was a numbered instruction, verify that the instruction is the
1567 // expected value and resolve any forward references.
1568 if (NameStr.empty()) {
1569 // If neither a name nor an ID was specified, just use the next ID.
1571 NameID = NumberedVals.size();
1573 if (unsigned(NameID) != NumberedVals.size())
1574 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1575 utostr(NumberedVals.size()) + "'");
1577 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1578 ForwardRefValIDs.find(NameID);
1579 if (FI != ForwardRefValIDs.end()) {
1580 if (FI->second.first->getType() != Inst->getType())
1581 return P.Error(NameLoc, "instruction forward referenced with type '" +
1582 FI->second.first->getType()->getDescription() + "'");
1583 FI->second.first->replaceAllUsesWith(Inst);
1584 ForwardRefValIDs.erase(FI);
1587 NumberedVals.push_back(Inst);
1591 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1592 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1593 FI = ForwardRefVals.find(NameStr);
1594 if (FI != ForwardRefVals.end()) {
1595 if (FI->second.first->getType() != Inst->getType())
1596 return P.Error(NameLoc, "instruction forward referenced with type '" +
1597 FI->second.first->getType()->getDescription() + "'");
1598 FI->second.first->replaceAllUsesWith(Inst);
1599 ForwardRefVals.erase(FI);
1602 // Set the name on the instruction.
1603 Inst->setName(NameStr);
1605 if (Inst->getNameStr() != NameStr)
1606 return P.Error(NameLoc, "multiple definition of local value named '" +
1611 /// GetBB - Get a basic block with the specified name or ID, creating a
1612 /// forward reference record if needed.
1613 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1615 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1618 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1619 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1622 /// DefineBB - Define the specified basic block, which is either named or
1623 /// unnamed. If there is an error, this returns null otherwise it returns
1624 /// the block being defined.
1625 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1629 BB = GetBB(NumberedVals.size(), Loc);
1631 BB = GetBB(Name, Loc);
1632 if (BB == 0) return 0; // Already diagnosed error.
1634 // Move the block to the end of the function. Forward ref'd blocks are
1635 // inserted wherever they happen to be referenced.
1636 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1638 // Remove the block from forward ref sets.
1640 ForwardRefValIDs.erase(NumberedVals.size());
1641 NumberedVals.push_back(BB);
1643 // BB forward references are already in the function symbol table.
1644 ForwardRefVals.erase(Name);
1650 //===----------------------------------------------------------------------===//
1652 //===----------------------------------------------------------------------===//
1654 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1655 /// type implied. For example, if we parse "4" we don't know what integer type
1656 /// it has. The value will later be combined with its type and checked for
1658 bool LLParser::ParseValID(ValID &ID) {
1659 ID.Loc = Lex.getLoc();
1660 switch (Lex.getKind()) {
1661 default: return TokError("expected value token");
1662 case lltok::GlobalID: // @42
1663 ID.UIntVal = Lex.getUIntVal();
1664 ID.Kind = ValID::t_GlobalID;
1666 case lltok::GlobalVar: // @foo
1667 ID.StrVal = Lex.getStrVal();
1668 ID.Kind = ValID::t_GlobalName;
1670 case lltok::LocalVarID: // %42
1671 ID.UIntVal = Lex.getUIntVal();
1672 ID.Kind = ValID::t_LocalID;
1674 case lltok::LocalVar: // %foo
1675 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1676 ID.StrVal = Lex.getStrVal();
1677 ID.Kind = ValID::t_LocalName;
1679 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1680 ID.Kind = ValID::t_Constant;
1682 if (Lex.getKind() == lltok::lbrace) {
1683 SmallVector<Value*, 16> Elts;
1684 if (ParseMDNodeVector(Elts) ||
1685 ParseToken(lltok::rbrace, "expected end of metadata node"))
1688 ID.ConstantVal = Context.getMDNode(Elts.data(), Elts.size());
1692 // Standalone metadata reference
1693 // !{ ..., !42, ... }
1694 if (!ParseMDNode(ID.ConstantVal))
1698 // ::= '!' STRINGCONSTANT
1699 if (ParseMDString(ID.MetadataVal)) return true;
1700 ID.Kind = ValID::t_Metadata;
1704 ID.APSIntVal = Lex.getAPSIntVal();
1705 ID.Kind = ValID::t_APSInt;
1707 case lltok::APFloat:
1708 ID.APFloatVal = Lex.getAPFloatVal();
1709 ID.Kind = ValID::t_APFloat;
1711 case lltok::kw_true:
1712 ID.ConstantVal = Context.getTrue();
1713 ID.Kind = ValID::t_Constant;
1715 case lltok::kw_false:
1716 ID.ConstantVal = Context.getFalse();
1717 ID.Kind = ValID::t_Constant;
1719 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1720 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1721 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1723 case lltok::lbrace: {
1724 // ValID ::= '{' ConstVector '}'
1726 SmallVector<Constant*, 16> Elts;
1727 if (ParseGlobalValueVector(Elts) ||
1728 ParseToken(lltok::rbrace, "expected end of struct constant"))
1731 ID.ConstantVal = Context.getConstantStruct(Elts.data(), Elts.size(), false);
1732 ID.Kind = ValID::t_Constant;
1736 // ValID ::= '<' ConstVector '>' --> Vector.
1737 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1739 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1741 SmallVector<Constant*, 16> Elts;
1742 LocTy FirstEltLoc = Lex.getLoc();
1743 if (ParseGlobalValueVector(Elts) ||
1745 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1746 ParseToken(lltok::greater, "expected end of constant"))
1749 if (isPackedStruct) {
1751 Context.getConstantStruct(Elts.data(), Elts.size(), true);
1752 ID.Kind = ValID::t_Constant;
1757 return Error(ID.Loc, "constant vector must not be empty");
1759 if (!Elts[0]->getType()->isInteger() &&
1760 !Elts[0]->getType()->isFloatingPoint())
1761 return Error(FirstEltLoc,
1762 "vector elements must have integer or floating point type");
1764 // Verify that all the vector elements have the same type.
1765 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1766 if (Elts[i]->getType() != Elts[0]->getType())
1767 return Error(FirstEltLoc,
1768 "vector element #" + utostr(i) +
1769 " is not of type '" + Elts[0]->getType()->getDescription());
1771 ID.ConstantVal = Context.getConstantVector(Elts.data(), Elts.size());
1772 ID.Kind = ValID::t_Constant;
1775 case lltok::lsquare: { // Array Constant
1777 SmallVector<Constant*, 16> Elts;
1778 LocTy FirstEltLoc = Lex.getLoc();
1779 if (ParseGlobalValueVector(Elts) ||
1780 ParseToken(lltok::rsquare, "expected end of array constant"))
1783 // Handle empty element.
1785 // Use undef instead of an array because it's inconvenient to determine
1786 // the element type at this point, there being no elements to examine.
1787 ID.Kind = ValID::t_EmptyArray;
1791 if (!Elts[0]->getType()->isFirstClassType())
1792 return Error(FirstEltLoc, "invalid array element type: " +
1793 Elts[0]->getType()->getDescription());
1795 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1797 // Verify all elements are correct type!
1798 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1799 if (Elts[i]->getType() != Elts[0]->getType())
1800 return Error(FirstEltLoc,
1801 "array element #" + utostr(i) +
1802 " is not of type '" +Elts[0]->getType()->getDescription());
1805 ID.ConstantVal = Context.getConstantArray(ATy, Elts.data(), Elts.size());
1806 ID.Kind = ValID::t_Constant;
1809 case lltok::kw_c: // c "foo"
1811 ID.ConstantVal = Context.getConstantArray(Lex.getStrVal(), false);
1812 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1813 ID.Kind = ValID::t_Constant;
1816 case lltok::kw_asm: {
1817 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1820 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1821 ParseStringConstant(ID.StrVal) ||
1822 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1823 ParseToken(lltok::StringConstant, "expected constraint string"))
1825 ID.StrVal2 = Lex.getStrVal();
1826 ID.UIntVal = HasSideEffect;
1827 ID.Kind = ValID::t_InlineAsm;
1831 case lltok::kw_trunc:
1832 case lltok::kw_zext:
1833 case lltok::kw_sext:
1834 case lltok::kw_fptrunc:
1835 case lltok::kw_fpext:
1836 case lltok::kw_bitcast:
1837 case lltok::kw_uitofp:
1838 case lltok::kw_sitofp:
1839 case lltok::kw_fptoui:
1840 case lltok::kw_fptosi:
1841 case lltok::kw_inttoptr:
1842 case lltok::kw_ptrtoint: {
1843 unsigned Opc = Lex.getUIntVal();
1844 PATypeHolder DestTy(Type::VoidTy);
1847 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1848 ParseGlobalTypeAndValue(SrcVal) ||
1849 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1850 ParseType(DestTy) ||
1851 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1853 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1854 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1855 SrcVal->getType()->getDescription() + "' to '" +
1856 DestTy->getDescription() + "'");
1857 ID.ConstantVal = Context.getConstantExprCast((Instruction::CastOps)Opc,
1859 ID.Kind = ValID::t_Constant;
1862 case lltok::kw_extractvalue: {
1865 SmallVector<unsigned, 4> Indices;
1866 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1867 ParseGlobalTypeAndValue(Val) ||
1868 ParseIndexList(Indices) ||
1869 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1871 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1872 return Error(ID.Loc, "extractvalue operand must be array or struct");
1873 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1875 return Error(ID.Loc, "invalid indices for extractvalue");
1877 Context.getConstantExprExtractValue(Val, Indices.data(), Indices.size());
1878 ID.Kind = ValID::t_Constant;
1881 case lltok::kw_insertvalue: {
1883 Constant *Val0, *Val1;
1884 SmallVector<unsigned, 4> Indices;
1885 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1886 ParseGlobalTypeAndValue(Val0) ||
1887 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1888 ParseGlobalTypeAndValue(Val1) ||
1889 ParseIndexList(Indices) ||
1890 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1892 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1893 return Error(ID.Loc, "extractvalue operand must be array or struct");
1894 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1896 return Error(ID.Loc, "invalid indices for insertvalue");
1897 ID.ConstantVal = Context.getConstantExprInsertValue(Val0, Val1,
1898 Indices.data(), Indices.size());
1899 ID.Kind = ValID::t_Constant;
1902 case lltok::kw_icmp:
1903 case lltok::kw_fcmp: {
1904 unsigned PredVal, Opc = Lex.getUIntVal();
1905 Constant *Val0, *Val1;
1907 if (ParseCmpPredicate(PredVal, Opc) ||
1908 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1909 ParseGlobalTypeAndValue(Val0) ||
1910 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1911 ParseGlobalTypeAndValue(Val1) ||
1912 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1915 if (Val0->getType() != Val1->getType())
1916 return Error(ID.Loc, "compare operands must have the same type");
1918 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1920 if (Opc == Instruction::FCmp) {
1921 if (!Val0->getType()->isFPOrFPVector())
1922 return Error(ID.Loc, "fcmp requires floating point operands");
1923 ID.ConstantVal = Context.getConstantExprFCmp(Pred, Val0, Val1);
1925 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
1926 if (!Val0->getType()->isIntOrIntVector() &&
1927 !isa<PointerType>(Val0->getType()))
1928 return Error(ID.Loc, "icmp requires pointer or integer operands");
1929 ID.ConstantVal = Context.getConstantExprICmp(Pred, Val0, Val1);
1931 ID.Kind = ValID::t_Constant;
1935 // Binary Operators.
1937 case lltok::kw_fadd:
1939 case lltok::kw_fsub:
1941 case lltok::kw_fmul:
1942 case lltok::kw_udiv:
1943 case lltok::kw_sdiv:
1944 case lltok::kw_fdiv:
1945 case lltok::kw_urem:
1946 case lltok::kw_srem:
1947 case lltok::kw_frem: {
1948 unsigned Opc = Lex.getUIntVal();
1949 Constant *Val0, *Val1;
1951 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1952 ParseGlobalTypeAndValue(Val0) ||
1953 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1954 ParseGlobalTypeAndValue(Val1) ||
1955 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1957 if (Val0->getType() != Val1->getType())
1958 return Error(ID.Loc, "operands of constexpr must have same type");
1959 if (!Val0->getType()->isIntOrIntVector() &&
1960 !Val0->getType()->isFPOrFPVector())
1961 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1962 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1963 ID.Kind = ValID::t_Constant;
1967 // Logical Operations
1969 case lltok::kw_lshr:
1970 case lltok::kw_ashr:
1973 case lltok::kw_xor: {
1974 unsigned Opc = Lex.getUIntVal();
1975 Constant *Val0, *Val1;
1977 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1978 ParseGlobalTypeAndValue(Val0) ||
1979 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1980 ParseGlobalTypeAndValue(Val1) ||
1981 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1983 if (Val0->getType() != Val1->getType())
1984 return Error(ID.Loc, "operands of constexpr must have same type");
1985 if (!Val0->getType()->isIntOrIntVector())
1986 return Error(ID.Loc,
1987 "constexpr requires integer or integer vector operands");
1988 ID.ConstantVal = Context.getConstantExpr(Opc, Val0, Val1);
1989 ID.Kind = ValID::t_Constant;
1993 case lltok::kw_getelementptr:
1994 case lltok::kw_shufflevector:
1995 case lltok::kw_insertelement:
1996 case lltok::kw_extractelement:
1997 case lltok::kw_select: {
1998 unsigned Opc = Lex.getUIntVal();
1999 SmallVector<Constant*, 16> Elts;
2001 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2002 ParseGlobalValueVector(Elts) ||
2003 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2006 if (Opc == Instruction::GetElementPtr) {
2007 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2008 return Error(ID.Loc, "getelementptr requires pointer operand");
2010 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2011 (Value**)&Elts[1], Elts.size()-1))
2012 return Error(ID.Loc, "invalid indices for getelementptr");
2013 ID.ConstantVal = Context.getConstantExprGetElementPtr(Elts[0],
2014 &Elts[1], Elts.size()-1);
2015 } else if (Opc == Instruction::Select) {
2016 if (Elts.size() != 3)
2017 return Error(ID.Loc, "expected three operands to select");
2018 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2020 return Error(ID.Loc, Reason);
2021 ID.ConstantVal = Context.getConstantExprSelect(Elts[0], Elts[1], Elts[2]);
2022 } else if (Opc == Instruction::ShuffleVector) {
2023 if (Elts.size() != 3)
2024 return Error(ID.Loc, "expected three operands to shufflevector");
2025 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2026 return Error(ID.Loc, "invalid operands to shufflevector");
2028 Context.getConstantExprShuffleVector(Elts[0], Elts[1],Elts[2]);
2029 } else if (Opc == Instruction::ExtractElement) {
2030 if (Elts.size() != 2)
2031 return Error(ID.Loc, "expected two operands to extractelement");
2032 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2033 return Error(ID.Loc, "invalid extractelement operands");
2034 ID.ConstantVal = Context.getConstantExprExtractElement(Elts[0], Elts[1]);
2036 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2037 if (Elts.size() != 3)
2038 return Error(ID.Loc, "expected three operands to insertelement");
2039 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2040 return Error(ID.Loc, "invalid insertelement operands");
2042 Context.getConstantExprInsertElement(Elts[0], Elts[1],Elts[2]);
2045 ID.Kind = ValID::t_Constant;
2048 case lltok::kw_nuw: {
2050 bool AlsoSigned = EatIfPresent(lltok::kw_nsw);
2051 if (Lex.getKind() != lltok::kw_add &&
2052 Lex.getKind() != lltok::kw_sub &&
2053 Lex.getKind() != lltok::kw_mul)
2054 return TokError("expected 'add', 'sub', or 'mul'");
2055 bool Result = LLParser::ParseValID(ID);
2057 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2058 ->setHasNoUnsignedOverflow(true);
2060 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2061 ->setHasNoSignedOverflow(true);
2065 case lltok::kw_nsw: {
2067 bool AlsoUnsigned = EatIfPresent(lltok::kw_nuw);
2068 if (Lex.getKind() != lltok::kw_add &&
2069 Lex.getKind() != lltok::kw_sub &&
2070 Lex.getKind() != lltok::kw_mul)
2071 return TokError("expected 'add', 'sub', or 'mul'");
2072 bool Result = LLParser::ParseValID(ID);
2074 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2075 ->setHasNoSignedOverflow(true);
2077 cast<OverflowingBinaryOperator>(ID.ConstantVal)
2078 ->setHasNoUnsignedOverflow(true);
2082 case lltok::kw_exact: {
2084 if (Lex.getKind() != lltok::kw_sdiv)
2085 return TokError("expected 'sdiv'");
2086 bool Result = LLParser::ParseValID(ID);
2088 cast<SDivOperator>(ID.ConstantVal)->setIsExact(true);
2097 /// ParseGlobalValue - Parse a global value with the specified type.
2098 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2101 return ParseValID(ID) ||
2102 ConvertGlobalValIDToValue(Ty, ID, V);
2105 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2107 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2109 if (isa<FunctionType>(Ty))
2110 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2113 default: llvm_unreachable("Unknown ValID!");
2114 case ValID::t_Metadata:
2115 return Error(ID.Loc, "invalid use of metadata");
2116 case ValID::t_LocalID:
2117 case ValID::t_LocalName:
2118 return Error(ID.Loc, "invalid use of function-local name");
2119 case ValID::t_InlineAsm:
2120 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2121 case ValID::t_GlobalName:
2122 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2124 case ValID::t_GlobalID:
2125 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2127 case ValID::t_APSInt:
2128 if (!isa<IntegerType>(Ty))
2129 return Error(ID.Loc, "integer constant must have integer type");
2130 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2131 V = Context.getConstantInt(ID.APSIntVal);
2133 case ValID::t_APFloat:
2134 if (!Ty->isFloatingPoint() ||
2135 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2136 return Error(ID.Loc, "floating point constant invalid for type");
2138 // The lexer has no type info, so builds all float and double FP constants
2139 // as double. Fix this here. Long double does not need this.
2140 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2141 Ty == Type::FloatTy) {
2143 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2146 V = Context.getConstantFP(ID.APFloatVal);
2148 if (V->getType() != Ty)
2149 return Error(ID.Loc, "floating point constant does not have type '" +
2150 Ty->getDescription() + "'");
2154 if (!isa<PointerType>(Ty))
2155 return Error(ID.Loc, "null must be a pointer type");
2156 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2158 case ValID::t_Undef:
2159 // FIXME: LabelTy should not be a first-class type.
2160 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2161 !isa<OpaqueType>(Ty))
2162 return Error(ID.Loc, "invalid type for undef constant");
2163 V = Context.getUndef(Ty);
2165 case ValID::t_EmptyArray:
2166 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2167 return Error(ID.Loc, "invalid empty array initializer");
2168 V = Context.getUndef(Ty);
2171 // FIXME: LabelTy should not be a first-class type.
2172 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2173 return Error(ID.Loc, "invalid type for null constant");
2174 V = Context.getNullValue(Ty);
2176 case ValID::t_Constant:
2177 if (ID.ConstantVal->getType() != Ty)
2178 return Error(ID.Loc, "constant expression type mismatch");
2184 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2185 PATypeHolder Type(Type::VoidTy);
2186 return ParseType(Type) ||
2187 ParseGlobalValue(Type, V);
2190 /// ParseGlobalValueVector
2192 /// ::= TypeAndValue (',' TypeAndValue)*
2193 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2195 if (Lex.getKind() == lltok::rbrace ||
2196 Lex.getKind() == lltok::rsquare ||
2197 Lex.getKind() == lltok::greater ||
2198 Lex.getKind() == lltok::rparen)
2202 if (ParseGlobalTypeAndValue(C)) return true;
2205 while (EatIfPresent(lltok::comma)) {
2206 if (ParseGlobalTypeAndValue(C)) return true;
2214 //===----------------------------------------------------------------------===//
2215 // Function Parsing.
2216 //===----------------------------------------------------------------------===//
2218 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2219 PerFunctionState &PFS) {
2220 if (ID.Kind == ValID::t_LocalID)
2221 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2222 else if (ID.Kind == ValID::t_LocalName)
2223 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2224 else if (ID.Kind == ValID::t_InlineAsm) {
2225 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2226 const FunctionType *FTy =
2227 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2228 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2229 return Error(ID.Loc, "invalid type for inline asm constraint string");
2230 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2232 } else if (ID.Kind == ValID::t_Metadata) {
2236 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2244 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2247 return ParseValID(ID) ||
2248 ConvertValIDToValue(Ty, ID, V, PFS);
2251 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2252 PATypeHolder T(Type::VoidTy);
2253 return ParseType(T) ||
2254 ParseValue(T, V, PFS);
2258 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2259 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2260 /// OptionalAlign OptGC
2261 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2262 // Parse the linkage.
2263 LocTy LinkageLoc = Lex.getLoc();
2266 unsigned Visibility, CC, RetAttrs;
2267 PATypeHolder RetType(Type::VoidTy);
2268 LocTy RetTypeLoc = Lex.getLoc();
2269 if (ParseOptionalLinkage(Linkage) ||
2270 ParseOptionalVisibility(Visibility) ||
2271 ParseOptionalCallingConv(CC) ||
2272 ParseOptionalAttrs(RetAttrs, 1) ||
2273 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2276 // Verify that the linkage is ok.
2277 switch ((GlobalValue::LinkageTypes)Linkage) {
2278 case GlobalValue::ExternalLinkage:
2279 break; // always ok.
2280 case GlobalValue::DLLImportLinkage:
2281 case GlobalValue::ExternalWeakLinkage:
2283 return Error(LinkageLoc, "invalid linkage for function definition");
2285 case GlobalValue::PrivateLinkage:
2286 case GlobalValue::LinkerPrivateLinkage:
2287 case GlobalValue::InternalLinkage:
2288 case GlobalValue::AvailableExternallyLinkage:
2289 case GlobalValue::LinkOnceAnyLinkage:
2290 case GlobalValue::LinkOnceODRLinkage:
2291 case GlobalValue::WeakAnyLinkage:
2292 case GlobalValue::WeakODRLinkage:
2293 case GlobalValue::DLLExportLinkage:
2295 return Error(LinkageLoc, "invalid linkage for function declaration");
2297 case GlobalValue::AppendingLinkage:
2298 case GlobalValue::GhostLinkage:
2299 case GlobalValue::CommonLinkage:
2300 return Error(LinkageLoc, "invalid function linkage type");
2303 if (!FunctionType::isValidReturnType(RetType) ||
2304 isa<OpaqueType>(RetType))
2305 return Error(RetTypeLoc, "invalid function return type");
2307 LocTy NameLoc = Lex.getLoc();
2309 std::string FunctionName;
2310 if (Lex.getKind() == lltok::GlobalVar) {
2311 FunctionName = Lex.getStrVal();
2312 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2313 unsigned NameID = Lex.getUIntVal();
2315 if (NameID != NumberedVals.size())
2316 return TokError("function expected to be numbered '%" +
2317 utostr(NumberedVals.size()) + "'");
2319 return TokError("expected function name");
2324 if (Lex.getKind() != lltok::lparen)
2325 return TokError("expected '(' in function argument list");
2327 std::vector<ArgInfo> ArgList;
2330 std::string Section;
2334 if (ParseArgumentList(ArgList, isVarArg, false) ||
2335 ParseOptionalAttrs(FuncAttrs, 2) ||
2336 (EatIfPresent(lltok::kw_section) &&
2337 ParseStringConstant(Section)) ||
2338 ParseOptionalAlignment(Alignment) ||
2339 (EatIfPresent(lltok::kw_gc) &&
2340 ParseStringConstant(GC)))
2343 // If the alignment was parsed as an attribute, move to the alignment field.
2344 if (FuncAttrs & Attribute::Alignment) {
2345 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2346 FuncAttrs &= ~Attribute::Alignment;
2349 // Okay, if we got here, the function is syntactically valid. Convert types
2350 // and do semantic checks.
2351 std::vector<const Type*> ParamTypeList;
2352 SmallVector<AttributeWithIndex, 8> Attrs;
2353 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2355 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2356 if (FuncAttrs & ObsoleteFuncAttrs) {
2357 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2358 FuncAttrs &= ~ObsoleteFuncAttrs;
2361 if (RetAttrs != Attribute::None)
2362 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2364 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2365 ParamTypeList.push_back(ArgList[i].Type);
2366 if (ArgList[i].Attrs != Attribute::None)
2367 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2370 if (FuncAttrs != Attribute::None)
2371 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2373 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2375 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2376 RetType != Type::VoidTy)
2377 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2379 const FunctionType *FT =
2380 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2381 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2384 if (!FunctionName.empty()) {
2385 // If this was a definition of a forward reference, remove the definition
2386 // from the forward reference table and fill in the forward ref.
2387 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2388 ForwardRefVals.find(FunctionName);
2389 if (FRVI != ForwardRefVals.end()) {
2390 Fn = M->getFunction(FunctionName);
2391 ForwardRefVals.erase(FRVI);
2392 } else if ((Fn = M->getFunction(FunctionName))) {
2393 // If this function already exists in the symbol table, then it is
2394 // multiply defined. We accept a few cases for old backwards compat.
2395 // FIXME: Remove this stuff for LLVM 3.0.
2396 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2397 (!Fn->isDeclaration() && isDefine)) {
2398 // If the redefinition has different type or different attributes,
2399 // reject it. If both have bodies, reject it.
2400 return Error(NameLoc, "invalid redefinition of function '" +
2401 FunctionName + "'");
2402 } else if (Fn->isDeclaration()) {
2403 // Make sure to strip off any argument names so we can't get conflicts.
2404 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2410 } else if (FunctionName.empty()) {
2411 // If this is a definition of a forward referenced function, make sure the
2413 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2414 = ForwardRefValIDs.find(NumberedVals.size());
2415 if (I != ForwardRefValIDs.end()) {
2416 Fn = cast<Function>(I->second.first);
2417 if (Fn->getType() != PFT)
2418 return Error(NameLoc, "type of definition and forward reference of '@" +
2419 utostr(NumberedVals.size()) +"' disagree");
2420 ForwardRefValIDs.erase(I);
2425 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2426 else // Move the forward-reference to the correct spot in the module.
2427 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2429 if (FunctionName.empty())
2430 NumberedVals.push_back(Fn);
2432 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2433 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2434 Fn->setCallingConv(CC);
2435 Fn->setAttributes(PAL);
2436 Fn->setAlignment(Alignment);
2437 Fn->setSection(Section);
2438 if (!GC.empty()) Fn->setGC(GC.c_str());
2440 // Add all of the arguments we parsed to the function.
2441 Function::arg_iterator ArgIt = Fn->arg_begin();
2442 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2443 // If the argument has a name, insert it into the argument symbol table.
2444 if (ArgList[i].Name.empty()) continue;
2446 // Set the name, if it conflicted, it will be auto-renamed.
2447 ArgIt->setName(ArgList[i].Name);
2449 if (ArgIt->getNameStr() != ArgList[i].Name)
2450 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2451 ArgList[i].Name + "'");
2458 /// ParseFunctionBody
2459 /// ::= '{' BasicBlock+ '}'
2460 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2462 bool LLParser::ParseFunctionBody(Function &Fn) {
2463 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2464 return TokError("expected '{' in function body");
2465 Lex.Lex(); // eat the {.
2467 PerFunctionState PFS(*this, Fn);
2469 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2470 if (ParseBasicBlock(PFS)) return true;
2475 // Verify function is ok.
2476 return PFS.VerifyFunctionComplete();
2480 /// ::= LabelStr? Instruction*
2481 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2482 // If this basic block starts out with a name, remember it.
2484 LocTy NameLoc = Lex.getLoc();
2485 if (Lex.getKind() == lltok::LabelStr) {
2486 Name = Lex.getStrVal();
2490 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2491 if (BB == 0) return true;
2493 std::string NameStr;
2495 // Parse the instructions in this block until we get a terminator.
2498 // This instruction may have three possibilities for a name: a) none
2499 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2500 LocTy NameLoc = Lex.getLoc();
2504 if (Lex.getKind() == lltok::LocalVarID) {
2505 NameID = Lex.getUIntVal();
2507 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2509 } else if (Lex.getKind() == lltok::LocalVar ||
2510 // FIXME: REMOVE IN LLVM 3.0
2511 Lex.getKind() == lltok::StringConstant) {
2512 NameStr = Lex.getStrVal();
2514 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2518 if (ParseInstruction(Inst, BB, PFS)) return true;
2520 BB->getInstList().push_back(Inst);
2522 // Set the name on the instruction.
2523 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2524 } while (!isa<TerminatorInst>(Inst));
2529 //===----------------------------------------------------------------------===//
2530 // Instruction Parsing.
2531 //===----------------------------------------------------------------------===//
2533 /// ParseInstruction - Parse one of the many different instructions.
2535 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2536 PerFunctionState &PFS) {
2537 lltok::Kind Token = Lex.getKind();
2538 if (Token == lltok::Eof)
2539 return TokError("found end of file when expecting more instructions");
2540 LocTy Loc = Lex.getLoc();
2541 unsigned KeywordVal = Lex.getUIntVal();
2542 Lex.Lex(); // Eat the keyword.
2545 default: return Error(Loc, "expected instruction opcode");
2546 // Terminator Instructions.
2547 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2548 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2549 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2550 case lltok::kw_br: return ParseBr(Inst, PFS);
2551 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2552 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2553 // Binary Operators.
2557 // API compatibility: Accept either integer or floating-point types.
2558 return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2559 case lltok::kw_fadd:
2560 case lltok::kw_fsub:
2561 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2563 case lltok::kw_udiv:
2564 case lltok::kw_sdiv:
2565 case lltok::kw_urem:
2566 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2567 case lltok::kw_fdiv:
2568 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2570 case lltok::kw_lshr:
2571 case lltok::kw_ashr:
2574 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2575 case lltok::kw_icmp:
2576 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2578 case lltok::kw_trunc:
2579 case lltok::kw_zext:
2580 case lltok::kw_sext:
2581 case lltok::kw_fptrunc:
2582 case lltok::kw_fpext:
2583 case lltok::kw_bitcast:
2584 case lltok::kw_uitofp:
2585 case lltok::kw_sitofp:
2586 case lltok::kw_fptoui:
2587 case lltok::kw_fptosi:
2588 case lltok::kw_inttoptr:
2589 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2591 case lltok::kw_select: return ParseSelect(Inst, PFS);
2592 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2593 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2594 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2595 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2596 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2597 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2598 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2600 case lltok::kw_alloca:
2601 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2602 case lltok::kw_free: return ParseFree(Inst, PFS);
2603 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2604 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2605 case lltok::kw_volatile:
2606 if (EatIfPresent(lltok::kw_load))
2607 return ParseLoad(Inst, PFS, true);
2608 else if (EatIfPresent(lltok::kw_store))
2609 return ParseStore(Inst, PFS, true);
2611 return TokError("expected 'load' or 'store'");
2612 case lltok::kw_nuw: {
2613 bool AlsoSigned = EatIfPresent(lltok::kw_nsw);
2614 if (Lex.getKind() == lltok::kw_add ||
2615 Lex.getKind() == lltok::kw_sub ||
2616 Lex.getKind() == lltok::kw_mul) {
2618 KeywordVal = Lex.getUIntVal();
2619 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2621 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2623 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2627 return TokError("expected 'add', 'sub', or 'mul'");
2629 case lltok::kw_nsw: {
2630 bool AlsoUnsigned = EatIfPresent(lltok::kw_nuw);
2631 if (Lex.getKind() == lltok::kw_add ||
2632 Lex.getKind() == lltok::kw_sub ||
2633 Lex.getKind() == lltok::kw_mul) {
2635 KeywordVal = Lex.getUIntVal();
2636 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2638 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2640 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2644 return TokError("expected 'add', 'sub', or 'mul'");
2646 case lltok::kw_exact:
2647 if (Lex.getKind() == lltok::kw_sdiv) {
2649 KeywordVal = Lex.getUIntVal();
2650 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2652 cast<SDivOperator>(Inst)->setIsExact(true);
2655 return TokError("expected 'udiv'");
2656 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2657 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2658 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2659 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2663 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2664 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2665 if (Opc == Instruction::FCmp) {
2666 switch (Lex.getKind()) {
2667 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2668 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2669 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2670 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2671 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2672 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2673 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2674 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2675 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2676 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2677 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2678 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2679 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2680 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2681 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2682 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2683 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2686 switch (Lex.getKind()) {
2687 default: TokError("expected icmp predicate (e.g. 'eq')");
2688 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2689 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2690 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2691 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2692 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2693 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2694 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2695 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2696 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2697 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2704 //===----------------------------------------------------------------------===//
2705 // Terminator Instructions.
2706 //===----------------------------------------------------------------------===//
2708 /// ParseRet - Parse a return instruction.
2710 /// ::= 'ret' TypeAndValue
2711 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2712 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2713 PerFunctionState &PFS) {
2714 PATypeHolder Ty(Type::VoidTy);
2715 if (ParseType(Ty, true /*void allowed*/)) return true;
2717 if (Ty == Type::VoidTy) {
2718 Inst = ReturnInst::Create();
2723 if (ParseValue(Ty, RV, PFS)) return true;
2725 // The normal case is one return value.
2726 if (Lex.getKind() == lltok::comma) {
2727 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2728 // of 'ret {i32,i32} {i32 1, i32 2}'
2729 SmallVector<Value*, 8> RVs;
2732 while (EatIfPresent(lltok::comma)) {
2733 if (ParseTypeAndValue(RV, PFS)) return true;
2737 RV = Context.getUndef(PFS.getFunction().getReturnType());
2738 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2739 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2740 BB->getInstList().push_back(I);
2744 Inst = ReturnInst::Create(RV);
2750 /// ::= 'br' TypeAndValue
2751 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2752 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2754 Value *Op0, *Op1, *Op2;
2755 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2757 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2758 Inst = BranchInst::Create(BB);
2762 if (Op0->getType() != Type::Int1Ty)
2763 return Error(Loc, "branch condition must have 'i1' type");
2765 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2766 ParseTypeAndValue(Op1, Loc, PFS) ||
2767 ParseToken(lltok::comma, "expected ',' after true destination") ||
2768 ParseTypeAndValue(Op2, Loc2, PFS))
2771 if (!isa<BasicBlock>(Op1))
2772 return Error(Loc, "true destination of branch must be a basic block");
2773 if (!isa<BasicBlock>(Op2))
2774 return Error(Loc2, "true destination of branch must be a basic block");
2776 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2782 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2784 /// ::= (TypeAndValue ',' TypeAndValue)*
2785 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2786 LocTy CondLoc, BBLoc;
2787 Value *Cond, *DefaultBB;
2788 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2789 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2790 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2791 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2794 if (!isa<IntegerType>(Cond->getType()))
2795 return Error(CondLoc, "switch condition must have integer type");
2796 if (!isa<BasicBlock>(DefaultBB))
2797 return Error(BBLoc, "default destination must be a basic block");
2799 // Parse the jump table pairs.
2800 SmallPtrSet<Value*, 32> SeenCases;
2801 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2802 while (Lex.getKind() != lltok::rsquare) {
2803 Value *Constant, *DestBB;
2805 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2806 ParseToken(lltok::comma, "expected ',' after case value") ||
2807 ParseTypeAndValue(DestBB, BBLoc, PFS))
2810 if (!SeenCases.insert(Constant))
2811 return Error(CondLoc, "duplicate case value in switch");
2812 if (!isa<ConstantInt>(Constant))
2813 return Error(CondLoc, "case value is not a constant integer");
2814 if (!isa<BasicBlock>(DestBB))
2815 return Error(BBLoc, "case destination is not a basic block");
2817 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2818 cast<BasicBlock>(DestBB)));
2821 Lex.Lex(); // Eat the ']'.
2823 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2825 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2826 SI->addCase(Table[i].first, Table[i].second);
2832 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2833 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2834 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2835 LocTy CallLoc = Lex.getLoc();
2836 unsigned CC, RetAttrs, FnAttrs;
2837 PATypeHolder RetType(Type::VoidTy);
2840 SmallVector<ParamInfo, 16> ArgList;
2842 Value *NormalBB, *UnwindBB;
2843 if (ParseOptionalCallingConv(CC) ||
2844 ParseOptionalAttrs(RetAttrs, 1) ||
2845 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2846 ParseValID(CalleeID) ||
2847 ParseParameterList(ArgList, PFS) ||
2848 ParseOptionalAttrs(FnAttrs, 2) ||
2849 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2850 ParseTypeAndValue(NormalBB, PFS) ||
2851 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2852 ParseTypeAndValue(UnwindBB, PFS))
2855 if (!isa<BasicBlock>(NormalBB))
2856 return Error(CallLoc, "normal destination is not a basic block");
2857 if (!isa<BasicBlock>(UnwindBB))
2858 return Error(CallLoc, "unwind destination is not a basic block");
2860 // If RetType is a non-function pointer type, then this is the short syntax
2861 // for the call, which means that RetType is just the return type. Infer the
2862 // rest of the function argument types from the arguments that are present.
2863 const PointerType *PFTy = 0;
2864 const FunctionType *Ty = 0;
2865 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2866 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2867 // Pull out the types of all of the arguments...
2868 std::vector<const Type*> ParamTypes;
2869 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2870 ParamTypes.push_back(ArgList[i].V->getType());
2872 if (!FunctionType::isValidReturnType(RetType))
2873 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2875 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2876 PFTy = Context.getPointerTypeUnqual(Ty);
2879 // Look up the callee.
2881 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2883 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2884 // function attributes.
2885 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2886 if (FnAttrs & ObsoleteFuncAttrs) {
2887 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2888 FnAttrs &= ~ObsoleteFuncAttrs;
2891 // Set up the Attributes for the function.
2892 SmallVector<AttributeWithIndex, 8> Attrs;
2893 if (RetAttrs != Attribute::None)
2894 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2896 SmallVector<Value*, 8> Args;
2898 // Loop through FunctionType's arguments and ensure they are specified
2899 // correctly. Also, gather any parameter attributes.
2900 FunctionType::param_iterator I = Ty->param_begin();
2901 FunctionType::param_iterator E = Ty->param_end();
2902 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2903 const Type *ExpectedTy = 0;
2906 } else if (!Ty->isVarArg()) {
2907 return Error(ArgList[i].Loc, "too many arguments specified");
2910 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2911 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2912 ExpectedTy->getDescription() + "'");
2913 Args.push_back(ArgList[i].V);
2914 if (ArgList[i].Attrs != Attribute::None)
2915 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2919 return Error(CallLoc, "not enough parameters specified for call");
2921 if (FnAttrs != Attribute::None)
2922 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2924 // Finish off the Attributes and check them
2925 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2927 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2928 cast<BasicBlock>(UnwindBB),
2929 Args.begin(), Args.end());
2930 II->setCallingConv(CC);
2931 II->setAttributes(PAL);
2938 //===----------------------------------------------------------------------===//
2939 // Binary Operators.
2940 //===----------------------------------------------------------------------===//
2943 /// ::= ArithmeticOps TypeAndValue ',' Value
2945 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2946 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2947 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2948 unsigned Opc, unsigned OperandType) {
2949 LocTy Loc; Value *LHS, *RHS;
2950 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2951 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2952 ParseValue(LHS->getType(), RHS, PFS))
2956 switch (OperandType) {
2957 default: llvm_unreachable("Unknown operand type!");
2958 case 0: // int or FP.
2959 Valid = LHS->getType()->isIntOrIntVector() ||
2960 LHS->getType()->isFPOrFPVector();
2962 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2963 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2967 return Error(Loc, "invalid operand type for instruction");
2969 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2974 /// ::= ArithmeticOps TypeAndValue ',' Value {
2975 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2977 LocTy Loc; Value *LHS, *RHS;
2978 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2979 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2980 ParseValue(LHS->getType(), RHS, PFS))
2983 if (!LHS->getType()->isIntOrIntVector())
2984 return Error(Loc,"instruction requires integer or integer vector operands");
2986 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2992 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2993 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2994 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2996 // Parse the integer/fp comparison predicate.
3000 if (ParseCmpPredicate(Pred, Opc) ||
3001 ParseTypeAndValue(LHS, Loc, PFS) ||
3002 ParseToken(lltok::comma, "expected ',' after compare value") ||
3003 ParseValue(LHS->getType(), RHS, PFS))
3006 if (Opc == Instruction::FCmp) {
3007 if (!LHS->getType()->isFPOrFPVector())
3008 return Error(Loc, "fcmp requires floating point operands");
3009 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3011 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3012 if (!LHS->getType()->isIntOrIntVector() &&
3013 !isa<PointerType>(LHS->getType()))
3014 return Error(Loc, "icmp requires integer operands");
3015 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3020 //===----------------------------------------------------------------------===//
3021 // Other Instructions.
3022 //===----------------------------------------------------------------------===//
3026 /// ::= CastOpc TypeAndValue 'to' Type
3027 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3029 LocTy Loc; Value *Op;
3030 PATypeHolder DestTy(Type::VoidTy);
3031 if (ParseTypeAndValue(Op, Loc, PFS) ||
3032 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3036 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3037 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3038 return Error(Loc, "invalid cast opcode for cast from '" +
3039 Op->getType()->getDescription() + "' to '" +
3040 DestTy->getDescription() + "'");
3042 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3047 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3048 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3050 Value *Op0, *Op1, *Op2;
3051 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3052 ParseToken(lltok::comma, "expected ',' after select condition") ||
3053 ParseTypeAndValue(Op1, PFS) ||
3054 ParseToken(lltok::comma, "expected ',' after select value") ||
3055 ParseTypeAndValue(Op2, PFS))
3058 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3059 return Error(Loc, Reason);
3061 Inst = SelectInst::Create(Op0, Op1, Op2);
3066 /// ::= 'va_arg' TypeAndValue ',' Type
3067 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3069 PATypeHolder EltTy(Type::VoidTy);
3071 if (ParseTypeAndValue(Op, PFS) ||
3072 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3073 ParseType(EltTy, TypeLoc))
3076 if (!EltTy->isFirstClassType())
3077 return Error(TypeLoc, "va_arg requires operand with first class type");
3079 Inst = new VAArgInst(Op, EltTy);
3083 /// ParseExtractElement
3084 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3085 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3088 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3089 ParseToken(lltok::comma, "expected ',' after extract value") ||
3090 ParseTypeAndValue(Op1, PFS))
3093 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3094 return Error(Loc, "invalid extractelement operands");
3096 Inst = new ExtractElementInst(Op0, Op1);
3100 /// ParseInsertElement
3101 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3102 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3104 Value *Op0, *Op1, *Op2;
3105 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3106 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3107 ParseTypeAndValue(Op1, PFS) ||
3108 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3109 ParseTypeAndValue(Op2, PFS))
3112 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3113 return Error(Loc, "invalid insertelement operands");
3115 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3119 /// ParseShuffleVector
3120 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3121 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3123 Value *Op0, *Op1, *Op2;
3124 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3125 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3126 ParseTypeAndValue(Op1, PFS) ||
3127 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3128 ParseTypeAndValue(Op2, PFS))
3131 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3132 return Error(Loc, "invalid extractelement operands");
3134 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3139 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3140 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3141 PATypeHolder Ty(Type::VoidTy);
3143 LocTy TypeLoc = Lex.getLoc();
3145 if (ParseType(Ty) ||
3146 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3147 ParseValue(Ty, Op0, PFS) ||
3148 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3149 ParseValue(Type::LabelTy, Op1, PFS) ||
3150 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3153 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3155 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3157 if (!EatIfPresent(lltok::comma))
3160 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3161 ParseValue(Ty, Op0, PFS) ||
3162 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3163 ParseValue(Type::LabelTy, Op1, PFS) ||
3164 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3168 if (!Ty->isFirstClassType())
3169 return Error(TypeLoc, "phi node must have first class type");
3171 PHINode *PN = PHINode::Create(Ty);
3172 PN->reserveOperandSpace(PHIVals.size());
3173 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3174 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3180 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3181 /// ParameterList OptionalAttrs
3182 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3184 unsigned CC, RetAttrs, FnAttrs;
3185 PATypeHolder RetType(Type::VoidTy);
3188 SmallVector<ParamInfo, 16> ArgList;
3189 LocTy CallLoc = Lex.getLoc();
3191 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3192 ParseOptionalCallingConv(CC) ||
3193 ParseOptionalAttrs(RetAttrs, 1) ||
3194 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3195 ParseValID(CalleeID) ||
3196 ParseParameterList(ArgList, PFS) ||
3197 ParseOptionalAttrs(FnAttrs, 2))
3200 // If RetType is a non-function pointer type, then this is the short syntax
3201 // for the call, which means that RetType is just the return type. Infer the
3202 // rest of the function argument types from the arguments that are present.
3203 const PointerType *PFTy = 0;
3204 const FunctionType *Ty = 0;
3205 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3206 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3207 // Pull out the types of all of the arguments...
3208 std::vector<const Type*> ParamTypes;
3209 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3210 ParamTypes.push_back(ArgList[i].V->getType());
3212 if (!FunctionType::isValidReturnType(RetType))
3213 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3215 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3216 PFTy = Context.getPointerTypeUnqual(Ty);
3219 // Look up the callee.
3221 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3223 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3224 // function attributes.
3225 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3226 if (FnAttrs & ObsoleteFuncAttrs) {
3227 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3228 FnAttrs &= ~ObsoleteFuncAttrs;
3231 // Set up the Attributes for the function.
3232 SmallVector<AttributeWithIndex, 8> Attrs;
3233 if (RetAttrs != Attribute::None)
3234 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3236 SmallVector<Value*, 8> Args;
3238 // Loop through FunctionType's arguments and ensure they are specified
3239 // correctly. Also, gather any parameter attributes.
3240 FunctionType::param_iterator I = Ty->param_begin();
3241 FunctionType::param_iterator E = Ty->param_end();
3242 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3243 const Type *ExpectedTy = 0;
3246 } else if (!Ty->isVarArg()) {
3247 return Error(ArgList[i].Loc, "too many arguments specified");
3250 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3251 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3252 ExpectedTy->getDescription() + "'");
3253 Args.push_back(ArgList[i].V);
3254 if (ArgList[i].Attrs != Attribute::None)
3255 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3259 return Error(CallLoc, "not enough parameters specified for call");
3261 if (FnAttrs != Attribute::None)
3262 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3264 // Finish off the Attributes and check them
3265 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3267 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3268 CI->setTailCall(isTail);
3269 CI->setCallingConv(CC);
3270 CI->setAttributes(PAL);
3275 //===----------------------------------------------------------------------===//
3276 // Memory Instructions.
3277 //===----------------------------------------------------------------------===//
3280 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3281 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3282 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3284 PATypeHolder Ty(Type::VoidTy);
3287 unsigned Alignment = 0;
3288 if (ParseType(Ty)) return true;
3290 if (EatIfPresent(lltok::comma)) {
3291 if (Lex.getKind() == lltok::kw_align) {
3292 if (ParseOptionalAlignment(Alignment)) return true;
3293 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3294 ParseOptionalCommaAlignment(Alignment)) {
3299 if (Size && Size->getType() != Type::Int32Ty)
3300 return Error(SizeLoc, "element count must be i32");
3302 if (Opc == Instruction::Malloc)
3303 Inst = new MallocInst(Ty, Size, Alignment);
3305 Inst = new AllocaInst(Ty, Size, Alignment);
3310 /// ::= 'free' TypeAndValue
3311 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3312 Value *Val; LocTy Loc;
3313 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3314 if (!isa<PointerType>(Val->getType()))
3315 return Error(Loc, "operand to free must be a pointer");
3316 Inst = new FreeInst(Val);
3321 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3322 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3324 Value *Val; LocTy Loc;
3326 if (ParseTypeAndValue(Val, Loc, PFS) ||
3327 ParseOptionalCommaAlignment(Alignment))
3330 if (!isa<PointerType>(Val->getType()) ||
3331 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3332 return Error(Loc, "load operand must be a pointer to a first class type");
3334 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3339 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3340 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3342 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3344 if (ParseTypeAndValue(Val, Loc, PFS) ||
3345 ParseToken(lltok::comma, "expected ',' after store operand") ||
3346 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3347 ParseOptionalCommaAlignment(Alignment))
3350 if (!isa<PointerType>(Ptr->getType()))
3351 return Error(PtrLoc, "store operand must be a pointer");
3352 if (!Val->getType()->isFirstClassType())
3353 return Error(Loc, "store operand must be a first class value");
3354 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3355 return Error(Loc, "stored value and pointer type do not match");
3357 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3362 /// ::= 'getresult' TypeAndValue ',' i32
3363 /// FIXME: Remove support for getresult in LLVM 3.0
3364 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3365 Value *Val; LocTy ValLoc, EltLoc;
3367 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3368 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3369 ParseUInt32(Element, EltLoc))
3372 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3373 return Error(ValLoc, "getresult inst requires an aggregate operand");
3374 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3375 return Error(EltLoc, "invalid getresult index for value");
3376 Inst = ExtractValueInst::Create(Val, Element);
3380 /// ParseGetElementPtr
3381 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3382 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3383 Value *Ptr, *Val; LocTy Loc, EltLoc;
3384 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3386 if (!isa<PointerType>(Ptr->getType()))
3387 return Error(Loc, "base of getelementptr must be a pointer");
3389 SmallVector<Value*, 16> Indices;
3390 while (EatIfPresent(lltok::comma)) {
3391 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3392 if (!isa<IntegerType>(Val->getType()))
3393 return Error(EltLoc, "getelementptr index must be an integer");
3394 Indices.push_back(Val);
3397 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3398 Indices.begin(), Indices.end()))
3399 return Error(Loc, "invalid getelementptr indices");
3400 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3404 /// ParseExtractValue
3405 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3406 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3407 Value *Val; LocTy Loc;
3408 SmallVector<unsigned, 4> Indices;
3409 if (ParseTypeAndValue(Val, Loc, PFS) ||
3410 ParseIndexList(Indices))
3413 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3414 return Error(Loc, "extractvalue operand must be array or struct");
3416 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3418 return Error(Loc, "invalid indices for extractvalue");
3419 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3423 /// ParseInsertValue
3424 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3425 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3426 Value *Val0, *Val1; LocTy Loc0, Loc1;
3427 SmallVector<unsigned, 4> Indices;
3428 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3429 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3430 ParseTypeAndValue(Val1, Loc1, PFS) ||
3431 ParseIndexList(Indices))
3434 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3435 return Error(Loc0, "extractvalue operand must be array or struct");
3437 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3439 return Error(Loc0, "invalid indices for insertvalue");
3440 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3444 //===----------------------------------------------------------------------===//
3445 // Embedded metadata.
3446 //===----------------------------------------------------------------------===//
3448 /// ParseMDNodeVector
3449 /// ::= Element (',' Element)*
3451 /// ::= 'null' | TypeAndValue
3452 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3453 assert(Lex.getKind() == lltok::lbrace);
3457 if (Lex.getKind() == lltok::kw_null) {
3461 PATypeHolder Ty(Type::VoidTy);
3462 if (ParseType(Ty)) return true;
3463 if (Lex.getKind() == lltok::Metadata) {
3466 if (!ParseMDNode(Node))
3469 MetadataBase *MDS = 0;
3470 if (ParseMDString(MDS)) return true;
3475 if (ParseGlobalValue(Ty, C)) return true;
3480 } while (EatIfPresent(lltok::comma));