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/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 /// Run: module ::= toplevelentity*
30 bool LLParser::Run() {
34 return ParseTopLevelEntities() ||
35 ValidateEndOfModule();
38 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
40 bool LLParser::ValidateEndOfModule() {
41 // Handle any instruction metadata forward references.
42 if (!ForwardRefInstMetadata.empty()) {
43 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
44 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
46 Instruction *Inst = I->first;
47 const std::vector<MDRef> &MDList = I->second;
49 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
50 unsigned SlotNo = MDList[i].MDSlot;
52 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
53 return Error(MDList[i].Loc, "use of undefined metadata '!" +
55 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
58 ForwardRefInstMetadata.clear();
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 Twine(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 Twine(ForwardRefValIDs.begin()->first) + "'");
105 if (!ForwardRefMDNodes.empty())
106 return Error(ForwardRefMDNodes.begin()->second.second,
107 "use of undefined metadata '!" +
108 Twine(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) {
127 if (Refs[i].first.Kind == ValID::t_LocalName)
128 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
130 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
131 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
132 return Error(Refs[i].first.Loc,
133 "cannot take address of numeric label after the function is defined");
135 Res = dyn_cast_or_null<BasicBlock>(
136 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
140 return Error(Refs[i].first.Loc,
141 "referenced value is not a basic block");
143 // Get the BlockAddress for this and update references to use it.
144 BlockAddress *BA = BlockAddress::get(TheFn, Res);
145 Refs[i].second->replaceAllUsesWith(BA);
146 Refs[i].second->eraseFromParent();
152 //===----------------------------------------------------------------------===//
153 // Top-Level Entities
154 //===----------------------------------------------------------------------===//
156 bool LLParser::ParseTopLevelEntities() {
158 switch (Lex.getKind()) {
159 default: return TokError("expected top-level entity");
160 case lltok::Eof: return false;
161 case lltok::kw_declare: if (ParseDeclare()) return true; break;
162 case lltok::kw_define: if (ParseDefine()) return true; break;
163 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
164 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
165 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
166 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
167 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
168 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
169 case lltok::LocalVar: if (ParseNamedType()) return true; break;
170 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
171 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
172 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
173 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
175 // The Global variable production with no name can have many different
176 // optional leading prefixes, the production is:
177 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
178 // OptionalAddrSpace OptionalUnNammedAddr
179 // ('constant'|'global') ...
180 case lltok::kw_private: // OptionalLinkage
181 case lltok::kw_linker_private: // OptionalLinkage
182 case lltok::kw_linker_private_weak: // OptionalLinkage
183 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
184 case lltok::kw_internal: // OptionalLinkage
185 case lltok::kw_weak: // OptionalLinkage
186 case lltok::kw_weak_odr: // OptionalLinkage
187 case lltok::kw_linkonce: // OptionalLinkage
188 case lltok::kw_linkonce_odr: // OptionalLinkage
189 case lltok::kw_appending: // OptionalLinkage
190 case lltok::kw_dllexport: // OptionalLinkage
191 case lltok::kw_common: // OptionalLinkage
192 case lltok::kw_dllimport: // OptionalLinkage
193 case lltok::kw_extern_weak: // OptionalLinkage
194 case lltok::kw_external: { // OptionalLinkage
195 unsigned Linkage, Visibility;
196 if (ParseOptionalLinkage(Linkage) ||
197 ParseOptionalVisibility(Visibility) ||
198 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
202 case lltok::kw_default: // OptionalVisibility
203 case lltok::kw_hidden: // OptionalVisibility
204 case lltok::kw_protected: { // OptionalVisibility
206 if (ParseOptionalVisibility(Visibility) ||
207 ParseGlobal("", SMLoc(), 0, false, Visibility))
212 case lltok::kw_thread_local: // OptionalThreadLocal
213 case lltok::kw_addrspace: // OptionalAddrSpace
214 case lltok::kw_constant: // GlobalType
215 case lltok::kw_global: // GlobalType
216 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
224 /// ::= 'module' 'asm' STRINGCONSTANT
225 bool LLParser::ParseModuleAsm() {
226 assert(Lex.getKind() == lltok::kw_module);
230 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
231 ParseStringConstant(AsmStr)) return true;
233 M->appendModuleInlineAsm(AsmStr);
238 /// ::= 'target' 'triple' '=' STRINGCONSTANT
239 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
240 bool LLParser::ParseTargetDefinition() {
241 assert(Lex.getKind() == lltok::kw_target);
244 default: return TokError("unknown target property");
245 case lltok::kw_triple:
247 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
248 ParseStringConstant(Str))
250 M->setTargetTriple(Str);
252 case lltok::kw_datalayout:
254 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
255 ParseStringConstant(Str))
257 M->setDataLayout(Str);
263 /// ::= 'deplibs' '=' '[' ']'
264 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
265 bool LLParser::ParseDepLibs() {
266 assert(Lex.getKind() == lltok::kw_deplibs);
268 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
269 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
272 if (EatIfPresent(lltok::rsquare))
276 if (ParseStringConstant(Str)) return true;
279 while (EatIfPresent(lltok::comma)) {
280 if (ParseStringConstant(Str)) return true;
284 return ParseToken(lltok::rsquare, "expected ']' at end of list");
287 /// ParseUnnamedType:
289 /// ::= LocalVarID '=' 'type' type
290 bool LLParser::ParseUnnamedType() {
291 unsigned TypeID = NumberedTypes.size();
293 // Handle the LocalVarID form.
294 if (Lex.getKind() == lltok::LocalVarID) {
295 if (Lex.getUIntVal() != TypeID)
296 return Error(Lex.getLoc(), "type expected to be numbered '%" +
297 Twine(TypeID) + "'");
298 Lex.Lex(); // eat LocalVarID;
300 if (ParseToken(lltok::equal, "expected '=' after name"))
304 LocTy TypeLoc = Lex.getLoc();
305 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
307 PATypeHolder Ty(Type::getVoidTy(Context));
308 if (ParseType(Ty)) return true;
310 // See if this type was previously referenced.
311 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
312 FI = ForwardRefTypeIDs.find(TypeID);
313 if (FI != ForwardRefTypeIDs.end()) {
314 if (FI->second.first.get() == Ty)
315 return Error(TypeLoc, "self referential type is invalid");
317 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
318 Ty = FI->second.first.get();
319 ForwardRefTypeIDs.erase(FI);
322 NumberedTypes.push_back(Ty);
328 /// ::= LocalVar '=' 'type' type
329 bool LLParser::ParseNamedType() {
330 std::string Name = Lex.getStrVal();
331 LocTy NameLoc = Lex.getLoc();
332 Lex.Lex(); // eat LocalVar.
334 PATypeHolder Ty(Type::getVoidTy(Context));
336 if (ParseToken(lltok::equal, "expected '=' after name") ||
337 ParseToken(lltok::kw_type, "expected 'type' after name") ||
341 // Set the type name, checking for conflicts as we do so.
342 bool AlreadyExists = M->addTypeName(Name, Ty);
343 if (!AlreadyExists) return false;
345 // See if this type is a forward reference. We need to eagerly resolve
346 // types to allow recursive type redefinitions below.
347 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
348 FI = ForwardRefTypes.find(Name);
349 if (FI != ForwardRefTypes.end()) {
350 if (FI->second.first.get() == Ty)
351 return Error(NameLoc, "self referential type is invalid");
353 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
354 Ty = FI->second.first.get();
355 ForwardRefTypes.erase(FI);
358 // Inserting a name that is already defined, get the existing name.
359 const Type *Existing = M->getTypeByName(Name);
360 assert(Existing && "Conflict but no matching type?!");
362 // Otherwise, this is an attempt to redefine a type. That's okay if
363 // the redefinition is identical to the original.
364 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
365 if (Existing == Ty) return false;
367 // Any other kind of (non-equivalent) redefinition is an error.
368 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
369 Ty->getDescription() + "'");
374 /// ::= 'declare' FunctionHeader
375 bool LLParser::ParseDeclare() {
376 assert(Lex.getKind() == lltok::kw_declare);
380 return ParseFunctionHeader(F, false);
384 /// ::= 'define' FunctionHeader '{' ...
385 bool LLParser::ParseDefine() {
386 assert(Lex.getKind() == lltok::kw_define);
390 return ParseFunctionHeader(F, true) ||
391 ParseFunctionBody(*F);
397 bool LLParser::ParseGlobalType(bool &IsConstant) {
398 if (Lex.getKind() == lltok::kw_constant)
400 else if (Lex.getKind() == lltok::kw_global)
404 return TokError("expected 'global' or 'constant'");
410 /// ParseUnnamedGlobal:
411 /// OptionalVisibility ALIAS ...
412 /// OptionalLinkage OptionalVisibility ... -> global variable
413 /// GlobalID '=' OptionalVisibility ALIAS ...
414 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
415 bool LLParser::ParseUnnamedGlobal() {
416 unsigned VarID = NumberedVals.size();
418 LocTy NameLoc = Lex.getLoc();
420 // Handle the GlobalID form.
421 if (Lex.getKind() == lltok::GlobalID) {
422 if (Lex.getUIntVal() != VarID)
423 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
425 Lex.Lex(); // eat GlobalID;
427 if (ParseToken(lltok::equal, "expected '=' after name"))
432 unsigned Linkage, Visibility;
433 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
434 ParseOptionalVisibility(Visibility))
437 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
438 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
439 return ParseAlias(Name, NameLoc, Visibility);
442 /// ParseNamedGlobal:
443 /// GlobalVar '=' OptionalVisibility ALIAS ...
444 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
445 bool LLParser::ParseNamedGlobal() {
446 assert(Lex.getKind() == lltok::GlobalVar);
447 LocTy NameLoc = Lex.getLoc();
448 std::string Name = Lex.getStrVal();
452 unsigned Linkage, Visibility;
453 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
454 ParseOptionalLinkage(Linkage, HasLinkage) ||
455 ParseOptionalVisibility(Visibility))
458 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
459 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
460 return ParseAlias(Name, NameLoc, Visibility);
464 // ::= '!' STRINGCONSTANT
465 bool LLParser::ParseMDString(MDString *&Result) {
467 if (ParseStringConstant(Str)) return true;
468 Result = MDString::get(Context, Str);
473 // ::= '!' MDNodeNumber
475 /// This version of ParseMDNodeID returns the slot number and null in the case
476 /// of a forward reference.
477 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
478 // !{ ..., !42, ... }
479 if (ParseUInt32(SlotNo)) return true;
481 // Check existing MDNode.
482 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
483 Result = NumberedMetadata[SlotNo];
489 bool LLParser::ParseMDNodeID(MDNode *&Result) {
490 // !{ ..., !42, ... }
492 if (ParseMDNodeID(Result, MID)) return true;
494 // If not a forward reference, just return it now.
495 if (Result) return false;
497 // Otherwise, create MDNode forward reference.
498 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
499 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
501 if (NumberedMetadata.size() <= MID)
502 NumberedMetadata.resize(MID+1);
503 NumberedMetadata[MID] = FwdNode;
508 /// ParseNamedMetadata:
509 /// !foo = !{ !1, !2 }
510 bool LLParser::ParseNamedMetadata() {
511 assert(Lex.getKind() == lltok::MetadataVar);
512 std::string Name = Lex.getStrVal();
515 if (ParseToken(lltok::equal, "expected '=' here") ||
516 ParseToken(lltok::exclaim, "Expected '!' here") ||
517 ParseToken(lltok::lbrace, "Expected '{' here"))
520 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
521 if (Lex.getKind() != lltok::rbrace)
523 if (ParseToken(lltok::exclaim, "Expected '!' here"))
527 if (ParseMDNodeID(N)) return true;
529 } while (EatIfPresent(lltok::comma));
531 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
537 /// ParseStandaloneMetadata:
539 bool LLParser::ParseStandaloneMetadata() {
540 assert(Lex.getKind() == lltok::exclaim);
542 unsigned MetadataID = 0;
545 PATypeHolder Ty(Type::getVoidTy(Context));
546 SmallVector<Value *, 16> Elts;
547 if (ParseUInt32(MetadataID) ||
548 ParseToken(lltok::equal, "expected '=' here") ||
549 ParseType(Ty, TyLoc) ||
550 ParseToken(lltok::exclaim, "Expected '!' here") ||
551 ParseToken(lltok::lbrace, "Expected '{' here") ||
552 ParseMDNodeVector(Elts, NULL) ||
553 ParseToken(lltok::rbrace, "expected end of metadata node"))
556 MDNode *Init = MDNode::get(Context, Elts);
558 // See if this was forward referenced, if so, handle it.
559 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
560 FI = ForwardRefMDNodes.find(MetadataID);
561 if (FI != ForwardRefMDNodes.end()) {
562 MDNode *Temp = FI->second.first;
563 Temp->replaceAllUsesWith(Init);
564 MDNode::deleteTemporary(Temp);
565 ForwardRefMDNodes.erase(FI);
567 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
569 if (MetadataID >= NumberedMetadata.size())
570 NumberedMetadata.resize(MetadataID+1);
572 if (NumberedMetadata[MetadataID] != 0)
573 return TokError("Metadata id is already used");
574 NumberedMetadata[MetadataID] = Init;
581 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
584 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
585 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
587 /// Everything through visibility has already been parsed.
589 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
590 unsigned Visibility) {
591 assert(Lex.getKind() == lltok::kw_alias);
594 LocTy LinkageLoc = Lex.getLoc();
595 if (ParseOptionalLinkage(Linkage))
598 if (Linkage != GlobalValue::ExternalLinkage &&
599 Linkage != GlobalValue::WeakAnyLinkage &&
600 Linkage != GlobalValue::WeakODRLinkage &&
601 Linkage != GlobalValue::InternalLinkage &&
602 Linkage != GlobalValue::PrivateLinkage &&
603 Linkage != GlobalValue::LinkerPrivateLinkage &&
604 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
605 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
606 return Error(LinkageLoc, "invalid linkage type for alias");
609 LocTy AliaseeLoc = Lex.getLoc();
610 if (Lex.getKind() != lltok::kw_bitcast &&
611 Lex.getKind() != lltok::kw_getelementptr) {
612 if (ParseGlobalTypeAndValue(Aliasee)) return true;
614 // The bitcast dest type is not present, it is implied by the dest type.
616 if (ParseValID(ID)) return true;
617 if (ID.Kind != ValID::t_Constant)
618 return Error(AliaseeLoc, "invalid aliasee");
619 Aliasee = ID.ConstantVal;
622 if (!Aliasee->getType()->isPointerTy())
623 return Error(AliaseeLoc, "alias must have pointer type");
625 // Okay, create the alias but do not insert it into the module yet.
626 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
627 (GlobalValue::LinkageTypes)Linkage, Name,
629 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
631 // See if this value already exists in the symbol table. If so, it is either
632 // a redefinition or a definition of a forward reference.
633 if (GlobalValue *Val = M->getNamedValue(Name)) {
634 // See if this was a redefinition. If so, there is no entry in
636 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
637 I = ForwardRefVals.find(Name);
638 if (I == ForwardRefVals.end())
639 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
641 // Otherwise, this was a definition of forward ref. Verify that types
643 if (Val->getType() != GA->getType())
644 return Error(NameLoc,
645 "forward reference and definition of alias have different types");
647 // If they agree, just RAUW the old value with the alias and remove the
649 Val->replaceAllUsesWith(GA);
650 Val->eraseFromParent();
651 ForwardRefVals.erase(I);
654 // Insert into the module, we know its name won't collide now.
655 M->getAliasList().push_back(GA);
656 assert(GA->getName() == Name && "Should not be a name conflict!");
662 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
663 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
664 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
665 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
667 /// Everything through visibility has been parsed already.
669 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
670 unsigned Linkage, bool HasLinkage,
671 unsigned Visibility) {
673 bool ThreadLocal, IsConstant, UnnamedAddr;
674 LocTy UnnamedAddrLoc;
677 PATypeHolder Ty(Type::getVoidTy(Context));
678 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
679 ParseOptionalAddrSpace(AddrSpace) ||
680 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
682 ParseGlobalType(IsConstant) ||
683 ParseType(Ty, TyLoc))
686 // If the linkage is specified and is external, then no initializer is
689 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
690 Linkage != GlobalValue::ExternalWeakLinkage &&
691 Linkage != GlobalValue::ExternalLinkage)) {
692 if (ParseGlobalValue(Ty, Init))
696 if (Ty->isFunctionTy() || Ty->isLabelTy())
697 return Error(TyLoc, "invalid type for global variable");
699 GlobalVariable *GV = 0;
701 // See if the global was forward referenced, if so, use the global.
703 if (GlobalValue *GVal = M->getNamedValue(Name)) {
704 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
705 return Error(NameLoc, "redefinition of global '@" + Name + "'");
706 GV = cast<GlobalVariable>(GVal);
709 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
710 I = ForwardRefValIDs.find(NumberedVals.size());
711 if (I != ForwardRefValIDs.end()) {
712 GV = cast<GlobalVariable>(I->second.first);
713 ForwardRefValIDs.erase(I);
718 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
719 Name, 0, false, AddrSpace);
721 if (GV->getType()->getElementType() != Ty)
723 "forward reference and definition of global have different types");
725 // Move the forward-reference to the correct spot in the module.
726 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
730 NumberedVals.push_back(GV);
732 // Set the parsed properties on the global.
734 GV->setInitializer(Init);
735 GV->setConstant(IsConstant);
736 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
737 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
738 GV->setThreadLocal(ThreadLocal);
739 GV->setUnnamedAddr(UnnamedAddr);
741 // Parse attributes on the global.
742 while (Lex.getKind() == lltok::comma) {
745 if (Lex.getKind() == lltok::kw_section) {
747 GV->setSection(Lex.getStrVal());
748 if (ParseToken(lltok::StringConstant, "expected global section string"))
750 } else if (Lex.getKind() == lltok::kw_align) {
752 if (ParseOptionalAlignment(Alignment)) return true;
753 GV->setAlignment(Alignment);
755 TokError("unknown global variable property!");
763 //===----------------------------------------------------------------------===//
764 // GlobalValue Reference/Resolution Routines.
765 //===----------------------------------------------------------------------===//
767 /// GetGlobalVal - Get a value with the specified name or ID, creating a
768 /// forward reference record if needed. This can return null if the value
769 /// exists but does not have the right type.
770 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
772 const PointerType *PTy = dyn_cast<PointerType>(Ty);
774 Error(Loc, "global variable reference must have pointer type");
778 // Look this name up in the normal function symbol table.
780 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
782 // If this is a forward reference for the value, see if we already created a
783 // forward ref record.
785 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
786 I = ForwardRefVals.find(Name);
787 if (I != ForwardRefVals.end())
788 Val = I->second.first;
791 // If we have the value in the symbol table or fwd-ref table, return it.
793 if (Val->getType() == Ty) return Val;
794 Error(Loc, "'@" + Name + "' defined with type '" +
795 Val->getType()->getDescription() + "'");
799 // Otherwise, create a new forward reference for this value and remember it.
801 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
802 // Function types can return opaque but functions can't.
803 if (FT->getReturnType()->isOpaqueTy()) {
804 Error(Loc, "function may not return opaque type");
808 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
810 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
811 GlobalValue::ExternalWeakLinkage, 0, Name);
814 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
818 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
819 const PointerType *PTy = dyn_cast<PointerType>(Ty);
821 Error(Loc, "global variable reference must have pointer type");
825 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
827 // If this is a forward reference for the value, see if we already created a
828 // forward ref record.
830 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
831 I = ForwardRefValIDs.find(ID);
832 if (I != ForwardRefValIDs.end())
833 Val = I->second.first;
836 // If we have the value in the symbol table or fwd-ref table, return it.
838 if (Val->getType() == Ty) return Val;
839 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
840 Val->getType()->getDescription() + "'");
844 // Otherwise, create a new forward reference for this value and remember it.
846 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
847 // Function types can return opaque but functions can't.
848 if (FT->getReturnType()->isOpaqueTy()) {
849 Error(Loc, "function may not return opaque type");
852 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
854 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
855 GlobalValue::ExternalWeakLinkage, 0, "");
858 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
863 //===----------------------------------------------------------------------===//
865 //===----------------------------------------------------------------------===//
867 /// ParseToken - If the current token has the specified kind, eat it and return
868 /// success. Otherwise, emit the specified error and return failure.
869 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
870 if (Lex.getKind() != T)
871 return TokError(ErrMsg);
876 /// ParseStringConstant
877 /// ::= StringConstant
878 bool LLParser::ParseStringConstant(std::string &Result) {
879 if (Lex.getKind() != lltok::StringConstant)
880 return TokError("expected string constant");
881 Result = Lex.getStrVal();
888 bool LLParser::ParseUInt32(unsigned &Val) {
889 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
890 return TokError("expected integer");
891 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
892 if (Val64 != unsigned(Val64))
893 return TokError("expected 32-bit integer (too large)");
900 /// ParseOptionalAddrSpace
902 /// := 'addrspace' '(' uint32 ')'
903 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
905 if (!EatIfPresent(lltok::kw_addrspace))
907 return ParseToken(lltok::lparen, "expected '(' in address space") ||
908 ParseUInt32(AddrSpace) ||
909 ParseToken(lltok::rparen, "expected ')' in address space");
912 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
913 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
914 /// 2: function attr.
915 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
916 Attrs = Attribute::None;
917 LocTy AttrLoc = Lex.getLoc();
920 switch (Lex.getKind()) {
921 default: // End of attributes.
922 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
923 return Error(AttrLoc, "invalid use of function-only attribute");
925 // As a hack, we allow "align 2" on functions as a synonym for
928 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
929 return Error(AttrLoc, "invalid use of attribute on a function");
931 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
932 return Error(AttrLoc, "invalid use of parameter-only attribute");
935 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
936 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
937 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
938 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
939 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
940 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
941 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
942 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
944 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
945 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
946 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
947 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
948 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
949 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
950 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
951 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
952 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
953 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
954 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
955 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
956 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
957 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
958 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
959 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
961 case lltok::kw_alignstack: {
963 if (ParseOptionalStackAlignment(Alignment))
965 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
969 case lltok::kw_align: {
971 if (ParseOptionalAlignment(Alignment))
973 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
982 /// ParseOptionalLinkage
985 /// ::= 'linker_private'
986 /// ::= 'linker_private_weak'
987 /// ::= 'linker_private_weak_def_auto'
992 /// ::= 'linkonce_odr'
993 /// ::= 'available_externally'
998 /// ::= 'extern_weak'
1000 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1002 switch (Lex.getKind()) {
1003 default: Res=GlobalValue::ExternalLinkage; return false;
1004 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1005 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1006 case lltok::kw_linker_private_weak:
1007 Res = GlobalValue::LinkerPrivateWeakLinkage;
1009 case lltok::kw_linker_private_weak_def_auto:
1010 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1012 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1013 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1014 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1015 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1016 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1017 case lltok::kw_available_externally:
1018 Res = GlobalValue::AvailableExternallyLinkage;
1020 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1021 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1022 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1023 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1024 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1025 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1032 /// ParseOptionalVisibility
1038 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1039 switch (Lex.getKind()) {
1040 default: Res = GlobalValue::DefaultVisibility; return false;
1041 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1042 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1043 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1049 /// ParseOptionalCallingConv
1054 /// ::= 'x86_stdcallcc'
1055 /// ::= 'x86_fastcallcc'
1056 /// ::= 'x86_thiscallcc'
1057 /// ::= 'arm_apcscc'
1058 /// ::= 'arm_aapcscc'
1059 /// ::= 'arm_aapcs_vfpcc'
1060 /// ::= 'msp430_intrcc'
1061 /// ::= 'ptx_kernel'
1062 /// ::= 'ptx_device'
1065 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1066 switch (Lex.getKind()) {
1067 default: CC = CallingConv::C; return false;
1068 case lltok::kw_ccc: CC = CallingConv::C; break;
1069 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1070 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1071 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1072 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1073 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1074 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1075 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1076 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1077 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1078 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1079 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1080 case lltok::kw_cc: {
1081 unsigned ArbitraryCC;
1083 if (ParseUInt32(ArbitraryCC)) {
1086 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1096 /// ParseInstructionMetadata
1097 /// ::= !dbg !42 (',' !dbg !57)*
1098 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1099 PerFunctionState *PFS) {
1101 if (Lex.getKind() != lltok::MetadataVar)
1102 return TokError("expected metadata after comma");
1104 std::string Name = Lex.getStrVal();
1105 unsigned MDK = M->getMDKindID(Name.c_str());
1109 SMLoc Loc = Lex.getLoc();
1111 if (ParseToken(lltok::exclaim, "expected '!' here"))
1114 // This code is similar to that of ParseMetadataValue, however it needs to
1115 // have special-case code for a forward reference; see the comments on
1116 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1117 // at the top level here.
1118 if (Lex.getKind() == lltok::lbrace) {
1120 if (ParseMetadataListValue(ID, PFS))
1122 assert(ID.Kind == ValID::t_MDNode);
1123 Inst->setMetadata(MDK, ID.MDNodeVal);
1125 unsigned NodeID = 0;
1126 if (ParseMDNodeID(Node, NodeID))
1129 // If we got the node, add it to the instruction.
1130 Inst->setMetadata(MDK, Node);
1132 MDRef R = { Loc, MDK, NodeID };
1133 // Otherwise, remember that this should be resolved later.
1134 ForwardRefInstMetadata[Inst].push_back(R);
1138 // If this is the end of the list, we're done.
1139 } while (EatIfPresent(lltok::comma));
1143 /// ParseOptionalAlignment
1146 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1148 if (!EatIfPresent(lltok::kw_align))
1150 LocTy AlignLoc = Lex.getLoc();
1151 if (ParseUInt32(Alignment)) return true;
1152 if (!isPowerOf2_32(Alignment))
1153 return Error(AlignLoc, "alignment is not a power of two");
1154 if (Alignment > Value::MaximumAlignment)
1155 return Error(AlignLoc, "huge alignments are not supported yet");
1159 /// ParseOptionalCommaAlign
1163 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1165 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1166 bool &AteExtraComma) {
1167 AteExtraComma = false;
1168 while (EatIfPresent(lltok::comma)) {
1169 // Metadata at the end is an early exit.
1170 if (Lex.getKind() == lltok::MetadataVar) {
1171 AteExtraComma = true;
1175 if (Lex.getKind() != lltok::kw_align)
1176 return Error(Lex.getLoc(), "expected metadata or 'align'");
1178 if (ParseOptionalAlignment(Alignment)) return true;
1184 /// ParseOptionalStackAlignment
1186 /// ::= 'alignstack' '(' 4 ')'
1187 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1189 if (!EatIfPresent(lltok::kw_alignstack))
1191 LocTy ParenLoc = Lex.getLoc();
1192 if (!EatIfPresent(lltok::lparen))
1193 return Error(ParenLoc, "expected '('");
1194 LocTy AlignLoc = Lex.getLoc();
1195 if (ParseUInt32(Alignment)) return true;
1196 ParenLoc = Lex.getLoc();
1197 if (!EatIfPresent(lltok::rparen))
1198 return Error(ParenLoc, "expected ')'");
1199 if (!isPowerOf2_32(Alignment))
1200 return Error(AlignLoc, "stack alignment is not a power of two");
1204 /// ParseIndexList - This parses the index list for an insert/extractvalue
1205 /// instruction. This sets AteExtraComma in the case where we eat an extra
1206 /// comma at the end of the line and find that it is followed by metadata.
1207 /// Clients that don't allow metadata can call the version of this function that
1208 /// only takes one argument.
1211 /// ::= (',' uint32)+
1213 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1214 bool &AteExtraComma) {
1215 AteExtraComma = false;
1217 if (Lex.getKind() != lltok::comma)
1218 return TokError("expected ',' as start of index list");
1220 while (EatIfPresent(lltok::comma)) {
1221 if (Lex.getKind() == lltok::MetadataVar) {
1222 AteExtraComma = true;
1226 if (ParseUInt32(Idx)) return true;
1227 Indices.push_back(Idx);
1233 //===----------------------------------------------------------------------===//
1235 //===----------------------------------------------------------------------===//
1237 /// ParseType - Parse and resolve a full type.
1238 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1239 LocTy TypeLoc = Lex.getLoc();
1240 if (ParseTypeRec(Result)) return true;
1242 // Verify no unresolved uprefs.
1243 if (!UpRefs.empty())
1244 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1246 if (!AllowVoid && Result.get()->isVoidTy())
1247 return Error(TypeLoc, "void type only allowed for function results");
1252 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1253 /// called. It loops through the UpRefs vector, which is a list of the
1254 /// currently active types. For each type, if the up-reference is contained in
1255 /// the newly completed type, we decrement the level count. When the level
1256 /// count reaches zero, the up-referenced type is the type that is passed in:
1257 /// thus we can complete the cycle.
1259 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1260 // If Ty isn't abstract, or if there are no up-references in it, then there is
1261 // nothing to resolve here.
1262 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1264 PATypeHolder Ty(ty);
1266 dbgs() << "Type '" << Ty->getDescription()
1267 << "' newly formed. Resolving upreferences.\n"
1268 << UpRefs.size() << " upreferences active!\n";
1271 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1272 // to zero), we resolve them all together before we resolve them to Ty. At
1273 // the end of the loop, if there is anything to resolve to Ty, it will be in
1275 OpaqueType *TypeToResolve = 0;
1277 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1278 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1280 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1281 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1284 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1285 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1286 << (ContainsType ? "true" : "false")
1287 << " level=" << UpRefs[i].NestingLevel << "\n";
1292 // Decrement level of upreference
1293 unsigned Level = --UpRefs[i].NestingLevel;
1294 UpRefs[i].LastContainedTy = Ty;
1296 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1301 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1304 TypeToResolve = UpRefs[i].UpRefTy;
1306 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1307 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1308 --i; // Do not skip the next element.
1312 TypeToResolve->refineAbstractTypeTo(Ty);
1318 /// ParseTypeRec - The recursive function used to process the internal
1319 /// implementation details of types.
1320 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1321 switch (Lex.getKind()) {
1323 return TokError("expected type");
1325 // TypeRec ::= 'float' | 'void' (etc)
1326 Result = Lex.getTyVal();
1329 case lltok::kw_opaque:
1330 // TypeRec ::= 'opaque'
1331 Result = OpaqueType::get(Context);
1335 // TypeRec ::= '{' ... '}'
1336 if (ParseStructType(Result, false))
1339 case lltok::lsquare:
1340 // TypeRec ::= '[' ... ']'
1341 Lex.Lex(); // eat the lsquare.
1342 if (ParseArrayVectorType(Result, false))
1345 case lltok::less: // Either vector or packed struct.
1346 // TypeRec ::= '<' ... '>'
1348 if (Lex.getKind() == lltok::lbrace) {
1349 if (ParseStructType(Result, true) ||
1350 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1352 } else if (ParseArrayVectorType(Result, true))
1355 case lltok::LocalVar:
1356 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1358 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1361 Result = OpaqueType::get(Context);
1362 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1363 std::make_pair(Result,
1365 M->addTypeName(Lex.getStrVal(), Result.get());
1370 case lltok::LocalVarID:
1372 if (Lex.getUIntVal() < NumberedTypes.size())
1373 Result = NumberedTypes[Lex.getUIntVal()];
1375 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1376 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1377 if (I != ForwardRefTypeIDs.end())
1378 Result = I->second.first;
1380 Result = OpaqueType::get(Context);
1381 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1382 std::make_pair(Result,
1388 case lltok::backslash: {
1389 // TypeRec ::= '\' 4
1392 if (ParseUInt32(Val)) return true;
1393 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1394 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1400 // Parse the type suffixes.
1402 switch (Lex.getKind()) {
1404 default: return false;
1406 // TypeRec ::= TypeRec '*'
1408 if (Result.get()->isLabelTy())
1409 return TokError("basic block pointers are invalid");
1410 if (Result.get()->isVoidTy())
1411 return TokError("pointers to void are invalid; use i8* instead");
1412 if (!PointerType::isValidElementType(Result.get()))
1413 return TokError("pointer to this type is invalid");
1414 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1418 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1419 case lltok::kw_addrspace: {
1420 if (Result.get()->isLabelTy())
1421 return TokError("basic block pointers are invalid");
1422 if (Result.get()->isVoidTy())
1423 return TokError("pointers to void are invalid; use i8* instead");
1424 if (!PointerType::isValidElementType(Result.get()))
1425 return TokError("pointer to this type is invalid");
1427 if (ParseOptionalAddrSpace(AddrSpace) ||
1428 ParseToken(lltok::star, "expected '*' in address space"))
1431 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1435 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1437 if (ParseFunctionType(Result))
1444 /// ParseParameterList
1446 /// ::= '(' Arg (',' Arg)* ')'
1448 /// ::= Type OptionalAttributes Value OptionalAttributes
1449 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1450 PerFunctionState &PFS) {
1451 if (ParseToken(lltok::lparen, "expected '(' in call"))
1454 while (Lex.getKind() != lltok::rparen) {
1455 // If this isn't the first argument, we need a comma.
1456 if (!ArgList.empty() &&
1457 ParseToken(lltok::comma, "expected ',' in argument list"))
1460 // Parse the argument.
1462 PATypeHolder ArgTy(Type::getVoidTy(Context));
1463 unsigned ArgAttrs1 = Attribute::None;
1464 unsigned ArgAttrs2 = Attribute::None;
1466 if (ParseType(ArgTy, ArgLoc))
1469 // Otherwise, handle normal operands.
1470 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
1472 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1475 Lex.Lex(); // Lex the ')'.
1481 /// ParseArgumentList - Parse the argument list for a function type or function
1482 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1483 /// ::= '(' ArgTypeListI ')'
1487 /// ::= ArgTypeList ',' '...'
1488 /// ::= ArgType (',' ArgType)*
1490 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1491 bool &isVarArg, bool inType) {
1493 assert(Lex.getKind() == lltok::lparen);
1494 Lex.Lex(); // eat the (.
1496 if (Lex.getKind() == lltok::rparen) {
1498 } else if (Lex.getKind() == lltok::dotdotdot) {
1502 LocTy TypeLoc = Lex.getLoc();
1503 PATypeHolder ArgTy(Type::getVoidTy(Context));
1507 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1508 // types (such as a function returning a pointer to itself). If parsing a
1509 // function prototype, we require fully resolved types.
1510 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1511 ParseOptionalAttrs(Attrs, 0)) return true;
1513 if (ArgTy->isVoidTy())
1514 return Error(TypeLoc, "argument can not have void type");
1516 if (Lex.getKind() == lltok::LocalVar ||
1517 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1518 Name = Lex.getStrVal();
1522 if (!FunctionType::isValidArgumentType(ArgTy))
1523 return Error(TypeLoc, "invalid type for function argument");
1525 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1527 while (EatIfPresent(lltok::comma)) {
1528 // Handle ... at end of arg list.
1529 if (EatIfPresent(lltok::dotdotdot)) {
1534 // Otherwise must be an argument type.
1535 TypeLoc = Lex.getLoc();
1536 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1537 ParseOptionalAttrs(Attrs, 0)) return true;
1539 if (ArgTy->isVoidTy())
1540 return Error(TypeLoc, "argument can not have void type");
1542 if (Lex.getKind() == lltok::LocalVar ||
1543 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1544 Name = Lex.getStrVal();
1550 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
1551 return Error(TypeLoc, "invalid type for function argument");
1553 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1557 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1560 /// ParseFunctionType
1561 /// ::= Type ArgumentList OptionalAttrs
1562 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1563 assert(Lex.getKind() == lltok::lparen);
1565 if (!FunctionType::isValidReturnType(Result))
1566 return TokError("invalid function return type");
1568 std::vector<ArgInfo> ArgList;
1571 if (ParseArgumentList(ArgList, isVarArg, true) ||
1572 // FIXME: Allow, but ignore attributes on function types!
1573 // FIXME: Remove in LLVM 3.0
1574 ParseOptionalAttrs(Attrs, 2))
1577 // Reject names on the arguments lists.
1578 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1579 if (!ArgList[i].Name.empty())
1580 return Error(ArgList[i].Loc, "argument name invalid in function type");
1581 if (!ArgList[i].Attrs != 0) {
1582 // Allow but ignore attributes on function types; this permits
1584 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1588 std::vector<const Type*> ArgListTy;
1589 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1590 ArgListTy.push_back(ArgList[i].Type);
1592 Result = HandleUpRefs(FunctionType::get(Result.get(),
1593 ArgListTy, isVarArg));
1597 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1600 /// ::= '{' TypeRec (',' TypeRec)* '}'
1601 /// ::= '<' '{' '}' '>'
1602 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1603 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1604 assert(Lex.getKind() == lltok::lbrace);
1605 Lex.Lex(); // Consume the '{'
1607 if (EatIfPresent(lltok::rbrace)) {
1608 Result = StructType::get(Context, Packed);
1612 std::vector<PATypeHolder> ParamsList;
1613 LocTy EltTyLoc = Lex.getLoc();
1614 if (ParseTypeRec(Result)) return true;
1615 ParamsList.push_back(Result);
1617 if (Result->isVoidTy())
1618 return Error(EltTyLoc, "struct element can not have void type");
1619 if (!StructType::isValidElementType(Result))
1620 return Error(EltTyLoc, "invalid element type for struct");
1622 while (EatIfPresent(lltok::comma)) {
1623 EltTyLoc = Lex.getLoc();
1624 if (ParseTypeRec(Result)) return true;
1626 if (Result->isVoidTy())
1627 return Error(EltTyLoc, "struct element can not have void type");
1628 if (!StructType::isValidElementType(Result))
1629 return Error(EltTyLoc, "invalid element type for struct");
1631 ParamsList.push_back(Result);
1634 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1637 std::vector<const Type*> ParamsListTy;
1638 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1639 ParamsListTy.push_back(ParamsList[i].get());
1640 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1644 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1645 /// token has already been consumed.
1647 /// ::= '[' APSINTVAL 'x' Types ']'
1648 /// ::= '<' APSINTVAL 'x' Types '>'
1649 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1650 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1651 Lex.getAPSIntVal().getBitWidth() > 64)
1652 return TokError("expected number in address space");
1654 LocTy SizeLoc = Lex.getLoc();
1655 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1658 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1661 LocTy TypeLoc = Lex.getLoc();
1662 PATypeHolder EltTy(Type::getVoidTy(Context));
1663 if (ParseTypeRec(EltTy)) return true;
1665 if (EltTy->isVoidTy())
1666 return Error(TypeLoc, "array and vector element type cannot be void");
1668 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1669 "expected end of sequential type"))
1674 return Error(SizeLoc, "zero element vector is illegal");
1675 if ((unsigned)Size != Size)
1676 return Error(SizeLoc, "size too large for vector");
1677 if (!VectorType::isValidElementType(EltTy))
1678 return Error(TypeLoc, "vector element type must be fp or integer");
1679 Result = VectorType::get(EltTy, unsigned(Size));
1681 if (!ArrayType::isValidElementType(EltTy))
1682 return Error(TypeLoc, "invalid array element type");
1683 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1688 //===----------------------------------------------------------------------===//
1689 // Function Semantic Analysis.
1690 //===----------------------------------------------------------------------===//
1692 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1694 : P(p), F(f), FunctionNumber(functionNumber) {
1696 // Insert unnamed arguments into the NumberedVals list.
1697 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1700 NumberedVals.push_back(AI);
1703 LLParser::PerFunctionState::~PerFunctionState() {
1704 // If there were any forward referenced non-basicblock values, delete them.
1705 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1706 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1707 if (!isa<BasicBlock>(I->second.first)) {
1708 I->second.first->replaceAllUsesWith(
1709 UndefValue::get(I->second.first->getType()));
1710 delete I->second.first;
1711 I->second.first = 0;
1714 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1715 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1716 if (!isa<BasicBlock>(I->second.first)) {
1717 I->second.first->replaceAllUsesWith(
1718 UndefValue::get(I->second.first->getType()));
1719 delete I->second.first;
1720 I->second.first = 0;
1724 bool LLParser::PerFunctionState::FinishFunction() {
1725 // Check to see if someone took the address of labels in this block.
1726 if (!P.ForwardRefBlockAddresses.empty()) {
1728 if (!F.getName().empty()) {
1729 FunctionID.Kind = ValID::t_GlobalName;
1730 FunctionID.StrVal = F.getName();
1732 FunctionID.Kind = ValID::t_GlobalID;
1733 FunctionID.UIntVal = FunctionNumber;
1736 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1737 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1738 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1739 // Resolve all these references.
1740 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1743 P.ForwardRefBlockAddresses.erase(FRBAI);
1747 if (!ForwardRefVals.empty())
1748 return P.Error(ForwardRefVals.begin()->second.second,
1749 "use of undefined value '%" + ForwardRefVals.begin()->first +
1751 if (!ForwardRefValIDs.empty())
1752 return P.Error(ForwardRefValIDs.begin()->second.second,
1753 "use of undefined value '%" +
1754 Twine(ForwardRefValIDs.begin()->first) + "'");
1759 /// GetVal - Get a value with the specified name or ID, creating a
1760 /// forward reference record if needed. This can return null if the value
1761 /// exists but does not have the right type.
1762 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1763 const Type *Ty, LocTy Loc) {
1764 // Look this name up in the normal function symbol table.
1765 Value *Val = F.getValueSymbolTable().lookup(Name);
1767 // If this is a forward reference for the value, see if we already created a
1768 // forward ref record.
1770 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1771 I = ForwardRefVals.find(Name);
1772 if (I != ForwardRefVals.end())
1773 Val = I->second.first;
1776 // If we have the value in the symbol table or fwd-ref table, return it.
1778 if (Val->getType() == Ty) return Val;
1779 if (Ty->isLabelTy())
1780 P.Error(Loc, "'%" + Name + "' is not a basic block");
1782 P.Error(Loc, "'%" + Name + "' defined with type '" +
1783 Val->getType()->getDescription() + "'");
1787 // Don't make placeholders with invalid type.
1788 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1789 P.Error(Loc, "invalid use of a non-first-class type");
1793 // Otherwise, create a new forward reference for this value and remember it.
1795 if (Ty->isLabelTy())
1796 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1798 FwdVal = new Argument(Ty, Name);
1800 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1804 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1806 // Look this name up in the normal function symbol table.
1807 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1809 // If this is a forward reference for the value, see if we already created a
1810 // forward ref record.
1812 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1813 I = ForwardRefValIDs.find(ID);
1814 if (I != ForwardRefValIDs.end())
1815 Val = I->second.first;
1818 // If we have the value in the symbol table or fwd-ref table, return it.
1820 if (Val->getType() == Ty) return Val;
1821 if (Ty->isLabelTy())
1822 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1824 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1825 Val->getType()->getDescription() + "'");
1829 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1830 P.Error(Loc, "invalid use of a non-first-class type");
1834 // Otherwise, create a new forward reference for this value and remember it.
1836 if (Ty->isLabelTy())
1837 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1839 FwdVal = new Argument(Ty);
1841 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1845 /// SetInstName - After an instruction is parsed and inserted into its
1846 /// basic block, this installs its name.
1847 bool LLParser::PerFunctionState::SetInstName(int NameID,
1848 const std::string &NameStr,
1849 LocTy NameLoc, Instruction *Inst) {
1850 // If this instruction has void type, it cannot have a name or ID specified.
1851 if (Inst->getType()->isVoidTy()) {
1852 if (NameID != -1 || !NameStr.empty())
1853 return P.Error(NameLoc, "instructions returning void cannot have a name");
1857 // If this was a numbered instruction, verify that the instruction is the
1858 // expected value and resolve any forward references.
1859 if (NameStr.empty()) {
1860 // If neither a name nor an ID was specified, just use the next ID.
1862 NameID = NumberedVals.size();
1864 if (unsigned(NameID) != NumberedVals.size())
1865 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1866 Twine(NumberedVals.size()) + "'");
1868 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1869 ForwardRefValIDs.find(NameID);
1870 if (FI != ForwardRefValIDs.end()) {
1871 if (FI->second.first->getType() != Inst->getType())
1872 return P.Error(NameLoc, "instruction forward referenced with type '" +
1873 FI->second.first->getType()->getDescription() + "'");
1874 FI->second.first->replaceAllUsesWith(Inst);
1875 delete FI->second.first;
1876 ForwardRefValIDs.erase(FI);
1879 NumberedVals.push_back(Inst);
1883 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1884 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1885 FI = ForwardRefVals.find(NameStr);
1886 if (FI != ForwardRefVals.end()) {
1887 if (FI->second.first->getType() != Inst->getType())
1888 return P.Error(NameLoc, "instruction forward referenced with type '" +
1889 FI->second.first->getType()->getDescription() + "'");
1890 FI->second.first->replaceAllUsesWith(Inst);
1891 delete FI->second.first;
1892 ForwardRefVals.erase(FI);
1895 // Set the name on the instruction.
1896 Inst->setName(NameStr);
1898 if (Inst->getName() != NameStr)
1899 return P.Error(NameLoc, "multiple definition of local value named '" +
1904 /// GetBB - Get a basic block with the specified name or ID, creating a
1905 /// forward reference record if needed.
1906 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1908 return cast_or_null<BasicBlock>(GetVal(Name,
1909 Type::getLabelTy(F.getContext()), Loc));
1912 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1913 return cast_or_null<BasicBlock>(GetVal(ID,
1914 Type::getLabelTy(F.getContext()), Loc));
1917 /// DefineBB - Define the specified basic block, which is either named or
1918 /// unnamed. If there is an error, this returns null otherwise it returns
1919 /// the block being defined.
1920 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1924 BB = GetBB(NumberedVals.size(), Loc);
1926 BB = GetBB(Name, Loc);
1927 if (BB == 0) return 0; // Already diagnosed error.
1929 // Move the block to the end of the function. Forward ref'd blocks are
1930 // inserted wherever they happen to be referenced.
1931 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1933 // Remove the block from forward ref sets.
1935 ForwardRefValIDs.erase(NumberedVals.size());
1936 NumberedVals.push_back(BB);
1938 // BB forward references are already in the function symbol table.
1939 ForwardRefVals.erase(Name);
1945 //===----------------------------------------------------------------------===//
1947 //===----------------------------------------------------------------------===//
1949 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1950 /// type implied. For example, if we parse "4" we don't know what integer type
1951 /// it has. The value will later be combined with its type and checked for
1952 /// sanity. PFS is used to convert function-local operands of metadata (since
1953 /// metadata operands are not just parsed here but also converted to values).
1954 /// PFS can be null when we are not parsing metadata values inside a function.
1955 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1956 ID.Loc = Lex.getLoc();
1957 switch (Lex.getKind()) {
1958 default: return TokError("expected value token");
1959 case lltok::GlobalID: // @42
1960 ID.UIntVal = Lex.getUIntVal();
1961 ID.Kind = ValID::t_GlobalID;
1963 case lltok::GlobalVar: // @foo
1964 ID.StrVal = Lex.getStrVal();
1965 ID.Kind = ValID::t_GlobalName;
1967 case lltok::LocalVarID: // %42
1968 ID.UIntVal = Lex.getUIntVal();
1969 ID.Kind = ValID::t_LocalID;
1971 case lltok::LocalVar: // %foo
1972 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1973 ID.StrVal = Lex.getStrVal();
1974 ID.Kind = ValID::t_LocalName;
1976 case lltok::exclaim: // !42, !{...}, or !"foo"
1977 return ParseMetadataValue(ID, PFS);
1979 ID.APSIntVal = Lex.getAPSIntVal();
1980 ID.Kind = ValID::t_APSInt;
1982 case lltok::APFloat:
1983 ID.APFloatVal = Lex.getAPFloatVal();
1984 ID.Kind = ValID::t_APFloat;
1986 case lltok::kw_true:
1987 ID.ConstantVal = ConstantInt::getTrue(Context);
1988 ID.Kind = ValID::t_Constant;
1990 case lltok::kw_false:
1991 ID.ConstantVal = ConstantInt::getFalse(Context);
1992 ID.Kind = ValID::t_Constant;
1994 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1995 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1996 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1998 case lltok::lbrace: {
1999 // ValID ::= '{' ConstVector '}'
2001 SmallVector<Constant*, 16> Elts;
2002 if (ParseGlobalValueVector(Elts) ||
2003 ParseToken(lltok::rbrace, "expected end of struct constant"))
2006 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2007 Elts.size(), false);
2008 ID.Kind = ValID::t_Constant;
2012 // ValID ::= '<' ConstVector '>' --> Vector.
2013 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2015 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2017 SmallVector<Constant*, 16> Elts;
2018 LocTy FirstEltLoc = Lex.getLoc();
2019 if (ParseGlobalValueVector(Elts) ||
2021 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2022 ParseToken(lltok::greater, "expected end of constant"))
2025 if (isPackedStruct) {
2027 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
2028 ID.Kind = ValID::t_Constant;
2033 return Error(ID.Loc, "constant vector must not be empty");
2035 if (!Elts[0]->getType()->isIntegerTy() &&
2036 !Elts[0]->getType()->isFloatingPointTy())
2037 return Error(FirstEltLoc,
2038 "vector elements must have integer or floating point type");
2040 // Verify that all the vector elements have the same type.
2041 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2042 if (Elts[i]->getType() != Elts[0]->getType())
2043 return Error(FirstEltLoc,
2044 "vector element #" + Twine(i) +
2045 " is not of type '" + Elts[0]->getType()->getDescription());
2047 ID.ConstantVal = ConstantVector::get(Elts);
2048 ID.Kind = ValID::t_Constant;
2051 case lltok::lsquare: { // Array Constant
2053 SmallVector<Constant*, 16> Elts;
2054 LocTy FirstEltLoc = Lex.getLoc();
2055 if (ParseGlobalValueVector(Elts) ||
2056 ParseToken(lltok::rsquare, "expected end of array constant"))
2059 // Handle empty element.
2061 // Use undef instead of an array because it's inconvenient to determine
2062 // the element type at this point, there being no elements to examine.
2063 ID.Kind = ValID::t_EmptyArray;
2067 if (!Elts[0]->getType()->isFirstClassType())
2068 return Error(FirstEltLoc, "invalid array element type: " +
2069 Elts[0]->getType()->getDescription());
2071 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2073 // Verify all elements are correct type!
2074 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2075 if (Elts[i]->getType() != Elts[0]->getType())
2076 return Error(FirstEltLoc,
2077 "array element #" + Twine(i) +
2078 " is not of type '" +Elts[0]->getType()->getDescription());
2081 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2082 ID.Kind = ValID::t_Constant;
2085 case lltok::kw_c: // c "foo"
2087 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2088 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2089 ID.Kind = ValID::t_Constant;
2092 case lltok::kw_asm: {
2093 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2094 bool HasSideEffect, AlignStack;
2096 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2097 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2098 ParseStringConstant(ID.StrVal) ||
2099 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2100 ParseToken(lltok::StringConstant, "expected constraint string"))
2102 ID.StrVal2 = Lex.getStrVal();
2103 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2104 ID.Kind = ValID::t_InlineAsm;
2108 case lltok::kw_blockaddress: {
2109 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2113 LocTy FnLoc, LabelLoc;
2115 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2117 ParseToken(lltok::comma, "expected comma in block address expression")||
2118 ParseValID(Label) ||
2119 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2122 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2123 return Error(Fn.Loc, "expected function name in blockaddress");
2124 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2125 return Error(Label.Loc, "expected basic block name in blockaddress");
2127 // Make a global variable as a placeholder for this reference.
2128 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2129 false, GlobalValue::InternalLinkage,
2131 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2132 ID.ConstantVal = FwdRef;
2133 ID.Kind = ValID::t_Constant;
2137 case lltok::kw_trunc:
2138 case lltok::kw_zext:
2139 case lltok::kw_sext:
2140 case lltok::kw_fptrunc:
2141 case lltok::kw_fpext:
2142 case lltok::kw_bitcast:
2143 case lltok::kw_uitofp:
2144 case lltok::kw_sitofp:
2145 case lltok::kw_fptoui:
2146 case lltok::kw_fptosi:
2147 case lltok::kw_inttoptr:
2148 case lltok::kw_ptrtoint: {
2149 unsigned Opc = Lex.getUIntVal();
2150 PATypeHolder DestTy(Type::getVoidTy(Context));
2153 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2154 ParseGlobalTypeAndValue(SrcVal) ||
2155 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2156 ParseType(DestTy) ||
2157 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2159 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2160 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2161 SrcVal->getType()->getDescription() + "' to '" +
2162 DestTy->getDescription() + "'");
2163 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2165 ID.Kind = ValID::t_Constant;
2168 case lltok::kw_extractvalue: {
2171 SmallVector<unsigned, 4> Indices;
2172 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2173 ParseGlobalTypeAndValue(Val) ||
2174 ParseIndexList(Indices) ||
2175 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2178 if (!Val->getType()->isAggregateType())
2179 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2180 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2182 return Error(ID.Loc, "invalid indices for extractvalue");
2184 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2185 ID.Kind = ValID::t_Constant;
2188 case lltok::kw_insertvalue: {
2190 Constant *Val0, *Val1;
2191 SmallVector<unsigned, 4> Indices;
2192 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2193 ParseGlobalTypeAndValue(Val0) ||
2194 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2195 ParseGlobalTypeAndValue(Val1) ||
2196 ParseIndexList(Indices) ||
2197 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2199 if (!Val0->getType()->isAggregateType())
2200 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2201 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2203 return Error(ID.Loc, "invalid indices for insertvalue");
2204 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2205 Indices.data(), Indices.size());
2206 ID.Kind = ValID::t_Constant;
2209 case lltok::kw_icmp:
2210 case lltok::kw_fcmp: {
2211 unsigned PredVal, Opc = Lex.getUIntVal();
2212 Constant *Val0, *Val1;
2214 if (ParseCmpPredicate(PredVal, Opc) ||
2215 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2216 ParseGlobalTypeAndValue(Val0) ||
2217 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2218 ParseGlobalTypeAndValue(Val1) ||
2219 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2222 if (Val0->getType() != Val1->getType())
2223 return Error(ID.Loc, "compare operands must have the same type");
2225 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2227 if (Opc == Instruction::FCmp) {
2228 if (!Val0->getType()->isFPOrFPVectorTy())
2229 return Error(ID.Loc, "fcmp requires floating point operands");
2230 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2232 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2233 if (!Val0->getType()->isIntOrIntVectorTy() &&
2234 !Val0->getType()->isPointerTy())
2235 return Error(ID.Loc, "icmp requires pointer or integer operands");
2236 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2238 ID.Kind = ValID::t_Constant;
2242 // Binary Operators.
2244 case lltok::kw_fadd:
2246 case lltok::kw_fsub:
2248 case lltok::kw_fmul:
2249 case lltok::kw_udiv:
2250 case lltok::kw_sdiv:
2251 case lltok::kw_fdiv:
2252 case lltok::kw_urem:
2253 case lltok::kw_srem:
2254 case lltok::kw_frem:
2256 case lltok::kw_lshr:
2257 case lltok::kw_ashr: {
2261 unsigned Opc = Lex.getUIntVal();
2262 Constant *Val0, *Val1;
2264 LocTy ModifierLoc = Lex.getLoc();
2265 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2266 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2267 if (EatIfPresent(lltok::kw_nuw))
2269 if (EatIfPresent(lltok::kw_nsw)) {
2271 if (EatIfPresent(lltok::kw_nuw))
2274 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2275 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2276 if (EatIfPresent(lltok::kw_exact))
2279 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2280 ParseGlobalTypeAndValue(Val0) ||
2281 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2282 ParseGlobalTypeAndValue(Val1) ||
2283 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2285 if (Val0->getType() != Val1->getType())
2286 return Error(ID.Loc, "operands of constexpr must have same type");
2287 if (!Val0->getType()->isIntOrIntVectorTy()) {
2289 return Error(ModifierLoc, "nuw only applies to integer operations");
2291 return Error(ModifierLoc, "nsw only applies to integer operations");
2293 // Check that the type is valid for the operator.
2295 case Instruction::Add:
2296 case Instruction::Sub:
2297 case Instruction::Mul:
2298 case Instruction::UDiv:
2299 case Instruction::SDiv:
2300 case Instruction::URem:
2301 case Instruction::SRem:
2302 case Instruction::Shl:
2303 case Instruction::AShr:
2304 case Instruction::LShr:
2305 if (!Val0->getType()->isIntOrIntVectorTy())
2306 return Error(ID.Loc, "constexpr requires integer operands");
2308 case Instruction::FAdd:
2309 case Instruction::FSub:
2310 case Instruction::FMul:
2311 case Instruction::FDiv:
2312 case Instruction::FRem:
2313 if (!Val0->getType()->isFPOrFPVectorTy())
2314 return Error(ID.Loc, "constexpr requires fp operands");
2316 default: llvm_unreachable("Unknown binary operator!");
2319 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2320 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2321 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2322 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2324 ID.Kind = ValID::t_Constant;
2328 // Logical Operations
2331 case lltok::kw_xor: {
2332 unsigned Opc = Lex.getUIntVal();
2333 Constant *Val0, *Val1;
2335 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2336 ParseGlobalTypeAndValue(Val0) ||
2337 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2338 ParseGlobalTypeAndValue(Val1) ||
2339 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2341 if (Val0->getType() != Val1->getType())
2342 return Error(ID.Loc, "operands of constexpr must have same type");
2343 if (!Val0->getType()->isIntOrIntVectorTy())
2344 return Error(ID.Loc,
2345 "constexpr requires integer or integer vector operands");
2346 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2347 ID.Kind = ValID::t_Constant;
2351 case lltok::kw_getelementptr:
2352 case lltok::kw_shufflevector:
2353 case lltok::kw_insertelement:
2354 case lltok::kw_extractelement:
2355 case lltok::kw_select: {
2356 unsigned Opc = Lex.getUIntVal();
2357 SmallVector<Constant*, 16> Elts;
2358 bool InBounds = false;
2360 if (Opc == Instruction::GetElementPtr)
2361 InBounds = EatIfPresent(lltok::kw_inbounds);
2362 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2363 ParseGlobalValueVector(Elts) ||
2364 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2367 if (Opc == Instruction::GetElementPtr) {
2368 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2369 return Error(ID.Loc, "getelementptr requires pointer operand");
2371 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2372 (Value**)(Elts.data() + 1),
2374 return Error(ID.Loc, "invalid indices for getelementptr");
2375 ID.ConstantVal = InBounds ?
2376 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2379 ConstantExpr::getGetElementPtr(Elts[0],
2380 Elts.data() + 1, Elts.size() - 1);
2381 } else if (Opc == Instruction::Select) {
2382 if (Elts.size() != 3)
2383 return Error(ID.Loc, "expected three operands to select");
2384 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2386 return Error(ID.Loc, Reason);
2387 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2388 } else if (Opc == Instruction::ShuffleVector) {
2389 if (Elts.size() != 3)
2390 return Error(ID.Loc, "expected three operands to shufflevector");
2391 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2392 return Error(ID.Loc, "invalid operands to shufflevector");
2394 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2395 } else if (Opc == Instruction::ExtractElement) {
2396 if (Elts.size() != 2)
2397 return Error(ID.Loc, "expected two operands to extractelement");
2398 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2399 return Error(ID.Loc, "invalid extractelement operands");
2400 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2402 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2403 if (Elts.size() != 3)
2404 return Error(ID.Loc, "expected three operands to insertelement");
2405 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2406 return Error(ID.Loc, "invalid insertelement operands");
2408 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2411 ID.Kind = ValID::t_Constant;
2420 /// ParseGlobalValue - Parse a global value with the specified type.
2421 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2425 bool Parsed = ParseValID(ID) ||
2426 ConvertValIDToValue(Ty, ID, V, NULL);
2427 if (V && !(C = dyn_cast<Constant>(V)))
2428 return Error(ID.Loc, "global values must be constants");
2432 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2433 PATypeHolder Type(Type::getVoidTy(Context));
2434 return ParseType(Type) ||
2435 ParseGlobalValue(Type, V);
2438 /// ParseGlobalValueVector
2440 /// ::= TypeAndValue (',' TypeAndValue)*
2441 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2443 if (Lex.getKind() == lltok::rbrace ||
2444 Lex.getKind() == lltok::rsquare ||
2445 Lex.getKind() == lltok::greater ||
2446 Lex.getKind() == lltok::rparen)
2450 if (ParseGlobalTypeAndValue(C)) return true;
2453 while (EatIfPresent(lltok::comma)) {
2454 if (ParseGlobalTypeAndValue(C)) return true;
2461 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2462 assert(Lex.getKind() == lltok::lbrace);
2465 SmallVector<Value*, 16> Elts;
2466 if (ParseMDNodeVector(Elts, PFS) ||
2467 ParseToken(lltok::rbrace, "expected end of metadata node"))
2470 ID.MDNodeVal = MDNode::get(Context, Elts);
2471 ID.Kind = ValID::t_MDNode;
2475 /// ParseMetadataValue
2479 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2480 assert(Lex.getKind() == lltok::exclaim);
2485 if (Lex.getKind() == lltok::lbrace)
2486 return ParseMetadataListValue(ID, PFS);
2488 // Standalone metadata reference
2490 if (Lex.getKind() == lltok::APSInt) {
2491 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2492 ID.Kind = ValID::t_MDNode;
2497 // ::= '!' STRINGCONSTANT
2498 if (ParseMDString(ID.MDStringVal)) return true;
2499 ID.Kind = ValID::t_MDString;
2504 //===----------------------------------------------------------------------===//
2505 // Function Parsing.
2506 //===----------------------------------------------------------------------===//
2508 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2509 PerFunctionState *PFS) {
2510 if (Ty->isFunctionTy())
2511 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2514 default: llvm_unreachable("Unknown ValID!");
2515 case ValID::t_LocalID:
2516 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2517 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2519 case ValID::t_LocalName:
2520 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2521 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2523 case ValID::t_InlineAsm: {
2524 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2525 const FunctionType *FTy =
2526 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2527 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2528 return Error(ID.Loc, "invalid type for inline asm constraint string");
2529 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2532 case ValID::t_MDNode:
2533 if (!Ty->isMetadataTy())
2534 return Error(ID.Loc, "metadata value must have metadata type");
2537 case ValID::t_MDString:
2538 if (!Ty->isMetadataTy())
2539 return Error(ID.Loc, "metadata value must have metadata type");
2542 case ValID::t_GlobalName:
2543 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2545 case ValID::t_GlobalID:
2546 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2548 case ValID::t_APSInt:
2549 if (!Ty->isIntegerTy())
2550 return Error(ID.Loc, "integer constant must have integer type");
2551 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2552 V = ConstantInt::get(Context, ID.APSIntVal);
2554 case ValID::t_APFloat:
2555 if (!Ty->isFloatingPointTy() ||
2556 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2557 return Error(ID.Loc, "floating point constant invalid for type");
2559 // The lexer has no type info, so builds all float and double FP constants
2560 // as double. Fix this here. Long double does not need this.
2561 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2564 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2567 V = ConstantFP::get(Context, ID.APFloatVal);
2569 if (V->getType() != Ty)
2570 return Error(ID.Loc, "floating point constant does not have type '" +
2571 Ty->getDescription() + "'");
2575 if (!Ty->isPointerTy())
2576 return Error(ID.Loc, "null must be a pointer type");
2577 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2579 case ValID::t_Undef:
2580 // FIXME: LabelTy should not be a first-class type.
2581 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2583 return Error(ID.Loc, "invalid type for undef constant");
2584 V = UndefValue::get(Ty);
2586 case ValID::t_EmptyArray:
2587 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2588 return Error(ID.Loc, "invalid empty array initializer");
2589 V = UndefValue::get(Ty);
2592 // FIXME: LabelTy should not be a first-class type.
2593 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2594 return Error(ID.Loc, "invalid type for null constant");
2595 V = Constant::getNullValue(Ty);
2597 case ValID::t_Constant:
2598 if (ID.ConstantVal->getType() != Ty)
2599 return Error(ID.Loc, "constant expression type mismatch");
2606 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2609 return ParseValID(ID, &PFS) ||
2610 ConvertValIDToValue(Ty, ID, V, &PFS);
2613 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2614 PATypeHolder T(Type::getVoidTy(Context));
2615 return ParseType(T) ||
2616 ParseValue(T, V, PFS);
2619 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2620 PerFunctionState &PFS) {
2623 if (ParseTypeAndValue(V, PFS)) return true;
2624 if (!isa<BasicBlock>(V))
2625 return Error(Loc, "expected a basic block");
2626 BB = cast<BasicBlock>(V);
2632 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2633 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2634 /// OptionalAlign OptGC
2635 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2636 // Parse the linkage.
2637 LocTy LinkageLoc = Lex.getLoc();
2640 unsigned Visibility, RetAttrs;
2642 PATypeHolder RetType(Type::getVoidTy(Context));
2643 LocTy RetTypeLoc = Lex.getLoc();
2644 if (ParseOptionalLinkage(Linkage) ||
2645 ParseOptionalVisibility(Visibility) ||
2646 ParseOptionalCallingConv(CC) ||
2647 ParseOptionalAttrs(RetAttrs, 1) ||
2648 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2651 // Verify that the linkage is ok.
2652 switch ((GlobalValue::LinkageTypes)Linkage) {
2653 case GlobalValue::ExternalLinkage:
2654 break; // always ok.
2655 case GlobalValue::DLLImportLinkage:
2656 case GlobalValue::ExternalWeakLinkage:
2658 return Error(LinkageLoc, "invalid linkage for function definition");
2660 case GlobalValue::PrivateLinkage:
2661 case GlobalValue::LinkerPrivateLinkage:
2662 case GlobalValue::LinkerPrivateWeakLinkage:
2663 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2664 case GlobalValue::InternalLinkage:
2665 case GlobalValue::AvailableExternallyLinkage:
2666 case GlobalValue::LinkOnceAnyLinkage:
2667 case GlobalValue::LinkOnceODRLinkage:
2668 case GlobalValue::WeakAnyLinkage:
2669 case GlobalValue::WeakODRLinkage:
2670 case GlobalValue::DLLExportLinkage:
2672 return Error(LinkageLoc, "invalid linkage for function declaration");
2674 case GlobalValue::AppendingLinkage:
2675 case GlobalValue::CommonLinkage:
2676 return Error(LinkageLoc, "invalid function linkage type");
2679 if (!FunctionType::isValidReturnType(RetType) ||
2680 RetType->isOpaqueTy())
2681 return Error(RetTypeLoc, "invalid function return type");
2683 LocTy NameLoc = Lex.getLoc();
2685 std::string FunctionName;
2686 if (Lex.getKind() == lltok::GlobalVar) {
2687 FunctionName = Lex.getStrVal();
2688 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2689 unsigned NameID = Lex.getUIntVal();
2691 if (NameID != NumberedVals.size())
2692 return TokError("function expected to be numbered '%" +
2693 Twine(NumberedVals.size()) + "'");
2695 return TokError("expected function name");
2700 if (Lex.getKind() != lltok::lparen)
2701 return TokError("expected '(' in function argument list");
2703 std::vector<ArgInfo> ArgList;
2706 std::string Section;
2710 LocTy UnnamedAddrLoc;
2712 if (ParseArgumentList(ArgList, isVarArg, false) ||
2713 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2715 ParseOptionalAttrs(FuncAttrs, 2) ||
2716 (EatIfPresent(lltok::kw_section) &&
2717 ParseStringConstant(Section)) ||
2718 ParseOptionalAlignment(Alignment) ||
2719 (EatIfPresent(lltok::kw_gc) &&
2720 ParseStringConstant(GC)))
2723 // If the alignment was parsed as an attribute, move to the alignment field.
2724 if (FuncAttrs & Attribute::Alignment) {
2725 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2726 FuncAttrs &= ~Attribute::Alignment;
2729 // Okay, if we got here, the function is syntactically valid. Convert types
2730 // and do semantic checks.
2731 std::vector<const Type*> ParamTypeList;
2732 SmallVector<AttributeWithIndex, 8> Attrs;
2734 if (RetAttrs != Attribute::None)
2735 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2737 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2738 ParamTypeList.push_back(ArgList[i].Type);
2739 if (ArgList[i].Attrs != Attribute::None)
2740 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2743 if (FuncAttrs != Attribute::None)
2744 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2746 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2748 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2749 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2751 const FunctionType *FT =
2752 FunctionType::get(RetType, ParamTypeList, isVarArg);
2753 const PointerType *PFT = PointerType::getUnqual(FT);
2756 if (!FunctionName.empty()) {
2757 // If this was a definition of a forward reference, remove the definition
2758 // from the forward reference table and fill in the forward ref.
2759 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2760 ForwardRefVals.find(FunctionName);
2761 if (FRVI != ForwardRefVals.end()) {
2762 Fn = M->getFunction(FunctionName);
2763 if (Fn->getType() != PFT)
2764 return Error(FRVI->second.second, "invalid forward reference to "
2765 "function '" + FunctionName + "' with wrong type!");
2767 ForwardRefVals.erase(FRVI);
2768 } else if ((Fn = M->getFunction(FunctionName))) {
2769 // If this function already exists in the symbol table, then it is
2770 // multiply defined. We accept a few cases for old backwards compat.
2771 // FIXME: Remove this stuff for LLVM 3.0.
2772 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2773 (!Fn->isDeclaration() && isDefine)) {
2774 // If the redefinition has different type or different attributes,
2775 // reject it. If both have bodies, reject it.
2776 return Error(NameLoc, "invalid redefinition of function '" +
2777 FunctionName + "'");
2778 } else if (Fn->isDeclaration()) {
2779 // Make sure to strip off any argument names so we can't get conflicts.
2780 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2784 } else if (M->getNamedValue(FunctionName)) {
2785 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2789 // If this is a definition of a forward referenced function, make sure the
2791 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2792 = ForwardRefValIDs.find(NumberedVals.size());
2793 if (I != ForwardRefValIDs.end()) {
2794 Fn = cast<Function>(I->second.first);
2795 if (Fn->getType() != PFT)
2796 return Error(NameLoc, "type of definition and forward reference of '@" +
2797 Twine(NumberedVals.size()) + "' disagree");
2798 ForwardRefValIDs.erase(I);
2803 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2804 else // Move the forward-reference to the correct spot in the module.
2805 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2807 if (FunctionName.empty())
2808 NumberedVals.push_back(Fn);
2810 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2811 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2812 Fn->setCallingConv(CC);
2813 Fn->setAttributes(PAL);
2814 Fn->setUnnamedAddr(UnnamedAddr);
2815 Fn->setAlignment(Alignment);
2816 Fn->setSection(Section);
2817 if (!GC.empty()) Fn->setGC(GC.c_str());
2819 // Add all of the arguments we parsed to the function.
2820 Function::arg_iterator ArgIt = Fn->arg_begin();
2821 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2822 // If we run out of arguments in the Function prototype, exit early.
2823 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2824 if (ArgIt == Fn->arg_end()) break;
2826 // If the argument has a name, insert it into the argument symbol table.
2827 if (ArgList[i].Name.empty()) continue;
2829 // Set the name, if it conflicted, it will be auto-renamed.
2830 ArgIt->setName(ArgList[i].Name);
2832 if (ArgIt->getName() != ArgList[i].Name)
2833 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2834 ArgList[i].Name + "'");
2841 /// ParseFunctionBody
2842 /// ::= '{' BasicBlock+ '}'
2843 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2845 bool LLParser::ParseFunctionBody(Function &Fn) {
2846 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2847 return TokError("expected '{' in function body");
2848 Lex.Lex(); // eat the {.
2850 int FunctionNumber = -1;
2851 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2853 PerFunctionState PFS(*this, Fn, FunctionNumber);
2855 // We need at least one basic block.
2856 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2857 return TokError("function body requires at least one basic block");
2859 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2860 if (ParseBasicBlock(PFS)) return true;
2865 // Verify function is ok.
2866 return PFS.FinishFunction();
2870 /// ::= LabelStr? Instruction*
2871 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2872 // If this basic block starts out with a name, remember it.
2874 LocTy NameLoc = Lex.getLoc();
2875 if (Lex.getKind() == lltok::LabelStr) {
2876 Name = Lex.getStrVal();
2880 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2881 if (BB == 0) return true;
2883 std::string NameStr;
2885 // Parse the instructions in this block until we get a terminator.
2887 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2889 // This instruction may have three possibilities for a name: a) none
2890 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2891 LocTy NameLoc = Lex.getLoc();
2895 if (Lex.getKind() == lltok::LocalVarID) {
2896 NameID = Lex.getUIntVal();
2898 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2900 } else if (Lex.getKind() == lltok::LocalVar ||
2901 // FIXME: REMOVE IN LLVM 3.0
2902 Lex.getKind() == lltok::StringConstant) {
2903 NameStr = Lex.getStrVal();
2905 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2909 switch (ParseInstruction(Inst, BB, PFS)) {
2910 default: assert(0 && "Unknown ParseInstruction result!");
2911 case InstError: return true;
2913 BB->getInstList().push_back(Inst);
2915 // With a normal result, we check to see if the instruction is followed by
2916 // a comma and metadata.
2917 if (EatIfPresent(lltok::comma))
2918 if (ParseInstructionMetadata(Inst, &PFS))
2921 case InstExtraComma:
2922 BB->getInstList().push_back(Inst);
2924 // If the instruction parser ate an extra comma at the end of it, it
2925 // *must* be followed by metadata.
2926 if (ParseInstructionMetadata(Inst, &PFS))
2931 // Set the name on the instruction.
2932 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2933 } while (!isa<TerminatorInst>(Inst));
2938 //===----------------------------------------------------------------------===//
2939 // Instruction Parsing.
2940 //===----------------------------------------------------------------------===//
2942 /// ParseInstruction - Parse one of the many different instructions.
2944 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2945 PerFunctionState &PFS) {
2946 lltok::Kind Token = Lex.getKind();
2947 if (Token == lltok::Eof)
2948 return TokError("found end of file when expecting more instructions");
2949 LocTy Loc = Lex.getLoc();
2950 unsigned KeywordVal = Lex.getUIntVal();
2951 Lex.Lex(); // Eat the keyword.
2954 default: return Error(Loc, "expected instruction opcode");
2955 // Terminator Instructions.
2956 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2957 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2958 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2959 case lltok::kw_br: return ParseBr(Inst, PFS);
2960 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2961 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2962 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2963 // Binary Operators.
2967 case lltok::kw_shl: {
2968 bool NUW = EatIfPresent(lltok::kw_nuw);
2969 bool NSW = EatIfPresent(lltok::kw_nsw);
2970 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2972 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2974 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2975 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2978 case lltok::kw_fadd:
2979 case lltok::kw_fsub:
2980 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2982 case lltok::kw_sdiv:
2983 case lltok::kw_udiv:
2984 case lltok::kw_lshr:
2985 case lltok::kw_ashr: {
2986 bool Exact = EatIfPresent(lltok::kw_exact);
2988 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2989 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2993 case lltok::kw_urem:
2994 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2995 case lltok::kw_fdiv:
2996 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2999 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3000 case lltok::kw_icmp:
3001 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3003 case lltok::kw_trunc:
3004 case lltok::kw_zext:
3005 case lltok::kw_sext:
3006 case lltok::kw_fptrunc:
3007 case lltok::kw_fpext:
3008 case lltok::kw_bitcast:
3009 case lltok::kw_uitofp:
3010 case lltok::kw_sitofp:
3011 case lltok::kw_fptoui:
3012 case lltok::kw_fptosi:
3013 case lltok::kw_inttoptr:
3014 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3016 case lltok::kw_select: return ParseSelect(Inst, PFS);
3017 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3018 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3019 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3020 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3021 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3022 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3023 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3025 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3026 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3027 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3028 case lltok::kw_volatile:
3029 if (EatIfPresent(lltok::kw_load))
3030 return ParseLoad(Inst, PFS, true);
3031 else if (EatIfPresent(lltok::kw_store))
3032 return ParseStore(Inst, PFS, true);
3034 return TokError("expected 'load' or 'store'");
3035 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3036 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3037 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3038 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3042 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3043 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3044 if (Opc == Instruction::FCmp) {
3045 switch (Lex.getKind()) {
3046 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3047 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3048 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3049 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3050 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3051 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3052 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3053 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3054 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3055 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3056 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3057 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3058 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3059 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3060 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3061 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3062 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3065 switch (Lex.getKind()) {
3066 default: TokError("expected icmp predicate (e.g. 'eq')");
3067 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3068 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3069 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3070 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3071 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3072 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3073 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3074 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3075 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3076 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3083 //===----------------------------------------------------------------------===//
3084 // Terminator Instructions.
3085 //===----------------------------------------------------------------------===//
3087 /// ParseRet - Parse a return instruction.
3088 /// ::= 'ret' void (',' !dbg, !1)*
3089 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3090 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
3091 /// [[obsolete: LLVM 3.0]]
3092 int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3093 PerFunctionState &PFS) {
3094 PATypeHolder Ty(Type::getVoidTy(Context));
3095 if (ParseType(Ty, true /*void allowed*/)) return true;
3097 if (Ty->isVoidTy()) {
3098 Inst = ReturnInst::Create(Context);
3103 if (ParseValue(Ty, RV, PFS)) return true;
3105 bool ExtraComma = false;
3106 if (EatIfPresent(lltok::comma)) {
3107 // Parse optional custom metadata, e.g. !dbg
3108 if (Lex.getKind() == lltok::MetadataVar) {
3111 // The normal case is one return value.
3112 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3113 // use of 'ret {i32,i32} {i32 1, i32 2}'
3114 SmallVector<Value*, 8> RVs;
3118 // If optional custom metadata, e.g. !dbg is seen then this is the
3120 if (Lex.getKind() == lltok::MetadataVar)
3122 if (ParseTypeAndValue(RV, PFS)) return true;
3124 } while (EatIfPresent(lltok::comma));
3126 RV = UndefValue::get(PFS.getFunction().getReturnType());
3127 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
3128 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3129 BB->getInstList().push_back(I);
3135 Inst = ReturnInst::Create(Context, RV);
3136 return ExtraComma ? InstExtraComma : InstNormal;
3141 /// ::= 'br' TypeAndValue
3142 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3143 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3146 BasicBlock *Op1, *Op2;
3147 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3149 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3150 Inst = BranchInst::Create(BB);
3154 if (Op0->getType() != Type::getInt1Ty(Context))
3155 return Error(Loc, "branch condition must have 'i1' type");
3157 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3158 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3159 ParseToken(lltok::comma, "expected ',' after true destination") ||
3160 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3163 Inst = BranchInst::Create(Op1, Op2, Op0);
3169 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3171 /// ::= (TypeAndValue ',' TypeAndValue)*
3172 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3173 LocTy CondLoc, BBLoc;
3175 BasicBlock *DefaultBB;
3176 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3177 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3178 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3179 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3182 if (!Cond->getType()->isIntegerTy())
3183 return Error(CondLoc, "switch condition must have integer type");
3185 // Parse the jump table pairs.
3186 SmallPtrSet<Value*, 32> SeenCases;
3187 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3188 while (Lex.getKind() != lltok::rsquare) {
3192 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3193 ParseToken(lltok::comma, "expected ',' after case value") ||
3194 ParseTypeAndBasicBlock(DestBB, PFS))
3197 if (!SeenCases.insert(Constant))
3198 return Error(CondLoc, "duplicate case value in switch");
3199 if (!isa<ConstantInt>(Constant))
3200 return Error(CondLoc, "case value is not a constant integer");
3202 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3205 Lex.Lex(); // Eat the ']'.
3207 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3208 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3209 SI->addCase(Table[i].first, Table[i].second);
3216 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3217 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3220 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3221 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3222 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3225 if (!Address->getType()->isPointerTy())
3226 return Error(AddrLoc, "indirectbr address must have pointer type");
3228 // Parse the destination list.
3229 SmallVector<BasicBlock*, 16> DestList;
3231 if (Lex.getKind() != lltok::rsquare) {
3233 if (ParseTypeAndBasicBlock(DestBB, PFS))
3235 DestList.push_back(DestBB);
3237 while (EatIfPresent(lltok::comma)) {
3238 if (ParseTypeAndBasicBlock(DestBB, PFS))
3240 DestList.push_back(DestBB);
3244 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3247 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3248 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3249 IBI->addDestination(DestList[i]);
3256 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3257 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3258 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3259 LocTy CallLoc = Lex.getLoc();
3260 unsigned RetAttrs, FnAttrs;
3262 PATypeHolder RetType(Type::getVoidTy(Context));
3265 SmallVector<ParamInfo, 16> ArgList;
3267 BasicBlock *NormalBB, *UnwindBB;
3268 if (ParseOptionalCallingConv(CC) ||
3269 ParseOptionalAttrs(RetAttrs, 1) ||
3270 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3271 ParseValID(CalleeID) ||
3272 ParseParameterList(ArgList, PFS) ||
3273 ParseOptionalAttrs(FnAttrs, 2) ||
3274 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3275 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3276 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3277 ParseTypeAndBasicBlock(UnwindBB, PFS))
3280 // If RetType is a non-function pointer type, then this is the short syntax
3281 // for the call, which means that RetType is just the return type. Infer the
3282 // rest of the function argument types from the arguments that are present.
3283 const PointerType *PFTy = 0;
3284 const FunctionType *Ty = 0;
3285 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3286 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3287 // Pull out the types of all of the arguments...
3288 std::vector<const Type*> ParamTypes;
3289 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3290 ParamTypes.push_back(ArgList[i].V->getType());
3292 if (!FunctionType::isValidReturnType(RetType))
3293 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3295 Ty = FunctionType::get(RetType, ParamTypes, false);
3296 PFTy = PointerType::getUnqual(Ty);
3299 // Look up the callee.
3301 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3303 // Set up the Attributes for the function.
3304 SmallVector<AttributeWithIndex, 8> Attrs;
3305 if (RetAttrs != Attribute::None)
3306 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3308 SmallVector<Value*, 8> Args;
3310 // Loop through FunctionType's arguments and ensure they are specified
3311 // correctly. Also, gather any parameter attributes.
3312 FunctionType::param_iterator I = Ty->param_begin();
3313 FunctionType::param_iterator E = Ty->param_end();
3314 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3315 const Type *ExpectedTy = 0;
3318 } else if (!Ty->isVarArg()) {
3319 return Error(ArgList[i].Loc, "too many arguments specified");
3322 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3323 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3324 ExpectedTy->getDescription() + "'");
3325 Args.push_back(ArgList[i].V);
3326 if (ArgList[i].Attrs != Attribute::None)
3327 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3331 return Error(CallLoc, "not enough parameters specified for call");
3333 if (FnAttrs != Attribute::None)
3334 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3336 // Finish off the Attributes and check them
3337 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3339 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3340 Args.begin(), Args.end());
3341 II->setCallingConv(CC);
3342 II->setAttributes(PAL);
3349 //===----------------------------------------------------------------------===//
3350 // Binary Operators.
3351 //===----------------------------------------------------------------------===//
3354 /// ::= ArithmeticOps TypeAndValue ',' Value
3356 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3357 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3358 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3359 unsigned Opc, unsigned OperandType) {
3360 LocTy Loc; Value *LHS, *RHS;
3361 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3362 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3363 ParseValue(LHS->getType(), RHS, PFS))
3367 switch (OperandType) {
3368 default: llvm_unreachable("Unknown operand type!");
3369 case 0: // int or FP.
3370 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3371 LHS->getType()->isFPOrFPVectorTy();
3373 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3374 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3378 return Error(Loc, "invalid operand type for instruction");
3380 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3385 /// ::= ArithmeticOps TypeAndValue ',' Value {
3386 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3388 LocTy Loc; Value *LHS, *RHS;
3389 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3390 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3391 ParseValue(LHS->getType(), RHS, PFS))
3394 if (!LHS->getType()->isIntOrIntVectorTy())
3395 return Error(Loc,"instruction requires integer or integer vector operands");
3397 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3403 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3404 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3405 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3407 // Parse the integer/fp comparison predicate.
3411 if (ParseCmpPredicate(Pred, Opc) ||
3412 ParseTypeAndValue(LHS, Loc, PFS) ||
3413 ParseToken(lltok::comma, "expected ',' after compare value") ||
3414 ParseValue(LHS->getType(), RHS, PFS))
3417 if (Opc == Instruction::FCmp) {
3418 if (!LHS->getType()->isFPOrFPVectorTy())
3419 return Error(Loc, "fcmp requires floating point operands");
3420 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3422 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3423 if (!LHS->getType()->isIntOrIntVectorTy() &&
3424 !LHS->getType()->isPointerTy())
3425 return Error(Loc, "icmp requires integer operands");
3426 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3431 //===----------------------------------------------------------------------===//
3432 // Other Instructions.
3433 //===----------------------------------------------------------------------===//
3437 /// ::= CastOpc TypeAndValue 'to' Type
3438 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3440 LocTy Loc; Value *Op;
3441 PATypeHolder DestTy(Type::getVoidTy(Context));
3442 if (ParseTypeAndValue(Op, Loc, PFS) ||
3443 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3447 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3448 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3449 return Error(Loc, "invalid cast opcode for cast from '" +
3450 Op->getType()->getDescription() + "' to '" +
3451 DestTy->getDescription() + "'");
3453 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3458 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3459 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3461 Value *Op0, *Op1, *Op2;
3462 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3463 ParseToken(lltok::comma, "expected ',' after select condition") ||
3464 ParseTypeAndValue(Op1, PFS) ||
3465 ParseToken(lltok::comma, "expected ',' after select value") ||
3466 ParseTypeAndValue(Op2, PFS))
3469 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3470 return Error(Loc, Reason);
3472 Inst = SelectInst::Create(Op0, Op1, Op2);
3477 /// ::= 'va_arg' TypeAndValue ',' Type
3478 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3480 PATypeHolder EltTy(Type::getVoidTy(Context));
3482 if (ParseTypeAndValue(Op, PFS) ||
3483 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3484 ParseType(EltTy, TypeLoc))
3487 if (!EltTy->isFirstClassType())
3488 return Error(TypeLoc, "va_arg requires operand with first class type");
3490 Inst = new VAArgInst(Op, EltTy);
3494 /// ParseExtractElement
3495 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3496 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3499 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3500 ParseToken(lltok::comma, "expected ',' after extract value") ||
3501 ParseTypeAndValue(Op1, PFS))
3504 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3505 return Error(Loc, "invalid extractelement operands");
3507 Inst = ExtractElementInst::Create(Op0, Op1);
3511 /// ParseInsertElement
3512 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3513 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3515 Value *Op0, *Op1, *Op2;
3516 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3517 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3518 ParseTypeAndValue(Op1, PFS) ||
3519 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3520 ParseTypeAndValue(Op2, PFS))
3523 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3524 return Error(Loc, "invalid insertelement operands");
3526 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3530 /// ParseShuffleVector
3531 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3532 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3534 Value *Op0, *Op1, *Op2;
3535 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3536 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3537 ParseTypeAndValue(Op1, PFS) ||
3538 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3539 ParseTypeAndValue(Op2, PFS))
3542 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3543 return Error(Loc, "invalid extractelement operands");
3545 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3550 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3551 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3552 PATypeHolder Ty(Type::getVoidTy(Context));
3554 LocTy TypeLoc = Lex.getLoc();
3556 if (ParseType(Ty) ||
3557 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3558 ParseValue(Ty, Op0, PFS) ||
3559 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3560 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3561 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3564 bool AteExtraComma = false;
3565 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3567 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3569 if (!EatIfPresent(lltok::comma))
3572 if (Lex.getKind() == lltok::MetadataVar) {
3573 AteExtraComma = true;
3577 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3578 ParseValue(Ty, Op0, PFS) ||
3579 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3580 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3581 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3585 if (!Ty->isFirstClassType())
3586 return Error(TypeLoc, "phi node must have first class type");
3588 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3589 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3590 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3592 return AteExtraComma ? InstExtraComma : InstNormal;
3596 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3597 /// ParameterList OptionalAttrs
3598 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3600 unsigned RetAttrs, FnAttrs;
3602 PATypeHolder RetType(Type::getVoidTy(Context));
3605 SmallVector<ParamInfo, 16> ArgList;
3606 LocTy CallLoc = Lex.getLoc();
3608 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3609 ParseOptionalCallingConv(CC) ||
3610 ParseOptionalAttrs(RetAttrs, 1) ||
3611 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3612 ParseValID(CalleeID) ||
3613 ParseParameterList(ArgList, PFS) ||
3614 ParseOptionalAttrs(FnAttrs, 2))
3617 // If RetType is a non-function pointer type, then this is the short syntax
3618 // for the call, which means that RetType is just the return type. Infer the
3619 // rest of the function argument types from the arguments that are present.
3620 const PointerType *PFTy = 0;
3621 const FunctionType *Ty = 0;
3622 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3623 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3624 // Pull out the types of all of the arguments...
3625 std::vector<const Type*> ParamTypes;
3626 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3627 ParamTypes.push_back(ArgList[i].V->getType());
3629 if (!FunctionType::isValidReturnType(RetType))
3630 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3632 Ty = FunctionType::get(RetType, ParamTypes, false);
3633 PFTy = PointerType::getUnqual(Ty);
3636 // Look up the callee.
3638 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3640 // Set up the Attributes for the function.
3641 SmallVector<AttributeWithIndex, 8> Attrs;
3642 if (RetAttrs != Attribute::None)
3643 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3645 SmallVector<Value*, 8> Args;
3647 // Loop through FunctionType's arguments and ensure they are specified
3648 // correctly. Also, gather any parameter attributes.
3649 FunctionType::param_iterator I = Ty->param_begin();
3650 FunctionType::param_iterator E = Ty->param_end();
3651 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3652 const Type *ExpectedTy = 0;
3655 } else if (!Ty->isVarArg()) {
3656 return Error(ArgList[i].Loc, "too many arguments specified");
3659 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3660 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3661 ExpectedTy->getDescription() + "'");
3662 Args.push_back(ArgList[i].V);
3663 if (ArgList[i].Attrs != Attribute::None)
3664 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3668 return Error(CallLoc, "not enough parameters specified for call");
3670 if (FnAttrs != Attribute::None)
3671 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3673 // Finish off the Attributes and check them
3674 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3676 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3677 CI->setTailCall(isTail);
3678 CI->setCallingConv(CC);
3679 CI->setAttributes(PAL);
3684 //===----------------------------------------------------------------------===//
3685 // Memory Instructions.
3686 //===----------------------------------------------------------------------===//
3689 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3690 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3691 PATypeHolder Ty(Type::getVoidTy(Context));
3694 unsigned Alignment = 0;
3695 if (ParseType(Ty)) return true;
3697 bool AteExtraComma = false;
3698 if (EatIfPresent(lltok::comma)) {
3699 if (Lex.getKind() == lltok::kw_align) {
3700 if (ParseOptionalAlignment(Alignment)) return true;
3701 } else if (Lex.getKind() == lltok::MetadataVar) {
3702 AteExtraComma = true;
3704 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3705 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3710 if (Size && !Size->getType()->isIntegerTy())
3711 return Error(SizeLoc, "element count must have integer type");
3713 Inst = new AllocaInst(Ty, Size, Alignment);
3714 return AteExtraComma ? InstExtraComma : InstNormal;
3718 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3719 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3721 Value *Val; LocTy Loc;
3722 unsigned Alignment = 0;
3723 bool AteExtraComma = false;
3724 if (ParseTypeAndValue(Val, Loc, PFS) ||
3725 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3728 if (!Val->getType()->isPointerTy() ||
3729 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3730 return Error(Loc, "load operand must be a pointer to a first class type");
3732 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3733 return AteExtraComma ? InstExtraComma : InstNormal;
3737 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3738 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3740 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3741 unsigned Alignment = 0;
3742 bool AteExtraComma = false;
3743 if (ParseTypeAndValue(Val, Loc, PFS) ||
3744 ParseToken(lltok::comma, "expected ',' after store operand") ||
3745 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3746 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3749 if (!Ptr->getType()->isPointerTy())
3750 return Error(PtrLoc, "store operand must be a pointer");
3751 if (!Val->getType()->isFirstClassType())
3752 return Error(Loc, "store operand must be a first class value");
3753 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3754 return Error(Loc, "stored value and pointer type do not match");
3756 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3757 return AteExtraComma ? InstExtraComma : InstNormal;
3761 /// ::= 'getresult' TypeAndValue ',' i32
3762 /// FIXME: Remove support for getresult in LLVM 3.0
3763 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3764 Value *Val; LocTy ValLoc, EltLoc;
3766 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3767 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3768 ParseUInt32(Element, EltLoc))
3771 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
3772 return Error(ValLoc, "getresult inst requires an aggregate operand");
3773 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3774 return Error(EltLoc, "invalid getresult index for value");
3775 Inst = ExtractValueInst::Create(Val, Element);
3779 /// ParseGetElementPtr
3780 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3781 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3782 Value *Ptr, *Val; LocTy Loc, EltLoc;
3784 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3786 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3788 if (!Ptr->getType()->isPointerTy())
3789 return Error(Loc, "base of getelementptr must be a pointer");
3791 SmallVector<Value*, 16> Indices;
3792 bool AteExtraComma = false;
3793 while (EatIfPresent(lltok::comma)) {
3794 if (Lex.getKind() == lltok::MetadataVar) {
3795 AteExtraComma = true;
3798 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3799 if (!Val->getType()->isIntegerTy())
3800 return Error(EltLoc, "getelementptr index must be an integer");
3801 Indices.push_back(Val);
3804 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3805 Indices.begin(), Indices.end()))
3806 return Error(Loc, "invalid getelementptr indices");
3807 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3809 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3810 return AteExtraComma ? InstExtraComma : InstNormal;
3813 /// ParseExtractValue
3814 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3815 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3816 Value *Val; LocTy Loc;
3817 SmallVector<unsigned, 4> Indices;
3819 if (ParseTypeAndValue(Val, Loc, PFS) ||
3820 ParseIndexList(Indices, AteExtraComma))
3823 if (!Val->getType()->isAggregateType())
3824 return Error(Loc, "extractvalue operand must be aggregate type");
3826 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3828 return Error(Loc, "invalid indices for extractvalue");
3829 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3830 return AteExtraComma ? InstExtraComma : InstNormal;
3833 /// ParseInsertValue
3834 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3835 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3836 Value *Val0, *Val1; LocTy Loc0, Loc1;
3837 SmallVector<unsigned, 4> Indices;
3839 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3840 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3841 ParseTypeAndValue(Val1, Loc1, PFS) ||
3842 ParseIndexList(Indices, AteExtraComma))
3845 if (!Val0->getType()->isAggregateType())
3846 return Error(Loc0, "insertvalue operand must be aggregate type");
3848 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3850 return Error(Loc0, "invalid indices for insertvalue");
3851 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3852 return AteExtraComma ? InstExtraComma : InstNormal;
3855 //===----------------------------------------------------------------------===//
3856 // Embedded metadata.
3857 //===----------------------------------------------------------------------===//
3859 /// ParseMDNodeVector
3860 /// ::= Element (',' Element)*
3862 /// ::= 'null' | TypeAndValue
3863 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3864 PerFunctionState *PFS) {
3865 // Check for an empty list.
3866 if (Lex.getKind() == lltok::rbrace)
3870 // Null is a special case since it is typeless.
3871 if (EatIfPresent(lltok::kw_null)) {
3877 PATypeHolder Ty(Type::getVoidTy(Context));
3879 if (ParseType(Ty) || ParseValID(ID, PFS) ||
3880 ConvertValIDToValue(Ty, ID, V, PFS))
3884 } while (EatIfPresent(lltok::comma));