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_linker_private_weak: // OptionalLinkage
202 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
203 case lltok::kw_internal: // OptionalLinkage
204 case lltok::kw_weak: // OptionalLinkage
205 case lltok::kw_weak_odr: // OptionalLinkage
206 case lltok::kw_linkonce: // OptionalLinkage
207 case lltok::kw_linkonce_odr: // OptionalLinkage
208 case lltok::kw_appending: // OptionalLinkage
209 case lltok::kw_dllexport: // OptionalLinkage
210 case lltok::kw_common: // OptionalLinkage
211 case lltok::kw_dllimport: // OptionalLinkage
212 case lltok::kw_extern_weak: // OptionalLinkage
213 case lltok::kw_external: { // OptionalLinkage
214 unsigned Linkage, Visibility;
215 if (ParseOptionalLinkage(Linkage) ||
216 ParseOptionalVisibility(Visibility) ||
217 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
221 case lltok::kw_default: // OptionalVisibility
222 case lltok::kw_hidden: // OptionalVisibility
223 case lltok::kw_protected: { // OptionalVisibility
225 if (ParseOptionalVisibility(Visibility) ||
226 ParseGlobal("", SMLoc(), 0, false, Visibility))
231 case lltok::kw_thread_local: // OptionalThreadLocal
232 case lltok::kw_addrspace: // OptionalAddrSpace
233 case lltok::kw_constant: // GlobalType
234 case lltok::kw_global: // GlobalType
235 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
243 /// ::= 'module' 'asm' STRINGCONSTANT
244 bool LLParser::ParseModuleAsm() {
245 assert(Lex.getKind() == lltok::kw_module);
249 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
250 ParseStringConstant(AsmStr)) return true;
252 const std::string &AsmSoFar = M->getModuleInlineAsm();
253 if (AsmSoFar.empty())
254 M->setModuleInlineAsm(AsmStr);
256 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
261 /// ::= 'target' 'triple' '=' STRINGCONSTANT
262 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
263 bool LLParser::ParseTargetDefinition() {
264 assert(Lex.getKind() == lltok::kw_target);
267 default: return TokError("unknown target property");
268 case lltok::kw_triple:
270 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
271 ParseStringConstant(Str))
273 M->setTargetTriple(Str);
275 case lltok::kw_datalayout:
277 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
278 ParseStringConstant(Str))
280 M->setDataLayout(Str);
286 /// ::= 'deplibs' '=' '[' ']'
287 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
288 bool LLParser::ParseDepLibs() {
289 assert(Lex.getKind() == lltok::kw_deplibs);
291 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
292 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
295 if (EatIfPresent(lltok::rsquare))
299 if (ParseStringConstant(Str)) return true;
302 while (EatIfPresent(lltok::comma)) {
303 if (ParseStringConstant(Str)) return true;
307 return ParseToken(lltok::rsquare, "expected ']' at end of list");
310 /// ParseUnnamedType:
312 /// ::= LocalVarID '=' 'type' type
313 bool LLParser::ParseUnnamedType() {
314 unsigned TypeID = NumberedTypes.size();
316 // Handle the LocalVarID form.
317 if (Lex.getKind() == lltok::LocalVarID) {
318 if (Lex.getUIntVal() != TypeID)
319 return Error(Lex.getLoc(), "type expected to be numbered '%" +
320 utostr(TypeID) + "'");
321 Lex.Lex(); // eat LocalVarID;
323 if (ParseToken(lltok::equal, "expected '=' after name"))
327 LocTy TypeLoc = Lex.getLoc();
328 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
330 PATypeHolder Ty(Type::getVoidTy(Context));
331 if (ParseType(Ty)) return true;
333 // See if this type was previously referenced.
334 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
335 FI = ForwardRefTypeIDs.find(TypeID);
336 if (FI != ForwardRefTypeIDs.end()) {
337 if (FI->second.first.get() == Ty)
338 return Error(TypeLoc, "self referential type is invalid");
340 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
341 Ty = FI->second.first.get();
342 ForwardRefTypeIDs.erase(FI);
345 NumberedTypes.push_back(Ty);
351 /// ::= LocalVar '=' 'type' type
352 bool LLParser::ParseNamedType() {
353 std::string Name = Lex.getStrVal();
354 LocTy NameLoc = Lex.getLoc();
355 Lex.Lex(); // eat LocalVar.
357 PATypeHolder Ty(Type::getVoidTy(Context));
359 if (ParseToken(lltok::equal, "expected '=' after name") ||
360 ParseToken(lltok::kw_type, "expected 'type' after name") ||
364 // Set the type name, checking for conflicts as we do so.
365 bool AlreadyExists = M->addTypeName(Name, Ty);
366 if (!AlreadyExists) return false;
368 // See if this type is a forward reference. We need to eagerly resolve
369 // types to allow recursive type redefinitions below.
370 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
371 FI = ForwardRefTypes.find(Name);
372 if (FI != ForwardRefTypes.end()) {
373 if (FI->second.first.get() == Ty)
374 return Error(NameLoc, "self referential type is invalid");
376 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
377 Ty = FI->second.first.get();
378 ForwardRefTypes.erase(FI);
381 // Inserting a name that is already defined, get the existing name.
382 const Type *Existing = M->getTypeByName(Name);
383 assert(Existing && "Conflict but no matching type?!");
385 // Otherwise, this is an attempt to redefine a type. That's okay if
386 // the redefinition is identical to the original.
387 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
388 if (Existing == Ty) return false;
390 // Any other kind of (non-equivalent) redefinition is an error.
391 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
392 Ty->getDescription() + "'");
397 /// ::= 'declare' FunctionHeader
398 bool LLParser::ParseDeclare() {
399 assert(Lex.getKind() == lltok::kw_declare);
403 return ParseFunctionHeader(F, false);
407 /// ::= 'define' FunctionHeader '{' ...
408 bool LLParser::ParseDefine() {
409 assert(Lex.getKind() == lltok::kw_define);
413 return ParseFunctionHeader(F, true) ||
414 ParseFunctionBody(*F);
420 bool LLParser::ParseGlobalType(bool &IsConstant) {
421 if (Lex.getKind() == lltok::kw_constant)
423 else if (Lex.getKind() == lltok::kw_global)
427 return TokError("expected 'global' or 'constant'");
433 /// ParseUnnamedGlobal:
434 /// OptionalVisibility ALIAS ...
435 /// OptionalLinkage OptionalVisibility ... -> global variable
436 /// GlobalID '=' OptionalVisibility ALIAS ...
437 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
438 bool LLParser::ParseUnnamedGlobal() {
439 unsigned VarID = NumberedVals.size();
441 LocTy NameLoc = Lex.getLoc();
443 // Handle the GlobalID form.
444 if (Lex.getKind() == lltok::GlobalID) {
445 if (Lex.getUIntVal() != VarID)
446 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
447 utostr(VarID) + "'");
448 Lex.Lex(); // eat GlobalID;
450 if (ParseToken(lltok::equal, "expected '=' after name"))
455 unsigned Linkage, Visibility;
456 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
457 ParseOptionalVisibility(Visibility))
460 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
461 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
462 return ParseAlias(Name, NameLoc, Visibility);
465 /// ParseNamedGlobal:
466 /// GlobalVar '=' OptionalVisibility ALIAS ...
467 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
468 bool LLParser::ParseNamedGlobal() {
469 assert(Lex.getKind() == lltok::GlobalVar);
470 LocTy NameLoc = Lex.getLoc();
471 std::string Name = Lex.getStrVal();
475 unsigned Linkage, Visibility;
476 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
477 ParseOptionalLinkage(Linkage, HasLinkage) ||
478 ParseOptionalVisibility(Visibility))
481 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
482 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
483 return ParseAlias(Name, NameLoc, Visibility);
487 // ::= '!' STRINGCONSTANT
488 bool LLParser::ParseMDString(MDString *&Result) {
490 if (ParseStringConstant(Str)) return true;
491 Result = MDString::get(Context, Str);
496 // ::= '!' MDNodeNumber
498 /// This version of ParseMDNodeID returns the slot number and null in the case
499 /// of a forward reference.
500 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
501 // !{ ..., !42, ... }
502 if (ParseUInt32(SlotNo)) return true;
504 // Check existing MDNode.
505 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
506 Result = NumberedMetadata[SlotNo];
512 bool LLParser::ParseMDNodeID(MDNode *&Result) {
513 // !{ ..., !42, ... }
515 if (ParseMDNodeID(Result, MID)) return true;
517 // If not a forward reference, just return it now.
518 if (Result) return false;
520 // Otherwise, create MDNode forward reference.
521 MDNode *FwdNode = MDNode::getTemporary(Context, 0, 0);
522 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
524 if (NumberedMetadata.size() <= MID)
525 NumberedMetadata.resize(MID+1);
526 NumberedMetadata[MID] = FwdNode;
531 /// ParseNamedMetadata:
532 /// !foo = !{ !1, !2 }
533 bool LLParser::ParseNamedMetadata() {
534 assert(Lex.getKind() == lltok::MetadataVar);
535 std::string Name = Lex.getStrVal();
538 if (ParseToken(lltok::equal, "expected '=' here") ||
539 ParseToken(lltok::exclaim, "Expected '!' here") ||
540 ParseToken(lltok::lbrace, "Expected '{' here"))
543 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
544 if (Lex.getKind() != lltok::rbrace)
546 if (ParseToken(lltok::exclaim, "Expected '!' here"))
550 if (ParseMDNodeID(N)) return true;
552 } while (EatIfPresent(lltok::comma));
554 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
560 /// ParseStandaloneMetadata:
562 bool LLParser::ParseStandaloneMetadata() {
563 assert(Lex.getKind() == lltok::exclaim);
565 unsigned MetadataID = 0;
568 PATypeHolder Ty(Type::getVoidTy(Context));
569 SmallVector<Value *, 16> Elts;
570 if (ParseUInt32(MetadataID) ||
571 ParseToken(lltok::equal, "expected '=' here") ||
572 ParseType(Ty, TyLoc) ||
573 ParseToken(lltok::exclaim, "Expected '!' here") ||
574 ParseToken(lltok::lbrace, "Expected '{' here") ||
575 ParseMDNodeVector(Elts, NULL) ||
576 ParseToken(lltok::rbrace, "expected end of metadata node"))
579 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
581 // See if this was forward referenced, if so, handle it.
582 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
583 FI = ForwardRefMDNodes.find(MetadataID);
584 if (FI != ForwardRefMDNodes.end()) {
585 MDNode *Temp = FI->second.first;
586 Temp->replaceAllUsesWith(Init);
587 MDNode::deleteTemporary(Temp);
588 ForwardRefMDNodes.erase(FI);
590 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
592 if (MetadataID >= NumberedMetadata.size())
593 NumberedMetadata.resize(MetadataID+1);
595 if (NumberedMetadata[MetadataID] != 0)
596 return TokError("Metadata id is already used");
597 NumberedMetadata[MetadataID] = Init;
604 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
607 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
608 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
610 /// Everything through visibility has already been parsed.
612 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
613 unsigned Visibility) {
614 assert(Lex.getKind() == lltok::kw_alias);
617 LocTy LinkageLoc = Lex.getLoc();
618 if (ParseOptionalLinkage(Linkage))
621 if (Linkage != GlobalValue::ExternalLinkage &&
622 Linkage != GlobalValue::WeakAnyLinkage &&
623 Linkage != GlobalValue::WeakODRLinkage &&
624 Linkage != GlobalValue::InternalLinkage &&
625 Linkage != GlobalValue::PrivateLinkage &&
626 Linkage != GlobalValue::LinkerPrivateLinkage &&
627 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
628 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
629 return Error(LinkageLoc, "invalid linkage type for alias");
632 LocTy AliaseeLoc = Lex.getLoc();
633 if (Lex.getKind() != lltok::kw_bitcast &&
634 Lex.getKind() != lltok::kw_getelementptr) {
635 if (ParseGlobalTypeAndValue(Aliasee)) return true;
637 // The bitcast dest type is not present, it is implied by the dest type.
639 if (ParseValID(ID)) return true;
640 if (ID.Kind != ValID::t_Constant)
641 return Error(AliaseeLoc, "invalid aliasee");
642 Aliasee = ID.ConstantVal;
645 if (!Aliasee->getType()->isPointerTy())
646 return Error(AliaseeLoc, "alias must have pointer type");
648 // Okay, create the alias but do not insert it into the module yet.
649 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
650 (GlobalValue::LinkageTypes)Linkage, Name,
652 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
654 // See if this value already exists in the symbol table. If so, it is either
655 // a redefinition or a definition of a forward reference.
656 if (GlobalValue *Val = M->getNamedValue(Name)) {
657 // See if this was a redefinition. If so, there is no entry in
659 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
660 I = ForwardRefVals.find(Name);
661 if (I == ForwardRefVals.end())
662 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
664 // Otherwise, this was a definition of forward ref. Verify that types
666 if (Val->getType() != GA->getType())
667 return Error(NameLoc,
668 "forward reference and definition of alias have different types");
670 // If they agree, just RAUW the old value with the alias and remove the
672 Val->replaceAllUsesWith(GA);
673 Val->eraseFromParent();
674 ForwardRefVals.erase(I);
677 // Insert into the module, we know its name won't collide now.
678 M->getAliasList().push_back(GA);
679 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
685 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
686 /// OptionalAddrSpace GlobalType Type Const
687 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
688 /// OptionalAddrSpace GlobalType Type Const
690 /// Everything through visibility has been parsed already.
692 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
693 unsigned Linkage, bool HasLinkage,
694 unsigned Visibility) {
696 bool ThreadLocal, IsConstant;
699 PATypeHolder Ty(Type::getVoidTy(Context));
700 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
701 ParseOptionalAddrSpace(AddrSpace) ||
702 ParseGlobalType(IsConstant) ||
703 ParseType(Ty, TyLoc))
706 // If the linkage is specified and is external, then no initializer is
709 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
710 Linkage != GlobalValue::ExternalWeakLinkage &&
711 Linkage != GlobalValue::ExternalLinkage)) {
712 if (ParseGlobalValue(Ty, Init))
716 if (Ty->isFunctionTy() || Ty->isLabelTy())
717 return Error(TyLoc, "invalid type for global variable");
719 GlobalVariable *GV = 0;
721 // See if the global was forward referenced, if so, use the global.
723 if (GlobalValue *GVal = M->getNamedValue(Name)) {
724 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
725 return Error(NameLoc, "redefinition of global '@" + Name + "'");
726 GV = cast<GlobalVariable>(GVal);
729 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
730 I = ForwardRefValIDs.find(NumberedVals.size());
731 if (I != ForwardRefValIDs.end()) {
732 GV = cast<GlobalVariable>(I->second.first);
733 ForwardRefValIDs.erase(I);
738 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
739 Name, 0, false, AddrSpace);
741 if (GV->getType()->getElementType() != Ty)
743 "forward reference and definition of global have different types");
745 // Move the forward-reference to the correct spot in the module.
746 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
750 NumberedVals.push_back(GV);
752 // Set the parsed properties on the global.
754 GV->setInitializer(Init);
755 GV->setConstant(IsConstant);
756 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
757 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
758 GV->setThreadLocal(ThreadLocal);
760 // Parse attributes on the global.
761 while (Lex.getKind() == lltok::comma) {
764 if (Lex.getKind() == lltok::kw_section) {
766 GV->setSection(Lex.getStrVal());
767 if (ParseToken(lltok::StringConstant, "expected global section string"))
769 } else if (Lex.getKind() == lltok::kw_align) {
771 if (ParseOptionalAlignment(Alignment)) return true;
772 GV->setAlignment(Alignment);
774 TokError("unknown global variable property!");
782 //===----------------------------------------------------------------------===//
783 // GlobalValue Reference/Resolution Routines.
784 //===----------------------------------------------------------------------===//
786 /// GetGlobalVal - Get a value with the specified name or ID, creating a
787 /// forward reference record if needed. This can return null if the value
788 /// exists but does not have the right type.
789 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
791 const PointerType *PTy = dyn_cast<PointerType>(Ty);
793 Error(Loc, "global variable reference must have pointer type");
797 // Look this name up in the normal function symbol table.
799 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
801 // If this is a forward reference for the value, see if we already created a
802 // forward ref record.
804 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
805 I = ForwardRefVals.find(Name);
806 if (I != ForwardRefVals.end())
807 Val = I->second.first;
810 // If we have the value in the symbol table or fwd-ref table, return it.
812 if (Val->getType() == Ty) return Val;
813 Error(Loc, "'@" + Name + "' defined with type '" +
814 Val->getType()->getDescription() + "'");
818 // Otherwise, create a new forward reference for this value and remember it.
820 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
821 // Function types can return opaque but functions can't.
822 if (FT->getReturnType()->isOpaqueTy()) {
823 Error(Loc, "function may not return opaque type");
827 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
829 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
830 GlobalValue::ExternalWeakLinkage, 0, Name);
833 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
837 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
838 const PointerType *PTy = dyn_cast<PointerType>(Ty);
840 Error(Loc, "global variable reference must have pointer type");
844 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
846 // If this is a forward reference for the value, see if we already created a
847 // forward ref record.
849 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
850 I = ForwardRefValIDs.find(ID);
851 if (I != ForwardRefValIDs.end())
852 Val = I->second.first;
855 // If we have the value in the symbol table or fwd-ref table, return it.
857 if (Val->getType() == Ty) return Val;
858 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
859 Val->getType()->getDescription() + "'");
863 // Otherwise, create a new forward reference for this value and remember it.
865 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
866 // Function types can return opaque but functions can't.
867 if (FT->getReturnType()->isOpaqueTy()) {
868 Error(Loc, "function may not return opaque type");
871 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
873 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
874 GlobalValue::ExternalWeakLinkage, 0, "");
877 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
882 //===----------------------------------------------------------------------===//
884 //===----------------------------------------------------------------------===//
886 /// ParseToken - If the current token has the specified kind, eat it and return
887 /// success. Otherwise, emit the specified error and return failure.
888 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
889 if (Lex.getKind() != T)
890 return TokError(ErrMsg);
895 /// ParseStringConstant
896 /// ::= StringConstant
897 bool LLParser::ParseStringConstant(std::string &Result) {
898 if (Lex.getKind() != lltok::StringConstant)
899 return TokError("expected string constant");
900 Result = Lex.getStrVal();
907 bool LLParser::ParseUInt32(unsigned &Val) {
908 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
909 return TokError("expected integer");
910 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
911 if (Val64 != unsigned(Val64))
912 return TokError("expected 32-bit integer (too large)");
919 /// ParseOptionalAddrSpace
921 /// := 'addrspace' '(' uint32 ')'
922 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
924 if (!EatIfPresent(lltok::kw_addrspace))
926 return ParseToken(lltok::lparen, "expected '(' in address space") ||
927 ParseUInt32(AddrSpace) ||
928 ParseToken(lltok::rparen, "expected ')' in address space");
931 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
932 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
933 /// 2: function attr.
934 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
935 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
936 Attrs = Attribute::None;
937 LocTy AttrLoc = Lex.getLoc();
940 switch (Lex.getKind()) {
943 // Treat these as signext/zeroext if they occur in the argument list after
944 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
945 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
947 // FIXME: REMOVE THIS IN LLVM 3.0
949 if (Lex.getKind() == lltok::kw_sext)
950 Attrs |= Attribute::SExt;
952 Attrs |= Attribute::ZExt;
956 default: // End of attributes.
957 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
958 return Error(AttrLoc, "invalid use of function-only attribute");
960 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
961 return Error(AttrLoc, "invalid use of parameter-only attribute");
964 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
965 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
966 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
967 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
968 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
969 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
970 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
971 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
973 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
974 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
975 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
976 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
977 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
978 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
979 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
980 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
981 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
982 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
983 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
984 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
985 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
987 case lltok::kw_alignstack: {
989 if (ParseOptionalStackAlignment(Alignment))
991 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
995 case lltok::kw_align: {
997 if (ParseOptionalAlignment(Alignment))
999 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1008 /// ParseOptionalLinkage
1011 /// ::= 'linker_private'
1012 /// ::= 'linker_private_weak'
1013 /// ::= 'linker_private_weak_def_auto'
1018 /// ::= 'linkonce_odr'
1019 /// ::= 'available_externally'
1024 /// ::= 'extern_weak'
1026 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1028 switch (Lex.getKind()) {
1029 default: Res=GlobalValue::ExternalLinkage; return false;
1030 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1031 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1032 case lltok::kw_linker_private_weak:
1033 Res = GlobalValue::LinkerPrivateWeakLinkage;
1035 case lltok::kw_linker_private_weak_def_auto:
1036 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1038 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1039 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1040 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1041 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1042 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1043 case lltok::kw_available_externally:
1044 Res = GlobalValue::AvailableExternallyLinkage;
1046 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1047 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1048 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1049 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1050 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1051 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1058 /// ParseOptionalVisibility
1064 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1065 switch (Lex.getKind()) {
1066 default: Res = GlobalValue::DefaultVisibility; return false;
1067 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1068 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1069 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1075 /// ParseOptionalCallingConv
1080 /// ::= 'x86_stdcallcc'
1081 /// ::= 'x86_fastcallcc'
1082 /// ::= 'x86_thiscallcc'
1083 /// ::= 'arm_apcscc'
1084 /// ::= 'arm_aapcscc'
1085 /// ::= 'arm_aapcs_vfpcc'
1086 /// ::= 'msp430_intrcc'
1087 /// ::= 'ptx_kernel'
1088 /// ::= 'ptx_device'
1091 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1092 switch (Lex.getKind()) {
1093 default: CC = CallingConv::C; return false;
1094 case lltok::kw_ccc: CC = CallingConv::C; break;
1095 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1096 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1097 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1098 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1099 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1100 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1101 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1102 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1103 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1104 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1105 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1106 case lltok::kw_cc: {
1107 unsigned ArbitraryCC;
1109 if (ParseUInt32(ArbitraryCC)) {
1112 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1122 /// ParseInstructionMetadata
1123 /// ::= !dbg !42 (',' !dbg !57)*
1124 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1125 PerFunctionState *PFS) {
1127 if (Lex.getKind() != lltok::MetadataVar)
1128 return TokError("expected metadata after comma");
1130 std::string Name = Lex.getStrVal();
1131 unsigned MDK = M->getMDKindID(Name.c_str());
1136 SMLoc Loc = Lex.getLoc();
1138 if (ParseToken(lltok::exclaim, "expected '!' here"))
1141 // This code is similar to that of ParseMetadataValue, however it needs to
1142 // have special-case code for a forward reference; see the comments on
1143 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1144 // at the top level here.
1145 if (Lex.getKind() == lltok::lbrace) {
1147 if (ParseMetadataListValue(ID, PFS))
1149 assert(ID.Kind == ValID::t_MDNode);
1150 Inst->setMetadata(MDK, ID.MDNodeVal);
1152 if (ParseMDNodeID(Node, NodeID))
1155 // If we got the node, add it to the instruction.
1156 Inst->setMetadata(MDK, Node);
1158 MDRef R = { Loc, MDK, NodeID };
1159 // Otherwise, remember that this should be resolved later.
1160 ForwardRefInstMetadata[Inst].push_back(R);
1164 // If this is the end of the list, we're done.
1165 } while (EatIfPresent(lltok::comma));
1169 /// ParseOptionalAlignment
1172 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1174 if (!EatIfPresent(lltok::kw_align))
1176 LocTy AlignLoc = Lex.getLoc();
1177 if (ParseUInt32(Alignment)) return true;
1178 if (!isPowerOf2_32(Alignment))
1179 return Error(AlignLoc, "alignment is not a power of two");
1180 if (Alignment > Value::MaximumAlignment)
1181 return Error(AlignLoc, "huge alignments are not supported yet");
1185 /// ParseOptionalCommaAlign
1189 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1191 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1192 bool &AteExtraComma) {
1193 AteExtraComma = false;
1194 while (EatIfPresent(lltok::comma)) {
1195 // Metadata at the end is an early exit.
1196 if (Lex.getKind() == lltok::MetadataVar) {
1197 AteExtraComma = true;
1201 if (Lex.getKind() != lltok::kw_align)
1202 return Error(Lex.getLoc(), "expected metadata or 'align'");
1204 LocTy AlignLoc = Lex.getLoc();
1205 if (ParseOptionalAlignment(Alignment)) return true;
1211 /// ParseOptionalStackAlignment
1213 /// ::= 'alignstack' '(' 4 ')'
1214 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1216 if (!EatIfPresent(lltok::kw_alignstack))
1218 LocTy ParenLoc = Lex.getLoc();
1219 if (!EatIfPresent(lltok::lparen))
1220 return Error(ParenLoc, "expected '('");
1221 LocTy AlignLoc = Lex.getLoc();
1222 if (ParseUInt32(Alignment)) return true;
1223 ParenLoc = Lex.getLoc();
1224 if (!EatIfPresent(lltok::rparen))
1225 return Error(ParenLoc, "expected ')'");
1226 if (!isPowerOf2_32(Alignment))
1227 return Error(AlignLoc, "stack alignment is not a power of two");
1231 /// ParseIndexList - This parses the index list for an insert/extractvalue
1232 /// instruction. This sets AteExtraComma in the case where we eat an extra
1233 /// comma at the end of the line and find that it is followed by metadata.
1234 /// Clients that don't allow metadata can call the version of this function that
1235 /// only takes one argument.
1238 /// ::= (',' uint32)+
1240 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1241 bool &AteExtraComma) {
1242 AteExtraComma = false;
1244 if (Lex.getKind() != lltok::comma)
1245 return TokError("expected ',' as start of index list");
1247 while (EatIfPresent(lltok::comma)) {
1248 if (Lex.getKind() == lltok::MetadataVar) {
1249 AteExtraComma = true;
1253 if (ParseUInt32(Idx)) return true;
1254 Indices.push_back(Idx);
1260 //===----------------------------------------------------------------------===//
1262 //===----------------------------------------------------------------------===//
1264 /// ParseType - Parse and resolve a full type.
1265 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1266 LocTy TypeLoc = Lex.getLoc();
1267 if (ParseTypeRec(Result)) return true;
1269 // Verify no unresolved uprefs.
1270 if (!UpRefs.empty())
1271 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1273 if (!AllowVoid && Result.get()->isVoidTy())
1274 return Error(TypeLoc, "void type only allowed for function results");
1279 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1280 /// called. It loops through the UpRefs vector, which is a list of the
1281 /// currently active types. For each type, if the up-reference is contained in
1282 /// the newly completed type, we decrement the level count. When the level
1283 /// count reaches zero, the up-referenced type is the type that is passed in:
1284 /// thus we can complete the cycle.
1286 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1287 // If Ty isn't abstract, or if there are no up-references in it, then there is
1288 // nothing to resolve here.
1289 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1291 PATypeHolder Ty(ty);
1293 dbgs() << "Type '" << Ty->getDescription()
1294 << "' newly formed. Resolving upreferences.\n"
1295 << UpRefs.size() << " upreferences active!\n";
1298 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1299 // to zero), we resolve them all together before we resolve them to Ty. At
1300 // the end of the loop, if there is anything to resolve to Ty, it will be in
1302 OpaqueType *TypeToResolve = 0;
1304 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1305 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1307 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1308 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1311 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1312 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1313 << (ContainsType ? "true" : "false")
1314 << " level=" << UpRefs[i].NestingLevel << "\n";
1319 // Decrement level of upreference
1320 unsigned Level = --UpRefs[i].NestingLevel;
1321 UpRefs[i].LastContainedTy = Ty;
1323 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1328 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1331 TypeToResolve = UpRefs[i].UpRefTy;
1333 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1334 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1335 --i; // Do not skip the next element.
1339 TypeToResolve->refineAbstractTypeTo(Ty);
1345 /// ParseTypeRec - The recursive function used to process the internal
1346 /// implementation details of types.
1347 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1348 switch (Lex.getKind()) {
1350 return TokError("expected type");
1352 // TypeRec ::= 'float' | 'void' (etc)
1353 Result = Lex.getTyVal();
1356 case lltok::kw_opaque:
1357 // TypeRec ::= 'opaque'
1358 Result = OpaqueType::get(Context);
1362 // TypeRec ::= '{' ... '}'
1363 if (ParseStructType(Result, false))
1366 case lltok::lsquare:
1367 // TypeRec ::= '[' ... ']'
1368 Lex.Lex(); // eat the lsquare.
1369 if (ParseArrayVectorType(Result, false))
1372 case lltok::less: // Either vector or packed struct.
1373 // TypeRec ::= '<' ... '>'
1375 if (Lex.getKind() == lltok::lbrace) {
1376 if (ParseStructType(Result, true) ||
1377 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1379 } else if (ParseArrayVectorType(Result, true))
1382 case lltok::LocalVar:
1383 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1385 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1388 Result = OpaqueType::get(Context);
1389 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1390 std::make_pair(Result,
1392 M->addTypeName(Lex.getStrVal(), Result.get());
1397 case lltok::LocalVarID:
1399 if (Lex.getUIntVal() < NumberedTypes.size())
1400 Result = NumberedTypes[Lex.getUIntVal()];
1402 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1403 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1404 if (I != ForwardRefTypeIDs.end())
1405 Result = I->second.first;
1407 Result = OpaqueType::get(Context);
1408 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1409 std::make_pair(Result,
1415 case lltok::backslash: {
1416 // TypeRec ::= '\' 4
1419 if (ParseUInt32(Val)) return true;
1420 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1421 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1427 // Parse the type suffixes.
1429 switch (Lex.getKind()) {
1431 default: return false;
1433 // TypeRec ::= TypeRec '*'
1435 if (Result.get()->isLabelTy())
1436 return TokError("basic block pointers are invalid");
1437 if (Result.get()->isVoidTy())
1438 return TokError("pointers to void are invalid; use i8* instead");
1439 if (!PointerType::isValidElementType(Result.get()))
1440 return TokError("pointer to this type is invalid");
1441 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1445 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1446 case lltok::kw_addrspace: {
1447 if (Result.get()->isLabelTy())
1448 return TokError("basic block pointers are invalid");
1449 if (Result.get()->isVoidTy())
1450 return TokError("pointers to void are invalid; use i8* instead");
1451 if (!PointerType::isValidElementType(Result.get()))
1452 return TokError("pointer to this type is invalid");
1454 if (ParseOptionalAddrSpace(AddrSpace) ||
1455 ParseToken(lltok::star, "expected '*' in address space"))
1458 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1462 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1464 if (ParseFunctionType(Result))
1471 /// ParseParameterList
1473 /// ::= '(' Arg (',' Arg)* ')'
1475 /// ::= Type OptionalAttributes Value OptionalAttributes
1476 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1477 PerFunctionState &PFS) {
1478 if (ParseToken(lltok::lparen, "expected '(' in call"))
1481 while (Lex.getKind() != lltok::rparen) {
1482 // If this isn't the first argument, we need a comma.
1483 if (!ArgList.empty() &&
1484 ParseToken(lltok::comma, "expected ',' in argument list"))
1487 // Parse the argument.
1489 PATypeHolder ArgTy(Type::getVoidTy(Context));
1490 unsigned ArgAttrs1 = Attribute::None;
1491 unsigned ArgAttrs2 = Attribute::None;
1493 if (ParseType(ArgTy, ArgLoc))
1496 // Otherwise, handle normal operands.
1497 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1498 ParseValue(ArgTy, V, PFS) ||
1499 // FIXME: Should not allow attributes after the argument, remove this
1501 ParseOptionalAttrs(ArgAttrs2, 3))
1503 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1506 Lex.Lex(); // Lex the ')'.
1512 /// ParseArgumentList - Parse the argument list for a function type or function
1513 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1514 /// ::= '(' ArgTypeListI ')'
1518 /// ::= ArgTypeList ',' '...'
1519 /// ::= ArgType (',' ArgType)*
1521 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1522 bool &isVarArg, bool inType) {
1524 assert(Lex.getKind() == lltok::lparen);
1525 Lex.Lex(); // eat the (.
1527 if (Lex.getKind() == lltok::rparen) {
1529 } else if (Lex.getKind() == lltok::dotdotdot) {
1533 LocTy TypeLoc = Lex.getLoc();
1534 PATypeHolder ArgTy(Type::getVoidTy(Context));
1538 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1539 // types (such as a function returning a pointer to itself). If parsing a
1540 // function prototype, we require fully resolved types.
1541 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1542 ParseOptionalAttrs(Attrs, 0)) return true;
1544 if (ArgTy->isVoidTy())
1545 return Error(TypeLoc, "argument can not have void type");
1547 if (Lex.getKind() == lltok::LocalVar ||
1548 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1549 Name = Lex.getStrVal();
1553 if (!FunctionType::isValidArgumentType(ArgTy))
1554 return Error(TypeLoc, "invalid type for function argument");
1556 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1558 while (EatIfPresent(lltok::comma)) {
1559 // Handle ... at end of arg list.
1560 if (EatIfPresent(lltok::dotdotdot)) {
1565 // Otherwise must be an argument type.
1566 TypeLoc = Lex.getLoc();
1567 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1568 ParseOptionalAttrs(Attrs, 0)) return true;
1570 if (ArgTy->isVoidTy())
1571 return Error(TypeLoc, "argument can not have void type");
1573 if (Lex.getKind() == lltok::LocalVar ||
1574 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1575 Name = Lex.getStrVal();
1581 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
1582 return Error(TypeLoc, "invalid type for function argument");
1584 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1588 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1591 /// ParseFunctionType
1592 /// ::= Type ArgumentList OptionalAttrs
1593 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1594 assert(Lex.getKind() == lltok::lparen);
1596 if (!FunctionType::isValidReturnType(Result))
1597 return TokError("invalid function return type");
1599 std::vector<ArgInfo> ArgList;
1602 if (ParseArgumentList(ArgList, isVarArg, true) ||
1603 // FIXME: Allow, but ignore attributes on function types!
1604 // FIXME: Remove in LLVM 3.0
1605 ParseOptionalAttrs(Attrs, 2))
1608 // Reject names on the arguments lists.
1609 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1610 if (!ArgList[i].Name.empty())
1611 return Error(ArgList[i].Loc, "argument name invalid in function type");
1612 if (!ArgList[i].Attrs != 0) {
1613 // Allow but ignore attributes on function types; this permits
1615 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1619 std::vector<const Type*> ArgListTy;
1620 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1621 ArgListTy.push_back(ArgList[i].Type);
1623 Result = HandleUpRefs(FunctionType::get(Result.get(),
1624 ArgListTy, isVarArg));
1628 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1631 /// ::= '{' TypeRec (',' TypeRec)* '}'
1632 /// ::= '<' '{' '}' '>'
1633 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1634 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1635 assert(Lex.getKind() == lltok::lbrace);
1636 Lex.Lex(); // Consume the '{'
1638 if (EatIfPresent(lltok::rbrace)) {
1639 Result = StructType::get(Context, Packed);
1643 std::vector<PATypeHolder> ParamsList;
1644 LocTy EltTyLoc = Lex.getLoc();
1645 if (ParseTypeRec(Result)) return true;
1646 ParamsList.push_back(Result);
1648 if (Result->isVoidTy())
1649 return Error(EltTyLoc, "struct element can not have void type");
1650 if (!StructType::isValidElementType(Result))
1651 return Error(EltTyLoc, "invalid element type for struct");
1653 while (EatIfPresent(lltok::comma)) {
1654 EltTyLoc = Lex.getLoc();
1655 if (ParseTypeRec(Result)) return true;
1657 if (Result->isVoidTy())
1658 return Error(EltTyLoc, "struct element can not have void type");
1659 if (!StructType::isValidElementType(Result))
1660 return Error(EltTyLoc, "invalid element type for struct");
1662 ParamsList.push_back(Result);
1665 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1668 std::vector<const Type*> ParamsListTy;
1669 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1670 ParamsListTy.push_back(ParamsList[i].get());
1671 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1675 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1676 /// token has already been consumed.
1678 /// ::= '[' APSINTVAL 'x' Types ']'
1679 /// ::= '<' APSINTVAL 'x' Types '>'
1680 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1681 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1682 Lex.getAPSIntVal().getBitWidth() > 64)
1683 return TokError("expected number in address space");
1685 LocTy SizeLoc = Lex.getLoc();
1686 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1689 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1692 LocTy TypeLoc = Lex.getLoc();
1693 PATypeHolder EltTy(Type::getVoidTy(Context));
1694 if (ParseTypeRec(EltTy)) return true;
1696 if (EltTy->isVoidTy())
1697 return Error(TypeLoc, "array and vector element type cannot be void");
1699 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1700 "expected end of sequential type"))
1705 return Error(SizeLoc, "zero element vector is illegal");
1706 if ((unsigned)Size != Size)
1707 return Error(SizeLoc, "size too large for vector");
1708 if (!VectorType::isValidElementType(EltTy))
1709 return Error(TypeLoc, "vector element type must be fp or integer");
1710 Result = VectorType::get(EltTy, unsigned(Size));
1712 if (!ArrayType::isValidElementType(EltTy))
1713 return Error(TypeLoc, "invalid array element type");
1714 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1719 //===----------------------------------------------------------------------===//
1720 // Function Semantic Analysis.
1721 //===----------------------------------------------------------------------===//
1723 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1725 : P(p), F(f), FunctionNumber(functionNumber) {
1727 // Insert unnamed arguments into the NumberedVals list.
1728 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1731 NumberedVals.push_back(AI);
1734 LLParser::PerFunctionState::~PerFunctionState() {
1735 // If there were any forward referenced non-basicblock values, delete them.
1736 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1737 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1738 if (!isa<BasicBlock>(I->second.first)) {
1739 I->second.first->replaceAllUsesWith(
1740 UndefValue::get(I->second.first->getType()));
1741 delete I->second.first;
1742 I->second.first = 0;
1745 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1746 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.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;
1755 bool LLParser::PerFunctionState::FinishFunction() {
1756 // Check to see if someone took the address of labels in this block.
1757 if (!P.ForwardRefBlockAddresses.empty()) {
1759 if (!F.getName().empty()) {
1760 FunctionID.Kind = ValID::t_GlobalName;
1761 FunctionID.StrVal = F.getName();
1763 FunctionID.Kind = ValID::t_GlobalID;
1764 FunctionID.UIntVal = FunctionNumber;
1767 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1768 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1769 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1770 // Resolve all these references.
1771 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1774 P.ForwardRefBlockAddresses.erase(FRBAI);
1778 if (!ForwardRefVals.empty())
1779 return P.Error(ForwardRefVals.begin()->second.second,
1780 "use of undefined value '%" + ForwardRefVals.begin()->first +
1782 if (!ForwardRefValIDs.empty())
1783 return P.Error(ForwardRefValIDs.begin()->second.second,
1784 "use of undefined value '%" +
1785 utostr(ForwardRefValIDs.begin()->first) + "'");
1790 /// GetVal - Get a value with the specified name or ID, creating a
1791 /// forward reference record if needed. This can return null if the value
1792 /// exists but does not have the right type.
1793 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1794 const Type *Ty, LocTy Loc) {
1795 // Look this name up in the normal function symbol table.
1796 Value *Val = F.getValueSymbolTable().lookup(Name);
1798 // If this is a forward reference for the value, see if we already created a
1799 // forward ref record.
1801 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1802 I = ForwardRefVals.find(Name);
1803 if (I != ForwardRefVals.end())
1804 Val = I->second.first;
1807 // If we have the value in the symbol table or fwd-ref table, return it.
1809 if (Val->getType() == Ty) return Val;
1810 if (Ty->isLabelTy())
1811 P.Error(Loc, "'%" + Name + "' is not a basic block");
1813 P.Error(Loc, "'%" + Name + "' defined with type '" +
1814 Val->getType()->getDescription() + "'");
1818 // Don't make placeholders with invalid type.
1819 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1820 P.Error(Loc, "invalid use of a non-first-class type");
1824 // Otherwise, create a new forward reference for this value and remember it.
1826 if (Ty->isLabelTy())
1827 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1829 FwdVal = new Argument(Ty, Name);
1831 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1835 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1837 // Look this name up in the normal function symbol table.
1838 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1840 // If this is a forward reference for the value, see if we already created a
1841 // forward ref record.
1843 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1844 I = ForwardRefValIDs.find(ID);
1845 if (I != ForwardRefValIDs.end())
1846 Val = I->second.first;
1849 // If we have the value in the symbol table or fwd-ref table, return it.
1851 if (Val->getType() == Ty) return Val;
1852 if (Ty->isLabelTy())
1853 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1855 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1856 Val->getType()->getDescription() + "'");
1860 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1861 P.Error(Loc, "invalid use of a non-first-class type");
1865 // Otherwise, create a new forward reference for this value and remember it.
1867 if (Ty->isLabelTy())
1868 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1870 FwdVal = new Argument(Ty);
1872 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1876 /// SetInstName - After an instruction is parsed and inserted into its
1877 /// basic block, this installs its name.
1878 bool LLParser::PerFunctionState::SetInstName(int NameID,
1879 const std::string &NameStr,
1880 LocTy NameLoc, Instruction *Inst) {
1881 // If this instruction has void type, it cannot have a name or ID specified.
1882 if (Inst->getType()->isVoidTy()) {
1883 if (NameID != -1 || !NameStr.empty())
1884 return P.Error(NameLoc, "instructions returning void cannot have a name");
1888 // If this was a numbered instruction, verify that the instruction is the
1889 // expected value and resolve any forward references.
1890 if (NameStr.empty()) {
1891 // If neither a name nor an ID was specified, just use the next ID.
1893 NameID = NumberedVals.size();
1895 if (unsigned(NameID) != NumberedVals.size())
1896 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1897 utostr(NumberedVals.size()) + "'");
1899 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1900 ForwardRefValIDs.find(NameID);
1901 if (FI != ForwardRefValIDs.end()) {
1902 if (FI->second.first->getType() != Inst->getType())
1903 return P.Error(NameLoc, "instruction forward referenced with type '" +
1904 FI->second.first->getType()->getDescription() + "'");
1905 FI->second.first->replaceAllUsesWith(Inst);
1906 delete FI->second.first;
1907 ForwardRefValIDs.erase(FI);
1910 NumberedVals.push_back(Inst);
1914 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1915 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1916 FI = ForwardRefVals.find(NameStr);
1917 if (FI != ForwardRefVals.end()) {
1918 if (FI->second.first->getType() != Inst->getType())
1919 return P.Error(NameLoc, "instruction forward referenced with type '" +
1920 FI->second.first->getType()->getDescription() + "'");
1921 FI->second.first->replaceAllUsesWith(Inst);
1922 delete FI->second.first;
1923 ForwardRefVals.erase(FI);
1926 // Set the name on the instruction.
1927 Inst->setName(NameStr);
1929 if (Inst->getNameStr() != NameStr)
1930 return P.Error(NameLoc, "multiple definition of local value named '" +
1935 /// GetBB - Get a basic block with the specified name or ID, creating a
1936 /// forward reference record if needed.
1937 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1939 return cast_or_null<BasicBlock>(GetVal(Name,
1940 Type::getLabelTy(F.getContext()), Loc));
1943 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1944 return cast_or_null<BasicBlock>(GetVal(ID,
1945 Type::getLabelTy(F.getContext()), Loc));
1948 /// DefineBB - Define the specified basic block, which is either named or
1949 /// unnamed. If there is an error, this returns null otherwise it returns
1950 /// the block being defined.
1951 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1955 BB = GetBB(NumberedVals.size(), Loc);
1957 BB = GetBB(Name, Loc);
1958 if (BB == 0) return 0; // Already diagnosed error.
1960 // Move the block to the end of the function. Forward ref'd blocks are
1961 // inserted wherever they happen to be referenced.
1962 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1964 // Remove the block from forward ref sets.
1966 ForwardRefValIDs.erase(NumberedVals.size());
1967 NumberedVals.push_back(BB);
1969 // BB forward references are already in the function symbol table.
1970 ForwardRefVals.erase(Name);
1976 //===----------------------------------------------------------------------===//
1978 //===----------------------------------------------------------------------===//
1980 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1981 /// type implied. For example, if we parse "4" we don't know what integer type
1982 /// it has. The value will later be combined with its type and checked for
1983 /// sanity. PFS is used to convert function-local operands of metadata (since
1984 /// metadata operands are not just parsed here but also converted to values).
1985 /// PFS can be null when we are not parsing metadata values inside a function.
1986 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1987 ID.Loc = Lex.getLoc();
1988 switch (Lex.getKind()) {
1989 default: return TokError("expected value token");
1990 case lltok::GlobalID: // @42
1991 ID.UIntVal = Lex.getUIntVal();
1992 ID.Kind = ValID::t_GlobalID;
1994 case lltok::GlobalVar: // @foo
1995 ID.StrVal = Lex.getStrVal();
1996 ID.Kind = ValID::t_GlobalName;
1998 case lltok::LocalVarID: // %42
1999 ID.UIntVal = Lex.getUIntVal();
2000 ID.Kind = ValID::t_LocalID;
2002 case lltok::LocalVar: // %foo
2003 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2004 ID.StrVal = Lex.getStrVal();
2005 ID.Kind = ValID::t_LocalName;
2007 case lltok::exclaim: // !42, !{...}, or !"foo"
2008 return ParseMetadataValue(ID, PFS);
2010 ID.APSIntVal = Lex.getAPSIntVal();
2011 ID.Kind = ValID::t_APSInt;
2013 case lltok::APFloat:
2014 ID.APFloatVal = Lex.getAPFloatVal();
2015 ID.Kind = ValID::t_APFloat;
2017 case lltok::kw_true:
2018 ID.ConstantVal = ConstantInt::getTrue(Context);
2019 ID.Kind = ValID::t_Constant;
2021 case lltok::kw_false:
2022 ID.ConstantVal = ConstantInt::getFalse(Context);
2023 ID.Kind = ValID::t_Constant;
2025 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2026 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2027 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2029 case lltok::lbrace: {
2030 // ValID ::= '{' ConstVector '}'
2032 SmallVector<Constant*, 16> Elts;
2033 if (ParseGlobalValueVector(Elts) ||
2034 ParseToken(lltok::rbrace, "expected end of struct constant"))
2037 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2038 Elts.size(), false);
2039 ID.Kind = ValID::t_Constant;
2043 // ValID ::= '<' ConstVector '>' --> Vector.
2044 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2046 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2048 SmallVector<Constant*, 16> Elts;
2049 LocTy FirstEltLoc = Lex.getLoc();
2050 if (ParseGlobalValueVector(Elts) ||
2052 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2053 ParseToken(lltok::greater, "expected end of constant"))
2056 if (isPackedStruct) {
2058 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
2059 ID.Kind = ValID::t_Constant;
2064 return Error(ID.Loc, "constant vector must not be empty");
2066 if (!Elts[0]->getType()->isIntegerTy() &&
2067 !Elts[0]->getType()->isFloatingPointTy())
2068 return Error(FirstEltLoc,
2069 "vector elements must have integer or floating point type");
2071 // Verify that all the vector elements have the same type.
2072 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2073 if (Elts[i]->getType() != Elts[0]->getType())
2074 return Error(FirstEltLoc,
2075 "vector element #" + utostr(i) +
2076 " is not of type '" + Elts[0]->getType()->getDescription());
2078 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
2079 ID.Kind = ValID::t_Constant;
2082 case lltok::lsquare: { // Array Constant
2084 SmallVector<Constant*, 16> Elts;
2085 LocTy FirstEltLoc = Lex.getLoc();
2086 if (ParseGlobalValueVector(Elts) ||
2087 ParseToken(lltok::rsquare, "expected end of array constant"))
2090 // Handle empty element.
2092 // Use undef instead of an array because it's inconvenient to determine
2093 // the element type at this point, there being no elements to examine.
2094 ID.Kind = ValID::t_EmptyArray;
2098 if (!Elts[0]->getType()->isFirstClassType())
2099 return Error(FirstEltLoc, "invalid array element type: " +
2100 Elts[0]->getType()->getDescription());
2102 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2104 // Verify all elements are correct type!
2105 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2106 if (Elts[i]->getType() != Elts[0]->getType())
2107 return Error(FirstEltLoc,
2108 "array element #" + utostr(i) +
2109 " is not of type '" +Elts[0]->getType()->getDescription());
2112 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2113 ID.Kind = ValID::t_Constant;
2116 case lltok::kw_c: // c "foo"
2118 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2119 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2120 ID.Kind = ValID::t_Constant;
2123 case lltok::kw_asm: {
2124 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2125 bool HasSideEffect, AlignStack;
2127 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2128 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2129 ParseStringConstant(ID.StrVal) ||
2130 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2131 ParseToken(lltok::StringConstant, "expected constraint string"))
2133 ID.StrVal2 = Lex.getStrVal();
2134 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2135 ID.Kind = ValID::t_InlineAsm;
2139 case lltok::kw_blockaddress: {
2140 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2144 LocTy FnLoc, LabelLoc;
2146 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2148 ParseToken(lltok::comma, "expected comma in block address expression")||
2149 ParseValID(Label) ||
2150 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2153 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2154 return Error(Fn.Loc, "expected function name in blockaddress");
2155 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2156 return Error(Label.Loc, "expected basic block name in blockaddress");
2158 // Make a global variable as a placeholder for this reference.
2159 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2160 false, GlobalValue::InternalLinkage,
2162 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2163 ID.ConstantVal = FwdRef;
2164 ID.Kind = ValID::t_Constant;
2168 case lltok::kw_trunc:
2169 case lltok::kw_zext:
2170 case lltok::kw_sext:
2171 case lltok::kw_fptrunc:
2172 case lltok::kw_fpext:
2173 case lltok::kw_bitcast:
2174 case lltok::kw_uitofp:
2175 case lltok::kw_sitofp:
2176 case lltok::kw_fptoui:
2177 case lltok::kw_fptosi:
2178 case lltok::kw_inttoptr:
2179 case lltok::kw_ptrtoint: {
2180 unsigned Opc = Lex.getUIntVal();
2181 PATypeHolder DestTy(Type::getVoidTy(Context));
2184 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2185 ParseGlobalTypeAndValue(SrcVal) ||
2186 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2187 ParseType(DestTy) ||
2188 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2190 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2191 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2192 SrcVal->getType()->getDescription() + "' to '" +
2193 DestTy->getDescription() + "'");
2194 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2196 ID.Kind = ValID::t_Constant;
2199 case lltok::kw_extractvalue: {
2202 SmallVector<unsigned, 4> Indices;
2203 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2204 ParseGlobalTypeAndValue(Val) ||
2205 ParseIndexList(Indices) ||
2206 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2209 if (!Val->getType()->isAggregateType())
2210 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2211 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2213 return Error(ID.Loc, "invalid indices for extractvalue");
2215 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2216 ID.Kind = ValID::t_Constant;
2219 case lltok::kw_insertvalue: {
2221 Constant *Val0, *Val1;
2222 SmallVector<unsigned, 4> Indices;
2223 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2224 ParseGlobalTypeAndValue(Val0) ||
2225 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2226 ParseGlobalTypeAndValue(Val1) ||
2227 ParseIndexList(Indices) ||
2228 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2230 if (!Val0->getType()->isAggregateType())
2231 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2232 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2234 return Error(ID.Loc, "invalid indices for insertvalue");
2235 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2236 Indices.data(), Indices.size());
2237 ID.Kind = ValID::t_Constant;
2240 case lltok::kw_icmp:
2241 case lltok::kw_fcmp: {
2242 unsigned PredVal, Opc = Lex.getUIntVal();
2243 Constant *Val0, *Val1;
2245 if (ParseCmpPredicate(PredVal, Opc) ||
2246 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2247 ParseGlobalTypeAndValue(Val0) ||
2248 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2249 ParseGlobalTypeAndValue(Val1) ||
2250 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2253 if (Val0->getType() != Val1->getType())
2254 return Error(ID.Loc, "compare operands must have the same type");
2256 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2258 if (Opc == Instruction::FCmp) {
2259 if (!Val0->getType()->isFPOrFPVectorTy())
2260 return Error(ID.Loc, "fcmp requires floating point operands");
2261 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2263 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2264 if (!Val0->getType()->isIntOrIntVectorTy() &&
2265 !Val0->getType()->isPointerTy())
2266 return Error(ID.Loc, "icmp requires pointer or integer operands");
2267 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2269 ID.Kind = ValID::t_Constant;
2273 // Binary Operators.
2275 case lltok::kw_fadd:
2277 case lltok::kw_fsub:
2279 case lltok::kw_fmul:
2280 case lltok::kw_udiv:
2281 case lltok::kw_sdiv:
2282 case lltok::kw_fdiv:
2283 case lltok::kw_urem:
2284 case lltok::kw_srem:
2285 case lltok::kw_frem: {
2289 unsigned Opc = Lex.getUIntVal();
2290 Constant *Val0, *Val1;
2292 LocTy ModifierLoc = Lex.getLoc();
2293 if (Opc == Instruction::Add ||
2294 Opc == Instruction::Sub ||
2295 Opc == Instruction::Mul) {
2296 if (EatIfPresent(lltok::kw_nuw))
2298 if (EatIfPresent(lltok::kw_nsw)) {
2300 if (EatIfPresent(lltok::kw_nuw))
2303 } else if (Opc == Instruction::SDiv) {
2304 if (EatIfPresent(lltok::kw_exact))
2307 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2308 ParseGlobalTypeAndValue(Val0) ||
2309 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2310 ParseGlobalTypeAndValue(Val1) ||
2311 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2313 if (Val0->getType() != Val1->getType())
2314 return Error(ID.Loc, "operands of constexpr must have same type");
2315 if (!Val0->getType()->isIntOrIntVectorTy()) {
2317 return Error(ModifierLoc, "nuw only applies to integer operations");
2319 return Error(ModifierLoc, "nsw only applies to integer operations");
2321 // Check that the type is valid for the operator.
2323 case Instruction::Add:
2324 case Instruction::Sub:
2325 case Instruction::Mul:
2326 case Instruction::UDiv:
2327 case Instruction::SDiv:
2328 case Instruction::URem:
2329 case Instruction::SRem:
2330 if (!Val0->getType()->isIntOrIntVectorTy())
2331 return Error(ID.Loc, "constexpr requires integer operands");
2333 case Instruction::FAdd:
2334 case Instruction::FSub:
2335 case Instruction::FMul:
2336 case Instruction::FDiv:
2337 case Instruction::FRem:
2338 if (!Val0->getType()->isFPOrFPVectorTy())
2339 return Error(ID.Loc, "constexpr requires fp operands");
2341 default: llvm_unreachable("Unknown binary operator!");
2344 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2345 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2346 if (Exact) Flags |= SDivOperator::IsExact;
2347 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2349 ID.Kind = ValID::t_Constant;
2353 // Logical Operations
2355 case lltok::kw_lshr:
2356 case lltok::kw_ashr:
2359 case lltok::kw_xor: {
2360 unsigned Opc = Lex.getUIntVal();
2361 Constant *Val0, *Val1;
2363 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2364 ParseGlobalTypeAndValue(Val0) ||
2365 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2366 ParseGlobalTypeAndValue(Val1) ||
2367 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2369 if (Val0->getType() != Val1->getType())
2370 return Error(ID.Loc, "operands of constexpr must have same type");
2371 if (!Val0->getType()->isIntOrIntVectorTy())
2372 return Error(ID.Loc,
2373 "constexpr requires integer or integer vector operands");
2374 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2375 ID.Kind = ValID::t_Constant;
2379 case lltok::kw_getelementptr:
2380 case lltok::kw_shufflevector:
2381 case lltok::kw_insertelement:
2382 case lltok::kw_extractelement:
2383 case lltok::kw_select: {
2384 unsigned Opc = Lex.getUIntVal();
2385 SmallVector<Constant*, 16> Elts;
2386 bool InBounds = false;
2388 if (Opc == Instruction::GetElementPtr)
2389 InBounds = EatIfPresent(lltok::kw_inbounds);
2390 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2391 ParseGlobalValueVector(Elts) ||
2392 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2395 if (Opc == Instruction::GetElementPtr) {
2396 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2397 return Error(ID.Loc, "getelementptr requires pointer operand");
2399 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2400 (Value**)(Elts.data() + 1),
2402 return Error(ID.Loc, "invalid indices for getelementptr");
2403 ID.ConstantVal = InBounds ?
2404 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2407 ConstantExpr::getGetElementPtr(Elts[0],
2408 Elts.data() + 1, Elts.size() - 1);
2409 } else if (Opc == Instruction::Select) {
2410 if (Elts.size() != 3)
2411 return Error(ID.Loc, "expected three operands to select");
2412 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2414 return Error(ID.Loc, Reason);
2415 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2416 } else if (Opc == Instruction::ShuffleVector) {
2417 if (Elts.size() != 3)
2418 return Error(ID.Loc, "expected three operands to shufflevector");
2419 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2420 return Error(ID.Loc, "invalid operands to shufflevector");
2422 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2423 } else if (Opc == Instruction::ExtractElement) {
2424 if (Elts.size() != 2)
2425 return Error(ID.Loc, "expected two operands to extractelement");
2426 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2427 return Error(ID.Loc, "invalid extractelement operands");
2428 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2430 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2431 if (Elts.size() != 3)
2432 return Error(ID.Loc, "expected three operands to insertelement");
2433 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2434 return Error(ID.Loc, "invalid insertelement operands");
2436 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2439 ID.Kind = ValID::t_Constant;
2448 /// ParseGlobalValue - Parse a global value with the specified type.
2449 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2453 bool Parsed = ParseValID(ID) ||
2454 ConvertValIDToValue(Ty, ID, V, NULL);
2455 if (V && !(C = dyn_cast<Constant>(V)))
2456 return Error(ID.Loc, "global values must be constants");
2460 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2461 PATypeHolder Type(Type::getVoidTy(Context));
2462 return ParseType(Type) ||
2463 ParseGlobalValue(Type, V);
2466 /// ParseGlobalValueVector
2468 /// ::= TypeAndValue (',' TypeAndValue)*
2469 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2471 if (Lex.getKind() == lltok::rbrace ||
2472 Lex.getKind() == lltok::rsquare ||
2473 Lex.getKind() == lltok::greater ||
2474 Lex.getKind() == lltok::rparen)
2478 if (ParseGlobalTypeAndValue(C)) return true;
2481 while (EatIfPresent(lltok::comma)) {
2482 if (ParseGlobalTypeAndValue(C)) return true;
2489 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2490 assert(Lex.getKind() == lltok::lbrace);
2493 SmallVector<Value*, 16> Elts;
2494 if (ParseMDNodeVector(Elts, PFS) ||
2495 ParseToken(lltok::rbrace, "expected end of metadata node"))
2498 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2499 ID.Kind = ValID::t_MDNode;
2503 /// ParseMetadataValue
2507 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2508 assert(Lex.getKind() == lltok::exclaim);
2513 if (Lex.getKind() == lltok::lbrace)
2514 return ParseMetadataListValue(ID, PFS);
2516 // Standalone metadata reference
2518 if (Lex.getKind() == lltok::APSInt) {
2519 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2520 ID.Kind = ValID::t_MDNode;
2525 // ::= '!' STRINGCONSTANT
2526 if (ParseMDString(ID.MDStringVal)) return true;
2527 ID.Kind = ValID::t_MDString;
2532 //===----------------------------------------------------------------------===//
2533 // Function Parsing.
2534 //===----------------------------------------------------------------------===//
2536 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2537 PerFunctionState *PFS) {
2538 if (Ty->isFunctionTy())
2539 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2542 default: llvm_unreachable("Unknown ValID!");
2543 case ValID::t_LocalID:
2544 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2545 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2547 case ValID::t_LocalName:
2548 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2549 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2551 case ValID::t_InlineAsm: {
2552 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2553 const FunctionType *FTy =
2554 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2555 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2556 return Error(ID.Loc, "invalid type for inline asm constraint string");
2557 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2560 case ValID::t_MDNode:
2561 if (!Ty->isMetadataTy())
2562 return Error(ID.Loc, "metadata value must have metadata type");
2565 case ValID::t_MDString:
2566 if (!Ty->isMetadataTy())
2567 return Error(ID.Loc, "metadata value must have metadata type");
2570 case ValID::t_GlobalName:
2571 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2573 case ValID::t_GlobalID:
2574 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2576 case ValID::t_APSInt:
2577 if (!Ty->isIntegerTy())
2578 return Error(ID.Loc, "integer constant must have integer type");
2579 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2580 V = ConstantInt::get(Context, ID.APSIntVal);
2582 case ValID::t_APFloat:
2583 if (!Ty->isFloatingPointTy() ||
2584 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2585 return Error(ID.Loc, "floating point constant invalid for type");
2587 // The lexer has no type info, so builds all float and double FP constants
2588 // as double. Fix this here. Long double does not need this.
2589 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2592 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2595 V = ConstantFP::get(Context, ID.APFloatVal);
2597 if (V->getType() != Ty)
2598 return Error(ID.Loc, "floating point constant does not have type '" +
2599 Ty->getDescription() + "'");
2603 if (!Ty->isPointerTy())
2604 return Error(ID.Loc, "null must be a pointer type");
2605 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2607 case ValID::t_Undef:
2608 // FIXME: LabelTy should not be a first-class type.
2609 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2611 return Error(ID.Loc, "invalid type for undef constant");
2612 V = UndefValue::get(Ty);
2614 case ValID::t_EmptyArray:
2615 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2616 return Error(ID.Loc, "invalid empty array initializer");
2617 V = UndefValue::get(Ty);
2620 // FIXME: LabelTy should not be a first-class type.
2621 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2622 return Error(ID.Loc, "invalid type for null constant");
2623 V = Constant::getNullValue(Ty);
2625 case ValID::t_Constant:
2626 if (ID.ConstantVal->getType() != Ty)
2627 return Error(ID.Loc, "constant expression type mismatch");
2634 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2637 return ParseValID(ID, &PFS) ||
2638 ConvertValIDToValue(Ty, ID, V, &PFS);
2641 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2642 PATypeHolder T(Type::getVoidTy(Context));
2643 return ParseType(T) ||
2644 ParseValue(T, V, PFS);
2647 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2648 PerFunctionState &PFS) {
2651 if (ParseTypeAndValue(V, PFS)) return true;
2652 if (!isa<BasicBlock>(V))
2653 return Error(Loc, "expected a basic block");
2654 BB = cast<BasicBlock>(V);
2660 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2661 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2662 /// OptionalAlign OptGC
2663 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2664 // Parse the linkage.
2665 LocTy LinkageLoc = Lex.getLoc();
2668 unsigned Visibility, RetAttrs;
2670 PATypeHolder RetType(Type::getVoidTy(Context));
2671 LocTy RetTypeLoc = Lex.getLoc();
2672 if (ParseOptionalLinkage(Linkage) ||
2673 ParseOptionalVisibility(Visibility) ||
2674 ParseOptionalCallingConv(CC) ||
2675 ParseOptionalAttrs(RetAttrs, 1) ||
2676 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2679 // Verify that the linkage is ok.
2680 switch ((GlobalValue::LinkageTypes)Linkage) {
2681 case GlobalValue::ExternalLinkage:
2682 break; // always ok.
2683 case GlobalValue::DLLImportLinkage:
2684 case GlobalValue::ExternalWeakLinkage:
2686 return Error(LinkageLoc, "invalid linkage for function definition");
2688 case GlobalValue::PrivateLinkage:
2689 case GlobalValue::LinkerPrivateLinkage:
2690 case GlobalValue::LinkerPrivateWeakLinkage:
2691 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2692 case GlobalValue::InternalLinkage:
2693 case GlobalValue::AvailableExternallyLinkage:
2694 case GlobalValue::LinkOnceAnyLinkage:
2695 case GlobalValue::LinkOnceODRLinkage:
2696 case GlobalValue::WeakAnyLinkage:
2697 case GlobalValue::WeakODRLinkage:
2698 case GlobalValue::DLLExportLinkage:
2700 return Error(LinkageLoc, "invalid linkage for function declaration");
2702 case GlobalValue::AppendingLinkage:
2703 case GlobalValue::CommonLinkage:
2704 return Error(LinkageLoc, "invalid function linkage type");
2707 if (!FunctionType::isValidReturnType(RetType) ||
2708 RetType->isOpaqueTy())
2709 return Error(RetTypeLoc, "invalid function return type");
2711 LocTy NameLoc = Lex.getLoc();
2713 std::string FunctionName;
2714 if (Lex.getKind() == lltok::GlobalVar) {
2715 FunctionName = Lex.getStrVal();
2716 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2717 unsigned NameID = Lex.getUIntVal();
2719 if (NameID != NumberedVals.size())
2720 return TokError("function expected to be numbered '%" +
2721 utostr(NumberedVals.size()) + "'");
2723 return TokError("expected function name");
2728 if (Lex.getKind() != lltok::lparen)
2729 return TokError("expected '(' in function argument list");
2731 std::vector<ArgInfo> ArgList;
2734 std::string Section;
2738 if (ParseArgumentList(ArgList, isVarArg, false) ||
2739 ParseOptionalAttrs(FuncAttrs, 2) ||
2740 (EatIfPresent(lltok::kw_section) &&
2741 ParseStringConstant(Section)) ||
2742 ParseOptionalAlignment(Alignment) ||
2743 (EatIfPresent(lltok::kw_gc) &&
2744 ParseStringConstant(GC)))
2747 // If the alignment was parsed as an attribute, move to the alignment field.
2748 if (FuncAttrs & Attribute::Alignment) {
2749 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2750 FuncAttrs &= ~Attribute::Alignment;
2753 // Okay, if we got here, the function is syntactically valid. Convert types
2754 // and do semantic checks.
2755 std::vector<const Type*> ParamTypeList;
2756 SmallVector<AttributeWithIndex, 8> Attrs;
2757 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2759 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2760 if (FuncAttrs & ObsoleteFuncAttrs) {
2761 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2762 FuncAttrs &= ~ObsoleteFuncAttrs;
2765 if (RetAttrs != Attribute::None)
2766 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2768 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2769 ParamTypeList.push_back(ArgList[i].Type);
2770 if (ArgList[i].Attrs != Attribute::None)
2771 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2774 if (FuncAttrs != Attribute::None)
2775 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2777 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2779 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2780 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2782 const FunctionType *FT =
2783 FunctionType::get(RetType, ParamTypeList, isVarArg);
2784 const PointerType *PFT = PointerType::getUnqual(FT);
2787 if (!FunctionName.empty()) {
2788 // If this was a definition of a forward reference, remove the definition
2789 // from the forward reference table and fill in the forward ref.
2790 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2791 ForwardRefVals.find(FunctionName);
2792 if (FRVI != ForwardRefVals.end()) {
2793 Fn = M->getFunction(FunctionName);
2794 if (Fn->getType() != PFT)
2795 return Error(FRVI->second.second, "invalid forward reference to "
2796 "function '" + FunctionName + "' with wrong type!");
2798 ForwardRefVals.erase(FRVI);
2799 } else if ((Fn = M->getFunction(FunctionName))) {
2800 // If this function already exists in the symbol table, then it is
2801 // multiply defined. We accept a few cases for old backwards compat.
2802 // FIXME: Remove this stuff for LLVM 3.0.
2803 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2804 (!Fn->isDeclaration() && isDefine)) {
2805 // If the redefinition has different type or different attributes,
2806 // reject it. If both have bodies, reject it.
2807 return Error(NameLoc, "invalid redefinition of function '" +
2808 FunctionName + "'");
2809 } else if (Fn->isDeclaration()) {
2810 // Make sure to strip off any argument names so we can't get conflicts.
2811 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2815 } else if (M->getNamedValue(FunctionName)) {
2816 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2820 // If this is a definition of a forward referenced function, make sure the
2822 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2823 = ForwardRefValIDs.find(NumberedVals.size());
2824 if (I != ForwardRefValIDs.end()) {
2825 Fn = cast<Function>(I->second.first);
2826 if (Fn->getType() != PFT)
2827 return Error(NameLoc, "type of definition and forward reference of '@" +
2828 utostr(NumberedVals.size()) +"' disagree");
2829 ForwardRefValIDs.erase(I);
2834 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2835 else // Move the forward-reference to the correct spot in the module.
2836 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2838 if (FunctionName.empty())
2839 NumberedVals.push_back(Fn);
2841 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2842 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2843 Fn->setCallingConv(CC);
2844 Fn->setAttributes(PAL);
2845 Fn->setAlignment(Alignment);
2846 Fn->setSection(Section);
2847 if (!GC.empty()) Fn->setGC(GC.c_str());
2849 // Add all of the arguments we parsed to the function.
2850 Function::arg_iterator ArgIt = Fn->arg_begin();
2851 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2852 // If we run out of arguments in the Function prototype, exit early.
2853 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2854 if (ArgIt == Fn->arg_end()) break;
2856 // If the argument has a name, insert it into the argument symbol table.
2857 if (ArgList[i].Name.empty()) continue;
2859 // Set the name, if it conflicted, it will be auto-renamed.
2860 ArgIt->setName(ArgList[i].Name);
2862 if (ArgIt->getNameStr() != ArgList[i].Name)
2863 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2864 ArgList[i].Name + "'");
2871 /// ParseFunctionBody
2872 /// ::= '{' BasicBlock+ '}'
2873 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2875 bool LLParser::ParseFunctionBody(Function &Fn) {
2876 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2877 return TokError("expected '{' in function body");
2878 Lex.Lex(); // eat the {.
2880 int FunctionNumber = -1;
2881 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2883 PerFunctionState PFS(*this, Fn, FunctionNumber);
2885 // We need at least one basic block.
2886 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2887 return TokError("function body requires at least one basic block");
2889 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2890 if (ParseBasicBlock(PFS)) return true;
2895 // Verify function is ok.
2896 return PFS.FinishFunction();
2900 /// ::= LabelStr? Instruction*
2901 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2902 // If this basic block starts out with a name, remember it.
2904 LocTy NameLoc = Lex.getLoc();
2905 if (Lex.getKind() == lltok::LabelStr) {
2906 Name = Lex.getStrVal();
2910 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2911 if (BB == 0) return true;
2913 std::string NameStr;
2915 // Parse the instructions in this block until we get a terminator.
2917 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2919 // This instruction may have three possibilities for a name: a) none
2920 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2921 LocTy NameLoc = Lex.getLoc();
2925 if (Lex.getKind() == lltok::LocalVarID) {
2926 NameID = Lex.getUIntVal();
2928 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2930 } else if (Lex.getKind() == lltok::LocalVar ||
2931 // FIXME: REMOVE IN LLVM 3.0
2932 Lex.getKind() == lltok::StringConstant) {
2933 NameStr = Lex.getStrVal();
2935 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2939 switch (ParseInstruction(Inst, BB, PFS)) {
2940 default: assert(0 && "Unknown ParseInstruction result!");
2941 case InstError: return true;
2943 BB->getInstList().push_back(Inst);
2945 // With a normal result, we check to see if the instruction is followed by
2946 // a comma and metadata.
2947 if (EatIfPresent(lltok::comma))
2948 if (ParseInstructionMetadata(Inst, &PFS))
2951 case InstExtraComma:
2952 BB->getInstList().push_back(Inst);
2954 // If the instruction parser ate an extra comma at the end of it, it
2955 // *must* be followed by metadata.
2956 if (ParseInstructionMetadata(Inst, &PFS))
2961 // Set the name on the instruction.
2962 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2963 } while (!isa<TerminatorInst>(Inst));
2968 //===----------------------------------------------------------------------===//
2969 // Instruction Parsing.
2970 //===----------------------------------------------------------------------===//
2972 /// ParseInstruction - Parse one of the many different instructions.
2974 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2975 PerFunctionState &PFS) {
2976 lltok::Kind Token = Lex.getKind();
2977 if (Token == lltok::Eof)
2978 return TokError("found end of file when expecting more instructions");
2979 LocTy Loc = Lex.getLoc();
2980 unsigned KeywordVal = Lex.getUIntVal();
2981 Lex.Lex(); // Eat the keyword.
2984 default: return Error(Loc, "expected instruction opcode");
2985 // Terminator Instructions.
2986 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2987 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2988 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2989 case lltok::kw_br: return ParseBr(Inst, PFS);
2990 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2991 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2992 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2993 // Binary Operators.
2996 case lltok::kw_mul: {
2999 LocTy ModifierLoc = Lex.getLoc();
3000 if (EatIfPresent(lltok::kw_nuw))
3002 if (EatIfPresent(lltok::kw_nsw)) {
3004 if (EatIfPresent(lltok::kw_nuw))
3007 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3009 if (!Inst->getType()->isIntOrIntVectorTy()) {
3011 return Error(ModifierLoc, "nuw only applies to integer operations");
3013 return Error(ModifierLoc, "nsw only applies to integer operations");
3016 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3018 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3022 case lltok::kw_fadd:
3023 case lltok::kw_fsub:
3024 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3026 case lltok::kw_sdiv: {
3028 if (EatIfPresent(lltok::kw_exact))
3030 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3033 cast<BinaryOperator>(Inst)->setIsExact(true);
3037 case lltok::kw_udiv:
3038 case lltok::kw_urem:
3039 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3040 case lltok::kw_fdiv:
3041 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3043 case lltok::kw_lshr:
3044 case lltok::kw_ashr:
3047 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3048 case lltok::kw_icmp:
3049 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3051 case lltok::kw_trunc:
3052 case lltok::kw_zext:
3053 case lltok::kw_sext:
3054 case lltok::kw_fptrunc:
3055 case lltok::kw_fpext:
3056 case lltok::kw_bitcast:
3057 case lltok::kw_uitofp:
3058 case lltok::kw_sitofp:
3059 case lltok::kw_fptoui:
3060 case lltok::kw_fptosi:
3061 case lltok::kw_inttoptr:
3062 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3064 case lltok::kw_select: return ParseSelect(Inst, PFS);
3065 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3066 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3067 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3068 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3069 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3070 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3071 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3073 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3074 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
3075 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
3076 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3077 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3078 case lltok::kw_volatile:
3079 if (EatIfPresent(lltok::kw_load))
3080 return ParseLoad(Inst, PFS, true);
3081 else if (EatIfPresent(lltok::kw_store))
3082 return ParseStore(Inst, PFS, true);
3084 return TokError("expected 'load' or 'store'");
3085 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3086 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3087 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3088 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3092 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3093 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3094 if (Opc == Instruction::FCmp) {
3095 switch (Lex.getKind()) {
3096 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3097 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3098 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3099 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3100 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3101 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3102 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3103 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3104 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3105 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3106 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3107 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3108 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3109 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3110 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3111 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3112 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3115 switch (Lex.getKind()) {
3116 default: TokError("expected icmp predicate (e.g. 'eq')");
3117 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3118 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3119 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3120 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3121 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3122 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3123 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3124 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3125 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3126 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3133 //===----------------------------------------------------------------------===//
3134 // Terminator Instructions.
3135 //===----------------------------------------------------------------------===//
3137 /// ParseRet - Parse a return instruction.
3138 /// ::= 'ret' void (',' !dbg, !1)*
3139 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3140 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
3141 /// [[obsolete: LLVM 3.0]]
3142 int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3143 PerFunctionState &PFS) {
3144 PATypeHolder Ty(Type::getVoidTy(Context));
3145 if (ParseType(Ty, true /*void allowed*/)) return true;
3147 if (Ty->isVoidTy()) {
3148 Inst = ReturnInst::Create(Context);
3153 if (ParseValue(Ty, RV, PFS)) return true;
3155 bool ExtraComma = false;
3156 if (EatIfPresent(lltok::comma)) {
3157 // Parse optional custom metadata, e.g. !dbg
3158 if (Lex.getKind() == lltok::MetadataVar) {
3161 // The normal case is one return value.
3162 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3163 // use of 'ret {i32,i32} {i32 1, i32 2}'
3164 SmallVector<Value*, 8> RVs;
3168 // If optional custom metadata, e.g. !dbg is seen then this is the
3170 if (Lex.getKind() == lltok::MetadataVar)
3172 if (ParseTypeAndValue(RV, PFS)) return true;
3174 } while (EatIfPresent(lltok::comma));
3176 RV = UndefValue::get(PFS.getFunction().getReturnType());
3177 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
3178 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3179 BB->getInstList().push_back(I);
3185 Inst = ReturnInst::Create(Context, RV);
3186 return ExtraComma ? InstExtraComma : InstNormal;
3191 /// ::= 'br' TypeAndValue
3192 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3193 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3196 BasicBlock *Op1, *Op2;
3197 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3199 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3200 Inst = BranchInst::Create(BB);
3204 if (Op0->getType() != Type::getInt1Ty(Context))
3205 return Error(Loc, "branch condition must have 'i1' type");
3207 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3208 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3209 ParseToken(lltok::comma, "expected ',' after true destination") ||
3210 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3213 Inst = BranchInst::Create(Op1, Op2, Op0);
3219 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3221 /// ::= (TypeAndValue ',' TypeAndValue)*
3222 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3223 LocTy CondLoc, BBLoc;
3225 BasicBlock *DefaultBB;
3226 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3227 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3228 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3229 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3232 if (!Cond->getType()->isIntegerTy())
3233 return Error(CondLoc, "switch condition must have integer type");
3235 // Parse the jump table pairs.
3236 SmallPtrSet<Value*, 32> SeenCases;
3237 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3238 while (Lex.getKind() != lltok::rsquare) {
3242 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3243 ParseToken(lltok::comma, "expected ',' after case value") ||
3244 ParseTypeAndBasicBlock(DestBB, PFS))
3247 if (!SeenCases.insert(Constant))
3248 return Error(CondLoc, "duplicate case value in switch");
3249 if (!isa<ConstantInt>(Constant))
3250 return Error(CondLoc, "case value is not a constant integer");
3252 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3255 Lex.Lex(); // Eat the ']'.
3257 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3258 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3259 SI->addCase(Table[i].first, Table[i].second);
3266 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3267 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3270 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3271 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3272 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3275 if (!Address->getType()->isPointerTy())
3276 return Error(AddrLoc, "indirectbr address must have pointer type");
3278 // Parse the destination list.
3279 SmallVector<BasicBlock*, 16> DestList;
3281 if (Lex.getKind() != lltok::rsquare) {
3283 if (ParseTypeAndBasicBlock(DestBB, PFS))
3285 DestList.push_back(DestBB);
3287 while (EatIfPresent(lltok::comma)) {
3288 if (ParseTypeAndBasicBlock(DestBB, PFS))
3290 DestList.push_back(DestBB);
3294 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3297 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3298 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3299 IBI->addDestination(DestList[i]);
3306 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3307 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3308 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3309 LocTy CallLoc = Lex.getLoc();
3310 unsigned RetAttrs, FnAttrs;
3312 PATypeHolder RetType(Type::getVoidTy(Context));
3315 SmallVector<ParamInfo, 16> ArgList;
3317 BasicBlock *NormalBB, *UnwindBB;
3318 if (ParseOptionalCallingConv(CC) ||
3319 ParseOptionalAttrs(RetAttrs, 1) ||
3320 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3321 ParseValID(CalleeID) ||
3322 ParseParameterList(ArgList, PFS) ||
3323 ParseOptionalAttrs(FnAttrs, 2) ||
3324 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3325 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3326 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3327 ParseTypeAndBasicBlock(UnwindBB, PFS))
3330 // If RetType is a non-function pointer type, then this is the short syntax
3331 // for the call, which means that RetType is just the return type. Infer the
3332 // rest of the function argument types from the arguments that are present.
3333 const PointerType *PFTy = 0;
3334 const FunctionType *Ty = 0;
3335 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3336 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3337 // Pull out the types of all of the arguments...
3338 std::vector<const Type*> ParamTypes;
3339 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3340 ParamTypes.push_back(ArgList[i].V->getType());
3342 if (!FunctionType::isValidReturnType(RetType))
3343 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3345 Ty = FunctionType::get(RetType, ParamTypes, false);
3346 PFTy = PointerType::getUnqual(Ty);
3349 // Look up the callee.
3351 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3353 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3354 // function attributes.
3355 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3356 if (FnAttrs & ObsoleteFuncAttrs) {
3357 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3358 FnAttrs &= ~ObsoleteFuncAttrs;
3361 // Set up the Attributes for the function.
3362 SmallVector<AttributeWithIndex, 8> Attrs;
3363 if (RetAttrs != Attribute::None)
3364 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3366 SmallVector<Value*, 8> Args;
3368 // Loop through FunctionType's arguments and ensure they are specified
3369 // correctly. Also, gather any parameter attributes.
3370 FunctionType::param_iterator I = Ty->param_begin();
3371 FunctionType::param_iterator E = Ty->param_end();
3372 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3373 const Type *ExpectedTy = 0;
3376 } else if (!Ty->isVarArg()) {
3377 return Error(ArgList[i].Loc, "too many arguments specified");
3380 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3381 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3382 ExpectedTy->getDescription() + "'");
3383 Args.push_back(ArgList[i].V);
3384 if (ArgList[i].Attrs != Attribute::None)
3385 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3389 return Error(CallLoc, "not enough parameters specified for call");
3391 if (FnAttrs != Attribute::None)
3392 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3394 // Finish off the Attributes and check them
3395 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3397 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3398 Args.begin(), Args.end());
3399 II->setCallingConv(CC);
3400 II->setAttributes(PAL);
3407 //===----------------------------------------------------------------------===//
3408 // Binary Operators.
3409 //===----------------------------------------------------------------------===//
3412 /// ::= ArithmeticOps TypeAndValue ',' Value
3414 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3415 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3416 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3417 unsigned Opc, unsigned OperandType) {
3418 LocTy Loc; Value *LHS, *RHS;
3419 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3420 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3421 ParseValue(LHS->getType(), RHS, PFS))
3425 switch (OperandType) {
3426 default: llvm_unreachable("Unknown operand type!");
3427 case 0: // int or FP.
3428 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3429 LHS->getType()->isFPOrFPVectorTy();
3431 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3432 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3436 return Error(Loc, "invalid operand type for instruction");
3438 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3443 /// ::= ArithmeticOps TypeAndValue ',' Value {
3444 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3446 LocTy Loc; Value *LHS, *RHS;
3447 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3448 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3449 ParseValue(LHS->getType(), RHS, PFS))
3452 if (!LHS->getType()->isIntOrIntVectorTy())
3453 return Error(Loc,"instruction requires integer or integer vector operands");
3455 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3461 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3462 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3463 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3465 // Parse the integer/fp comparison predicate.
3469 if (ParseCmpPredicate(Pred, Opc) ||
3470 ParseTypeAndValue(LHS, Loc, PFS) ||
3471 ParseToken(lltok::comma, "expected ',' after compare value") ||
3472 ParseValue(LHS->getType(), RHS, PFS))
3475 if (Opc == Instruction::FCmp) {
3476 if (!LHS->getType()->isFPOrFPVectorTy())
3477 return Error(Loc, "fcmp requires floating point operands");
3478 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3480 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3481 if (!LHS->getType()->isIntOrIntVectorTy() &&
3482 !LHS->getType()->isPointerTy())
3483 return Error(Loc, "icmp requires integer operands");
3484 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3489 //===----------------------------------------------------------------------===//
3490 // Other Instructions.
3491 //===----------------------------------------------------------------------===//
3495 /// ::= CastOpc TypeAndValue 'to' Type
3496 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3498 LocTy Loc; Value *Op;
3499 PATypeHolder DestTy(Type::getVoidTy(Context));
3500 if (ParseTypeAndValue(Op, Loc, PFS) ||
3501 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3505 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3506 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3507 return Error(Loc, "invalid cast opcode for cast from '" +
3508 Op->getType()->getDescription() + "' to '" +
3509 DestTy->getDescription() + "'");
3511 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3516 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3517 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3519 Value *Op0, *Op1, *Op2;
3520 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3521 ParseToken(lltok::comma, "expected ',' after select condition") ||
3522 ParseTypeAndValue(Op1, PFS) ||
3523 ParseToken(lltok::comma, "expected ',' after select value") ||
3524 ParseTypeAndValue(Op2, PFS))
3527 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3528 return Error(Loc, Reason);
3530 Inst = SelectInst::Create(Op0, Op1, Op2);
3535 /// ::= 'va_arg' TypeAndValue ',' Type
3536 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3538 PATypeHolder EltTy(Type::getVoidTy(Context));
3540 if (ParseTypeAndValue(Op, PFS) ||
3541 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3542 ParseType(EltTy, TypeLoc))
3545 if (!EltTy->isFirstClassType())
3546 return Error(TypeLoc, "va_arg requires operand with first class type");
3548 Inst = new VAArgInst(Op, EltTy);
3552 /// ParseExtractElement
3553 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3554 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3557 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3558 ParseToken(lltok::comma, "expected ',' after extract value") ||
3559 ParseTypeAndValue(Op1, PFS))
3562 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3563 return Error(Loc, "invalid extractelement operands");
3565 Inst = ExtractElementInst::Create(Op0, Op1);
3569 /// ParseInsertElement
3570 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3571 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3573 Value *Op0, *Op1, *Op2;
3574 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3575 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3576 ParseTypeAndValue(Op1, PFS) ||
3577 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3578 ParseTypeAndValue(Op2, PFS))
3581 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3582 return Error(Loc, "invalid insertelement operands");
3584 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3588 /// ParseShuffleVector
3589 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3590 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3592 Value *Op0, *Op1, *Op2;
3593 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3594 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3595 ParseTypeAndValue(Op1, PFS) ||
3596 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3597 ParseTypeAndValue(Op2, PFS))
3600 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3601 return Error(Loc, "invalid extractelement operands");
3603 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3608 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3609 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3610 PATypeHolder Ty(Type::getVoidTy(Context));
3612 LocTy TypeLoc = Lex.getLoc();
3614 if (ParseType(Ty) ||
3615 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3616 ParseValue(Ty, Op0, PFS) ||
3617 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3618 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3619 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3622 bool AteExtraComma = false;
3623 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3625 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3627 if (!EatIfPresent(lltok::comma))
3630 if (Lex.getKind() == lltok::MetadataVar) {
3631 AteExtraComma = true;
3635 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3636 ParseValue(Ty, Op0, PFS) ||
3637 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3638 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3639 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3643 if (!Ty->isFirstClassType())
3644 return Error(TypeLoc, "phi node must have first class type");
3646 PHINode *PN = PHINode::Create(Ty);
3647 PN->reserveOperandSpace(PHIVals.size());
3648 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3649 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3651 return AteExtraComma ? InstExtraComma : InstNormal;
3655 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3656 /// ParameterList OptionalAttrs
3657 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3659 unsigned RetAttrs, FnAttrs;
3661 PATypeHolder RetType(Type::getVoidTy(Context));
3664 SmallVector<ParamInfo, 16> ArgList;
3665 LocTy CallLoc = Lex.getLoc();
3667 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3668 ParseOptionalCallingConv(CC) ||
3669 ParseOptionalAttrs(RetAttrs, 1) ||
3670 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3671 ParseValID(CalleeID) ||
3672 ParseParameterList(ArgList, PFS) ||
3673 ParseOptionalAttrs(FnAttrs, 2))
3676 // If RetType is a non-function pointer type, then this is the short syntax
3677 // for the call, which means that RetType is just the return type. Infer the
3678 // rest of the function argument types from the arguments that are present.
3679 const PointerType *PFTy = 0;
3680 const FunctionType *Ty = 0;
3681 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3682 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3683 // Pull out the types of all of the arguments...
3684 std::vector<const Type*> ParamTypes;
3685 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3686 ParamTypes.push_back(ArgList[i].V->getType());
3688 if (!FunctionType::isValidReturnType(RetType))
3689 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3691 Ty = FunctionType::get(RetType, ParamTypes, false);
3692 PFTy = PointerType::getUnqual(Ty);
3695 // Look up the callee.
3697 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3699 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3700 // function attributes.
3701 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3702 if (FnAttrs & ObsoleteFuncAttrs) {
3703 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3704 FnAttrs &= ~ObsoleteFuncAttrs;
3707 // Set up the Attributes for the function.
3708 SmallVector<AttributeWithIndex, 8> Attrs;
3709 if (RetAttrs != Attribute::None)
3710 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3712 SmallVector<Value*, 8> Args;
3714 // Loop through FunctionType's arguments and ensure they are specified
3715 // correctly. Also, gather any parameter attributes.
3716 FunctionType::param_iterator I = Ty->param_begin();
3717 FunctionType::param_iterator E = Ty->param_end();
3718 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3719 const Type *ExpectedTy = 0;
3722 } else if (!Ty->isVarArg()) {
3723 return Error(ArgList[i].Loc, "too many arguments specified");
3726 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3727 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3728 ExpectedTy->getDescription() + "'");
3729 Args.push_back(ArgList[i].V);
3730 if (ArgList[i].Attrs != Attribute::None)
3731 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3735 return Error(CallLoc, "not enough parameters specified for call");
3737 if (FnAttrs != Attribute::None)
3738 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3740 // Finish off the Attributes and check them
3741 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3743 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3744 CI->setTailCall(isTail);
3745 CI->setCallingConv(CC);
3746 CI->setAttributes(PAL);
3751 //===----------------------------------------------------------------------===//
3752 // Memory Instructions.
3753 //===----------------------------------------------------------------------===//
3756 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3757 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3758 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3759 BasicBlock* BB, bool isAlloca) {
3760 PATypeHolder Ty(Type::getVoidTy(Context));
3763 unsigned Alignment = 0;
3764 if (ParseType(Ty)) return true;
3766 bool AteExtraComma = false;
3767 if (EatIfPresent(lltok::comma)) {
3768 if (Lex.getKind() == lltok::kw_align) {
3769 if (ParseOptionalAlignment(Alignment)) return true;
3770 } else if (Lex.getKind() == lltok::MetadataVar) {
3771 AteExtraComma = true;
3773 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3774 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3779 if (Size && !Size->getType()->isIntegerTy())
3780 return Error(SizeLoc, "element count must have integer type");
3783 Inst = new AllocaInst(Ty, Size, Alignment);
3784 return AteExtraComma ? InstExtraComma : InstNormal;
3787 // Autoupgrade old malloc instruction to malloc call.
3788 // FIXME: Remove in LLVM 3.0.
3789 if (Size && !Size->getType()->isIntegerTy(32))
3790 return Error(SizeLoc, "element count must be i32");
3791 const Type *IntPtrTy = Type::getInt32Ty(Context);
3792 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3793 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
3795 // Prototype malloc as "void *(int32)".
3796 // This function is renamed as "malloc" in ValidateEndOfModule().
3797 MallocF = cast<Function>(
3798 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
3799 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
3800 return AteExtraComma ? InstExtraComma : InstNormal;
3804 /// ::= 'free' TypeAndValue
3805 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3807 Value *Val; LocTy Loc;
3808 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3809 if (!Val->getType()->isPointerTy())
3810 return Error(Loc, "operand to free must be a pointer");
3811 Inst = CallInst::CreateFree(Val, BB);
3816 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3817 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3819 Value *Val; LocTy Loc;
3820 unsigned Alignment = 0;
3821 bool AteExtraComma = false;
3822 if (ParseTypeAndValue(Val, Loc, PFS) ||
3823 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3826 if (!Val->getType()->isPointerTy() ||
3827 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3828 return Error(Loc, "load operand must be a pointer to a first class type");
3830 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3831 return AteExtraComma ? InstExtraComma : InstNormal;
3835 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3836 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3838 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3839 unsigned Alignment = 0;
3840 bool AteExtraComma = false;
3841 if (ParseTypeAndValue(Val, Loc, PFS) ||
3842 ParseToken(lltok::comma, "expected ',' after store operand") ||
3843 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3844 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3847 if (!Ptr->getType()->isPointerTy())
3848 return Error(PtrLoc, "store operand must be a pointer");
3849 if (!Val->getType()->isFirstClassType())
3850 return Error(Loc, "store operand must be a first class value");
3851 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3852 return Error(Loc, "stored value and pointer type do not match");
3854 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3855 return AteExtraComma ? InstExtraComma : InstNormal;
3859 /// ::= 'getresult' TypeAndValue ',' i32
3860 /// FIXME: Remove support for getresult in LLVM 3.0
3861 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3862 Value *Val; LocTy ValLoc, EltLoc;
3864 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3865 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3866 ParseUInt32(Element, EltLoc))
3869 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
3870 return Error(ValLoc, "getresult inst requires an aggregate operand");
3871 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3872 return Error(EltLoc, "invalid getresult index for value");
3873 Inst = ExtractValueInst::Create(Val, Element);
3877 /// ParseGetElementPtr
3878 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3879 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3880 Value *Ptr, *Val; LocTy Loc, EltLoc;
3882 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3884 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3886 if (!Ptr->getType()->isPointerTy())
3887 return Error(Loc, "base of getelementptr must be a pointer");
3889 SmallVector<Value*, 16> Indices;
3890 bool AteExtraComma = false;
3891 while (EatIfPresent(lltok::comma)) {
3892 if (Lex.getKind() == lltok::MetadataVar) {
3893 AteExtraComma = true;
3896 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3897 if (!Val->getType()->isIntegerTy())
3898 return Error(EltLoc, "getelementptr index must be an integer");
3899 Indices.push_back(Val);
3902 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3903 Indices.begin(), Indices.end()))
3904 return Error(Loc, "invalid getelementptr indices");
3905 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3907 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3908 return AteExtraComma ? InstExtraComma : InstNormal;
3911 /// ParseExtractValue
3912 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3913 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3914 Value *Val; LocTy Loc;
3915 SmallVector<unsigned, 4> Indices;
3917 if (ParseTypeAndValue(Val, Loc, PFS) ||
3918 ParseIndexList(Indices, AteExtraComma))
3921 if (!Val->getType()->isAggregateType())
3922 return Error(Loc, "extractvalue operand must be aggregate type");
3924 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3926 return Error(Loc, "invalid indices for extractvalue");
3927 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3928 return AteExtraComma ? InstExtraComma : InstNormal;
3931 /// ParseInsertValue
3932 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3933 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3934 Value *Val0, *Val1; LocTy Loc0, Loc1;
3935 SmallVector<unsigned, 4> Indices;
3937 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3938 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3939 ParseTypeAndValue(Val1, Loc1, PFS) ||
3940 ParseIndexList(Indices, AteExtraComma))
3943 if (!Val0->getType()->isAggregateType())
3944 return Error(Loc0, "insertvalue operand must be aggregate type");
3946 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3948 return Error(Loc0, "invalid indices for insertvalue");
3949 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3950 return AteExtraComma ? InstExtraComma : InstNormal;
3953 //===----------------------------------------------------------------------===//
3954 // Embedded metadata.
3955 //===----------------------------------------------------------------------===//
3957 /// ParseMDNodeVector
3958 /// ::= Element (',' Element)*
3960 /// ::= 'null' | TypeAndValue
3961 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3962 PerFunctionState *PFS) {
3963 // Check for an empty list.
3964 if (Lex.getKind() == lltok::rbrace)
3968 // Null is a special case since it is typeless.
3969 if (EatIfPresent(lltok::kw_null)) {
3975 PATypeHolder Ty(Type::getVoidTy(Context));
3977 if (ParseType(Ty) || ParseValID(ID, PFS) ||
3978 ConvertValIDToValue(Ty, ID, V, PFS))
3982 } while (EatIfPresent(lltok::comma));