1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 static std::string getTypeString(Type *T) {
31 raw_string_ostream Tmp(Result);
36 /// Run: module ::= toplevelentity*
37 bool LLParser::Run() {
41 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
45 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47 bool LLParser::ValidateEndOfModule() {
48 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
62 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
65 ForwardRefInstMetadata.clear();
69 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
92 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
93 if (NumberedTypes[i].second.isValid())
94 return Error(NumberedTypes[i].second,
95 "use of undefined type '%" + Twine(i) + "'");
97 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
99 if (I->second.second.isValid())
100 return Error(I->second.second,
101 "use of undefined type named '" + I->getKey() + "'");
103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
111 Twine(ForwardRefValIDs.begin()->first) + "'");
113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
116 Twine(ForwardRefMDNodes.begin()->first) + "'");
119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
123 // Check debug info intrinsics.
124 CheckDebugInfoIntrinsics(M);
128 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
129 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
130 PerFunctionState *PFS) {
131 // Loop over all the references, resolving them.
132 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
135 if (Refs[i].first.Kind == ValID::t_LocalName)
136 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
138 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
139 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
140 return Error(Refs[i].first.Loc,
141 "cannot take address of numeric label after the function is defined");
143 Res = dyn_cast_or_null<BasicBlock>(
144 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
148 return Error(Refs[i].first.Loc,
149 "referenced value is not a basic block");
151 // Get the BlockAddress for this and update references to use it.
152 BlockAddress *BA = BlockAddress::get(TheFn, Res);
153 Refs[i].second->replaceAllUsesWith(BA);
154 Refs[i].second->eraseFromParent();
160 //===----------------------------------------------------------------------===//
161 // Top-Level Entities
162 //===----------------------------------------------------------------------===//
164 bool LLParser::ParseTopLevelEntities() {
166 switch (Lex.getKind()) {
167 default: return TokError("expected top-level entity");
168 case lltok::Eof: return false;
169 case lltok::kw_declare: if (ParseDeclare()) return true; break;
170 case lltok::kw_define: if (ParseDefine()) return true; break;
171 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
172 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
173 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
174 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
175 case lltok::LocalVar: if (ParseNamedType()) return true; break;
176 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
177 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
178 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
179 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
181 // The Global variable production with no name can have many different
182 // optional leading prefixes, the production is:
183 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
184 // OptionalAddrSpace OptionalUnNammedAddr
185 // ('constant'|'global') ...
186 case lltok::kw_private: // OptionalLinkage
187 case lltok::kw_linker_private: // OptionalLinkage
188 case lltok::kw_linker_private_weak: // OptionalLinkage
189 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
190 case lltok::kw_internal: // OptionalLinkage
191 case lltok::kw_weak: // OptionalLinkage
192 case lltok::kw_weak_odr: // OptionalLinkage
193 case lltok::kw_linkonce: // OptionalLinkage
194 case lltok::kw_linkonce_odr: // OptionalLinkage
195 case lltok::kw_appending: // OptionalLinkage
196 case lltok::kw_dllexport: // OptionalLinkage
197 case lltok::kw_common: // OptionalLinkage
198 case lltok::kw_dllimport: // OptionalLinkage
199 case lltok::kw_extern_weak: // OptionalLinkage
200 case lltok::kw_external: { // OptionalLinkage
201 unsigned Linkage, Visibility;
202 if (ParseOptionalLinkage(Linkage) ||
203 ParseOptionalVisibility(Visibility) ||
204 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
208 case lltok::kw_default: // OptionalVisibility
209 case lltok::kw_hidden: // OptionalVisibility
210 case lltok::kw_protected: { // OptionalVisibility
212 if (ParseOptionalVisibility(Visibility) ||
213 ParseGlobal("", SMLoc(), 0, false, Visibility))
218 case lltok::kw_thread_local: // OptionalThreadLocal
219 case lltok::kw_addrspace: // OptionalAddrSpace
220 case lltok::kw_constant: // GlobalType
221 case lltok::kw_global: // GlobalType
222 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
230 /// ::= 'module' 'asm' STRINGCONSTANT
231 bool LLParser::ParseModuleAsm() {
232 assert(Lex.getKind() == lltok::kw_module);
236 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
237 ParseStringConstant(AsmStr)) return true;
239 M->appendModuleInlineAsm(AsmStr);
244 /// ::= 'target' 'triple' '=' STRINGCONSTANT
245 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
246 bool LLParser::ParseTargetDefinition() {
247 assert(Lex.getKind() == lltok::kw_target);
250 default: return TokError("unknown target property");
251 case lltok::kw_triple:
253 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
254 ParseStringConstant(Str))
256 M->setTargetTriple(Str);
258 case lltok::kw_datalayout:
260 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
261 ParseStringConstant(Str))
263 M->setDataLayout(Str);
269 /// ::= 'deplibs' '=' '[' ']'
270 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
271 bool LLParser::ParseDepLibs() {
272 assert(Lex.getKind() == lltok::kw_deplibs);
274 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
275 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
278 if (EatIfPresent(lltok::rsquare))
282 if (ParseStringConstant(Str)) return true;
285 while (EatIfPresent(lltok::comma)) {
286 if (ParseStringConstant(Str)) return true;
290 return ParseToken(lltok::rsquare, "expected ']' at end of list");
293 /// ParseUnnamedType:
294 /// ::= LocalVarID '=' 'type' type
295 bool LLParser::ParseUnnamedType() {
296 LocTy TypeLoc = Lex.getLoc();
297 unsigned TypeID = Lex.getUIntVal();
298 Lex.Lex(); // eat LocalVarID;
300 if (ParseToken(lltok::equal, "expected '=' after name") ||
301 ParseToken(lltok::kw_type, "expected 'type' after '='"))
304 if (TypeID >= NumberedTypes.size())
305 NumberedTypes.resize(TypeID+1);
308 if (ParseStructDefinition(TypeLoc, "",
309 NumberedTypes[TypeID], Result)) return true;
311 if (!isa<StructType>(Result)) {
312 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
314 return Error(TypeLoc, "non-struct types may not be recursive");
315 Entry.first = Result;
316 Entry.second = SMLoc();
324 /// ::= LocalVar '=' 'type' type
325 bool LLParser::ParseNamedType() {
326 std::string Name = Lex.getStrVal();
327 LocTy NameLoc = Lex.getLoc();
328 Lex.Lex(); // eat LocalVar.
330 if (ParseToken(lltok::equal, "expected '=' after name") ||
331 ParseToken(lltok::kw_type, "expected 'type' after name"))
335 if (ParseStructDefinition(NameLoc, Name,
336 NamedTypes[Name], Result)) return true;
338 if (!isa<StructType>(Result)) {
339 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
341 return Error(NameLoc, "non-struct types may not be recursive");
342 Entry.first = Result;
343 Entry.second = SMLoc();
351 /// ::= 'declare' FunctionHeader
352 bool LLParser::ParseDeclare() {
353 assert(Lex.getKind() == lltok::kw_declare);
357 return ParseFunctionHeader(F, false);
361 /// ::= 'define' FunctionHeader '{' ...
362 bool LLParser::ParseDefine() {
363 assert(Lex.getKind() == lltok::kw_define);
367 return ParseFunctionHeader(F, true) ||
368 ParseFunctionBody(*F);
374 bool LLParser::ParseGlobalType(bool &IsConstant) {
375 if (Lex.getKind() == lltok::kw_constant)
377 else if (Lex.getKind() == lltok::kw_global)
381 return TokError("expected 'global' or 'constant'");
387 /// ParseUnnamedGlobal:
388 /// OptionalVisibility ALIAS ...
389 /// OptionalLinkage OptionalVisibility ... -> global variable
390 /// GlobalID '=' OptionalVisibility ALIAS ...
391 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
392 bool LLParser::ParseUnnamedGlobal() {
393 unsigned VarID = NumberedVals.size();
395 LocTy NameLoc = Lex.getLoc();
397 // Handle the GlobalID form.
398 if (Lex.getKind() == lltok::GlobalID) {
399 if (Lex.getUIntVal() != VarID)
400 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
402 Lex.Lex(); // eat GlobalID;
404 if (ParseToken(lltok::equal, "expected '=' after name"))
409 unsigned Linkage, Visibility;
410 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
411 ParseOptionalVisibility(Visibility))
414 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
415 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
416 return ParseAlias(Name, NameLoc, Visibility);
419 /// ParseNamedGlobal:
420 /// GlobalVar '=' OptionalVisibility ALIAS ...
421 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
422 bool LLParser::ParseNamedGlobal() {
423 assert(Lex.getKind() == lltok::GlobalVar);
424 LocTy NameLoc = Lex.getLoc();
425 std::string Name = Lex.getStrVal();
429 unsigned Linkage, Visibility;
430 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
431 ParseOptionalLinkage(Linkage, HasLinkage) ||
432 ParseOptionalVisibility(Visibility))
435 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
436 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
437 return ParseAlias(Name, NameLoc, Visibility);
441 // ::= '!' STRINGCONSTANT
442 bool LLParser::ParseMDString(MDString *&Result) {
444 if (ParseStringConstant(Str)) return true;
445 Result = MDString::get(Context, Str);
450 // ::= '!' MDNodeNumber
452 /// This version of ParseMDNodeID returns the slot number and null in the case
453 /// of a forward reference.
454 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
455 // !{ ..., !42, ... }
456 if (ParseUInt32(SlotNo)) return true;
458 // Check existing MDNode.
459 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
460 Result = NumberedMetadata[SlotNo];
466 bool LLParser::ParseMDNodeID(MDNode *&Result) {
467 // !{ ..., !42, ... }
469 if (ParseMDNodeID(Result, MID)) return true;
471 // If not a forward reference, just return it now.
472 if (Result) return false;
474 // Otherwise, create MDNode forward reference.
475 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
476 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
478 if (NumberedMetadata.size() <= MID)
479 NumberedMetadata.resize(MID+1);
480 NumberedMetadata[MID] = FwdNode;
485 /// ParseNamedMetadata:
486 /// !foo = !{ !1, !2 }
487 bool LLParser::ParseNamedMetadata() {
488 assert(Lex.getKind() == lltok::MetadataVar);
489 std::string Name = Lex.getStrVal();
492 if (ParseToken(lltok::equal, "expected '=' here") ||
493 ParseToken(lltok::exclaim, "Expected '!' here") ||
494 ParseToken(lltok::lbrace, "Expected '{' here"))
497 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
498 if (Lex.getKind() != lltok::rbrace)
500 if (ParseToken(lltok::exclaim, "Expected '!' here"))
504 if (ParseMDNodeID(N)) return true;
506 } while (EatIfPresent(lltok::comma));
508 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
514 /// ParseStandaloneMetadata:
516 bool LLParser::ParseStandaloneMetadata() {
517 assert(Lex.getKind() == lltok::exclaim);
519 unsigned MetadataID = 0;
523 SmallVector<Value *, 16> Elts;
524 if (ParseUInt32(MetadataID) ||
525 ParseToken(lltok::equal, "expected '=' here") ||
526 ParseType(Ty, TyLoc) ||
527 ParseToken(lltok::exclaim, "Expected '!' here") ||
528 ParseToken(lltok::lbrace, "Expected '{' here") ||
529 ParseMDNodeVector(Elts, NULL) ||
530 ParseToken(lltok::rbrace, "expected end of metadata node"))
533 MDNode *Init = MDNode::get(Context, Elts);
535 // See if this was forward referenced, if so, handle it.
536 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
537 FI = ForwardRefMDNodes.find(MetadataID);
538 if (FI != ForwardRefMDNodes.end()) {
539 MDNode *Temp = FI->second.first;
540 Temp->replaceAllUsesWith(Init);
541 MDNode::deleteTemporary(Temp);
542 ForwardRefMDNodes.erase(FI);
544 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
546 if (MetadataID >= NumberedMetadata.size())
547 NumberedMetadata.resize(MetadataID+1);
549 if (NumberedMetadata[MetadataID] != 0)
550 return TokError("Metadata id is already used");
551 NumberedMetadata[MetadataID] = Init;
558 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
561 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
562 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
564 /// Everything through visibility has already been parsed.
566 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
567 unsigned Visibility) {
568 assert(Lex.getKind() == lltok::kw_alias);
571 LocTy LinkageLoc = Lex.getLoc();
572 if (ParseOptionalLinkage(Linkage))
575 if (Linkage != GlobalValue::ExternalLinkage &&
576 Linkage != GlobalValue::WeakAnyLinkage &&
577 Linkage != GlobalValue::WeakODRLinkage &&
578 Linkage != GlobalValue::InternalLinkage &&
579 Linkage != GlobalValue::PrivateLinkage &&
580 Linkage != GlobalValue::LinkerPrivateLinkage &&
581 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
582 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
583 return Error(LinkageLoc, "invalid linkage type for alias");
586 LocTy AliaseeLoc = Lex.getLoc();
587 if (Lex.getKind() != lltok::kw_bitcast &&
588 Lex.getKind() != lltok::kw_getelementptr) {
589 if (ParseGlobalTypeAndValue(Aliasee)) return true;
591 // The bitcast dest type is not present, it is implied by the dest type.
593 if (ParseValID(ID)) return true;
594 if (ID.Kind != ValID::t_Constant)
595 return Error(AliaseeLoc, "invalid aliasee");
596 Aliasee = ID.ConstantVal;
599 if (!Aliasee->getType()->isPointerTy())
600 return Error(AliaseeLoc, "alias must have pointer type");
602 // Okay, create the alias but do not insert it into the module yet.
603 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
604 (GlobalValue::LinkageTypes)Linkage, Name,
606 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
608 // See if this value already exists in the symbol table. If so, it is either
609 // a redefinition or a definition of a forward reference.
610 if (GlobalValue *Val = M->getNamedValue(Name)) {
611 // See if this was a redefinition. If so, there is no entry in
613 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
614 I = ForwardRefVals.find(Name);
615 if (I == ForwardRefVals.end())
616 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
618 // Otherwise, this was a definition of forward ref. Verify that types
620 if (Val->getType() != GA->getType())
621 return Error(NameLoc,
622 "forward reference and definition of alias have different types");
624 // If they agree, just RAUW the old value with the alias and remove the
626 Val->replaceAllUsesWith(GA);
627 Val->eraseFromParent();
628 ForwardRefVals.erase(I);
631 // Insert into the module, we know its name won't collide now.
632 M->getAliasList().push_back(GA);
633 assert(GA->getName() == Name && "Should not be a name conflict!");
639 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
640 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
641 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
642 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
644 /// Everything through visibility has been parsed already.
646 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
647 unsigned Linkage, bool HasLinkage,
648 unsigned Visibility) {
650 bool ThreadLocal, IsConstant, UnnamedAddr;
651 LocTy UnnamedAddrLoc;
655 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
656 ParseOptionalAddrSpace(AddrSpace) ||
657 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
659 ParseGlobalType(IsConstant) ||
660 ParseType(Ty, TyLoc))
663 // If the linkage is specified and is external, then no initializer is
666 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
667 Linkage != GlobalValue::ExternalWeakLinkage &&
668 Linkage != GlobalValue::ExternalLinkage)) {
669 if (ParseGlobalValue(Ty, Init))
673 if (Ty->isFunctionTy() || Ty->isLabelTy())
674 return Error(TyLoc, "invalid type for global variable");
676 GlobalVariable *GV = 0;
678 // See if the global was forward referenced, if so, use the global.
680 if (GlobalValue *GVal = M->getNamedValue(Name)) {
681 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
682 return Error(NameLoc, "redefinition of global '@" + Name + "'");
683 GV = cast<GlobalVariable>(GVal);
686 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
687 I = ForwardRefValIDs.find(NumberedVals.size());
688 if (I != ForwardRefValIDs.end()) {
689 GV = cast<GlobalVariable>(I->second.first);
690 ForwardRefValIDs.erase(I);
695 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
696 Name, 0, false, AddrSpace);
698 if (GV->getType()->getElementType() != Ty)
700 "forward reference and definition of global have different types");
702 // Move the forward-reference to the correct spot in the module.
703 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
707 NumberedVals.push_back(GV);
709 // Set the parsed properties on the global.
711 GV->setInitializer(Init);
712 GV->setConstant(IsConstant);
713 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
714 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
715 GV->setThreadLocal(ThreadLocal);
716 GV->setUnnamedAddr(UnnamedAddr);
718 // Parse attributes on the global.
719 while (Lex.getKind() == lltok::comma) {
722 if (Lex.getKind() == lltok::kw_section) {
724 GV->setSection(Lex.getStrVal());
725 if (ParseToken(lltok::StringConstant, "expected global section string"))
727 } else if (Lex.getKind() == lltok::kw_align) {
729 if (ParseOptionalAlignment(Alignment)) return true;
730 GV->setAlignment(Alignment);
732 TokError("unknown global variable property!");
740 //===----------------------------------------------------------------------===//
741 // GlobalValue Reference/Resolution Routines.
742 //===----------------------------------------------------------------------===//
744 /// GetGlobalVal - Get a value with the specified name or ID, creating a
745 /// forward reference record if needed. This can return null if the value
746 /// exists but does not have the right type.
747 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
749 PointerType *PTy = dyn_cast<PointerType>(Ty);
751 Error(Loc, "global variable reference must have pointer type");
755 // Look this name up in the normal function symbol table.
757 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
759 // If this is a forward reference for the value, see if we already created a
760 // forward ref record.
762 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
763 I = ForwardRefVals.find(Name);
764 if (I != ForwardRefVals.end())
765 Val = I->second.first;
768 // If we have the value in the symbol table or fwd-ref table, return it.
770 if (Val->getType() == Ty) return Val;
771 Error(Loc, "'@" + Name + "' defined with type '" +
772 getTypeString(Val->getType()) + "'");
776 // Otherwise, create a new forward reference for this value and remember it.
778 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
779 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
781 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
782 GlobalValue::ExternalWeakLinkage, 0, Name);
784 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
788 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
789 PointerType *PTy = dyn_cast<PointerType>(Ty);
791 Error(Loc, "global variable reference must have pointer type");
795 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
797 // If this is a forward reference for the value, see if we already created a
798 // forward ref record.
800 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
801 I = ForwardRefValIDs.find(ID);
802 if (I != ForwardRefValIDs.end())
803 Val = I->second.first;
806 // If we have the value in the symbol table or fwd-ref table, return it.
808 if (Val->getType() == Ty) return Val;
809 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
810 getTypeString(Val->getType()) + "'");
814 // Otherwise, create a new forward reference for this value and remember it.
816 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
817 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
819 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
820 GlobalValue::ExternalWeakLinkage, 0, "");
822 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
827 //===----------------------------------------------------------------------===//
829 //===----------------------------------------------------------------------===//
831 /// ParseToken - If the current token has the specified kind, eat it and return
832 /// success. Otherwise, emit the specified error and return failure.
833 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
834 if (Lex.getKind() != T)
835 return TokError(ErrMsg);
840 /// ParseStringConstant
841 /// ::= StringConstant
842 bool LLParser::ParseStringConstant(std::string &Result) {
843 if (Lex.getKind() != lltok::StringConstant)
844 return TokError("expected string constant");
845 Result = Lex.getStrVal();
852 bool LLParser::ParseUInt32(unsigned &Val) {
853 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
854 return TokError("expected integer");
855 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
856 if (Val64 != unsigned(Val64))
857 return TokError("expected 32-bit integer (too large)");
864 /// ParseOptionalAddrSpace
866 /// := 'addrspace' '(' uint32 ')'
867 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
869 if (!EatIfPresent(lltok::kw_addrspace))
871 return ParseToken(lltok::lparen, "expected '(' in address space") ||
872 ParseUInt32(AddrSpace) ||
873 ParseToken(lltok::rparen, "expected ')' in address space");
876 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
877 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
878 /// 2: function attr.
879 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
880 Attrs = Attribute::None;
881 LocTy AttrLoc = Lex.getLoc();
884 switch (Lex.getKind()) {
885 default: // End of attributes.
886 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
887 return Error(AttrLoc, "invalid use of function-only attribute");
889 // As a hack, we allow "align 2" on functions as a synonym for
892 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
893 return Error(AttrLoc, "invalid use of attribute on a function");
895 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
896 return Error(AttrLoc, "invalid use of parameter-only attribute");
899 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
900 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
901 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
902 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
903 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
904 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
905 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
906 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
908 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
909 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
910 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
911 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
912 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
913 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
914 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
915 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
916 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
917 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
918 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
919 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
920 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
921 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
922 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
923 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
925 case lltok::kw_alignstack: {
927 if (ParseOptionalStackAlignment(Alignment))
929 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
933 case lltok::kw_align: {
935 if (ParseOptionalAlignment(Alignment))
937 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
946 /// ParseOptionalLinkage
949 /// ::= 'linker_private'
950 /// ::= 'linker_private_weak'
951 /// ::= 'linker_private_weak_def_auto'
956 /// ::= 'linkonce_odr'
957 /// ::= 'available_externally'
962 /// ::= 'extern_weak'
964 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
966 switch (Lex.getKind()) {
967 default: Res=GlobalValue::ExternalLinkage; return false;
968 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
969 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
970 case lltok::kw_linker_private_weak:
971 Res = GlobalValue::LinkerPrivateWeakLinkage;
973 case lltok::kw_linker_private_weak_def_auto:
974 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
976 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
977 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
978 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
979 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
980 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
981 case lltok::kw_available_externally:
982 Res = GlobalValue::AvailableExternallyLinkage;
984 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
985 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
986 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
987 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
988 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
989 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
996 /// ParseOptionalVisibility
1002 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1003 switch (Lex.getKind()) {
1004 default: Res = GlobalValue::DefaultVisibility; return false;
1005 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1006 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1007 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1013 /// ParseOptionalCallingConv
1018 /// ::= 'x86_stdcallcc'
1019 /// ::= 'x86_fastcallcc'
1020 /// ::= 'x86_thiscallcc'
1021 /// ::= 'arm_apcscc'
1022 /// ::= 'arm_aapcscc'
1023 /// ::= 'arm_aapcs_vfpcc'
1024 /// ::= 'msp430_intrcc'
1025 /// ::= 'ptx_kernel'
1026 /// ::= 'ptx_device'
1029 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1030 switch (Lex.getKind()) {
1031 default: CC = CallingConv::C; return false;
1032 case lltok::kw_ccc: CC = CallingConv::C; break;
1033 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1034 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1035 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1036 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1037 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1038 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1039 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1040 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1041 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1042 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1043 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1044 case lltok::kw_cc: {
1045 unsigned ArbitraryCC;
1047 if (ParseUInt32(ArbitraryCC)) {
1050 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1060 /// ParseInstructionMetadata
1061 /// ::= !dbg !42 (',' !dbg !57)*
1062 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1063 PerFunctionState *PFS) {
1065 if (Lex.getKind() != lltok::MetadataVar)
1066 return TokError("expected metadata after comma");
1068 std::string Name = Lex.getStrVal();
1069 unsigned MDK = M->getMDKindID(Name.c_str());
1073 SMLoc Loc = Lex.getLoc();
1075 if (ParseToken(lltok::exclaim, "expected '!' here"))
1078 // This code is similar to that of ParseMetadataValue, however it needs to
1079 // have special-case code for a forward reference; see the comments on
1080 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1081 // at the top level here.
1082 if (Lex.getKind() == lltok::lbrace) {
1084 if (ParseMetadataListValue(ID, PFS))
1086 assert(ID.Kind == ValID::t_MDNode);
1087 Inst->setMetadata(MDK, ID.MDNodeVal);
1089 unsigned NodeID = 0;
1090 if (ParseMDNodeID(Node, NodeID))
1093 // If we got the node, add it to the instruction.
1094 Inst->setMetadata(MDK, Node);
1096 MDRef R = { Loc, MDK, NodeID };
1097 // Otherwise, remember that this should be resolved later.
1098 ForwardRefInstMetadata[Inst].push_back(R);
1102 // If this is the end of the list, we're done.
1103 } while (EatIfPresent(lltok::comma));
1107 /// ParseOptionalAlignment
1110 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1112 if (!EatIfPresent(lltok::kw_align))
1114 LocTy AlignLoc = Lex.getLoc();
1115 if (ParseUInt32(Alignment)) return true;
1116 if (!isPowerOf2_32(Alignment))
1117 return Error(AlignLoc, "alignment is not a power of two");
1118 if (Alignment > Value::MaximumAlignment)
1119 return Error(AlignLoc, "huge alignments are not supported yet");
1123 /// ParseOptionalCommaAlign
1127 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1129 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1130 bool &AteExtraComma) {
1131 AteExtraComma = false;
1132 while (EatIfPresent(lltok::comma)) {
1133 // Metadata at the end is an early exit.
1134 if (Lex.getKind() == lltok::MetadataVar) {
1135 AteExtraComma = true;
1139 if (Lex.getKind() != lltok::kw_align)
1140 return Error(Lex.getLoc(), "expected metadata or 'align'");
1142 if (ParseOptionalAlignment(Alignment)) return true;
1148 /// ParseScopeAndOrdering
1149 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1152 /// This sets Scope and Ordering to the parsed values.
1153 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1154 AtomicOrdering &Ordering) {
1158 Scope = CrossThread;
1159 if (EatIfPresent(lltok::kw_singlethread))
1160 Scope = SingleThread;
1161 switch (Lex.getKind()) {
1162 default: return TokError("Expected ordering on atomic instruction");
1163 case lltok::kw_unordered: Ordering = Unordered; break;
1164 case lltok::kw_monotonic: Ordering = Monotonic; break;
1165 case lltok::kw_acquire: Ordering = Acquire; break;
1166 case lltok::kw_release: Ordering = Release; break;
1167 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1168 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1174 /// ParseOptionalStackAlignment
1176 /// ::= 'alignstack' '(' 4 ')'
1177 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1179 if (!EatIfPresent(lltok::kw_alignstack))
1181 LocTy ParenLoc = Lex.getLoc();
1182 if (!EatIfPresent(lltok::lparen))
1183 return Error(ParenLoc, "expected '('");
1184 LocTy AlignLoc = Lex.getLoc();
1185 if (ParseUInt32(Alignment)) return true;
1186 ParenLoc = Lex.getLoc();
1187 if (!EatIfPresent(lltok::rparen))
1188 return Error(ParenLoc, "expected ')'");
1189 if (!isPowerOf2_32(Alignment))
1190 return Error(AlignLoc, "stack alignment is not a power of two");
1194 /// ParseIndexList - This parses the index list for an insert/extractvalue
1195 /// instruction. This sets AteExtraComma in the case where we eat an extra
1196 /// comma at the end of the line and find that it is followed by metadata.
1197 /// Clients that don't allow metadata can call the version of this function that
1198 /// only takes one argument.
1201 /// ::= (',' uint32)+
1203 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1204 bool &AteExtraComma) {
1205 AteExtraComma = false;
1207 if (Lex.getKind() != lltok::comma)
1208 return TokError("expected ',' as start of index list");
1210 while (EatIfPresent(lltok::comma)) {
1211 if (Lex.getKind() == lltok::MetadataVar) {
1212 AteExtraComma = true;
1216 if (ParseUInt32(Idx)) return true;
1217 Indices.push_back(Idx);
1223 //===----------------------------------------------------------------------===//
1225 //===----------------------------------------------------------------------===//
1227 /// ParseType - Parse a type.
1228 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1229 SMLoc TypeLoc = Lex.getLoc();
1230 switch (Lex.getKind()) {
1232 return TokError("expected type");
1234 // Type ::= 'float' | 'void' (etc)
1235 Result = Lex.getTyVal();
1239 // Type ::= StructType
1240 if (ParseAnonStructType(Result, false))
1243 case lltok::lsquare:
1244 // Type ::= '[' ... ']'
1245 Lex.Lex(); // eat the lsquare.
1246 if (ParseArrayVectorType(Result, false))
1249 case lltok::less: // Either vector or packed struct.
1250 // Type ::= '<' ... '>'
1252 if (Lex.getKind() == lltok::lbrace) {
1253 if (ParseAnonStructType(Result, true) ||
1254 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1256 } else if (ParseArrayVectorType(Result, true))
1259 case lltok::LocalVar: {
1261 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1263 // If the type hasn't been defined yet, create a forward definition and
1264 // remember where that forward def'n was seen (in case it never is defined).
1265 if (Entry.first == 0) {
1266 Entry.first = StructType::create(Context, Lex.getStrVal());
1267 Entry.second = Lex.getLoc();
1269 Result = Entry.first;
1274 case lltok::LocalVarID: {
1276 if (Lex.getUIntVal() >= NumberedTypes.size())
1277 NumberedTypes.resize(Lex.getUIntVal()+1);
1278 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1280 // If the type hasn't been defined yet, create a forward definition and
1281 // remember where that forward def'n was seen (in case it never is defined).
1282 if (Entry.first == 0) {
1283 Entry.first = StructType::create(Context);
1284 Entry.second = Lex.getLoc();
1286 Result = Entry.first;
1292 // Parse the type suffixes.
1294 switch (Lex.getKind()) {
1297 if (!AllowVoid && Result->isVoidTy())
1298 return Error(TypeLoc, "void type only allowed for function results");
1301 // Type ::= Type '*'
1303 if (Result->isLabelTy())
1304 return TokError("basic block pointers are invalid");
1305 if (Result->isVoidTy())
1306 return TokError("pointers to void are invalid - use i8* instead");
1307 if (!PointerType::isValidElementType(Result))
1308 return TokError("pointer to this type is invalid");
1309 Result = PointerType::getUnqual(Result);
1313 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1314 case lltok::kw_addrspace: {
1315 if (Result->isLabelTy())
1316 return TokError("basic block pointers are invalid");
1317 if (Result->isVoidTy())
1318 return TokError("pointers to void are invalid; use i8* instead");
1319 if (!PointerType::isValidElementType(Result))
1320 return TokError("pointer to this type is invalid");
1322 if (ParseOptionalAddrSpace(AddrSpace) ||
1323 ParseToken(lltok::star, "expected '*' in address space"))
1326 Result = PointerType::get(Result, AddrSpace);
1330 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1332 if (ParseFunctionType(Result))
1339 /// ParseParameterList
1341 /// ::= '(' Arg (',' Arg)* ')'
1343 /// ::= Type OptionalAttributes Value OptionalAttributes
1344 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1345 PerFunctionState &PFS) {
1346 if (ParseToken(lltok::lparen, "expected '(' in call"))
1349 while (Lex.getKind() != lltok::rparen) {
1350 // If this isn't the first argument, we need a comma.
1351 if (!ArgList.empty() &&
1352 ParseToken(lltok::comma, "expected ',' in argument list"))
1355 // Parse the argument.
1358 unsigned ArgAttrs1 = Attribute::None;
1359 unsigned ArgAttrs2 = Attribute::None;
1361 if (ParseType(ArgTy, ArgLoc))
1364 // Otherwise, handle normal operands.
1365 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
1367 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1370 Lex.Lex(); // Lex the ')'.
1376 /// ParseArgumentList - Parse the argument list for a function type or function
1378 /// ::= '(' ArgTypeListI ')'
1382 /// ::= ArgTypeList ',' '...'
1383 /// ::= ArgType (',' ArgType)*
1385 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1388 assert(Lex.getKind() == lltok::lparen);
1389 Lex.Lex(); // eat the (.
1391 if (Lex.getKind() == lltok::rparen) {
1393 } else if (Lex.getKind() == lltok::dotdotdot) {
1397 LocTy TypeLoc = Lex.getLoc();
1402 if (ParseType(ArgTy) ||
1403 ParseOptionalAttrs(Attrs, 0)) return true;
1405 if (ArgTy->isVoidTy())
1406 return Error(TypeLoc, "argument can not have void type");
1408 if (Lex.getKind() == lltok::LocalVar) {
1409 Name = Lex.getStrVal();
1413 if (!FunctionType::isValidArgumentType(ArgTy))
1414 return Error(TypeLoc, "invalid type for function argument");
1416 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1418 while (EatIfPresent(lltok::comma)) {
1419 // Handle ... at end of arg list.
1420 if (EatIfPresent(lltok::dotdotdot)) {
1425 // Otherwise must be an argument type.
1426 TypeLoc = Lex.getLoc();
1427 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
1429 if (ArgTy->isVoidTy())
1430 return Error(TypeLoc, "argument can not have void type");
1432 if (Lex.getKind() == lltok::LocalVar) {
1433 Name = Lex.getStrVal();
1439 if (!ArgTy->isFirstClassType())
1440 return Error(TypeLoc, "invalid type for function argument");
1442 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1446 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1449 /// ParseFunctionType
1450 /// ::= Type ArgumentList OptionalAttrs
1451 bool LLParser::ParseFunctionType(Type *&Result) {
1452 assert(Lex.getKind() == lltok::lparen);
1454 if (!FunctionType::isValidReturnType(Result))
1455 return TokError("invalid function return type");
1457 SmallVector<ArgInfo, 8> ArgList;
1459 if (ParseArgumentList(ArgList, isVarArg))
1462 // Reject names on the arguments lists.
1463 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1464 if (!ArgList[i].Name.empty())
1465 return Error(ArgList[i].Loc, "argument name invalid in function type");
1466 if (ArgList[i].Attrs != 0)
1467 return Error(ArgList[i].Loc,
1468 "argument attributes invalid in function type");
1471 SmallVector<Type*, 16> ArgListTy;
1472 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1473 ArgListTy.push_back(ArgList[i].Ty);
1475 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1479 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1481 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1482 SmallVector<Type*, 8> Elts;
1483 if (ParseStructBody(Elts)) return true;
1485 Result = StructType::get(Context, Elts, Packed);
1489 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1490 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1491 std::pair<Type*, LocTy> &Entry,
1493 // If the type was already defined, diagnose the redefinition.
1494 if (Entry.first && !Entry.second.isValid())
1495 return Error(TypeLoc, "redefinition of type");
1497 // If we have opaque, just return without filling in the definition for the
1498 // struct. This counts as a definition as far as the .ll file goes.
1499 if (EatIfPresent(lltok::kw_opaque)) {
1500 // This type is being defined, so clear the location to indicate this.
1501 Entry.second = SMLoc();
1503 // If this type number has never been uttered, create it.
1504 if (Entry.first == 0)
1505 Entry.first = StructType::create(Context, Name);
1506 ResultTy = Entry.first;
1510 // If the type starts with '<', then it is either a packed struct or a vector.
1511 bool isPacked = EatIfPresent(lltok::less);
1513 // If we don't have a struct, then we have a random type alias, which we
1514 // accept for compatibility with old files. These types are not allowed to be
1515 // forward referenced and not allowed to be recursive.
1516 if (Lex.getKind() != lltok::lbrace) {
1518 return Error(TypeLoc, "forward references to non-struct type");
1522 return ParseArrayVectorType(ResultTy, true);
1523 return ParseType(ResultTy);
1526 // This type is being defined, so clear the location to indicate this.
1527 Entry.second = SMLoc();
1529 // If this type number has never been uttered, create it.
1530 if (Entry.first == 0)
1531 Entry.first = StructType::create(Context, Name);
1533 StructType *STy = cast<StructType>(Entry.first);
1535 SmallVector<Type*, 8> Body;
1536 if (ParseStructBody(Body) ||
1537 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1540 STy->setBody(Body, isPacked);
1546 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1549 /// ::= '{' Type (',' Type)* '}'
1550 /// ::= '<' '{' '}' '>'
1551 /// ::= '<' '{' Type (',' Type)* '}' '>'
1552 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1553 assert(Lex.getKind() == lltok::lbrace);
1554 Lex.Lex(); // Consume the '{'
1556 // Handle the empty struct.
1557 if (EatIfPresent(lltok::rbrace))
1560 LocTy EltTyLoc = Lex.getLoc();
1562 if (ParseType(Ty)) return true;
1565 if (!StructType::isValidElementType(Ty))
1566 return Error(EltTyLoc, "invalid element type for struct");
1568 while (EatIfPresent(lltok::comma)) {
1569 EltTyLoc = Lex.getLoc();
1570 if (ParseType(Ty)) return true;
1572 if (!StructType::isValidElementType(Ty))
1573 return Error(EltTyLoc, "invalid element type for struct");
1578 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1581 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1582 /// token has already been consumed.
1584 /// ::= '[' APSINTVAL 'x' Types ']'
1585 /// ::= '<' APSINTVAL 'x' Types '>'
1586 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1587 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1588 Lex.getAPSIntVal().getBitWidth() > 64)
1589 return TokError("expected number in address space");
1591 LocTy SizeLoc = Lex.getLoc();
1592 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1595 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1598 LocTy TypeLoc = Lex.getLoc();
1600 if (ParseType(EltTy)) return true;
1602 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1603 "expected end of sequential type"))
1608 return Error(SizeLoc, "zero element vector is illegal");
1609 if ((unsigned)Size != Size)
1610 return Error(SizeLoc, "size too large for vector");
1611 if (!VectorType::isValidElementType(EltTy))
1612 return Error(TypeLoc, "vector element type must be fp or integer");
1613 Result = VectorType::get(EltTy, unsigned(Size));
1615 if (!ArrayType::isValidElementType(EltTy))
1616 return Error(TypeLoc, "invalid array element type");
1617 Result = ArrayType::get(EltTy, Size);
1622 //===----------------------------------------------------------------------===//
1623 // Function Semantic Analysis.
1624 //===----------------------------------------------------------------------===//
1626 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1628 : P(p), F(f), FunctionNumber(functionNumber) {
1630 // Insert unnamed arguments into the NumberedVals list.
1631 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1634 NumberedVals.push_back(AI);
1637 LLParser::PerFunctionState::~PerFunctionState() {
1638 // If there were any forward referenced non-basicblock values, delete them.
1639 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1640 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1641 if (!isa<BasicBlock>(I->second.first)) {
1642 I->second.first->replaceAllUsesWith(
1643 UndefValue::get(I->second.first->getType()));
1644 delete I->second.first;
1645 I->second.first = 0;
1648 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1649 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.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;
1658 bool LLParser::PerFunctionState::FinishFunction() {
1659 // Check to see if someone took the address of labels in this block.
1660 if (!P.ForwardRefBlockAddresses.empty()) {
1662 if (!F.getName().empty()) {
1663 FunctionID.Kind = ValID::t_GlobalName;
1664 FunctionID.StrVal = F.getName();
1666 FunctionID.Kind = ValID::t_GlobalID;
1667 FunctionID.UIntVal = FunctionNumber;
1670 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1671 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1672 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1673 // Resolve all these references.
1674 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1677 P.ForwardRefBlockAddresses.erase(FRBAI);
1681 if (!ForwardRefVals.empty())
1682 return P.Error(ForwardRefVals.begin()->second.second,
1683 "use of undefined value '%" + ForwardRefVals.begin()->first +
1685 if (!ForwardRefValIDs.empty())
1686 return P.Error(ForwardRefValIDs.begin()->second.second,
1687 "use of undefined value '%" +
1688 Twine(ForwardRefValIDs.begin()->first) + "'");
1693 /// GetVal - Get a value with the specified name or ID, creating a
1694 /// forward reference record if needed. This can return null if the value
1695 /// exists but does not have the right type.
1696 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1697 Type *Ty, LocTy Loc) {
1698 // Look this name up in the normal function symbol table.
1699 Value *Val = F.getValueSymbolTable().lookup(Name);
1701 // If this is a forward reference for the value, see if we already created a
1702 // forward ref record.
1704 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1705 I = ForwardRefVals.find(Name);
1706 if (I != ForwardRefVals.end())
1707 Val = I->second.first;
1710 // If we have the value in the symbol table or fwd-ref table, return it.
1712 if (Val->getType() == Ty) return Val;
1713 if (Ty->isLabelTy())
1714 P.Error(Loc, "'%" + Name + "' is not a basic block");
1716 P.Error(Loc, "'%" + Name + "' defined with type '" +
1717 getTypeString(Val->getType()) + "'");
1721 // Don't make placeholders with invalid type.
1722 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1723 P.Error(Loc, "invalid use of a non-first-class type");
1727 // Otherwise, create a new forward reference for this value and remember it.
1729 if (Ty->isLabelTy())
1730 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1732 FwdVal = new Argument(Ty, Name);
1734 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1738 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1740 // Look this name up in the normal function symbol table.
1741 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1743 // If this is a forward reference for the value, see if we already created a
1744 // forward ref record.
1746 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1747 I = ForwardRefValIDs.find(ID);
1748 if (I != ForwardRefValIDs.end())
1749 Val = I->second.first;
1752 // If we have the value in the symbol table or fwd-ref table, return it.
1754 if (Val->getType() == Ty) return Val;
1755 if (Ty->isLabelTy())
1756 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1758 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1759 getTypeString(Val->getType()) + "'");
1763 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1764 P.Error(Loc, "invalid use of a non-first-class type");
1768 // Otherwise, create a new forward reference for this value and remember it.
1770 if (Ty->isLabelTy())
1771 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1773 FwdVal = new Argument(Ty);
1775 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1779 /// SetInstName - After an instruction is parsed and inserted into its
1780 /// basic block, this installs its name.
1781 bool LLParser::PerFunctionState::SetInstName(int NameID,
1782 const std::string &NameStr,
1783 LocTy NameLoc, Instruction *Inst) {
1784 // If this instruction has void type, it cannot have a name or ID specified.
1785 if (Inst->getType()->isVoidTy()) {
1786 if (NameID != -1 || !NameStr.empty())
1787 return P.Error(NameLoc, "instructions returning void cannot have a name");
1791 // If this was a numbered instruction, verify that the instruction is the
1792 // expected value and resolve any forward references.
1793 if (NameStr.empty()) {
1794 // If neither a name nor an ID was specified, just use the next ID.
1796 NameID = NumberedVals.size();
1798 if (unsigned(NameID) != NumberedVals.size())
1799 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1800 Twine(NumberedVals.size()) + "'");
1802 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1803 ForwardRefValIDs.find(NameID);
1804 if (FI != ForwardRefValIDs.end()) {
1805 if (FI->second.first->getType() != Inst->getType())
1806 return P.Error(NameLoc, "instruction forward referenced with type '" +
1807 getTypeString(FI->second.first->getType()) + "'");
1808 FI->second.first->replaceAllUsesWith(Inst);
1809 delete FI->second.first;
1810 ForwardRefValIDs.erase(FI);
1813 NumberedVals.push_back(Inst);
1817 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1818 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1819 FI = ForwardRefVals.find(NameStr);
1820 if (FI != ForwardRefVals.end()) {
1821 if (FI->second.first->getType() != Inst->getType())
1822 return P.Error(NameLoc, "instruction forward referenced with type '" +
1823 getTypeString(FI->second.first->getType()) + "'");
1824 FI->second.first->replaceAllUsesWith(Inst);
1825 delete FI->second.first;
1826 ForwardRefVals.erase(FI);
1829 // Set the name on the instruction.
1830 Inst->setName(NameStr);
1832 if (Inst->getName() != NameStr)
1833 return P.Error(NameLoc, "multiple definition of local value named '" +
1838 /// GetBB - Get a basic block with the specified name or ID, creating a
1839 /// forward reference record if needed.
1840 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1842 return cast_or_null<BasicBlock>(GetVal(Name,
1843 Type::getLabelTy(F.getContext()), Loc));
1846 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1847 return cast_or_null<BasicBlock>(GetVal(ID,
1848 Type::getLabelTy(F.getContext()), Loc));
1851 /// DefineBB - Define the specified basic block, which is either named or
1852 /// unnamed. If there is an error, this returns null otherwise it returns
1853 /// the block being defined.
1854 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1858 BB = GetBB(NumberedVals.size(), Loc);
1860 BB = GetBB(Name, Loc);
1861 if (BB == 0) return 0; // Already diagnosed error.
1863 // Move the block to the end of the function. Forward ref'd blocks are
1864 // inserted wherever they happen to be referenced.
1865 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1867 // Remove the block from forward ref sets.
1869 ForwardRefValIDs.erase(NumberedVals.size());
1870 NumberedVals.push_back(BB);
1872 // BB forward references are already in the function symbol table.
1873 ForwardRefVals.erase(Name);
1879 //===----------------------------------------------------------------------===//
1881 //===----------------------------------------------------------------------===//
1883 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1884 /// type implied. For example, if we parse "4" we don't know what integer type
1885 /// it has. The value will later be combined with its type and checked for
1886 /// sanity. PFS is used to convert function-local operands of metadata (since
1887 /// metadata operands are not just parsed here but also converted to values).
1888 /// PFS can be null when we are not parsing metadata values inside a function.
1889 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1890 ID.Loc = Lex.getLoc();
1891 switch (Lex.getKind()) {
1892 default: return TokError("expected value token");
1893 case lltok::GlobalID: // @42
1894 ID.UIntVal = Lex.getUIntVal();
1895 ID.Kind = ValID::t_GlobalID;
1897 case lltok::GlobalVar: // @foo
1898 ID.StrVal = Lex.getStrVal();
1899 ID.Kind = ValID::t_GlobalName;
1901 case lltok::LocalVarID: // %42
1902 ID.UIntVal = Lex.getUIntVal();
1903 ID.Kind = ValID::t_LocalID;
1905 case lltok::LocalVar: // %foo
1906 ID.StrVal = Lex.getStrVal();
1907 ID.Kind = ValID::t_LocalName;
1909 case lltok::exclaim: // !42, !{...}, or !"foo"
1910 return ParseMetadataValue(ID, PFS);
1912 ID.APSIntVal = Lex.getAPSIntVal();
1913 ID.Kind = ValID::t_APSInt;
1915 case lltok::APFloat:
1916 ID.APFloatVal = Lex.getAPFloatVal();
1917 ID.Kind = ValID::t_APFloat;
1919 case lltok::kw_true:
1920 ID.ConstantVal = ConstantInt::getTrue(Context);
1921 ID.Kind = ValID::t_Constant;
1923 case lltok::kw_false:
1924 ID.ConstantVal = ConstantInt::getFalse(Context);
1925 ID.Kind = ValID::t_Constant;
1927 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1928 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1929 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1931 case lltok::lbrace: {
1932 // ValID ::= '{' ConstVector '}'
1934 SmallVector<Constant*, 16> Elts;
1935 if (ParseGlobalValueVector(Elts) ||
1936 ParseToken(lltok::rbrace, "expected end of struct constant"))
1939 ID.ConstantStructElts = new Constant*[Elts.size()];
1940 ID.UIntVal = Elts.size();
1941 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1942 ID.Kind = ValID::t_ConstantStruct;
1946 // ValID ::= '<' ConstVector '>' --> Vector.
1947 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1949 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1951 SmallVector<Constant*, 16> Elts;
1952 LocTy FirstEltLoc = Lex.getLoc();
1953 if (ParseGlobalValueVector(Elts) ||
1955 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1956 ParseToken(lltok::greater, "expected end of constant"))
1959 if (isPackedStruct) {
1960 ID.ConstantStructElts = new Constant*[Elts.size()];
1961 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
1962 ID.UIntVal = Elts.size();
1963 ID.Kind = ValID::t_PackedConstantStruct;
1968 return Error(ID.Loc, "constant vector must not be empty");
1970 if (!Elts[0]->getType()->isIntegerTy() &&
1971 !Elts[0]->getType()->isFloatingPointTy())
1972 return Error(FirstEltLoc,
1973 "vector elements must have integer or floating point type");
1975 // Verify that all the vector elements have the same type.
1976 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1977 if (Elts[i]->getType() != Elts[0]->getType())
1978 return Error(FirstEltLoc,
1979 "vector element #" + Twine(i) +
1980 " is not of type '" + getTypeString(Elts[0]->getType()));
1982 ID.ConstantVal = ConstantVector::get(Elts);
1983 ID.Kind = ValID::t_Constant;
1986 case lltok::lsquare: { // Array Constant
1988 SmallVector<Constant*, 16> Elts;
1989 LocTy FirstEltLoc = Lex.getLoc();
1990 if (ParseGlobalValueVector(Elts) ||
1991 ParseToken(lltok::rsquare, "expected end of array constant"))
1994 // Handle empty element.
1996 // Use undef instead of an array because it's inconvenient to determine
1997 // the element type at this point, there being no elements to examine.
1998 ID.Kind = ValID::t_EmptyArray;
2002 if (!Elts[0]->getType()->isFirstClassType())
2003 return Error(FirstEltLoc, "invalid array element type: " +
2004 getTypeString(Elts[0]->getType()));
2006 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2008 // Verify all elements are correct type!
2009 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2010 if (Elts[i]->getType() != Elts[0]->getType())
2011 return Error(FirstEltLoc,
2012 "array element #" + Twine(i) +
2013 " is not of type '" + getTypeString(Elts[0]->getType()));
2016 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2017 ID.Kind = ValID::t_Constant;
2020 case lltok::kw_c: // c "foo"
2022 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2023 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2024 ID.Kind = ValID::t_Constant;
2027 case lltok::kw_asm: {
2028 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2029 bool HasSideEffect, AlignStack;
2031 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2032 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2033 ParseStringConstant(ID.StrVal) ||
2034 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2035 ParseToken(lltok::StringConstant, "expected constraint string"))
2037 ID.StrVal2 = Lex.getStrVal();
2038 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2039 ID.Kind = ValID::t_InlineAsm;
2043 case lltok::kw_blockaddress: {
2044 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2048 LocTy FnLoc, LabelLoc;
2050 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2052 ParseToken(lltok::comma, "expected comma in block address expression")||
2053 ParseValID(Label) ||
2054 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2057 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2058 return Error(Fn.Loc, "expected function name in blockaddress");
2059 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2060 return Error(Label.Loc, "expected basic block name in blockaddress");
2062 // Make a global variable as a placeholder for this reference.
2063 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2064 false, GlobalValue::InternalLinkage,
2066 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2067 ID.ConstantVal = FwdRef;
2068 ID.Kind = ValID::t_Constant;
2072 case lltok::kw_trunc:
2073 case lltok::kw_zext:
2074 case lltok::kw_sext:
2075 case lltok::kw_fptrunc:
2076 case lltok::kw_fpext:
2077 case lltok::kw_bitcast:
2078 case lltok::kw_uitofp:
2079 case lltok::kw_sitofp:
2080 case lltok::kw_fptoui:
2081 case lltok::kw_fptosi:
2082 case lltok::kw_inttoptr:
2083 case lltok::kw_ptrtoint: {
2084 unsigned Opc = Lex.getUIntVal();
2088 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2089 ParseGlobalTypeAndValue(SrcVal) ||
2090 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2091 ParseType(DestTy) ||
2092 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2094 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2095 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2096 getTypeString(SrcVal->getType()) + "' to '" +
2097 getTypeString(DestTy) + "'");
2098 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2100 ID.Kind = ValID::t_Constant;
2103 case lltok::kw_extractvalue: {
2106 SmallVector<unsigned, 4> Indices;
2107 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2108 ParseGlobalTypeAndValue(Val) ||
2109 ParseIndexList(Indices) ||
2110 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2113 if (!Val->getType()->isAggregateType())
2114 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2115 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2116 return Error(ID.Loc, "invalid indices for extractvalue");
2117 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2118 ID.Kind = ValID::t_Constant;
2121 case lltok::kw_insertvalue: {
2123 Constant *Val0, *Val1;
2124 SmallVector<unsigned, 4> Indices;
2125 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2126 ParseGlobalTypeAndValue(Val0) ||
2127 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2128 ParseGlobalTypeAndValue(Val1) ||
2129 ParseIndexList(Indices) ||
2130 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2132 if (!Val0->getType()->isAggregateType())
2133 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2134 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2135 return Error(ID.Loc, "invalid indices for insertvalue");
2136 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2137 ID.Kind = ValID::t_Constant;
2140 case lltok::kw_icmp:
2141 case lltok::kw_fcmp: {
2142 unsigned PredVal, Opc = Lex.getUIntVal();
2143 Constant *Val0, *Val1;
2145 if (ParseCmpPredicate(PredVal, Opc) ||
2146 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2147 ParseGlobalTypeAndValue(Val0) ||
2148 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2149 ParseGlobalTypeAndValue(Val1) ||
2150 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2153 if (Val0->getType() != Val1->getType())
2154 return Error(ID.Loc, "compare operands must have the same type");
2156 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2158 if (Opc == Instruction::FCmp) {
2159 if (!Val0->getType()->isFPOrFPVectorTy())
2160 return Error(ID.Loc, "fcmp requires floating point operands");
2161 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2163 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2164 if (!Val0->getType()->isIntOrIntVectorTy() &&
2165 !Val0->getType()->isPointerTy())
2166 return Error(ID.Loc, "icmp requires pointer or integer operands");
2167 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2169 ID.Kind = ValID::t_Constant;
2173 // Binary Operators.
2175 case lltok::kw_fadd:
2177 case lltok::kw_fsub:
2179 case lltok::kw_fmul:
2180 case lltok::kw_udiv:
2181 case lltok::kw_sdiv:
2182 case lltok::kw_fdiv:
2183 case lltok::kw_urem:
2184 case lltok::kw_srem:
2185 case lltok::kw_frem:
2187 case lltok::kw_lshr:
2188 case lltok::kw_ashr: {
2192 unsigned Opc = Lex.getUIntVal();
2193 Constant *Val0, *Val1;
2195 LocTy ModifierLoc = Lex.getLoc();
2196 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2197 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2198 if (EatIfPresent(lltok::kw_nuw))
2200 if (EatIfPresent(lltok::kw_nsw)) {
2202 if (EatIfPresent(lltok::kw_nuw))
2205 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2206 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2207 if (EatIfPresent(lltok::kw_exact))
2210 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2211 ParseGlobalTypeAndValue(Val0) ||
2212 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2213 ParseGlobalTypeAndValue(Val1) ||
2214 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2216 if (Val0->getType() != Val1->getType())
2217 return Error(ID.Loc, "operands of constexpr must have same type");
2218 if (!Val0->getType()->isIntOrIntVectorTy()) {
2220 return Error(ModifierLoc, "nuw only applies to integer operations");
2222 return Error(ModifierLoc, "nsw only applies to integer operations");
2224 // Check that the type is valid for the operator.
2226 case Instruction::Add:
2227 case Instruction::Sub:
2228 case Instruction::Mul:
2229 case Instruction::UDiv:
2230 case Instruction::SDiv:
2231 case Instruction::URem:
2232 case Instruction::SRem:
2233 case Instruction::Shl:
2234 case Instruction::AShr:
2235 case Instruction::LShr:
2236 if (!Val0->getType()->isIntOrIntVectorTy())
2237 return Error(ID.Loc, "constexpr requires integer operands");
2239 case Instruction::FAdd:
2240 case Instruction::FSub:
2241 case Instruction::FMul:
2242 case Instruction::FDiv:
2243 case Instruction::FRem:
2244 if (!Val0->getType()->isFPOrFPVectorTy())
2245 return Error(ID.Loc, "constexpr requires fp operands");
2247 default: llvm_unreachable("Unknown binary operator!");
2250 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2251 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2252 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2253 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2255 ID.Kind = ValID::t_Constant;
2259 // Logical Operations
2262 case lltok::kw_xor: {
2263 unsigned Opc = Lex.getUIntVal();
2264 Constant *Val0, *Val1;
2266 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2267 ParseGlobalTypeAndValue(Val0) ||
2268 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2269 ParseGlobalTypeAndValue(Val1) ||
2270 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2272 if (Val0->getType() != Val1->getType())
2273 return Error(ID.Loc, "operands of constexpr must have same type");
2274 if (!Val0->getType()->isIntOrIntVectorTy())
2275 return Error(ID.Loc,
2276 "constexpr requires integer or integer vector operands");
2277 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2278 ID.Kind = ValID::t_Constant;
2282 case lltok::kw_getelementptr:
2283 case lltok::kw_shufflevector:
2284 case lltok::kw_insertelement:
2285 case lltok::kw_extractelement:
2286 case lltok::kw_select: {
2287 unsigned Opc = Lex.getUIntVal();
2288 SmallVector<Constant*, 16> Elts;
2289 bool InBounds = false;
2291 if (Opc == Instruction::GetElementPtr)
2292 InBounds = EatIfPresent(lltok::kw_inbounds);
2293 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2294 ParseGlobalValueVector(Elts) ||
2295 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2298 if (Opc == Instruction::GetElementPtr) {
2299 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2300 return Error(ID.Loc, "getelementptr requires pointer operand");
2302 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2303 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2304 return Error(ID.Loc, "invalid indices for getelementptr");
2305 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2307 } else if (Opc == Instruction::Select) {
2308 if (Elts.size() != 3)
2309 return Error(ID.Loc, "expected three operands to select");
2310 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2312 return Error(ID.Loc, Reason);
2313 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2314 } else if (Opc == Instruction::ShuffleVector) {
2315 if (Elts.size() != 3)
2316 return Error(ID.Loc, "expected three operands to shufflevector");
2317 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2318 return Error(ID.Loc, "invalid operands to shufflevector");
2320 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2321 } else if (Opc == Instruction::ExtractElement) {
2322 if (Elts.size() != 2)
2323 return Error(ID.Loc, "expected two operands to extractelement");
2324 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2325 return Error(ID.Loc, "invalid extractelement operands");
2326 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2328 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2329 if (Elts.size() != 3)
2330 return Error(ID.Loc, "expected three operands to insertelement");
2331 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2332 return Error(ID.Loc, "invalid insertelement operands");
2334 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2337 ID.Kind = ValID::t_Constant;
2346 /// ParseGlobalValue - Parse a global value with the specified type.
2347 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2351 bool Parsed = ParseValID(ID) ||
2352 ConvertValIDToValue(Ty, ID, V, NULL);
2353 if (V && !(C = dyn_cast<Constant>(V)))
2354 return Error(ID.Loc, "global values must be constants");
2358 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2360 return ParseType(Ty) ||
2361 ParseGlobalValue(Ty, V);
2364 /// ParseGlobalValueVector
2366 /// ::= TypeAndValue (',' TypeAndValue)*
2367 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2369 if (Lex.getKind() == lltok::rbrace ||
2370 Lex.getKind() == lltok::rsquare ||
2371 Lex.getKind() == lltok::greater ||
2372 Lex.getKind() == lltok::rparen)
2376 if (ParseGlobalTypeAndValue(C)) return true;
2379 while (EatIfPresent(lltok::comma)) {
2380 if (ParseGlobalTypeAndValue(C)) return true;
2387 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2388 assert(Lex.getKind() == lltok::lbrace);
2391 SmallVector<Value*, 16> Elts;
2392 if (ParseMDNodeVector(Elts, PFS) ||
2393 ParseToken(lltok::rbrace, "expected end of metadata node"))
2396 ID.MDNodeVal = MDNode::get(Context, Elts);
2397 ID.Kind = ValID::t_MDNode;
2401 /// ParseMetadataValue
2405 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2406 assert(Lex.getKind() == lltok::exclaim);
2411 if (Lex.getKind() == lltok::lbrace)
2412 return ParseMetadataListValue(ID, PFS);
2414 // Standalone metadata reference
2416 if (Lex.getKind() == lltok::APSInt) {
2417 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2418 ID.Kind = ValID::t_MDNode;
2423 // ::= '!' STRINGCONSTANT
2424 if (ParseMDString(ID.MDStringVal)) return true;
2425 ID.Kind = ValID::t_MDString;
2430 //===----------------------------------------------------------------------===//
2431 // Function Parsing.
2432 //===----------------------------------------------------------------------===//
2434 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2435 PerFunctionState *PFS) {
2436 if (Ty->isFunctionTy())
2437 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2440 default: llvm_unreachable("Unknown ValID!");
2441 case ValID::t_LocalID:
2442 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2443 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2445 case ValID::t_LocalName:
2446 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2447 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2449 case ValID::t_InlineAsm: {
2450 PointerType *PTy = dyn_cast<PointerType>(Ty);
2452 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2453 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2454 return Error(ID.Loc, "invalid type for inline asm constraint string");
2455 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2458 case ValID::t_MDNode:
2459 if (!Ty->isMetadataTy())
2460 return Error(ID.Loc, "metadata value must have metadata type");
2463 case ValID::t_MDString:
2464 if (!Ty->isMetadataTy())
2465 return Error(ID.Loc, "metadata value must have metadata type");
2468 case ValID::t_GlobalName:
2469 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2471 case ValID::t_GlobalID:
2472 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2474 case ValID::t_APSInt:
2475 if (!Ty->isIntegerTy())
2476 return Error(ID.Loc, "integer constant must have integer type");
2477 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2478 V = ConstantInt::get(Context, ID.APSIntVal);
2480 case ValID::t_APFloat:
2481 if (!Ty->isFloatingPointTy() ||
2482 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2483 return Error(ID.Loc, "floating point constant invalid for type");
2485 // The lexer has no type info, so builds all float and double FP constants
2486 // as double. Fix this here. Long double does not need this.
2487 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2490 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2493 V = ConstantFP::get(Context, ID.APFloatVal);
2495 if (V->getType() != Ty)
2496 return Error(ID.Loc, "floating point constant does not have type '" +
2497 getTypeString(Ty) + "'");
2501 if (!Ty->isPointerTy())
2502 return Error(ID.Loc, "null must be a pointer type");
2503 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2505 case ValID::t_Undef:
2506 // FIXME: LabelTy should not be a first-class type.
2507 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2508 return Error(ID.Loc, "invalid type for undef constant");
2509 V = UndefValue::get(Ty);
2511 case ValID::t_EmptyArray:
2512 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2513 return Error(ID.Loc, "invalid empty array initializer");
2514 V = UndefValue::get(Ty);
2517 // FIXME: LabelTy should not be a first-class type.
2518 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2519 return Error(ID.Loc, "invalid type for null constant");
2520 V = Constant::getNullValue(Ty);
2522 case ValID::t_Constant:
2523 if (ID.ConstantVal->getType() != Ty)
2524 return Error(ID.Loc, "constant expression type mismatch");
2528 case ValID::t_ConstantStruct:
2529 case ValID::t_PackedConstantStruct:
2530 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2531 if (ST->getNumElements() != ID.UIntVal)
2532 return Error(ID.Loc,
2533 "initializer with struct type has wrong # elements");
2534 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2535 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2537 // Verify that the elements are compatible with the structtype.
2538 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2539 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2540 return Error(ID.Loc, "element " + Twine(i) +
2541 " of struct initializer doesn't match struct element type");
2543 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2546 return Error(ID.Loc, "constant expression type mismatch");
2551 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2554 return ParseValID(ID, PFS) ||
2555 ConvertValIDToValue(Ty, ID, V, PFS);
2558 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2560 return ParseType(Ty) ||
2561 ParseValue(Ty, V, PFS);
2564 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2565 PerFunctionState &PFS) {
2568 if (ParseTypeAndValue(V, PFS)) return true;
2569 if (!isa<BasicBlock>(V))
2570 return Error(Loc, "expected a basic block");
2571 BB = cast<BasicBlock>(V);
2577 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2578 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2579 /// OptionalAlign OptGC
2580 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2581 // Parse the linkage.
2582 LocTy LinkageLoc = Lex.getLoc();
2585 unsigned Visibility, RetAttrs;
2588 LocTy RetTypeLoc = Lex.getLoc();
2589 if (ParseOptionalLinkage(Linkage) ||
2590 ParseOptionalVisibility(Visibility) ||
2591 ParseOptionalCallingConv(CC) ||
2592 ParseOptionalAttrs(RetAttrs, 1) ||
2593 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2596 // Verify that the linkage is ok.
2597 switch ((GlobalValue::LinkageTypes)Linkage) {
2598 case GlobalValue::ExternalLinkage:
2599 break; // always ok.
2600 case GlobalValue::DLLImportLinkage:
2601 case GlobalValue::ExternalWeakLinkage:
2603 return Error(LinkageLoc, "invalid linkage for function definition");
2605 case GlobalValue::PrivateLinkage:
2606 case GlobalValue::LinkerPrivateLinkage:
2607 case GlobalValue::LinkerPrivateWeakLinkage:
2608 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2609 case GlobalValue::InternalLinkage:
2610 case GlobalValue::AvailableExternallyLinkage:
2611 case GlobalValue::LinkOnceAnyLinkage:
2612 case GlobalValue::LinkOnceODRLinkage:
2613 case GlobalValue::WeakAnyLinkage:
2614 case GlobalValue::WeakODRLinkage:
2615 case GlobalValue::DLLExportLinkage:
2617 return Error(LinkageLoc, "invalid linkage for function declaration");
2619 case GlobalValue::AppendingLinkage:
2620 case GlobalValue::CommonLinkage:
2621 return Error(LinkageLoc, "invalid function linkage type");
2624 if (!FunctionType::isValidReturnType(RetType))
2625 return Error(RetTypeLoc, "invalid function return type");
2627 LocTy NameLoc = Lex.getLoc();
2629 std::string FunctionName;
2630 if (Lex.getKind() == lltok::GlobalVar) {
2631 FunctionName = Lex.getStrVal();
2632 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2633 unsigned NameID = Lex.getUIntVal();
2635 if (NameID != NumberedVals.size())
2636 return TokError("function expected to be numbered '%" +
2637 Twine(NumberedVals.size()) + "'");
2639 return TokError("expected function name");
2644 if (Lex.getKind() != lltok::lparen)
2645 return TokError("expected '(' in function argument list");
2647 SmallVector<ArgInfo, 8> ArgList;
2650 std::string Section;
2654 LocTy UnnamedAddrLoc;
2656 if (ParseArgumentList(ArgList, isVarArg) ||
2657 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2659 ParseOptionalAttrs(FuncAttrs, 2) ||
2660 (EatIfPresent(lltok::kw_section) &&
2661 ParseStringConstant(Section)) ||
2662 ParseOptionalAlignment(Alignment) ||
2663 (EatIfPresent(lltok::kw_gc) &&
2664 ParseStringConstant(GC)))
2667 // If the alignment was parsed as an attribute, move to the alignment field.
2668 if (FuncAttrs & Attribute::Alignment) {
2669 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2670 FuncAttrs &= ~Attribute::Alignment;
2673 // Okay, if we got here, the function is syntactically valid. Convert types
2674 // and do semantic checks.
2675 std::vector<Type*> ParamTypeList;
2676 SmallVector<AttributeWithIndex, 8> Attrs;
2678 if (RetAttrs != Attribute::None)
2679 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2681 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2682 ParamTypeList.push_back(ArgList[i].Ty);
2683 if (ArgList[i].Attrs != Attribute::None)
2684 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2687 if (FuncAttrs != Attribute::None)
2688 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2690 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2692 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2693 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2696 FunctionType::get(RetType, ParamTypeList, isVarArg);
2697 PointerType *PFT = PointerType::getUnqual(FT);
2700 if (!FunctionName.empty()) {
2701 // If this was a definition of a forward reference, remove the definition
2702 // from the forward reference table and fill in the forward ref.
2703 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2704 ForwardRefVals.find(FunctionName);
2705 if (FRVI != ForwardRefVals.end()) {
2706 Fn = M->getFunction(FunctionName);
2707 if (Fn->getType() != PFT)
2708 return Error(FRVI->second.second, "invalid forward reference to "
2709 "function '" + FunctionName + "' with wrong type!");
2711 ForwardRefVals.erase(FRVI);
2712 } else if ((Fn = M->getFunction(FunctionName))) {
2713 // Reject redefinitions.
2714 return Error(NameLoc, "invalid redefinition of function '" +
2715 FunctionName + "'");
2716 } else if (M->getNamedValue(FunctionName)) {
2717 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2721 // If this is a definition of a forward referenced function, make sure the
2723 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2724 = ForwardRefValIDs.find(NumberedVals.size());
2725 if (I != ForwardRefValIDs.end()) {
2726 Fn = cast<Function>(I->second.first);
2727 if (Fn->getType() != PFT)
2728 return Error(NameLoc, "type of definition and forward reference of '@" +
2729 Twine(NumberedVals.size()) + "' disagree");
2730 ForwardRefValIDs.erase(I);
2735 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2736 else // Move the forward-reference to the correct spot in the module.
2737 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2739 if (FunctionName.empty())
2740 NumberedVals.push_back(Fn);
2742 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2743 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2744 Fn->setCallingConv(CC);
2745 Fn->setAttributes(PAL);
2746 Fn->setUnnamedAddr(UnnamedAddr);
2747 Fn->setAlignment(Alignment);
2748 Fn->setSection(Section);
2749 if (!GC.empty()) Fn->setGC(GC.c_str());
2751 // Add all of the arguments we parsed to the function.
2752 Function::arg_iterator ArgIt = Fn->arg_begin();
2753 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2754 // If the argument has a name, insert it into the argument symbol table.
2755 if (ArgList[i].Name.empty()) continue;
2757 // Set the name, if it conflicted, it will be auto-renamed.
2758 ArgIt->setName(ArgList[i].Name);
2760 if (ArgIt->getName() != ArgList[i].Name)
2761 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2762 ArgList[i].Name + "'");
2769 /// ParseFunctionBody
2770 /// ::= '{' BasicBlock+ '}'
2772 bool LLParser::ParseFunctionBody(Function &Fn) {
2773 if (Lex.getKind() != lltok::lbrace)
2774 return TokError("expected '{' in function body");
2775 Lex.Lex(); // eat the {.
2777 int FunctionNumber = -1;
2778 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2780 PerFunctionState PFS(*this, Fn, FunctionNumber);
2782 // We need at least one basic block.
2783 if (Lex.getKind() == lltok::rbrace)
2784 return TokError("function body requires at least one basic block");
2786 while (Lex.getKind() != lltok::rbrace)
2787 if (ParseBasicBlock(PFS)) return true;
2792 // Verify function is ok.
2793 return PFS.FinishFunction();
2797 /// ::= LabelStr? Instruction*
2798 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2799 // If this basic block starts out with a name, remember it.
2801 LocTy NameLoc = Lex.getLoc();
2802 if (Lex.getKind() == lltok::LabelStr) {
2803 Name = Lex.getStrVal();
2807 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2808 if (BB == 0) return true;
2810 std::string NameStr;
2812 // Parse the instructions in this block until we get a terminator.
2814 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2816 // This instruction may have three possibilities for a name: a) none
2817 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2818 LocTy NameLoc = Lex.getLoc();
2822 if (Lex.getKind() == lltok::LocalVarID) {
2823 NameID = Lex.getUIntVal();
2825 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2827 } else if (Lex.getKind() == lltok::LocalVar) {
2828 NameStr = Lex.getStrVal();
2830 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2834 switch (ParseInstruction(Inst, BB, PFS)) {
2835 default: assert(0 && "Unknown ParseInstruction result!");
2836 case InstError: return true;
2838 BB->getInstList().push_back(Inst);
2840 // With a normal result, we check to see if the instruction is followed by
2841 // a comma and metadata.
2842 if (EatIfPresent(lltok::comma))
2843 if (ParseInstructionMetadata(Inst, &PFS))
2846 case InstExtraComma:
2847 BB->getInstList().push_back(Inst);
2849 // If the instruction parser ate an extra comma at the end of it, it
2850 // *must* be followed by metadata.
2851 if (ParseInstructionMetadata(Inst, &PFS))
2856 // Set the name on the instruction.
2857 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2858 } while (!isa<TerminatorInst>(Inst));
2863 //===----------------------------------------------------------------------===//
2864 // Instruction Parsing.
2865 //===----------------------------------------------------------------------===//
2867 /// ParseInstruction - Parse one of the many different instructions.
2869 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2870 PerFunctionState &PFS) {
2871 lltok::Kind Token = Lex.getKind();
2872 if (Token == lltok::Eof)
2873 return TokError("found end of file when expecting more instructions");
2874 LocTy Loc = Lex.getLoc();
2875 unsigned KeywordVal = Lex.getUIntVal();
2876 Lex.Lex(); // Eat the keyword.
2879 default: return Error(Loc, "expected instruction opcode");
2880 // Terminator Instructions.
2881 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2882 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2883 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2884 case lltok::kw_br: return ParseBr(Inst, PFS);
2885 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2886 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2887 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2888 case lltok::kw_resume: return ParseResume(Inst, PFS);
2889 // Binary Operators.
2893 case lltok::kw_shl: {
2894 bool NUW = EatIfPresent(lltok::kw_nuw);
2895 bool NSW = EatIfPresent(lltok::kw_nsw);
2896 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2898 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2900 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2901 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2904 case lltok::kw_fadd:
2905 case lltok::kw_fsub:
2906 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2908 case lltok::kw_sdiv:
2909 case lltok::kw_udiv:
2910 case lltok::kw_lshr:
2911 case lltok::kw_ashr: {
2912 bool Exact = EatIfPresent(lltok::kw_exact);
2914 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2915 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2919 case lltok::kw_urem:
2920 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2921 case lltok::kw_fdiv:
2922 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2925 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2926 case lltok::kw_icmp:
2927 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2929 case lltok::kw_trunc:
2930 case lltok::kw_zext:
2931 case lltok::kw_sext:
2932 case lltok::kw_fptrunc:
2933 case lltok::kw_fpext:
2934 case lltok::kw_bitcast:
2935 case lltok::kw_uitofp:
2936 case lltok::kw_sitofp:
2937 case lltok::kw_fptoui:
2938 case lltok::kw_fptosi:
2939 case lltok::kw_inttoptr:
2940 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2942 case lltok::kw_select: return ParseSelect(Inst, PFS);
2943 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2944 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2945 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2946 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2947 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2948 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
2949 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2950 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2952 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2953 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2954 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2955 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
2956 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
2957 case lltok::kw_fence: return ParseFence(Inst, PFS);
2958 case lltok::kw_volatile:
2959 // For compatibility; canonical location is after load
2960 if (EatIfPresent(lltok::kw_load))
2961 return ParseLoad(Inst, PFS, true);
2962 else if (EatIfPresent(lltok::kw_store))
2963 return ParseStore(Inst, PFS, true);
2965 return TokError("expected 'load' or 'store'");
2966 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2967 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2968 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2972 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2973 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2974 if (Opc == Instruction::FCmp) {
2975 switch (Lex.getKind()) {
2976 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2977 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2978 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2979 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2980 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2981 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2982 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2983 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2984 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2985 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2986 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2987 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2988 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2989 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2990 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2991 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2992 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2995 switch (Lex.getKind()) {
2996 default: TokError("expected icmp predicate (e.g. 'eq')");
2997 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2998 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2999 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3000 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3001 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3002 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3003 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3004 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3005 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3006 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3013 //===----------------------------------------------------------------------===//
3014 // Terminator Instructions.
3015 //===----------------------------------------------------------------------===//
3017 /// ParseRet - Parse a return instruction.
3018 /// ::= 'ret' void (',' !dbg, !1)*
3019 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3020 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3021 PerFunctionState &PFS) {
3022 SMLoc TypeLoc = Lex.getLoc();
3024 if (ParseType(Ty, true /*void allowed*/)) return true;
3026 Type *ResType = PFS.getFunction().getReturnType();
3028 if (Ty->isVoidTy()) {
3029 if (!ResType->isVoidTy())
3030 return Error(TypeLoc, "value doesn't match function result type '" +
3031 getTypeString(ResType) + "'");
3033 Inst = ReturnInst::Create(Context);
3038 if (ParseValue(Ty, RV, PFS)) return true;
3040 if (ResType != RV->getType())
3041 return Error(TypeLoc, "value doesn't match function result type '" +
3042 getTypeString(ResType) + "'");
3044 Inst = ReturnInst::Create(Context, RV);
3050 /// ::= 'br' TypeAndValue
3051 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3052 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3055 BasicBlock *Op1, *Op2;
3056 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3058 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3059 Inst = BranchInst::Create(BB);
3063 if (Op0->getType() != Type::getInt1Ty(Context))
3064 return Error(Loc, "branch condition must have 'i1' type");
3066 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3067 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3068 ParseToken(lltok::comma, "expected ',' after true destination") ||
3069 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3072 Inst = BranchInst::Create(Op1, Op2, Op0);
3078 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3080 /// ::= (TypeAndValue ',' TypeAndValue)*
3081 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3082 LocTy CondLoc, BBLoc;
3084 BasicBlock *DefaultBB;
3085 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3086 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3087 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3088 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3091 if (!Cond->getType()->isIntegerTy())
3092 return Error(CondLoc, "switch condition must have integer type");
3094 // Parse the jump table pairs.
3095 SmallPtrSet<Value*, 32> SeenCases;
3096 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3097 while (Lex.getKind() != lltok::rsquare) {
3101 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3102 ParseToken(lltok::comma, "expected ',' after case value") ||
3103 ParseTypeAndBasicBlock(DestBB, PFS))
3106 if (!SeenCases.insert(Constant))
3107 return Error(CondLoc, "duplicate case value in switch");
3108 if (!isa<ConstantInt>(Constant))
3109 return Error(CondLoc, "case value is not a constant integer");
3111 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3114 Lex.Lex(); // Eat the ']'.
3116 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3117 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3118 SI->addCase(Table[i].first, Table[i].second);
3125 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3126 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3129 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3130 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3131 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3134 if (!Address->getType()->isPointerTy())
3135 return Error(AddrLoc, "indirectbr address must have pointer type");
3137 // Parse the destination list.
3138 SmallVector<BasicBlock*, 16> DestList;
3140 if (Lex.getKind() != lltok::rsquare) {
3142 if (ParseTypeAndBasicBlock(DestBB, PFS))
3144 DestList.push_back(DestBB);
3146 while (EatIfPresent(lltok::comma)) {
3147 if (ParseTypeAndBasicBlock(DestBB, PFS))
3149 DestList.push_back(DestBB);
3153 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3156 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3157 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3158 IBI->addDestination(DestList[i]);
3165 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3166 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3167 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3168 LocTy CallLoc = Lex.getLoc();
3169 unsigned RetAttrs, FnAttrs;
3174 SmallVector<ParamInfo, 16> ArgList;
3176 BasicBlock *NormalBB, *UnwindBB;
3177 if (ParseOptionalCallingConv(CC) ||
3178 ParseOptionalAttrs(RetAttrs, 1) ||
3179 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3180 ParseValID(CalleeID) ||
3181 ParseParameterList(ArgList, PFS) ||
3182 ParseOptionalAttrs(FnAttrs, 2) ||
3183 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3184 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3185 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3186 ParseTypeAndBasicBlock(UnwindBB, PFS))
3189 // If RetType is a non-function pointer type, then this is the short syntax
3190 // for the call, which means that RetType is just the return type. Infer the
3191 // rest of the function argument types from the arguments that are present.
3192 PointerType *PFTy = 0;
3193 FunctionType *Ty = 0;
3194 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3195 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3196 // Pull out the types of all of the arguments...
3197 std::vector<Type*> ParamTypes;
3198 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3199 ParamTypes.push_back(ArgList[i].V->getType());
3201 if (!FunctionType::isValidReturnType(RetType))
3202 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3204 Ty = FunctionType::get(RetType, ParamTypes, false);
3205 PFTy = PointerType::getUnqual(Ty);
3208 // Look up the callee.
3210 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3212 // Set up the Attributes for the function.
3213 SmallVector<AttributeWithIndex, 8> Attrs;
3214 if (RetAttrs != Attribute::None)
3215 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3217 SmallVector<Value*, 8> Args;
3219 // Loop through FunctionType's arguments and ensure they are specified
3220 // correctly. Also, gather any parameter attributes.
3221 FunctionType::param_iterator I = Ty->param_begin();
3222 FunctionType::param_iterator E = Ty->param_end();
3223 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3224 Type *ExpectedTy = 0;
3227 } else if (!Ty->isVarArg()) {
3228 return Error(ArgList[i].Loc, "too many arguments specified");
3231 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3232 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3233 getTypeString(ExpectedTy) + "'");
3234 Args.push_back(ArgList[i].V);
3235 if (ArgList[i].Attrs != Attribute::None)
3236 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3240 return Error(CallLoc, "not enough parameters specified for call");
3242 if (FnAttrs != Attribute::None)
3243 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3245 // Finish off the Attributes and check them
3246 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3248 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3249 II->setCallingConv(CC);
3250 II->setAttributes(PAL);
3256 /// ::= 'resume' TypeAndValue
3257 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3258 Value *Exn; LocTy ExnLoc;
3259 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3262 ResumeInst *RI = ResumeInst::Create(Exn);
3267 //===----------------------------------------------------------------------===//
3268 // Binary Operators.
3269 //===----------------------------------------------------------------------===//
3272 /// ::= ArithmeticOps TypeAndValue ',' Value
3274 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3275 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3276 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3277 unsigned Opc, unsigned OperandType) {
3278 LocTy Loc; Value *LHS, *RHS;
3279 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3280 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3281 ParseValue(LHS->getType(), RHS, PFS))
3285 switch (OperandType) {
3286 default: llvm_unreachable("Unknown operand type!");
3287 case 0: // int or FP.
3288 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3289 LHS->getType()->isFPOrFPVectorTy();
3291 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3292 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3296 return Error(Loc, "invalid operand type for instruction");
3298 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3303 /// ::= ArithmeticOps TypeAndValue ',' Value {
3304 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3306 LocTy Loc; Value *LHS, *RHS;
3307 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3308 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3309 ParseValue(LHS->getType(), RHS, PFS))
3312 if (!LHS->getType()->isIntOrIntVectorTy())
3313 return Error(Loc,"instruction requires integer or integer vector operands");
3315 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3321 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3322 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3323 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3325 // Parse the integer/fp comparison predicate.
3329 if (ParseCmpPredicate(Pred, Opc) ||
3330 ParseTypeAndValue(LHS, Loc, PFS) ||
3331 ParseToken(lltok::comma, "expected ',' after compare value") ||
3332 ParseValue(LHS->getType(), RHS, PFS))
3335 if (Opc == Instruction::FCmp) {
3336 if (!LHS->getType()->isFPOrFPVectorTy())
3337 return Error(Loc, "fcmp requires floating point operands");
3338 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3340 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3341 if (!LHS->getType()->isIntOrIntVectorTy() &&
3342 !LHS->getType()->isPointerTy())
3343 return Error(Loc, "icmp requires integer operands");
3344 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3349 //===----------------------------------------------------------------------===//
3350 // Other Instructions.
3351 //===----------------------------------------------------------------------===//
3355 /// ::= CastOpc TypeAndValue 'to' Type
3356 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3361 if (ParseTypeAndValue(Op, Loc, PFS) ||
3362 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3366 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3367 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3368 return Error(Loc, "invalid cast opcode for cast from '" +
3369 getTypeString(Op->getType()) + "' to '" +
3370 getTypeString(DestTy) + "'");
3372 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3377 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3378 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3380 Value *Op0, *Op1, *Op2;
3381 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3382 ParseToken(lltok::comma, "expected ',' after select condition") ||
3383 ParseTypeAndValue(Op1, PFS) ||
3384 ParseToken(lltok::comma, "expected ',' after select value") ||
3385 ParseTypeAndValue(Op2, PFS))
3388 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3389 return Error(Loc, Reason);
3391 Inst = SelectInst::Create(Op0, Op1, Op2);
3396 /// ::= 'va_arg' TypeAndValue ',' Type
3397 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3401 if (ParseTypeAndValue(Op, PFS) ||
3402 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3403 ParseType(EltTy, TypeLoc))
3406 if (!EltTy->isFirstClassType())
3407 return Error(TypeLoc, "va_arg requires operand with first class type");
3409 Inst = new VAArgInst(Op, EltTy);
3413 /// ParseExtractElement
3414 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3415 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3418 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3419 ParseToken(lltok::comma, "expected ',' after extract value") ||
3420 ParseTypeAndValue(Op1, PFS))
3423 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3424 return Error(Loc, "invalid extractelement operands");
3426 Inst = ExtractElementInst::Create(Op0, Op1);
3430 /// ParseInsertElement
3431 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3432 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3434 Value *Op0, *Op1, *Op2;
3435 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3436 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3437 ParseTypeAndValue(Op1, PFS) ||
3438 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3439 ParseTypeAndValue(Op2, PFS))
3442 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3443 return Error(Loc, "invalid insertelement operands");
3445 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3449 /// ParseShuffleVector
3450 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3451 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3453 Value *Op0, *Op1, *Op2;
3454 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3455 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3456 ParseTypeAndValue(Op1, PFS) ||
3457 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3458 ParseTypeAndValue(Op2, PFS))
3461 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3462 return Error(Loc, "invalid extractelement operands");
3464 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3469 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3470 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3471 Type *Ty = 0; LocTy TypeLoc;
3474 if (ParseType(Ty, TypeLoc) ||
3475 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3476 ParseValue(Ty, Op0, PFS) ||
3477 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3478 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3479 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3482 bool AteExtraComma = false;
3483 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3485 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3487 if (!EatIfPresent(lltok::comma))
3490 if (Lex.getKind() == lltok::MetadataVar) {
3491 AteExtraComma = true;
3495 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3496 ParseValue(Ty, Op0, PFS) ||
3497 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3498 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3499 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3503 if (!Ty->isFirstClassType())
3504 return Error(TypeLoc, "phi node must have first class type");
3506 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3507 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3508 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3510 return AteExtraComma ? InstExtraComma : InstNormal;
3514 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3516 /// ::= 'catch' TypeAndValue
3518 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3519 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3520 Type *Ty = 0; LocTy TyLoc;
3521 Value *PersFn; LocTy PersFnLoc;
3522 LocTy LPLoc = Lex.getLoc();
3524 if (ParseType(Ty, TyLoc) ||
3525 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3526 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3529 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3530 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3532 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3533 LandingPadInst::ClauseType CT;
3534 if (EatIfPresent(lltok::kw_catch))
3535 CT = LandingPadInst::Catch;
3536 else if (EatIfPresent(lltok::kw_filter))
3537 CT = LandingPadInst::Filter;
3539 return TokError("expected 'catch' or 'filter' clause type");
3541 Value *V; LocTy VLoc;
3542 if (ParseTypeAndValue(V, VLoc, PFS)) {
3547 // A 'catch' type expects a non-array constant. A filter clause expects an
3549 if (CT == LandingPadInst::Catch) {
3550 if (isa<ArrayType>(V->getType()))
3551 Error(VLoc, "'catch' clause has an invalid type");
3553 if (!isa<ArrayType>(V->getType()))
3554 Error(VLoc, "'filter' clause has an invalid type");
3565 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3566 /// ParameterList OptionalAttrs
3567 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3569 unsigned RetAttrs, FnAttrs;
3574 SmallVector<ParamInfo, 16> ArgList;
3575 LocTy CallLoc = Lex.getLoc();
3577 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3578 ParseOptionalCallingConv(CC) ||
3579 ParseOptionalAttrs(RetAttrs, 1) ||
3580 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3581 ParseValID(CalleeID) ||
3582 ParseParameterList(ArgList, PFS) ||
3583 ParseOptionalAttrs(FnAttrs, 2))
3586 // If RetType is a non-function pointer type, then this is the short syntax
3587 // for the call, which means that RetType is just the return type. Infer the
3588 // rest of the function argument types from the arguments that are present.
3589 PointerType *PFTy = 0;
3590 FunctionType *Ty = 0;
3591 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3592 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3593 // Pull out the types of all of the arguments...
3594 std::vector<Type*> ParamTypes;
3595 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3596 ParamTypes.push_back(ArgList[i].V->getType());
3598 if (!FunctionType::isValidReturnType(RetType))
3599 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3601 Ty = FunctionType::get(RetType, ParamTypes, false);
3602 PFTy = PointerType::getUnqual(Ty);
3605 // Look up the callee.
3607 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3609 // Set up the Attributes for the function.
3610 SmallVector<AttributeWithIndex, 8> Attrs;
3611 if (RetAttrs != Attribute::None)
3612 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3614 SmallVector<Value*, 8> Args;
3616 // Loop through FunctionType's arguments and ensure they are specified
3617 // correctly. Also, gather any parameter attributes.
3618 FunctionType::param_iterator I = Ty->param_begin();
3619 FunctionType::param_iterator E = Ty->param_end();
3620 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3621 Type *ExpectedTy = 0;
3624 } else if (!Ty->isVarArg()) {
3625 return Error(ArgList[i].Loc, "too many arguments specified");
3628 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3629 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3630 getTypeString(ExpectedTy) + "'");
3631 Args.push_back(ArgList[i].V);
3632 if (ArgList[i].Attrs != Attribute::None)
3633 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3637 return Error(CallLoc, "not enough parameters specified for call");
3639 if (FnAttrs != Attribute::None)
3640 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3642 // Finish off the Attributes and check them
3643 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3645 CallInst *CI = CallInst::Create(Callee, Args);
3646 CI->setTailCall(isTail);
3647 CI->setCallingConv(CC);
3648 CI->setAttributes(PAL);
3653 //===----------------------------------------------------------------------===//
3654 // Memory Instructions.
3655 //===----------------------------------------------------------------------===//
3658 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3659 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3662 unsigned Alignment = 0;
3664 if (ParseType(Ty)) return true;
3666 bool AteExtraComma = false;
3667 if (EatIfPresent(lltok::comma)) {
3668 if (Lex.getKind() == lltok::kw_align) {
3669 if (ParseOptionalAlignment(Alignment)) return true;
3670 } else if (Lex.getKind() == lltok::MetadataVar) {
3671 AteExtraComma = true;
3673 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3674 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3679 if (Size && !Size->getType()->isIntegerTy())
3680 return Error(SizeLoc, "element count must have integer type");
3682 Inst = new AllocaInst(Ty, Size, Alignment);
3683 return AteExtraComma ? InstExtraComma : InstNormal;
3687 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3688 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3689 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3691 /// ::= 'volatile' 'load' TypeAndValue (',' 'align' i32)?
3692 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3694 Value *Val; LocTy Loc;
3695 unsigned Alignment = 0;
3696 bool AteExtraComma = false;
3697 bool isAtomic = false;
3698 AtomicOrdering Ordering = NotAtomic;
3699 SynchronizationScope Scope = CrossThread;
3701 if (Lex.getKind() == lltok::kw_atomic) {
3703 return TokError("mixing atomic with old volatile placement");
3708 if (Lex.getKind() == lltok::kw_volatile) {
3710 return TokError("duplicate volatile before and after store");
3715 if (ParseTypeAndValue(Val, Loc, PFS) ||
3716 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3717 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3720 if (!Val->getType()->isPointerTy() ||
3721 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3722 return Error(Loc, "load operand must be a pointer to a first class type");
3723 if (isAtomic && !Alignment)
3724 return Error(Loc, "atomic load must have explicit non-zero alignment");
3725 if (Ordering == Release || Ordering == AcquireRelease)
3726 return Error(Loc, "atomic load cannot use Release ordering");
3728 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
3729 return AteExtraComma ? InstExtraComma : InstNormal;
3734 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3735 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
3736 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3738 /// ::= 'volatile' 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3739 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3741 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3742 unsigned Alignment = 0;
3743 bool AteExtraComma = false;
3744 bool isAtomic = false;
3745 AtomicOrdering Ordering = NotAtomic;
3746 SynchronizationScope Scope = CrossThread;
3748 if (Lex.getKind() == lltok::kw_atomic) {
3750 return TokError("mixing atomic with old volatile placement");
3755 if (Lex.getKind() == lltok::kw_volatile) {
3757 return TokError("duplicate volatile before and after store");
3762 if (ParseTypeAndValue(Val, Loc, PFS) ||
3763 ParseToken(lltok::comma, "expected ',' after store operand") ||
3764 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3765 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3766 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3769 if (!Ptr->getType()->isPointerTy())
3770 return Error(PtrLoc, "store operand must be a pointer");
3771 if (!Val->getType()->isFirstClassType())
3772 return Error(Loc, "store operand must be a first class value");
3773 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3774 return Error(Loc, "stored value and pointer type do not match");
3775 if (isAtomic && !Alignment)
3776 return Error(Loc, "atomic store must have explicit non-zero alignment");
3777 if (Ordering == Acquire || Ordering == AcquireRelease)
3778 return Error(Loc, "atomic store cannot use Acquire ordering");
3780 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
3781 return AteExtraComma ? InstExtraComma : InstNormal;
3785 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3786 /// 'singlethread'? AtomicOrdering
3787 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
3788 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3789 bool AteExtraComma = false;
3790 AtomicOrdering Ordering = NotAtomic;
3791 SynchronizationScope Scope = CrossThread;
3792 bool isVolatile = false;
3794 if (EatIfPresent(lltok::kw_volatile))
3797 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3798 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3799 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3800 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3801 ParseTypeAndValue(New, NewLoc, PFS) ||
3802 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3805 if (Ordering == Unordered)
3806 return TokError("cmpxchg cannot be unordered");
3807 if (!Ptr->getType()->isPointerTy())
3808 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3809 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3810 return Error(CmpLoc, "compare value and pointer type do not match");
3811 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3812 return Error(NewLoc, "new value and pointer type do not match");
3813 if (!New->getType()->isIntegerTy())
3814 return Error(NewLoc, "cmpxchg operand must be an integer");
3815 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3816 if (Size < 8 || (Size & (Size - 1)))
3817 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3820 AtomicCmpXchgInst *CXI =
3821 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3822 CXI->setVolatile(isVolatile);
3824 return AteExtraComma ? InstExtraComma : InstNormal;
3828 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3829 /// 'singlethread'? AtomicOrdering
3830 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
3831 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3832 bool AteExtraComma = false;
3833 AtomicOrdering Ordering = NotAtomic;
3834 SynchronizationScope Scope = CrossThread;
3835 bool isVolatile = false;
3836 AtomicRMWInst::BinOp Operation;
3838 if (EatIfPresent(lltok::kw_volatile))
3841 switch (Lex.getKind()) {
3842 default: return TokError("expected binary operation in atomicrmw");
3843 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3844 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3845 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3846 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3847 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3848 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3849 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3850 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3851 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3852 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3853 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3855 Lex.Lex(); // Eat the operation.
3857 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3858 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3859 ParseTypeAndValue(Val, ValLoc, PFS) ||
3860 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3863 if (Ordering == Unordered)
3864 return TokError("atomicrmw cannot be unordered");
3865 if (!Ptr->getType()->isPointerTy())
3866 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3867 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3868 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3869 if (!Val->getType()->isIntegerTy())
3870 return Error(ValLoc, "atomicrmw operand must be an integer");
3871 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3872 if (Size < 8 || (Size & (Size - 1)))
3873 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3876 AtomicRMWInst *RMWI =
3877 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3878 RMWI->setVolatile(isVolatile);
3880 return AteExtraComma ? InstExtraComma : InstNormal;
3884 /// ::= 'fence' 'singlethread'? AtomicOrdering
3885 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3886 AtomicOrdering Ordering = NotAtomic;
3887 SynchronizationScope Scope = CrossThread;
3888 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3891 if (Ordering == Unordered)
3892 return TokError("fence cannot be unordered");
3893 if (Ordering == Monotonic)
3894 return TokError("fence cannot be monotonic");
3896 Inst = new FenceInst(Context, Ordering, Scope);
3900 /// ParseGetElementPtr
3901 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3902 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3903 Value *Ptr, *Val; LocTy Loc, EltLoc;
3905 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3907 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3909 if (!Ptr->getType()->isPointerTy())
3910 return Error(Loc, "base of getelementptr must be a pointer");
3912 SmallVector<Value*, 16> Indices;
3913 bool AteExtraComma = false;
3914 while (EatIfPresent(lltok::comma)) {
3915 if (Lex.getKind() == lltok::MetadataVar) {
3916 AteExtraComma = true;
3919 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3920 if (!Val->getType()->isIntegerTy())
3921 return Error(EltLoc, "getelementptr index must be an integer");
3922 Indices.push_back(Val);
3925 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
3926 return Error(Loc, "invalid getelementptr indices");
3927 Inst = GetElementPtrInst::Create(Ptr, Indices);
3929 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3930 return AteExtraComma ? InstExtraComma : InstNormal;
3933 /// ParseExtractValue
3934 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3935 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3936 Value *Val; LocTy Loc;
3937 SmallVector<unsigned, 4> Indices;
3939 if (ParseTypeAndValue(Val, Loc, PFS) ||
3940 ParseIndexList(Indices, AteExtraComma))
3943 if (!Val->getType()->isAggregateType())
3944 return Error(Loc, "extractvalue operand must be aggregate type");
3946 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3947 return Error(Loc, "invalid indices for extractvalue");
3948 Inst = ExtractValueInst::Create(Val, Indices);
3949 return AteExtraComma ? InstExtraComma : InstNormal;
3952 /// ParseInsertValue
3953 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3954 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3955 Value *Val0, *Val1; LocTy Loc0, Loc1;
3956 SmallVector<unsigned, 4> Indices;
3958 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3959 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3960 ParseTypeAndValue(Val1, Loc1, PFS) ||
3961 ParseIndexList(Indices, AteExtraComma))
3964 if (!Val0->getType()->isAggregateType())
3965 return Error(Loc0, "insertvalue operand must be aggregate type");
3967 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
3968 return Error(Loc0, "invalid indices for insertvalue");
3969 Inst = InsertValueInst::Create(Val0, Val1, Indices);
3970 return AteExtraComma ? InstExtraComma : InstNormal;
3973 //===----------------------------------------------------------------------===//
3974 // Embedded metadata.
3975 //===----------------------------------------------------------------------===//
3977 /// ParseMDNodeVector
3978 /// ::= Element (',' Element)*
3980 /// ::= 'null' | TypeAndValue
3981 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3982 PerFunctionState *PFS) {
3983 // Check for an empty list.
3984 if (Lex.getKind() == lltok::rbrace)
3988 // Null is a special case since it is typeless.
3989 if (EatIfPresent(lltok::kw_null)) {
3995 if (ParseTypeAndValue(V, PFS)) return true;
3997 } while (EatIfPresent(lltok::comma));