1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetData.h"
30 static std::string getTypeString(Type *T) {
32 raw_string_ostream Tmp(Result);
37 /// Run: module ::= toplevelentity*
38 bool LLParser::Run() {
42 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
46 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48 bool LLParser::ValidateEndOfModule() {
49 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
57 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
60 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
61 return Error(MDList[i].Loc, "use of undefined metadata '!" +
63 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
66 ForwardRefInstMetadata.clear();
70 // If there are entries in ForwardRefBlockAddresses at this point, they are
71 // references after the function was defined. Resolve those now.
72 while (!ForwardRefBlockAddresses.empty()) {
73 // Okay, we are referencing an already-parsed function, resolve them now.
75 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
76 if (Fn.Kind == ValID::t_GlobalName)
77 TheFn = M->getFunction(Fn.StrVal);
78 else if (Fn.UIntVal < NumberedVals.size())
79 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
82 return Error(Fn.Loc, "unknown function referenced by blockaddress");
84 // Resolve all these references.
85 if (ResolveForwardRefBlockAddresses(TheFn,
86 ForwardRefBlockAddresses.begin()->second,
90 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
93 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
94 if (NumberedTypes[i].second.isValid())
95 return Error(NumberedTypes[i].second,
96 "use of undefined type '%" + Twine(i) + "'");
98 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
99 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
100 if (I->second.second.isValid())
101 return Error(I->second.second,
102 "use of undefined type named '" + I->getKey() + "'");
104 if (!ForwardRefVals.empty())
105 return Error(ForwardRefVals.begin()->second.second,
106 "use of undefined value '@" + ForwardRefVals.begin()->first +
109 if (!ForwardRefValIDs.empty())
110 return Error(ForwardRefValIDs.begin()->second.second,
111 "use of undefined value '@" +
112 Twine(ForwardRefValIDs.begin()->first) + "'");
114 if (!ForwardRefMDNodes.empty())
115 return Error(ForwardRefMDNodes.begin()->second.second,
116 "use of undefined metadata '!" +
117 Twine(ForwardRefMDNodes.begin()->first) + "'");
120 // Look for intrinsic functions and CallInst that need to be upgraded
121 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
122 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
124 // Upgrade to new EH scheme. N.B. This will go away in 3.1.
125 UpgradeExceptionHandling(M);
127 // Check debug info intrinsics.
128 CheckDebugInfoIntrinsics(M);
132 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
133 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
134 PerFunctionState *PFS) {
135 // Loop over all the references, resolving them.
136 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
139 if (Refs[i].first.Kind == ValID::t_LocalName)
140 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
142 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
143 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
144 return Error(Refs[i].first.Loc,
145 "cannot take address of numeric label after the function is defined");
147 Res = dyn_cast_or_null<BasicBlock>(
148 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
152 return Error(Refs[i].first.Loc,
153 "referenced value is not a basic block");
155 // Get the BlockAddress for this and update references to use it.
156 BlockAddress *BA = BlockAddress::get(TheFn, Res);
157 Refs[i].second->replaceAllUsesWith(BA);
158 Refs[i].second->eraseFromParent();
164 //===----------------------------------------------------------------------===//
165 // Top-Level Entities
166 //===----------------------------------------------------------------------===//
168 bool LLParser::ParseTopLevelEntities() {
170 switch (Lex.getKind()) {
171 default: return TokError("expected top-level entity");
172 case lltok::Eof: return false;
173 case lltok::kw_declare: if (ParseDeclare()) return true; break;
174 case lltok::kw_define: if (ParseDefine()) return true; break;
175 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
176 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
177 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
178 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
179 case lltok::LocalVar: if (ParseNamedType()) return true; break;
180 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
181 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
182 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
183 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
185 // The Global variable production with no name can have many different
186 // optional leading prefixes, the production is:
187 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
188 // OptionalAddrSpace OptionalUnNammedAddr
189 // ('constant'|'global') ...
190 case lltok::kw_private: // OptionalLinkage
191 case lltok::kw_linker_private: // OptionalLinkage
192 case lltok::kw_linker_private_weak: // OptionalLinkage
193 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
194 case lltok::kw_internal: // OptionalLinkage
195 case lltok::kw_weak: // OptionalLinkage
196 case lltok::kw_weak_odr: // OptionalLinkage
197 case lltok::kw_linkonce: // OptionalLinkage
198 case lltok::kw_linkonce_odr: // OptionalLinkage
199 case lltok::kw_appending: // OptionalLinkage
200 case lltok::kw_dllexport: // OptionalLinkage
201 case lltok::kw_common: // OptionalLinkage
202 case lltok::kw_dllimport: // OptionalLinkage
203 case lltok::kw_extern_weak: // OptionalLinkage
204 case lltok::kw_external: { // OptionalLinkage
205 unsigned Linkage, Visibility;
206 if (ParseOptionalLinkage(Linkage) ||
207 ParseOptionalVisibility(Visibility) ||
208 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
212 case lltok::kw_default: // OptionalVisibility
213 case lltok::kw_hidden: // OptionalVisibility
214 case lltok::kw_protected: { // OptionalVisibility
216 if (ParseOptionalVisibility(Visibility) ||
217 ParseGlobal("", SMLoc(), 0, false, Visibility))
222 case lltok::kw_thread_local: // OptionalThreadLocal
223 case lltok::kw_addrspace: // OptionalAddrSpace
224 case lltok::kw_constant: // GlobalType
225 case lltok::kw_global: // GlobalType
226 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
234 /// ::= 'module' 'asm' STRINGCONSTANT
235 bool LLParser::ParseModuleAsm() {
236 assert(Lex.getKind() == lltok::kw_module);
240 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
241 ParseStringConstant(AsmStr)) return true;
243 M->appendModuleInlineAsm(AsmStr);
248 /// ::= 'target' 'triple' '=' STRINGCONSTANT
249 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
250 bool LLParser::ParseTargetDefinition() {
251 assert(Lex.getKind() == lltok::kw_target);
254 default: return TokError("unknown target property");
255 case lltok::kw_triple:
257 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
258 ParseStringConstant(Str))
260 M->setTargetTriple(Str);
262 case lltok::kw_datalayout:
264 LocTy SpecifierLoc = Lex.getLoc();
265 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
266 ParseStringConstant(Str))
268 std::string errMsg = TargetData::parseSpecifier(Str);
270 return Error(SpecifierLoc, errMsg);
272 M->setDataLayout(Str);
278 /// ::= 'deplibs' '=' '[' ']'
279 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
280 bool LLParser::ParseDepLibs() {
281 assert(Lex.getKind() == lltok::kw_deplibs);
283 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
284 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
287 if (EatIfPresent(lltok::rsquare))
291 if (ParseStringConstant(Str)) return true;
294 while (EatIfPresent(lltok::comma)) {
295 if (ParseStringConstant(Str)) return true;
299 return ParseToken(lltok::rsquare, "expected ']' at end of list");
302 /// ParseUnnamedType:
303 /// ::= LocalVarID '=' 'type' type
304 bool LLParser::ParseUnnamedType() {
305 LocTy TypeLoc = Lex.getLoc();
306 unsigned TypeID = Lex.getUIntVal();
307 Lex.Lex(); // eat LocalVarID;
309 if (ParseToken(lltok::equal, "expected '=' after name") ||
310 ParseToken(lltok::kw_type, "expected 'type' after '='"))
313 if (TypeID >= NumberedTypes.size())
314 NumberedTypes.resize(TypeID+1);
317 if (ParseStructDefinition(TypeLoc, "",
318 NumberedTypes[TypeID], Result)) return true;
320 if (!isa<StructType>(Result)) {
321 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
323 return Error(TypeLoc, "non-struct types may not be recursive");
324 Entry.first = Result;
325 Entry.second = SMLoc();
333 /// ::= LocalVar '=' 'type' type
334 bool LLParser::ParseNamedType() {
335 std::string Name = Lex.getStrVal();
336 LocTy NameLoc = Lex.getLoc();
337 Lex.Lex(); // eat LocalVar.
339 if (ParseToken(lltok::equal, "expected '=' after name") ||
340 ParseToken(lltok::kw_type, "expected 'type' after name"))
344 if (ParseStructDefinition(NameLoc, Name,
345 NamedTypes[Name], Result)) return true;
347 if (!isa<StructType>(Result)) {
348 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
350 return Error(NameLoc, "non-struct types may not be recursive");
351 Entry.first = Result;
352 Entry.second = SMLoc();
360 /// ::= 'declare' FunctionHeader
361 bool LLParser::ParseDeclare() {
362 assert(Lex.getKind() == lltok::kw_declare);
366 return ParseFunctionHeader(F, false);
370 /// ::= 'define' FunctionHeader '{' ...
371 bool LLParser::ParseDefine() {
372 assert(Lex.getKind() == lltok::kw_define);
376 return ParseFunctionHeader(F, true) ||
377 ParseFunctionBody(*F);
383 bool LLParser::ParseGlobalType(bool &IsConstant) {
384 if (Lex.getKind() == lltok::kw_constant)
386 else if (Lex.getKind() == lltok::kw_global)
390 return TokError("expected 'global' or 'constant'");
396 /// ParseUnnamedGlobal:
397 /// OptionalVisibility ALIAS ...
398 /// OptionalLinkage OptionalVisibility ... -> global variable
399 /// GlobalID '=' OptionalVisibility ALIAS ...
400 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
401 bool LLParser::ParseUnnamedGlobal() {
402 unsigned VarID = NumberedVals.size();
404 LocTy NameLoc = Lex.getLoc();
406 // Handle the GlobalID form.
407 if (Lex.getKind() == lltok::GlobalID) {
408 if (Lex.getUIntVal() != VarID)
409 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
411 Lex.Lex(); // eat GlobalID;
413 if (ParseToken(lltok::equal, "expected '=' after name"))
418 unsigned Linkage, Visibility;
419 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
420 ParseOptionalVisibility(Visibility))
423 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
424 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
425 return ParseAlias(Name, NameLoc, Visibility);
428 /// ParseNamedGlobal:
429 /// GlobalVar '=' OptionalVisibility ALIAS ...
430 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
431 bool LLParser::ParseNamedGlobal() {
432 assert(Lex.getKind() == lltok::GlobalVar);
433 LocTy NameLoc = Lex.getLoc();
434 std::string Name = Lex.getStrVal();
438 unsigned Linkage, Visibility;
439 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
440 ParseOptionalLinkage(Linkage, HasLinkage) ||
441 ParseOptionalVisibility(Visibility))
444 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
445 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
446 return ParseAlias(Name, NameLoc, Visibility);
450 // ::= '!' STRINGCONSTANT
451 bool LLParser::ParseMDString(MDString *&Result) {
453 if (ParseStringConstant(Str)) return true;
454 Result = MDString::get(Context, Str);
459 // ::= '!' MDNodeNumber
461 /// This version of ParseMDNodeID returns the slot number and null in the case
462 /// of a forward reference.
463 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
464 // !{ ..., !42, ... }
465 if (ParseUInt32(SlotNo)) return true;
467 // Check existing MDNode.
468 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
469 Result = NumberedMetadata[SlotNo];
475 bool LLParser::ParseMDNodeID(MDNode *&Result) {
476 // !{ ..., !42, ... }
478 if (ParseMDNodeID(Result, MID)) return true;
480 // If not a forward reference, just return it now.
481 if (Result) return false;
483 // Otherwise, create MDNode forward reference.
484 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
485 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
487 if (NumberedMetadata.size() <= MID)
488 NumberedMetadata.resize(MID+1);
489 NumberedMetadata[MID] = FwdNode;
494 /// ParseNamedMetadata:
495 /// !foo = !{ !1, !2 }
496 bool LLParser::ParseNamedMetadata() {
497 assert(Lex.getKind() == lltok::MetadataVar);
498 std::string Name = Lex.getStrVal();
501 if (ParseToken(lltok::equal, "expected '=' here") ||
502 ParseToken(lltok::exclaim, "Expected '!' here") ||
503 ParseToken(lltok::lbrace, "Expected '{' here"))
506 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
507 if (Lex.getKind() != lltok::rbrace)
509 if (ParseToken(lltok::exclaim, "Expected '!' here"))
513 if (ParseMDNodeID(N)) return true;
515 } while (EatIfPresent(lltok::comma));
517 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
523 /// ParseStandaloneMetadata:
525 bool LLParser::ParseStandaloneMetadata() {
526 assert(Lex.getKind() == lltok::exclaim);
528 unsigned MetadataID = 0;
532 SmallVector<Value *, 16> Elts;
533 if (ParseUInt32(MetadataID) ||
534 ParseToken(lltok::equal, "expected '=' here") ||
535 ParseType(Ty, TyLoc) ||
536 ParseToken(lltok::exclaim, "Expected '!' here") ||
537 ParseToken(lltok::lbrace, "Expected '{' here") ||
538 ParseMDNodeVector(Elts, NULL) ||
539 ParseToken(lltok::rbrace, "expected end of metadata node"))
542 MDNode *Init = MDNode::get(Context, Elts);
544 // See if this was forward referenced, if so, handle it.
545 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
546 FI = ForwardRefMDNodes.find(MetadataID);
547 if (FI != ForwardRefMDNodes.end()) {
548 MDNode *Temp = FI->second.first;
549 Temp->replaceAllUsesWith(Init);
550 MDNode::deleteTemporary(Temp);
551 ForwardRefMDNodes.erase(FI);
553 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
555 if (MetadataID >= NumberedMetadata.size())
556 NumberedMetadata.resize(MetadataID+1);
558 if (NumberedMetadata[MetadataID] != 0)
559 return TokError("Metadata id is already used");
560 NumberedMetadata[MetadataID] = Init;
567 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
570 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
571 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
573 /// Everything through visibility has already been parsed.
575 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
576 unsigned Visibility) {
577 assert(Lex.getKind() == lltok::kw_alias);
580 LocTy LinkageLoc = Lex.getLoc();
581 if (ParseOptionalLinkage(Linkage))
584 if (Linkage != GlobalValue::ExternalLinkage &&
585 Linkage != GlobalValue::WeakAnyLinkage &&
586 Linkage != GlobalValue::WeakODRLinkage &&
587 Linkage != GlobalValue::InternalLinkage &&
588 Linkage != GlobalValue::PrivateLinkage &&
589 Linkage != GlobalValue::LinkerPrivateLinkage &&
590 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
591 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
592 return Error(LinkageLoc, "invalid linkage type for alias");
595 LocTy AliaseeLoc = Lex.getLoc();
596 if (Lex.getKind() != lltok::kw_bitcast &&
597 Lex.getKind() != lltok::kw_getelementptr) {
598 if (ParseGlobalTypeAndValue(Aliasee)) return true;
600 // The bitcast dest type is not present, it is implied by the dest type.
602 if (ParseValID(ID)) return true;
603 if (ID.Kind != ValID::t_Constant)
604 return Error(AliaseeLoc, "invalid aliasee");
605 Aliasee = ID.ConstantVal;
608 if (!Aliasee->getType()->isPointerTy())
609 return Error(AliaseeLoc, "alias must have pointer type");
611 // Okay, create the alias but do not insert it into the module yet.
612 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
613 (GlobalValue::LinkageTypes)Linkage, Name,
615 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
617 // See if this value already exists in the symbol table. If so, it is either
618 // a redefinition or a definition of a forward reference.
619 if (GlobalValue *Val = M->getNamedValue(Name)) {
620 // See if this was a redefinition. If so, there is no entry in
622 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
623 I = ForwardRefVals.find(Name);
624 if (I == ForwardRefVals.end())
625 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
627 // Otherwise, this was a definition of forward ref. Verify that types
629 if (Val->getType() != GA->getType())
630 return Error(NameLoc,
631 "forward reference and definition of alias have different types");
633 // If they agree, just RAUW the old value with the alias and remove the
635 Val->replaceAllUsesWith(GA);
636 Val->eraseFromParent();
637 ForwardRefVals.erase(I);
640 // Insert into the module, we know its name won't collide now.
641 M->getAliasList().push_back(GA);
642 assert(GA->getName() == Name && "Should not be a name conflict!");
648 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
649 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
650 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
651 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
653 /// Everything through visibility has been parsed already.
655 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
656 unsigned Linkage, bool HasLinkage,
657 unsigned Visibility) {
659 bool ThreadLocal, IsConstant, UnnamedAddr;
660 LocTy UnnamedAddrLoc;
664 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
665 ParseOptionalAddrSpace(AddrSpace) ||
666 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
668 ParseGlobalType(IsConstant) ||
669 ParseType(Ty, TyLoc))
672 // If the linkage is specified and is external, then no initializer is
675 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
676 Linkage != GlobalValue::ExternalWeakLinkage &&
677 Linkage != GlobalValue::ExternalLinkage)) {
678 if (ParseGlobalValue(Ty, Init))
682 if (Ty->isFunctionTy() || Ty->isLabelTy())
683 return Error(TyLoc, "invalid type for global variable");
685 GlobalVariable *GV = 0;
687 // See if the global was forward referenced, if so, use the global.
689 if (GlobalValue *GVal = M->getNamedValue(Name)) {
690 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
691 return Error(NameLoc, "redefinition of global '@" + Name + "'");
692 GV = cast<GlobalVariable>(GVal);
695 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
696 I = ForwardRefValIDs.find(NumberedVals.size());
697 if (I != ForwardRefValIDs.end()) {
698 GV = cast<GlobalVariable>(I->second.first);
699 ForwardRefValIDs.erase(I);
704 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
705 Name, 0, false, AddrSpace);
707 if (GV->getType()->getElementType() != Ty)
709 "forward reference and definition of global have different types");
711 // Move the forward-reference to the correct spot in the module.
712 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
716 NumberedVals.push_back(GV);
718 // Set the parsed properties on the global.
720 GV->setInitializer(Init);
721 GV->setConstant(IsConstant);
722 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
723 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
724 GV->setThreadLocal(ThreadLocal);
725 GV->setUnnamedAddr(UnnamedAddr);
727 // Parse attributes on the global.
728 while (Lex.getKind() == lltok::comma) {
731 if (Lex.getKind() == lltok::kw_section) {
733 GV->setSection(Lex.getStrVal());
734 if (ParseToken(lltok::StringConstant, "expected global section string"))
736 } else if (Lex.getKind() == lltok::kw_align) {
738 if (ParseOptionalAlignment(Alignment)) return true;
739 GV->setAlignment(Alignment);
741 TokError("unknown global variable property!");
749 //===----------------------------------------------------------------------===//
750 // GlobalValue Reference/Resolution Routines.
751 //===----------------------------------------------------------------------===//
753 /// GetGlobalVal - Get a value with the specified name or ID, creating a
754 /// forward reference record if needed. This can return null if the value
755 /// exists but does not have the right type.
756 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
758 PointerType *PTy = dyn_cast<PointerType>(Ty);
760 Error(Loc, "global variable reference must have pointer type");
764 // Look this name up in the normal function symbol table.
766 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
768 // If this is a forward reference for the value, see if we already created a
769 // forward ref record.
771 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
772 I = ForwardRefVals.find(Name);
773 if (I != ForwardRefVals.end())
774 Val = I->second.first;
777 // If we have the value in the symbol table or fwd-ref table, return it.
779 if (Val->getType() == Ty) return Val;
780 Error(Loc, "'@" + Name + "' defined with type '" +
781 getTypeString(Val->getType()) + "'");
785 // Otherwise, create a new forward reference for this value and remember it.
787 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
788 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
790 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
791 GlobalValue::ExternalWeakLinkage, 0, Name);
793 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
797 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
798 PointerType *PTy = dyn_cast<PointerType>(Ty);
800 Error(Loc, "global variable reference must have pointer type");
804 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
806 // If this is a forward reference for the value, see if we already created a
807 // forward ref record.
809 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
810 I = ForwardRefValIDs.find(ID);
811 if (I != ForwardRefValIDs.end())
812 Val = I->second.first;
815 // If we have the value in the symbol table or fwd-ref table, return it.
817 if (Val->getType() == Ty) return Val;
818 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
819 getTypeString(Val->getType()) + "'");
823 // Otherwise, create a new forward reference for this value and remember it.
825 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
826 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
828 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
829 GlobalValue::ExternalWeakLinkage, 0, "");
831 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
836 //===----------------------------------------------------------------------===//
838 //===----------------------------------------------------------------------===//
840 /// ParseToken - If the current token has the specified kind, eat it and return
841 /// success. Otherwise, emit the specified error and return failure.
842 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
843 if (Lex.getKind() != T)
844 return TokError(ErrMsg);
849 /// ParseStringConstant
850 /// ::= StringConstant
851 bool LLParser::ParseStringConstant(std::string &Result) {
852 if (Lex.getKind() != lltok::StringConstant)
853 return TokError("expected string constant");
854 Result = Lex.getStrVal();
861 bool LLParser::ParseUInt32(unsigned &Val) {
862 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
863 return TokError("expected integer");
864 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
865 if (Val64 != unsigned(Val64))
866 return TokError("expected 32-bit integer (too large)");
873 /// ParseOptionalAddrSpace
875 /// := 'addrspace' '(' uint32 ')'
876 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
878 if (!EatIfPresent(lltok::kw_addrspace))
880 return ParseToken(lltok::lparen, "expected '(' in address space") ||
881 ParseUInt32(AddrSpace) ||
882 ParseToken(lltok::rparen, "expected ')' in address space");
885 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
886 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
887 /// 2: function attr.
888 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
889 Attrs = Attribute::None;
890 LocTy AttrLoc = Lex.getLoc();
893 switch (Lex.getKind()) {
894 default: // End of attributes.
895 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
896 return Error(AttrLoc, "invalid use of function-only attribute");
898 // As a hack, we allow "align 2" on functions as a synonym for
901 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
902 return Error(AttrLoc, "invalid use of attribute on a function");
904 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
905 return Error(AttrLoc, "invalid use of parameter-only attribute");
908 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
909 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
910 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
911 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
912 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
913 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
914 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
915 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
917 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
918 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
919 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
920 case lltok::kw_returns_twice: Attrs |= Attribute::ReturnsTwice; break;
921 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
922 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
923 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
924 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
925 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
926 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
927 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
928 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
929 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
930 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
931 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
932 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
934 case lltok::kw_alignstack: {
936 if (ParseOptionalStackAlignment(Alignment))
938 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
942 case lltok::kw_align: {
944 if (ParseOptionalAlignment(Alignment))
946 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
955 /// ParseOptionalLinkage
958 /// ::= 'linker_private'
959 /// ::= 'linker_private_weak'
960 /// ::= 'linker_private_weak_def_auto'
965 /// ::= 'linkonce_odr'
966 /// ::= 'available_externally'
971 /// ::= 'extern_weak'
973 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
975 switch (Lex.getKind()) {
976 default: Res=GlobalValue::ExternalLinkage; return false;
977 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
978 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
979 case lltok::kw_linker_private_weak:
980 Res = GlobalValue::LinkerPrivateWeakLinkage;
982 case lltok::kw_linker_private_weak_def_auto:
983 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
985 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
986 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
987 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
988 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
989 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
990 case lltok::kw_available_externally:
991 Res = GlobalValue::AvailableExternallyLinkage;
993 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
994 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
995 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
996 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
997 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
998 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1005 /// ParseOptionalVisibility
1011 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1012 switch (Lex.getKind()) {
1013 default: Res = GlobalValue::DefaultVisibility; return false;
1014 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1015 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1016 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1022 /// ParseOptionalCallingConv
1027 /// ::= 'x86_stdcallcc'
1028 /// ::= 'x86_fastcallcc'
1029 /// ::= 'x86_thiscallcc'
1030 /// ::= 'arm_apcscc'
1031 /// ::= 'arm_aapcscc'
1032 /// ::= 'arm_aapcs_vfpcc'
1033 /// ::= 'msp430_intrcc'
1034 /// ::= 'ptx_kernel'
1035 /// ::= 'ptx_device'
1038 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1039 switch (Lex.getKind()) {
1040 default: CC = CallingConv::C; return false;
1041 case lltok::kw_ccc: CC = CallingConv::C; break;
1042 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1043 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1044 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1045 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1046 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1047 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1048 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1049 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1050 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1051 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1052 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1053 case lltok::kw_cc: {
1054 unsigned ArbitraryCC;
1056 if (ParseUInt32(ArbitraryCC)) {
1059 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1069 /// ParseInstructionMetadata
1070 /// ::= !dbg !42 (',' !dbg !57)*
1071 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1072 PerFunctionState *PFS) {
1074 if (Lex.getKind() != lltok::MetadataVar)
1075 return TokError("expected metadata after comma");
1077 std::string Name = Lex.getStrVal();
1078 unsigned MDK = M->getMDKindID(Name.c_str());
1082 SMLoc Loc = Lex.getLoc();
1084 if (ParseToken(lltok::exclaim, "expected '!' here"))
1087 // This code is similar to that of ParseMetadataValue, however it needs to
1088 // have special-case code for a forward reference; see the comments on
1089 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1090 // at the top level here.
1091 if (Lex.getKind() == lltok::lbrace) {
1093 if (ParseMetadataListValue(ID, PFS))
1095 assert(ID.Kind == ValID::t_MDNode);
1096 Inst->setMetadata(MDK, ID.MDNodeVal);
1098 unsigned NodeID = 0;
1099 if (ParseMDNodeID(Node, NodeID))
1102 // If we got the node, add it to the instruction.
1103 Inst->setMetadata(MDK, Node);
1105 MDRef R = { Loc, MDK, NodeID };
1106 // Otherwise, remember that this should be resolved later.
1107 ForwardRefInstMetadata[Inst].push_back(R);
1111 // If this is the end of the list, we're done.
1112 } while (EatIfPresent(lltok::comma));
1116 /// ParseOptionalAlignment
1119 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1121 if (!EatIfPresent(lltok::kw_align))
1123 LocTy AlignLoc = Lex.getLoc();
1124 if (ParseUInt32(Alignment)) return true;
1125 if (!isPowerOf2_32(Alignment))
1126 return Error(AlignLoc, "alignment is not a power of two");
1127 if (Alignment > Value::MaximumAlignment)
1128 return Error(AlignLoc, "huge alignments are not supported yet");
1132 /// ParseOptionalCommaAlign
1136 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1138 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1139 bool &AteExtraComma) {
1140 AteExtraComma = false;
1141 while (EatIfPresent(lltok::comma)) {
1142 // Metadata at the end is an early exit.
1143 if (Lex.getKind() == lltok::MetadataVar) {
1144 AteExtraComma = true;
1148 if (Lex.getKind() != lltok::kw_align)
1149 return Error(Lex.getLoc(), "expected metadata or 'align'");
1151 if (ParseOptionalAlignment(Alignment)) return true;
1157 /// ParseScopeAndOrdering
1158 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1161 /// This sets Scope and Ordering to the parsed values.
1162 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1163 AtomicOrdering &Ordering) {
1167 Scope = CrossThread;
1168 if (EatIfPresent(lltok::kw_singlethread))
1169 Scope = SingleThread;
1170 switch (Lex.getKind()) {
1171 default: return TokError("Expected ordering on atomic instruction");
1172 case lltok::kw_unordered: Ordering = Unordered; break;
1173 case lltok::kw_monotonic: Ordering = Monotonic; break;
1174 case lltok::kw_acquire: Ordering = Acquire; break;
1175 case lltok::kw_release: Ordering = Release; break;
1176 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1177 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1183 /// ParseOptionalStackAlignment
1185 /// ::= 'alignstack' '(' 4 ')'
1186 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1188 if (!EatIfPresent(lltok::kw_alignstack))
1190 LocTy ParenLoc = Lex.getLoc();
1191 if (!EatIfPresent(lltok::lparen))
1192 return Error(ParenLoc, "expected '('");
1193 LocTy AlignLoc = Lex.getLoc();
1194 if (ParseUInt32(Alignment)) return true;
1195 ParenLoc = Lex.getLoc();
1196 if (!EatIfPresent(lltok::rparen))
1197 return Error(ParenLoc, "expected ')'");
1198 if (!isPowerOf2_32(Alignment))
1199 return Error(AlignLoc, "stack alignment is not a power of two");
1203 /// ParseIndexList - This parses the index list for an insert/extractvalue
1204 /// instruction. This sets AteExtraComma in the case where we eat an extra
1205 /// comma at the end of the line and find that it is followed by metadata.
1206 /// Clients that don't allow metadata can call the version of this function that
1207 /// only takes one argument.
1210 /// ::= (',' uint32)+
1212 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1213 bool &AteExtraComma) {
1214 AteExtraComma = false;
1216 if (Lex.getKind() != lltok::comma)
1217 return TokError("expected ',' as start of index list");
1219 while (EatIfPresent(lltok::comma)) {
1220 if (Lex.getKind() == lltok::MetadataVar) {
1221 AteExtraComma = true;
1225 if (ParseUInt32(Idx)) return true;
1226 Indices.push_back(Idx);
1232 //===----------------------------------------------------------------------===//
1234 //===----------------------------------------------------------------------===//
1236 /// ParseType - Parse a type.
1237 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1238 SMLoc TypeLoc = Lex.getLoc();
1239 switch (Lex.getKind()) {
1241 return TokError("expected type");
1243 // Type ::= 'float' | 'void' (etc)
1244 Result = Lex.getTyVal();
1248 // Type ::= StructType
1249 if (ParseAnonStructType(Result, false))
1252 case lltok::lsquare:
1253 // Type ::= '[' ... ']'
1254 Lex.Lex(); // eat the lsquare.
1255 if (ParseArrayVectorType(Result, false))
1258 case lltok::less: // Either vector or packed struct.
1259 // Type ::= '<' ... '>'
1261 if (Lex.getKind() == lltok::lbrace) {
1262 if (ParseAnonStructType(Result, true) ||
1263 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1265 } else if (ParseArrayVectorType(Result, true))
1268 case lltok::LocalVar: {
1270 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1272 // If the type hasn't been defined yet, create a forward definition and
1273 // remember where that forward def'n was seen (in case it never is defined).
1274 if (Entry.first == 0) {
1275 Entry.first = StructType::create(Context, Lex.getStrVal());
1276 Entry.second = Lex.getLoc();
1278 Result = Entry.first;
1283 case lltok::LocalVarID: {
1285 if (Lex.getUIntVal() >= NumberedTypes.size())
1286 NumberedTypes.resize(Lex.getUIntVal()+1);
1287 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1289 // If the type hasn't been defined yet, create a forward definition and
1290 // remember where that forward def'n was seen (in case it never is defined).
1291 if (Entry.first == 0) {
1292 Entry.first = StructType::create(Context);
1293 Entry.second = Lex.getLoc();
1295 Result = Entry.first;
1301 // Parse the type suffixes.
1303 switch (Lex.getKind()) {
1306 if (!AllowVoid && Result->isVoidTy())
1307 return Error(TypeLoc, "void type only allowed for function results");
1310 // Type ::= Type '*'
1312 if (Result->isLabelTy())
1313 return TokError("basic block pointers are invalid");
1314 if (Result->isVoidTy())
1315 return TokError("pointers to void are invalid - use i8* instead");
1316 if (!PointerType::isValidElementType(Result))
1317 return TokError("pointer to this type is invalid");
1318 Result = PointerType::getUnqual(Result);
1322 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1323 case lltok::kw_addrspace: {
1324 if (Result->isLabelTy())
1325 return TokError("basic block pointers are invalid");
1326 if (Result->isVoidTy())
1327 return TokError("pointers to void are invalid; use i8* instead");
1328 if (!PointerType::isValidElementType(Result))
1329 return TokError("pointer to this type is invalid");
1331 if (ParseOptionalAddrSpace(AddrSpace) ||
1332 ParseToken(lltok::star, "expected '*' in address space"))
1335 Result = PointerType::get(Result, AddrSpace);
1339 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1341 if (ParseFunctionType(Result))
1348 /// ParseParameterList
1350 /// ::= '(' Arg (',' Arg)* ')'
1352 /// ::= Type OptionalAttributes Value OptionalAttributes
1353 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1354 PerFunctionState &PFS) {
1355 if (ParseToken(lltok::lparen, "expected '(' in call"))
1358 while (Lex.getKind() != lltok::rparen) {
1359 // If this isn't the first argument, we need a comma.
1360 if (!ArgList.empty() &&
1361 ParseToken(lltok::comma, "expected ',' in argument list"))
1364 // Parse the argument.
1367 unsigned ArgAttrs1 = Attribute::None;
1368 unsigned ArgAttrs2 = Attribute::None;
1370 if (ParseType(ArgTy, ArgLoc))
1373 // Otherwise, handle normal operands.
1374 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
1376 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1379 Lex.Lex(); // Lex the ')'.
1385 /// ParseArgumentList - Parse the argument list for a function type or function
1387 /// ::= '(' ArgTypeListI ')'
1391 /// ::= ArgTypeList ',' '...'
1392 /// ::= ArgType (',' ArgType)*
1394 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1397 assert(Lex.getKind() == lltok::lparen);
1398 Lex.Lex(); // eat the (.
1400 if (Lex.getKind() == lltok::rparen) {
1402 } else if (Lex.getKind() == lltok::dotdotdot) {
1406 LocTy TypeLoc = Lex.getLoc();
1411 if (ParseType(ArgTy) ||
1412 ParseOptionalAttrs(Attrs, 0)) return true;
1414 if (ArgTy->isVoidTy())
1415 return Error(TypeLoc, "argument can not have void type");
1417 if (Lex.getKind() == lltok::LocalVar) {
1418 Name = Lex.getStrVal();
1422 if (!FunctionType::isValidArgumentType(ArgTy))
1423 return Error(TypeLoc, "invalid type for function argument");
1425 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1427 while (EatIfPresent(lltok::comma)) {
1428 // Handle ... at end of arg list.
1429 if (EatIfPresent(lltok::dotdotdot)) {
1434 // Otherwise must be an argument type.
1435 TypeLoc = Lex.getLoc();
1436 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
1438 if (ArgTy->isVoidTy())
1439 return Error(TypeLoc, "argument can not have void type");
1441 if (Lex.getKind() == lltok::LocalVar) {
1442 Name = Lex.getStrVal();
1448 if (!ArgTy->isFirstClassType())
1449 return Error(TypeLoc, "invalid type for function argument");
1451 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1455 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1458 /// ParseFunctionType
1459 /// ::= Type ArgumentList OptionalAttrs
1460 bool LLParser::ParseFunctionType(Type *&Result) {
1461 assert(Lex.getKind() == lltok::lparen);
1463 if (!FunctionType::isValidReturnType(Result))
1464 return TokError("invalid function return type");
1466 SmallVector<ArgInfo, 8> ArgList;
1468 if (ParseArgumentList(ArgList, isVarArg))
1471 // Reject names on the arguments lists.
1472 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1473 if (!ArgList[i].Name.empty())
1474 return Error(ArgList[i].Loc, "argument name invalid in function type");
1475 if (ArgList[i].Attrs != 0)
1476 return Error(ArgList[i].Loc,
1477 "argument attributes invalid in function type");
1480 SmallVector<Type*, 16> ArgListTy;
1481 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1482 ArgListTy.push_back(ArgList[i].Ty);
1484 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1488 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1490 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1491 SmallVector<Type*, 8> Elts;
1492 if (ParseStructBody(Elts)) return true;
1494 Result = StructType::get(Context, Elts, Packed);
1498 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1499 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1500 std::pair<Type*, LocTy> &Entry,
1502 // If the type was already defined, diagnose the redefinition.
1503 if (Entry.first && !Entry.second.isValid())
1504 return Error(TypeLoc, "redefinition of type");
1506 // If we have opaque, just return without filling in the definition for the
1507 // struct. This counts as a definition as far as the .ll file goes.
1508 if (EatIfPresent(lltok::kw_opaque)) {
1509 // This type is being defined, so clear the location to indicate this.
1510 Entry.second = SMLoc();
1512 // If this type number has never been uttered, create it.
1513 if (Entry.first == 0)
1514 Entry.first = StructType::create(Context, Name);
1515 ResultTy = Entry.first;
1519 // If the type starts with '<', then it is either a packed struct or a vector.
1520 bool isPacked = EatIfPresent(lltok::less);
1522 // If we don't have a struct, then we have a random type alias, which we
1523 // accept for compatibility with old files. These types are not allowed to be
1524 // forward referenced and not allowed to be recursive.
1525 if (Lex.getKind() != lltok::lbrace) {
1527 return Error(TypeLoc, "forward references to non-struct type");
1531 return ParseArrayVectorType(ResultTy, true);
1532 return ParseType(ResultTy);
1535 // This type is being defined, so clear the location to indicate this.
1536 Entry.second = SMLoc();
1538 // If this type number has never been uttered, create it.
1539 if (Entry.first == 0)
1540 Entry.first = StructType::create(Context, Name);
1542 StructType *STy = cast<StructType>(Entry.first);
1544 SmallVector<Type*, 8> Body;
1545 if (ParseStructBody(Body) ||
1546 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1549 STy->setBody(Body, isPacked);
1555 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1558 /// ::= '{' Type (',' Type)* '}'
1559 /// ::= '<' '{' '}' '>'
1560 /// ::= '<' '{' Type (',' Type)* '}' '>'
1561 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1562 assert(Lex.getKind() == lltok::lbrace);
1563 Lex.Lex(); // Consume the '{'
1565 // Handle the empty struct.
1566 if (EatIfPresent(lltok::rbrace))
1569 LocTy EltTyLoc = Lex.getLoc();
1571 if (ParseType(Ty)) return true;
1574 if (!StructType::isValidElementType(Ty))
1575 return Error(EltTyLoc, "invalid element type for struct");
1577 while (EatIfPresent(lltok::comma)) {
1578 EltTyLoc = Lex.getLoc();
1579 if (ParseType(Ty)) return true;
1581 if (!StructType::isValidElementType(Ty))
1582 return Error(EltTyLoc, "invalid element type for struct");
1587 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1590 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1591 /// token has already been consumed.
1593 /// ::= '[' APSINTVAL 'x' Types ']'
1594 /// ::= '<' APSINTVAL 'x' Types '>'
1595 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1596 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1597 Lex.getAPSIntVal().getBitWidth() > 64)
1598 return TokError("expected number in address space");
1600 LocTy SizeLoc = Lex.getLoc();
1601 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1604 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1607 LocTy TypeLoc = Lex.getLoc();
1609 if (ParseType(EltTy)) return true;
1611 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1612 "expected end of sequential type"))
1617 return Error(SizeLoc, "zero element vector is illegal");
1618 if ((unsigned)Size != Size)
1619 return Error(SizeLoc, "size too large for vector");
1620 if (!VectorType::isValidElementType(EltTy))
1621 return Error(TypeLoc, "vector element type must be fp or integer");
1622 Result = VectorType::get(EltTy, unsigned(Size));
1624 if (!ArrayType::isValidElementType(EltTy))
1625 return Error(TypeLoc, "invalid array element type");
1626 Result = ArrayType::get(EltTy, Size);
1631 //===----------------------------------------------------------------------===//
1632 // Function Semantic Analysis.
1633 //===----------------------------------------------------------------------===//
1635 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1637 : P(p), F(f), FunctionNumber(functionNumber) {
1639 // Insert unnamed arguments into the NumberedVals list.
1640 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1643 NumberedVals.push_back(AI);
1646 LLParser::PerFunctionState::~PerFunctionState() {
1647 // If there were any forward referenced non-basicblock values, delete them.
1648 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1649 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1650 if (!isa<BasicBlock>(I->second.first)) {
1651 I->second.first->replaceAllUsesWith(
1652 UndefValue::get(I->second.first->getType()));
1653 delete I->second.first;
1654 I->second.first = 0;
1657 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1658 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1659 if (!isa<BasicBlock>(I->second.first)) {
1660 I->second.first->replaceAllUsesWith(
1661 UndefValue::get(I->second.first->getType()));
1662 delete I->second.first;
1663 I->second.first = 0;
1667 bool LLParser::PerFunctionState::FinishFunction() {
1668 // Check to see if someone took the address of labels in this block.
1669 if (!P.ForwardRefBlockAddresses.empty()) {
1671 if (!F.getName().empty()) {
1672 FunctionID.Kind = ValID::t_GlobalName;
1673 FunctionID.StrVal = F.getName();
1675 FunctionID.Kind = ValID::t_GlobalID;
1676 FunctionID.UIntVal = FunctionNumber;
1679 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1680 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1681 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1682 // Resolve all these references.
1683 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1686 P.ForwardRefBlockAddresses.erase(FRBAI);
1690 if (!ForwardRefVals.empty())
1691 return P.Error(ForwardRefVals.begin()->second.second,
1692 "use of undefined value '%" + ForwardRefVals.begin()->first +
1694 if (!ForwardRefValIDs.empty())
1695 return P.Error(ForwardRefValIDs.begin()->second.second,
1696 "use of undefined value '%" +
1697 Twine(ForwardRefValIDs.begin()->first) + "'");
1702 /// GetVal - Get a value with the specified name or ID, creating a
1703 /// forward reference record if needed. This can return null if the value
1704 /// exists but does not have the right type.
1705 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1706 Type *Ty, LocTy Loc) {
1707 // Look this name up in the normal function symbol table.
1708 Value *Val = F.getValueSymbolTable().lookup(Name);
1710 // If this is a forward reference for the value, see if we already created a
1711 // forward ref record.
1713 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1714 I = ForwardRefVals.find(Name);
1715 if (I != ForwardRefVals.end())
1716 Val = I->second.first;
1719 // If we have the value in the symbol table or fwd-ref table, return it.
1721 if (Val->getType() == Ty) return Val;
1722 if (Ty->isLabelTy())
1723 P.Error(Loc, "'%" + Name + "' is not a basic block");
1725 P.Error(Loc, "'%" + Name + "' defined with type '" +
1726 getTypeString(Val->getType()) + "'");
1730 // Don't make placeholders with invalid type.
1731 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1732 P.Error(Loc, "invalid use of a non-first-class type");
1736 // Otherwise, create a new forward reference for this value and remember it.
1738 if (Ty->isLabelTy())
1739 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1741 FwdVal = new Argument(Ty, Name);
1743 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1747 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1749 // Look this name up in the normal function symbol table.
1750 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1752 // If this is a forward reference for the value, see if we already created a
1753 // forward ref record.
1755 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1756 I = ForwardRefValIDs.find(ID);
1757 if (I != ForwardRefValIDs.end())
1758 Val = I->second.first;
1761 // If we have the value in the symbol table or fwd-ref table, return it.
1763 if (Val->getType() == Ty) return Val;
1764 if (Ty->isLabelTy())
1765 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1767 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1768 getTypeString(Val->getType()) + "'");
1772 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1773 P.Error(Loc, "invalid use of a non-first-class type");
1777 // Otherwise, create a new forward reference for this value and remember it.
1779 if (Ty->isLabelTy())
1780 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1782 FwdVal = new Argument(Ty);
1784 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1788 /// SetInstName - After an instruction is parsed and inserted into its
1789 /// basic block, this installs its name.
1790 bool LLParser::PerFunctionState::SetInstName(int NameID,
1791 const std::string &NameStr,
1792 LocTy NameLoc, Instruction *Inst) {
1793 // If this instruction has void type, it cannot have a name or ID specified.
1794 if (Inst->getType()->isVoidTy()) {
1795 if (NameID != -1 || !NameStr.empty())
1796 return P.Error(NameLoc, "instructions returning void cannot have a name");
1800 // If this was a numbered instruction, verify that the instruction is the
1801 // expected value and resolve any forward references.
1802 if (NameStr.empty()) {
1803 // If neither a name nor an ID was specified, just use the next ID.
1805 NameID = NumberedVals.size();
1807 if (unsigned(NameID) != NumberedVals.size())
1808 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1809 Twine(NumberedVals.size()) + "'");
1811 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1812 ForwardRefValIDs.find(NameID);
1813 if (FI != ForwardRefValIDs.end()) {
1814 if (FI->second.first->getType() != Inst->getType())
1815 return P.Error(NameLoc, "instruction forward referenced with type '" +
1816 getTypeString(FI->second.first->getType()) + "'");
1817 FI->second.first->replaceAllUsesWith(Inst);
1818 delete FI->second.first;
1819 ForwardRefValIDs.erase(FI);
1822 NumberedVals.push_back(Inst);
1826 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1827 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1828 FI = ForwardRefVals.find(NameStr);
1829 if (FI != ForwardRefVals.end()) {
1830 if (FI->second.first->getType() != Inst->getType())
1831 return P.Error(NameLoc, "instruction forward referenced with type '" +
1832 getTypeString(FI->second.first->getType()) + "'");
1833 FI->second.first->replaceAllUsesWith(Inst);
1834 delete FI->second.first;
1835 ForwardRefVals.erase(FI);
1838 // Set the name on the instruction.
1839 Inst->setName(NameStr);
1841 if (Inst->getName() != NameStr)
1842 return P.Error(NameLoc, "multiple definition of local value named '" +
1847 /// GetBB - Get a basic block with the specified name or ID, creating a
1848 /// forward reference record if needed.
1849 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1851 return cast_or_null<BasicBlock>(GetVal(Name,
1852 Type::getLabelTy(F.getContext()), Loc));
1855 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1856 return cast_or_null<BasicBlock>(GetVal(ID,
1857 Type::getLabelTy(F.getContext()), Loc));
1860 /// DefineBB - Define the specified basic block, which is either named or
1861 /// unnamed. If there is an error, this returns null otherwise it returns
1862 /// the block being defined.
1863 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1867 BB = GetBB(NumberedVals.size(), Loc);
1869 BB = GetBB(Name, Loc);
1870 if (BB == 0) return 0; // Already diagnosed error.
1872 // Move the block to the end of the function. Forward ref'd blocks are
1873 // inserted wherever they happen to be referenced.
1874 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1876 // Remove the block from forward ref sets.
1878 ForwardRefValIDs.erase(NumberedVals.size());
1879 NumberedVals.push_back(BB);
1881 // BB forward references are already in the function symbol table.
1882 ForwardRefVals.erase(Name);
1888 //===----------------------------------------------------------------------===//
1890 //===----------------------------------------------------------------------===//
1892 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1893 /// type implied. For example, if we parse "4" we don't know what integer type
1894 /// it has. The value will later be combined with its type and checked for
1895 /// sanity. PFS is used to convert function-local operands of metadata (since
1896 /// metadata operands are not just parsed here but also converted to values).
1897 /// PFS can be null when we are not parsing metadata values inside a function.
1898 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1899 ID.Loc = Lex.getLoc();
1900 switch (Lex.getKind()) {
1901 default: return TokError("expected value token");
1902 case lltok::GlobalID: // @42
1903 ID.UIntVal = Lex.getUIntVal();
1904 ID.Kind = ValID::t_GlobalID;
1906 case lltok::GlobalVar: // @foo
1907 ID.StrVal = Lex.getStrVal();
1908 ID.Kind = ValID::t_GlobalName;
1910 case lltok::LocalVarID: // %42
1911 ID.UIntVal = Lex.getUIntVal();
1912 ID.Kind = ValID::t_LocalID;
1914 case lltok::LocalVar: // %foo
1915 ID.StrVal = Lex.getStrVal();
1916 ID.Kind = ValID::t_LocalName;
1918 case lltok::exclaim: // !42, !{...}, or !"foo"
1919 return ParseMetadataValue(ID, PFS);
1921 ID.APSIntVal = Lex.getAPSIntVal();
1922 ID.Kind = ValID::t_APSInt;
1924 case lltok::APFloat:
1925 ID.APFloatVal = Lex.getAPFloatVal();
1926 ID.Kind = ValID::t_APFloat;
1928 case lltok::kw_true:
1929 ID.ConstantVal = ConstantInt::getTrue(Context);
1930 ID.Kind = ValID::t_Constant;
1932 case lltok::kw_false:
1933 ID.ConstantVal = ConstantInt::getFalse(Context);
1934 ID.Kind = ValID::t_Constant;
1936 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1937 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1938 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1940 case lltok::lbrace: {
1941 // ValID ::= '{' ConstVector '}'
1943 SmallVector<Constant*, 16> Elts;
1944 if (ParseGlobalValueVector(Elts) ||
1945 ParseToken(lltok::rbrace, "expected end of struct constant"))
1948 ID.ConstantStructElts = new Constant*[Elts.size()];
1949 ID.UIntVal = Elts.size();
1950 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1951 ID.Kind = ValID::t_ConstantStruct;
1955 // ValID ::= '<' ConstVector '>' --> Vector.
1956 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1958 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1960 SmallVector<Constant*, 16> Elts;
1961 LocTy FirstEltLoc = Lex.getLoc();
1962 if (ParseGlobalValueVector(Elts) ||
1964 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1965 ParseToken(lltok::greater, "expected end of constant"))
1968 if (isPackedStruct) {
1969 ID.ConstantStructElts = new Constant*[Elts.size()];
1970 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1971 ID.UIntVal = Elts.size();
1972 ID.Kind = ValID::t_PackedConstantStruct;
1977 return Error(ID.Loc, "constant vector must not be empty");
1979 if (!Elts[0]->getType()->isIntegerTy() &&
1980 !Elts[0]->getType()->isFloatingPointTy())
1981 return Error(FirstEltLoc,
1982 "vector elements must have integer or floating point type");
1984 // Verify that all the vector elements have the same type.
1985 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1986 if (Elts[i]->getType() != Elts[0]->getType())
1987 return Error(FirstEltLoc,
1988 "vector element #" + Twine(i) +
1989 " is not of type '" + getTypeString(Elts[0]->getType()));
1991 ID.ConstantVal = ConstantVector::get(Elts);
1992 ID.Kind = ValID::t_Constant;
1995 case lltok::lsquare: { // Array Constant
1997 SmallVector<Constant*, 16> Elts;
1998 LocTy FirstEltLoc = Lex.getLoc();
1999 if (ParseGlobalValueVector(Elts) ||
2000 ParseToken(lltok::rsquare, "expected end of array constant"))
2003 // Handle empty element.
2005 // Use undef instead of an array because it's inconvenient to determine
2006 // the element type at this point, there being no elements to examine.
2007 ID.Kind = ValID::t_EmptyArray;
2011 if (!Elts[0]->getType()->isFirstClassType())
2012 return Error(FirstEltLoc, "invalid array element type: " +
2013 getTypeString(Elts[0]->getType()));
2015 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2017 // Verify all elements are correct type!
2018 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2019 if (Elts[i]->getType() != Elts[0]->getType())
2020 return Error(FirstEltLoc,
2021 "array element #" + Twine(i) +
2022 " is not of type '" + getTypeString(Elts[0]->getType()));
2025 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2026 ID.Kind = ValID::t_Constant;
2029 case lltok::kw_c: // c "foo"
2031 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2032 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2033 ID.Kind = ValID::t_Constant;
2036 case lltok::kw_asm: {
2037 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2038 bool HasSideEffect, AlignStack;
2040 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2041 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2042 ParseStringConstant(ID.StrVal) ||
2043 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2044 ParseToken(lltok::StringConstant, "expected constraint string"))
2046 ID.StrVal2 = Lex.getStrVal();
2047 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2048 ID.Kind = ValID::t_InlineAsm;
2052 case lltok::kw_blockaddress: {
2053 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2057 LocTy FnLoc, LabelLoc;
2059 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2061 ParseToken(lltok::comma, "expected comma in block address expression")||
2062 ParseValID(Label) ||
2063 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2066 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2067 return Error(Fn.Loc, "expected function name in blockaddress");
2068 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2069 return Error(Label.Loc, "expected basic block name in blockaddress");
2071 // Make a global variable as a placeholder for this reference.
2072 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2073 false, GlobalValue::InternalLinkage,
2075 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2076 ID.ConstantVal = FwdRef;
2077 ID.Kind = ValID::t_Constant;
2081 case lltok::kw_trunc:
2082 case lltok::kw_zext:
2083 case lltok::kw_sext:
2084 case lltok::kw_fptrunc:
2085 case lltok::kw_fpext:
2086 case lltok::kw_bitcast:
2087 case lltok::kw_uitofp:
2088 case lltok::kw_sitofp:
2089 case lltok::kw_fptoui:
2090 case lltok::kw_fptosi:
2091 case lltok::kw_inttoptr:
2092 case lltok::kw_ptrtoint: {
2093 unsigned Opc = Lex.getUIntVal();
2097 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2098 ParseGlobalTypeAndValue(SrcVal) ||
2099 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2100 ParseType(DestTy) ||
2101 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2103 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2104 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2105 getTypeString(SrcVal->getType()) + "' to '" +
2106 getTypeString(DestTy) + "'");
2107 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2109 ID.Kind = ValID::t_Constant;
2112 case lltok::kw_extractvalue: {
2115 SmallVector<unsigned, 4> Indices;
2116 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2117 ParseGlobalTypeAndValue(Val) ||
2118 ParseIndexList(Indices) ||
2119 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2122 if (!Val->getType()->isAggregateType())
2123 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2124 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2125 return Error(ID.Loc, "invalid indices for extractvalue");
2126 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2127 ID.Kind = ValID::t_Constant;
2130 case lltok::kw_insertvalue: {
2132 Constant *Val0, *Val1;
2133 SmallVector<unsigned, 4> Indices;
2134 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2135 ParseGlobalTypeAndValue(Val0) ||
2136 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2137 ParseGlobalTypeAndValue(Val1) ||
2138 ParseIndexList(Indices) ||
2139 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2141 if (!Val0->getType()->isAggregateType())
2142 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2143 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2144 return Error(ID.Loc, "invalid indices for insertvalue");
2145 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2146 ID.Kind = ValID::t_Constant;
2149 case lltok::kw_icmp:
2150 case lltok::kw_fcmp: {
2151 unsigned PredVal, Opc = Lex.getUIntVal();
2152 Constant *Val0, *Val1;
2154 if (ParseCmpPredicate(PredVal, Opc) ||
2155 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2156 ParseGlobalTypeAndValue(Val0) ||
2157 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2158 ParseGlobalTypeAndValue(Val1) ||
2159 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2162 if (Val0->getType() != Val1->getType())
2163 return Error(ID.Loc, "compare operands must have the same type");
2165 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2167 if (Opc == Instruction::FCmp) {
2168 if (!Val0->getType()->isFPOrFPVectorTy())
2169 return Error(ID.Loc, "fcmp requires floating point operands");
2170 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2172 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2173 if (!Val0->getType()->isIntOrIntVectorTy() &&
2174 !Val0->getType()->isPointerTy())
2175 return Error(ID.Loc, "icmp requires pointer or integer operands");
2176 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2178 ID.Kind = ValID::t_Constant;
2182 // Binary Operators.
2184 case lltok::kw_fadd:
2186 case lltok::kw_fsub:
2188 case lltok::kw_fmul:
2189 case lltok::kw_udiv:
2190 case lltok::kw_sdiv:
2191 case lltok::kw_fdiv:
2192 case lltok::kw_urem:
2193 case lltok::kw_srem:
2194 case lltok::kw_frem:
2196 case lltok::kw_lshr:
2197 case lltok::kw_ashr: {
2201 unsigned Opc = Lex.getUIntVal();
2202 Constant *Val0, *Val1;
2204 LocTy ModifierLoc = Lex.getLoc();
2205 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2206 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2207 if (EatIfPresent(lltok::kw_nuw))
2209 if (EatIfPresent(lltok::kw_nsw)) {
2211 if (EatIfPresent(lltok::kw_nuw))
2214 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2215 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2216 if (EatIfPresent(lltok::kw_exact))
2219 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2220 ParseGlobalTypeAndValue(Val0) ||
2221 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2222 ParseGlobalTypeAndValue(Val1) ||
2223 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2225 if (Val0->getType() != Val1->getType())
2226 return Error(ID.Loc, "operands of constexpr must have same type");
2227 if (!Val0->getType()->isIntOrIntVectorTy()) {
2229 return Error(ModifierLoc, "nuw only applies to integer operations");
2231 return Error(ModifierLoc, "nsw only applies to integer operations");
2233 // Check that the type is valid for the operator.
2235 case Instruction::Add:
2236 case Instruction::Sub:
2237 case Instruction::Mul:
2238 case Instruction::UDiv:
2239 case Instruction::SDiv:
2240 case Instruction::URem:
2241 case Instruction::SRem:
2242 case Instruction::Shl:
2243 case Instruction::AShr:
2244 case Instruction::LShr:
2245 if (!Val0->getType()->isIntOrIntVectorTy())
2246 return Error(ID.Loc, "constexpr requires integer operands");
2248 case Instruction::FAdd:
2249 case Instruction::FSub:
2250 case Instruction::FMul:
2251 case Instruction::FDiv:
2252 case Instruction::FRem:
2253 if (!Val0->getType()->isFPOrFPVectorTy())
2254 return Error(ID.Loc, "constexpr requires fp operands");
2256 default: llvm_unreachable("Unknown binary operator!");
2259 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2260 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2261 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2262 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2264 ID.Kind = ValID::t_Constant;
2268 // Logical Operations
2271 case lltok::kw_xor: {
2272 unsigned Opc = Lex.getUIntVal();
2273 Constant *Val0, *Val1;
2275 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2276 ParseGlobalTypeAndValue(Val0) ||
2277 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2278 ParseGlobalTypeAndValue(Val1) ||
2279 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2281 if (Val0->getType() != Val1->getType())
2282 return Error(ID.Loc, "operands of constexpr must have same type");
2283 if (!Val0->getType()->isIntOrIntVectorTy())
2284 return Error(ID.Loc,
2285 "constexpr requires integer or integer vector operands");
2286 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2287 ID.Kind = ValID::t_Constant;
2291 case lltok::kw_getelementptr:
2292 case lltok::kw_shufflevector:
2293 case lltok::kw_insertelement:
2294 case lltok::kw_extractelement:
2295 case lltok::kw_select: {
2296 unsigned Opc = Lex.getUIntVal();
2297 SmallVector<Constant*, 16> Elts;
2298 bool InBounds = false;
2300 if (Opc == Instruction::GetElementPtr)
2301 InBounds = EatIfPresent(lltok::kw_inbounds);
2302 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2303 ParseGlobalValueVector(Elts) ||
2304 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2307 if (Opc == Instruction::GetElementPtr) {
2308 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2309 return Error(ID.Loc, "getelementptr requires pointer operand");
2311 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2312 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2313 return Error(ID.Loc, "invalid indices for getelementptr");
2314 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2316 } else if (Opc == Instruction::Select) {
2317 if (Elts.size() != 3)
2318 return Error(ID.Loc, "expected three operands to select");
2319 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2321 return Error(ID.Loc, Reason);
2322 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2323 } else if (Opc == Instruction::ShuffleVector) {
2324 if (Elts.size() != 3)
2325 return Error(ID.Loc, "expected three operands to shufflevector");
2326 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2327 return Error(ID.Loc, "invalid operands to shufflevector");
2329 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2330 } else if (Opc == Instruction::ExtractElement) {
2331 if (Elts.size() != 2)
2332 return Error(ID.Loc, "expected two operands to extractelement");
2333 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2334 return Error(ID.Loc, "invalid extractelement operands");
2335 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2337 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2338 if (Elts.size() != 3)
2339 return Error(ID.Loc, "expected three operands to insertelement");
2340 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2341 return Error(ID.Loc, "invalid insertelement operands");
2343 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2346 ID.Kind = ValID::t_Constant;
2355 /// ParseGlobalValue - Parse a global value with the specified type.
2356 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2360 bool Parsed = ParseValID(ID) ||
2361 ConvertValIDToValue(Ty, ID, V, NULL);
2362 if (V && !(C = dyn_cast<Constant>(V)))
2363 return Error(ID.Loc, "global values must be constants");
2367 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2369 return ParseType(Ty) ||
2370 ParseGlobalValue(Ty, V);
2373 /// ParseGlobalValueVector
2375 /// ::= TypeAndValue (',' TypeAndValue)*
2376 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2378 if (Lex.getKind() == lltok::rbrace ||
2379 Lex.getKind() == lltok::rsquare ||
2380 Lex.getKind() == lltok::greater ||
2381 Lex.getKind() == lltok::rparen)
2385 if (ParseGlobalTypeAndValue(C)) return true;
2388 while (EatIfPresent(lltok::comma)) {
2389 if (ParseGlobalTypeAndValue(C)) return true;
2396 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2397 assert(Lex.getKind() == lltok::lbrace);
2400 SmallVector<Value*, 16> Elts;
2401 if (ParseMDNodeVector(Elts, PFS) ||
2402 ParseToken(lltok::rbrace, "expected end of metadata node"))
2405 ID.MDNodeVal = MDNode::get(Context, Elts);
2406 ID.Kind = ValID::t_MDNode;
2410 /// ParseMetadataValue
2414 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2415 assert(Lex.getKind() == lltok::exclaim);
2420 if (Lex.getKind() == lltok::lbrace)
2421 return ParseMetadataListValue(ID, PFS);
2423 // Standalone metadata reference
2425 if (Lex.getKind() == lltok::APSInt) {
2426 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2427 ID.Kind = ValID::t_MDNode;
2432 // ::= '!' STRINGCONSTANT
2433 if (ParseMDString(ID.MDStringVal)) return true;
2434 ID.Kind = ValID::t_MDString;
2439 //===----------------------------------------------------------------------===//
2440 // Function Parsing.
2441 //===----------------------------------------------------------------------===//
2443 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2444 PerFunctionState *PFS) {
2445 if (Ty->isFunctionTy())
2446 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2449 default: llvm_unreachable("Unknown ValID!");
2450 case ValID::t_LocalID:
2451 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2452 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2454 case ValID::t_LocalName:
2455 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2456 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2458 case ValID::t_InlineAsm: {
2459 PointerType *PTy = dyn_cast<PointerType>(Ty);
2461 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2462 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2463 return Error(ID.Loc, "invalid type for inline asm constraint string");
2464 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2467 case ValID::t_MDNode:
2468 if (!Ty->isMetadataTy())
2469 return Error(ID.Loc, "metadata value must have metadata type");
2472 case ValID::t_MDString:
2473 if (!Ty->isMetadataTy())
2474 return Error(ID.Loc, "metadata value must have metadata type");
2477 case ValID::t_GlobalName:
2478 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2480 case ValID::t_GlobalID:
2481 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2483 case ValID::t_APSInt:
2484 if (!Ty->isIntegerTy())
2485 return Error(ID.Loc, "integer constant must have integer type");
2486 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2487 V = ConstantInt::get(Context, ID.APSIntVal);
2489 case ValID::t_APFloat:
2490 if (!Ty->isFloatingPointTy() ||
2491 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2492 return Error(ID.Loc, "floating point constant invalid for type");
2494 // The lexer has no type info, so builds all float and double FP constants
2495 // as double. Fix this here. Long double does not need this.
2496 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2499 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2502 V = ConstantFP::get(Context, ID.APFloatVal);
2504 if (V->getType() != Ty)
2505 return Error(ID.Loc, "floating point constant does not have type '" +
2506 getTypeString(Ty) + "'");
2510 if (!Ty->isPointerTy())
2511 return Error(ID.Loc, "null must be a pointer type");
2512 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2514 case ValID::t_Undef:
2515 // FIXME: LabelTy should not be a first-class type.
2516 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2517 return Error(ID.Loc, "invalid type for undef constant");
2518 V = UndefValue::get(Ty);
2520 case ValID::t_EmptyArray:
2521 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2522 return Error(ID.Loc, "invalid empty array initializer");
2523 V = UndefValue::get(Ty);
2526 // FIXME: LabelTy should not be a first-class type.
2527 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2528 return Error(ID.Loc, "invalid type for null constant");
2529 V = Constant::getNullValue(Ty);
2531 case ValID::t_Constant:
2532 if (ID.ConstantVal->getType() != Ty)
2533 return Error(ID.Loc, "constant expression type mismatch");
2537 case ValID::t_ConstantStruct:
2538 case ValID::t_PackedConstantStruct:
2539 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2540 if (ST->getNumElements() != ID.UIntVal)
2541 return Error(ID.Loc,
2542 "initializer with struct type has wrong # elements");
2543 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2544 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2546 // Verify that the elements are compatible with the structtype.
2547 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2548 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2549 return Error(ID.Loc, "element " + Twine(i) +
2550 " of struct initializer doesn't match struct element type");
2552 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2555 return Error(ID.Loc, "constant expression type mismatch");
2560 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2563 return ParseValID(ID, PFS) ||
2564 ConvertValIDToValue(Ty, ID, V, PFS);
2567 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2569 return ParseType(Ty) ||
2570 ParseValue(Ty, V, PFS);
2573 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2574 PerFunctionState &PFS) {
2577 if (ParseTypeAndValue(V, PFS)) return true;
2578 if (!isa<BasicBlock>(V))
2579 return Error(Loc, "expected a basic block");
2580 BB = cast<BasicBlock>(V);
2586 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2587 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2588 /// OptionalAlign OptGC
2589 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2590 // Parse the linkage.
2591 LocTy LinkageLoc = Lex.getLoc();
2594 unsigned Visibility, RetAttrs;
2597 LocTy RetTypeLoc = Lex.getLoc();
2598 if (ParseOptionalLinkage(Linkage) ||
2599 ParseOptionalVisibility(Visibility) ||
2600 ParseOptionalCallingConv(CC) ||
2601 ParseOptionalAttrs(RetAttrs, 1) ||
2602 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2605 // Verify that the linkage is ok.
2606 switch ((GlobalValue::LinkageTypes)Linkage) {
2607 case GlobalValue::ExternalLinkage:
2608 break; // always ok.
2609 case GlobalValue::DLLImportLinkage:
2610 case GlobalValue::ExternalWeakLinkage:
2612 return Error(LinkageLoc, "invalid linkage for function definition");
2614 case GlobalValue::PrivateLinkage:
2615 case GlobalValue::LinkerPrivateLinkage:
2616 case GlobalValue::LinkerPrivateWeakLinkage:
2617 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2618 case GlobalValue::InternalLinkage:
2619 case GlobalValue::AvailableExternallyLinkage:
2620 case GlobalValue::LinkOnceAnyLinkage:
2621 case GlobalValue::LinkOnceODRLinkage:
2622 case GlobalValue::WeakAnyLinkage:
2623 case GlobalValue::WeakODRLinkage:
2624 case GlobalValue::DLLExportLinkage:
2626 return Error(LinkageLoc, "invalid linkage for function declaration");
2628 case GlobalValue::AppendingLinkage:
2629 case GlobalValue::CommonLinkage:
2630 return Error(LinkageLoc, "invalid function linkage type");
2633 if (!FunctionType::isValidReturnType(RetType))
2634 return Error(RetTypeLoc, "invalid function return type");
2636 LocTy NameLoc = Lex.getLoc();
2638 std::string FunctionName;
2639 if (Lex.getKind() == lltok::GlobalVar) {
2640 FunctionName = Lex.getStrVal();
2641 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2642 unsigned NameID = Lex.getUIntVal();
2644 if (NameID != NumberedVals.size())
2645 return TokError("function expected to be numbered '%" +
2646 Twine(NumberedVals.size()) + "'");
2648 return TokError("expected function name");
2653 if (Lex.getKind() != lltok::lparen)
2654 return TokError("expected '(' in function argument list");
2656 SmallVector<ArgInfo, 8> ArgList;
2659 std::string Section;
2663 LocTy UnnamedAddrLoc;
2665 if (ParseArgumentList(ArgList, isVarArg) ||
2666 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2668 ParseOptionalAttrs(FuncAttrs, 2) ||
2669 (EatIfPresent(lltok::kw_section) &&
2670 ParseStringConstant(Section)) ||
2671 ParseOptionalAlignment(Alignment) ||
2672 (EatIfPresent(lltok::kw_gc) &&
2673 ParseStringConstant(GC)))
2676 // If the alignment was parsed as an attribute, move to the alignment field.
2677 if (FuncAttrs & Attribute::Alignment) {
2678 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2679 FuncAttrs &= ~Attribute::Alignment;
2682 // Okay, if we got here, the function is syntactically valid. Convert types
2683 // and do semantic checks.
2684 std::vector<Type*> ParamTypeList;
2685 SmallVector<AttributeWithIndex, 8> Attrs;
2687 if (RetAttrs != Attribute::None)
2688 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2690 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2691 ParamTypeList.push_back(ArgList[i].Ty);
2692 if (ArgList[i].Attrs != Attribute::None)
2693 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2696 if (FuncAttrs != Attribute::None)
2697 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2699 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2701 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2702 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2705 FunctionType::get(RetType, ParamTypeList, isVarArg);
2706 PointerType *PFT = PointerType::getUnqual(FT);
2709 if (!FunctionName.empty()) {
2710 // If this was a definition of a forward reference, remove the definition
2711 // from the forward reference table and fill in the forward ref.
2712 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2713 ForwardRefVals.find(FunctionName);
2714 if (FRVI != ForwardRefVals.end()) {
2715 Fn = M->getFunction(FunctionName);
2716 if (Fn->getType() != PFT)
2717 return Error(FRVI->second.second, "invalid forward reference to "
2718 "function '" + FunctionName + "' with wrong type!");
2720 ForwardRefVals.erase(FRVI);
2721 } else if ((Fn = M->getFunction(FunctionName))) {
2722 // Reject redefinitions.
2723 return Error(NameLoc, "invalid redefinition of function '" +
2724 FunctionName + "'");
2725 } else if (M->getNamedValue(FunctionName)) {
2726 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2730 // If this is a definition of a forward referenced function, make sure the
2732 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2733 = ForwardRefValIDs.find(NumberedVals.size());
2734 if (I != ForwardRefValIDs.end()) {
2735 Fn = cast<Function>(I->second.first);
2736 if (Fn->getType() != PFT)
2737 return Error(NameLoc, "type of definition and forward reference of '@" +
2738 Twine(NumberedVals.size()) + "' disagree");
2739 ForwardRefValIDs.erase(I);
2744 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2745 else // Move the forward-reference to the correct spot in the module.
2746 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2748 if (FunctionName.empty())
2749 NumberedVals.push_back(Fn);
2751 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2752 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2753 Fn->setCallingConv(CC);
2754 Fn->setAttributes(PAL);
2755 Fn->setUnnamedAddr(UnnamedAddr);
2756 Fn->setAlignment(Alignment);
2757 Fn->setSection(Section);
2758 if (!GC.empty()) Fn->setGC(GC.c_str());
2760 // Add all of the arguments we parsed to the function.
2761 Function::arg_iterator ArgIt = Fn->arg_begin();
2762 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2763 // If the argument has a name, insert it into the argument symbol table.
2764 if (ArgList[i].Name.empty()) continue;
2766 // Set the name, if it conflicted, it will be auto-renamed.
2767 ArgIt->setName(ArgList[i].Name);
2769 if (ArgIt->getName() != ArgList[i].Name)
2770 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2771 ArgList[i].Name + "'");
2778 /// ParseFunctionBody
2779 /// ::= '{' BasicBlock+ '}'
2781 bool LLParser::ParseFunctionBody(Function &Fn) {
2782 if (Lex.getKind() != lltok::lbrace)
2783 return TokError("expected '{' in function body");
2784 Lex.Lex(); // eat the {.
2786 int FunctionNumber = -1;
2787 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2789 PerFunctionState PFS(*this, Fn, FunctionNumber);
2791 // We need at least one basic block.
2792 if (Lex.getKind() == lltok::rbrace)
2793 return TokError("function body requires at least one basic block");
2795 while (Lex.getKind() != lltok::rbrace)
2796 if (ParseBasicBlock(PFS)) return true;
2801 // Verify function is ok.
2802 return PFS.FinishFunction();
2806 /// ::= LabelStr? Instruction*
2807 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2808 // If this basic block starts out with a name, remember it.
2810 LocTy NameLoc = Lex.getLoc();
2811 if (Lex.getKind() == lltok::LabelStr) {
2812 Name = Lex.getStrVal();
2816 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2817 if (BB == 0) return true;
2819 std::string NameStr;
2821 // Parse the instructions in this block until we get a terminator.
2823 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2825 // This instruction may have three possibilities for a name: a) none
2826 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2827 LocTy NameLoc = Lex.getLoc();
2831 if (Lex.getKind() == lltok::LocalVarID) {
2832 NameID = Lex.getUIntVal();
2834 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2836 } else if (Lex.getKind() == lltok::LocalVar) {
2837 NameStr = Lex.getStrVal();
2839 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2843 switch (ParseInstruction(Inst, BB, PFS)) {
2844 default: assert(0 && "Unknown ParseInstruction result!");
2845 case InstError: return true;
2847 BB->getInstList().push_back(Inst);
2849 // With a normal result, we check to see if the instruction is followed by
2850 // a comma and metadata.
2851 if (EatIfPresent(lltok::comma))
2852 if (ParseInstructionMetadata(Inst, &PFS))
2855 case InstExtraComma:
2856 BB->getInstList().push_back(Inst);
2858 // If the instruction parser ate an extra comma at the end of it, it
2859 // *must* be followed by metadata.
2860 if (ParseInstructionMetadata(Inst, &PFS))
2865 // Set the name on the instruction.
2866 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2867 } while (!isa<TerminatorInst>(Inst));
2872 //===----------------------------------------------------------------------===//
2873 // Instruction Parsing.
2874 //===----------------------------------------------------------------------===//
2876 /// ParseInstruction - Parse one of the many different instructions.
2878 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2879 PerFunctionState &PFS) {
2880 lltok::Kind Token = Lex.getKind();
2881 if (Token == lltok::Eof)
2882 return TokError("found end of file when expecting more instructions");
2883 LocTy Loc = Lex.getLoc();
2884 unsigned KeywordVal = Lex.getUIntVal();
2885 Lex.Lex(); // Eat the keyword.
2888 default: return Error(Loc, "expected instruction opcode");
2889 // Terminator Instructions.
2890 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2891 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2892 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2893 case lltok::kw_br: return ParseBr(Inst, PFS);
2894 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2895 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2896 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2897 case lltok::kw_resume: return ParseResume(Inst, PFS);
2898 // Binary Operators.
2902 case lltok::kw_shl: {
2903 bool NUW = EatIfPresent(lltok::kw_nuw);
2904 bool NSW = EatIfPresent(lltok::kw_nsw);
2905 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2907 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2909 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2910 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2913 case lltok::kw_fadd:
2914 case lltok::kw_fsub:
2915 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2917 case lltok::kw_sdiv:
2918 case lltok::kw_udiv:
2919 case lltok::kw_lshr:
2920 case lltok::kw_ashr: {
2921 bool Exact = EatIfPresent(lltok::kw_exact);
2923 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2924 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2928 case lltok::kw_urem:
2929 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2930 case lltok::kw_fdiv:
2931 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2934 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2935 case lltok::kw_icmp:
2936 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2938 case lltok::kw_trunc:
2939 case lltok::kw_zext:
2940 case lltok::kw_sext:
2941 case lltok::kw_fptrunc:
2942 case lltok::kw_fpext:
2943 case lltok::kw_bitcast:
2944 case lltok::kw_uitofp:
2945 case lltok::kw_sitofp:
2946 case lltok::kw_fptoui:
2947 case lltok::kw_fptosi:
2948 case lltok::kw_inttoptr:
2949 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2951 case lltok::kw_select: return ParseSelect(Inst, PFS);
2952 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2953 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2954 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2955 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2956 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2957 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
2958 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2959 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2961 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2962 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2963 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2964 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
2965 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
2966 case lltok::kw_fence: return ParseFence(Inst, PFS);
2967 case lltok::kw_volatile:
2968 // For compatibility; canonical location is after load
2969 if (EatIfPresent(lltok::kw_load))
2970 return ParseLoad(Inst, PFS, true);
2971 else if (EatIfPresent(lltok::kw_store))
2972 return ParseStore(Inst, PFS, true);
2974 return TokError("expected 'load' or 'store'");
2975 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2976 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2977 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2981 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2982 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2983 if (Opc == Instruction::FCmp) {
2984 switch (Lex.getKind()) {
2985 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2986 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2987 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2988 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2989 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2990 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2991 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2992 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2993 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2994 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2995 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2996 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2997 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2998 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2999 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3000 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3001 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3004 switch (Lex.getKind()) {
3005 default: TokError("expected icmp predicate (e.g. 'eq')");
3006 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3007 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3008 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3009 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3010 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3011 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3012 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3013 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3014 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3015 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3022 //===----------------------------------------------------------------------===//
3023 // Terminator Instructions.
3024 //===----------------------------------------------------------------------===//
3026 /// ParseRet - Parse a return instruction.
3027 /// ::= 'ret' void (',' !dbg, !1)*
3028 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3029 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3030 PerFunctionState &PFS) {
3031 SMLoc TypeLoc = Lex.getLoc();
3033 if (ParseType(Ty, true /*void allowed*/)) return true;
3035 Type *ResType = PFS.getFunction().getReturnType();
3037 if (Ty->isVoidTy()) {
3038 if (!ResType->isVoidTy())
3039 return Error(TypeLoc, "value doesn't match function result type '" +
3040 getTypeString(ResType) + "'");
3042 Inst = ReturnInst::Create(Context);
3047 if (ParseValue(Ty, RV, PFS)) return true;
3049 if (ResType != RV->getType())
3050 return Error(TypeLoc, "value doesn't match function result type '" +
3051 getTypeString(ResType) + "'");
3053 Inst = ReturnInst::Create(Context, RV);
3059 /// ::= 'br' TypeAndValue
3060 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3061 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3064 BasicBlock *Op1, *Op2;
3065 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3067 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3068 Inst = BranchInst::Create(BB);
3072 if (Op0->getType() != Type::getInt1Ty(Context))
3073 return Error(Loc, "branch condition must have 'i1' type");
3075 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3076 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3077 ParseToken(lltok::comma, "expected ',' after true destination") ||
3078 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3081 Inst = BranchInst::Create(Op1, Op2, Op0);
3087 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3089 /// ::= (TypeAndValue ',' TypeAndValue)*
3090 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3091 LocTy CondLoc, BBLoc;
3093 BasicBlock *DefaultBB;
3094 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3095 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3096 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3097 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3100 if (!Cond->getType()->isIntegerTy())
3101 return Error(CondLoc, "switch condition must have integer type");
3103 // Parse the jump table pairs.
3104 SmallPtrSet<Value*, 32> SeenCases;
3105 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3106 while (Lex.getKind() != lltok::rsquare) {
3110 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3111 ParseToken(lltok::comma, "expected ',' after case value") ||
3112 ParseTypeAndBasicBlock(DestBB, PFS))
3115 if (!SeenCases.insert(Constant))
3116 return Error(CondLoc, "duplicate case value in switch");
3117 if (!isa<ConstantInt>(Constant))
3118 return Error(CondLoc, "case value is not a constant integer");
3120 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3123 Lex.Lex(); // Eat the ']'.
3125 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3126 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3127 SI->addCase(Table[i].first, Table[i].second);
3134 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3135 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3138 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3139 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3140 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3143 if (!Address->getType()->isPointerTy())
3144 return Error(AddrLoc, "indirectbr address must have pointer type");
3146 // Parse the destination list.
3147 SmallVector<BasicBlock*, 16> DestList;
3149 if (Lex.getKind() != lltok::rsquare) {
3151 if (ParseTypeAndBasicBlock(DestBB, PFS))
3153 DestList.push_back(DestBB);
3155 while (EatIfPresent(lltok::comma)) {
3156 if (ParseTypeAndBasicBlock(DestBB, PFS))
3158 DestList.push_back(DestBB);
3162 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3165 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3166 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3167 IBI->addDestination(DestList[i]);
3174 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3175 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3176 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3177 LocTy CallLoc = Lex.getLoc();
3178 unsigned RetAttrs, FnAttrs;
3183 SmallVector<ParamInfo, 16> ArgList;
3185 BasicBlock *NormalBB, *UnwindBB;
3186 if (ParseOptionalCallingConv(CC) ||
3187 ParseOptionalAttrs(RetAttrs, 1) ||
3188 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3189 ParseValID(CalleeID) ||
3190 ParseParameterList(ArgList, PFS) ||
3191 ParseOptionalAttrs(FnAttrs, 2) ||
3192 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3193 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3194 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3195 ParseTypeAndBasicBlock(UnwindBB, PFS))
3198 // If RetType is a non-function pointer type, then this is the short syntax
3199 // for the call, which means that RetType is just the return type. Infer the
3200 // rest of the function argument types from the arguments that are present.
3201 PointerType *PFTy = 0;
3202 FunctionType *Ty = 0;
3203 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3204 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3205 // Pull out the types of all of the arguments...
3206 std::vector<Type*> ParamTypes;
3207 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3208 ParamTypes.push_back(ArgList[i].V->getType());
3210 if (!FunctionType::isValidReturnType(RetType))
3211 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3213 Ty = FunctionType::get(RetType, ParamTypes, false);
3214 PFTy = PointerType::getUnqual(Ty);
3217 // Look up the callee.
3219 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3221 // Set up the Attributes for the function.
3222 SmallVector<AttributeWithIndex, 8> Attrs;
3223 if (RetAttrs != Attribute::None)
3224 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3226 SmallVector<Value*, 8> Args;
3228 // Loop through FunctionType's arguments and ensure they are specified
3229 // correctly. Also, gather any parameter attributes.
3230 FunctionType::param_iterator I = Ty->param_begin();
3231 FunctionType::param_iterator E = Ty->param_end();
3232 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3233 Type *ExpectedTy = 0;
3236 } else if (!Ty->isVarArg()) {
3237 return Error(ArgList[i].Loc, "too many arguments specified");
3240 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3241 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3242 getTypeString(ExpectedTy) + "'");
3243 Args.push_back(ArgList[i].V);
3244 if (ArgList[i].Attrs != Attribute::None)
3245 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3249 return Error(CallLoc, "not enough parameters specified for call");
3251 if (FnAttrs != Attribute::None)
3252 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3254 // Finish off the Attributes and check them
3255 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3257 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3258 II->setCallingConv(CC);
3259 II->setAttributes(PAL);
3265 /// ::= 'resume' TypeAndValue
3266 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3267 Value *Exn; LocTy ExnLoc;
3268 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3271 ResumeInst *RI = ResumeInst::Create(Exn);
3276 //===----------------------------------------------------------------------===//
3277 // Binary Operators.
3278 //===----------------------------------------------------------------------===//
3281 /// ::= ArithmeticOps TypeAndValue ',' Value
3283 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3284 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3285 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3286 unsigned Opc, unsigned OperandType) {
3287 LocTy Loc; Value *LHS, *RHS;
3288 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3289 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3290 ParseValue(LHS->getType(), RHS, PFS))
3294 switch (OperandType) {
3295 default: llvm_unreachable("Unknown operand type!");
3296 case 0: // int or FP.
3297 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3298 LHS->getType()->isFPOrFPVectorTy();
3300 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3301 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3305 return Error(Loc, "invalid operand type for instruction");
3307 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3312 /// ::= ArithmeticOps TypeAndValue ',' Value {
3313 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3315 LocTy Loc; Value *LHS, *RHS;
3316 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3317 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3318 ParseValue(LHS->getType(), RHS, PFS))
3321 if (!LHS->getType()->isIntOrIntVectorTy())
3322 return Error(Loc,"instruction requires integer or integer vector operands");
3324 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3330 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3331 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3332 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3334 // Parse the integer/fp comparison predicate.
3338 if (ParseCmpPredicate(Pred, Opc) ||
3339 ParseTypeAndValue(LHS, Loc, PFS) ||
3340 ParseToken(lltok::comma, "expected ',' after compare value") ||
3341 ParseValue(LHS->getType(), RHS, PFS))
3344 if (Opc == Instruction::FCmp) {
3345 if (!LHS->getType()->isFPOrFPVectorTy())
3346 return Error(Loc, "fcmp requires floating point operands");
3347 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3349 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3350 if (!LHS->getType()->isIntOrIntVectorTy() &&
3351 !LHS->getType()->isPointerTy())
3352 return Error(Loc, "icmp requires integer operands");
3353 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3358 //===----------------------------------------------------------------------===//
3359 // Other Instructions.
3360 //===----------------------------------------------------------------------===//
3364 /// ::= CastOpc TypeAndValue 'to' Type
3365 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3370 if (ParseTypeAndValue(Op, Loc, PFS) ||
3371 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3375 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3376 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3377 return Error(Loc, "invalid cast opcode for cast from '" +
3378 getTypeString(Op->getType()) + "' to '" +
3379 getTypeString(DestTy) + "'");
3381 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3386 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3387 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3389 Value *Op0, *Op1, *Op2;
3390 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3391 ParseToken(lltok::comma, "expected ',' after select condition") ||
3392 ParseTypeAndValue(Op1, PFS) ||
3393 ParseToken(lltok::comma, "expected ',' after select value") ||
3394 ParseTypeAndValue(Op2, PFS))
3397 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3398 return Error(Loc, Reason);
3400 Inst = SelectInst::Create(Op0, Op1, Op2);
3405 /// ::= 'va_arg' TypeAndValue ',' Type
3406 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3410 if (ParseTypeAndValue(Op, PFS) ||
3411 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3412 ParseType(EltTy, TypeLoc))
3415 if (!EltTy->isFirstClassType())
3416 return Error(TypeLoc, "va_arg requires operand with first class type");
3418 Inst = new VAArgInst(Op, EltTy);
3422 /// ParseExtractElement
3423 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3424 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3427 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3428 ParseToken(lltok::comma, "expected ',' after extract value") ||
3429 ParseTypeAndValue(Op1, PFS))
3432 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3433 return Error(Loc, "invalid extractelement operands");
3435 Inst = ExtractElementInst::Create(Op0, Op1);
3439 /// ParseInsertElement
3440 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3441 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3443 Value *Op0, *Op1, *Op2;
3444 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3445 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3446 ParseTypeAndValue(Op1, PFS) ||
3447 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3448 ParseTypeAndValue(Op2, PFS))
3451 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3452 return Error(Loc, "invalid insertelement operands");
3454 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3458 /// ParseShuffleVector
3459 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3460 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3462 Value *Op0, *Op1, *Op2;
3463 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3464 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3465 ParseTypeAndValue(Op1, PFS) ||
3466 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3467 ParseTypeAndValue(Op2, PFS))
3470 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3471 return Error(Loc, "invalid extractelement operands");
3473 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3478 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3479 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3480 Type *Ty = 0; LocTy TypeLoc;
3483 if (ParseType(Ty, TypeLoc) ||
3484 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3485 ParseValue(Ty, Op0, PFS) ||
3486 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3487 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3488 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3491 bool AteExtraComma = false;
3492 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3494 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3496 if (!EatIfPresent(lltok::comma))
3499 if (Lex.getKind() == lltok::MetadataVar) {
3500 AteExtraComma = true;
3504 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3505 ParseValue(Ty, Op0, PFS) ||
3506 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3507 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3508 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3512 if (!Ty->isFirstClassType())
3513 return Error(TypeLoc, "phi node must have first class type");
3515 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3516 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3517 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3519 return AteExtraComma ? InstExtraComma : InstNormal;
3523 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3525 /// ::= 'catch' TypeAndValue
3527 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3528 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3529 Type *Ty = 0; LocTy TyLoc;
3530 Value *PersFn; LocTy PersFnLoc;
3532 if (ParseType(Ty, TyLoc) ||
3533 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3534 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3537 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3538 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3540 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3541 LandingPadInst::ClauseType CT;
3542 if (EatIfPresent(lltok::kw_catch))
3543 CT = LandingPadInst::Catch;
3544 else if (EatIfPresent(lltok::kw_filter))
3545 CT = LandingPadInst::Filter;
3547 return TokError("expected 'catch' or 'filter' clause type");
3549 Value *V; LocTy VLoc;
3550 if (ParseTypeAndValue(V, VLoc, PFS)) {
3555 // A 'catch' type expects a non-array constant. A filter clause expects an
3557 if (CT == LandingPadInst::Catch) {
3558 if (isa<ArrayType>(V->getType()))
3559 Error(VLoc, "'catch' clause has an invalid type");
3561 if (!isa<ArrayType>(V->getType()))
3562 Error(VLoc, "'filter' clause has an invalid type");
3573 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3574 /// ParameterList OptionalAttrs
3575 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3577 unsigned RetAttrs, FnAttrs;
3582 SmallVector<ParamInfo, 16> ArgList;
3583 LocTy CallLoc = Lex.getLoc();
3585 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3586 ParseOptionalCallingConv(CC) ||
3587 ParseOptionalAttrs(RetAttrs, 1) ||
3588 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3589 ParseValID(CalleeID) ||
3590 ParseParameterList(ArgList, PFS) ||
3591 ParseOptionalAttrs(FnAttrs, 2))
3594 // If RetType is a non-function pointer type, then this is the short syntax
3595 // for the call, which means that RetType is just the return type. Infer the
3596 // rest of the function argument types from the arguments that are present.
3597 PointerType *PFTy = 0;
3598 FunctionType *Ty = 0;
3599 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3600 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3601 // Pull out the types of all of the arguments...
3602 std::vector<Type*> ParamTypes;
3603 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3604 ParamTypes.push_back(ArgList[i].V->getType());
3606 if (!FunctionType::isValidReturnType(RetType))
3607 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3609 Ty = FunctionType::get(RetType, ParamTypes, false);
3610 PFTy = PointerType::getUnqual(Ty);
3613 // Look up the callee.
3615 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3617 // Set up the Attributes for the function.
3618 SmallVector<AttributeWithIndex, 8> Attrs;
3619 if (RetAttrs != Attribute::None)
3620 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3622 SmallVector<Value*, 8> Args;
3624 // Loop through FunctionType's arguments and ensure they are specified
3625 // correctly. Also, gather any parameter attributes.
3626 FunctionType::param_iterator I = Ty->param_begin();
3627 FunctionType::param_iterator E = Ty->param_end();
3628 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3629 Type *ExpectedTy = 0;
3632 } else if (!Ty->isVarArg()) {
3633 return Error(ArgList[i].Loc, "too many arguments specified");
3636 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3637 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3638 getTypeString(ExpectedTy) + "'");
3639 Args.push_back(ArgList[i].V);
3640 if (ArgList[i].Attrs != Attribute::None)
3641 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3645 return Error(CallLoc, "not enough parameters specified for call");
3647 if (FnAttrs != Attribute::None)
3648 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3650 // Finish off the Attributes and check them
3651 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3653 CallInst *CI = CallInst::Create(Callee, Args);
3654 CI->setTailCall(isTail);
3655 CI->setCallingConv(CC);
3656 CI->setAttributes(PAL);
3661 //===----------------------------------------------------------------------===//
3662 // Memory Instructions.
3663 //===----------------------------------------------------------------------===//
3666 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3667 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3670 unsigned Alignment = 0;
3672 if (ParseType(Ty)) return true;
3674 bool AteExtraComma = false;
3675 if (EatIfPresent(lltok::comma)) {
3676 if (Lex.getKind() == lltok::kw_align) {
3677 if (ParseOptionalAlignment(Alignment)) return true;
3678 } else if (Lex.getKind() == lltok::MetadataVar) {
3679 AteExtraComma = true;
3681 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3682 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3687 if (Size && !Size->getType()->isIntegerTy())
3688 return Error(SizeLoc, "element count must have integer type");
3690 Inst = new AllocaInst(Ty, Size, Alignment);
3691 return AteExtraComma ? InstExtraComma : InstNormal;
3695 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3696 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3697 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3699 /// ::= 'volatile' 'load' TypeAndValue (',' 'align' i32)?
3700 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3702 Value *Val; LocTy Loc;
3703 unsigned Alignment = 0;
3704 bool AteExtraComma = false;
3705 bool isAtomic = false;
3706 AtomicOrdering Ordering = NotAtomic;
3707 SynchronizationScope Scope = CrossThread;
3709 if (Lex.getKind() == lltok::kw_atomic) {
3711 return TokError("mixing atomic with old volatile placement");
3716 if (Lex.getKind() == lltok::kw_volatile) {
3718 return TokError("duplicate volatile before and after store");
3723 if (ParseTypeAndValue(Val, Loc, PFS) ||
3724 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3725 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3728 if (!Val->getType()->isPointerTy() ||
3729 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3730 return Error(Loc, "load operand must be a pointer to a first class type");
3731 if (isAtomic && !Alignment)
3732 return Error(Loc, "atomic load must have explicit non-zero alignment");
3733 if (Ordering == Release || Ordering == AcquireRelease)
3734 return Error(Loc, "atomic load cannot use Release ordering");
3736 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
3737 return AteExtraComma ? InstExtraComma : InstNormal;
3742 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3743 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
3744 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3746 /// ::= 'volatile' 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3747 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3749 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3750 unsigned Alignment = 0;
3751 bool AteExtraComma = false;
3752 bool isAtomic = false;
3753 AtomicOrdering Ordering = NotAtomic;
3754 SynchronizationScope Scope = CrossThread;
3756 if (Lex.getKind() == lltok::kw_atomic) {
3758 return TokError("mixing atomic with old volatile placement");
3763 if (Lex.getKind() == lltok::kw_volatile) {
3765 return TokError("duplicate volatile before and after store");
3770 if (ParseTypeAndValue(Val, Loc, PFS) ||
3771 ParseToken(lltok::comma, "expected ',' after store operand") ||
3772 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3773 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3774 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3777 if (!Ptr->getType()->isPointerTy())
3778 return Error(PtrLoc, "store operand must be a pointer");
3779 if (!Val->getType()->isFirstClassType())
3780 return Error(Loc, "store operand must be a first class value");
3781 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3782 return Error(Loc, "stored value and pointer type do not match");
3783 if (isAtomic && !Alignment)
3784 return Error(Loc, "atomic store must have explicit non-zero alignment");
3785 if (Ordering == Acquire || Ordering == AcquireRelease)
3786 return Error(Loc, "atomic store cannot use Acquire ordering");
3788 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
3789 return AteExtraComma ? InstExtraComma : InstNormal;
3793 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3794 /// 'singlethread'? AtomicOrdering
3795 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
3796 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3797 bool AteExtraComma = false;
3798 AtomicOrdering Ordering = NotAtomic;
3799 SynchronizationScope Scope = CrossThread;
3800 bool isVolatile = false;
3802 if (EatIfPresent(lltok::kw_volatile))
3805 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3806 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3807 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3808 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3809 ParseTypeAndValue(New, NewLoc, PFS) ||
3810 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3813 if (Ordering == Unordered)
3814 return TokError("cmpxchg cannot be unordered");
3815 if (!Ptr->getType()->isPointerTy())
3816 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3817 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3818 return Error(CmpLoc, "compare value and pointer type do not match");
3819 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3820 return Error(NewLoc, "new value and pointer type do not match");
3821 if (!New->getType()->isIntegerTy())
3822 return Error(NewLoc, "cmpxchg operand must be an integer");
3823 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3824 if (Size < 8 || (Size & (Size - 1)))
3825 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3828 AtomicCmpXchgInst *CXI =
3829 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3830 CXI->setVolatile(isVolatile);
3832 return AteExtraComma ? InstExtraComma : InstNormal;
3836 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3837 /// 'singlethread'? AtomicOrdering
3838 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
3839 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3840 bool AteExtraComma = false;
3841 AtomicOrdering Ordering = NotAtomic;
3842 SynchronizationScope Scope = CrossThread;
3843 bool isVolatile = false;
3844 AtomicRMWInst::BinOp Operation;
3846 if (EatIfPresent(lltok::kw_volatile))
3849 switch (Lex.getKind()) {
3850 default: return TokError("expected binary operation in atomicrmw");
3851 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3852 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3853 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3854 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3855 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3856 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3857 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3858 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3859 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3860 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3861 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3863 Lex.Lex(); // Eat the operation.
3865 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3866 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3867 ParseTypeAndValue(Val, ValLoc, PFS) ||
3868 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3871 if (Ordering == Unordered)
3872 return TokError("atomicrmw cannot be unordered");
3873 if (!Ptr->getType()->isPointerTy())
3874 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3875 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3876 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3877 if (!Val->getType()->isIntegerTy())
3878 return Error(ValLoc, "atomicrmw operand must be an integer");
3879 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3880 if (Size < 8 || (Size & (Size - 1)))
3881 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3884 AtomicRMWInst *RMWI =
3885 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3886 RMWI->setVolatile(isVolatile);
3888 return AteExtraComma ? InstExtraComma : InstNormal;
3892 /// ::= 'fence' 'singlethread'? AtomicOrdering
3893 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3894 AtomicOrdering Ordering = NotAtomic;
3895 SynchronizationScope Scope = CrossThread;
3896 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3899 if (Ordering == Unordered)
3900 return TokError("fence cannot be unordered");
3901 if (Ordering == Monotonic)
3902 return TokError("fence cannot be monotonic");
3904 Inst = new FenceInst(Context, Ordering, Scope);
3908 /// ParseGetElementPtr
3909 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3910 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3911 Value *Ptr, *Val; LocTy Loc, EltLoc;
3913 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3915 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3917 if (!Ptr->getType()->isPointerTy())
3918 return Error(Loc, "base of getelementptr must be a pointer");
3920 SmallVector<Value*, 16> Indices;
3921 bool AteExtraComma = false;
3922 while (EatIfPresent(lltok::comma)) {
3923 if (Lex.getKind() == lltok::MetadataVar) {
3924 AteExtraComma = true;
3927 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3928 if (!Val->getType()->isIntegerTy())
3929 return Error(EltLoc, "getelementptr index must be an integer");
3930 Indices.push_back(Val);
3933 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
3934 return Error(Loc, "invalid getelementptr indices");
3935 Inst = GetElementPtrInst::Create(Ptr, Indices);
3937 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3938 return AteExtraComma ? InstExtraComma : InstNormal;
3941 /// ParseExtractValue
3942 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3943 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3944 Value *Val; LocTy Loc;
3945 SmallVector<unsigned, 4> Indices;
3947 if (ParseTypeAndValue(Val, Loc, PFS) ||
3948 ParseIndexList(Indices, AteExtraComma))
3951 if (!Val->getType()->isAggregateType())
3952 return Error(Loc, "extractvalue operand must be aggregate type");
3954 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3955 return Error(Loc, "invalid indices for extractvalue");
3956 Inst = ExtractValueInst::Create(Val, Indices);
3957 return AteExtraComma ? InstExtraComma : InstNormal;
3960 /// ParseInsertValue
3961 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3962 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3963 Value *Val0, *Val1; LocTy Loc0, Loc1;
3964 SmallVector<unsigned, 4> Indices;
3966 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3967 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3968 ParseTypeAndValue(Val1, Loc1, PFS) ||
3969 ParseIndexList(Indices, AteExtraComma))
3972 if (!Val0->getType()->isAggregateType())
3973 return Error(Loc0, "insertvalue operand must be aggregate type");
3975 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
3976 return Error(Loc0, "invalid indices for insertvalue");
3977 Inst = InsertValueInst::Create(Val0, Val1, Indices);
3978 return AteExtraComma ? InstExtraComma : InstNormal;
3981 //===----------------------------------------------------------------------===//
3982 // Embedded metadata.
3983 //===----------------------------------------------------------------------===//
3985 /// ParseMDNodeVector
3986 /// ::= Element (',' Element)*
3988 /// ::= 'null' | TypeAndValue
3989 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3990 PerFunctionState *PFS) {
3991 // Check for an empty list.
3992 if (Lex.getKind() == lltok::rbrace)
3996 // Null is a special case since it is typeless.
3997 if (EatIfPresent(lltok::kw_null)) {
4003 if (ParseTypeAndValue(V, PFS)) return true;
4005 } while (EatIfPresent(lltok::comma));