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"
32 /// Run: module ::= toplevelentity*
33 bool LLParser::Run() {
37 return ParseTopLevelEntities() ||
38 ValidateEndOfModule();
41 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
43 bool LLParser::ValidateEndOfModule() {
44 // Update auto-upgraded malloc calls to "malloc".
45 // FIXME: Remove in LLVM 3.0.
47 MallocF->setName("malloc");
48 // If setName() does not set the name to "malloc", then there is already a
49 // declaration of "malloc". In that case, iterate over all calls to MallocF
50 // and get them to call the declared "malloc" instead.
51 if (MallocF->getName() != "malloc") {
52 Constant *RealMallocF = M->getFunction("malloc");
53 if (RealMallocF->getType() != MallocF->getType())
54 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
55 MallocF->replaceAllUsesWith(RealMallocF);
56 MallocF->eraseFromParent();
62 // If there are entries in ForwardRefBlockAddresses at this point, they are
63 // references after the function was defined. Resolve those now.
64 while (!ForwardRefBlockAddresses.empty()) {
65 // Okay, we are referencing an already-parsed function, resolve them now.
67 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
68 if (Fn.Kind == ValID::t_GlobalName)
69 TheFn = M->getFunction(Fn.StrVal);
70 else if (Fn.UIntVal < NumberedVals.size())
71 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
74 return Error(Fn.Loc, "unknown function referenced by blockaddress");
76 // Resolve all these references.
77 if (ResolveForwardRefBlockAddresses(TheFn,
78 ForwardRefBlockAddresses.begin()->second,
82 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
86 if (!ForwardRefTypes.empty())
87 return Error(ForwardRefTypes.begin()->second.second,
88 "use of undefined type named '" +
89 ForwardRefTypes.begin()->first + "'");
90 if (!ForwardRefTypeIDs.empty())
91 return Error(ForwardRefTypeIDs.begin()->second.second,
92 "use of undefined type '%" +
93 utostr(ForwardRefTypeIDs.begin()->first) + "'");
95 if (!ForwardRefVals.empty())
96 return Error(ForwardRefVals.begin()->second.second,
97 "use of undefined value '@" + ForwardRefVals.begin()->first +
100 if (!ForwardRefValIDs.empty())
101 return Error(ForwardRefValIDs.begin()->second.second,
102 "use of undefined value '@" +
103 utostr(ForwardRefValIDs.begin()->first) + "'");
105 if (!ForwardRefMDNodes.empty())
106 return Error(ForwardRefMDNodes.begin()->second.second,
107 "use of undefined metadata '!" +
108 utostr(ForwardRefMDNodes.begin()->first) + "'");
111 // Look for intrinsic functions and CallInst that need to be upgraded
112 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
113 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
115 // Check debug info intrinsics.
116 CheckDebugInfoIntrinsics(M);
120 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
121 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
122 PerFunctionState *PFS) {
123 // Loop over all the references, resolving them.
124 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
126 if (Refs[i].first.Kind == ValID::t_Null)
129 if (Refs[i].first.Kind == ValID::t_LocalName)
130 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
132 assert(Refs[i].first.Kind == ValID::t_LocalID);
133 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
135 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
136 return Error(Refs[i].first.Loc,
137 "cannot take address of numeric label after it the function is defined");
139 assert(Refs[i].first.Kind == ValID::t_LocalName);
140 Res = dyn_cast_or_null<BasicBlock>(
141 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
144 if (Res == 0 && Refs[i].first.Kind != ValID::t_Null)
145 return Error(Refs[i].first.Loc,
146 "referenced value is not a basic block");
148 // Get the BlockAddress for this and update references to use it.
149 BlockAddress *BA = BlockAddress::get(TheFn, Res);
150 Refs[i].second->replaceAllUsesWith(BA);
151 Refs[i].second->eraseFromParent();
157 //===----------------------------------------------------------------------===//
158 // Top-Level Entities
159 //===----------------------------------------------------------------------===//
161 bool LLParser::ParseTopLevelEntities() {
163 switch (Lex.getKind()) {
164 default: return TokError("expected top-level entity");
165 case lltok::Eof: return false;
166 //case lltok::kw_define:
167 case lltok::kw_declare: if (ParseDeclare()) return true; break;
168 case lltok::kw_define: if (ParseDefine()) return true; break;
169 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
171 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
172 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
173 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
174 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
175 case lltok::LocalVar: if (ParseNamedType()) return true; break;
176 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
177 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
178 case lltok::Metadata: if (ParseStandaloneMetadata()) return true; break;
179 case lltok::NamedOrCustomMD: if (ParseNamedMetadata()) return true; break;
181 // The Global variable production with no name can have many different
182 // optional leading prefixes, the production is:
183 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
184 // OptionalAddrSpace ('constant'|'global') ...
185 case lltok::kw_private : // OptionalLinkage
186 case lltok::kw_linker_private: // OptionalLinkage
187 case lltok::kw_internal: // OptionalLinkage
188 case lltok::kw_weak: // OptionalLinkage
189 case lltok::kw_weak_odr: // OptionalLinkage
190 case lltok::kw_linkonce: // OptionalLinkage
191 case lltok::kw_linkonce_odr: // OptionalLinkage
192 case lltok::kw_appending: // OptionalLinkage
193 case lltok::kw_dllexport: // OptionalLinkage
194 case lltok::kw_common: // OptionalLinkage
195 case lltok::kw_dllimport: // OptionalLinkage
196 case lltok::kw_extern_weak: // OptionalLinkage
197 case lltok::kw_external: { // OptionalLinkage
198 unsigned Linkage, Visibility;
199 if (ParseOptionalLinkage(Linkage) ||
200 ParseOptionalVisibility(Visibility) ||
201 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
205 case lltok::kw_default: // OptionalVisibility
206 case lltok::kw_hidden: // OptionalVisibility
207 case lltok::kw_protected: { // OptionalVisibility
209 if (ParseOptionalVisibility(Visibility) ||
210 ParseGlobal("", SMLoc(), 0, false, Visibility))
215 case lltok::kw_thread_local: // OptionalThreadLocal
216 case lltok::kw_addrspace: // OptionalAddrSpace
217 case lltok::kw_constant: // GlobalType
218 case lltok::kw_global: // GlobalType
219 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
227 /// ::= 'module' 'asm' STRINGCONSTANT
228 bool LLParser::ParseModuleAsm() {
229 assert(Lex.getKind() == lltok::kw_module);
233 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
234 ParseStringConstant(AsmStr)) return true;
236 const std::string &AsmSoFar = M->getModuleInlineAsm();
237 if (AsmSoFar.empty())
238 M->setModuleInlineAsm(AsmStr);
240 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
245 /// ::= 'target' 'triple' '=' STRINGCONSTANT
246 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
247 bool LLParser::ParseTargetDefinition() {
248 assert(Lex.getKind() == lltok::kw_target);
251 default: return TokError("unknown target property");
252 case lltok::kw_triple:
254 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
255 ParseStringConstant(Str))
257 M->setTargetTriple(Str);
259 case lltok::kw_datalayout:
261 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
262 ParseStringConstant(Str))
264 M->setDataLayout(Str);
270 /// ::= 'deplibs' '=' '[' ']'
271 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
272 bool LLParser::ParseDepLibs() {
273 assert(Lex.getKind() == lltok::kw_deplibs);
275 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
276 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
279 if (EatIfPresent(lltok::rsquare))
283 if (ParseStringConstant(Str)) return true;
286 while (EatIfPresent(lltok::comma)) {
287 if (ParseStringConstant(Str)) return true;
291 return ParseToken(lltok::rsquare, "expected ']' at end of list");
294 /// ParseUnnamedType:
296 /// ::= LocalVarID '=' 'type' type
297 bool LLParser::ParseUnnamedType() {
298 unsigned TypeID = NumberedTypes.size();
300 // Handle the LocalVarID form.
301 if (Lex.getKind() == lltok::LocalVarID) {
302 if (Lex.getUIntVal() != TypeID)
303 return Error(Lex.getLoc(), "type expected to be numbered '%" +
304 utostr(TypeID) + "'");
305 Lex.Lex(); // eat LocalVarID;
307 if (ParseToken(lltok::equal, "expected '=' after name"))
311 assert(Lex.getKind() == lltok::kw_type);
312 LocTy TypeLoc = Lex.getLoc();
313 Lex.Lex(); // eat kw_type
315 PATypeHolder Ty(Type::getVoidTy(Context));
316 if (ParseType(Ty)) return true;
318 // See if this type was previously referenced.
319 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
320 FI = ForwardRefTypeIDs.find(TypeID);
321 if (FI != ForwardRefTypeIDs.end()) {
322 if (FI->second.first.get() == Ty)
323 return Error(TypeLoc, "self referential type is invalid");
325 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
326 Ty = FI->second.first.get();
327 ForwardRefTypeIDs.erase(FI);
330 NumberedTypes.push_back(Ty);
336 /// ::= LocalVar '=' 'type' type
337 bool LLParser::ParseNamedType() {
338 std::string Name = Lex.getStrVal();
339 LocTy NameLoc = Lex.getLoc();
340 Lex.Lex(); // eat LocalVar.
342 PATypeHolder Ty(Type::getVoidTy(Context));
344 if (ParseToken(lltok::equal, "expected '=' after name") ||
345 ParseToken(lltok::kw_type, "expected 'type' after name") ||
349 // Set the type name, checking for conflicts as we do so.
350 bool AlreadyExists = M->addTypeName(Name, Ty);
351 if (!AlreadyExists) return false;
353 // See if this type is a forward reference. We need to eagerly resolve
354 // types to allow recursive type redefinitions below.
355 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
356 FI = ForwardRefTypes.find(Name);
357 if (FI != ForwardRefTypes.end()) {
358 if (FI->second.first.get() == Ty)
359 return Error(NameLoc, "self referential type is invalid");
361 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
362 Ty = FI->second.first.get();
363 ForwardRefTypes.erase(FI);
366 // Inserting a name that is already defined, get the existing name.
367 const Type *Existing = M->getTypeByName(Name);
368 assert(Existing && "Conflict but no matching type?!");
370 // Otherwise, this is an attempt to redefine a type. That's okay if
371 // the redefinition is identical to the original.
372 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
373 if (Existing == Ty) return false;
375 // Any other kind of (non-equivalent) redefinition is an error.
376 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
377 Ty->getDescription() + "'");
382 /// ::= 'declare' FunctionHeader
383 bool LLParser::ParseDeclare() {
384 assert(Lex.getKind() == lltok::kw_declare);
388 return ParseFunctionHeader(F, false);
392 /// ::= 'define' FunctionHeader '{' ...
393 bool LLParser::ParseDefine() {
394 assert(Lex.getKind() == lltok::kw_define);
398 return ParseFunctionHeader(F, true) ||
399 ParseFunctionBody(*F);
405 bool LLParser::ParseGlobalType(bool &IsConstant) {
406 if (Lex.getKind() == lltok::kw_constant)
408 else if (Lex.getKind() == lltok::kw_global)
412 return TokError("expected 'global' or 'constant'");
418 /// ParseUnnamedGlobal:
419 /// OptionalVisibility ALIAS ...
420 /// OptionalLinkage OptionalVisibility ... -> global variable
421 /// GlobalID '=' OptionalVisibility ALIAS ...
422 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
423 bool LLParser::ParseUnnamedGlobal() {
424 unsigned VarID = NumberedVals.size();
426 LocTy NameLoc = Lex.getLoc();
428 // Handle the GlobalID form.
429 if (Lex.getKind() == lltok::GlobalID) {
430 if (Lex.getUIntVal() != VarID)
431 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
432 utostr(VarID) + "'");
433 Lex.Lex(); // eat GlobalID;
435 if (ParseToken(lltok::equal, "expected '=' after name"))
440 unsigned Linkage, Visibility;
441 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
442 ParseOptionalVisibility(Visibility))
445 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
446 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
447 return ParseAlias(Name, NameLoc, Visibility);
450 /// ParseNamedGlobal:
451 /// GlobalVar '=' OptionalVisibility ALIAS ...
452 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
453 bool LLParser::ParseNamedGlobal() {
454 assert(Lex.getKind() == lltok::GlobalVar);
455 LocTy NameLoc = Lex.getLoc();
456 std::string Name = Lex.getStrVal();
460 unsigned Linkage, Visibility;
461 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
462 ParseOptionalLinkage(Linkage, HasLinkage) ||
463 ParseOptionalVisibility(Visibility))
466 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
467 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
468 return ParseAlias(Name, NameLoc, Visibility);
472 // ::= '!' STRINGCONSTANT
473 bool LLParser::ParseMDString(MetadataBase *&MDS) {
475 if (ParseStringConstant(Str)) return true;
476 MDS = MDString::get(Context, Str);
481 // ::= '!' MDNodeNumber
482 bool LLParser::ParseMDNode(MetadataBase *&Node) {
483 // !{ ..., !42, ... }
485 if (ParseUInt32(MID)) return true;
487 // Check existing MDNode.
488 std::map<unsigned, MetadataBase *>::iterator I = MetadataCache.find(MID);
489 if (I != MetadataCache.end()) {
494 // Check known forward references.
495 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
496 FI = ForwardRefMDNodes.find(MID);
497 if (FI != ForwardRefMDNodes.end()) {
498 Node = FI->second.first;
502 // Create MDNode forward reference
503 SmallVector<Value *, 1> Elts;
504 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
505 Elts.push_back(MDString::get(Context, FwdRefName));
506 MDNode *FwdNode = MDNode::get(Context, Elts.data(), Elts.size());
507 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
512 ///ParseNamedMetadata:
513 /// !foo = !{ !1, !2 }
514 bool LLParser::ParseNamedMetadata() {
515 assert(Lex.getKind() == lltok::NamedOrCustomMD);
517 std::string Name = Lex.getStrVal();
519 if (ParseToken(lltok::equal, "expected '=' here"))
522 if (Lex.getKind() != lltok::Metadata)
523 return TokError("Expected '!' here");
526 if (Lex.getKind() != lltok::lbrace)
527 return TokError("Expected '{' here");
529 SmallVector<MetadataBase *, 8> Elts;
531 if (Lex.getKind() != lltok::Metadata)
532 return TokError("Expected '!' here");
535 if (ParseMDNode(N)) return true;
537 } while (EatIfPresent(lltok::comma));
539 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
542 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
546 /// ParseStandaloneMetadata:
548 bool LLParser::ParseStandaloneMetadata() {
549 assert(Lex.getKind() == lltok::Metadata);
551 unsigned MetadataID = 0;
552 if (ParseUInt32(MetadataID))
554 if (MetadataCache.find(MetadataID) != MetadataCache.end())
555 return TokError("Metadata id is already used");
556 if (ParseToken(lltok::equal, "expected '=' here"))
560 PATypeHolder Ty(Type::getVoidTy(Context));
561 if (ParseType(Ty, TyLoc))
564 if (Lex.getKind() != lltok::Metadata)
565 return TokError("Expected metadata here");
568 if (Lex.getKind() != lltok::lbrace)
569 return TokError("Expected '{' here");
571 SmallVector<Value *, 16> Elts;
572 if (ParseMDNodeVector(Elts)
573 || ParseToken(lltok::rbrace, "expected end of metadata node"))
576 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
577 MetadataCache[MetadataID] = Init;
578 std::map<unsigned, std::pair<MetadataBase *, LocTy> >::iterator
579 FI = ForwardRefMDNodes.find(MetadataID);
580 if (FI != ForwardRefMDNodes.end()) {
581 MDNode *FwdNode = cast<MDNode>(FI->second.first);
582 FwdNode->replaceAllUsesWith(Init);
583 ForwardRefMDNodes.erase(FI);
590 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
593 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
594 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
596 /// Everything through visibility has already been parsed.
598 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
599 unsigned Visibility) {
600 assert(Lex.getKind() == lltok::kw_alias);
603 LocTy LinkageLoc = Lex.getLoc();
604 if (ParseOptionalLinkage(Linkage))
607 if (Linkage != GlobalValue::ExternalLinkage &&
608 Linkage != GlobalValue::WeakAnyLinkage &&
609 Linkage != GlobalValue::WeakODRLinkage &&
610 Linkage != GlobalValue::InternalLinkage &&
611 Linkage != GlobalValue::PrivateLinkage &&
612 Linkage != GlobalValue::LinkerPrivateLinkage)
613 return Error(LinkageLoc, "invalid linkage type for alias");
616 LocTy AliaseeLoc = Lex.getLoc();
617 if (Lex.getKind() != lltok::kw_bitcast &&
618 Lex.getKind() != lltok::kw_getelementptr) {
619 if (ParseGlobalTypeAndValue(Aliasee)) return true;
621 // The bitcast dest type is not present, it is implied by the dest type.
623 if (ParseValID(ID)) return true;
624 if (ID.Kind != ValID::t_Constant)
625 return Error(AliaseeLoc, "invalid aliasee");
626 Aliasee = ID.ConstantVal;
629 if (!isa<PointerType>(Aliasee->getType()))
630 return Error(AliaseeLoc, "alias must have pointer type");
632 // Okay, create the alias but do not insert it into the module yet.
633 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
634 (GlobalValue::LinkageTypes)Linkage, Name,
636 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
638 // See if this value already exists in the symbol table. If so, it is either
639 // a redefinition or a definition of a forward reference.
640 if (GlobalValue *Val = M->getNamedValue(Name)) {
641 // See if this was a redefinition. If so, there is no entry in
643 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
644 I = ForwardRefVals.find(Name);
645 if (I == ForwardRefVals.end())
646 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
648 // Otherwise, this was a definition of forward ref. Verify that types
650 if (Val->getType() != GA->getType())
651 return Error(NameLoc,
652 "forward reference and definition of alias have different types");
654 // If they agree, just RAUW the old value with the alias and remove the
656 Val->replaceAllUsesWith(GA);
657 Val->eraseFromParent();
658 ForwardRefVals.erase(I);
661 // Insert into the module, we know its name won't collide now.
662 M->getAliasList().push_back(GA);
663 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
669 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
670 /// OptionalAddrSpace GlobalType Type Const
671 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
672 /// OptionalAddrSpace GlobalType Type Const
674 /// Everything through visibility has been parsed already.
676 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
677 unsigned Linkage, bool HasLinkage,
678 unsigned Visibility) {
680 bool ThreadLocal, IsConstant;
683 PATypeHolder Ty(Type::getVoidTy(Context));
684 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
685 ParseOptionalAddrSpace(AddrSpace) ||
686 ParseGlobalType(IsConstant) ||
687 ParseType(Ty, TyLoc))
690 // If the linkage is specified and is external, then no initializer is
693 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
694 Linkage != GlobalValue::ExternalWeakLinkage &&
695 Linkage != GlobalValue::ExternalLinkage)) {
696 if (ParseGlobalValue(Ty, Init))
700 if (isa<FunctionType>(Ty) || Ty->isLabelTy())
701 return Error(TyLoc, "invalid type for global variable");
703 GlobalVariable *GV = 0;
705 // See if the global was forward referenced, if so, use the global.
707 if (GlobalValue *GVal = M->getNamedValue(Name)) {
708 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
709 return Error(NameLoc, "redefinition of global '@" + Name + "'");
710 GV = cast<GlobalVariable>(GVal);
713 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
714 I = ForwardRefValIDs.find(NumberedVals.size());
715 if (I != ForwardRefValIDs.end()) {
716 GV = cast<GlobalVariable>(I->second.first);
717 ForwardRefValIDs.erase(I);
722 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
723 Name, 0, false, AddrSpace);
725 if (GV->getType()->getElementType() != Ty)
727 "forward reference and definition of global have different types");
729 // Move the forward-reference to the correct spot in the module.
730 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
734 NumberedVals.push_back(GV);
736 // Set the parsed properties on the global.
738 GV->setInitializer(Init);
739 GV->setConstant(IsConstant);
740 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
741 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
742 GV->setThreadLocal(ThreadLocal);
744 // Parse attributes on the global.
745 while (Lex.getKind() == lltok::comma) {
748 if (Lex.getKind() == lltok::kw_section) {
750 GV->setSection(Lex.getStrVal());
751 if (ParseToken(lltok::StringConstant, "expected global section string"))
753 } else if (Lex.getKind() == lltok::kw_align) {
755 if (ParseOptionalAlignment(Alignment)) return true;
756 GV->setAlignment(Alignment);
758 TokError("unknown global variable property!");
766 //===----------------------------------------------------------------------===//
767 // GlobalValue Reference/Resolution Routines.
768 //===----------------------------------------------------------------------===//
770 /// GetGlobalVal - Get a value with the specified name or ID, creating a
771 /// forward reference record if needed. This can return null if the value
772 /// exists but does not have the right type.
773 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
775 const PointerType *PTy = dyn_cast<PointerType>(Ty);
777 Error(Loc, "global variable reference must have pointer type");
781 // Look this name up in the normal function symbol table.
783 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
785 // If this is a forward reference for the value, see if we already created a
786 // forward ref record.
788 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
789 I = ForwardRefVals.find(Name);
790 if (I != ForwardRefVals.end())
791 Val = I->second.first;
794 // If we have the value in the symbol table or fwd-ref table, return it.
796 if (Val->getType() == Ty) return Val;
797 Error(Loc, "'@" + Name + "' defined with type '" +
798 Val->getType()->getDescription() + "'");
802 // Otherwise, create a new forward reference for this value and remember it.
804 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
805 // Function types can return opaque but functions can't.
806 if (isa<OpaqueType>(FT->getReturnType())) {
807 Error(Loc, "function may not return opaque type");
811 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
813 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
814 GlobalValue::ExternalWeakLinkage, 0, Name);
817 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
821 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
822 const PointerType *PTy = dyn_cast<PointerType>(Ty);
824 Error(Loc, "global variable reference must have pointer type");
828 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
830 // If this is a forward reference for the value, see if we already created a
831 // forward ref record.
833 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
834 I = ForwardRefValIDs.find(ID);
835 if (I != ForwardRefValIDs.end())
836 Val = I->second.first;
839 // If we have the value in the symbol table or fwd-ref table, return it.
841 if (Val->getType() == Ty) return Val;
842 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
843 Val->getType()->getDescription() + "'");
847 // Otherwise, create a new forward reference for this value and remember it.
849 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
850 // Function types can return opaque but functions can't.
851 if (isa<OpaqueType>(FT->getReturnType())) {
852 Error(Loc, "function may not return opaque type");
855 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
857 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
858 GlobalValue::ExternalWeakLinkage, 0, "");
861 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
866 //===----------------------------------------------------------------------===//
868 //===----------------------------------------------------------------------===//
870 /// ParseToken - If the current token has the specified kind, eat it and return
871 /// success. Otherwise, emit the specified error and return failure.
872 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
873 if (Lex.getKind() != T)
874 return TokError(ErrMsg);
879 /// ParseStringConstant
880 /// ::= StringConstant
881 bool LLParser::ParseStringConstant(std::string &Result) {
882 if (Lex.getKind() != lltok::StringConstant)
883 return TokError("expected string constant");
884 Result = Lex.getStrVal();
891 bool LLParser::ParseUInt32(unsigned &Val) {
892 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
893 return TokError("expected integer");
894 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
895 if (Val64 != unsigned(Val64))
896 return TokError("expected 32-bit integer (too large)");
903 /// ParseOptionalAddrSpace
905 /// := 'addrspace' '(' uint32 ')'
906 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
908 if (!EatIfPresent(lltok::kw_addrspace))
910 return ParseToken(lltok::lparen, "expected '(' in address space") ||
911 ParseUInt32(AddrSpace) ||
912 ParseToken(lltok::rparen, "expected ')' in address space");
915 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
916 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
917 /// 2: function attr.
918 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
919 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
920 Attrs = Attribute::None;
921 LocTy AttrLoc = Lex.getLoc();
924 switch (Lex.getKind()) {
927 // Treat these as signext/zeroext if they occur in the argument list after
928 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
929 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
931 // FIXME: REMOVE THIS IN LLVM 3.0
933 if (Lex.getKind() == lltok::kw_sext)
934 Attrs |= Attribute::SExt;
936 Attrs |= Attribute::ZExt;
940 default: // End of attributes.
941 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
942 return Error(AttrLoc, "invalid use of function-only attribute");
944 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
945 return Error(AttrLoc, "invalid use of parameter-only attribute");
948 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
949 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
950 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
951 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
952 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
953 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
954 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
955 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
957 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
958 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
959 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
960 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
961 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
962 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
963 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
964 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
965 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
966 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
967 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
968 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
969 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
971 case lltok::kw_align: {
973 if (ParseOptionalAlignment(Alignment))
975 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
983 /// ParseOptionalLinkage
986 /// ::= 'linker_private'
991 /// ::= 'linkonce_odr'
996 /// ::= 'extern_weak'
998 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1000 switch (Lex.getKind()) {
1001 default: Res=GlobalValue::ExternalLinkage; return false;
1002 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1003 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1004 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1005 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1006 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1007 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1008 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1009 case lltok::kw_available_externally:
1010 Res = GlobalValue::AvailableExternallyLinkage;
1012 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1013 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1014 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1015 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1016 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1017 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1024 /// ParseOptionalVisibility
1030 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1031 switch (Lex.getKind()) {
1032 default: Res = GlobalValue::DefaultVisibility; return false;
1033 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1034 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1035 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1041 /// ParseOptionalCallingConv
1046 /// ::= 'x86_stdcallcc'
1047 /// ::= 'x86_fastcallcc'
1048 /// ::= 'arm_apcscc'
1049 /// ::= 'arm_aapcscc'
1050 /// ::= 'arm_aapcs_vfpcc'
1053 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1054 switch (Lex.getKind()) {
1055 default: CC = CallingConv::C; return false;
1056 case lltok::kw_ccc: CC = CallingConv::C; break;
1057 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1058 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1059 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1060 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1061 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1062 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1063 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1064 case lltok::kw_cc: {
1065 unsigned ArbitraryCC;
1067 if (ParseUInt32(ArbitraryCC)) {
1070 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1080 /// ParseOptionalCustomMetadata
1083 bool LLParser::ParseOptionalCustomMetadata() {
1084 if (Lex.getKind() != lltok::NamedOrCustomMD)
1087 std::string Name = Lex.getStrVal();
1090 if (Lex.getKind() != lltok::Metadata)
1091 return TokError("Expected '!' here");
1095 if (ParseMDNode(Node)) return true;
1097 MetadataContext &TheMetadata = M->getContext().getMetadata();
1098 unsigned MDK = TheMetadata.getMDKind(Name.c_str());
1100 MDK = TheMetadata.registerMDKind(Name.c_str());
1101 MDsOnInst.push_back(std::make_pair(MDK, cast<MDNode>(Node)));
1106 /// ParseOptionalAlignment
1109 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1111 if (!EatIfPresent(lltok::kw_align))
1113 LocTy AlignLoc = Lex.getLoc();
1114 if (ParseUInt32(Alignment)) return true;
1115 if (!isPowerOf2_32(Alignment))
1116 return Error(AlignLoc, "alignment is not a power of two");
1120 /// ParseOptionalInfo
1121 /// ::= OptionalInfo (',' OptionalInfo)+
1122 bool LLParser::ParseOptionalInfo(unsigned &Alignment) {
1124 // FIXME: Handle customized metadata info attached with an instruction.
1126 if (Lex.getKind() == lltok::NamedOrCustomMD) {
1127 if (ParseOptionalCustomMetadata()) return true;
1128 } else if (Lex.getKind() == lltok::kw_align) {
1129 if (ParseOptionalAlignment(Alignment)) return true;
1132 } while (EatIfPresent(lltok::comma));
1139 /// ::= (',' uint32)+
1140 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
1141 if (Lex.getKind() != lltok::comma)
1142 return TokError("expected ',' as start of index list");
1144 while (EatIfPresent(lltok::comma)) {
1146 if (ParseUInt32(Idx)) return true;
1147 Indices.push_back(Idx);
1153 //===----------------------------------------------------------------------===//
1155 //===----------------------------------------------------------------------===//
1157 /// ParseType - Parse and resolve a full type.
1158 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1159 LocTy TypeLoc = Lex.getLoc();
1160 if (ParseTypeRec(Result)) return true;
1162 // Verify no unresolved uprefs.
1163 if (!UpRefs.empty())
1164 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1166 if (!AllowVoid && Result.get()->isVoidTy())
1167 return Error(TypeLoc, "void type only allowed for function results");
1172 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1173 /// called. It loops through the UpRefs vector, which is a list of the
1174 /// currently active types. For each type, if the up-reference is contained in
1175 /// the newly completed type, we decrement the level count. When the level
1176 /// count reaches zero, the up-referenced type is the type that is passed in:
1177 /// thus we can complete the cycle.
1179 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1180 // If Ty isn't abstract, or if there are no up-references in it, then there is
1181 // nothing to resolve here.
1182 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1184 PATypeHolder Ty(ty);
1186 errs() << "Type '" << Ty->getDescription()
1187 << "' newly formed. Resolving upreferences.\n"
1188 << UpRefs.size() << " upreferences active!\n";
1191 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1192 // to zero), we resolve them all together before we resolve them to Ty. At
1193 // the end of the loop, if there is anything to resolve to Ty, it will be in
1195 OpaqueType *TypeToResolve = 0;
1197 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1198 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1200 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1201 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1204 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1205 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1206 << (ContainsType ? "true" : "false")
1207 << " level=" << UpRefs[i].NestingLevel << "\n";
1212 // Decrement level of upreference
1213 unsigned Level = --UpRefs[i].NestingLevel;
1214 UpRefs[i].LastContainedTy = Ty;
1216 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1221 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1224 TypeToResolve = UpRefs[i].UpRefTy;
1226 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1227 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1228 --i; // Do not skip the next element.
1232 TypeToResolve->refineAbstractTypeTo(Ty);
1238 /// ParseTypeRec - The recursive function used to process the internal
1239 /// implementation details of types.
1240 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1241 switch (Lex.getKind()) {
1243 return TokError("expected type");
1245 // TypeRec ::= 'float' | 'void' (etc)
1246 Result = Lex.getTyVal();
1249 case lltok::kw_opaque:
1250 // TypeRec ::= 'opaque'
1251 Result = OpaqueType::get(Context);
1255 // TypeRec ::= '{' ... '}'
1256 if (ParseStructType(Result, false))
1259 case lltok::lsquare:
1260 // TypeRec ::= '[' ... ']'
1261 Lex.Lex(); // eat the lsquare.
1262 if (ParseArrayVectorType(Result, false))
1265 case lltok::less: // Either vector or packed struct.
1266 // TypeRec ::= '<' ... '>'
1268 if (Lex.getKind() == lltok::lbrace) {
1269 if (ParseStructType(Result, true) ||
1270 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1272 } else if (ParseArrayVectorType(Result, true))
1275 case lltok::LocalVar:
1276 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1278 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1281 Result = OpaqueType::get(Context);
1282 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1283 std::make_pair(Result,
1285 M->addTypeName(Lex.getStrVal(), Result.get());
1290 case lltok::LocalVarID:
1292 if (Lex.getUIntVal() < NumberedTypes.size())
1293 Result = NumberedTypes[Lex.getUIntVal()];
1295 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1296 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1297 if (I != ForwardRefTypeIDs.end())
1298 Result = I->second.first;
1300 Result = OpaqueType::get(Context);
1301 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1302 std::make_pair(Result,
1308 case lltok::backslash: {
1309 // TypeRec ::= '\' 4
1312 if (ParseUInt32(Val)) return true;
1313 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1314 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1320 // Parse the type suffixes.
1322 switch (Lex.getKind()) {
1324 default: return false;
1326 // TypeRec ::= TypeRec '*'
1328 if (Result.get()->isLabelTy())
1329 return TokError("basic block pointers are invalid");
1330 if (Result.get()->isVoidTy())
1331 return TokError("pointers to void are invalid; use i8* instead");
1332 if (!PointerType::isValidElementType(Result.get()))
1333 return TokError("pointer to this type is invalid");
1334 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1338 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1339 case lltok::kw_addrspace: {
1340 if (Result.get()->isLabelTy())
1341 return TokError("basic block pointers are invalid");
1342 if (Result.get()->isVoidTy())
1343 return TokError("pointers to void are invalid; use i8* instead");
1344 if (!PointerType::isValidElementType(Result.get()))
1345 return TokError("pointer to this type is invalid");
1347 if (ParseOptionalAddrSpace(AddrSpace) ||
1348 ParseToken(lltok::star, "expected '*' in address space"))
1351 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1355 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1357 if (ParseFunctionType(Result))
1364 /// ParseParameterList
1366 /// ::= '(' Arg (',' Arg)* ')'
1368 /// ::= Type OptionalAttributes Value OptionalAttributes
1369 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1370 PerFunctionState &PFS) {
1371 if (ParseToken(lltok::lparen, "expected '(' in call"))
1374 while (Lex.getKind() != lltok::rparen) {
1375 // If this isn't the first argument, we need a comma.
1376 if (!ArgList.empty() &&
1377 ParseToken(lltok::comma, "expected ',' in argument list"))
1380 // Parse the argument.
1382 PATypeHolder ArgTy(Type::getVoidTy(Context));
1383 unsigned ArgAttrs1, ArgAttrs2;
1385 if (ParseType(ArgTy, ArgLoc) ||
1386 ParseOptionalAttrs(ArgAttrs1, 0) ||
1387 ParseValue(ArgTy, V, PFS) ||
1388 // FIXME: Should not allow attributes after the argument, remove this in
1390 ParseOptionalAttrs(ArgAttrs2, 3))
1392 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1395 Lex.Lex(); // Lex the ')'.
1401 /// ParseArgumentList - Parse the argument list for a function type or function
1402 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1403 /// ::= '(' ArgTypeListI ')'
1407 /// ::= ArgTypeList ',' '...'
1408 /// ::= ArgType (',' ArgType)*
1410 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1411 bool &isVarArg, bool inType) {
1413 assert(Lex.getKind() == lltok::lparen);
1414 Lex.Lex(); // eat the (.
1416 if (Lex.getKind() == lltok::rparen) {
1418 } else if (Lex.getKind() == lltok::dotdotdot) {
1422 LocTy TypeLoc = Lex.getLoc();
1423 PATypeHolder ArgTy(Type::getVoidTy(Context));
1427 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1428 // types (such as a function returning a pointer to itself). If parsing a
1429 // function prototype, we require fully resolved types.
1430 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1431 ParseOptionalAttrs(Attrs, 0)) return true;
1433 if (ArgTy->isVoidTy())
1434 return Error(TypeLoc, "argument can not have void type");
1436 if (Lex.getKind() == lltok::LocalVar ||
1437 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1438 Name = Lex.getStrVal();
1442 if (!FunctionType::isValidArgumentType(ArgTy))
1443 return Error(TypeLoc, "invalid type for function argument");
1445 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1447 while (EatIfPresent(lltok::comma)) {
1448 // Handle ... at end of arg list.
1449 if (EatIfPresent(lltok::dotdotdot)) {
1454 // Otherwise must be an argument type.
1455 TypeLoc = Lex.getLoc();
1456 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1457 ParseOptionalAttrs(Attrs, 0)) return true;
1459 if (ArgTy->isVoidTy())
1460 return Error(TypeLoc, "argument can not have void type");
1462 if (Lex.getKind() == lltok::LocalVar ||
1463 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1464 Name = Lex.getStrVal();
1470 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1471 return Error(TypeLoc, "invalid type for function argument");
1473 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1477 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1480 /// ParseFunctionType
1481 /// ::= Type ArgumentList OptionalAttrs
1482 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1483 assert(Lex.getKind() == lltok::lparen);
1485 if (!FunctionType::isValidReturnType(Result))
1486 return TokError("invalid function return type");
1488 std::vector<ArgInfo> ArgList;
1491 if (ParseArgumentList(ArgList, isVarArg, true) ||
1492 // FIXME: Allow, but ignore attributes on function types!
1493 // FIXME: Remove in LLVM 3.0
1494 ParseOptionalAttrs(Attrs, 2))
1497 // Reject names on the arguments lists.
1498 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1499 if (!ArgList[i].Name.empty())
1500 return Error(ArgList[i].Loc, "argument name invalid in function type");
1501 if (!ArgList[i].Attrs != 0) {
1502 // Allow but ignore attributes on function types; this permits
1504 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1508 std::vector<const Type*> ArgListTy;
1509 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1510 ArgListTy.push_back(ArgList[i].Type);
1512 Result = HandleUpRefs(FunctionType::get(Result.get(),
1513 ArgListTy, isVarArg));
1517 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1520 /// ::= '{' TypeRec (',' TypeRec)* '}'
1521 /// ::= '<' '{' '}' '>'
1522 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1523 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1524 assert(Lex.getKind() == lltok::lbrace);
1525 Lex.Lex(); // Consume the '{'
1527 if (EatIfPresent(lltok::rbrace)) {
1528 Result = StructType::get(Context, Packed);
1532 std::vector<PATypeHolder> ParamsList;
1533 LocTy EltTyLoc = Lex.getLoc();
1534 if (ParseTypeRec(Result)) return true;
1535 ParamsList.push_back(Result);
1537 if (Result->isVoidTy())
1538 return Error(EltTyLoc, "struct element can not have void type");
1539 if (!StructType::isValidElementType(Result))
1540 return Error(EltTyLoc, "invalid element type for struct");
1542 while (EatIfPresent(lltok::comma)) {
1543 EltTyLoc = Lex.getLoc();
1544 if (ParseTypeRec(Result)) return true;
1546 if (Result->isVoidTy())
1547 return Error(EltTyLoc, "struct element can not have void type");
1548 if (!StructType::isValidElementType(Result))
1549 return Error(EltTyLoc, "invalid element type for struct");
1551 ParamsList.push_back(Result);
1554 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1557 std::vector<const Type*> ParamsListTy;
1558 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1559 ParamsListTy.push_back(ParamsList[i].get());
1560 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1564 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1565 /// token has already been consumed.
1567 /// ::= '[' APSINTVAL 'x' Types ']'
1568 /// ::= '<' APSINTVAL 'x' Types '>'
1569 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1570 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1571 Lex.getAPSIntVal().getBitWidth() > 64)
1572 return TokError("expected number in address space");
1574 LocTy SizeLoc = Lex.getLoc();
1575 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1578 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1581 LocTy TypeLoc = Lex.getLoc();
1582 PATypeHolder EltTy(Type::getVoidTy(Context));
1583 if (ParseTypeRec(EltTy)) return true;
1585 if (EltTy->isVoidTy())
1586 return Error(TypeLoc, "array and vector element type cannot be void");
1588 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1589 "expected end of sequential type"))
1594 return Error(SizeLoc, "zero element vector is illegal");
1595 if ((unsigned)Size != Size)
1596 return Error(SizeLoc, "size too large for vector");
1597 if (!VectorType::isValidElementType(EltTy))
1598 return Error(TypeLoc, "vector element type must be fp or integer");
1599 Result = VectorType::get(EltTy, unsigned(Size));
1601 if (!ArrayType::isValidElementType(EltTy))
1602 return Error(TypeLoc, "invalid array element type");
1603 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1608 //===----------------------------------------------------------------------===//
1609 // Function Semantic Analysis.
1610 //===----------------------------------------------------------------------===//
1612 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1614 : P(p), F(f), FunctionNumber(functionNumber) {
1616 // Insert unnamed arguments into the NumberedVals list.
1617 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1620 NumberedVals.push_back(AI);
1623 LLParser::PerFunctionState::~PerFunctionState() {
1624 // If there were any forward referenced non-basicblock values, delete them.
1625 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1626 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1627 if (!isa<BasicBlock>(I->second.first)) {
1628 I->second.first->replaceAllUsesWith(
1629 UndefValue::get(I->second.first->getType()));
1630 delete I->second.first;
1631 I->second.first = 0;
1634 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1635 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1636 if (!isa<BasicBlock>(I->second.first)) {
1637 I->second.first->replaceAllUsesWith(
1638 UndefValue::get(I->second.first->getType()));
1639 delete I->second.first;
1640 I->second.first = 0;
1644 bool LLParser::PerFunctionState::FinishFunction() {
1645 // Check to see if someone took the address of labels in this block.
1646 if (!P.ForwardRefBlockAddresses.empty()) {
1648 if (!F.getName().empty()) {
1649 FunctionID.Kind = ValID::t_GlobalName;
1650 FunctionID.StrVal = F.getName();
1652 FunctionID.Kind = ValID::t_GlobalID;
1653 FunctionID.UIntVal = FunctionNumber;
1656 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1657 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1658 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1659 // Resolve all these references.
1660 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1663 P.ForwardRefBlockAddresses.erase(FRBAI);
1667 if (!ForwardRefVals.empty())
1668 return P.Error(ForwardRefVals.begin()->second.second,
1669 "use of undefined value '%" + ForwardRefVals.begin()->first +
1671 if (!ForwardRefValIDs.empty())
1672 return P.Error(ForwardRefValIDs.begin()->second.second,
1673 "use of undefined value '%" +
1674 utostr(ForwardRefValIDs.begin()->first) + "'");
1679 /// GetVal - Get a value with the specified name or ID, creating a
1680 /// forward reference record if needed. This can return null if the value
1681 /// exists but does not have the right type.
1682 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1683 const Type *Ty, LocTy Loc) {
1684 // Look this name up in the normal function symbol table.
1685 Value *Val = F.getValueSymbolTable().lookup(Name);
1687 // If this is a forward reference for the value, see if we already created a
1688 // forward ref record.
1690 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1691 I = ForwardRefVals.find(Name);
1692 if (I != ForwardRefVals.end())
1693 Val = I->second.first;
1696 // If we have the value in the symbol table or fwd-ref table, return it.
1698 if (Val->getType() == Ty) return Val;
1699 if (Ty->isLabelTy())
1700 P.Error(Loc, "'%" + Name + "' is not a basic block");
1702 P.Error(Loc, "'%" + Name + "' defined with type '" +
1703 Val->getType()->getDescription() + "'");
1707 // Don't make placeholders with invalid type.
1708 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1709 Ty != Type::getLabelTy(F.getContext())) {
1710 P.Error(Loc, "invalid use of a non-first-class type");
1714 // Otherwise, create a new forward reference for this value and remember it.
1716 if (Ty->isLabelTy())
1717 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1719 FwdVal = new Argument(Ty, Name);
1721 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1725 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1727 // Look this name up in the normal function symbol table.
1728 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1730 // If this is a forward reference for the value, see if we already created a
1731 // forward ref record.
1733 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1734 I = ForwardRefValIDs.find(ID);
1735 if (I != ForwardRefValIDs.end())
1736 Val = I->second.first;
1739 // If we have the value in the symbol table or fwd-ref table, return it.
1741 if (Val->getType() == Ty) return Val;
1742 if (Ty->isLabelTy())
1743 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1745 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1746 Val->getType()->getDescription() + "'");
1750 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) &&
1751 Ty != Type::getLabelTy(F.getContext())) {
1752 P.Error(Loc, "invalid use of a non-first-class type");
1756 // Otherwise, create a new forward reference for this value and remember it.
1758 if (Ty->isLabelTy())
1759 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1761 FwdVal = new Argument(Ty);
1763 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1767 /// SetInstName - After an instruction is parsed and inserted into its
1768 /// basic block, this installs its name.
1769 bool LLParser::PerFunctionState::SetInstName(int NameID,
1770 const std::string &NameStr,
1771 LocTy NameLoc, Instruction *Inst) {
1772 // If this instruction has void type, it cannot have a name or ID specified.
1773 if (Inst->getType()->isVoidTy()) {
1774 if (NameID != -1 || !NameStr.empty())
1775 return P.Error(NameLoc, "instructions returning void cannot have a name");
1779 // If this was a numbered instruction, verify that the instruction is the
1780 // expected value and resolve any forward references.
1781 if (NameStr.empty()) {
1782 // If neither a name nor an ID was specified, just use the next ID.
1784 NameID = NumberedVals.size();
1786 if (unsigned(NameID) != NumberedVals.size())
1787 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1788 utostr(NumberedVals.size()) + "'");
1790 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1791 ForwardRefValIDs.find(NameID);
1792 if (FI != ForwardRefValIDs.end()) {
1793 if (FI->second.first->getType() != Inst->getType())
1794 return P.Error(NameLoc, "instruction forward referenced with type '" +
1795 FI->second.first->getType()->getDescription() + "'");
1796 FI->second.first->replaceAllUsesWith(Inst);
1797 delete FI->second.first;
1798 ForwardRefValIDs.erase(FI);
1801 NumberedVals.push_back(Inst);
1805 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1806 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1807 FI = ForwardRefVals.find(NameStr);
1808 if (FI != ForwardRefVals.end()) {
1809 if (FI->second.first->getType() != Inst->getType())
1810 return P.Error(NameLoc, "instruction forward referenced with type '" +
1811 FI->second.first->getType()->getDescription() + "'");
1812 FI->second.first->replaceAllUsesWith(Inst);
1813 delete FI->second.first;
1814 ForwardRefVals.erase(FI);
1817 // Set the name on the instruction.
1818 Inst->setName(NameStr);
1820 if (Inst->getNameStr() != NameStr)
1821 return P.Error(NameLoc, "multiple definition of local value named '" +
1826 /// GetBB - Get a basic block with the specified name or ID, creating a
1827 /// forward reference record if needed.
1828 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1830 return cast_or_null<BasicBlock>(GetVal(Name,
1831 Type::getLabelTy(F.getContext()), Loc));
1834 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1835 return cast_or_null<BasicBlock>(GetVal(ID,
1836 Type::getLabelTy(F.getContext()), Loc));
1839 /// DefineBB - Define the specified basic block, which is either named or
1840 /// unnamed. If there is an error, this returns null otherwise it returns
1841 /// the block being defined.
1842 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1846 BB = GetBB(NumberedVals.size(), Loc);
1848 BB = GetBB(Name, Loc);
1849 if (BB == 0) return 0; // Already diagnosed error.
1851 // Move the block to the end of the function. Forward ref'd blocks are
1852 // inserted wherever they happen to be referenced.
1853 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1855 // Remove the block from forward ref sets.
1857 ForwardRefValIDs.erase(NumberedVals.size());
1858 NumberedVals.push_back(BB);
1860 // BB forward references are already in the function symbol table.
1861 ForwardRefVals.erase(Name);
1867 //===----------------------------------------------------------------------===//
1869 //===----------------------------------------------------------------------===//
1871 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1872 /// type implied. For example, if we parse "4" we don't know what integer type
1873 /// it has. The value will later be combined with its type and checked for
1875 bool LLParser::ParseValID(ValID &ID) {
1876 ID.Loc = Lex.getLoc();
1877 switch (Lex.getKind()) {
1878 default: return TokError("expected value token");
1879 case lltok::GlobalID: // @42
1880 ID.UIntVal = Lex.getUIntVal();
1881 ID.Kind = ValID::t_GlobalID;
1883 case lltok::GlobalVar: // @foo
1884 ID.StrVal = Lex.getStrVal();
1885 ID.Kind = ValID::t_GlobalName;
1887 case lltok::LocalVarID: // %42
1888 ID.UIntVal = Lex.getUIntVal();
1889 ID.Kind = ValID::t_LocalID;
1891 case lltok::LocalVar: // %foo
1892 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1893 ID.StrVal = Lex.getStrVal();
1894 ID.Kind = ValID::t_LocalName;
1896 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1897 ID.Kind = ValID::t_Metadata;
1899 if (Lex.getKind() == lltok::lbrace) {
1900 SmallVector<Value*, 16> Elts;
1901 if (ParseMDNodeVector(Elts) ||
1902 ParseToken(lltok::rbrace, "expected end of metadata node"))
1905 ID.MetadataVal = MDNode::get(Context, Elts.data(), Elts.size());
1909 // Standalone metadata reference
1910 // !{ ..., !42, ... }
1911 if (!ParseMDNode(ID.MetadataVal))
1915 // ::= '!' STRINGCONSTANT
1916 if (ParseMDString(ID.MetadataVal)) return true;
1917 ID.Kind = ValID::t_Metadata;
1921 ID.APSIntVal = Lex.getAPSIntVal();
1922 ID.Kind = ValID::t_APSInt;
1924 case lltok::APFloat:
1925 ID.APFloatVal = Lex.getAPFloatVal();
1926 ID.Kind = ValID::t_APFloat;
1928 case lltok::kw_true:
1929 ID.ConstantVal = ConstantInt::getTrue(Context);
1930 ID.Kind = ValID::t_Constant;
1932 case lltok::kw_false:
1933 ID.ConstantVal = ConstantInt::getFalse(Context);
1934 ID.Kind = ValID::t_Constant;
1936 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1937 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1938 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1940 case lltok::lbrace: {
1941 // ValID ::= '{' ConstVector '}'
1943 SmallVector<Constant*, 16> Elts;
1944 if (ParseGlobalValueVector(Elts) ||
1945 ParseToken(lltok::rbrace, "expected end of struct constant"))
1948 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1949 Elts.size(), false);
1950 ID.Kind = ValID::t_Constant;
1954 // ValID ::= '<' ConstVector '>' --> Vector.
1955 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1957 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1959 SmallVector<Constant*, 16> Elts;
1960 LocTy FirstEltLoc = Lex.getLoc();
1961 if (ParseGlobalValueVector(Elts) ||
1963 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1964 ParseToken(lltok::greater, "expected end of constant"))
1967 if (isPackedStruct) {
1969 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
1970 ID.Kind = ValID::t_Constant;
1975 return Error(ID.Loc, "constant vector must not be empty");
1977 if (!Elts[0]->getType()->isInteger() &&
1978 !Elts[0]->getType()->isFloatingPoint())
1979 return Error(FirstEltLoc,
1980 "vector elements must have integer or floating point type");
1982 // Verify that all the vector elements have the same type.
1983 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1984 if (Elts[i]->getType() != Elts[0]->getType())
1985 return Error(FirstEltLoc,
1986 "vector element #" + utostr(i) +
1987 " is not of type '" + Elts[0]->getType()->getDescription());
1989 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
1990 ID.Kind = ValID::t_Constant;
1993 case lltok::lsquare: { // Array Constant
1995 SmallVector<Constant*, 16> Elts;
1996 LocTy FirstEltLoc = Lex.getLoc();
1997 if (ParseGlobalValueVector(Elts) ||
1998 ParseToken(lltok::rsquare, "expected end of array constant"))
2001 // Handle empty element.
2003 // Use undef instead of an array because it's inconvenient to determine
2004 // the element type at this point, there being no elements to examine.
2005 ID.Kind = ValID::t_EmptyArray;
2009 if (!Elts[0]->getType()->isFirstClassType())
2010 return Error(FirstEltLoc, "invalid array element type: " +
2011 Elts[0]->getType()->getDescription());
2013 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2015 // Verify all elements are correct type!
2016 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2017 if (Elts[i]->getType() != Elts[0]->getType())
2018 return Error(FirstEltLoc,
2019 "array element #" + utostr(i) +
2020 " is not of type '" +Elts[0]->getType()->getDescription());
2023 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2024 ID.Kind = ValID::t_Constant;
2027 case lltok::kw_c: // c "foo"
2029 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2030 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2031 ID.Kind = ValID::t_Constant;
2034 case lltok::kw_asm: {
2035 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2036 bool HasSideEffect, AlignStack;
2038 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2039 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2040 ParseStringConstant(ID.StrVal) ||
2041 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2042 ParseToken(lltok::StringConstant, "expected constraint string"))
2044 ID.StrVal2 = Lex.getStrVal();
2045 ID.UIntVal = HasSideEffect | ((unsigned)AlignStack<<1);
2046 ID.Kind = ValID::t_InlineAsm;
2050 case lltok::kw_blockaddress: {
2051 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2055 LocTy FnLoc, LabelLoc;
2057 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2059 ParseToken(lltok::comma, "expected comma in block address expression")||
2060 ParseValID(Label) ||
2061 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2064 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2065 return Error(Fn.Loc, "expected function name in blockaddress");
2066 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName &&
2067 Label.Kind != ValID::t_Null)
2068 return Error(Label.Loc, "expected basic block name in blockaddress");
2070 // Make a global variable as a placeholder for this reference.
2071 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2072 false, GlobalValue::InternalLinkage,
2074 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2075 ID.ConstantVal = FwdRef;
2076 ID.Kind = ValID::t_Constant;
2080 case lltok::kw_trunc:
2081 case lltok::kw_zext:
2082 case lltok::kw_sext:
2083 case lltok::kw_fptrunc:
2084 case lltok::kw_fpext:
2085 case lltok::kw_bitcast:
2086 case lltok::kw_uitofp:
2087 case lltok::kw_sitofp:
2088 case lltok::kw_fptoui:
2089 case lltok::kw_fptosi:
2090 case lltok::kw_inttoptr:
2091 case lltok::kw_ptrtoint: {
2092 unsigned Opc = Lex.getUIntVal();
2093 PATypeHolder DestTy(Type::getVoidTy(Context));
2096 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2097 ParseGlobalTypeAndValue(SrcVal) ||
2098 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2099 ParseType(DestTy) ||
2100 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2102 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2103 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2104 SrcVal->getType()->getDescription() + "' to '" +
2105 DestTy->getDescription() + "'");
2106 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2108 ID.Kind = ValID::t_Constant;
2111 case lltok::kw_extractvalue: {
2114 SmallVector<unsigned, 4> Indices;
2115 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2116 ParseGlobalTypeAndValue(Val) ||
2117 ParseIndexList(Indices) ||
2118 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2120 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
2121 return Error(ID.Loc, "extractvalue operand must be array or struct");
2122 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2124 return Error(ID.Loc, "invalid indices for extractvalue");
2126 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2127 ID.Kind = ValID::t_Constant;
2130 case lltok::kw_insertvalue: {
2132 Constant *Val0, *Val1;
2133 SmallVector<unsigned, 4> Indices;
2134 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2135 ParseGlobalTypeAndValue(Val0) ||
2136 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2137 ParseGlobalTypeAndValue(Val1) ||
2138 ParseIndexList(Indices) ||
2139 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2141 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
2142 return Error(ID.Loc, "extractvalue operand must be array or struct");
2143 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2145 return Error(ID.Loc, "invalid indices for insertvalue");
2146 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2147 Indices.data(), Indices.size());
2148 ID.Kind = ValID::t_Constant;
2151 case lltok::kw_icmp:
2152 case lltok::kw_fcmp: {
2153 unsigned PredVal, Opc = Lex.getUIntVal();
2154 Constant *Val0, *Val1;
2156 if (ParseCmpPredicate(PredVal, Opc) ||
2157 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2158 ParseGlobalTypeAndValue(Val0) ||
2159 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2160 ParseGlobalTypeAndValue(Val1) ||
2161 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2164 if (Val0->getType() != Val1->getType())
2165 return Error(ID.Loc, "compare operands must have the same type");
2167 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2169 if (Opc == Instruction::FCmp) {
2170 if (!Val0->getType()->isFPOrFPVector())
2171 return Error(ID.Loc, "fcmp requires floating point operands");
2172 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2174 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2175 if (!Val0->getType()->isIntOrIntVector() &&
2176 !isa<PointerType>(Val0->getType()))
2177 return Error(ID.Loc, "icmp requires pointer or integer operands");
2178 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2180 ID.Kind = ValID::t_Constant;
2184 // Binary Operators.
2186 case lltok::kw_fadd:
2188 case lltok::kw_fsub:
2190 case lltok::kw_fmul:
2191 case lltok::kw_udiv:
2192 case lltok::kw_sdiv:
2193 case lltok::kw_fdiv:
2194 case lltok::kw_urem:
2195 case lltok::kw_srem:
2196 case lltok::kw_frem: {
2200 unsigned Opc = Lex.getUIntVal();
2201 Constant *Val0, *Val1;
2203 LocTy ModifierLoc = Lex.getLoc();
2204 if (Opc == Instruction::Add ||
2205 Opc == Instruction::Sub ||
2206 Opc == Instruction::Mul) {
2207 if (EatIfPresent(lltok::kw_nuw))
2209 if (EatIfPresent(lltok::kw_nsw)) {
2211 if (EatIfPresent(lltok::kw_nuw))
2214 } else if (Opc == Instruction::SDiv) {
2215 if (EatIfPresent(lltok::kw_exact))
2218 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2219 ParseGlobalTypeAndValue(Val0) ||
2220 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2221 ParseGlobalTypeAndValue(Val1) ||
2222 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2224 if (Val0->getType() != Val1->getType())
2225 return Error(ID.Loc, "operands of constexpr must have same type");
2226 if (!Val0->getType()->isIntOrIntVector()) {
2228 return Error(ModifierLoc, "nuw only applies to integer operations");
2230 return Error(ModifierLoc, "nsw only applies to integer operations");
2232 // API compatibility: Accept either integer or floating-point types with
2233 // add, sub, and mul.
2234 if (!Val0->getType()->isIntOrIntVector() &&
2235 !Val0->getType()->isFPOrFPVector())
2236 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2238 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2239 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2240 if (Exact) Flags |= SDivOperator::IsExact;
2241 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2243 ID.Kind = ValID::t_Constant;
2247 // Logical Operations
2249 case lltok::kw_lshr:
2250 case lltok::kw_ashr:
2253 case lltok::kw_xor: {
2254 unsigned Opc = Lex.getUIntVal();
2255 Constant *Val0, *Val1;
2257 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2258 ParseGlobalTypeAndValue(Val0) ||
2259 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2260 ParseGlobalTypeAndValue(Val1) ||
2261 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2263 if (Val0->getType() != Val1->getType())
2264 return Error(ID.Loc, "operands of constexpr must have same type");
2265 if (!Val0->getType()->isIntOrIntVector())
2266 return Error(ID.Loc,
2267 "constexpr requires integer or integer vector operands");
2268 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2269 ID.Kind = ValID::t_Constant;
2273 case lltok::kw_getelementptr:
2274 case lltok::kw_shufflevector:
2275 case lltok::kw_insertelement:
2276 case lltok::kw_extractelement:
2277 case lltok::kw_select: {
2278 unsigned Opc = Lex.getUIntVal();
2279 SmallVector<Constant*, 16> Elts;
2280 bool InBounds = false;
2282 if (Opc == Instruction::GetElementPtr)
2283 InBounds = EatIfPresent(lltok::kw_inbounds);
2284 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2285 ParseGlobalValueVector(Elts) ||
2286 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2289 if (Opc == Instruction::GetElementPtr) {
2290 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
2291 return Error(ID.Loc, "getelementptr requires pointer operand");
2293 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2294 (Value**)(Elts.data() + 1),
2296 return Error(ID.Loc, "invalid indices for getelementptr");
2297 ID.ConstantVal = InBounds ?
2298 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2301 ConstantExpr::getGetElementPtr(Elts[0],
2302 Elts.data() + 1, Elts.size() - 1);
2303 } else if (Opc == Instruction::Select) {
2304 if (Elts.size() != 3)
2305 return Error(ID.Loc, "expected three operands to select");
2306 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2308 return Error(ID.Loc, Reason);
2309 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2310 } else if (Opc == Instruction::ShuffleVector) {
2311 if (Elts.size() != 3)
2312 return Error(ID.Loc, "expected three operands to shufflevector");
2313 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2314 return Error(ID.Loc, "invalid operands to shufflevector");
2316 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2317 } else if (Opc == Instruction::ExtractElement) {
2318 if (Elts.size() != 2)
2319 return Error(ID.Loc, "expected two operands to extractelement");
2320 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2321 return Error(ID.Loc, "invalid extractelement operands");
2322 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2324 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2325 if (Elts.size() != 3)
2326 return Error(ID.Loc, "expected three operands to insertelement");
2327 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2328 return Error(ID.Loc, "invalid insertelement operands");
2330 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2333 ID.Kind = ValID::t_Constant;
2342 /// ParseGlobalValue - Parse a global value with the specified type.
2343 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
2346 return ParseValID(ID) ||
2347 ConvertGlobalValIDToValue(Ty, ID, V);
2350 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2352 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
2354 if (isa<FunctionType>(Ty))
2355 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2358 default: llvm_unreachable("Unknown ValID!");
2359 case ValID::t_Metadata:
2360 return Error(ID.Loc, "invalid use of metadata");
2361 case ValID::t_LocalID:
2362 case ValID::t_LocalName:
2363 return Error(ID.Loc, "invalid use of function-local name");
2364 case ValID::t_InlineAsm:
2365 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
2366 case ValID::t_GlobalName:
2367 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2369 case ValID::t_GlobalID:
2370 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2372 case ValID::t_APSInt:
2373 if (!isa<IntegerType>(Ty))
2374 return Error(ID.Loc, "integer constant must have integer type");
2375 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2376 V = ConstantInt::get(Context, ID.APSIntVal);
2378 case ValID::t_APFloat:
2379 if (!Ty->isFloatingPoint() ||
2380 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2381 return Error(ID.Loc, "floating point constant invalid for type");
2383 // The lexer has no type info, so builds all float and double FP constants
2384 // as double. Fix this here. Long double does not need this.
2385 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2388 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2391 V = ConstantFP::get(Context, ID.APFloatVal);
2393 if (V->getType() != Ty)
2394 return Error(ID.Loc, "floating point constant does not have type '" +
2395 Ty->getDescription() + "'");
2399 if (!isa<PointerType>(Ty))
2400 return Error(ID.Loc, "null must be a pointer type");
2401 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2403 case ValID::t_Undef:
2404 // FIXME: LabelTy should not be a first-class type.
2405 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2406 !isa<OpaqueType>(Ty))
2407 return Error(ID.Loc, "invalid type for undef constant");
2408 V = UndefValue::get(Ty);
2410 case ValID::t_EmptyArray:
2411 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2412 return Error(ID.Loc, "invalid empty array initializer");
2413 V = UndefValue::get(Ty);
2416 // FIXME: LabelTy should not be a first-class type.
2417 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2418 return Error(ID.Loc, "invalid type for null constant");
2419 V = Constant::getNullValue(Ty);
2421 case ValID::t_Constant:
2422 if (ID.ConstantVal->getType() != Ty)
2423 return Error(ID.Loc, "constant expression type mismatch");
2429 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2430 PATypeHolder Type(Type::getVoidTy(Context));
2431 return ParseType(Type) ||
2432 ParseGlobalValue(Type, V);
2435 /// ParseGlobalValueVector
2437 /// ::= TypeAndValue (',' TypeAndValue)*
2438 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2440 if (Lex.getKind() == lltok::rbrace ||
2441 Lex.getKind() == lltok::rsquare ||
2442 Lex.getKind() == lltok::greater ||
2443 Lex.getKind() == lltok::rparen)
2447 if (ParseGlobalTypeAndValue(C)) return true;
2450 while (EatIfPresent(lltok::comma)) {
2451 if (ParseGlobalTypeAndValue(C)) return true;
2459 //===----------------------------------------------------------------------===//
2460 // Function Parsing.
2461 //===----------------------------------------------------------------------===//
2463 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2464 PerFunctionState &PFS) {
2465 if (ID.Kind == ValID::t_LocalID)
2466 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2467 else if (ID.Kind == ValID::t_LocalName)
2468 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2469 else if (ID.Kind == ValID::t_InlineAsm) {
2470 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2471 const FunctionType *FTy =
2472 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2473 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2474 return Error(ID.Loc, "invalid type for inline asm constraint string");
2475 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2477 } else if (ID.Kind == ValID::t_Metadata) {
2481 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2489 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2492 return ParseValID(ID) ||
2493 ConvertValIDToValue(Ty, ID, V, PFS);
2496 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2497 PATypeHolder T(Type::getVoidTy(Context));
2498 return ParseType(T) ||
2499 ParseValue(T, V, PFS);
2502 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2503 PerFunctionState &PFS) {
2506 if (ParseTypeAndValue(V, PFS)) return true;
2507 if (!isa<BasicBlock>(V))
2508 return Error(Loc, "expected a basic block");
2509 BB = cast<BasicBlock>(V);
2515 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2516 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2517 /// OptionalAlign OptGC
2518 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2519 // Parse the linkage.
2520 LocTy LinkageLoc = Lex.getLoc();
2523 unsigned Visibility, RetAttrs;
2525 PATypeHolder RetType(Type::getVoidTy(Context));
2526 LocTy RetTypeLoc = Lex.getLoc();
2527 if (ParseOptionalLinkage(Linkage) ||
2528 ParseOptionalVisibility(Visibility) ||
2529 ParseOptionalCallingConv(CC) ||
2530 ParseOptionalAttrs(RetAttrs, 1) ||
2531 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2534 // Verify that the linkage is ok.
2535 switch ((GlobalValue::LinkageTypes)Linkage) {
2536 case GlobalValue::ExternalLinkage:
2537 break; // always ok.
2538 case GlobalValue::DLLImportLinkage:
2539 case GlobalValue::ExternalWeakLinkage:
2541 return Error(LinkageLoc, "invalid linkage for function definition");
2543 case GlobalValue::PrivateLinkage:
2544 case GlobalValue::LinkerPrivateLinkage:
2545 case GlobalValue::InternalLinkage:
2546 case GlobalValue::AvailableExternallyLinkage:
2547 case GlobalValue::LinkOnceAnyLinkage:
2548 case GlobalValue::LinkOnceODRLinkage:
2549 case GlobalValue::WeakAnyLinkage:
2550 case GlobalValue::WeakODRLinkage:
2551 case GlobalValue::DLLExportLinkage:
2553 return Error(LinkageLoc, "invalid linkage for function declaration");
2555 case GlobalValue::AppendingLinkage:
2556 case GlobalValue::GhostLinkage:
2557 case GlobalValue::CommonLinkage:
2558 return Error(LinkageLoc, "invalid function linkage type");
2561 if (!FunctionType::isValidReturnType(RetType) ||
2562 isa<OpaqueType>(RetType))
2563 return Error(RetTypeLoc, "invalid function return type");
2565 LocTy NameLoc = Lex.getLoc();
2567 std::string FunctionName;
2568 if (Lex.getKind() == lltok::GlobalVar) {
2569 FunctionName = Lex.getStrVal();
2570 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2571 unsigned NameID = Lex.getUIntVal();
2573 if (NameID != NumberedVals.size())
2574 return TokError("function expected to be numbered '%" +
2575 utostr(NumberedVals.size()) + "'");
2577 return TokError("expected function name");
2582 if (Lex.getKind() != lltok::lparen)
2583 return TokError("expected '(' in function argument list");
2585 std::vector<ArgInfo> ArgList;
2588 std::string Section;
2592 if (ParseArgumentList(ArgList, isVarArg, false) ||
2593 ParseOptionalAttrs(FuncAttrs, 2) ||
2594 (EatIfPresent(lltok::kw_section) &&
2595 ParseStringConstant(Section)) ||
2596 ParseOptionalAlignment(Alignment) ||
2597 (EatIfPresent(lltok::kw_gc) &&
2598 ParseStringConstant(GC)))
2601 // If the alignment was parsed as an attribute, move to the alignment field.
2602 if (FuncAttrs & Attribute::Alignment) {
2603 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2604 FuncAttrs &= ~Attribute::Alignment;
2607 // Okay, if we got here, the function is syntactically valid. Convert types
2608 // and do semantic checks.
2609 std::vector<const Type*> ParamTypeList;
2610 SmallVector<AttributeWithIndex, 8> Attrs;
2611 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2613 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2614 if (FuncAttrs & ObsoleteFuncAttrs) {
2615 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2616 FuncAttrs &= ~ObsoleteFuncAttrs;
2619 if (RetAttrs != Attribute::None)
2620 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2622 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2623 ParamTypeList.push_back(ArgList[i].Type);
2624 if (ArgList[i].Attrs != Attribute::None)
2625 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2628 if (FuncAttrs != Attribute::None)
2629 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2631 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2633 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2634 RetType != Type::getVoidTy(Context))
2635 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2637 const FunctionType *FT =
2638 FunctionType::get(RetType, ParamTypeList, isVarArg);
2639 const PointerType *PFT = PointerType::getUnqual(FT);
2642 if (!FunctionName.empty()) {
2643 // If this was a definition of a forward reference, remove the definition
2644 // from the forward reference table and fill in the forward ref.
2645 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2646 ForwardRefVals.find(FunctionName);
2647 if (FRVI != ForwardRefVals.end()) {
2648 Fn = M->getFunction(FunctionName);
2649 ForwardRefVals.erase(FRVI);
2650 } else if ((Fn = M->getFunction(FunctionName))) {
2651 // If this function already exists in the symbol table, then it is
2652 // multiply defined. We accept a few cases for old backwards compat.
2653 // FIXME: Remove this stuff for LLVM 3.0.
2654 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2655 (!Fn->isDeclaration() && isDefine)) {
2656 // If the redefinition has different type or different attributes,
2657 // reject it. If both have bodies, reject it.
2658 return Error(NameLoc, "invalid redefinition of function '" +
2659 FunctionName + "'");
2660 } else if (Fn->isDeclaration()) {
2661 // Make sure to strip off any argument names so we can't get conflicts.
2662 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2666 } else if (M->getNamedValue(FunctionName)) {
2667 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2671 // If this is a definition of a forward referenced function, make sure the
2673 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2674 = ForwardRefValIDs.find(NumberedVals.size());
2675 if (I != ForwardRefValIDs.end()) {
2676 Fn = cast<Function>(I->second.first);
2677 if (Fn->getType() != PFT)
2678 return Error(NameLoc, "type of definition and forward reference of '@" +
2679 utostr(NumberedVals.size()) +"' disagree");
2680 ForwardRefValIDs.erase(I);
2685 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2686 else // Move the forward-reference to the correct spot in the module.
2687 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2689 if (FunctionName.empty())
2690 NumberedVals.push_back(Fn);
2692 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2693 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2694 Fn->setCallingConv(CC);
2695 Fn->setAttributes(PAL);
2696 Fn->setAlignment(Alignment);
2697 Fn->setSection(Section);
2698 if (!GC.empty()) Fn->setGC(GC.c_str());
2700 // Add all of the arguments we parsed to the function.
2701 Function::arg_iterator ArgIt = Fn->arg_begin();
2702 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2703 // If the argument has a name, insert it into the argument symbol table.
2704 if (ArgList[i].Name.empty()) continue;
2706 // Set the name, if it conflicted, it will be auto-renamed.
2707 ArgIt->setName(ArgList[i].Name);
2709 if (ArgIt->getNameStr() != ArgList[i].Name)
2710 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2711 ArgList[i].Name + "'");
2718 /// ParseFunctionBody
2719 /// ::= '{' BasicBlock+ '}'
2720 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2722 bool LLParser::ParseFunctionBody(Function &Fn) {
2723 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2724 return TokError("expected '{' in function body");
2725 Lex.Lex(); // eat the {.
2727 int FunctionNumber = -1;
2728 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2730 PerFunctionState PFS(*this, Fn, FunctionNumber);
2732 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2733 if (ParseBasicBlock(PFS)) return true;
2738 // Verify function is ok.
2739 return PFS.FinishFunction();
2743 /// ::= LabelStr? Instruction*
2744 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2745 // If this basic block starts out with a name, remember it.
2747 LocTy NameLoc = Lex.getLoc();
2748 if (Lex.getKind() == lltok::LabelStr) {
2749 Name = Lex.getStrVal();
2753 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2754 if (BB == 0) return true;
2756 std::string NameStr;
2758 // Parse the instructions in this block until we get a terminator.
2761 // This instruction may have three possibilities for a name: a) none
2762 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2763 LocTy NameLoc = Lex.getLoc();
2767 if (Lex.getKind() == lltok::LocalVarID) {
2768 NameID = Lex.getUIntVal();
2770 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2772 } else if (Lex.getKind() == lltok::LocalVar ||
2773 // FIXME: REMOVE IN LLVM 3.0
2774 Lex.getKind() == lltok::StringConstant) {
2775 NameStr = Lex.getStrVal();
2777 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2781 if (ParseInstruction(Inst, BB, PFS)) return true;
2782 if (EatIfPresent(lltok::comma))
2783 ParseOptionalCustomMetadata();
2785 // Set metadata attached with this instruction.
2786 MetadataContext &TheMetadata = M->getContext().getMetadata();
2787 for (SmallVector<std::pair<unsigned, MDNode *>, 2>::iterator
2788 MDI = MDsOnInst.begin(), MDE = MDsOnInst.end(); MDI != MDE; ++MDI)
2789 TheMetadata.addMD(MDI->first, MDI->second, Inst);
2792 BB->getInstList().push_back(Inst);
2794 // Set the name on the instruction.
2795 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2796 } while (!isa<TerminatorInst>(Inst));
2801 //===----------------------------------------------------------------------===//
2802 // Instruction Parsing.
2803 //===----------------------------------------------------------------------===//
2805 /// ParseInstruction - Parse one of the many different instructions.
2807 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2808 PerFunctionState &PFS) {
2809 lltok::Kind Token = Lex.getKind();
2810 if (Token == lltok::Eof)
2811 return TokError("found end of file when expecting more instructions");
2812 LocTy Loc = Lex.getLoc();
2813 unsigned KeywordVal = Lex.getUIntVal();
2814 Lex.Lex(); // Eat the keyword.
2817 default: return Error(Loc, "expected instruction opcode");
2818 // Terminator Instructions.
2819 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2820 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2821 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2822 case lltok::kw_br: return ParseBr(Inst, PFS);
2823 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2824 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2825 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2826 // Binary Operators.
2829 case lltok::kw_mul: {
2832 LocTy ModifierLoc = Lex.getLoc();
2833 if (EatIfPresent(lltok::kw_nuw))
2835 if (EatIfPresent(lltok::kw_nsw)) {
2837 if (EatIfPresent(lltok::kw_nuw))
2840 // API compatibility: Accept either integer or floating-point types.
2841 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
2843 if (!Inst->getType()->isIntOrIntVector()) {
2845 return Error(ModifierLoc, "nuw only applies to integer operations");
2847 return Error(ModifierLoc, "nsw only applies to integer operations");
2850 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2852 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2856 case lltok::kw_fadd:
2857 case lltok::kw_fsub:
2858 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2860 case lltok::kw_sdiv: {
2862 if (EatIfPresent(lltok::kw_exact))
2864 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
2867 cast<BinaryOperator>(Inst)->setIsExact(true);
2871 case lltok::kw_udiv:
2872 case lltok::kw_urem:
2873 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2874 case lltok::kw_fdiv:
2875 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2877 case lltok::kw_lshr:
2878 case lltok::kw_ashr:
2881 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2882 case lltok::kw_icmp:
2883 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2885 case lltok::kw_trunc:
2886 case lltok::kw_zext:
2887 case lltok::kw_sext:
2888 case lltok::kw_fptrunc:
2889 case lltok::kw_fpext:
2890 case lltok::kw_bitcast:
2891 case lltok::kw_uitofp:
2892 case lltok::kw_sitofp:
2893 case lltok::kw_fptoui:
2894 case lltok::kw_fptosi:
2895 case lltok::kw_inttoptr:
2896 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2898 case lltok::kw_select: return ParseSelect(Inst, PFS);
2899 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2900 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2901 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2902 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2903 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2904 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2905 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2907 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2908 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
2909 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
2910 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2911 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2912 case lltok::kw_volatile:
2913 if (EatIfPresent(lltok::kw_load))
2914 return ParseLoad(Inst, PFS, true);
2915 else if (EatIfPresent(lltok::kw_store))
2916 return ParseStore(Inst, PFS, true);
2918 return TokError("expected 'load' or 'store'");
2919 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2920 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2921 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2922 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2926 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2927 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2928 if (Opc == Instruction::FCmp) {
2929 switch (Lex.getKind()) {
2930 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2931 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2932 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2933 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2934 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2935 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2936 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2937 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2938 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2939 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2940 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2941 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2942 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2943 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2944 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2945 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2946 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2949 switch (Lex.getKind()) {
2950 default: TokError("expected icmp predicate (e.g. 'eq')");
2951 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2952 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2953 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2954 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2955 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2956 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2957 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2958 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2959 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2960 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2967 //===----------------------------------------------------------------------===//
2968 // Terminator Instructions.
2969 //===----------------------------------------------------------------------===//
2971 /// ParseRet - Parse a return instruction.
2972 /// ::= 'ret' void (',' !dbg, !1)
2973 /// ::= 'ret' TypeAndValue (',' !dbg, !1)
2974 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)
2975 /// [[obsolete: LLVM 3.0]]
2976 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2977 PerFunctionState &PFS) {
2978 PATypeHolder Ty(Type::getVoidTy(Context));
2979 if (ParseType(Ty, true /*void allowed*/)) return true;
2981 if (Ty->isVoidTy()) {
2982 Inst = ReturnInst::Create(Context);
2987 if (ParseValue(Ty, RV, PFS)) return true;
2989 if (EatIfPresent(lltok::comma)) {
2990 // Parse optional custom metadata, e.g. !dbg
2991 if (Lex.getKind() == lltok::NamedOrCustomMD) {
2992 if (ParseOptionalCustomMetadata()) return true;
2994 // The normal case is one return value.
2995 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2996 // of 'ret {i32,i32} {i32 1, i32 2}'
2997 SmallVector<Value*, 8> RVs;
3001 // If optional custom metadata, e.g. !dbg is seen then this is the
3003 if (Lex.getKind() == lltok::NamedOrCustomMD)
3005 if (ParseTypeAndValue(RV, PFS)) return true;
3007 } while (EatIfPresent(lltok::comma));
3009 RV = UndefValue::get(PFS.getFunction().getReturnType());
3010 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
3011 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3012 BB->getInstList().push_back(I);
3018 Inst = ReturnInst::Create(Context, RV);
3024 /// ::= 'br' TypeAndValue
3025 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3026 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3029 BasicBlock *Op1, *Op2;
3030 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3032 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3033 Inst = BranchInst::Create(BB);
3037 if (Op0->getType() != Type::getInt1Ty(Context))
3038 return Error(Loc, "branch condition must have 'i1' type");
3040 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3041 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3042 ParseToken(lltok::comma, "expected ',' after true destination") ||
3043 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3046 Inst = BranchInst::Create(Op1, Op2, Op0);
3052 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3054 /// ::= (TypeAndValue ',' TypeAndValue)*
3055 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3056 LocTy CondLoc, BBLoc;
3058 BasicBlock *DefaultBB;
3059 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3060 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3061 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3062 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3065 if (!isa<IntegerType>(Cond->getType()))
3066 return Error(CondLoc, "switch condition must have integer type");
3068 // Parse the jump table pairs.
3069 SmallPtrSet<Value*, 32> SeenCases;
3070 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3071 while (Lex.getKind() != lltok::rsquare) {
3075 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3076 ParseToken(lltok::comma, "expected ',' after case value") ||
3077 ParseTypeAndBasicBlock(DestBB, PFS))
3080 if (!SeenCases.insert(Constant))
3081 return Error(CondLoc, "duplicate case value in switch");
3082 if (!isa<ConstantInt>(Constant))
3083 return Error(CondLoc, "case value is not a constant integer");
3085 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3088 Lex.Lex(); // Eat the ']'.
3090 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3091 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3092 SI->addCase(Table[i].first, Table[i].second);
3099 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3100 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3103 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3104 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3105 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3108 if (!isa<PointerType>(Address->getType()))
3109 return Error(AddrLoc, "indirectbr address must have pointer type");
3111 // Parse the destination list.
3112 SmallVector<BasicBlock*, 16> DestList;
3114 if (Lex.getKind() != lltok::rsquare) {
3116 if (ParseTypeAndBasicBlock(DestBB, PFS))
3118 DestList.push_back(DestBB);
3120 while (EatIfPresent(lltok::comma)) {
3121 if (ParseTypeAndBasicBlock(DestBB, PFS))
3123 DestList.push_back(DestBB);
3127 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3130 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3131 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3132 IBI->addDestination(DestList[i]);
3139 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3140 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3141 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3142 LocTy CallLoc = Lex.getLoc();
3143 unsigned RetAttrs, FnAttrs;
3145 PATypeHolder RetType(Type::getVoidTy(Context));
3148 SmallVector<ParamInfo, 16> ArgList;
3150 BasicBlock *NormalBB, *UnwindBB;
3151 if (ParseOptionalCallingConv(CC) ||
3152 ParseOptionalAttrs(RetAttrs, 1) ||
3153 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3154 ParseValID(CalleeID) ||
3155 ParseParameterList(ArgList, PFS) ||
3156 ParseOptionalAttrs(FnAttrs, 2) ||
3157 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3158 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3159 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3160 ParseTypeAndBasicBlock(UnwindBB, PFS))
3163 // If RetType is a non-function pointer type, then this is the short syntax
3164 // for the call, which means that RetType is just the return type. Infer the
3165 // rest of the function argument types from the arguments that are present.
3166 const PointerType *PFTy = 0;
3167 const FunctionType *Ty = 0;
3168 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3169 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3170 // Pull out the types of all of the arguments...
3171 std::vector<const Type*> ParamTypes;
3172 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3173 ParamTypes.push_back(ArgList[i].V->getType());
3175 if (!FunctionType::isValidReturnType(RetType))
3176 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3178 Ty = FunctionType::get(RetType, ParamTypes, false);
3179 PFTy = PointerType::getUnqual(Ty);
3182 // Look up the callee.
3184 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3186 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3187 // function attributes.
3188 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3189 if (FnAttrs & ObsoleteFuncAttrs) {
3190 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3191 FnAttrs &= ~ObsoleteFuncAttrs;
3194 // Set up the Attributes for the function.
3195 SmallVector<AttributeWithIndex, 8> Attrs;
3196 if (RetAttrs != Attribute::None)
3197 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3199 SmallVector<Value*, 8> Args;
3201 // Loop through FunctionType's arguments and ensure they are specified
3202 // correctly. Also, gather any parameter attributes.
3203 FunctionType::param_iterator I = Ty->param_begin();
3204 FunctionType::param_iterator E = Ty->param_end();
3205 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3206 const Type *ExpectedTy = 0;
3209 } else if (!Ty->isVarArg()) {
3210 return Error(ArgList[i].Loc, "too many arguments specified");
3213 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3214 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3215 ExpectedTy->getDescription() + "'");
3216 Args.push_back(ArgList[i].V);
3217 if (ArgList[i].Attrs != Attribute::None)
3218 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3222 return Error(CallLoc, "not enough parameters specified for call");
3224 if (FnAttrs != Attribute::None)
3225 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3227 // Finish off the Attributes and check them
3228 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3230 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3231 Args.begin(), Args.end());
3232 II->setCallingConv(CC);
3233 II->setAttributes(PAL);
3240 //===----------------------------------------------------------------------===//
3241 // Binary Operators.
3242 //===----------------------------------------------------------------------===//
3245 /// ::= ArithmeticOps TypeAndValue ',' Value
3247 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3248 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3249 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3250 unsigned Opc, unsigned OperandType) {
3251 LocTy Loc; Value *LHS, *RHS;
3252 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3253 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3254 ParseValue(LHS->getType(), RHS, PFS))
3258 switch (OperandType) {
3259 default: llvm_unreachable("Unknown operand type!");
3260 case 0: // int or FP.
3261 Valid = LHS->getType()->isIntOrIntVector() ||
3262 LHS->getType()->isFPOrFPVector();
3264 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
3265 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
3269 return Error(Loc, "invalid operand type for instruction");
3271 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3276 /// ::= ArithmeticOps TypeAndValue ',' Value {
3277 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3279 LocTy Loc; Value *LHS, *RHS;
3280 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3281 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3282 ParseValue(LHS->getType(), RHS, PFS))
3285 if (!LHS->getType()->isIntOrIntVector())
3286 return Error(Loc,"instruction requires integer or integer vector operands");
3288 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3294 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3295 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3296 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3298 // Parse the integer/fp comparison predicate.
3302 if (ParseCmpPredicate(Pred, Opc) ||
3303 ParseTypeAndValue(LHS, Loc, PFS) ||
3304 ParseToken(lltok::comma, "expected ',' after compare value") ||
3305 ParseValue(LHS->getType(), RHS, PFS))
3308 if (Opc == Instruction::FCmp) {
3309 if (!LHS->getType()->isFPOrFPVector())
3310 return Error(Loc, "fcmp requires floating point operands");
3311 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3313 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3314 if (!LHS->getType()->isIntOrIntVector() &&
3315 !isa<PointerType>(LHS->getType()))
3316 return Error(Loc, "icmp requires integer operands");
3317 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3322 //===----------------------------------------------------------------------===//
3323 // Other Instructions.
3324 //===----------------------------------------------------------------------===//
3328 /// ::= CastOpc TypeAndValue 'to' Type
3329 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3331 LocTy Loc; Value *Op;
3332 PATypeHolder DestTy(Type::getVoidTy(Context));
3333 if (ParseTypeAndValue(Op, Loc, PFS) ||
3334 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3338 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3339 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3340 return Error(Loc, "invalid cast opcode for cast from '" +
3341 Op->getType()->getDescription() + "' to '" +
3342 DestTy->getDescription() + "'");
3344 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3349 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3350 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3352 Value *Op0, *Op1, *Op2;
3353 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3354 ParseToken(lltok::comma, "expected ',' after select condition") ||
3355 ParseTypeAndValue(Op1, PFS) ||
3356 ParseToken(lltok::comma, "expected ',' after select value") ||
3357 ParseTypeAndValue(Op2, PFS))
3360 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3361 return Error(Loc, Reason);
3363 Inst = SelectInst::Create(Op0, Op1, Op2);
3368 /// ::= 'va_arg' TypeAndValue ',' Type
3369 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3371 PATypeHolder EltTy(Type::getVoidTy(Context));
3373 if (ParseTypeAndValue(Op, PFS) ||
3374 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3375 ParseType(EltTy, TypeLoc))
3378 if (!EltTy->isFirstClassType())
3379 return Error(TypeLoc, "va_arg requires operand with first class type");
3381 Inst = new VAArgInst(Op, EltTy);
3385 /// ParseExtractElement
3386 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3387 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3390 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3391 ParseToken(lltok::comma, "expected ',' after extract value") ||
3392 ParseTypeAndValue(Op1, PFS))
3395 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3396 return Error(Loc, "invalid extractelement operands");
3398 Inst = ExtractElementInst::Create(Op0, Op1);
3402 /// ParseInsertElement
3403 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3404 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3406 Value *Op0, *Op1, *Op2;
3407 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3408 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3409 ParseTypeAndValue(Op1, PFS) ||
3410 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3411 ParseTypeAndValue(Op2, PFS))
3414 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3415 return Error(Loc, "invalid insertelement operands");
3417 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3421 /// ParseShuffleVector
3422 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3423 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3425 Value *Op0, *Op1, *Op2;
3426 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3427 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3428 ParseTypeAndValue(Op1, PFS) ||
3429 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3430 ParseTypeAndValue(Op2, PFS))
3433 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3434 return Error(Loc, "invalid extractelement operands");
3436 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3441 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3442 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3443 PATypeHolder Ty(Type::getVoidTy(Context));
3445 LocTy TypeLoc = Lex.getLoc();
3447 if (ParseType(Ty) ||
3448 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3449 ParseValue(Ty, Op0, PFS) ||
3450 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3451 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3452 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3455 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3457 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3459 if (!EatIfPresent(lltok::comma))
3462 if (Lex.getKind() == lltok::NamedOrCustomMD)
3465 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3466 ParseValue(Ty, Op0, PFS) ||
3467 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3468 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3469 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3473 if (Lex.getKind() == lltok::NamedOrCustomMD)
3474 if (ParseOptionalCustomMetadata()) return true;
3476 if (!Ty->isFirstClassType())
3477 return Error(TypeLoc, "phi node must have first class type");
3479 PHINode *PN = PHINode::Create(Ty);
3480 PN->reserveOperandSpace(PHIVals.size());
3481 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3482 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3488 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3489 /// ParameterList OptionalAttrs
3490 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3492 unsigned RetAttrs, FnAttrs;
3494 PATypeHolder RetType(Type::getVoidTy(Context));
3497 SmallVector<ParamInfo, 16> ArgList;
3498 LocTy CallLoc = Lex.getLoc();
3500 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3501 ParseOptionalCallingConv(CC) ||
3502 ParseOptionalAttrs(RetAttrs, 1) ||
3503 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3504 ParseValID(CalleeID) ||
3505 ParseParameterList(ArgList, PFS) ||
3506 ParseOptionalAttrs(FnAttrs, 2))
3509 // If RetType is a non-function pointer type, then this is the short syntax
3510 // for the call, which means that RetType is just the return type. Infer the
3511 // rest of the function argument types from the arguments that are present.
3512 const PointerType *PFTy = 0;
3513 const FunctionType *Ty = 0;
3514 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3515 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3516 // Pull out the types of all of the arguments...
3517 std::vector<const Type*> ParamTypes;
3518 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3519 ParamTypes.push_back(ArgList[i].V->getType());
3521 if (!FunctionType::isValidReturnType(RetType))
3522 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3524 Ty = FunctionType::get(RetType, ParamTypes, false);
3525 PFTy = PointerType::getUnqual(Ty);
3528 // Look up the callee.
3530 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3532 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3533 // function attributes.
3534 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3535 if (FnAttrs & ObsoleteFuncAttrs) {
3536 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3537 FnAttrs &= ~ObsoleteFuncAttrs;
3540 // Set up the Attributes for the function.
3541 SmallVector<AttributeWithIndex, 8> Attrs;
3542 if (RetAttrs != Attribute::None)
3543 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3545 SmallVector<Value*, 8> Args;
3547 // Loop through FunctionType's arguments and ensure they are specified
3548 // correctly. Also, gather any parameter attributes.
3549 FunctionType::param_iterator I = Ty->param_begin();
3550 FunctionType::param_iterator E = Ty->param_end();
3551 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3552 const Type *ExpectedTy = 0;
3555 } else if (!Ty->isVarArg()) {
3556 return Error(ArgList[i].Loc, "too many arguments specified");
3559 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3560 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3561 ExpectedTy->getDescription() + "'");
3562 Args.push_back(ArgList[i].V);
3563 if (ArgList[i].Attrs != Attribute::None)
3564 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3568 return Error(CallLoc, "not enough parameters specified for call");
3570 if (FnAttrs != Attribute::None)
3571 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3573 // Finish off the Attributes and check them
3574 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3576 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3577 CI->setTailCall(isTail);
3578 CI->setCallingConv(CC);
3579 CI->setAttributes(PAL);
3584 //===----------------------------------------------------------------------===//
3585 // Memory Instructions.
3586 //===----------------------------------------------------------------------===//
3589 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3590 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3591 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3592 BasicBlock* BB, bool isAlloca) {
3593 PATypeHolder Ty(Type::getVoidTy(Context));
3596 unsigned Alignment = 0;
3597 if (ParseType(Ty)) return true;
3599 if (EatIfPresent(lltok::comma)) {
3600 if (Lex.getKind() == lltok::kw_align
3601 || Lex.getKind() == lltok::NamedOrCustomMD) {
3602 if (ParseOptionalInfo(Alignment)) return true;
3604 if (ParseTypeAndValue(Size, SizeLoc, PFS)) return true;
3605 if (EatIfPresent(lltok::comma))
3606 if (ParseOptionalInfo(Alignment)) return true;
3610 if (Size && Size->getType() != Type::getInt32Ty(Context))
3611 return Error(SizeLoc, "element count must be i32");
3614 Inst = new AllocaInst(Ty, Size, Alignment);
3618 // Autoupgrade old malloc instruction to malloc call.
3619 // FIXME: Remove in LLVM 3.0.
3620 const Type *IntPtrTy = Type::getInt32Ty(Context);
3622 // Prototype malloc as "void *(int32)".
3623 // This function is renamed as "malloc" in ValidateEndOfModule().
3624 MallocF = cast<Function>(
3625 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
3626 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, Size, MallocF);
3631 /// ::= 'free' TypeAndValue
3632 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3634 Value *Val; LocTy Loc;
3635 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3636 if (!isa<PointerType>(Val->getType()))
3637 return Error(Loc, "operand to free must be a pointer");
3638 Inst = CallInst::CreateFree(Val, BB);
3643 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3644 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3646 Value *Val; LocTy Loc;
3647 unsigned Alignment = 0;
3648 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3650 if (EatIfPresent(lltok::comma))
3651 if (ParseOptionalInfo(Alignment)) return true;
3653 if (!isa<PointerType>(Val->getType()) ||
3654 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3655 return Error(Loc, "load operand must be a pointer to a first class type");
3657 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3662 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3663 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3665 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3666 unsigned Alignment = 0;
3667 if (ParseTypeAndValue(Val, Loc, PFS) ||
3668 ParseToken(lltok::comma, "expected ',' after store operand") ||
3669 ParseTypeAndValue(Ptr, PtrLoc, PFS))
3672 if (EatIfPresent(lltok::comma))
3673 if (ParseOptionalInfo(Alignment)) return true;
3675 if (!isa<PointerType>(Ptr->getType()))
3676 return Error(PtrLoc, "store operand must be a pointer");
3677 if (!Val->getType()->isFirstClassType())
3678 return Error(Loc, "store operand must be a first class value");
3679 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3680 return Error(Loc, "stored value and pointer type do not match");
3682 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3687 /// ::= 'getresult' TypeAndValue ',' i32
3688 /// FIXME: Remove support for getresult in LLVM 3.0
3689 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3690 Value *Val; LocTy ValLoc, EltLoc;
3692 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3693 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3694 ParseUInt32(Element, EltLoc))
3697 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3698 return Error(ValLoc, "getresult inst requires an aggregate operand");
3699 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3700 return Error(EltLoc, "invalid getresult index for value");
3701 Inst = ExtractValueInst::Create(Val, Element);
3705 /// ParseGetElementPtr
3706 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3707 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3708 Value *Ptr, *Val; LocTy Loc, EltLoc;
3710 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3712 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3714 if (!isa<PointerType>(Ptr->getType()))
3715 return Error(Loc, "base of getelementptr must be a pointer");
3717 SmallVector<Value*, 16> Indices;
3718 while (EatIfPresent(lltok::comma)) {
3719 if (Lex.getKind() == lltok::NamedOrCustomMD)
3721 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3722 if (!isa<IntegerType>(Val->getType()))
3723 return Error(EltLoc, "getelementptr index must be an integer");
3724 Indices.push_back(Val);
3726 if (Lex.getKind() == lltok::NamedOrCustomMD)
3727 if (ParseOptionalCustomMetadata()) return true;
3729 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3730 Indices.begin(), Indices.end()))
3731 return Error(Loc, "invalid getelementptr indices");
3732 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3734 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3738 /// ParseExtractValue
3739 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3740 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3741 Value *Val; LocTy Loc;
3742 SmallVector<unsigned, 4> Indices;
3743 if (ParseTypeAndValue(Val, Loc, PFS) ||
3744 ParseIndexList(Indices))
3747 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3748 return Error(Loc, "extractvalue operand must be array or struct");
3750 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3752 return Error(Loc, "invalid indices for extractvalue");
3753 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3757 /// ParseInsertValue
3758 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3759 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3760 Value *Val0, *Val1; LocTy Loc0, Loc1;
3761 SmallVector<unsigned, 4> Indices;
3762 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3763 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3764 ParseTypeAndValue(Val1, Loc1, PFS) ||
3765 ParseIndexList(Indices))
3768 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3769 return Error(Loc0, "extractvalue operand must be array or struct");
3771 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3773 return Error(Loc0, "invalid indices for insertvalue");
3774 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3778 //===----------------------------------------------------------------------===//
3779 // Embedded metadata.
3780 //===----------------------------------------------------------------------===//
3782 /// ParseMDNodeVector
3783 /// ::= Element (',' Element)*
3785 /// ::= 'null' | TypeAndValue
3786 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts) {
3787 assert(Lex.getKind() == lltok::lbrace);
3791 if (Lex.getKind() == lltok::kw_null) {
3795 PATypeHolder Ty(Type::getVoidTy(Context));
3796 if (ParseType(Ty)) return true;
3797 if (Lex.getKind() == lltok::Metadata) {
3799 MetadataBase *Node = 0;
3800 if (!ParseMDNode(Node))
3803 MetadataBase *MDS = 0;
3804 if (ParseMDString(MDS)) return true;
3809 if (ParseGlobalValue(Ty, C)) return true;
3814 } while (EatIfPresent(lltok::comma));