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/ADT/StringExtras.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
30 /// Run: module ::= toplevelentity*
31 bool LLParser::Run() {
35 return ParseTopLevelEntities() ||
36 ValidateEndOfModule();
39 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
41 bool LLParser::ValidateEndOfModule() {
42 // Handle any instruction metadata forward references.
43 if (!ForwardRefInstMetadata.empty()) {
44 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
45 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
47 Instruction *Inst = I->first;
48 const std::vector<MDRef> &MDList = I->second;
50 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
51 unsigned SlotNo = MDList[i].MDSlot;
53 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
54 return Error(MDList[i].Loc, "use of undefined metadata '!" +
55 utostr(SlotNo) + "'");
56 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
59 ForwardRefInstMetadata.clear();
63 // Update auto-upgraded malloc calls to "malloc".
64 // FIXME: Remove in LLVM 3.0.
66 MallocF->setName("malloc");
67 // If setName() does not set the name to "malloc", then there is already a
68 // declaration of "malloc". In that case, iterate over all calls to MallocF
69 // and get them to call the declared "malloc" instead.
70 if (MallocF->getName() != "malloc") {
71 Constant *RealMallocF = M->getFunction("malloc");
72 if (RealMallocF->getType() != MallocF->getType())
73 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
74 MallocF->replaceAllUsesWith(RealMallocF);
75 MallocF->eraseFromParent();
81 // If there are entries in ForwardRefBlockAddresses at this point, they are
82 // references after the function was defined. Resolve those now.
83 while (!ForwardRefBlockAddresses.empty()) {
84 // Okay, we are referencing an already-parsed function, resolve them now.
86 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
87 if (Fn.Kind == ValID::t_GlobalName)
88 TheFn = M->getFunction(Fn.StrVal);
89 else if (Fn.UIntVal < NumberedVals.size())
90 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
93 return Error(Fn.Loc, "unknown function referenced by blockaddress");
95 // Resolve all these references.
96 if (ResolveForwardRefBlockAddresses(TheFn,
97 ForwardRefBlockAddresses.begin()->second,
101 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
105 if (!ForwardRefTypes.empty())
106 return Error(ForwardRefTypes.begin()->second.second,
107 "use of undefined type named '" +
108 ForwardRefTypes.begin()->first + "'");
109 if (!ForwardRefTypeIDs.empty())
110 return Error(ForwardRefTypeIDs.begin()->second.second,
111 "use of undefined type '%" +
112 utostr(ForwardRefTypeIDs.begin()->first) + "'");
114 if (!ForwardRefVals.empty())
115 return Error(ForwardRefVals.begin()->second.second,
116 "use of undefined value '@" + ForwardRefVals.begin()->first +
119 if (!ForwardRefValIDs.empty())
120 return Error(ForwardRefValIDs.begin()->second.second,
121 "use of undefined value '@" +
122 utostr(ForwardRefValIDs.begin()->first) + "'");
124 if (!ForwardRefMDNodes.empty())
125 return Error(ForwardRefMDNodes.begin()->second.second,
126 "use of undefined metadata '!" +
127 utostr(ForwardRefMDNodes.begin()->first) + "'");
130 // Look for intrinsic functions and CallInst that need to be upgraded
131 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
132 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
134 // Check debug info intrinsics.
135 CheckDebugInfoIntrinsics(M);
139 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
140 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
141 PerFunctionState *PFS) {
142 // Loop over all the references, resolving them.
143 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
146 if (Refs[i].first.Kind == ValID::t_LocalName)
147 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
149 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
150 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
151 return Error(Refs[i].first.Loc,
152 "cannot take address of numeric label after the function is defined");
154 Res = dyn_cast_or_null<BasicBlock>(
155 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
159 return Error(Refs[i].first.Loc,
160 "referenced value is not a basic block");
162 // Get the BlockAddress for this and update references to use it.
163 BlockAddress *BA = BlockAddress::get(TheFn, Res);
164 Refs[i].second->replaceAllUsesWith(BA);
165 Refs[i].second->eraseFromParent();
171 //===----------------------------------------------------------------------===//
172 // Top-Level Entities
173 //===----------------------------------------------------------------------===//
175 bool LLParser::ParseTopLevelEntities() {
177 switch (Lex.getKind()) {
178 default: return TokError("expected top-level entity");
179 case lltok::Eof: return false;
180 //case lltok::kw_define:
181 case lltok::kw_declare: if (ParseDeclare()) return true; break;
182 case lltok::kw_define: if (ParseDefine()) return true; break;
183 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
184 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
185 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
186 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
187 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
188 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
189 case lltok::LocalVar: if (ParseNamedType()) return true; break;
190 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
191 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
192 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
193 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
195 // The Global variable production with no name can have many different
196 // optional leading prefixes, the production is:
197 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
198 // OptionalAddrSpace ('constant'|'global') ...
199 case lltok::kw_private : // OptionalLinkage
200 case lltok::kw_linker_private: // OptionalLinkage
201 case lltok::kw_internal: // OptionalLinkage
202 case lltok::kw_weak: // OptionalLinkage
203 case lltok::kw_weak_odr: // OptionalLinkage
204 case lltok::kw_linkonce: // OptionalLinkage
205 case lltok::kw_linkonce_odr: // OptionalLinkage
206 case lltok::kw_appending: // OptionalLinkage
207 case lltok::kw_dllexport: // OptionalLinkage
208 case lltok::kw_common: // OptionalLinkage
209 case lltok::kw_dllimport: // OptionalLinkage
210 case lltok::kw_extern_weak: // OptionalLinkage
211 case lltok::kw_external: { // OptionalLinkage
212 unsigned Linkage, Visibility;
213 if (ParseOptionalLinkage(Linkage) ||
214 ParseOptionalVisibility(Visibility) ||
215 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
219 case lltok::kw_default: // OptionalVisibility
220 case lltok::kw_hidden: // OptionalVisibility
221 case lltok::kw_protected: { // OptionalVisibility
223 if (ParseOptionalVisibility(Visibility) ||
224 ParseGlobal("", SMLoc(), 0, false, Visibility))
229 case lltok::kw_thread_local: // OptionalThreadLocal
230 case lltok::kw_addrspace: // OptionalAddrSpace
231 case lltok::kw_constant: // GlobalType
232 case lltok::kw_global: // GlobalType
233 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
241 /// ::= 'module' 'asm' STRINGCONSTANT
242 bool LLParser::ParseModuleAsm() {
243 assert(Lex.getKind() == lltok::kw_module);
247 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
248 ParseStringConstant(AsmStr)) return true;
250 const std::string &AsmSoFar = M->getModuleInlineAsm();
251 if (AsmSoFar.empty())
252 M->setModuleInlineAsm(AsmStr);
254 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
259 /// ::= 'target' 'triple' '=' STRINGCONSTANT
260 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
261 bool LLParser::ParseTargetDefinition() {
262 assert(Lex.getKind() == lltok::kw_target);
265 default: return TokError("unknown target property");
266 case lltok::kw_triple:
268 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
269 ParseStringConstant(Str))
271 M->setTargetTriple(Str);
273 case lltok::kw_datalayout:
275 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
276 ParseStringConstant(Str))
278 M->setDataLayout(Str);
284 /// ::= 'deplibs' '=' '[' ']'
285 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
286 bool LLParser::ParseDepLibs() {
287 assert(Lex.getKind() == lltok::kw_deplibs);
289 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
290 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
293 if (EatIfPresent(lltok::rsquare))
297 if (ParseStringConstant(Str)) return true;
300 while (EatIfPresent(lltok::comma)) {
301 if (ParseStringConstant(Str)) return true;
305 return ParseToken(lltok::rsquare, "expected ']' at end of list");
308 /// ParseUnnamedType:
310 /// ::= LocalVarID '=' 'type' type
311 bool LLParser::ParseUnnamedType() {
312 unsigned TypeID = NumberedTypes.size();
314 // Handle the LocalVarID form.
315 if (Lex.getKind() == lltok::LocalVarID) {
316 if (Lex.getUIntVal() != TypeID)
317 return Error(Lex.getLoc(), "type expected to be numbered '%" +
318 utostr(TypeID) + "'");
319 Lex.Lex(); // eat LocalVarID;
321 if (ParseToken(lltok::equal, "expected '=' after name"))
325 assert(Lex.getKind() == lltok::kw_type);
326 LocTy TypeLoc = Lex.getLoc();
327 Lex.Lex(); // eat kw_type
329 PATypeHolder Ty(Type::getVoidTy(Context));
330 if (ParseType(Ty)) return true;
332 // See if this type was previously referenced.
333 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
334 FI = ForwardRefTypeIDs.find(TypeID);
335 if (FI != ForwardRefTypeIDs.end()) {
336 if (FI->second.first.get() == Ty)
337 return Error(TypeLoc, "self referential type is invalid");
339 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
340 Ty = FI->second.first.get();
341 ForwardRefTypeIDs.erase(FI);
344 NumberedTypes.push_back(Ty);
350 /// ::= LocalVar '=' 'type' type
351 bool LLParser::ParseNamedType() {
352 std::string Name = Lex.getStrVal();
353 LocTy NameLoc = Lex.getLoc();
354 Lex.Lex(); // eat LocalVar.
356 PATypeHolder Ty(Type::getVoidTy(Context));
358 if (ParseToken(lltok::equal, "expected '=' after name") ||
359 ParseToken(lltok::kw_type, "expected 'type' after name") ||
363 // Set the type name, checking for conflicts as we do so.
364 bool AlreadyExists = M->addTypeName(Name, Ty);
365 if (!AlreadyExists) return false;
367 // See if this type is a forward reference. We need to eagerly resolve
368 // types to allow recursive type redefinitions below.
369 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
370 FI = ForwardRefTypes.find(Name);
371 if (FI != ForwardRefTypes.end()) {
372 if (FI->second.first.get() == Ty)
373 return Error(NameLoc, "self referential type is invalid");
375 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
376 Ty = FI->second.first.get();
377 ForwardRefTypes.erase(FI);
380 // Inserting a name that is already defined, get the existing name.
381 const Type *Existing = M->getTypeByName(Name);
382 assert(Existing && "Conflict but no matching type?!");
384 // Otherwise, this is an attempt to redefine a type. That's okay if
385 // the redefinition is identical to the original.
386 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
387 if (Existing == Ty) return false;
389 // Any other kind of (non-equivalent) redefinition is an error.
390 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
391 Ty->getDescription() + "'");
396 /// ::= 'declare' FunctionHeader
397 bool LLParser::ParseDeclare() {
398 assert(Lex.getKind() == lltok::kw_declare);
402 return ParseFunctionHeader(F, false);
406 /// ::= 'define' FunctionHeader '{' ...
407 bool LLParser::ParseDefine() {
408 assert(Lex.getKind() == lltok::kw_define);
412 return ParseFunctionHeader(F, true) ||
413 ParseFunctionBody(*F);
419 bool LLParser::ParseGlobalType(bool &IsConstant) {
420 if (Lex.getKind() == lltok::kw_constant)
422 else if (Lex.getKind() == lltok::kw_global)
426 return TokError("expected 'global' or 'constant'");
432 /// ParseUnnamedGlobal:
433 /// OptionalVisibility ALIAS ...
434 /// OptionalLinkage OptionalVisibility ... -> global variable
435 /// GlobalID '=' OptionalVisibility ALIAS ...
436 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
437 bool LLParser::ParseUnnamedGlobal() {
438 unsigned VarID = NumberedVals.size();
440 LocTy NameLoc = Lex.getLoc();
442 // Handle the GlobalID form.
443 if (Lex.getKind() == lltok::GlobalID) {
444 if (Lex.getUIntVal() != VarID)
445 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
446 utostr(VarID) + "'");
447 Lex.Lex(); // eat GlobalID;
449 if (ParseToken(lltok::equal, "expected '=' after name"))
454 unsigned Linkage, Visibility;
455 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
456 ParseOptionalVisibility(Visibility))
459 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
460 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
461 return ParseAlias(Name, NameLoc, Visibility);
464 /// ParseNamedGlobal:
465 /// GlobalVar '=' OptionalVisibility ALIAS ...
466 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
467 bool LLParser::ParseNamedGlobal() {
468 assert(Lex.getKind() == lltok::GlobalVar);
469 LocTy NameLoc = Lex.getLoc();
470 std::string Name = Lex.getStrVal();
474 unsigned Linkage, Visibility;
475 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
476 ParseOptionalLinkage(Linkage, HasLinkage) ||
477 ParseOptionalVisibility(Visibility))
480 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
481 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
482 return ParseAlias(Name, NameLoc, Visibility);
486 // ::= '!' STRINGCONSTANT
487 bool LLParser::ParseMDString(MDString *&Result) {
489 if (ParseStringConstant(Str)) return true;
490 Result = MDString::get(Context, Str);
495 // ::= '!' MDNodeNumber
497 /// This version of ParseMDNodeID returns the slot number and null in the case
498 /// of a forward reference.
499 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
500 // !{ ..., !42, ... }
501 if (ParseUInt32(SlotNo)) return true;
503 // Check existing MDNode.
504 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
505 Result = NumberedMetadata[SlotNo];
511 bool LLParser::ParseMDNodeID(MDNode *&Result) {
512 // !{ ..., !42, ... }
514 if (ParseMDNodeID(Result, MID)) return true;
516 // If not a forward reference, just return it now.
517 if (Result) return false;
519 // Otherwise, create MDNode forward reference.
521 // FIXME: This is not unique enough!
522 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
523 Value *V = MDString::get(Context, FwdRefName);
524 MDNode *FwdNode = MDNode::get(Context, &V, 1);
525 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
527 if (NumberedMetadata.size() <= MID)
528 NumberedMetadata.resize(MID+1);
529 NumberedMetadata[MID] = FwdNode;
534 /// ParseNamedMetadata:
535 /// !foo = !{ !1, !2 }
536 bool LLParser::ParseNamedMetadata() {
537 assert(Lex.getKind() == lltok::MetadataVar);
538 std::string Name = Lex.getStrVal();
541 if (ParseToken(lltok::equal, "expected '=' here") ||
542 ParseToken(lltok::exclaim, "Expected '!' here") ||
543 ParseToken(lltok::lbrace, "Expected '{' here"))
546 SmallVector<MDNode *, 8> Elts;
548 // Null is a special case since it is typeless.
549 if (EatIfPresent(lltok::kw_null)) {
554 if (ParseToken(lltok::exclaim, "Expected '!' here"))
558 if (ParseMDNodeID(N)) return true;
560 } while (EatIfPresent(lltok::comma));
562 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
565 NamedMDNode::Create(Context, Name, Elts.data(), Elts.size(), M);
569 /// ParseStandaloneMetadata:
571 bool LLParser::ParseStandaloneMetadata() {
572 assert(Lex.getKind() == lltok::exclaim);
574 unsigned MetadataID = 0;
577 PATypeHolder Ty(Type::getVoidTy(Context));
578 SmallVector<Value *, 16> Elts;
579 if (ParseUInt32(MetadataID) ||
580 ParseToken(lltok::equal, "expected '=' here") ||
581 ParseType(Ty, TyLoc) ||
582 ParseToken(lltok::exclaim, "Expected '!' here") ||
583 ParseToken(lltok::lbrace, "Expected '{' here") ||
584 ParseMDNodeVector(Elts, NULL) ||
585 ParseToken(lltok::rbrace, "expected end of metadata node"))
588 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
590 // See if this was forward referenced, if so, handle it.
591 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
592 FI = ForwardRefMDNodes.find(MetadataID);
593 if (FI != ForwardRefMDNodes.end()) {
594 FI->second.first->replaceAllUsesWith(Init);
595 ForwardRefMDNodes.erase(FI);
597 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
599 if (MetadataID >= NumberedMetadata.size())
600 NumberedMetadata.resize(MetadataID+1);
602 if (NumberedMetadata[MetadataID] != 0)
603 return TokError("Metadata id is already used");
604 NumberedMetadata[MetadataID] = Init;
611 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
614 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
615 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
617 /// Everything through visibility has already been parsed.
619 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
620 unsigned Visibility) {
621 assert(Lex.getKind() == lltok::kw_alias);
624 LocTy LinkageLoc = Lex.getLoc();
625 if (ParseOptionalLinkage(Linkage))
628 if (Linkage != GlobalValue::ExternalLinkage &&
629 Linkage != GlobalValue::WeakAnyLinkage &&
630 Linkage != GlobalValue::WeakODRLinkage &&
631 Linkage != GlobalValue::InternalLinkage &&
632 Linkage != GlobalValue::PrivateLinkage &&
633 Linkage != GlobalValue::LinkerPrivateLinkage)
634 return Error(LinkageLoc, "invalid linkage type for alias");
637 LocTy AliaseeLoc = Lex.getLoc();
638 if (Lex.getKind() != lltok::kw_bitcast &&
639 Lex.getKind() != lltok::kw_getelementptr) {
640 if (ParseGlobalTypeAndValue(Aliasee)) return true;
642 // The bitcast dest type is not present, it is implied by the dest type.
644 if (ParseValID(ID)) return true;
645 if (ID.Kind != ValID::t_Constant)
646 return Error(AliaseeLoc, "invalid aliasee");
647 Aliasee = ID.ConstantVal;
650 if (!Aliasee->getType()->isPointerTy())
651 return Error(AliaseeLoc, "alias must have pointer type");
653 // Okay, create the alias but do not insert it into the module yet.
654 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
655 (GlobalValue::LinkageTypes)Linkage, Name,
657 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
659 // See if this value already exists in the symbol table. If so, it is either
660 // a redefinition or a definition of a forward reference.
661 if (GlobalValue *Val = M->getNamedValue(Name)) {
662 // See if this was a redefinition. If so, there is no entry in
664 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
665 I = ForwardRefVals.find(Name);
666 if (I == ForwardRefVals.end())
667 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
669 // Otherwise, this was a definition of forward ref. Verify that types
671 if (Val->getType() != GA->getType())
672 return Error(NameLoc,
673 "forward reference and definition of alias have different types");
675 // If they agree, just RAUW the old value with the alias and remove the
677 Val->replaceAllUsesWith(GA);
678 Val->eraseFromParent();
679 ForwardRefVals.erase(I);
682 // Insert into the module, we know its name won't collide now.
683 M->getAliasList().push_back(GA);
684 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
690 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
691 /// OptionalAddrSpace GlobalType Type Const
692 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
693 /// OptionalAddrSpace GlobalType Type Const
695 /// Everything through visibility has been parsed already.
697 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
698 unsigned Linkage, bool HasLinkage,
699 unsigned Visibility) {
701 bool ThreadLocal, IsConstant;
704 PATypeHolder Ty(Type::getVoidTy(Context));
705 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
706 ParseOptionalAddrSpace(AddrSpace) ||
707 ParseGlobalType(IsConstant) ||
708 ParseType(Ty, TyLoc))
711 // If the linkage is specified and is external, then no initializer is
714 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
715 Linkage != GlobalValue::ExternalWeakLinkage &&
716 Linkage != GlobalValue::ExternalLinkage)) {
717 if (ParseGlobalValue(Ty, Init))
721 if (Ty->isFunctionTy() || Ty->isLabelTy())
722 return Error(TyLoc, "invalid type for global variable");
724 GlobalVariable *GV = 0;
726 // See if the global was forward referenced, if so, use the global.
728 if (GlobalValue *GVal = M->getNamedValue(Name)) {
729 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
730 return Error(NameLoc, "redefinition of global '@" + Name + "'");
731 GV = cast<GlobalVariable>(GVal);
734 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
735 I = ForwardRefValIDs.find(NumberedVals.size());
736 if (I != ForwardRefValIDs.end()) {
737 GV = cast<GlobalVariable>(I->second.first);
738 ForwardRefValIDs.erase(I);
743 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
744 Name, 0, false, AddrSpace);
746 if (GV->getType()->getElementType() != Ty)
748 "forward reference and definition of global have different types");
750 // Move the forward-reference to the correct spot in the module.
751 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
755 NumberedVals.push_back(GV);
757 // Set the parsed properties on the global.
759 GV->setInitializer(Init);
760 GV->setConstant(IsConstant);
761 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
762 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
763 GV->setThreadLocal(ThreadLocal);
765 // Parse attributes on the global.
766 while (Lex.getKind() == lltok::comma) {
769 if (Lex.getKind() == lltok::kw_section) {
771 GV->setSection(Lex.getStrVal());
772 if (ParseToken(lltok::StringConstant, "expected global section string"))
774 } else if (Lex.getKind() == lltok::kw_align) {
776 if (ParseOptionalAlignment(Alignment)) return true;
777 GV->setAlignment(Alignment);
779 TokError("unknown global variable property!");
787 //===----------------------------------------------------------------------===//
788 // GlobalValue Reference/Resolution Routines.
789 //===----------------------------------------------------------------------===//
791 /// GetGlobalVal - Get a value with the specified name or ID, creating a
792 /// forward reference record if needed. This can return null if the value
793 /// exists but does not have the right type.
794 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
796 const PointerType *PTy = dyn_cast<PointerType>(Ty);
798 Error(Loc, "global variable reference must have pointer type");
802 // Look this name up in the normal function symbol table.
804 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
806 // If this is a forward reference for the value, see if we already created a
807 // forward ref record.
809 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
810 I = ForwardRefVals.find(Name);
811 if (I != ForwardRefVals.end())
812 Val = I->second.first;
815 // If we have the value in the symbol table or fwd-ref table, return it.
817 if (Val->getType() == Ty) return Val;
818 Error(Loc, "'@" + Name + "' defined with type '" +
819 Val->getType()->getDescription() + "'");
823 // Otherwise, create a new forward reference for this value and remember it.
825 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
826 // Function types can return opaque but functions can't.
827 if (FT->getReturnType()->isOpaqueTy()) {
828 Error(Loc, "function may not return opaque type");
832 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
834 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
835 GlobalValue::ExternalWeakLinkage, 0, Name);
838 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
842 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
843 const PointerType *PTy = dyn_cast<PointerType>(Ty);
845 Error(Loc, "global variable reference must have pointer type");
849 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
851 // If this is a forward reference for the value, see if we already created a
852 // forward ref record.
854 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
855 I = ForwardRefValIDs.find(ID);
856 if (I != ForwardRefValIDs.end())
857 Val = I->second.first;
860 // If we have the value in the symbol table or fwd-ref table, return it.
862 if (Val->getType() == Ty) return Val;
863 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
864 Val->getType()->getDescription() + "'");
868 // Otherwise, create a new forward reference for this value and remember it.
870 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
871 // Function types can return opaque but functions can't.
872 if (FT->getReturnType()->isOpaqueTy()) {
873 Error(Loc, "function may not return opaque type");
876 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
878 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
879 GlobalValue::ExternalWeakLinkage, 0, "");
882 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
887 //===----------------------------------------------------------------------===//
889 //===----------------------------------------------------------------------===//
891 /// ParseToken - If the current token has the specified kind, eat it and return
892 /// success. Otherwise, emit the specified error and return failure.
893 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
894 if (Lex.getKind() != T)
895 return TokError(ErrMsg);
900 /// ParseStringConstant
901 /// ::= StringConstant
902 bool LLParser::ParseStringConstant(std::string &Result) {
903 if (Lex.getKind() != lltok::StringConstant)
904 return TokError("expected string constant");
905 Result = Lex.getStrVal();
912 bool LLParser::ParseUInt32(unsigned &Val) {
913 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
914 return TokError("expected integer");
915 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
916 if (Val64 != unsigned(Val64))
917 return TokError("expected 32-bit integer (too large)");
924 /// ParseOptionalAddrSpace
926 /// := 'addrspace' '(' uint32 ')'
927 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
929 if (!EatIfPresent(lltok::kw_addrspace))
931 return ParseToken(lltok::lparen, "expected '(' in address space") ||
932 ParseUInt32(AddrSpace) ||
933 ParseToken(lltok::rparen, "expected ')' in address space");
936 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
937 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
938 /// 2: function attr.
939 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
940 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
941 Attrs = Attribute::None;
942 LocTy AttrLoc = Lex.getLoc();
945 switch (Lex.getKind()) {
948 // Treat these as signext/zeroext if they occur in the argument list after
949 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
950 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
952 // FIXME: REMOVE THIS IN LLVM 3.0
954 if (Lex.getKind() == lltok::kw_sext)
955 Attrs |= Attribute::SExt;
957 Attrs |= Attribute::ZExt;
961 default: // End of attributes.
962 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
963 return Error(AttrLoc, "invalid use of function-only attribute");
965 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
966 return Error(AttrLoc, "invalid use of parameter-only attribute");
969 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
970 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
971 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
972 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
973 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
974 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
975 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
976 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
978 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
979 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
980 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
981 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
982 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
983 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
984 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
985 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
986 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
987 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
988 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
989 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
990 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
992 case lltok::kw_alignstack: {
994 if (ParseOptionalStackAlignment(Alignment))
996 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
1000 case lltok::kw_align: {
1002 if (ParseOptionalAlignment(Alignment))
1004 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1013 /// ParseOptionalLinkage
1016 /// ::= 'linker_private'
1021 /// ::= 'linkonce_odr'
1026 /// ::= 'extern_weak'
1028 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1030 switch (Lex.getKind()) {
1031 default: Res=GlobalValue::ExternalLinkage; return false;
1032 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1033 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1034 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1035 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1036 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1037 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1038 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1039 case lltok::kw_available_externally:
1040 Res = GlobalValue::AvailableExternallyLinkage;
1042 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1043 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1044 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1045 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1046 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1047 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1054 /// ParseOptionalVisibility
1060 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1061 switch (Lex.getKind()) {
1062 default: Res = GlobalValue::DefaultVisibility; return false;
1063 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1064 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1065 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1071 /// ParseOptionalCallingConv
1076 /// ::= 'x86_stdcallcc'
1077 /// ::= 'x86_fastcallcc'
1078 /// ::= 'arm_apcscc'
1079 /// ::= 'arm_aapcscc'
1080 /// ::= 'arm_aapcs_vfpcc'
1081 /// ::= 'msp430_intrcc'
1084 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1085 switch (Lex.getKind()) {
1086 default: CC = CallingConv::C; return false;
1087 case lltok::kw_ccc: CC = CallingConv::C; break;
1088 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1089 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1090 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1091 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1092 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1093 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1094 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1095 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1096 case lltok::kw_cc: {
1097 unsigned ArbitraryCC;
1099 if (ParseUInt32(ArbitraryCC)) {
1102 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1112 /// ParseInstructionMetadata
1113 /// ::= !dbg !42 (',' !dbg !57)*
1114 bool LLParser::ParseInstructionMetadata(Instruction *Inst) {
1116 if (Lex.getKind() != lltok::MetadataVar)
1117 return TokError("expected metadata after comma");
1119 std::string Name = Lex.getStrVal();
1124 SMLoc Loc = Lex.getLoc();
1125 if (ParseToken(lltok::exclaim, "expected '!' here") ||
1126 ParseMDNodeID(Node, NodeID))
1129 unsigned MDK = M->getMDKindID(Name.c_str());
1131 // If we got the node, add it to the instruction.
1132 Inst->setMetadata(MDK, Node);
1134 MDRef R = { Loc, MDK, NodeID };
1135 // Otherwise, remember that this should be resolved later.
1136 ForwardRefInstMetadata[Inst].push_back(R);
1139 // If this is the end of the list, we're done.
1140 } while (EatIfPresent(lltok::comma));
1144 /// ParseOptionalAlignment
1147 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1149 if (!EatIfPresent(lltok::kw_align))
1151 LocTy AlignLoc = Lex.getLoc();
1152 if (ParseUInt32(Alignment)) return true;
1153 if (!isPowerOf2_32(Alignment))
1154 return Error(AlignLoc, "alignment is not a power of two");
1158 /// ParseOptionalCommaAlign
1162 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1164 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1165 bool &AteExtraComma) {
1166 AteExtraComma = false;
1167 while (EatIfPresent(lltok::comma)) {
1168 // Metadata at the end is an early exit.
1169 if (Lex.getKind() == lltok::MetadataVar) {
1170 AteExtraComma = true;
1174 if (Lex.getKind() == lltok::kw_align) {
1175 if (ParseOptionalAlignment(Alignment)) return true;
1183 /// ParseOptionalStackAlignment
1185 /// ::= 'alignstack' '(' 4 ')'
1186 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1188 if (!EatIfPresent(lltok::kw_alignstack))
1190 LocTy ParenLoc = Lex.getLoc();
1191 if (!EatIfPresent(lltok::lparen))
1192 return Error(ParenLoc, "expected '('");
1193 LocTy AlignLoc = Lex.getLoc();
1194 if (ParseUInt32(Alignment)) return true;
1195 ParenLoc = Lex.getLoc();
1196 if (!EatIfPresent(lltok::rparen))
1197 return Error(ParenLoc, "expected ')'");
1198 if (!isPowerOf2_32(Alignment))
1199 return Error(AlignLoc, "stack alignment is not a power of two");
1203 /// ParseIndexList - This parses the index list for an insert/extractvalue
1204 /// instruction. This sets AteExtraComma in the case where we eat an extra
1205 /// comma at the end of the line and find that it is followed by metadata.
1206 /// Clients that don't allow metadata can call the version of this function that
1207 /// only takes one argument.
1210 /// ::= (',' uint32)+
1212 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1213 bool &AteExtraComma) {
1214 AteExtraComma = false;
1216 if (Lex.getKind() != lltok::comma)
1217 return TokError("expected ',' as start of index list");
1219 while (EatIfPresent(lltok::comma)) {
1220 if (Lex.getKind() == lltok::MetadataVar) {
1221 AteExtraComma = true;
1225 if (ParseUInt32(Idx)) return true;
1226 Indices.push_back(Idx);
1232 //===----------------------------------------------------------------------===//
1234 //===----------------------------------------------------------------------===//
1236 /// ParseType - Parse and resolve a full type.
1237 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1238 LocTy TypeLoc = Lex.getLoc();
1239 if (ParseTypeRec(Result)) return true;
1241 // Verify no unresolved uprefs.
1242 if (!UpRefs.empty())
1243 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1245 if (!AllowVoid && Result.get()->isVoidTy())
1246 return Error(TypeLoc, "void type only allowed for function results");
1251 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1252 /// called. It loops through the UpRefs vector, which is a list of the
1253 /// currently active types. For each type, if the up-reference is contained in
1254 /// the newly completed type, we decrement the level count. When the level
1255 /// count reaches zero, the up-referenced type is the type that is passed in:
1256 /// thus we can complete the cycle.
1258 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1259 // If Ty isn't abstract, or if there are no up-references in it, then there is
1260 // nothing to resolve here.
1261 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1263 PATypeHolder Ty(ty);
1265 dbgs() << "Type '" << Ty->getDescription()
1266 << "' newly formed. Resolving upreferences.\n"
1267 << UpRefs.size() << " upreferences active!\n";
1270 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1271 // to zero), we resolve them all together before we resolve them to Ty. At
1272 // the end of the loop, if there is anything to resolve to Ty, it will be in
1274 OpaqueType *TypeToResolve = 0;
1276 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1277 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1279 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1280 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1283 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1284 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1285 << (ContainsType ? "true" : "false")
1286 << " level=" << UpRefs[i].NestingLevel << "\n";
1291 // Decrement level of upreference
1292 unsigned Level = --UpRefs[i].NestingLevel;
1293 UpRefs[i].LastContainedTy = Ty;
1295 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1300 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1303 TypeToResolve = UpRefs[i].UpRefTy;
1305 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1306 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1307 --i; // Do not skip the next element.
1311 TypeToResolve->refineAbstractTypeTo(Ty);
1317 /// ParseTypeRec - The recursive function used to process the internal
1318 /// implementation details of types.
1319 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1320 switch (Lex.getKind()) {
1322 return TokError("expected type");
1324 // TypeRec ::= 'float' | 'void' (etc)
1325 Result = Lex.getTyVal();
1328 case lltok::kw_opaque:
1329 // TypeRec ::= 'opaque'
1330 Result = OpaqueType::get(Context);
1334 // TypeRec ::= '{' ... '}'
1335 if (ParseStructType(Result, false))
1338 case lltok::kw_union:
1339 // TypeRec ::= 'union' '{' ... '}'
1340 if (ParseUnionType(Result))
1343 case lltok::lsquare:
1344 // TypeRec ::= '[' ... ']'
1345 Lex.Lex(); // eat the lsquare.
1346 if (ParseArrayVectorType(Result, false))
1349 case lltok::less: // Either vector or packed struct.
1350 // TypeRec ::= '<' ... '>'
1352 if (Lex.getKind() == lltok::lbrace) {
1353 if (ParseStructType(Result, true) ||
1354 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1356 } else if (ParseArrayVectorType(Result, true))
1359 case lltok::LocalVar:
1360 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1362 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1365 Result = OpaqueType::get(Context);
1366 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1367 std::make_pair(Result,
1369 M->addTypeName(Lex.getStrVal(), Result.get());
1374 case lltok::LocalVarID:
1376 if (Lex.getUIntVal() < NumberedTypes.size())
1377 Result = NumberedTypes[Lex.getUIntVal()];
1379 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1380 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1381 if (I != ForwardRefTypeIDs.end())
1382 Result = I->second.first;
1384 Result = OpaqueType::get(Context);
1385 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1386 std::make_pair(Result,
1392 case lltok::backslash: {
1393 // TypeRec ::= '\' 4
1396 if (ParseUInt32(Val)) return true;
1397 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1398 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1404 // Parse the type suffixes.
1406 switch (Lex.getKind()) {
1408 default: return false;
1410 // TypeRec ::= TypeRec '*'
1412 if (Result.get()->isLabelTy())
1413 return TokError("basic block pointers are invalid");
1414 if (Result.get()->isVoidTy())
1415 return TokError("pointers to void are invalid; use i8* instead");
1416 if (!PointerType::isValidElementType(Result.get()))
1417 return TokError("pointer to this type is invalid");
1418 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1422 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1423 case lltok::kw_addrspace: {
1424 if (Result.get()->isLabelTy())
1425 return TokError("basic block pointers are invalid");
1426 if (Result.get()->isVoidTy())
1427 return TokError("pointers to void are invalid; use i8* instead");
1428 if (!PointerType::isValidElementType(Result.get()))
1429 return TokError("pointer to this type is invalid");
1431 if (ParseOptionalAddrSpace(AddrSpace) ||
1432 ParseToken(lltok::star, "expected '*' in address space"))
1435 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1439 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1441 if (ParseFunctionType(Result))
1448 /// ParseParameterList
1450 /// ::= '(' Arg (',' Arg)* ')'
1452 /// ::= Type OptionalAttributes Value OptionalAttributes
1453 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1454 PerFunctionState &PFS) {
1455 if (ParseToken(lltok::lparen, "expected '(' in call"))
1458 while (Lex.getKind() != lltok::rparen) {
1459 // If this isn't the first argument, we need a comma.
1460 if (!ArgList.empty() &&
1461 ParseToken(lltok::comma, "expected ',' in argument list"))
1464 // Parse the argument.
1466 PATypeHolder ArgTy(Type::getVoidTy(Context));
1467 unsigned ArgAttrs1 = Attribute::None;
1468 unsigned ArgAttrs2 = Attribute::None;
1470 if (ParseType(ArgTy, ArgLoc))
1473 // Otherwise, handle normal operands.
1474 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1475 ParseValue(ArgTy, V, PFS) ||
1476 // FIXME: Should not allow attributes after the argument, remove this
1478 ParseOptionalAttrs(ArgAttrs2, 3))
1480 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1483 Lex.Lex(); // Lex the ')'.
1489 /// ParseArgumentList - Parse the argument list for a function type or function
1490 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1491 /// ::= '(' ArgTypeListI ')'
1495 /// ::= ArgTypeList ',' '...'
1496 /// ::= ArgType (',' ArgType)*
1498 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1499 bool &isVarArg, bool inType) {
1501 assert(Lex.getKind() == lltok::lparen);
1502 Lex.Lex(); // eat the (.
1504 if (Lex.getKind() == lltok::rparen) {
1506 } else if (Lex.getKind() == lltok::dotdotdot) {
1510 LocTy TypeLoc = Lex.getLoc();
1511 PATypeHolder ArgTy(Type::getVoidTy(Context));
1515 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1516 // types (such as a function returning a pointer to itself). If parsing a
1517 // function prototype, we require fully resolved types.
1518 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1519 ParseOptionalAttrs(Attrs, 0)) return true;
1521 if (ArgTy->isVoidTy())
1522 return Error(TypeLoc, "argument can not have void type");
1524 if (Lex.getKind() == lltok::LocalVar ||
1525 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1526 Name = Lex.getStrVal();
1530 if (!FunctionType::isValidArgumentType(ArgTy))
1531 return Error(TypeLoc, "invalid type for function argument");
1533 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1535 while (EatIfPresent(lltok::comma)) {
1536 // Handle ... at end of arg list.
1537 if (EatIfPresent(lltok::dotdotdot)) {
1542 // Otherwise must be an argument type.
1543 TypeLoc = Lex.getLoc();
1544 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1545 ParseOptionalAttrs(Attrs, 0)) return true;
1547 if (ArgTy->isVoidTy())
1548 return Error(TypeLoc, "argument can not have void type");
1550 if (Lex.getKind() == lltok::LocalVar ||
1551 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1552 Name = Lex.getStrVal();
1558 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
1559 return Error(TypeLoc, "invalid type for function argument");
1561 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1565 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1568 /// ParseFunctionType
1569 /// ::= Type ArgumentList OptionalAttrs
1570 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1571 assert(Lex.getKind() == lltok::lparen);
1573 if (!FunctionType::isValidReturnType(Result))
1574 return TokError("invalid function return type");
1576 std::vector<ArgInfo> ArgList;
1579 if (ParseArgumentList(ArgList, isVarArg, true) ||
1580 // FIXME: Allow, but ignore attributes on function types!
1581 // FIXME: Remove in LLVM 3.0
1582 ParseOptionalAttrs(Attrs, 2))
1585 // Reject names on the arguments lists.
1586 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1587 if (!ArgList[i].Name.empty())
1588 return Error(ArgList[i].Loc, "argument name invalid in function type");
1589 if (!ArgList[i].Attrs != 0) {
1590 // Allow but ignore attributes on function types; this permits
1592 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1596 std::vector<const Type*> ArgListTy;
1597 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1598 ArgListTy.push_back(ArgList[i].Type);
1600 Result = HandleUpRefs(FunctionType::get(Result.get(),
1601 ArgListTy, isVarArg));
1605 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1608 /// ::= '{' TypeRec (',' TypeRec)* '}'
1609 /// ::= '<' '{' '}' '>'
1610 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1611 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1612 assert(Lex.getKind() == lltok::lbrace);
1613 Lex.Lex(); // Consume the '{'
1615 if (EatIfPresent(lltok::rbrace)) {
1616 Result = StructType::get(Context, Packed);
1620 std::vector<PATypeHolder> ParamsList;
1621 LocTy EltTyLoc = Lex.getLoc();
1622 if (ParseTypeRec(Result)) return true;
1623 ParamsList.push_back(Result);
1625 if (Result->isVoidTy())
1626 return Error(EltTyLoc, "struct element can not have void type");
1627 if (!StructType::isValidElementType(Result))
1628 return Error(EltTyLoc, "invalid element type for struct");
1630 while (EatIfPresent(lltok::comma)) {
1631 EltTyLoc = Lex.getLoc();
1632 if (ParseTypeRec(Result)) return true;
1634 if (Result->isVoidTy())
1635 return Error(EltTyLoc, "struct element can not have void type");
1636 if (!StructType::isValidElementType(Result))
1637 return Error(EltTyLoc, "invalid element type for struct");
1639 ParamsList.push_back(Result);
1642 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1645 std::vector<const Type*> ParamsListTy;
1646 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1647 ParamsListTy.push_back(ParamsList[i].get());
1648 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1654 /// ::= 'union' '{' TypeRec (',' TypeRec)* '}'
1655 bool LLParser::ParseUnionType(PATypeHolder &Result) {
1656 assert(Lex.getKind() == lltok::kw_union);
1657 Lex.Lex(); // Consume the 'union'
1659 if (ParseToken(lltok::lbrace, "'{' expected after 'union'")) return true;
1661 SmallVector<PATypeHolder, 8> ParamsList;
1663 LocTy EltTyLoc = Lex.getLoc();
1664 if (ParseTypeRec(Result)) return true;
1665 ParamsList.push_back(Result);
1667 if (Result->isVoidTy())
1668 return Error(EltTyLoc, "union element can not have void type");
1669 if (!UnionType::isValidElementType(Result))
1670 return Error(EltTyLoc, "invalid element type for union");
1672 } while (EatIfPresent(lltok::comma)) ;
1674 if (ParseToken(lltok::rbrace, "expected '}' at end of union"))
1677 SmallVector<const Type*, 8> ParamsListTy;
1678 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1679 ParamsListTy.push_back(ParamsList[i].get());
1680 Result = HandleUpRefs(UnionType::get(&ParamsListTy[0], ParamsListTy.size()));
1684 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1685 /// token has already been consumed.
1687 /// ::= '[' APSINTVAL 'x' Types ']'
1688 /// ::= '<' APSINTVAL 'x' Types '>'
1689 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1690 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1691 Lex.getAPSIntVal().getBitWidth() > 64)
1692 return TokError("expected number in address space");
1694 LocTy SizeLoc = Lex.getLoc();
1695 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1698 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1701 LocTy TypeLoc = Lex.getLoc();
1702 PATypeHolder EltTy(Type::getVoidTy(Context));
1703 if (ParseTypeRec(EltTy)) return true;
1705 if (EltTy->isVoidTy())
1706 return Error(TypeLoc, "array and vector element type cannot be void");
1708 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1709 "expected end of sequential type"))
1714 return Error(SizeLoc, "zero element vector is illegal");
1715 if ((unsigned)Size != Size)
1716 return Error(SizeLoc, "size too large for vector");
1717 if (!VectorType::isValidElementType(EltTy))
1718 return Error(TypeLoc, "vector element type must be fp or integer");
1719 Result = VectorType::get(EltTy, unsigned(Size));
1721 if (!ArrayType::isValidElementType(EltTy))
1722 return Error(TypeLoc, "invalid array element type");
1723 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1728 //===----------------------------------------------------------------------===//
1729 // Function Semantic Analysis.
1730 //===----------------------------------------------------------------------===//
1732 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1734 : P(p), F(f), FunctionNumber(functionNumber) {
1736 // Insert unnamed arguments into the NumberedVals list.
1737 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1740 NumberedVals.push_back(AI);
1743 LLParser::PerFunctionState::~PerFunctionState() {
1744 // If there were any forward referenced non-basicblock values, delete them.
1745 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1746 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1747 if (!isa<BasicBlock>(I->second.first)) {
1748 I->second.first->replaceAllUsesWith(
1749 UndefValue::get(I->second.first->getType()));
1750 delete I->second.first;
1751 I->second.first = 0;
1754 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1755 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1756 if (!isa<BasicBlock>(I->second.first)) {
1757 I->second.first->replaceAllUsesWith(
1758 UndefValue::get(I->second.first->getType()));
1759 delete I->second.first;
1760 I->second.first = 0;
1764 bool LLParser::PerFunctionState::FinishFunction() {
1765 // Check to see if someone took the address of labels in this block.
1766 if (!P.ForwardRefBlockAddresses.empty()) {
1768 if (!F.getName().empty()) {
1769 FunctionID.Kind = ValID::t_GlobalName;
1770 FunctionID.StrVal = F.getName();
1772 FunctionID.Kind = ValID::t_GlobalID;
1773 FunctionID.UIntVal = FunctionNumber;
1776 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1777 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1778 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1779 // Resolve all these references.
1780 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1783 P.ForwardRefBlockAddresses.erase(FRBAI);
1787 if (!ForwardRefVals.empty())
1788 return P.Error(ForwardRefVals.begin()->second.second,
1789 "use of undefined value '%" + ForwardRefVals.begin()->first +
1791 if (!ForwardRefValIDs.empty())
1792 return P.Error(ForwardRefValIDs.begin()->second.second,
1793 "use of undefined value '%" +
1794 utostr(ForwardRefValIDs.begin()->first) + "'");
1799 /// GetVal - Get a value with the specified name or ID, creating a
1800 /// forward reference record if needed. This can return null if the value
1801 /// exists but does not have the right type.
1802 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1803 const Type *Ty, LocTy Loc) {
1804 // Look this name up in the normal function symbol table.
1805 Value *Val = F.getValueSymbolTable().lookup(Name);
1807 // If this is a forward reference for the value, see if we already created a
1808 // forward ref record.
1810 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1811 I = ForwardRefVals.find(Name);
1812 if (I != ForwardRefVals.end())
1813 Val = I->second.first;
1816 // If we have the value in the symbol table or fwd-ref table, return it.
1818 if (Val->getType() == Ty) return Val;
1819 if (Ty->isLabelTy())
1820 P.Error(Loc, "'%" + Name + "' is not a basic block");
1822 P.Error(Loc, "'%" + Name + "' defined with type '" +
1823 Val->getType()->getDescription() + "'");
1827 // Don't make placeholders with invalid type.
1828 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1829 P.Error(Loc, "invalid use of a non-first-class type");
1833 // Otherwise, create a new forward reference for this value and remember it.
1835 if (Ty->isLabelTy())
1836 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1838 FwdVal = new Argument(Ty, Name);
1840 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1844 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1846 // Look this name up in the normal function symbol table.
1847 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1849 // If this is a forward reference for the value, see if we already created a
1850 // forward ref record.
1852 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1853 I = ForwardRefValIDs.find(ID);
1854 if (I != ForwardRefValIDs.end())
1855 Val = I->second.first;
1858 // If we have the value in the symbol table or fwd-ref table, return it.
1860 if (Val->getType() == Ty) return Val;
1861 if (Ty->isLabelTy())
1862 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1864 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1865 Val->getType()->getDescription() + "'");
1869 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1870 P.Error(Loc, "invalid use of a non-first-class type");
1874 // Otherwise, create a new forward reference for this value and remember it.
1876 if (Ty->isLabelTy())
1877 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1879 FwdVal = new Argument(Ty);
1881 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1885 /// SetInstName - After an instruction is parsed and inserted into its
1886 /// basic block, this installs its name.
1887 bool LLParser::PerFunctionState::SetInstName(int NameID,
1888 const std::string &NameStr,
1889 LocTy NameLoc, Instruction *Inst) {
1890 // If this instruction has void type, it cannot have a name or ID specified.
1891 if (Inst->getType()->isVoidTy()) {
1892 if (NameID != -1 || !NameStr.empty())
1893 return P.Error(NameLoc, "instructions returning void cannot have a name");
1897 // If this was a numbered instruction, verify that the instruction is the
1898 // expected value and resolve any forward references.
1899 if (NameStr.empty()) {
1900 // If neither a name nor an ID was specified, just use the next ID.
1902 NameID = NumberedVals.size();
1904 if (unsigned(NameID) != NumberedVals.size())
1905 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1906 utostr(NumberedVals.size()) + "'");
1908 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1909 ForwardRefValIDs.find(NameID);
1910 if (FI != ForwardRefValIDs.end()) {
1911 if (FI->second.first->getType() != Inst->getType())
1912 return P.Error(NameLoc, "instruction forward referenced with type '" +
1913 FI->second.first->getType()->getDescription() + "'");
1914 FI->second.first->replaceAllUsesWith(Inst);
1915 delete FI->second.first;
1916 ForwardRefValIDs.erase(FI);
1919 NumberedVals.push_back(Inst);
1923 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1924 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1925 FI = ForwardRefVals.find(NameStr);
1926 if (FI != ForwardRefVals.end()) {
1927 if (FI->second.first->getType() != Inst->getType())
1928 return P.Error(NameLoc, "instruction forward referenced with type '" +
1929 FI->second.first->getType()->getDescription() + "'");
1930 FI->second.first->replaceAllUsesWith(Inst);
1931 delete FI->second.first;
1932 ForwardRefVals.erase(FI);
1935 // Set the name on the instruction.
1936 Inst->setName(NameStr);
1938 if (Inst->getNameStr() != NameStr)
1939 return P.Error(NameLoc, "multiple definition of local value named '" +
1944 /// GetBB - Get a basic block with the specified name or ID, creating a
1945 /// forward reference record if needed.
1946 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1948 return cast_or_null<BasicBlock>(GetVal(Name,
1949 Type::getLabelTy(F.getContext()), Loc));
1952 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1953 return cast_or_null<BasicBlock>(GetVal(ID,
1954 Type::getLabelTy(F.getContext()), Loc));
1957 /// DefineBB - Define the specified basic block, which is either named or
1958 /// unnamed. If there is an error, this returns null otherwise it returns
1959 /// the block being defined.
1960 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1964 BB = GetBB(NumberedVals.size(), Loc);
1966 BB = GetBB(Name, Loc);
1967 if (BB == 0) return 0; // Already diagnosed error.
1969 // Move the block to the end of the function. Forward ref'd blocks are
1970 // inserted wherever they happen to be referenced.
1971 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1973 // Remove the block from forward ref sets.
1975 ForwardRefValIDs.erase(NumberedVals.size());
1976 NumberedVals.push_back(BB);
1978 // BB forward references are already in the function symbol table.
1979 ForwardRefVals.erase(Name);
1985 //===----------------------------------------------------------------------===//
1987 //===----------------------------------------------------------------------===//
1989 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1990 /// type implied. For example, if we parse "4" we don't know what integer type
1991 /// it has. The value will later be combined with its type and checked for
1992 /// sanity. PFS is used to convert function-local operands of metadata (since
1993 /// metadata operands are not just parsed here but also converted to values).
1994 /// PFS can be null when we are not parsing metadata values inside a function.
1995 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1996 ID.Loc = Lex.getLoc();
1997 switch (Lex.getKind()) {
1998 default: return TokError("expected value token");
1999 case lltok::GlobalID: // @42
2000 ID.UIntVal = Lex.getUIntVal();
2001 ID.Kind = ValID::t_GlobalID;
2003 case lltok::GlobalVar: // @foo
2004 ID.StrVal = Lex.getStrVal();
2005 ID.Kind = ValID::t_GlobalName;
2007 case lltok::LocalVarID: // %42
2008 ID.UIntVal = Lex.getUIntVal();
2009 ID.Kind = ValID::t_LocalID;
2011 case lltok::LocalVar: // %foo
2012 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2013 ID.StrVal = Lex.getStrVal();
2014 ID.Kind = ValID::t_LocalName;
2016 case lltok::exclaim: // !{...} MDNode, !"foo" MDString
2019 if (EatIfPresent(lltok::lbrace)) {
2020 SmallVector<Value*, 16> Elts;
2021 if (ParseMDNodeVector(Elts, PFS) ||
2022 ParseToken(lltok::rbrace, "expected end of metadata node"))
2025 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2026 ID.Kind = ValID::t_MDNode;
2030 // Standalone metadata reference
2031 // !{ ..., !42, ... }
2032 if (Lex.getKind() == lltok::APSInt) {
2033 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2034 ID.Kind = ValID::t_MDNode;
2039 // ::= '!' STRINGCONSTANT
2040 if (ParseMDString(ID.MDStringVal)) return true;
2041 ID.Kind = ValID::t_MDString;
2044 ID.APSIntVal = Lex.getAPSIntVal();
2045 ID.Kind = ValID::t_APSInt;
2047 case lltok::APFloat:
2048 ID.APFloatVal = Lex.getAPFloatVal();
2049 ID.Kind = ValID::t_APFloat;
2051 case lltok::kw_true:
2052 ID.ConstantVal = ConstantInt::getTrue(Context);
2053 ID.Kind = ValID::t_Constant;
2055 case lltok::kw_false:
2056 ID.ConstantVal = ConstantInt::getFalse(Context);
2057 ID.Kind = ValID::t_Constant;
2059 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2060 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2061 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2063 case lltok::lbrace: {
2064 // ValID ::= '{' ConstVector '}'
2066 SmallVector<Constant*, 16> Elts;
2067 if (ParseGlobalValueVector(Elts) ||
2068 ParseToken(lltok::rbrace, "expected end of struct constant"))
2071 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2072 Elts.size(), false);
2073 ID.Kind = ValID::t_Constant;
2077 // ValID ::= '<' ConstVector '>' --> Vector.
2078 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2080 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2082 SmallVector<Constant*, 16> Elts;
2083 LocTy FirstEltLoc = Lex.getLoc();
2084 if (ParseGlobalValueVector(Elts) ||
2086 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2087 ParseToken(lltok::greater, "expected end of constant"))
2090 if (isPackedStruct) {
2092 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
2093 ID.Kind = ValID::t_Constant;
2098 return Error(ID.Loc, "constant vector must not be empty");
2100 if (!Elts[0]->getType()->isIntegerTy() &&
2101 !Elts[0]->getType()->isFloatingPointTy())
2102 return Error(FirstEltLoc,
2103 "vector elements must have integer or floating point type");
2105 // Verify that all the vector elements have the same type.
2106 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2107 if (Elts[i]->getType() != Elts[0]->getType())
2108 return Error(FirstEltLoc,
2109 "vector element #" + utostr(i) +
2110 " is not of type '" + Elts[0]->getType()->getDescription());
2112 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
2113 ID.Kind = ValID::t_Constant;
2116 case lltok::lsquare: { // Array Constant
2118 SmallVector<Constant*, 16> Elts;
2119 LocTy FirstEltLoc = Lex.getLoc();
2120 if (ParseGlobalValueVector(Elts) ||
2121 ParseToken(lltok::rsquare, "expected end of array constant"))
2124 // Handle empty element.
2126 // Use undef instead of an array because it's inconvenient to determine
2127 // the element type at this point, there being no elements to examine.
2128 ID.Kind = ValID::t_EmptyArray;
2132 if (!Elts[0]->getType()->isFirstClassType())
2133 return Error(FirstEltLoc, "invalid array element type: " +
2134 Elts[0]->getType()->getDescription());
2136 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2138 // Verify all elements are correct type!
2139 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2140 if (Elts[i]->getType() != Elts[0]->getType())
2141 return Error(FirstEltLoc,
2142 "array element #" + utostr(i) +
2143 " is not of type '" +Elts[0]->getType()->getDescription());
2146 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2147 ID.Kind = ValID::t_Constant;
2150 case lltok::kw_c: // c "foo"
2152 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2153 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2154 ID.Kind = ValID::t_Constant;
2157 case lltok::kw_asm: {
2158 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2159 bool HasSideEffect, AlignStack;
2161 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2162 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2163 ParseStringConstant(ID.StrVal) ||
2164 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2165 ParseToken(lltok::StringConstant, "expected constraint string"))
2167 ID.StrVal2 = Lex.getStrVal();
2168 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2169 ID.Kind = ValID::t_InlineAsm;
2173 case lltok::kw_blockaddress: {
2174 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2178 LocTy FnLoc, LabelLoc;
2180 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2182 ParseToken(lltok::comma, "expected comma in block address expression")||
2183 ParseValID(Label) ||
2184 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2187 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2188 return Error(Fn.Loc, "expected function name in blockaddress");
2189 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2190 return Error(Label.Loc, "expected basic block name in blockaddress");
2192 // Make a global variable as a placeholder for this reference.
2193 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2194 false, GlobalValue::InternalLinkage,
2196 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2197 ID.ConstantVal = FwdRef;
2198 ID.Kind = ValID::t_Constant;
2202 case lltok::kw_trunc:
2203 case lltok::kw_zext:
2204 case lltok::kw_sext:
2205 case lltok::kw_fptrunc:
2206 case lltok::kw_fpext:
2207 case lltok::kw_bitcast:
2208 case lltok::kw_uitofp:
2209 case lltok::kw_sitofp:
2210 case lltok::kw_fptoui:
2211 case lltok::kw_fptosi:
2212 case lltok::kw_inttoptr:
2213 case lltok::kw_ptrtoint: {
2214 unsigned Opc = Lex.getUIntVal();
2215 PATypeHolder DestTy(Type::getVoidTy(Context));
2218 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2219 ParseGlobalTypeAndValue(SrcVal) ||
2220 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2221 ParseType(DestTy) ||
2222 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2224 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2225 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2226 SrcVal->getType()->getDescription() + "' to '" +
2227 DestTy->getDescription() + "'");
2228 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2230 ID.Kind = ValID::t_Constant;
2233 case lltok::kw_extractvalue: {
2236 SmallVector<unsigned, 4> Indices;
2237 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2238 ParseGlobalTypeAndValue(Val) ||
2239 ParseIndexList(Indices) ||
2240 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2243 if (!Val->getType()->isAggregateType())
2244 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2245 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2247 return Error(ID.Loc, "invalid indices for extractvalue");
2249 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2250 ID.Kind = ValID::t_Constant;
2253 case lltok::kw_insertvalue: {
2255 Constant *Val0, *Val1;
2256 SmallVector<unsigned, 4> Indices;
2257 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2258 ParseGlobalTypeAndValue(Val0) ||
2259 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2260 ParseGlobalTypeAndValue(Val1) ||
2261 ParseIndexList(Indices) ||
2262 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2264 if (!Val0->getType()->isAggregateType())
2265 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2266 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2268 return Error(ID.Loc, "invalid indices for insertvalue");
2269 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2270 Indices.data(), Indices.size());
2271 ID.Kind = ValID::t_Constant;
2274 case lltok::kw_icmp:
2275 case lltok::kw_fcmp: {
2276 unsigned PredVal, Opc = Lex.getUIntVal();
2277 Constant *Val0, *Val1;
2279 if (ParseCmpPredicate(PredVal, Opc) ||
2280 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2281 ParseGlobalTypeAndValue(Val0) ||
2282 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2283 ParseGlobalTypeAndValue(Val1) ||
2284 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2287 if (Val0->getType() != Val1->getType())
2288 return Error(ID.Loc, "compare operands must have the same type");
2290 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2292 if (Opc == Instruction::FCmp) {
2293 if (!Val0->getType()->isFPOrFPVectorTy())
2294 return Error(ID.Loc, "fcmp requires floating point operands");
2295 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2297 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2298 if (!Val0->getType()->isIntOrIntVectorTy() &&
2299 !Val0->getType()->isPointerTy())
2300 return Error(ID.Loc, "icmp requires pointer or integer operands");
2301 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2303 ID.Kind = ValID::t_Constant;
2307 // Binary Operators.
2309 case lltok::kw_fadd:
2311 case lltok::kw_fsub:
2313 case lltok::kw_fmul:
2314 case lltok::kw_udiv:
2315 case lltok::kw_sdiv:
2316 case lltok::kw_fdiv:
2317 case lltok::kw_urem:
2318 case lltok::kw_srem:
2319 case lltok::kw_frem: {
2323 unsigned Opc = Lex.getUIntVal();
2324 Constant *Val0, *Val1;
2326 LocTy ModifierLoc = Lex.getLoc();
2327 if (Opc == Instruction::Add ||
2328 Opc == Instruction::Sub ||
2329 Opc == Instruction::Mul) {
2330 if (EatIfPresent(lltok::kw_nuw))
2332 if (EatIfPresent(lltok::kw_nsw)) {
2334 if (EatIfPresent(lltok::kw_nuw))
2337 } else if (Opc == Instruction::SDiv) {
2338 if (EatIfPresent(lltok::kw_exact))
2341 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2342 ParseGlobalTypeAndValue(Val0) ||
2343 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2344 ParseGlobalTypeAndValue(Val1) ||
2345 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2347 if (Val0->getType() != Val1->getType())
2348 return Error(ID.Loc, "operands of constexpr must have same type");
2349 if (!Val0->getType()->isIntOrIntVectorTy()) {
2351 return Error(ModifierLoc, "nuw only applies to integer operations");
2353 return Error(ModifierLoc, "nsw only applies to integer operations");
2355 // API compatibility: Accept either integer or floating-point types with
2356 // add, sub, and mul.
2357 if (!Val0->getType()->isIntOrIntVectorTy() &&
2358 !Val0->getType()->isFPOrFPVectorTy())
2359 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
2361 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2362 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2363 if (Exact) Flags |= SDivOperator::IsExact;
2364 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2366 ID.Kind = ValID::t_Constant;
2370 // Logical Operations
2372 case lltok::kw_lshr:
2373 case lltok::kw_ashr:
2376 case lltok::kw_xor: {
2377 unsigned Opc = Lex.getUIntVal();
2378 Constant *Val0, *Val1;
2380 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2381 ParseGlobalTypeAndValue(Val0) ||
2382 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2383 ParseGlobalTypeAndValue(Val1) ||
2384 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2386 if (Val0->getType() != Val1->getType())
2387 return Error(ID.Loc, "operands of constexpr must have same type");
2388 if (!Val0->getType()->isIntOrIntVectorTy())
2389 return Error(ID.Loc,
2390 "constexpr requires integer or integer vector operands");
2391 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2392 ID.Kind = ValID::t_Constant;
2396 case lltok::kw_getelementptr:
2397 case lltok::kw_shufflevector:
2398 case lltok::kw_insertelement:
2399 case lltok::kw_extractelement:
2400 case lltok::kw_select: {
2401 unsigned Opc = Lex.getUIntVal();
2402 SmallVector<Constant*, 16> Elts;
2403 bool InBounds = false;
2405 if (Opc == Instruction::GetElementPtr)
2406 InBounds = EatIfPresent(lltok::kw_inbounds);
2407 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2408 ParseGlobalValueVector(Elts) ||
2409 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2412 if (Opc == Instruction::GetElementPtr) {
2413 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2414 return Error(ID.Loc, "getelementptr requires pointer operand");
2416 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2417 (Value**)(Elts.data() + 1),
2419 return Error(ID.Loc, "invalid indices for getelementptr");
2420 ID.ConstantVal = InBounds ?
2421 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2424 ConstantExpr::getGetElementPtr(Elts[0],
2425 Elts.data() + 1, Elts.size() - 1);
2426 } else if (Opc == Instruction::Select) {
2427 if (Elts.size() != 3)
2428 return Error(ID.Loc, "expected three operands to select");
2429 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2431 return Error(ID.Loc, Reason);
2432 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2433 } else if (Opc == Instruction::ShuffleVector) {
2434 if (Elts.size() != 3)
2435 return Error(ID.Loc, "expected three operands to shufflevector");
2436 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2437 return Error(ID.Loc, "invalid operands to shufflevector");
2439 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2440 } else if (Opc == Instruction::ExtractElement) {
2441 if (Elts.size() != 2)
2442 return Error(ID.Loc, "expected two operands to extractelement");
2443 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2444 return Error(ID.Loc, "invalid extractelement operands");
2445 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2447 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2448 if (Elts.size() != 3)
2449 return Error(ID.Loc, "expected three operands to insertelement");
2450 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2451 return Error(ID.Loc, "invalid insertelement operands");
2453 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2456 ID.Kind = ValID::t_Constant;
2465 /// ParseGlobalValue - Parse a global value with the specified type.
2466 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2470 bool Parsed = ParseValID(ID) ||
2471 ConvertValIDToValue(Ty, ID, V, NULL);
2472 if (V && !(C = dyn_cast<Constant>(V)))
2473 return Error(ID.Loc, "global values must be constants");
2477 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2478 PATypeHolder Type(Type::getVoidTy(Context));
2479 return ParseType(Type) ||
2480 ParseGlobalValue(Type, V);
2483 /// ParseGlobalValueVector
2485 /// ::= TypeAndValue (',' TypeAndValue)*
2486 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2488 if (Lex.getKind() == lltok::rbrace ||
2489 Lex.getKind() == lltok::rsquare ||
2490 Lex.getKind() == lltok::greater ||
2491 Lex.getKind() == lltok::rparen)
2495 if (ParseGlobalTypeAndValue(C)) return true;
2498 while (EatIfPresent(lltok::comma)) {
2499 if (ParseGlobalTypeAndValue(C)) return true;
2507 //===----------------------------------------------------------------------===//
2508 // Function Parsing.
2509 //===----------------------------------------------------------------------===//
2511 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2512 PerFunctionState *PFS) {
2513 if (Ty->isFunctionTy())
2514 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2517 default: llvm_unreachable("Unknown ValID!");
2518 case ValID::t_LocalID:
2519 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2520 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2522 case ValID::t_LocalName:
2523 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2524 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2526 case ValID::t_InlineAsm: {
2527 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2528 const FunctionType *FTy =
2529 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2530 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2531 return Error(ID.Loc, "invalid type for inline asm constraint string");
2532 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2535 case ValID::t_MDNode:
2536 if (!Ty->isMetadataTy())
2537 return Error(ID.Loc, "metadata value must have metadata type");
2540 case ValID::t_MDString:
2541 if (!Ty->isMetadataTy())
2542 return Error(ID.Loc, "metadata value must have metadata type");
2545 case ValID::t_GlobalName:
2546 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2548 case ValID::t_GlobalID:
2549 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2551 case ValID::t_APSInt:
2552 if (!Ty->isIntegerTy())
2553 return Error(ID.Loc, "integer constant must have integer type");
2554 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2555 V = ConstantInt::get(Context, ID.APSIntVal);
2557 case ValID::t_APFloat:
2558 if (!Ty->isFloatingPointTy() ||
2559 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2560 return Error(ID.Loc, "floating point constant invalid for type");
2562 // The lexer has no type info, so builds all float and double FP constants
2563 // as double. Fix this here. Long double does not need this.
2564 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2567 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2570 V = ConstantFP::get(Context, ID.APFloatVal);
2572 if (V->getType() != Ty)
2573 return Error(ID.Loc, "floating point constant does not have type '" +
2574 Ty->getDescription() + "'");
2578 if (!Ty->isPointerTy())
2579 return Error(ID.Loc, "null must be a pointer type");
2580 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2582 case ValID::t_Undef:
2583 // FIXME: LabelTy should not be a first-class type.
2584 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2586 return Error(ID.Loc, "invalid type for undef constant");
2587 V = UndefValue::get(Ty);
2589 case ValID::t_EmptyArray:
2590 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2591 return Error(ID.Loc, "invalid empty array initializer");
2592 V = UndefValue::get(Ty);
2595 // FIXME: LabelTy should not be a first-class type.
2596 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2597 return Error(ID.Loc, "invalid type for null constant");
2598 V = Constant::getNullValue(Ty);
2600 case ValID::t_Constant:
2601 if (ID.ConstantVal->getType() != Ty) {
2602 // Allow a constant struct with a single member to be converted
2603 // to a union, if the union has a member which is the same type
2604 // as the struct member.
2605 if (const UnionType* utype = dyn_cast<UnionType>(Ty)) {
2606 return ParseUnionValue(utype, ID, V);
2609 return Error(ID.Loc, "constant expression type mismatch");
2617 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2620 return ParseValID(ID, &PFS) ||
2621 ConvertValIDToValue(Ty, ID, V, &PFS);
2624 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2625 PATypeHolder T(Type::getVoidTy(Context));
2626 return ParseType(T) ||
2627 ParseValue(T, V, PFS);
2630 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2631 PerFunctionState &PFS) {
2634 if (ParseTypeAndValue(V, PFS)) return true;
2635 if (!isa<BasicBlock>(V))
2636 return Error(Loc, "expected a basic block");
2637 BB = cast<BasicBlock>(V);
2641 bool LLParser::ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V) {
2642 if (const StructType* stype = dyn_cast<StructType>(ID.ConstantVal->getType())) {
2643 if (stype->getNumContainedTypes() != 1)
2644 return Error(ID.Loc, "constant expression type mismatch");
2645 int index = utype->getElementTypeIndex(stype->getContainedType(0));
2647 return Error(ID.Loc, "initializer type is not a member of the union");
2649 V = ConstantUnion::get(
2650 utype, cast<Constant>(ID.ConstantVal->getOperand(0)));
2654 return Error(ID.Loc, "constant expression type mismatch");
2659 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2660 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2661 /// OptionalAlign OptGC
2662 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2663 // Parse the linkage.
2664 LocTy LinkageLoc = Lex.getLoc();
2667 unsigned Visibility, RetAttrs;
2669 PATypeHolder RetType(Type::getVoidTy(Context));
2670 LocTy RetTypeLoc = Lex.getLoc();
2671 if (ParseOptionalLinkage(Linkage) ||
2672 ParseOptionalVisibility(Visibility) ||
2673 ParseOptionalCallingConv(CC) ||
2674 ParseOptionalAttrs(RetAttrs, 1) ||
2675 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2678 // Verify that the linkage is ok.
2679 switch ((GlobalValue::LinkageTypes)Linkage) {
2680 case GlobalValue::ExternalLinkage:
2681 break; // always ok.
2682 case GlobalValue::DLLImportLinkage:
2683 case GlobalValue::ExternalWeakLinkage:
2685 return Error(LinkageLoc, "invalid linkage for function definition");
2687 case GlobalValue::PrivateLinkage:
2688 case GlobalValue::LinkerPrivateLinkage:
2689 case GlobalValue::InternalLinkage:
2690 case GlobalValue::AvailableExternallyLinkage:
2691 case GlobalValue::LinkOnceAnyLinkage:
2692 case GlobalValue::LinkOnceODRLinkage:
2693 case GlobalValue::WeakAnyLinkage:
2694 case GlobalValue::WeakODRLinkage:
2695 case GlobalValue::DLLExportLinkage:
2697 return Error(LinkageLoc, "invalid linkage for function declaration");
2699 case GlobalValue::AppendingLinkage:
2700 case GlobalValue::CommonLinkage:
2701 return Error(LinkageLoc, "invalid function linkage type");
2704 if (!FunctionType::isValidReturnType(RetType) ||
2705 RetType->isOpaqueTy())
2706 return Error(RetTypeLoc, "invalid function return type");
2708 LocTy NameLoc = Lex.getLoc();
2710 std::string FunctionName;
2711 if (Lex.getKind() == lltok::GlobalVar) {
2712 FunctionName = Lex.getStrVal();
2713 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2714 unsigned NameID = Lex.getUIntVal();
2716 if (NameID != NumberedVals.size())
2717 return TokError("function expected to be numbered '%" +
2718 utostr(NumberedVals.size()) + "'");
2720 return TokError("expected function name");
2725 if (Lex.getKind() != lltok::lparen)
2726 return TokError("expected '(' in function argument list");
2728 std::vector<ArgInfo> ArgList;
2731 std::string Section;
2735 if (ParseArgumentList(ArgList, isVarArg, false) ||
2736 ParseOptionalAttrs(FuncAttrs, 2) ||
2737 (EatIfPresent(lltok::kw_section) &&
2738 ParseStringConstant(Section)) ||
2739 ParseOptionalAlignment(Alignment) ||
2740 (EatIfPresent(lltok::kw_gc) &&
2741 ParseStringConstant(GC)))
2744 // If the alignment was parsed as an attribute, move to the alignment field.
2745 if (FuncAttrs & Attribute::Alignment) {
2746 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2747 FuncAttrs &= ~Attribute::Alignment;
2750 // Okay, if we got here, the function is syntactically valid. Convert types
2751 // and do semantic checks.
2752 std::vector<const Type*> ParamTypeList;
2753 SmallVector<AttributeWithIndex, 8> Attrs;
2754 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2756 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2757 if (FuncAttrs & ObsoleteFuncAttrs) {
2758 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2759 FuncAttrs &= ~ObsoleteFuncAttrs;
2762 if (RetAttrs != Attribute::None)
2763 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2765 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2766 ParamTypeList.push_back(ArgList[i].Type);
2767 if (ArgList[i].Attrs != Attribute::None)
2768 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2771 if (FuncAttrs != Attribute::None)
2772 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2774 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2776 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2777 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2779 const FunctionType *FT =
2780 FunctionType::get(RetType, ParamTypeList, isVarArg);
2781 const PointerType *PFT = PointerType::getUnqual(FT);
2784 if (!FunctionName.empty()) {
2785 // If this was a definition of a forward reference, remove the definition
2786 // from the forward reference table and fill in the forward ref.
2787 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2788 ForwardRefVals.find(FunctionName);
2789 if (FRVI != ForwardRefVals.end()) {
2790 Fn = M->getFunction(FunctionName);
2791 ForwardRefVals.erase(FRVI);
2792 } else if ((Fn = M->getFunction(FunctionName))) {
2793 // If this function already exists in the symbol table, then it is
2794 // multiply defined. We accept a few cases for old backwards compat.
2795 // FIXME: Remove this stuff for LLVM 3.0.
2796 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2797 (!Fn->isDeclaration() && isDefine)) {
2798 // If the redefinition has different type or different attributes,
2799 // reject it. If both have bodies, reject it.
2800 return Error(NameLoc, "invalid redefinition of function '" +
2801 FunctionName + "'");
2802 } else if (Fn->isDeclaration()) {
2803 // Make sure to strip off any argument names so we can't get conflicts.
2804 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2808 } else if (M->getNamedValue(FunctionName)) {
2809 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2813 // If this is a definition of a forward referenced function, make sure the
2815 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2816 = ForwardRefValIDs.find(NumberedVals.size());
2817 if (I != ForwardRefValIDs.end()) {
2818 Fn = cast<Function>(I->second.first);
2819 if (Fn->getType() != PFT)
2820 return Error(NameLoc, "type of definition and forward reference of '@" +
2821 utostr(NumberedVals.size()) +"' disagree");
2822 ForwardRefValIDs.erase(I);
2827 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2828 else // Move the forward-reference to the correct spot in the module.
2829 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2831 if (FunctionName.empty())
2832 NumberedVals.push_back(Fn);
2834 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2835 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2836 Fn->setCallingConv(CC);
2837 Fn->setAttributes(PAL);
2838 Fn->setAlignment(Alignment);
2839 Fn->setSection(Section);
2840 if (!GC.empty()) Fn->setGC(GC.c_str());
2842 // Add all of the arguments we parsed to the function.
2843 Function::arg_iterator ArgIt = Fn->arg_begin();
2844 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2845 // If we run out of arguments in the Function prototype, exit early.
2846 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2847 if (ArgIt == Fn->arg_end()) break;
2849 // If the argument has a name, insert it into the argument symbol table.
2850 if (ArgList[i].Name.empty()) continue;
2852 // Set the name, if it conflicted, it will be auto-renamed.
2853 ArgIt->setName(ArgList[i].Name);
2855 if (ArgIt->getNameStr() != ArgList[i].Name)
2856 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2857 ArgList[i].Name + "'");
2864 /// ParseFunctionBody
2865 /// ::= '{' BasicBlock+ '}'
2866 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2868 bool LLParser::ParseFunctionBody(Function &Fn) {
2869 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2870 return TokError("expected '{' in function body");
2871 Lex.Lex(); // eat the {.
2873 int FunctionNumber = -1;
2874 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2876 PerFunctionState PFS(*this, Fn, FunctionNumber);
2878 // We need at least one basic block.
2879 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2880 return TokError("function body requires at least one basic block");
2882 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2883 if (ParseBasicBlock(PFS)) return true;
2888 // Verify function is ok.
2889 return PFS.FinishFunction();
2893 /// ::= LabelStr? Instruction*
2894 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2895 // If this basic block starts out with a name, remember it.
2897 LocTy NameLoc = Lex.getLoc();
2898 if (Lex.getKind() == lltok::LabelStr) {
2899 Name = Lex.getStrVal();
2903 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2904 if (BB == 0) return true;
2906 std::string NameStr;
2908 // Parse the instructions in this block until we get a terminator.
2910 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2912 // This instruction may have three possibilities for a name: a) none
2913 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2914 LocTy NameLoc = Lex.getLoc();
2918 if (Lex.getKind() == lltok::LocalVarID) {
2919 NameID = Lex.getUIntVal();
2921 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2923 } else if (Lex.getKind() == lltok::LocalVar ||
2924 // FIXME: REMOVE IN LLVM 3.0
2925 Lex.getKind() == lltok::StringConstant) {
2926 NameStr = Lex.getStrVal();
2928 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2932 switch (ParseInstruction(Inst, BB, PFS)) {
2933 default: assert(0 && "Unknown ParseInstruction result!");
2934 case InstError: return true;
2936 BB->getInstList().push_back(Inst);
2938 // With a normal result, we check to see if the instruction is followed by
2939 // a comma and metadata.
2940 if (EatIfPresent(lltok::comma))
2941 if (ParseInstructionMetadata(Inst))
2944 case InstExtraComma:
2945 BB->getInstList().push_back(Inst);
2947 // If the instruction parser ate an extra comma at the end of it, it
2948 // *must* be followed by metadata.
2949 if (ParseInstructionMetadata(Inst))
2954 // Set the name on the instruction.
2955 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2956 } while (!isa<TerminatorInst>(Inst));
2961 //===----------------------------------------------------------------------===//
2962 // Instruction Parsing.
2963 //===----------------------------------------------------------------------===//
2965 /// ParseInstruction - Parse one of the many different instructions.
2967 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2968 PerFunctionState &PFS) {
2969 lltok::Kind Token = Lex.getKind();
2970 if (Token == lltok::Eof)
2971 return TokError("found end of file when expecting more instructions");
2972 LocTy Loc = Lex.getLoc();
2973 unsigned KeywordVal = Lex.getUIntVal();
2974 Lex.Lex(); // Eat the keyword.
2977 default: return Error(Loc, "expected instruction opcode");
2978 // Terminator Instructions.
2979 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2980 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2981 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2982 case lltok::kw_br: return ParseBr(Inst, PFS);
2983 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2984 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2985 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2986 // Binary Operators.
2989 case lltok::kw_mul: {
2992 LocTy ModifierLoc = Lex.getLoc();
2993 if (EatIfPresent(lltok::kw_nuw))
2995 if (EatIfPresent(lltok::kw_nsw)) {
2997 if (EatIfPresent(lltok::kw_nuw))
3000 // API compatibility: Accept either integer or floating-point types.
3001 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 0);
3003 if (!Inst->getType()->isIntOrIntVectorTy()) {
3005 return Error(ModifierLoc, "nuw only applies to integer operations");
3007 return Error(ModifierLoc, "nsw only applies to integer operations");
3010 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3012 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3016 case lltok::kw_fadd:
3017 case lltok::kw_fsub:
3018 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3020 case lltok::kw_sdiv: {
3022 if (EatIfPresent(lltok::kw_exact))
3024 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3027 cast<BinaryOperator>(Inst)->setIsExact(true);
3031 case lltok::kw_udiv:
3032 case lltok::kw_urem:
3033 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3034 case lltok::kw_fdiv:
3035 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3037 case lltok::kw_lshr:
3038 case lltok::kw_ashr:
3041 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3042 case lltok::kw_icmp:
3043 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3045 case lltok::kw_trunc:
3046 case lltok::kw_zext:
3047 case lltok::kw_sext:
3048 case lltok::kw_fptrunc:
3049 case lltok::kw_fpext:
3050 case lltok::kw_bitcast:
3051 case lltok::kw_uitofp:
3052 case lltok::kw_sitofp:
3053 case lltok::kw_fptoui:
3054 case lltok::kw_fptosi:
3055 case lltok::kw_inttoptr:
3056 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3058 case lltok::kw_select: return ParseSelect(Inst, PFS);
3059 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3060 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3061 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3062 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3063 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3064 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3065 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3067 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3068 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
3069 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
3070 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3071 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3072 case lltok::kw_volatile:
3073 if (EatIfPresent(lltok::kw_load))
3074 return ParseLoad(Inst, PFS, true);
3075 else if (EatIfPresent(lltok::kw_store))
3076 return ParseStore(Inst, PFS, true);
3078 return TokError("expected 'load' or 'store'");
3079 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3080 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3081 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3082 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3086 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3087 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3088 if (Opc == Instruction::FCmp) {
3089 switch (Lex.getKind()) {
3090 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3091 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3092 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3093 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3094 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3095 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3096 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3097 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3098 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3099 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3100 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3101 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3102 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3103 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3104 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3105 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3106 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3109 switch (Lex.getKind()) {
3110 default: TokError("expected icmp predicate (e.g. 'eq')");
3111 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3112 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3113 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3114 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3115 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3116 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3117 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3118 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3119 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3120 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3127 //===----------------------------------------------------------------------===//
3128 // Terminator Instructions.
3129 //===----------------------------------------------------------------------===//
3131 /// ParseRet - Parse a return instruction.
3132 /// ::= 'ret' void (',' !dbg, !1)*
3133 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3134 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
3135 /// [[obsolete: LLVM 3.0]]
3136 int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3137 PerFunctionState &PFS) {
3138 PATypeHolder Ty(Type::getVoidTy(Context));
3139 if (ParseType(Ty, true /*void allowed*/)) return true;
3141 if (Ty->isVoidTy()) {
3142 Inst = ReturnInst::Create(Context);
3147 if (ParseValue(Ty, RV, PFS)) return true;
3149 bool ExtraComma = false;
3150 if (EatIfPresent(lltok::comma)) {
3151 // Parse optional custom metadata, e.g. !dbg
3152 if (Lex.getKind() == lltok::MetadataVar) {
3155 // The normal case is one return value.
3156 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3157 // use of 'ret {i32,i32} {i32 1, i32 2}'
3158 SmallVector<Value*, 8> RVs;
3162 // If optional custom metadata, e.g. !dbg is seen then this is the
3164 if (Lex.getKind() == lltok::MetadataVar)
3166 if (ParseTypeAndValue(RV, PFS)) return true;
3168 } while (EatIfPresent(lltok::comma));
3170 RV = UndefValue::get(PFS.getFunction().getReturnType());
3171 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
3172 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3173 BB->getInstList().push_back(I);
3179 Inst = ReturnInst::Create(Context, RV);
3180 return ExtraComma ? InstExtraComma : InstNormal;
3185 /// ::= 'br' TypeAndValue
3186 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3187 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3190 BasicBlock *Op1, *Op2;
3191 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3193 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3194 Inst = BranchInst::Create(BB);
3198 if (Op0->getType() != Type::getInt1Ty(Context))
3199 return Error(Loc, "branch condition must have 'i1' type");
3201 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3202 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3203 ParseToken(lltok::comma, "expected ',' after true destination") ||
3204 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3207 Inst = BranchInst::Create(Op1, Op2, Op0);
3213 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3215 /// ::= (TypeAndValue ',' TypeAndValue)*
3216 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3217 LocTy CondLoc, BBLoc;
3219 BasicBlock *DefaultBB;
3220 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3221 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3222 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3223 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3226 if (!Cond->getType()->isIntegerTy())
3227 return Error(CondLoc, "switch condition must have integer type");
3229 // Parse the jump table pairs.
3230 SmallPtrSet<Value*, 32> SeenCases;
3231 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3232 while (Lex.getKind() != lltok::rsquare) {
3236 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3237 ParseToken(lltok::comma, "expected ',' after case value") ||
3238 ParseTypeAndBasicBlock(DestBB, PFS))
3241 if (!SeenCases.insert(Constant))
3242 return Error(CondLoc, "duplicate case value in switch");
3243 if (!isa<ConstantInt>(Constant))
3244 return Error(CondLoc, "case value is not a constant integer");
3246 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3249 Lex.Lex(); // Eat the ']'.
3251 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3252 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3253 SI->addCase(Table[i].first, Table[i].second);
3260 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3261 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3264 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3265 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3266 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3269 if (!Address->getType()->isPointerTy())
3270 return Error(AddrLoc, "indirectbr address must have pointer type");
3272 // Parse the destination list.
3273 SmallVector<BasicBlock*, 16> DestList;
3275 if (Lex.getKind() != lltok::rsquare) {
3277 if (ParseTypeAndBasicBlock(DestBB, PFS))
3279 DestList.push_back(DestBB);
3281 while (EatIfPresent(lltok::comma)) {
3282 if (ParseTypeAndBasicBlock(DestBB, PFS))
3284 DestList.push_back(DestBB);
3288 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3291 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3292 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3293 IBI->addDestination(DestList[i]);
3300 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3301 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3302 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3303 LocTy CallLoc = Lex.getLoc();
3304 unsigned RetAttrs, FnAttrs;
3306 PATypeHolder RetType(Type::getVoidTy(Context));
3309 SmallVector<ParamInfo, 16> ArgList;
3311 BasicBlock *NormalBB, *UnwindBB;
3312 if (ParseOptionalCallingConv(CC) ||
3313 ParseOptionalAttrs(RetAttrs, 1) ||
3314 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3315 ParseValID(CalleeID) ||
3316 ParseParameterList(ArgList, PFS) ||
3317 ParseOptionalAttrs(FnAttrs, 2) ||
3318 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3319 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3320 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3321 ParseTypeAndBasicBlock(UnwindBB, PFS))
3324 // If RetType is a non-function pointer type, then this is the short syntax
3325 // for the call, which means that RetType is just the return type. Infer the
3326 // rest of the function argument types from the arguments that are present.
3327 const PointerType *PFTy = 0;
3328 const FunctionType *Ty = 0;
3329 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3330 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3331 // Pull out the types of all of the arguments...
3332 std::vector<const Type*> ParamTypes;
3333 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3334 ParamTypes.push_back(ArgList[i].V->getType());
3336 if (!FunctionType::isValidReturnType(RetType))
3337 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3339 Ty = FunctionType::get(RetType, ParamTypes, false);
3340 PFTy = PointerType::getUnqual(Ty);
3343 // Look up the callee.
3345 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3347 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3348 // function attributes.
3349 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3350 if (FnAttrs & ObsoleteFuncAttrs) {
3351 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3352 FnAttrs &= ~ObsoleteFuncAttrs;
3355 // Set up the Attributes for the function.
3356 SmallVector<AttributeWithIndex, 8> Attrs;
3357 if (RetAttrs != Attribute::None)
3358 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3360 SmallVector<Value*, 8> Args;
3362 // Loop through FunctionType's arguments and ensure they are specified
3363 // correctly. Also, gather any parameter attributes.
3364 FunctionType::param_iterator I = Ty->param_begin();
3365 FunctionType::param_iterator E = Ty->param_end();
3366 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3367 const Type *ExpectedTy = 0;
3370 } else if (!Ty->isVarArg()) {
3371 return Error(ArgList[i].Loc, "too many arguments specified");
3374 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3375 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3376 ExpectedTy->getDescription() + "'");
3377 Args.push_back(ArgList[i].V);
3378 if (ArgList[i].Attrs != Attribute::None)
3379 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3383 return Error(CallLoc, "not enough parameters specified for call");
3385 if (FnAttrs != Attribute::None)
3386 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3388 // Finish off the Attributes and check them
3389 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3391 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3392 Args.begin(), Args.end());
3393 II->setCallingConv(CC);
3394 II->setAttributes(PAL);
3401 //===----------------------------------------------------------------------===//
3402 // Binary Operators.
3403 //===----------------------------------------------------------------------===//
3406 /// ::= ArithmeticOps TypeAndValue ',' Value
3408 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3409 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3410 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3411 unsigned Opc, unsigned OperandType) {
3412 LocTy Loc; Value *LHS, *RHS;
3413 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3414 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3415 ParseValue(LHS->getType(), RHS, PFS))
3419 switch (OperandType) {
3420 default: llvm_unreachable("Unknown operand type!");
3421 case 0: // int or FP.
3422 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3423 LHS->getType()->isFPOrFPVectorTy();
3425 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3426 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3430 return Error(Loc, "invalid operand type for instruction");
3432 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3437 /// ::= ArithmeticOps TypeAndValue ',' Value {
3438 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3440 LocTy Loc; Value *LHS, *RHS;
3441 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3442 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3443 ParseValue(LHS->getType(), RHS, PFS))
3446 if (!LHS->getType()->isIntOrIntVectorTy())
3447 return Error(Loc,"instruction requires integer or integer vector operands");
3449 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3455 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3456 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3457 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3459 // Parse the integer/fp comparison predicate.
3463 if (ParseCmpPredicate(Pred, Opc) ||
3464 ParseTypeAndValue(LHS, Loc, PFS) ||
3465 ParseToken(lltok::comma, "expected ',' after compare value") ||
3466 ParseValue(LHS->getType(), RHS, PFS))
3469 if (Opc == Instruction::FCmp) {
3470 if (!LHS->getType()->isFPOrFPVectorTy())
3471 return Error(Loc, "fcmp requires floating point operands");
3472 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3474 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3475 if (!LHS->getType()->isIntOrIntVectorTy() &&
3476 !LHS->getType()->isPointerTy())
3477 return Error(Loc, "icmp requires integer operands");
3478 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3483 //===----------------------------------------------------------------------===//
3484 // Other Instructions.
3485 //===----------------------------------------------------------------------===//
3489 /// ::= CastOpc TypeAndValue 'to' Type
3490 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3492 LocTy Loc; Value *Op;
3493 PATypeHolder DestTy(Type::getVoidTy(Context));
3494 if (ParseTypeAndValue(Op, Loc, PFS) ||
3495 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3499 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3500 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3501 return Error(Loc, "invalid cast opcode for cast from '" +
3502 Op->getType()->getDescription() + "' to '" +
3503 DestTy->getDescription() + "'");
3505 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3510 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3511 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3513 Value *Op0, *Op1, *Op2;
3514 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3515 ParseToken(lltok::comma, "expected ',' after select condition") ||
3516 ParseTypeAndValue(Op1, PFS) ||
3517 ParseToken(lltok::comma, "expected ',' after select value") ||
3518 ParseTypeAndValue(Op2, PFS))
3521 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3522 return Error(Loc, Reason);
3524 Inst = SelectInst::Create(Op0, Op1, Op2);
3529 /// ::= 'va_arg' TypeAndValue ',' Type
3530 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3532 PATypeHolder EltTy(Type::getVoidTy(Context));
3534 if (ParseTypeAndValue(Op, PFS) ||
3535 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3536 ParseType(EltTy, TypeLoc))
3539 if (!EltTy->isFirstClassType())
3540 return Error(TypeLoc, "va_arg requires operand with first class type");
3542 Inst = new VAArgInst(Op, EltTy);
3546 /// ParseExtractElement
3547 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3548 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3551 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3552 ParseToken(lltok::comma, "expected ',' after extract value") ||
3553 ParseTypeAndValue(Op1, PFS))
3556 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3557 return Error(Loc, "invalid extractelement operands");
3559 Inst = ExtractElementInst::Create(Op0, Op1);
3563 /// ParseInsertElement
3564 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3565 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3567 Value *Op0, *Op1, *Op2;
3568 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3569 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3570 ParseTypeAndValue(Op1, PFS) ||
3571 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3572 ParseTypeAndValue(Op2, PFS))
3575 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3576 return Error(Loc, "invalid insertelement operands");
3578 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3582 /// ParseShuffleVector
3583 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3584 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3586 Value *Op0, *Op1, *Op2;
3587 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3588 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3589 ParseTypeAndValue(Op1, PFS) ||
3590 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3591 ParseTypeAndValue(Op2, PFS))
3594 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3595 return Error(Loc, "invalid extractelement operands");
3597 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3602 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3603 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3604 PATypeHolder Ty(Type::getVoidTy(Context));
3606 LocTy TypeLoc = Lex.getLoc();
3608 if (ParseType(Ty) ||
3609 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3610 ParseValue(Ty, Op0, PFS) ||
3611 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3612 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3613 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3616 bool AteExtraComma = false;
3617 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3619 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3621 if (!EatIfPresent(lltok::comma))
3624 if (Lex.getKind() == lltok::MetadataVar) {
3625 AteExtraComma = true;
3629 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3630 ParseValue(Ty, Op0, PFS) ||
3631 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3632 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3633 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3637 if (!Ty->isFirstClassType())
3638 return Error(TypeLoc, "phi node must have first class type");
3640 PHINode *PN = PHINode::Create(Ty);
3641 PN->reserveOperandSpace(PHIVals.size());
3642 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3643 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3645 return AteExtraComma ? InstExtraComma : InstNormal;
3649 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3650 /// ParameterList OptionalAttrs
3651 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3653 unsigned RetAttrs, FnAttrs;
3655 PATypeHolder RetType(Type::getVoidTy(Context));
3658 SmallVector<ParamInfo, 16> ArgList;
3659 LocTy CallLoc = Lex.getLoc();
3661 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3662 ParseOptionalCallingConv(CC) ||
3663 ParseOptionalAttrs(RetAttrs, 1) ||
3664 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3665 ParseValID(CalleeID) ||
3666 ParseParameterList(ArgList, PFS) ||
3667 ParseOptionalAttrs(FnAttrs, 2))
3670 // If RetType is a non-function pointer type, then this is the short syntax
3671 // for the call, which means that RetType is just the return type. Infer the
3672 // rest of the function argument types from the arguments that are present.
3673 const PointerType *PFTy = 0;
3674 const FunctionType *Ty = 0;
3675 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3676 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3677 // Pull out the types of all of the arguments...
3678 std::vector<const Type*> ParamTypes;
3679 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3680 ParamTypes.push_back(ArgList[i].V->getType());
3682 if (!FunctionType::isValidReturnType(RetType))
3683 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3685 Ty = FunctionType::get(RetType, ParamTypes, false);
3686 PFTy = PointerType::getUnqual(Ty);
3689 // Look up the callee.
3691 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3693 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3694 // function attributes.
3695 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3696 if (FnAttrs & ObsoleteFuncAttrs) {
3697 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3698 FnAttrs &= ~ObsoleteFuncAttrs;
3701 // Set up the Attributes for the function.
3702 SmallVector<AttributeWithIndex, 8> Attrs;
3703 if (RetAttrs != Attribute::None)
3704 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3706 SmallVector<Value*, 8> Args;
3708 // Loop through FunctionType's arguments and ensure they are specified
3709 // correctly. Also, gather any parameter attributes.
3710 FunctionType::param_iterator I = Ty->param_begin();
3711 FunctionType::param_iterator E = Ty->param_end();
3712 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3713 const Type *ExpectedTy = 0;
3716 } else if (!Ty->isVarArg()) {
3717 return Error(ArgList[i].Loc, "too many arguments specified");
3720 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3721 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3722 ExpectedTy->getDescription() + "'");
3723 Args.push_back(ArgList[i].V);
3724 if (ArgList[i].Attrs != Attribute::None)
3725 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3729 return Error(CallLoc, "not enough parameters specified for call");
3731 if (FnAttrs != Attribute::None)
3732 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3734 // Finish off the Attributes and check them
3735 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3737 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3738 CI->setTailCall(isTail);
3739 CI->setCallingConv(CC);
3740 CI->setAttributes(PAL);
3745 //===----------------------------------------------------------------------===//
3746 // Memory Instructions.
3747 //===----------------------------------------------------------------------===//
3750 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3751 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3752 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3753 BasicBlock* BB, bool isAlloca) {
3754 PATypeHolder Ty(Type::getVoidTy(Context));
3757 unsigned Alignment = 0;
3758 if (ParseType(Ty)) return true;
3760 bool AteExtraComma = false;
3761 if (EatIfPresent(lltok::comma)) {
3762 if (Lex.getKind() == lltok::kw_align) {
3763 if (ParseOptionalAlignment(Alignment)) return true;
3764 } else if (Lex.getKind() == lltok::MetadataVar) {
3765 AteExtraComma = true;
3767 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3768 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3773 if (Size && !Size->getType()->isIntegerTy(32))
3774 return Error(SizeLoc, "element count must be i32");
3777 Inst = new AllocaInst(Ty, Size, Alignment);
3778 return AteExtraComma ? InstExtraComma : InstNormal;
3781 // Autoupgrade old malloc instruction to malloc call.
3782 // FIXME: Remove in LLVM 3.0.
3783 const Type *IntPtrTy = Type::getInt32Ty(Context);
3784 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3785 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
3787 // Prototype malloc as "void *(int32)".
3788 // This function is renamed as "malloc" in ValidateEndOfModule().
3789 MallocF = cast<Function>(
3790 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
3791 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
3792 return AteExtraComma ? InstExtraComma : InstNormal;
3796 /// ::= 'free' TypeAndValue
3797 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3799 Value *Val; LocTy Loc;
3800 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3801 if (!Val->getType()->isPointerTy())
3802 return Error(Loc, "operand to free must be a pointer");
3803 Inst = CallInst::CreateFree(Val, BB);
3808 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3809 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3811 Value *Val; LocTy Loc;
3812 unsigned Alignment = 0;
3813 bool AteExtraComma = false;
3814 if (ParseTypeAndValue(Val, Loc, PFS) ||
3815 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3818 if (!Val->getType()->isPointerTy() ||
3819 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3820 return Error(Loc, "load operand must be a pointer to a first class type");
3822 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3823 return AteExtraComma ? InstExtraComma : InstNormal;
3827 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3828 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3830 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3831 unsigned Alignment = 0;
3832 bool AteExtraComma = false;
3833 if (ParseTypeAndValue(Val, Loc, PFS) ||
3834 ParseToken(lltok::comma, "expected ',' after store operand") ||
3835 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3836 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3839 if (!Ptr->getType()->isPointerTy())
3840 return Error(PtrLoc, "store operand must be a pointer");
3841 if (!Val->getType()->isFirstClassType())
3842 return Error(Loc, "store operand must be a first class value");
3843 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3844 return Error(Loc, "stored value and pointer type do not match");
3846 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3847 return AteExtraComma ? InstExtraComma : InstNormal;
3851 /// ::= 'getresult' TypeAndValue ',' i32
3852 /// FIXME: Remove support for getresult in LLVM 3.0
3853 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3854 Value *Val; LocTy ValLoc, EltLoc;
3856 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3857 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3858 ParseUInt32(Element, EltLoc))
3861 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
3862 return Error(ValLoc, "getresult inst requires an aggregate operand");
3863 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3864 return Error(EltLoc, "invalid getresult index for value");
3865 Inst = ExtractValueInst::Create(Val, Element);
3869 /// ParseGetElementPtr
3870 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3871 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3872 Value *Ptr, *Val; LocTy Loc, EltLoc;
3874 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3876 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3878 if (!Ptr->getType()->isPointerTy())
3879 return Error(Loc, "base of getelementptr must be a pointer");
3881 SmallVector<Value*, 16> Indices;
3882 bool AteExtraComma = false;
3883 while (EatIfPresent(lltok::comma)) {
3884 if (Lex.getKind() == lltok::MetadataVar) {
3885 AteExtraComma = true;
3888 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3889 if (!Val->getType()->isIntegerTy())
3890 return Error(EltLoc, "getelementptr index must be an integer");
3891 Indices.push_back(Val);
3894 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3895 Indices.begin(), Indices.end()))
3896 return Error(Loc, "invalid getelementptr indices");
3897 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3899 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3900 return AteExtraComma ? InstExtraComma : InstNormal;
3903 /// ParseExtractValue
3904 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3905 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3906 Value *Val; LocTy Loc;
3907 SmallVector<unsigned, 4> Indices;
3909 if (ParseTypeAndValue(Val, Loc, PFS) ||
3910 ParseIndexList(Indices, AteExtraComma))
3913 if (!Val->getType()->isAggregateType())
3914 return Error(Loc, "extractvalue operand must be aggregate type");
3916 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3918 return Error(Loc, "invalid indices for extractvalue");
3919 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3920 return AteExtraComma ? InstExtraComma : InstNormal;
3923 /// ParseInsertValue
3924 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3925 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3926 Value *Val0, *Val1; LocTy Loc0, Loc1;
3927 SmallVector<unsigned, 4> Indices;
3929 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3930 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3931 ParseTypeAndValue(Val1, Loc1, PFS) ||
3932 ParseIndexList(Indices, AteExtraComma))
3935 if (!Val0->getType()->isAggregateType())
3936 return Error(Loc0, "insertvalue operand must be aggregate type");
3938 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3940 return Error(Loc0, "invalid indices for insertvalue");
3941 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3942 return AteExtraComma ? InstExtraComma : InstNormal;
3945 //===----------------------------------------------------------------------===//
3946 // Embedded metadata.
3947 //===----------------------------------------------------------------------===//
3949 /// ParseMDNodeVector
3950 /// ::= Element (',' Element)*
3952 /// ::= 'null' | TypeAndValue
3953 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3954 PerFunctionState *PFS) {
3956 // Null is a special case since it is typeless.
3957 if (EatIfPresent(lltok::kw_null)) {
3963 PATypeHolder Ty(Type::getVoidTy(Context));
3965 if (ParseType(Ty) || ParseValID(ID, PFS) ||
3966 ConvertValIDToValue(Ty, ID, V, PFS))
3970 } while (EatIfPresent(lltok::comma));