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/Metadata.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;
124 case lltok::NamedMD: if (ParseNamedMetadata()) return true; break;
126 // The Global variable production with no name can have many different
127 // optional leading prefixes, the production is:
128 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
129 // OptionalAddrSpace ('constant'|'global') ...
130 case lltok::kw_private : // OptionalLinkage
131 case lltok::kw_linker_private: // OptionalLinkage
132 case lltok::kw_internal: // OptionalLinkage
133 case lltok::kw_weak: // OptionalLinkage
134 case lltok::kw_weak_odr: // OptionalLinkage
135 case lltok::kw_linkonce: // OptionalLinkage
136 case lltok::kw_linkonce_odr: // OptionalLinkage
137 case lltok::kw_appending: // OptionalLinkage
138 case lltok::kw_dllexport: // OptionalLinkage
139 case lltok::kw_common: // OptionalLinkage
140 case lltok::kw_dllimport: // OptionalLinkage
141 case lltok::kw_extern_weak: // OptionalLinkage
142 case lltok::kw_external: { // OptionalLinkage
143 unsigned Linkage, Visibility;
144 if (ParseOptionalLinkage(Linkage) ||
145 ParseOptionalVisibility(Visibility) ||
146 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
150 case lltok::kw_default: // OptionalVisibility
151 case lltok::kw_hidden: // OptionalVisibility
152 case lltok::kw_protected: { // OptionalVisibility
154 if (ParseOptionalVisibility(Visibility) ||
155 ParseGlobal("", SMLoc(), 0, false, Visibility))
160 case lltok::kw_thread_local: // OptionalThreadLocal
161 case lltok::kw_addrspace: // OptionalAddrSpace
162 case lltok::kw_constant: // GlobalType
163 case lltok::kw_global: // GlobalType
164 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
172 /// ::= 'module' 'asm' STRINGCONSTANT
173 bool LLParser::ParseModuleAsm() {
174 assert(Lex.getKind() == lltok::kw_module);
178 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
179 ParseStringConstant(AsmStr)) return true;
181 const std::string &AsmSoFar = M->getModuleInlineAsm();
182 if (AsmSoFar.empty())
183 M->setModuleInlineAsm(AsmStr);
185 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
190 /// ::= 'target' 'triple' '=' STRINGCONSTANT
191 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
192 bool LLParser::ParseTargetDefinition() {
193 assert(Lex.getKind() == lltok::kw_target);
196 default: return TokError("unknown target property");
197 case lltok::kw_triple:
199 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
200 ParseStringConstant(Str))
202 M->setTargetTriple(Str);
204 case lltok::kw_datalayout:
206 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
207 ParseStringConstant(Str))
209 M->setDataLayout(Str);
215 /// ::= 'deplibs' '=' '[' ']'
216 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
217 bool LLParser::ParseDepLibs() {
218 assert(Lex.getKind() == lltok::kw_deplibs);
220 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
221 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
224 if (EatIfPresent(lltok::rsquare))
228 if (ParseStringConstant(Str)) return true;
231 while (EatIfPresent(lltok::comma)) {
232 if (ParseStringConstant(Str)) return true;
236 return ParseToken(lltok::rsquare, "expected ']' at end of list");
241 bool LLParser::ParseUnnamedType() {
242 assert(Lex.getKind() == lltok::kw_type);
243 LocTy TypeLoc = Lex.getLoc();
244 Lex.Lex(); // eat kw_type
246 PATypeHolder Ty(Type::VoidTy);
247 if (ParseType(Ty)) return true;
249 unsigned TypeID = NumberedTypes.size();
251 // See if this type was previously referenced.
252 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
253 FI = ForwardRefTypeIDs.find(TypeID);
254 if (FI != ForwardRefTypeIDs.end()) {
255 if (FI->second.first.get() == Ty)
256 return Error(TypeLoc, "self referential type is invalid");
258 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
259 Ty = FI->second.first.get();
260 ForwardRefTypeIDs.erase(FI);
263 NumberedTypes.push_back(Ty);
269 /// ::= LocalVar '=' 'type' type
270 bool LLParser::ParseNamedType() {
271 std::string Name = Lex.getStrVal();
272 LocTy NameLoc = Lex.getLoc();
273 Lex.Lex(); // eat LocalVar.
275 PATypeHolder Ty(Type::VoidTy);
277 if (ParseToken(lltok::equal, "expected '=' after name") ||
278 ParseToken(lltok::kw_type, "expected 'type' after name") ||
282 // Set the type name, checking for conflicts as we do so.
283 bool AlreadyExists = M->addTypeName(Name, Ty);
284 if (!AlreadyExists) return false;
286 // See if this type is a forward reference. We need to eagerly resolve
287 // types to allow recursive type redefinitions below.
288 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
289 FI = ForwardRefTypes.find(Name);
290 if (FI != ForwardRefTypes.end()) {
291 if (FI->second.first.get() == Ty)
292 return Error(NameLoc, "self referential type is invalid");
294 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
295 Ty = FI->second.first.get();
296 ForwardRefTypes.erase(FI);
299 // Inserting a name that is already defined, get the existing name.
300 const Type *Existing = M->getTypeByName(Name);
301 assert(Existing && "Conflict but no matching type?!");
303 // Otherwise, this is an attempt to redefine a type. That's okay if
304 // the redefinition is identical to the original.
305 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
306 if (Existing == Ty) return false;
308 // Any other kind of (non-equivalent) redefinition is an error.
309 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
310 Ty->getDescription() + "'");
315 /// ::= 'declare' FunctionHeader
316 bool LLParser::ParseDeclare() {
317 assert(Lex.getKind() == lltok::kw_declare);
321 return ParseFunctionHeader(F, false);
325 /// ::= 'define' FunctionHeader '{' ...
326 bool LLParser::ParseDefine() {
327 assert(Lex.getKind() == lltok::kw_define);
331 return ParseFunctionHeader(F, true) ||
332 ParseFunctionBody(*F);
338 bool LLParser::ParseGlobalType(bool &IsConstant) {
339 if (Lex.getKind() == lltok::kw_constant)
341 else if (Lex.getKind() == lltok::kw_global)
345 return TokError("expected 'global' or 'constant'");
351 /// ParseNamedGlobal:
352 /// GlobalVar '=' OptionalVisibility ALIAS ...
353 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
354 bool LLParser::ParseNamedGlobal() {
355 assert(Lex.getKind() == lltok::GlobalVar);
356 LocTy NameLoc = Lex.getLoc();
357 std::string Name = Lex.getStrVal();
361 unsigned Linkage, Visibility;
362 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
363 ParseOptionalLinkage(Linkage, HasLinkage) ||
364 ParseOptionalVisibility(Visibility))
367 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
368 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
369 return ParseAlias(Name, NameLoc, Visibility);
373 // ::= '!' STRINGCONSTANT
374 bool LLParser::ParseMDString(MetadataBase *&MDS) {
376 if (ParseStringConstant(Str)) return true;
377 MDS = Context.getMDString(Str);
382 // ::= '!' MDNodeNumber
383 bool LLParser::ParseMDNode(MetadataBase *&Node) {
384 // !{ ..., !42, ... }
386 if (ParseUInt32(MID)) return true;
388 // Check existing MDNode.
389 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
390 if (I != MetadataCache.end()) {
395 // Check known forward references.
396 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
397 FI = ForwardRefMDNodes.find(MID);
398 if (FI != ForwardRefMDNodes.end()) {
399 Node = FI->second.first;
403 // Create MDNode forward reference
404 SmallVector<Value *, 1> Elts;
405 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
406 Elts.push_back(Context.getMDString(FwdRefName));
407 MDNode *FwdNode = Context.getMDNode(Elts.data(), Elts.size());
408 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
413 ///ParseNamedMetadata:
414 /// !foo = !{ !1, !2 }
415 bool LLParser::ParseNamedMetadata() {
416 assert(Lex.getKind() == lltok::NamedMD);
418 std::string Name = Lex.getStrVal();
420 if (ParseToken(lltok::equal, "expected '=' here"))
423 if (Lex.getKind() != lltok::Metadata)
424 return TokError("Expected '!' here");
427 if (Lex.getKind() != lltok::lbrace)
428 return TokError("Expected '{' here");
430 SmallVector<MetadataBase *, 8> Elts;
432 if (Lex.getKind() != lltok::Metadata)
433 return TokError("Expected '!' here");
436 if (ParseMDNode(N)) return true;
438 } while (EatIfPresent(lltok::comma));
440 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
443 NamedMDNode::Create(Name.c_str(), Name.length(),
444 Elts.data(), Elts.size(), M);
448 /// ParseStandaloneMetadata:
450 bool LLParser::ParseStandaloneMetadata() {
451 assert(Lex.getKind() == lltok::Metadata);
453 unsigned MetadataID = 0;
454 if (ParseUInt32(MetadataID))
456 if (MetadataCache.find(MetadataID) != MetadataCache.end())
457 return TokError("Metadata id is already used");
458 if (ParseToken(lltok::equal, "expected '=' here"))
462 PATypeHolder Ty(Type::VoidTy);
463 if (ParseType(Ty, TyLoc))
466 if (Lex.getKind() != lltok::Metadata)
467 return TokError("Expected metadata here");
470 if (Lex.getKind() != lltok::lbrace)
471 return TokError("Expected '{' here");
473 SmallVector<Value *, 16> Elts;
474 if (ParseMDNodeVector(Elts)
475 || ParseToken(lltok::rbrace, "expected end of metadata node"))
478 MDNode *Init = Context.getMDNode(Elts.data(), Elts.size());
479 MetadataCache[MetadataID] = Init;
480 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
481 FI = ForwardRefMDNodes.find(MetadataID);
482 if (FI != ForwardRefMDNodes.end()) {
483 MDNode *FwdNode = cast<MDNode>(FI->second.first);
484 FwdNode->replaceAllUsesWith(Init);
485 ForwardRefMDNodes.erase(FI);
492 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
495 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
496 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
498 /// Everything through visibility has already been parsed.
500 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
501 unsigned Visibility) {
502 assert(Lex.getKind() == lltok::kw_alias);
505 LocTy LinkageLoc = Lex.getLoc();
506 if (ParseOptionalLinkage(Linkage))
509 if (Linkage != GlobalValue::ExternalLinkage &&
510 Linkage != GlobalValue::WeakAnyLinkage &&
511 Linkage != GlobalValue::WeakODRLinkage &&
512 Linkage != GlobalValue::InternalLinkage &&
513 Linkage != GlobalValue::PrivateLinkage &&
514 Linkage != GlobalValue::LinkerPrivateLinkage)
515 return Error(LinkageLoc, "invalid linkage type for alias");
518 LocTy AliaseeLoc = Lex.getLoc();
519 if (Lex.getKind() != lltok::kw_bitcast &&
520 Lex.getKind() != lltok::kw_getelementptr) {
521 if (ParseGlobalTypeAndValue(Aliasee)) return true;
523 // The bitcast dest type is not present, it is implied by the dest type.
525 if (ParseValID(ID)) return true;
526 if (ID.Kind != ValID::t_Constant)
527 return Error(AliaseeLoc, "invalid aliasee");
528 Aliasee = ID.ConstantVal;
531 if (!isa<PointerType>(Aliasee->getType()))
532 return Error(AliaseeLoc, "alias must have pointer type");
534 // Okay, create the alias but do not insert it into the module yet.
535 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
536 (GlobalValue::LinkageTypes)Linkage, Name,
538 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
540 // See if this value already exists in the symbol table. If so, it is either
541 // a redefinition or a definition of a forward reference.
542 if (GlobalValue *Val =
543 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
544 // See if this was a redefinition. If so, there is no entry in
546 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
547 I = ForwardRefVals.find(Name);
548 if (I == ForwardRefVals.end())
549 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
551 // Otherwise, this was a definition of forward ref. Verify that types
553 if (Val->getType() != GA->getType())
554 return Error(NameLoc,
555 "forward reference and definition of alias have different types");
557 // If they agree, just RAUW the old value with the alias and remove the
559 Val->replaceAllUsesWith(GA);
560 Val->eraseFromParent();
561 ForwardRefVals.erase(I);
564 // Insert into the module, we know its name won't collide now.
565 M->getAliasList().push_back(GA);
566 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
572 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
573 /// OptionalAddrSpace GlobalType Type Const
574 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
575 /// OptionalAddrSpace GlobalType Type Const
577 /// Everything through visibility has been parsed already.
579 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
580 unsigned Linkage, bool HasLinkage,
581 unsigned Visibility) {
583 bool ThreadLocal, IsConstant;
586 PATypeHolder Ty(Type::VoidTy);
587 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
588 ParseOptionalAddrSpace(AddrSpace) ||
589 ParseGlobalType(IsConstant) ||
590 ParseType(Ty, TyLoc))
593 // If the linkage is specified and is external, then no initializer is
596 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
597 Linkage != GlobalValue::ExternalWeakLinkage &&
598 Linkage != GlobalValue::ExternalLinkage)) {
599 if (ParseGlobalValue(Ty, Init))
603 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
604 return Error(TyLoc, "invalid type for global variable");
606 GlobalVariable *GV = 0;
608 // See if the global was forward referenced, if so, use the global.
610 if ((GV = M->getGlobalVariable(Name, true)) &&
611 !ForwardRefVals.erase(Name))
612 return Error(NameLoc, "redefinition of global '@" + Name + "'");
614 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
615 I = ForwardRefValIDs.find(NumberedVals.size());
616 if (I != ForwardRefValIDs.end()) {
617 GV = cast<GlobalVariable>(I->second.first);
618 ForwardRefValIDs.erase(I);
623 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
624 Name, 0, false, AddrSpace);
626 if (GV->getType()->getElementType() != Ty)
628 "forward reference and definition of global have different types");
630 // Move the forward-reference to the correct spot in the module.
631 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
635 NumberedVals.push_back(GV);
637 // Set the parsed properties on the global.
639 GV->setInitializer(Init);
640 GV->setConstant(IsConstant);
641 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
642 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
643 GV->setThreadLocal(ThreadLocal);
645 // Parse attributes on the global.
646 while (Lex.getKind() == lltok::comma) {
649 if (Lex.getKind() == lltok::kw_section) {
651 GV->setSection(Lex.getStrVal());
652 if (ParseToken(lltok::StringConstant, "expected global section string"))
654 } else if (Lex.getKind() == lltok::kw_align) {
656 if (ParseOptionalAlignment(Alignment)) return true;
657 GV->setAlignment(Alignment);
659 TokError("unknown global variable property!");
667 //===----------------------------------------------------------------------===//
668 // GlobalValue Reference/Resolution Routines.
669 //===----------------------------------------------------------------------===//
671 /// GetGlobalVal - Get a value with the specified name or ID, creating a
672 /// forward reference record if needed. This can return null if the value
673 /// exists but does not have the right type.
674 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
676 const PointerType *PTy = dyn_cast<PointerType>(Ty);
678 Error(Loc, "global variable reference must have pointer type");
682 // Look this name up in the normal function symbol table.
684 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
686 // If this is a forward reference for the value, see if we already created a
687 // forward ref record.
689 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
690 I = ForwardRefVals.find(Name);
691 if (I != ForwardRefVals.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, "'@" + Name + "' 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");
712 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
714 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
715 GlobalValue::ExternalWeakLinkage, 0, Name);
718 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
722 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
723 const PointerType *PTy = dyn_cast<PointerType>(Ty);
725 Error(Loc, "global variable reference must have pointer type");
729 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
731 // If this is a forward reference for the value, see if we already created a
732 // forward ref record.
734 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
735 I = ForwardRefValIDs.find(ID);
736 if (I != ForwardRefValIDs.end())
737 Val = I->second.first;
740 // If we have the value in the symbol table or fwd-ref table, return it.
742 if (Val->getType() == Ty) return Val;
743 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
744 Val->getType()->getDescription() + "'");
748 // Otherwise, create a new forward reference for this value and remember it.
750 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
751 // Function types can return opaque but functions can't.
752 if (isa<OpaqueType>(FT->getReturnType())) {
753 Error(Loc, "function may not return opaque type");
756 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
758 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
759 GlobalValue::ExternalWeakLinkage, 0, "");
762 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
767 //===----------------------------------------------------------------------===//
769 //===----------------------------------------------------------------------===//
771 /// ParseToken - If the current token has the specified kind, eat it and return
772 /// success. Otherwise, emit the specified error and return failure.
773 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
774 if (Lex.getKind() != T)
775 return TokError(ErrMsg);
780 /// ParseStringConstant
781 /// ::= StringConstant
782 bool LLParser::ParseStringConstant(std::string &Result) {
783 if (Lex.getKind() != lltok::StringConstant)
784 return TokError("expected string constant");
785 Result = Lex.getStrVal();
792 bool LLParser::ParseUInt32(unsigned &Val) {
793 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
794 return TokError("expected integer");
795 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
796 if (Val64 != unsigned(Val64))
797 return TokError("expected 32-bit integer (too large)");
804 /// ParseOptionalAddrSpace
806 /// := 'addrspace' '(' uint32 ')'
807 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
809 if (!EatIfPresent(lltok::kw_addrspace))
811 return ParseToken(lltok::lparen, "expected '(' in address space") ||
812 ParseUInt32(AddrSpace) ||
813 ParseToken(lltok::rparen, "expected ')' in address space");
816 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
817 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
818 /// 2: function attr.
819 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
820 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
821 Attrs = Attribute::None;
822 LocTy AttrLoc = Lex.getLoc();
825 switch (Lex.getKind()) {
828 // Treat these as signext/zeroext if they occur in the argument list after
829 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
830 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
832 // FIXME: REMOVE THIS IN LLVM 3.0
834 if (Lex.getKind() == lltok::kw_sext)
835 Attrs |= Attribute::SExt;
837 Attrs |= Attribute::ZExt;
841 default: // End of attributes.
842 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
843 return Error(AttrLoc, "invalid use of function-only attribute");
845 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
846 return Error(AttrLoc, "invalid use of parameter-only attribute");
849 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
850 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
851 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
852 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
853 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
854 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
855 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
856 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
858 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
859 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
860 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
861 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
862 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
863 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
864 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
865 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
866 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
867 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
868 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
869 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
871 case lltok::kw_align: {
873 if (ParseOptionalAlignment(Alignment))
875 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
883 /// ParseOptionalLinkage
886 /// ::= 'linker_private'
891 /// ::= 'linkonce_odr'
896 /// ::= 'extern_weak'
898 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
900 switch (Lex.getKind()) {
901 default: Res=GlobalValue::ExternalLinkage; return false;
902 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
903 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
904 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
905 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
906 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
907 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
908 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
909 case lltok::kw_available_externally:
910 Res = GlobalValue::AvailableExternallyLinkage;
912 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
913 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
914 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
915 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
916 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
917 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
924 /// ParseOptionalVisibility
930 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
931 switch (Lex.getKind()) {
932 default: Res = GlobalValue::DefaultVisibility; return false;
933 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
934 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
935 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
941 /// ParseOptionalCallingConv
946 /// ::= 'x86_stdcallcc'
947 /// ::= 'x86_fastcallcc'
949 /// ::= 'arm_aapcscc'
950 /// ::= 'arm_aapcs_vfpcc'
953 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
954 switch (Lex.getKind()) {
955 default: CC = CallingConv::C; return false;
956 case lltok::kw_ccc: CC = CallingConv::C; break;
957 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
958 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
959 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
960 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
961 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
962 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
963 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
964 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
970 /// ParseOptionalAlignment
973 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
975 if (!EatIfPresent(lltok::kw_align))
977 LocTy AlignLoc = Lex.getLoc();
978 if (ParseUInt32(Alignment)) return true;
979 if (!isPowerOf2_32(Alignment))
980 return Error(AlignLoc, "alignment is not a power of two");
984 /// ParseOptionalCommaAlignment
986 /// ::= ',' 'align' 4
987 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
989 if (!EatIfPresent(lltok::comma))
991 return ParseToken(lltok::kw_align, "expected 'align'") ||
992 ParseUInt32(Alignment);
996 /// ::= (',' uint32)+
997 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
998 if (Lex.getKind() != lltok::comma)
999 return TokError("expected ',' as start of index list");
1001 while (EatIfPresent(lltok::comma)) {
1003 if (ParseUInt32(Idx)) return true;
1004 Indices.push_back(Idx);
1010 //===----------------------------------------------------------------------===//
1012 //===----------------------------------------------------------------------===//
1014 /// ParseType - Parse and resolve a full type.
1015 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1016 LocTy TypeLoc = Lex.getLoc();
1017 if (ParseTypeRec(Result)) return true;
1019 // Verify no unresolved uprefs.
1020 if (!UpRefs.empty())
1021 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1023 if (!AllowVoid && Result.get() == Type::VoidTy)
1024 return Error(TypeLoc, "void type only allowed for function results");
1029 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1030 /// called. It loops through the UpRefs vector, which is a list of the
1031 /// currently active types. For each type, if the up-reference is contained in
1032 /// the newly completed type, we decrement the level count. When the level
1033 /// count reaches zero, the up-referenced type is the type that is passed in:
1034 /// thus we can complete the cycle.
1036 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1037 // If Ty isn't abstract, or if there are no up-references in it, then there is
1038 // nothing to resolve here.
1039 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1041 PATypeHolder Ty(ty);
1043 errs() << "Type '" << Ty->getDescription()
1044 << "' newly formed. Resolving upreferences.\n"
1045 << UpRefs.size() << " upreferences active!\n";
1048 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1049 // to zero), we resolve them all together before we resolve them to Ty. At
1050 // the end of the loop, if there is anything to resolve to Ty, it will be in
1052 OpaqueType *TypeToResolve = 0;
1054 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1055 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1057 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1058 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1061 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1062 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1063 << (ContainsType ? "true" : "false")
1064 << " level=" << UpRefs[i].NestingLevel << "\n";
1069 // Decrement level of upreference
1070 unsigned Level = --UpRefs[i].NestingLevel;
1071 UpRefs[i].LastContainedTy = Ty;
1073 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1078 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1081 TypeToResolve = UpRefs[i].UpRefTy;
1083 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1084 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1085 --i; // Do not skip the next element.
1089 TypeToResolve->refineAbstractTypeTo(Ty);
1095 /// ParseTypeRec - The recursive function used to process the internal
1096 /// implementation details of types.
1097 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1098 switch (Lex.getKind()) {
1100 return TokError("expected type");
1102 // TypeRec ::= 'float' | 'void' (etc)
1103 Result = Lex.getTyVal();
1106 case lltok::kw_opaque:
1107 // TypeRec ::= 'opaque'
1108 Result = Context.getOpaqueType();
1112 // TypeRec ::= '{' ... '}'
1113 if (ParseStructType(Result, false))
1116 case lltok::lsquare:
1117 // TypeRec ::= '[' ... ']'
1118 Lex.Lex(); // eat the lsquare.
1119 if (ParseArrayVectorType(Result, false))
1122 case lltok::less: // Either vector or packed struct.
1123 // TypeRec ::= '<' ... '>'
1125 if (Lex.getKind() == lltok::lbrace) {
1126 if (ParseStructType(Result, true) ||
1127 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1129 } else if (ParseArrayVectorType(Result, true))
1132 case lltok::LocalVar:
1133 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1135 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1138 Result = Context.getOpaqueType();
1139 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1140 std::make_pair(Result,
1142 M->addTypeName(Lex.getStrVal(), Result.get());
1147 case lltok::LocalVarID:
1149 if (Lex.getUIntVal() < NumberedTypes.size())
1150 Result = NumberedTypes[Lex.getUIntVal()];
1152 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1153 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1154 if (I != ForwardRefTypeIDs.end())
1155 Result = I->second.first;
1157 Result = Context.getOpaqueType();
1158 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1159 std::make_pair(Result,
1165 case lltok::backslash: {
1166 // TypeRec ::= '\' 4
1169 if (ParseUInt32(Val)) return true;
1170 OpaqueType *OT = Context.getOpaqueType(); //Use temporary placeholder.
1171 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1177 // Parse the type suffixes.
1179 switch (Lex.getKind()) {
1181 default: return false;
1183 // TypeRec ::= TypeRec '*'
1185 if (Result.get() == Type::LabelTy)
1186 return TokError("basic block pointers are invalid");
1187 if (Result.get() == Type::VoidTy)
1188 return TokError("pointers to void are invalid; use i8* instead");
1189 if (!PointerType::isValidElementType(Result.get()))
1190 return TokError("pointer to this type is invalid");
1191 Result = HandleUpRefs(Context.getPointerTypeUnqual(Result.get()));
1195 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1196 case lltok::kw_addrspace: {
1197 if (Result.get() == Type::LabelTy)
1198 return TokError("basic block pointers are invalid");
1199 if (Result.get() == Type::VoidTy)
1200 return TokError("pointers to void are invalid; use i8* instead");
1201 if (!PointerType::isValidElementType(Result.get()))
1202 return TokError("pointer to this type is invalid");
1204 if (ParseOptionalAddrSpace(AddrSpace) ||
1205 ParseToken(lltok::star, "expected '*' in address space"))
1208 Result = HandleUpRefs(Context.getPointerType(Result.get(), AddrSpace));
1212 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1214 if (ParseFunctionType(Result))
1221 /// ParseParameterList
1223 /// ::= '(' Arg (',' Arg)* ')'
1225 /// ::= Type OptionalAttributes Value OptionalAttributes
1226 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1227 PerFunctionState &PFS) {
1228 if (ParseToken(lltok::lparen, "expected '(' in call"))
1231 while (Lex.getKind() != lltok::rparen) {
1232 // If this isn't the first argument, we need a comma.
1233 if (!ArgList.empty() &&
1234 ParseToken(lltok::comma, "expected ',' in argument list"))
1237 // Parse the argument.
1239 PATypeHolder ArgTy(Type::VoidTy);
1240 unsigned ArgAttrs1, ArgAttrs2;
1242 if (ParseType(ArgTy, ArgLoc) ||
1243 ParseOptionalAttrs(ArgAttrs1, 0) ||
1244 ParseValue(ArgTy, V, PFS) ||
1245 // FIXME: Should not allow attributes after the argument, remove this in
1247 ParseOptionalAttrs(ArgAttrs2, 3))
1249 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1252 Lex.Lex(); // Lex the ')'.
1258 /// ParseArgumentList - Parse the argument list for a function type or function
1259 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1260 /// ::= '(' ArgTypeListI ')'
1264 /// ::= ArgTypeList ',' '...'
1265 /// ::= ArgType (',' ArgType)*
1267 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1268 bool &isVarArg, bool inType) {
1270 assert(Lex.getKind() == lltok::lparen);
1271 Lex.Lex(); // eat the (.
1273 if (Lex.getKind() == lltok::rparen) {
1275 } else if (Lex.getKind() == lltok::dotdotdot) {
1279 LocTy TypeLoc = Lex.getLoc();
1280 PATypeHolder ArgTy(Type::VoidTy);
1284 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1285 // types (such as a function returning a pointer to itself). If parsing a
1286 // function prototype, we require fully resolved types.
1287 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1288 ParseOptionalAttrs(Attrs, 0)) return true;
1290 if (ArgTy == Type::VoidTy)
1291 return Error(TypeLoc, "argument can not have void type");
1293 if (Lex.getKind() == lltok::LocalVar ||
1294 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1295 Name = Lex.getStrVal();
1299 if (!FunctionType::isValidArgumentType(ArgTy))
1300 return Error(TypeLoc, "invalid type for function argument");
1302 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1304 while (EatIfPresent(lltok::comma)) {
1305 // Handle ... at end of arg list.
1306 if (EatIfPresent(lltok::dotdotdot)) {
1311 // Otherwise must be an argument type.
1312 TypeLoc = Lex.getLoc();
1313 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1314 ParseOptionalAttrs(Attrs, 0)) return true;
1316 if (ArgTy == Type::VoidTy)
1317 return Error(TypeLoc, "argument can not have void type");
1319 if (Lex.getKind() == lltok::LocalVar ||
1320 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1321 Name = Lex.getStrVal();
1327 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1328 return Error(TypeLoc, "invalid type for function argument");
1330 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1334 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1337 /// ParseFunctionType
1338 /// ::= Type ArgumentList OptionalAttrs
1339 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1340 assert(Lex.getKind() == lltok::lparen);
1342 if (!FunctionType::isValidReturnType(Result))
1343 return TokError("invalid function return type");
1345 std::vector<ArgInfo> ArgList;
1348 if (ParseArgumentList(ArgList, isVarArg, true) ||
1349 // FIXME: Allow, but ignore attributes on function types!
1350 // FIXME: Remove in LLVM 3.0
1351 ParseOptionalAttrs(Attrs, 2))
1354 // Reject names on the arguments lists.
1355 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1356 if (!ArgList[i].Name.empty())
1357 return Error(ArgList[i].Loc, "argument name invalid in function type");
1358 if (!ArgList[i].Attrs != 0) {
1359 // Allow but ignore attributes on function types; this permits
1361 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1365 std::vector<const Type*> ArgListTy;
1366 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1367 ArgListTy.push_back(ArgList[i].Type);
1369 Result = HandleUpRefs(Context.getFunctionType(Result.get(),
1370 ArgListTy, isVarArg));
1374 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1377 /// ::= '{' TypeRec (',' TypeRec)* '}'
1378 /// ::= '<' '{' '}' '>'
1379 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1380 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1381 assert(Lex.getKind() == lltok::lbrace);
1382 Lex.Lex(); // Consume the '{'
1384 if (EatIfPresent(lltok::rbrace)) {
1385 Result = Context.getStructType(Packed);
1389 std::vector<PATypeHolder> ParamsList;
1390 LocTy EltTyLoc = Lex.getLoc();
1391 if (ParseTypeRec(Result)) return true;
1392 ParamsList.push_back(Result);
1394 if (Result == Type::VoidTy)
1395 return Error(EltTyLoc, "struct element can not have void type");
1396 if (!StructType::isValidElementType(Result))
1397 return Error(EltTyLoc, "invalid element type for struct");
1399 while (EatIfPresent(lltok::comma)) {
1400 EltTyLoc = Lex.getLoc();
1401 if (ParseTypeRec(Result)) return true;
1403 if (Result == Type::VoidTy)
1404 return Error(EltTyLoc, "struct element can not have void type");
1405 if (!StructType::isValidElementType(Result))
1406 return Error(EltTyLoc, "invalid element type for struct");
1408 ParamsList.push_back(Result);
1411 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1414 std::vector<const Type*> ParamsListTy;
1415 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1416 ParamsListTy.push_back(ParamsList[i].get());
1417 Result = HandleUpRefs(Context.getStructType(ParamsListTy, Packed));
1421 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1422 /// token has already been consumed.
1424 /// ::= '[' APSINTVAL 'x' Types ']'
1425 /// ::= '<' APSINTVAL 'x' Types '>'
1426 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1427 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1428 Lex.getAPSIntVal().getBitWidth() > 64)
1429 return TokError("expected number in address space");
1431 LocTy SizeLoc = Lex.getLoc();
1432 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1435 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1438 LocTy TypeLoc = Lex.getLoc();
1439 PATypeHolder EltTy(Type::VoidTy);
1440 if (ParseTypeRec(EltTy)) return true;
1442 if (EltTy == Type::VoidTy)
1443 return Error(TypeLoc, "array and vector element type cannot be void");
1445 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1446 "expected end of sequential type"))
1451 return Error(SizeLoc, "zero element vector is illegal");
1452 if ((unsigned)Size != Size)
1453 return Error(SizeLoc, "size too large for vector");
1454 if (!VectorType::isValidElementType(EltTy))
1455 return Error(TypeLoc, "vector element type must be fp or integer");
1456 Result = Context.getVectorType(EltTy, unsigned(Size));
1458 if (!ArrayType::isValidElementType(EltTy))
1459 return Error(TypeLoc, "invalid array element type");
1460 Result = HandleUpRefs(Context.getArrayType(EltTy, Size));
1465 //===----------------------------------------------------------------------===//
1466 // Function Semantic Analysis.
1467 //===----------------------------------------------------------------------===//
1469 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1472 // Insert unnamed arguments into the NumberedVals list.
1473 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1476 NumberedVals.push_back(AI);
1479 LLParser::PerFunctionState::~PerFunctionState() {
1480 // If there were any forward referenced non-basicblock values, delete them.
1481 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1482 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1483 if (!isa<BasicBlock>(I->second.first)) {
1484 I->second.first->replaceAllUsesWith(
1485 P.getContext().getUndef(I->second.first->getType()));
1486 delete I->second.first;
1487 I->second.first = 0;
1490 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1491 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1492 if (!isa<BasicBlock>(I->second.first)) {
1493 I->second.first->replaceAllUsesWith(
1494 P.getContext().getUndef(I->second.first->getType()));
1495 delete I->second.first;
1496 I->second.first = 0;
1500 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1501 if (!ForwardRefVals.empty())
1502 return P.Error(ForwardRefVals.begin()->second.second,
1503 "use of undefined value '%" + ForwardRefVals.begin()->first +
1505 if (!ForwardRefValIDs.empty())
1506 return P.Error(ForwardRefValIDs.begin()->second.second,
1507 "use of undefined value '%" +
1508 utostr(ForwardRefValIDs.begin()->first) + "'");
1513 /// GetVal - Get a value with the specified name or ID, creating a
1514 /// forward reference record if needed. This can return null if the value
1515 /// exists but does not have the right type.
1516 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1517 const Type *Ty, LocTy Loc) {
1518 // Look this name up in the normal function symbol table.
1519 Value *Val = F.getValueSymbolTable().lookup(Name);
1521 // If this is a forward reference for the value, see if we already created a
1522 // forward ref record.
1524 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1525 I = ForwardRefVals.find(Name);
1526 if (I != ForwardRefVals.end())
1527 Val = I->second.first;
1530 // If we have the value in the symbol table or fwd-ref table, return it.
1532 if (Val->getType() == Ty) return Val;
1533 if (Ty == Type::LabelTy)
1534 P.Error(Loc, "'%" + Name + "' is not a basic block");
1536 P.Error(Loc, "'%" + Name + "' defined with type '" +
1537 Val->getType()->getDescription() + "'");
1541 // Don't make placeholders with invalid type.
1542 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1543 P.Error(Loc, "invalid use of a non-first-class type");
1547 // Otherwise, create a new forward reference for this value and remember it.
1549 if (Ty == Type::LabelTy)
1550 FwdVal = BasicBlock::Create(Name, &F);
1552 FwdVal = new Argument(Ty, Name);
1554 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1558 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1560 // Look this name up in the normal function symbol table.
1561 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1563 // If this is a forward reference for the value, see if we already created a
1564 // forward ref record.
1566 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1567 I = ForwardRefValIDs.find(ID);
1568 if (I != ForwardRefValIDs.end())
1569 Val = I->second.first;
1572 // If we have the value in the symbol table or fwd-ref table, return it.
1574 if (Val->getType() == Ty) return Val;
1575 if (Ty == Type::LabelTy)
1576 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1578 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1579 Val->getType()->getDescription() + "'");
1583 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1584 P.Error(Loc, "invalid use of a non-first-class type");
1588 // Otherwise, create a new forward reference for this value and remember it.
1590 if (Ty == Type::LabelTy)
1591 FwdVal = BasicBlock::Create("", &F);
1593 FwdVal = new Argument(Ty);
1595 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1599 /// SetInstName - After an instruction is parsed and inserted into its
1600 /// basic block, this installs its name.
1601 bool LLParser::PerFunctionState::SetInstName(int NameID,
1602 const std::string &NameStr,
1603 LocTy NameLoc, Instruction *Inst) {
1604 // If this instruction has void type, it cannot have a name or ID specified.
1605 if (Inst->getType() == Type::VoidTy) {
1606 if (NameID != -1 || !NameStr.empty())
1607 return P.Error(NameLoc, "instructions returning void cannot have a name");
1611 // If this was a numbered instruction, verify that the instruction is the
1612 // expected value and resolve any forward references.
1613 if (NameStr.empty()) {
1614 // If neither a name nor an ID was specified, just use the next ID.
1616 NameID = NumberedVals.size();
1618 if (unsigned(NameID) != NumberedVals.size())
1619 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1620 utostr(NumberedVals.size()) + "'");
1622 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1623 ForwardRefValIDs.find(NameID);
1624 if (FI != ForwardRefValIDs.end()) {
1625 if (FI->second.first->getType() != Inst->getType())
1626 return P.Error(NameLoc, "instruction forward referenced with type '" +
1627 FI->second.first->getType()->getDescription() + "'");
1628 FI->second.first->replaceAllUsesWith(Inst);
1629 ForwardRefValIDs.erase(FI);
1632 NumberedVals.push_back(Inst);
1636 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1637 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1638 FI = ForwardRefVals.find(NameStr);
1639 if (FI != ForwardRefVals.end()) {
1640 if (FI->second.first->getType() != Inst->getType())
1641 return P.Error(NameLoc, "instruction forward referenced with type '" +
1642 FI->second.first->getType()->getDescription() + "'");
1643 FI->second.first->replaceAllUsesWith(Inst);
1644 ForwardRefVals.erase(FI);
1647 // Set the name on the instruction.
1648 Inst->setName(NameStr);
1650 if (Inst->getNameStr() != NameStr)
1651 return P.Error(NameLoc, "multiple definition of local value named '" +
1656 /// GetBB - Get a basic block with the specified name or ID, creating a
1657 /// forward reference record if needed.
1658 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1660 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1663 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1664 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1667 /// DefineBB - Define the specified basic block, which is either named or
1668 /// unnamed. If there is an error, this returns null otherwise it returns
1669 /// the block being defined.
1670 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1674 BB = GetBB(NumberedVals.size(), Loc);
1676 BB = GetBB(Name, Loc);
1677 if (BB == 0) return 0; // Already diagnosed error.
1679 // Move the block to the end of the function. Forward ref'd blocks are
1680 // inserted wherever they happen to be referenced.
1681 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1683 // Remove the block from forward ref sets.
1685 ForwardRefValIDs.erase(NumberedVals.size());
1686 NumberedVals.push_back(BB);
1688 // BB forward references are already in the function symbol table.
1689 ForwardRefVals.erase(Name);
1695 //===----------------------------------------------------------------------===//
1697 //===----------------------------------------------------------------------===//
1699 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1700 /// type implied. For example, if we parse "4" we don't know what integer type
1701 /// it has. The value will later be combined with its type and checked for
1703 bool LLParser::ParseValID(ValID &ID) {
1704 ID.Loc = Lex.getLoc();
1705 switch (Lex.getKind()) {
1706 default: return TokError("expected value token");
1707 case lltok::GlobalID: // @42
1708 ID.UIntVal = Lex.getUIntVal();
1709 ID.Kind = ValID::t_GlobalID;
1711 case lltok::GlobalVar: // @foo
1712 ID.StrVal = Lex.getStrVal();
1713 ID.Kind = ValID::t_GlobalName;
1715 case lltok::LocalVarID: // %42
1716 ID.UIntVal = Lex.getUIntVal();
1717 ID.Kind = ValID::t_LocalID;
1719 case lltok::LocalVar: // %foo
1720 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1721 ID.StrVal = Lex.getStrVal();
1722 ID.Kind = ValID::t_LocalName;
1724 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1725 ID.Kind = ValID::t_Metadata;
1727 if (Lex.getKind() == lltok::lbrace) {
1728 SmallVector<Value*, 16> Elts;
1729 if (ParseMDNodeVector(Elts) ||
1730 ParseToken(lltok::rbrace, "expected end of metadata node"))
1733 ID.MetadataVal = Context.getMDNode(Elts.data(), Elts.size());
1737 // Standalone metadata reference
1738 // !{ ..., !42, ... }
1739 if (!ParseMDNode(ID.MetadataVal))
1743 // ::= '!' STRINGCONSTANT
1744 if (ParseMDString(ID.MetadataVal)) return true;
1745 ID.Kind = ValID::t_Metadata;
1749 ID.APSIntVal = Lex.getAPSIntVal();
1750 ID.Kind = ValID::t_APSInt;
1752 case lltok::APFloat:
1753 ID.APFloatVal = Lex.getAPFloatVal();
1754 ID.Kind = ValID::t_APFloat;
1756 case lltok::kw_true:
1757 ID.ConstantVal = Context.getTrue();
1758 ID.Kind = ValID::t_Constant;
1760 case lltok::kw_false:
1761 ID.ConstantVal = Context.getFalse();
1762 ID.Kind = ValID::t_Constant;
1764 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1765 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1766 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1768 case lltok::lbrace: {
1769 // ValID ::= '{' ConstVector '}'
1771 SmallVector<Constant*, 16> Elts;
1772 if (ParseGlobalValueVector(Elts) ||
1773 ParseToken(lltok::rbrace, "expected end of struct constant"))
1776 ID.ConstantVal = ConstantStruct::get(Elts.data(), Elts.size(), false);
1777 ID.Kind = ValID::t_Constant;
1781 // ValID ::= '<' ConstVector '>' --> Vector.
1782 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1784 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1786 SmallVector<Constant*, 16> Elts;
1787 LocTy FirstEltLoc = Lex.getLoc();
1788 if (ParseGlobalValueVector(Elts) ||
1790 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1791 ParseToken(lltok::greater, "expected end of constant"))
1794 if (isPackedStruct) {
1796 ConstantStruct::get(Elts.data(), Elts.size(), true);
1797 ID.Kind = ValID::t_Constant;
1802 return Error(ID.Loc, "constant vector must not be empty");
1804 if (!Elts[0]->getType()->isInteger() &&
1805 !Elts[0]->getType()->isFloatingPoint())
1806 return Error(FirstEltLoc,
1807 "vector elements must have integer or floating point type");
1809 // Verify that all the vector elements have the same type.
1810 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1811 if (Elts[i]->getType() != Elts[0]->getType())
1812 return Error(FirstEltLoc,
1813 "vector element #" + utostr(i) +
1814 " is not of type '" + Elts[0]->getType()->getDescription());
1816 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1817 ID.Kind = ValID::t_Constant;
1820 case lltok::lsquare: { // Array Constant
1822 SmallVector<Constant*, 16> Elts;
1823 LocTy FirstEltLoc = Lex.getLoc();
1824 if (ParseGlobalValueVector(Elts) ||
1825 ParseToken(lltok::rsquare, "expected end of array constant"))
1828 // Handle empty element.
1830 // Use undef instead of an array because it's inconvenient to determine
1831 // the element type at this point, there being no elements to examine.
1832 ID.Kind = ValID::t_EmptyArray;
1836 if (!Elts[0]->getType()->isFirstClassType())
1837 return Error(FirstEltLoc, "invalid array element type: " +
1838 Elts[0]->getType()->getDescription());
1840 ArrayType *ATy = Context.getArrayType(Elts[0]->getType(), Elts.size());
1842 // Verify all elements are correct type!
1843 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1844 if (Elts[i]->getType() != Elts[0]->getType())
1845 return Error(FirstEltLoc,
1846 "array element #" + utostr(i) +
1847 " is not of type '" +Elts[0]->getType()->getDescription());
1850 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
1851 ID.Kind = ValID::t_Constant;
1854 case lltok::kw_c: // c "foo"
1856 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1857 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1858 ID.Kind = ValID::t_Constant;
1861 case lltok::kw_asm: {
1862 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1865 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1866 ParseStringConstant(ID.StrVal) ||
1867 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1868 ParseToken(lltok::StringConstant, "expected constraint string"))
1870 ID.StrVal2 = Lex.getStrVal();
1871 ID.UIntVal = HasSideEffect;
1872 ID.Kind = ValID::t_InlineAsm;
1876 case lltok::kw_trunc:
1877 case lltok::kw_zext:
1878 case lltok::kw_sext:
1879 case lltok::kw_fptrunc:
1880 case lltok::kw_fpext:
1881 case lltok::kw_bitcast:
1882 case lltok::kw_uitofp:
1883 case lltok::kw_sitofp:
1884 case lltok::kw_fptoui:
1885 case lltok::kw_fptosi:
1886 case lltok::kw_inttoptr:
1887 case lltok::kw_ptrtoint: {
1888 unsigned Opc = Lex.getUIntVal();
1889 PATypeHolder DestTy(Type::VoidTy);
1892 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1893 ParseGlobalTypeAndValue(SrcVal) ||
1894 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
1895 ParseType(DestTy) ||
1896 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1898 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1899 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1900 SrcVal->getType()->getDescription() + "' to '" +
1901 DestTy->getDescription() + "'");
1902 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
1904 ID.Kind = ValID::t_Constant;
1907 case lltok::kw_extractvalue: {
1910 SmallVector<unsigned, 4> Indices;
1911 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1912 ParseGlobalTypeAndValue(Val) ||
1913 ParseIndexList(Indices) ||
1914 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1916 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1917 return Error(ID.Loc, "extractvalue operand must be array or struct");
1918 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1920 return Error(ID.Loc, "invalid indices for extractvalue");
1922 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
1923 ID.Kind = ValID::t_Constant;
1926 case lltok::kw_insertvalue: {
1928 Constant *Val0, *Val1;
1929 SmallVector<unsigned, 4> Indices;
1930 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1931 ParseGlobalTypeAndValue(Val0) ||
1932 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1933 ParseGlobalTypeAndValue(Val1) ||
1934 ParseIndexList(Indices) ||
1935 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1937 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1938 return Error(ID.Loc, "extractvalue operand must be array or struct");
1939 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1941 return Error(ID.Loc, "invalid indices for insertvalue");
1942 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1943 Indices.data(), Indices.size());
1944 ID.Kind = ValID::t_Constant;
1947 case lltok::kw_icmp:
1948 case lltok::kw_fcmp: {
1949 unsigned PredVal, Opc = Lex.getUIntVal();
1950 Constant *Val0, *Val1;
1952 if (ParseCmpPredicate(PredVal, Opc) ||
1953 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1954 ParseGlobalTypeAndValue(Val0) ||
1955 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1956 ParseGlobalTypeAndValue(Val1) ||
1957 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1960 if (Val0->getType() != Val1->getType())
1961 return Error(ID.Loc, "compare operands must have the same type");
1963 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1965 if (Opc == Instruction::FCmp) {
1966 if (!Val0->getType()->isFPOrFPVector())
1967 return Error(ID.Loc, "fcmp requires floating point operands");
1968 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1970 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
1971 if (!Val0->getType()->isIntOrIntVector() &&
1972 !isa<PointerType>(Val0->getType()))
1973 return Error(ID.Loc, "icmp requires pointer or integer operands");
1974 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1976 ID.Kind = ValID::t_Constant;
1980 // Binary Operators.
1982 case lltok::kw_fadd:
1984 case lltok::kw_fsub:
1986 case lltok::kw_fmul:
1987 case lltok::kw_udiv:
1988 case lltok::kw_sdiv:
1989 case lltok::kw_fdiv:
1990 case lltok::kw_urem:
1991 case lltok::kw_srem:
1992 case lltok::kw_frem: {
1996 unsigned Opc = Lex.getUIntVal();
1997 Constant *Val0, *Val1;
1999 LocTy ModifierLoc = Lex.getLoc();
2000 if (Opc == Instruction::Add ||
2001 Opc == Instruction::Sub ||
2002 Opc == Instruction::Mul) {
2003 if (EatIfPresent(lltok::kw_nuw))
2005 if (EatIfPresent(lltok::kw_nsw)) {
2007 if (EatIfPresent(lltok::kw_nuw))
2010 } else if (Opc == Instruction::SDiv) {
2011 if (EatIfPresent(lltok::kw_exact))
2014 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2015 ParseGlobalTypeAndValue(Val0) ||
2016 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2017 ParseGlobalTypeAndValue(Val1) ||
2018 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2020 if (Val0->getType() != Val1->getType())
2021 return Error(ID.Loc, "operands of constexpr must have same type");
2022 if (!Val0->getType()->isIntOrIntVector()) {
2024 return Error(ModifierLoc, "nuw only applies to integer operations");
2026 return Error(ModifierLoc, "nsw only applies to integer operations");
2028 // API compatibility: Accept either integer or floating-point types with
2029 // add, sub, and mul.
2030 if (!Val0->getType()->isIntOrIntVector() &&
2031 !Val0->getType()->isFPOrFPVector())
2032 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2033 Constant *C = ConstantExpr::get(Opc, Val0, Val1);
2035 cast<OverflowingBinaryOperator>(C)->setHasNoUnsignedOverflow(true);
2037 cast<OverflowingBinaryOperator>(C)->setHasNoSignedOverflow(true);
2039 cast<SDivOperator>(C)->setIsExact(true);
2041 ID.Kind = ValID::t_Constant;
2045 // Logical Operations
2047 case lltok::kw_lshr:
2048 case lltok::kw_ashr:
2051 case lltok::kw_xor: {
2052 unsigned Opc = Lex.getUIntVal();
2053 Constant *Val0, *Val1;
2055 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2056 ParseGlobalTypeAndValue(Val0) ||
2057 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2058 ParseGlobalTypeAndValue(Val1) ||
2059 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2061 if (Val0->getType() != Val1->getType())
2062 return Error(ID.Loc, "operands of constexpr must have same type");
2063 if (!Val0->getType()->isIntOrIntVector())
2064 return Error(ID.Loc,
2065 "constexpr requires integer or integer vector operands");
2066 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2067 ID.Kind = ValID::t_Constant;
2071 case lltok::kw_getelementptr:
2072 case lltok::kw_shufflevector:
2073 case lltok::kw_insertelement:
2074 case lltok::kw_extractelement:
2075 case lltok::kw_select: {
2076 unsigned Opc = Lex.getUIntVal();
2077 SmallVector<Constant*, 16> Elts;
2078 bool InBounds = false;
2080 if (Opc == Instruction::GetElementPtr)
2081 InBounds = EatIfPresent(lltok::kw_inbounds);
2082 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2083 ParseGlobalValueVector(Elts) ||
2084 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2087 if (Opc == Instruction::GetElementPtr) {
2088 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2089 return Error(ID.Loc, "getelementptr requires pointer operand");
2091 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2092 (Value**)(Elts.data() + 1),
2094 return Error(ID.Loc, "invalid indices for getelementptr");
2095 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
2096 Elts.data() + 1, Elts.size() - 1);
2098 cast<GEPOperator>(ID.ConstantVal)->setIsInBounds(true);
2099 } else if (Opc == Instruction::Select) {
2100 if (Elts.size() != 3)
2101 return Error(ID.Loc, "expected three operands to select");
2102 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2104 return Error(ID.Loc, Reason);
2105 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2106 } else if (Opc == Instruction::ShuffleVector) {
2107 if (Elts.size() != 3)
2108 return Error(ID.Loc, "expected three operands to shufflevector");
2109 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2110 return Error(ID.Loc, "invalid operands to shufflevector");
2112 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2113 } else if (Opc == Instruction::ExtractElement) {
2114 if (Elts.size() != 2)
2115 return Error(ID.Loc, "expected two operands to extractelement");
2116 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2117 return Error(ID.Loc, "invalid extractelement operands");
2118 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2120 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2121 if (Elts.size() != 3)
2122 return Error(ID.Loc, "expected three operands to insertelement");
2123 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2124 return Error(ID.Loc, "invalid insertelement operands");
2126 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2129 ID.Kind = ValID::t_Constant;
2138 /// ParseGlobalValue - Parse a global value with the specified type.
2139 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2142 return ParseValID(ID) ||
2143 ConvertGlobalValIDToValue(Ty, ID, V);
2146 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2148 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2150 if (isa<FunctionType>(Ty))
2151 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2154 default: llvm_unreachable("Unknown ValID!");
2155 case ValID::t_Metadata:
2156 return Error(ID.Loc, "invalid use of metadata");
2157 case ValID::t_LocalID:
2158 case ValID::t_LocalName:
2159 return Error(ID.Loc, "invalid use of function-local name");
2160 case ValID::t_InlineAsm:
2161 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2162 case ValID::t_GlobalName:
2163 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2165 case ValID::t_GlobalID:
2166 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2168 case ValID::t_APSInt:
2169 if (!isa<IntegerType>(Ty))
2170 return Error(ID.Loc, "integer constant must have integer type");
2171 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2172 V = ConstantInt::get(Context, ID.APSIntVal);
2174 case ValID::t_APFloat:
2175 if (!Ty->isFloatingPoint() ||
2176 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2177 return Error(ID.Loc, "floating point constant invalid for type");
2179 // The lexer has no type info, so builds all float and double FP constants
2180 // as double. Fix this here. Long double does not need this.
2181 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2182 Ty == Type::FloatTy) {
2184 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2187 V = ConstantFP::get(Context, ID.APFloatVal);
2189 if (V->getType() != Ty)
2190 return Error(ID.Loc, "floating point constant does not have type '" +
2191 Ty->getDescription() + "'");
2195 if (!isa<PointerType>(Ty))
2196 return Error(ID.Loc, "null must be a pointer type");
2197 V = Context.getConstantPointerNull(cast<PointerType>(Ty));
2199 case ValID::t_Undef:
2200 // FIXME: LabelTy should not be a first-class type.
2201 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2202 !isa<OpaqueType>(Ty))
2203 return Error(ID.Loc, "invalid type for undef constant");
2204 V = Context.getUndef(Ty);
2206 case ValID::t_EmptyArray:
2207 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2208 return Error(ID.Loc, "invalid empty array initializer");
2209 V = Context.getUndef(Ty);
2212 // FIXME: LabelTy should not be a first-class type.
2213 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2214 return Error(ID.Loc, "invalid type for null constant");
2215 V = Context.getNullValue(Ty);
2217 case ValID::t_Constant:
2218 if (ID.ConstantVal->getType() != Ty)
2219 return Error(ID.Loc, "constant expression type mismatch");
2225 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2226 PATypeHolder Type(Type::VoidTy);
2227 return ParseType(Type) ||
2228 ParseGlobalValue(Type, V);
2231 /// ParseGlobalValueVector
2233 /// ::= TypeAndValue (',' TypeAndValue)*
2234 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2236 if (Lex.getKind() == lltok::rbrace ||
2237 Lex.getKind() == lltok::rsquare ||
2238 Lex.getKind() == lltok::greater ||
2239 Lex.getKind() == lltok::rparen)
2243 if (ParseGlobalTypeAndValue(C)) return true;
2246 while (EatIfPresent(lltok::comma)) {
2247 if (ParseGlobalTypeAndValue(C)) return true;
2255 //===----------------------------------------------------------------------===//
2256 // Function Parsing.
2257 //===----------------------------------------------------------------------===//
2259 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2260 PerFunctionState &PFS) {
2261 if (ID.Kind == ValID::t_LocalID)
2262 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2263 else if (ID.Kind == ValID::t_LocalName)
2264 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2265 else if (ID.Kind == ValID::t_InlineAsm) {
2266 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2267 const FunctionType *FTy =
2268 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2269 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2270 return Error(ID.Loc, "invalid type for inline asm constraint string");
2271 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2273 } else if (ID.Kind == ValID::t_Metadata) {
2277 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2285 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2288 return ParseValID(ID) ||
2289 ConvertValIDToValue(Ty, ID, V, PFS);
2292 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2293 PATypeHolder T(Type::VoidTy);
2294 return ParseType(T) ||
2295 ParseValue(T, V, PFS);
2299 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2300 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2301 /// OptionalAlign OptGC
2302 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2303 // Parse the linkage.
2304 LocTy LinkageLoc = Lex.getLoc();
2307 unsigned Visibility, CC, RetAttrs;
2308 PATypeHolder RetType(Type::VoidTy);
2309 LocTy RetTypeLoc = Lex.getLoc();
2310 if (ParseOptionalLinkage(Linkage) ||
2311 ParseOptionalVisibility(Visibility) ||
2312 ParseOptionalCallingConv(CC) ||
2313 ParseOptionalAttrs(RetAttrs, 1) ||
2314 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2317 // Verify that the linkage is ok.
2318 switch ((GlobalValue::LinkageTypes)Linkage) {
2319 case GlobalValue::ExternalLinkage:
2320 break; // always ok.
2321 case GlobalValue::DLLImportLinkage:
2322 case GlobalValue::ExternalWeakLinkage:
2324 return Error(LinkageLoc, "invalid linkage for function definition");
2326 case GlobalValue::PrivateLinkage:
2327 case GlobalValue::LinkerPrivateLinkage:
2328 case GlobalValue::InternalLinkage:
2329 case GlobalValue::AvailableExternallyLinkage:
2330 case GlobalValue::LinkOnceAnyLinkage:
2331 case GlobalValue::LinkOnceODRLinkage:
2332 case GlobalValue::WeakAnyLinkage:
2333 case GlobalValue::WeakODRLinkage:
2334 case GlobalValue::DLLExportLinkage:
2336 return Error(LinkageLoc, "invalid linkage for function declaration");
2338 case GlobalValue::AppendingLinkage:
2339 case GlobalValue::GhostLinkage:
2340 case GlobalValue::CommonLinkage:
2341 return Error(LinkageLoc, "invalid function linkage type");
2344 if (!FunctionType::isValidReturnType(RetType) ||
2345 isa<OpaqueType>(RetType))
2346 return Error(RetTypeLoc, "invalid function return type");
2348 LocTy NameLoc = Lex.getLoc();
2350 std::string FunctionName;
2351 if (Lex.getKind() == lltok::GlobalVar) {
2352 FunctionName = Lex.getStrVal();
2353 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2354 unsigned NameID = Lex.getUIntVal();
2356 if (NameID != NumberedVals.size())
2357 return TokError("function expected to be numbered '%" +
2358 utostr(NumberedVals.size()) + "'");
2360 return TokError("expected function name");
2365 if (Lex.getKind() != lltok::lparen)
2366 return TokError("expected '(' in function argument list");
2368 std::vector<ArgInfo> ArgList;
2371 std::string Section;
2375 if (ParseArgumentList(ArgList, isVarArg, false) ||
2376 ParseOptionalAttrs(FuncAttrs, 2) ||
2377 (EatIfPresent(lltok::kw_section) &&
2378 ParseStringConstant(Section)) ||
2379 ParseOptionalAlignment(Alignment) ||
2380 (EatIfPresent(lltok::kw_gc) &&
2381 ParseStringConstant(GC)))
2384 // If the alignment was parsed as an attribute, move to the alignment field.
2385 if (FuncAttrs & Attribute::Alignment) {
2386 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2387 FuncAttrs &= ~Attribute::Alignment;
2390 // Okay, if we got here, the function is syntactically valid. Convert types
2391 // and do semantic checks.
2392 std::vector<const Type*> ParamTypeList;
2393 SmallVector<AttributeWithIndex, 8> Attrs;
2394 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2396 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2397 if (FuncAttrs & ObsoleteFuncAttrs) {
2398 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2399 FuncAttrs &= ~ObsoleteFuncAttrs;
2402 if (RetAttrs != Attribute::None)
2403 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2405 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2406 ParamTypeList.push_back(ArgList[i].Type);
2407 if (ArgList[i].Attrs != Attribute::None)
2408 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2411 if (FuncAttrs != Attribute::None)
2412 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2414 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2416 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2417 RetType != Type::VoidTy)
2418 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2420 const FunctionType *FT =
2421 Context.getFunctionType(RetType, ParamTypeList, isVarArg);
2422 const PointerType *PFT = Context.getPointerTypeUnqual(FT);
2425 if (!FunctionName.empty()) {
2426 // If this was a definition of a forward reference, remove the definition
2427 // from the forward reference table and fill in the forward ref.
2428 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2429 ForwardRefVals.find(FunctionName);
2430 if (FRVI != ForwardRefVals.end()) {
2431 Fn = M->getFunction(FunctionName);
2432 ForwardRefVals.erase(FRVI);
2433 } else if ((Fn = M->getFunction(FunctionName))) {
2434 // If this function already exists in the symbol table, then it is
2435 // multiply defined. We accept a few cases for old backwards compat.
2436 // FIXME: Remove this stuff for LLVM 3.0.
2437 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2438 (!Fn->isDeclaration() && isDefine)) {
2439 // If the redefinition has different type or different attributes,
2440 // reject it. If both have bodies, reject it.
2441 return Error(NameLoc, "invalid redefinition of function '" +
2442 FunctionName + "'");
2443 } else if (Fn->isDeclaration()) {
2444 // Make sure to strip off any argument names so we can't get conflicts.
2445 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2451 } else if (FunctionName.empty()) {
2452 // If this is a definition of a forward referenced function, make sure the
2454 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2455 = ForwardRefValIDs.find(NumberedVals.size());
2456 if (I != ForwardRefValIDs.end()) {
2457 Fn = cast<Function>(I->second.first);
2458 if (Fn->getType() != PFT)
2459 return Error(NameLoc, "type of definition and forward reference of '@" +
2460 utostr(NumberedVals.size()) +"' disagree");
2461 ForwardRefValIDs.erase(I);
2466 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2467 else // Move the forward-reference to the correct spot in the module.
2468 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2470 if (FunctionName.empty())
2471 NumberedVals.push_back(Fn);
2473 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2474 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2475 Fn->setCallingConv(CC);
2476 Fn->setAttributes(PAL);
2477 Fn->setAlignment(Alignment);
2478 Fn->setSection(Section);
2479 if (!GC.empty()) Fn->setGC(GC.c_str());
2481 // Add all of the arguments we parsed to the function.
2482 Function::arg_iterator ArgIt = Fn->arg_begin();
2483 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2484 // If the argument has a name, insert it into the argument symbol table.
2485 if (ArgList[i].Name.empty()) continue;
2487 // Set the name, if it conflicted, it will be auto-renamed.
2488 ArgIt->setName(ArgList[i].Name);
2490 if (ArgIt->getNameStr() != ArgList[i].Name)
2491 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2492 ArgList[i].Name + "'");
2499 /// ParseFunctionBody
2500 /// ::= '{' BasicBlock+ '}'
2501 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2503 bool LLParser::ParseFunctionBody(Function &Fn) {
2504 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2505 return TokError("expected '{' in function body");
2506 Lex.Lex(); // eat the {.
2508 PerFunctionState PFS(*this, Fn);
2510 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2511 if (ParseBasicBlock(PFS)) return true;
2516 // Verify function is ok.
2517 return PFS.VerifyFunctionComplete();
2521 /// ::= LabelStr? Instruction*
2522 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2523 // If this basic block starts out with a name, remember it.
2525 LocTy NameLoc = Lex.getLoc();
2526 if (Lex.getKind() == lltok::LabelStr) {
2527 Name = Lex.getStrVal();
2531 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2532 if (BB == 0) return true;
2534 std::string NameStr;
2536 // Parse the instructions in this block until we get a terminator.
2539 // This instruction may have three possibilities for a name: a) none
2540 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2541 LocTy NameLoc = Lex.getLoc();
2545 if (Lex.getKind() == lltok::LocalVarID) {
2546 NameID = Lex.getUIntVal();
2548 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2550 } else if (Lex.getKind() == lltok::LocalVar ||
2551 // FIXME: REMOVE IN LLVM 3.0
2552 Lex.getKind() == lltok::StringConstant) {
2553 NameStr = Lex.getStrVal();
2555 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2559 if (ParseInstruction(Inst, BB, PFS)) return true;
2561 BB->getInstList().push_back(Inst);
2563 // Set the name on the instruction.
2564 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2565 } while (!isa<TerminatorInst>(Inst));
2570 //===----------------------------------------------------------------------===//
2571 // Instruction Parsing.
2572 //===----------------------------------------------------------------------===//
2574 /// ParseInstruction - Parse one of the many different instructions.
2576 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2577 PerFunctionState &PFS) {
2578 lltok::Kind Token = Lex.getKind();
2579 if (Token == lltok::Eof)
2580 return TokError("found end of file when expecting more instructions");
2581 LocTy Loc = Lex.getLoc();
2582 unsigned KeywordVal = Lex.getUIntVal();
2583 Lex.Lex(); // Eat the keyword.
2586 default: return Error(Loc, "expected instruction opcode");
2587 // Terminator Instructions.
2588 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2589 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2590 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2591 case lltok::kw_br: return ParseBr(Inst, PFS);
2592 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2593 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2594 // Binary Operators.
2597 case lltok::kw_mul: {
2600 LocTy ModifierLoc = Lex.getLoc();
2601 if (EatIfPresent(lltok::kw_nuw))
2603 if (EatIfPresent(lltok::kw_nsw)) {
2605 if (EatIfPresent(lltok::kw_nuw))
2608 // API compatibility: Accept either integer or floating-point types.
2609 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2611 if (!Inst->getType()->isIntOrIntVector()) {
2613 return Error(ModifierLoc, "nuw only applies to integer operations");
2615 return Error(ModifierLoc, "nsw only applies to integer operations");
2618 cast<OverflowingBinaryOperator>(Inst)->setHasNoUnsignedOverflow(true);
2620 cast<OverflowingBinaryOperator>(Inst)->setHasNoSignedOverflow(true);
2624 case lltok::kw_fadd:
2625 case lltok::kw_fsub:
2626 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2628 case lltok::kw_sdiv: {
2630 if (EatIfPresent(lltok::kw_exact))
2632 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2635 cast<SDivOperator>(Inst)->setIsExact(true);
2639 case lltok::kw_udiv:
2640 case lltok::kw_urem:
2641 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2642 case lltok::kw_fdiv:
2643 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2645 case lltok::kw_lshr:
2646 case lltok::kw_ashr:
2649 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2650 case lltok::kw_icmp:
2651 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2653 case lltok::kw_trunc:
2654 case lltok::kw_zext:
2655 case lltok::kw_sext:
2656 case lltok::kw_fptrunc:
2657 case lltok::kw_fpext:
2658 case lltok::kw_bitcast:
2659 case lltok::kw_uitofp:
2660 case lltok::kw_sitofp:
2661 case lltok::kw_fptoui:
2662 case lltok::kw_fptosi:
2663 case lltok::kw_inttoptr:
2664 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2666 case lltok::kw_select: return ParseSelect(Inst, PFS);
2667 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2668 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2669 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2670 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2671 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2672 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2673 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2675 case lltok::kw_alloca:
2676 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2677 case lltok::kw_free: return ParseFree(Inst, PFS);
2678 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2679 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2680 case lltok::kw_volatile:
2681 if (EatIfPresent(lltok::kw_load))
2682 return ParseLoad(Inst, PFS, true);
2683 else if (EatIfPresent(lltok::kw_store))
2684 return ParseStore(Inst, PFS, true);
2686 return TokError("expected 'load' or 'store'");
2687 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2688 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2689 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2690 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2694 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2695 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2696 if (Opc == Instruction::FCmp) {
2697 switch (Lex.getKind()) {
2698 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2699 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2700 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2701 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2702 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2703 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2704 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2705 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2706 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2707 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2708 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2709 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2710 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2711 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2712 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2713 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2714 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2717 switch (Lex.getKind()) {
2718 default: TokError("expected icmp predicate (e.g. 'eq')");
2719 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2720 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2721 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2722 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2723 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2724 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2725 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2726 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2727 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2728 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2735 //===----------------------------------------------------------------------===//
2736 // Terminator Instructions.
2737 //===----------------------------------------------------------------------===//
2739 /// ParseRet - Parse a return instruction.
2741 /// ::= 'ret' TypeAndValue
2742 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2743 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2744 PerFunctionState &PFS) {
2745 PATypeHolder Ty(Type::VoidTy);
2746 if (ParseType(Ty, true /*void allowed*/)) return true;
2748 if (Ty == Type::VoidTy) {
2749 Inst = ReturnInst::Create();
2754 if (ParseValue(Ty, RV, PFS)) return true;
2756 // The normal case is one return value.
2757 if (Lex.getKind() == lltok::comma) {
2758 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2759 // of 'ret {i32,i32} {i32 1, i32 2}'
2760 SmallVector<Value*, 8> RVs;
2763 while (EatIfPresent(lltok::comma)) {
2764 if (ParseTypeAndValue(RV, PFS)) return true;
2768 RV = Context.getUndef(PFS.getFunction().getReturnType());
2769 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2770 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2771 BB->getInstList().push_back(I);
2775 Inst = ReturnInst::Create(RV);
2781 /// ::= 'br' TypeAndValue
2782 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2783 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2785 Value *Op0, *Op1, *Op2;
2786 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2788 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2789 Inst = BranchInst::Create(BB);
2793 if (Op0->getType() != Type::Int1Ty)
2794 return Error(Loc, "branch condition must have 'i1' type");
2796 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2797 ParseTypeAndValue(Op1, Loc, PFS) ||
2798 ParseToken(lltok::comma, "expected ',' after true destination") ||
2799 ParseTypeAndValue(Op2, Loc2, PFS))
2802 if (!isa<BasicBlock>(Op1))
2803 return Error(Loc, "true destination of branch must be a basic block");
2804 if (!isa<BasicBlock>(Op2))
2805 return Error(Loc2, "true destination of branch must be a basic block");
2807 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2813 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2815 /// ::= (TypeAndValue ',' TypeAndValue)*
2816 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2817 LocTy CondLoc, BBLoc;
2818 Value *Cond, *DefaultBB;
2819 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2820 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2821 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2822 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2825 if (!isa<IntegerType>(Cond->getType()))
2826 return Error(CondLoc, "switch condition must have integer type");
2827 if (!isa<BasicBlock>(DefaultBB))
2828 return Error(BBLoc, "default destination must be a basic block");
2830 // Parse the jump table pairs.
2831 SmallPtrSet<Value*, 32> SeenCases;
2832 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2833 while (Lex.getKind() != lltok::rsquare) {
2834 Value *Constant, *DestBB;
2836 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2837 ParseToken(lltok::comma, "expected ',' after case value") ||
2838 ParseTypeAndValue(DestBB, BBLoc, PFS))
2841 if (!SeenCases.insert(Constant))
2842 return Error(CondLoc, "duplicate case value in switch");
2843 if (!isa<ConstantInt>(Constant))
2844 return Error(CondLoc, "case value is not a constant integer");
2845 if (!isa<BasicBlock>(DestBB))
2846 return Error(BBLoc, "case destination is not a basic block");
2848 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2849 cast<BasicBlock>(DestBB)));
2852 Lex.Lex(); // Eat the ']'.
2854 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2856 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2857 SI->addCase(Table[i].first, Table[i].second);
2863 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2864 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2865 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2866 LocTy CallLoc = Lex.getLoc();
2867 unsigned CC, RetAttrs, FnAttrs;
2868 PATypeHolder RetType(Type::VoidTy);
2871 SmallVector<ParamInfo, 16> ArgList;
2873 Value *NormalBB, *UnwindBB;
2874 if (ParseOptionalCallingConv(CC) ||
2875 ParseOptionalAttrs(RetAttrs, 1) ||
2876 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2877 ParseValID(CalleeID) ||
2878 ParseParameterList(ArgList, PFS) ||
2879 ParseOptionalAttrs(FnAttrs, 2) ||
2880 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2881 ParseTypeAndValue(NormalBB, PFS) ||
2882 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2883 ParseTypeAndValue(UnwindBB, PFS))
2886 if (!isa<BasicBlock>(NormalBB))
2887 return Error(CallLoc, "normal destination is not a basic block");
2888 if (!isa<BasicBlock>(UnwindBB))
2889 return Error(CallLoc, "unwind destination is not a basic block");
2891 // If RetType is a non-function pointer type, then this is the short syntax
2892 // for the call, which means that RetType is just the return type. Infer the
2893 // rest of the function argument types from the arguments that are present.
2894 const PointerType *PFTy = 0;
2895 const FunctionType *Ty = 0;
2896 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2897 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2898 // Pull out the types of all of the arguments...
2899 std::vector<const Type*> ParamTypes;
2900 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2901 ParamTypes.push_back(ArgList[i].V->getType());
2903 if (!FunctionType::isValidReturnType(RetType))
2904 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2906 Ty = Context.getFunctionType(RetType, ParamTypes, false);
2907 PFTy = Context.getPointerTypeUnqual(Ty);
2910 // Look up the callee.
2912 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2914 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2915 // function attributes.
2916 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2917 if (FnAttrs & ObsoleteFuncAttrs) {
2918 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2919 FnAttrs &= ~ObsoleteFuncAttrs;
2922 // Set up the Attributes for the function.
2923 SmallVector<AttributeWithIndex, 8> Attrs;
2924 if (RetAttrs != Attribute::None)
2925 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2927 SmallVector<Value*, 8> Args;
2929 // Loop through FunctionType's arguments and ensure they are specified
2930 // correctly. Also, gather any parameter attributes.
2931 FunctionType::param_iterator I = Ty->param_begin();
2932 FunctionType::param_iterator E = Ty->param_end();
2933 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2934 const Type *ExpectedTy = 0;
2937 } else if (!Ty->isVarArg()) {
2938 return Error(ArgList[i].Loc, "too many arguments specified");
2941 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2942 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2943 ExpectedTy->getDescription() + "'");
2944 Args.push_back(ArgList[i].V);
2945 if (ArgList[i].Attrs != Attribute::None)
2946 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2950 return Error(CallLoc, "not enough parameters specified for call");
2952 if (FnAttrs != Attribute::None)
2953 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2955 // Finish off the Attributes and check them
2956 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2958 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2959 cast<BasicBlock>(UnwindBB),
2960 Args.begin(), Args.end());
2961 II->setCallingConv(CC);
2962 II->setAttributes(PAL);
2969 //===----------------------------------------------------------------------===//
2970 // Binary Operators.
2971 //===----------------------------------------------------------------------===//
2974 /// ::= ArithmeticOps TypeAndValue ',' Value
2976 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2977 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2978 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2979 unsigned Opc, unsigned OperandType) {
2980 LocTy Loc; Value *LHS, *RHS;
2981 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2982 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2983 ParseValue(LHS->getType(), RHS, PFS))
2987 switch (OperandType) {
2988 default: llvm_unreachable("Unknown operand type!");
2989 case 0: // int or FP.
2990 Valid = LHS->getType()->isIntOrIntVector() ||
2991 LHS->getType()->isFPOrFPVector();
2993 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2994 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2998 return Error(Loc, "invalid operand type for instruction");
3000 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3005 /// ::= ArithmeticOps TypeAndValue ',' Value {
3006 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3008 LocTy Loc; Value *LHS, *RHS;
3009 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3010 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3011 ParseValue(LHS->getType(), RHS, PFS))
3014 if (!LHS->getType()->isIntOrIntVector())
3015 return Error(Loc,"instruction requires integer or integer vector operands");
3017 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3023 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3024 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3025 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3027 // Parse the integer/fp comparison predicate.
3031 if (ParseCmpPredicate(Pred, Opc) ||
3032 ParseTypeAndValue(LHS, Loc, PFS) ||
3033 ParseToken(lltok::comma, "expected ',' after compare value") ||
3034 ParseValue(LHS->getType(), RHS, PFS))
3037 if (Opc == Instruction::FCmp) {
3038 if (!LHS->getType()->isFPOrFPVector())
3039 return Error(Loc, "fcmp requires floating point operands");
3040 Inst = new FCmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3042 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3043 if (!LHS->getType()->isIntOrIntVector() &&
3044 !isa<PointerType>(LHS->getType()))
3045 return Error(Loc, "icmp requires integer operands");
3046 Inst = new ICmpInst(Context, CmpInst::Predicate(Pred), LHS, RHS);
3051 //===----------------------------------------------------------------------===//
3052 // Other Instructions.
3053 //===----------------------------------------------------------------------===//
3057 /// ::= CastOpc TypeAndValue 'to' Type
3058 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3060 LocTy Loc; Value *Op;
3061 PATypeHolder DestTy(Type::VoidTy);
3062 if (ParseTypeAndValue(Op, Loc, PFS) ||
3063 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3067 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3068 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3069 return Error(Loc, "invalid cast opcode for cast from '" +
3070 Op->getType()->getDescription() + "' to '" +
3071 DestTy->getDescription() + "'");
3073 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3078 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3079 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3081 Value *Op0, *Op1, *Op2;
3082 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3083 ParseToken(lltok::comma, "expected ',' after select condition") ||
3084 ParseTypeAndValue(Op1, PFS) ||
3085 ParseToken(lltok::comma, "expected ',' after select value") ||
3086 ParseTypeAndValue(Op2, PFS))
3089 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3090 return Error(Loc, Reason);
3092 Inst = SelectInst::Create(Op0, Op1, Op2);
3097 /// ::= 'va_arg' TypeAndValue ',' Type
3098 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3100 PATypeHolder EltTy(Type::VoidTy);
3102 if (ParseTypeAndValue(Op, PFS) ||
3103 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3104 ParseType(EltTy, TypeLoc))
3107 if (!EltTy->isFirstClassType())
3108 return Error(TypeLoc, "va_arg requires operand with first class type");
3110 Inst = new VAArgInst(Op, EltTy);
3114 /// ParseExtractElement
3115 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3116 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3119 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3120 ParseToken(lltok::comma, "expected ',' after extract value") ||
3121 ParseTypeAndValue(Op1, PFS))
3124 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3125 return Error(Loc, "invalid extractelement operands");
3127 Inst = ExtractElementInst::Create(Op0, Op1);
3131 /// ParseInsertElement
3132 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3133 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3135 Value *Op0, *Op1, *Op2;
3136 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3137 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3138 ParseTypeAndValue(Op1, PFS) ||
3139 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3140 ParseTypeAndValue(Op2, PFS))
3143 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3144 return Error(Loc, "invalid insertelement operands");
3146 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3150 /// ParseShuffleVector
3151 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3152 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3154 Value *Op0, *Op1, *Op2;
3155 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3156 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3157 ParseTypeAndValue(Op1, PFS) ||
3158 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3159 ParseTypeAndValue(Op2, PFS))
3162 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3163 return Error(Loc, "invalid extractelement operands");
3165 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3170 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3171 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3172 PATypeHolder Ty(Type::VoidTy);
3174 LocTy TypeLoc = Lex.getLoc();
3176 if (ParseType(Ty) ||
3177 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3178 ParseValue(Ty, Op0, PFS) ||
3179 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3180 ParseValue(Type::LabelTy, Op1, PFS) ||
3181 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3184 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3186 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3188 if (!EatIfPresent(lltok::comma))
3191 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3192 ParseValue(Ty, Op0, PFS) ||
3193 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3194 ParseValue(Type::LabelTy, Op1, PFS) ||
3195 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3199 if (!Ty->isFirstClassType())
3200 return Error(TypeLoc, "phi node must have first class type");
3202 PHINode *PN = PHINode::Create(Ty);
3203 PN->reserveOperandSpace(PHIVals.size());
3204 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3205 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3211 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3212 /// ParameterList OptionalAttrs
3213 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3215 unsigned CC, RetAttrs, FnAttrs;
3216 PATypeHolder RetType(Type::VoidTy);
3219 SmallVector<ParamInfo, 16> ArgList;
3220 LocTy CallLoc = Lex.getLoc();
3222 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3223 ParseOptionalCallingConv(CC) ||
3224 ParseOptionalAttrs(RetAttrs, 1) ||
3225 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3226 ParseValID(CalleeID) ||
3227 ParseParameterList(ArgList, PFS) ||
3228 ParseOptionalAttrs(FnAttrs, 2))
3231 // If RetType is a non-function pointer type, then this is the short syntax
3232 // for the call, which means that RetType is just the return type. Infer the
3233 // rest of the function argument types from the arguments that are present.
3234 const PointerType *PFTy = 0;
3235 const FunctionType *Ty = 0;
3236 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3237 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3238 // Pull out the types of all of the arguments...
3239 std::vector<const Type*> ParamTypes;
3240 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3241 ParamTypes.push_back(ArgList[i].V->getType());
3243 if (!FunctionType::isValidReturnType(RetType))
3244 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3246 Ty = Context.getFunctionType(RetType, ParamTypes, false);
3247 PFTy = Context.getPointerTypeUnqual(Ty);
3250 // Look up the callee.
3252 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3254 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3255 // function attributes.
3256 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3257 if (FnAttrs & ObsoleteFuncAttrs) {
3258 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3259 FnAttrs &= ~ObsoleteFuncAttrs;
3262 // Set up the Attributes for the function.
3263 SmallVector<AttributeWithIndex, 8> Attrs;
3264 if (RetAttrs != Attribute::None)
3265 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3267 SmallVector<Value*, 8> Args;
3269 // Loop through FunctionType's arguments and ensure they are specified
3270 // correctly. Also, gather any parameter attributes.
3271 FunctionType::param_iterator I = Ty->param_begin();
3272 FunctionType::param_iterator E = Ty->param_end();
3273 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3274 const Type *ExpectedTy = 0;
3277 } else if (!Ty->isVarArg()) {
3278 return Error(ArgList[i].Loc, "too many arguments specified");
3281 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3282 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3283 ExpectedTy->getDescription() + "'");
3284 Args.push_back(ArgList[i].V);
3285 if (ArgList[i].Attrs != Attribute::None)
3286 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3290 return Error(CallLoc, "not enough parameters specified for call");
3292 if (FnAttrs != Attribute::None)
3293 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3295 // Finish off the Attributes and check them
3296 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3298 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3299 CI->setTailCall(isTail);
3300 CI->setCallingConv(CC);
3301 CI->setAttributes(PAL);
3306 //===----------------------------------------------------------------------===//
3307 // Memory Instructions.
3308 //===----------------------------------------------------------------------===//
3311 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3312 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3313 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3315 PATypeHolder Ty(Type::VoidTy);
3318 unsigned Alignment = 0;
3319 if (ParseType(Ty)) return true;
3321 if (EatIfPresent(lltok::comma)) {
3322 if (Lex.getKind() == lltok::kw_align) {
3323 if (ParseOptionalAlignment(Alignment)) return true;
3324 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3325 ParseOptionalCommaAlignment(Alignment)) {
3330 if (Size && Size->getType() != Type::Int32Ty)
3331 return Error(SizeLoc, "element count must be i32");
3333 if (Opc == Instruction::Malloc)
3334 Inst = new MallocInst(Ty, Size, Alignment);
3336 Inst = new AllocaInst(Ty, Size, Alignment);
3341 /// ::= 'free' TypeAndValue
3342 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3343 Value *Val; LocTy Loc;
3344 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3345 if (!isa<PointerType>(Val->getType()))
3346 return Error(Loc, "operand to free must be a pointer");
3347 Inst = new FreeInst(Val);
3352 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3353 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3355 Value *Val; LocTy Loc;
3357 if (ParseTypeAndValue(Val, Loc, PFS) ||
3358 ParseOptionalCommaAlignment(Alignment))
3361 if (!isa<PointerType>(Val->getType()) ||
3362 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3363 return Error(Loc, "load operand must be a pointer to a first class type");
3365 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3370 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3371 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3373 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3375 if (ParseTypeAndValue(Val, Loc, PFS) ||
3376 ParseToken(lltok::comma, "expected ',' after store operand") ||
3377 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3378 ParseOptionalCommaAlignment(Alignment))
3381 if (!isa<PointerType>(Ptr->getType()))
3382 return Error(PtrLoc, "store operand must be a pointer");
3383 if (!Val->getType()->isFirstClassType())
3384 return Error(Loc, "store operand must be a first class value");
3385 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3386 return Error(Loc, "stored value and pointer type do not match");
3388 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3393 /// ::= 'getresult' TypeAndValue ',' i32
3394 /// FIXME: Remove support for getresult in LLVM 3.0
3395 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3396 Value *Val; LocTy ValLoc, EltLoc;
3398 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3399 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3400 ParseUInt32(Element, EltLoc))
3403 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3404 return Error(ValLoc, "getresult inst requires an aggregate operand");
3405 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3406 return Error(EltLoc, "invalid getresult index for value");
3407 Inst = ExtractValueInst::Create(Val, Element);
3411 /// ParseGetElementPtr
3412 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3413 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3414 Value *Ptr, *Val; LocTy Loc, EltLoc;
3416 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3418 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3420 if (!isa<PointerType>(Ptr->getType()))
3421 return Error(Loc, "base of getelementptr must be a pointer");
3423 SmallVector<Value*, 16> Indices;
3424 while (EatIfPresent(lltok::comma)) {
3425 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3426 if (!isa<IntegerType>(Val->getType()))
3427 return Error(EltLoc, "getelementptr index must be an integer");
3428 Indices.push_back(Val);
3431 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3432 Indices.begin(), Indices.end()))
3433 return Error(Loc, "invalid getelementptr indices");
3434 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3436 cast<GEPOperator>(Inst)->setIsInBounds(true);
3440 /// ParseExtractValue
3441 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3442 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3443 Value *Val; LocTy Loc;
3444 SmallVector<unsigned, 4> Indices;
3445 if (ParseTypeAndValue(Val, Loc, PFS) ||
3446 ParseIndexList(Indices))
3449 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3450 return Error(Loc, "extractvalue operand must be array or struct");
3452 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3454 return Error(Loc, "invalid indices for extractvalue");
3455 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3459 /// ParseInsertValue
3460 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3461 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3462 Value *Val0, *Val1; LocTy Loc0, Loc1;
3463 SmallVector<unsigned, 4> Indices;
3464 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3465 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3466 ParseTypeAndValue(Val1, Loc1, PFS) ||
3467 ParseIndexList(Indices))
3470 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3471 return Error(Loc0, "extractvalue operand must be array or struct");
3473 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3475 return Error(Loc0, "invalid indices for insertvalue");
3476 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3480 //===----------------------------------------------------------------------===//
3481 // Embedded metadata.
3482 //===----------------------------------------------------------------------===//
3484 /// ParseMDNodeVector
3485 /// ::= Element (',' Element)*
3487 /// ::= 'null' | TypeAndValue
3488 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3489 assert(Lex.getKind() == lltok::lbrace);
3493 if (Lex.getKind() == lltok::kw_null) {
3497 PATypeHolder Ty(Type::VoidTy);
3498 if (ParseType(Ty)) return true;
3499 if (Lex.getKind() == lltok::Metadata) {
3501 MetadataBase *Node = 0;
3502 if (!ParseMDNode(Node))
3505 MetadataBase *MDS = 0;
3506 if (ParseMDString(MDS)) return true;
3511 if (ParseGlobalValue(Ty, C)) return true;
3516 } while (EatIfPresent(lltok::comma));