1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
30 /// Run: module ::= toplevelentity*
31 bool LLParser::Run() {
35 return ParseTopLevelEntities() ||
36 ValidateEndOfModule();
39 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
41 bool LLParser::ValidateEndOfModule() {
42 // Handle any instruction metadata forward references.
43 if (!ForwardRefInstMetadata.empty()) {
44 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
45 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
47 Instruction *Inst = I->first;
48 const std::vector<MDRef> &MDList = I->second;
50 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
51 unsigned SlotNo = MDList[i].MDSlot;
53 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
54 return Error(MDList[i].Loc, "use of undefined metadata '!" +
55 utostr(SlotNo) + "'");
56 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
59 ForwardRefInstMetadata.clear();
63 // Update auto-upgraded malloc calls to "malloc".
64 // FIXME: Remove in LLVM 3.0.
66 MallocF->setName("malloc");
67 // If setName() does not set the name to "malloc", then there is already a
68 // declaration of "malloc". In that case, iterate over all calls to MallocF
69 // and get them to call the declared "malloc" instead.
70 if (MallocF->getName() != "malloc") {
71 Constant *RealMallocF = M->getFunction("malloc");
72 if (RealMallocF->getType() != MallocF->getType())
73 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
74 MallocF->replaceAllUsesWith(RealMallocF);
75 MallocF->eraseFromParent();
81 // If there are entries in ForwardRefBlockAddresses at this point, they are
82 // references after the function was defined. Resolve those now.
83 while (!ForwardRefBlockAddresses.empty()) {
84 // Okay, we are referencing an already-parsed function, resolve them now.
86 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
87 if (Fn.Kind == ValID::t_GlobalName)
88 TheFn = M->getFunction(Fn.StrVal);
89 else if (Fn.UIntVal < NumberedVals.size())
90 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
93 return Error(Fn.Loc, "unknown function referenced by blockaddress");
95 // Resolve all these references.
96 if (ResolveForwardRefBlockAddresses(TheFn,
97 ForwardRefBlockAddresses.begin()->second,
101 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
105 if (!ForwardRefTypes.empty())
106 return Error(ForwardRefTypes.begin()->second.second,
107 "use of undefined type named '" +
108 ForwardRefTypes.begin()->first + "'");
109 if (!ForwardRefTypeIDs.empty())
110 return Error(ForwardRefTypeIDs.begin()->second.second,
111 "use of undefined type '%" +
112 utostr(ForwardRefTypeIDs.begin()->first) + "'");
114 if (!ForwardRefVals.empty())
115 return Error(ForwardRefVals.begin()->second.second,
116 "use of undefined value '@" + ForwardRefVals.begin()->first +
119 if (!ForwardRefValIDs.empty())
120 return Error(ForwardRefValIDs.begin()->second.second,
121 "use of undefined value '@" +
122 utostr(ForwardRefValIDs.begin()->first) + "'");
124 if (!ForwardRefMDNodes.empty())
125 return Error(ForwardRefMDNodes.begin()->second.second,
126 "use of undefined metadata '!" +
127 utostr(ForwardRefMDNodes.begin()->first) + "'");
130 // Look for intrinsic functions and CallInst that need to be upgraded
131 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
132 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
134 // Check debug info intrinsics.
135 CheckDebugInfoIntrinsics(M);
139 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
140 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
141 PerFunctionState *PFS) {
142 // Loop over all the references, resolving them.
143 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
146 if (Refs[i].first.Kind == ValID::t_LocalName)
147 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
149 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
150 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
151 return Error(Refs[i].first.Loc,
152 "cannot take address of numeric label after the function is defined");
154 Res = dyn_cast_or_null<BasicBlock>(
155 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
159 return Error(Refs[i].first.Loc,
160 "referenced value is not a basic block");
162 // Get the BlockAddress for this and update references to use it.
163 BlockAddress *BA = BlockAddress::get(TheFn, Res);
164 Refs[i].second->replaceAllUsesWith(BA);
165 Refs[i].second->eraseFromParent();
171 //===----------------------------------------------------------------------===//
172 // Top-Level Entities
173 //===----------------------------------------------------------------------===//
175 bool LLParser::ParseTopLevelEntities() {
177 switch (Lex.getKind()) {
178 default: return TokError("expected top-level entity");
179 case lltok::Eof: return false;
180 //case lltok::kw_define:
181 case lltok::kw_declare: if (ParseDeclare()) return true; break;
182 case lltok::kw_define: if (ParseDefine()) return true; break;
183 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
184 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
185 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
186 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
187 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
188 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
189 case lltok::LocalVar: if (ParseNamedType()) return true; break;
190 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
191 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
192 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
193 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
195 // The Global variable production with no name can have many different
196 // optional leading prefixes, the production is:
197 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
198 // OptionalAddrSpace ('constant'|'global') ...
199 case lltok::kw_private: // OptionalLinkage
200 case lltok::kw_linker_private: // OptionalLinkage
201 case lltok::kw_linker_private_weak: // OptionalLinkage
202 case lltok::kw_internal: // OptionalLinkage
203 case lltok::kw_weak: // OptionalLinkage
204 case lltok::kw_weak_odr: // OptionalLinkage
205 case lltok::kw_linkonce: // OptionalLinkage
206 case lltok::kw_linkonce_odr: // OptionalLinkage
207 case lltok::kw_appending: // OptionalLinkage
208 case lltok::kw_dllexport: // OptionalLinkage
209 case lltok::kw_common: // OptionalLinkage
210 case lltok::kw_dllimport: // OptionalLinkage
211 case lltok::kw_extern_weak: // OptionalLinkage
212 case lltok::kw_external: { // OptionalLinkage
213 unsigned Linkage, Visibility;
214 if (ParseOptionalLinkage(Linkage) ||
215 ParseOptionalVisibility(Visibility) ||
216 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
220 case lltok::kw_default: // OptionalVisibility
221 case lltok::kw_hidden: // OptionalVisibility
222 case lltok::kw_protected: { // OptionalVisibility
224 if (ParseOptionalVisibility(Visibility) ||
225 ParseGlobal("", SMLoc(), 0, false, Visibility))
230 case lltok::kw_thread_local: // OptionalThreadLocal
231 case lltok::kw_addrspace: // OptionalAddrSpace
232 case lltok::kw_constant: // GlobalType
233 case lltok::kw_global: // GlobalType
234 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
242 /// ::= 'module' 'asm' STRINGCONSTANT
243 bool LLParser::ParseModuleAsm() {
244 assert(Lex.getKind() == lltok::kw_module);
248 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
249 ParseStringConstant(AsmStr)) return true;
251 const std::string &AsmSoFar = M->getModuleInlineAsm();
252 if (AsmSoFar.empty())
253 M->setModuleInlineAsm(AsmStr);
255 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
260 /// ::= 'target' 'triple' '=' STRINGCONSTANT
261 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
262 bool LLParser::ParseTargetDefinition() {
263 assert(Lex.getKind() == lltok::kw_target);
266 default: return TokError("unknown target property");
267 case lltok::kw_triple:
269 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
270 ParseStringConstant(Str))
272 M->setTargetTriple(Str);
274 case lltok::kw_datalayout:
276 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
277 ParseStringConstant(Str))
279 M->setDataLayout(Str);
285 /// ::= 'deplibs' '=' '[' ']'
286 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
287 bool LLParser::ParseDepLibs() {
288 assert(Lex.getKind() == lltok::kw_deplibs);
290 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
291 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
294 if (EatIfPresent(lltok::rsquare))
298 if (ParseStringConstant(Str)) return true;
301 while (EatIfPresent(lltok::comma)) {
302 if (ParseStringConstant(Str)) return true;
306 return ParseToken(lltok::rsquare, "expected ']' at end of list");
309 /// ParseUnnamedType:
311 /// ::= LocalVarID '=' 'type' type
312 bool LLParser::ParseUnnamedType() {
313 unsigned TypeID = NumberedTypes.size();
315 // Handle the LocalVarID form.
316 if (Lex.getKind() == lltok::LocalVarID) {
317 if (Lex.getUIntVal() != TypeID)
318 return Error(Lex.getLoc(), "type expected to be numbered '%" +
319 utostr(TypeID) + "'");
320 Lex.Lex(); // eat LocalVarID;
322 if (ParseToken(lltok::equal, "expected '=' after name"))
326 LocTy TypeLoc = Lex.getLoc();
327 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
329 PATypeHolder Ty(Type::getVoidTy(Context));
330 if (ParseType(Ty)) return true;
332 // See if this type was previously referenced.
333 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
334 FI = ForwardRefTypeIDs.find(TypeID);
335 if (FI != ForwardRefTypeIDs.end()) {
336 if (FI->second.first.get() == Ty)
337 return Error(TypeLoc, "self referential type is invalid");
339 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
340 Ty = FI->second.first.get();
341 ForwardRefTypeIDs.erase(FI);
344 NumberedTypes.push_back(Ty);
350 /// ::= LocalVar '=' 'type' type
351 bool LLParser::ParseNamedType() {
352 std::string Name = Lex.getStrVal();
353 LocTy NameLoc = Lex.getLoc();
354 Lex.Lex(); // eat LocalVar.
356 PATypeHolder Ty(Type::getVoidTy(Context));
358 if (ParseToken(lltok::equal, "expected '=' after name") ||
359 ParseToken(lltok::kw_type, "expected 'type' after name") ||
363 // Set the type name, checking for conflicts as we do so.
364 bool AlreadyExists = M->addTypeName(Name, Ty);
365 if (!AlreadyExists) return false;
367 // See if this type is a forward reference. We need to eagerly resolve
368 // types to allow recursive type redefinitions below.
369 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
370 FI = ForwardRefTypes.find(Name);
371 if (FI != ForwardRefTypes.end()) {
372 if (FI->second.first.get() == Ty)
373 return Error(NameLoc, "self referential type is invalid");
375 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
376 Ty = FI->second.first.get();
377 ForwardRefTypes.erase(FI);
380 // Inserting a name that is already defined, get the existing name.
381 const Type *Existing = M->getTypeByName(Name);
382 assert(Existing && "Conflict but no matching type?!");
384 // Otherwise, this is an attempt to redefine a type. That's okay if
385 // the redefinition is identical to the original.
386 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
387 if (Existing == Ty) return false;
389 // Any other kind of (non-equivalent) redefinition is an error.
390 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
391 Ty->getDescription() + "'");
396 /// ::= 'declare' FunctionHeader
397 bool LLParser::ParseDeclare() {
398 assert(Lex.getKind() == lltok::kw_declare);
402 return ParseFunctionHeader(F, false);
406 /// ::= 'define' FunctionHeader '{' ...
407 bool LLParser::ParseDefine() {
408 assert(Lex.getKind() == lltok::kw_define);
412 return ParseFunctionHeader(F, true) ||
413 ParseFunctionBody(*F);
419 bool LLParser::ParseGlobalType(bool &IsConstant) {
420 if (Lex.getKind() == lltok::kw_constant)
422 else if (Lex.getKind() == lltok::kw_global)
426 return TokError("expected 'global' or 'constant'");
432 /// ParseUnnamedGlobal:
433 /// OptionalVisibility ALIAS ...
434 /// OptionalLinkage OptionalVisibility ... -> global variable
435 /// GlobalID '=' OptionalVisibility ALIAS ...
436 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
437 bool LLParser::ParseUnnamedGlobal() {
438 unsigned VarID = NumberedVals.size();
440 LocTy NameLoc = Lex.getLoc();
442 // Handle the GlobalID form.
443 if (Lex.getKind() == lltok::GlobalID) {
444 if (Lex.getUIntVal() != VarID)
445 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
446 utostr(VarID) + "'");
447 Lex.Lex(); // eat GlobalID;
449 if (ParseToken(lltok::equal, "expected '=' after name"))
454 unsigned Linkage, Visibility;
455 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
456 ParseOptionalVisibility(Visibility))
459 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
460 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
461 return ParseAlias(Name, NameLoc, Visibility);
464 /// ParseNamedGlobal:
465 /// GlobalVar '=' OptionalVisibility ALIAS ...
466 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
467 bool LLParser::ParseNamedGlobal() {
468 assert(Lex.getKind() == lltok::GlobalVar);
469 LocTy NameLoc = Lex.getLoc();
470 std::string Name = Lex.getStrVal();
474 unsigned Linkage, Visibility;
475 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
476 ParseOptionalLinkage(Linkage, HasLinkage) ||
477 ParseOptionalVisibility(Visibility))
480 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
481 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
482 return ParseAlias(Name, NameLoc, Visibility);
486 // ::= '!' STRINGCONSTANT
487 bool LLParser::ParseMDString(MDString *&Result) {
489 if (ParseStringConstant(Str)) return true;
490 Result = MDString::get(Context, Str);
495 // ::= '!' MDNodeNumber
497 /// This version of ParseMDNodeID returns the slot number and null in the case
498 /// of a forward reference.
499 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
500 // !{ ..., !42, ... }
501 if (ParseUInt32(SlotNo)) return true;
503 // Check existing MDNode.
504 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
505 Result = NumberedMetadata[SlotNo];
511 bool LLParser::ParseMDNodeID(MDNode *&Result) {
512 // !{ ..., !42, ... }
514 if (ParseMDNodeID(Result, MID)) return true;
516 // If not a forward reference, just return it now.
517 if (Result) return false;
519 // Otherwise, create MDNode forward reference.
521 // FIXME: This is not unique enough!
522 std::string FwdRefName = "llvm.mdnode.fwdref." + utostr(MID);
523 Value *V = MDString::get(Context, FwdRefName);
524 MDNode *FwdNode = MDNode::get(Context, &V, 1);
525 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
527 if (NumberedMetadata.size() <= MID)
528 NumberedMetadata.resize(MID+1);
529 NumberedMetadata[MID] = FwdNode;
534 /// ParseNamedMetadata:
535 /// !foo = !{ !1, !2 }
536 bool LLParser::ParseNamedMetadata() {
537 assert(Lex.getKind() == lltok::MetadataVar);
538 std::string Name = Lex.getStrVal();
541 if (ParseToken(lltok::equal, "expected '=' here") ||
542 ParseToken(lltok::exclaim, "Expected '!' here") ||
543 ParseToken(lltok::lbrace, "Expected '{' here"))
546 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
547 if (Lex.getKind() != lltok::rbrace)
549 if (ParseToken(lltok::exclaim, "Expected '!' here"))
553 if (ParseMDNodeID(N)) return true;
555 } while (EatIfPresent(lltok::comma));
557 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
563 /// ParseStandaloneMetadata:
565 bool LLParser::ParseStandaloneMetadata() {
566 assert(Lex.getKind() == lltok::exclaim);
568 unsigned MetadataID = 0;
571 PATypeHolder Ty(Type::getVoidTy(Context));
572 SmallVector<Value *, 16> Elts;
573 if (ParseUInt32(MetadataID) ||
574 ParseToken(lltok::equal, "expected '=' here") ||
575 ParseType(Ty, TyLoc) ||
576 ParseToken(lltok::exclaim, "Expected '!' here") ||
577 ParseToken(lltok::lbrace, "Expected '{' here") ||
578 ParseMDNodeVector(Elts, NULL) ||
579 ParseToken(lltok::rbrace, "expected end of metadata node"))
582 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
584 // See if this was forward referenced, if so, handle it.
585 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
586 FI = ForwardRefMDNodes.find(MetadataID);
587 if (FI != ForwardRefMDNodes.end()) {
588 FI->second.first->replaceAllUsesWith(Init);
589 ForwardRefMDNodes.erase(FI);
591 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
593 if (MetadataID >= NumberedMetadata.size())
594 NumberedMetadata.resize(MetadataID+1);
596 if (NumberedMetadata[MetadataID] != 0)
597 return TokError("Metadata id is already used");
598 NumberedMetadata[MetadataID] = Init;
605 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
608 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
609 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
611 /// Everything through visibility has already been parsed.
613 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
614 unsigned Visibility) {
615 assert(Lex.getKind() == lltok::kw_alias);
618 LocTy LinkageLoc = Lex.getLoc();
619 if (ParseOptionalLinkage(Linkage))
622 if (Linkage != GlobalValue::ExternalLinkage &&
623 Linkage != GlobalValue::WeakAnyLinkage &&
624 Linkage != GlobalValue::WeakODRLinkage &&
625 Linkage != GlobalValue::InternalLinkage &&
626 Linkage != GlobalValue::PrivateLinkage &&
627 Linkage != GlobalValue::LinkerPrivateLinkage &&
628 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
629 return Error(LinkageLoc, "invalid linkage type for alias");
632 LocTy AliaseeLoc = Lex.getLoc();
633 if (Lex.getKind() != lltok::kw_bitcast &&
634 Lex.getKind() != lltok::kw_getelementptr) {
635 if (ParseGlobalTypeAndValue(Aliasee)) return true;
637 // The bitcast dest type is not present, it is implied by the dest type.
639 if (ParseValID(ID)) return true;
640 if (ID.Kind != ValID::t_Constant)
641 return Error(AliaseeLoc, "invalid aliasee");
642 Aliasee = ID.ConstantVal;
645 if (!Aliasee->getType()->isPointerTy())
646 return Error(AliaseeLoc, "alias must have pointer type");
648 // Okay, create the alias but do not insert it into the module yet.
649 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
650 (GlobalValue::LinkageTypes)Linkage, Name,
652 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
654 // See if this value already exists in the symbol table. If so, it is either
655 // a redefinition or a definition of a forward reference.
656 if (GlobalValue *Val = M->getNamedValue(Name)) {
657 // See if this was a redefinition. If so, there is no entry in
659 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
660 I = ForwardRefVals.find(Name);
661 if (I == ForwardRefVals.end())
662 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
664 // Otherwise, this was a definition of forward ref. Verify that types
666 if (Val->getType() != GA->getType())
667 return Error(NameLoc,
668 "forward reference and definition of alias have different types");
670 // If they agree, just RAUW the old value with the alias and remove the
672 Val->replaceAllUsesWith(GA);
673 Val->eraseFromParent();
674 ForwardRefVals.erase(I);
677 // Insert into the module, we know its name won't collide now.
678 M->getAliasList().push_back(GA);
679 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
685 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
686 /// OptionalAddrSpace GlobalType Type Const
687 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
688 /// OptionalAddrSpace GlobalType Type Const
690 /// Everything through visibility has been parsed already.
692 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
693 unsigned Linkage, bool HasLinkage,
694 unsigned Visibility) {
696 bool ThreadLocal, IsConstant;
699 PATypeHolder Ty(Type::getVoidTy(Context));
700 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
701 ParseOptionalAddrSpace(AddrSpace) ||
702 ParseGlobalType(IsConstant) ||
703 ParseType(Ty, TyLoc))
706 // If the linkage is specified and is external, then no initializer is
709 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
710 Linkage != GlobalValue::ExternalWeakLinkage &&
711 Linkage != GlobalValue::ExternalLinkage)) {
712 if (ParseGlobalValue(Ty, Init))
716 if (Ty->isFunctionTy() || Ty->isLabelTy())
717 return Error(TyLoc, "invalid type for global variable");
719 GlobalVariable *GV = 0;
721 // See if the global was forward referenced, if so, use the global.
723 if (GlobalValue *GVal = M->getNamedValue(Name)) {
724 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
725 return Error(NameLoc, "redefinition of global '@" + Name + "'");
726 GV = cast<GlobalVariable>(GVal);
729 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
730 I = ForwardRefValIDs.find(NumberedVals.size());
731 if (I != ForwardRefValIDs.end()) {
732 GV = cast<GlobalVariable>(I->second.first);
733 ForwardRefValIDs.erase(I);
738 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
739 Name, 0, false, AddrSpace);
741 if (GV->getType()->getElementType() != Ty)
743 "forward reference and definition of global have different types");
745 // Move the forward-reference to the correct spot in the module.
746 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
750 NumberedVals.push_back(GV);
752 // Set the parsed properties on the global.
754 GV->setInitializer(Init);
755 GV->setConstant(IsConstant);
756 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
757 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
758 GV->setThreadLocal(ThreadLocal);
760 // Parse attributes on the global.
761 while (Lex.getKind() == lltok::comma) {
764 if (Lex.getKind() == lltok::kw_section) {
766 GV->setSection(Lex.getStrVal());
767 if (ParseToken(lltok::StringConstant, "expected global section string"))
769 } else if (Lex.getKind() == lltok::kw_align) {
771 if (ParseOptionalAlignment(Alignment)) return true;
772 GV->setAlignment(Alignment);
774 TokError("unknown global variable property!");
782 //===----------------------------------------------------------------------===//
783 // GlobalValue Reference/Resolution Routines.
784 //===----------------------------------------------------------------------===//
786 /// GetGlobalVal - Get a value with the specified name or ID, creating a
787 /// forward reference record if needed. This can return null if the value
788 /// exists but does not have the right type.
789 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
791 const PointerType *PTy = dyn_cast<PointerType>(Ty);
793 Error(Loc, "global variable reference must have pointer type");
797 // Look this name up in the normal function symbol table.
799 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
801 // If this is a forward reference for the value, see if we already created a
802 // forward ref record.
804 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
805 I = ForwardRefVals.find(Name);
806 if (I != ForwardRefVals.end())
807 Val = I->second.first;
810 // If we have the value in the symbol table or fwd-ref table, return it.
812 if (Val->getType() == Ty) return Val;
813 Error(Loc, "'@" + Name + "' defined with type '" +
814 Val->getType()->getDescription() + "'");
818 // Otherwise, create a new forward reference for this value and remember it.
820 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
821 // Function types can return opaque but functions can't.
822 if (FT->getReturnType()->isOpaqueTy()) {
823 Error(Loc, "function may not return opaque type");
827 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
829 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
830 GlobalValue::ExternalWeakLinkage, 0, Name);
833 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
837 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
838 const PointerType *PTy = dyn_cast<PointerType>(Ty);
840 Error(Loc, "global variable reference must have pointer type");
844 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
846 // If this is a forward reference for the value, see if we already created a
847 // forward ref record.
849 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
850 I = ForwardRefValIDs.find(ID);
851 if (I != ForwardRefValIDs.end())
852 Val = I->second.first;
855 // If we have the value in the symbol table or fwd-ref table, return it.
857 if (Val->getType() == Ty) return Val;
858 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
859 Val->getType()->getDescription() + "'");
863 // Otherwise, create a new forward reference for this value and remember it.
865 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
866 // Function types can return opaque but functions can't.
867 if (FT->getReturnType()->isOpaqueTy()) {
868 Error(Loc, "function may not return opaque type");
871 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
873 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
874 GlobalValue::ExternalWeakLinkage, 0, "");
877 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
882 //===----------------------------------------------------------------------===//
884 //===----------------------------------------------------------------------===//
886 /// ParseToken - If the current token has the specified kind, eat it and return
887 /// success. Otherwise, emit the specified error and return failure.
888 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
889 if (Lex.getKind() != T)
890 return TokError(ErrMsg);
895 /// ParseStringConstant
896 /// ::= StringConstant
897 bool LLParser::ParseStringConstant(std::string &Result) {
898 if (Lex.getKind() != lltok::StringConstant)
899 return TokError("expected string constant");
900 Result = Lex.getStrVal();
907 bool LLParser::ParseUInt32(unsigned &Val) {
908 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
909 return TokError("expected integer");
910 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
911 if (Val64 != unsigned(Val64))
912 return TokError("expected 32-bit integer (too large)");
919 /// ParseOptionalAddrSpace
921 /// := 'addrspace' '(' uint32 ')'
922 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
924 if (!EatIfPresent(lltok::kw_addrspace))
926 return ParseToken(lltok::lparen, "expected '(' in address space") ||
927 ParseUInt32(AddrSpace) ||
928 ParseToken(lltok::rparen, "expected ')' in address space");
931 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
932 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
933 /// 2: function attr.
934 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
935 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
936 Attrs = Attribute::None;
937 LocTy AttrLoc = Lex.getLoc();
940 switch (Lex.getKind()) {
943 // Treat these as signext/zeroext if they occur in the argument list after
944 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
945 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
947 // FIXME: REMOVE THIS IN LLVM 3.0
949 if (Lex.getKind() == lltok::kw_sext)
950 Attrs |= Attribute::SExt;
952 Attrs |= Attribute::ZExt;
956 default: // End of attributes.
957 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
958 return Error(AttrLoc, "invalid use of function-only attribute");
960 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
961 return Error(AttrLoc, "invalid use of parameter-only attribute");
964 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
965 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
966 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
967 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
968 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
969 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
970 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
971 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
973 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
974 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
975 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
976 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
977 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
978 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
979 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
980 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
981 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
982 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
983 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
984 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
985 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
987 case lltok::kw_alignstack: {
989 if (ParseOptionalStackAlignment(Alignment))
991 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
995 case lltok::kw_align: {
997 if (ParseOptionalAlignment(Alignment))
999 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1008 /// ParseOptionalLinkage
1011 /// ::= 'linker_private'
1012 /// ::= 'linker_private_weak'
1017 /// ::= 'linkonce_odr'
1018 /// ::= 'available_externally'
1023 /// ::= 'extern_weak'
1025 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1027 switch (Lex.getKind()) {
1028 default: Res=GlobalValue::ExternalLinkage; return false;
1029 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1030 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1031 case lltok::kw_linker_private_weak:
1032 Res = GlobalValue::LinkerPrivateWeakLinkage;
1034 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1035 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1036 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1037 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1038 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1039 case lltok::kw_available_externally:
1040 Res = GlobalValue::AvailableExternallyLinkage;
1042 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1043 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1044 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1045 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1046 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1047 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1054 /// ParseOptionalVisibility
1060 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1061 switch (Lex.getKind()) {
1062 default: Res = GlobalValue::DefaultVisibility; return false;
1063 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1064 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1065 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1071 /// ParseOptionalCallingConv
1076 /// ::= 'x86_stdcallcc'
1077 /// ::= 'x86_fastcallcc'
1078 /// ::= 'x86_thiscallcc'
1079 /// ::= 'arm_apcscc'
1080 /// ::= 'arm_aapcscc'
1081 /// ::= 'arm_aapcs_vfpcc'
1082 /// ::= 'msp430_intrcc'
1085 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1086 switch (Lex.getKind()) {
1087 default: CC = CallingConv::C; return false;
1088 case lltok::kw_ccc: CC = CallingConv::C; break;
1089 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1090 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1091 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1092 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1093 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1094 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1095 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1096 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1097 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1098 case lltok::kw_cc: {
1099 unsigned ArbitraryCC;
1101 if (ParseUInt32(ArbitraryCC)) {
1104 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1114 /// ParseInstructionMetadata
1115 /// ::= !dbg !42 (',' !dbg !57)*
1116 bool LLParser::ParseInstructionMetadata(Instruction *Inst) {
1118 if (Lex.getKind() != lltok::MetadataVar)
1119 return TokError("expected metadata after comma");
1121 std::string Name = Lex.getStrVal();
1126 SMLoc Loc = Lex.getLoc();
1127 if (ParseToken(lltok::exclaim, "expected '!' here") ||
1128 ParseMDNodeID(Node, NodeID))
1131 unsigned MDK = M->getMDKindID(Name.c_str());
1133 // If we got the node, add it to the instruction.
1134 Inst->setMetadata(MDK, Node);
1136 MDRef R = { Loc, MDK, NodeID };
1137 // Otherwise, remember that this should be resolved later.
1138 ForwardRefInstMetadata[Inst].push_back(R);
1141 // If this is the end of the list, we're done.
1142 } while (EatIfPresent(lltok::comma));
1146 /// ParseOptionalAlignment
1149 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1151 if (!EatIfPresent(lltok::kw_align))
1153 LocTy AlignLoc = Lex.getLoc();
1154 if (ParseUInt32(Alignment)) return true;
1155 if (!isPowerOf2_32(Alignment))
1156 return Error(AlignLoc, "alignment is not a power of two");
1160 /// ParseOptionalCommaAlign
1164 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1166 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1167 bool &AteExtraComma) {
1168 AteExtraComma = false;
1169 while (EatIfPresent(lltok::comma)) {
1170 // Metadata at the end is an early exit.
1171 if (Lex.getKind() == lltok::MetadataVar) {
1172 AteExtraComma = true;
1176 if (Lex.getKind() != lltok::kw_align)
1177 return Error(Lex.getLoc(), "expected metadata or 'align'");
1179 if (ParseOptionalAlignment(Alignment)) return true;
1185 /// ParseOptionalStackAlignment
1187 /// ::= 'alignstack' '(' 4 ')'
1188 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1190 if (!EatIfPresent(lltok::kw_alignstack))
1192 LocTy ParenLoc = Lex.getLoc();
1193 if (!EatIfPresent(lltok::lparen))
1194 return Error(ParenLoc, "expected '('");
1195 LocTy AlignLoc = Lex.getLoc();
1196 if (ParseUInt32(Alignment)) return true;
1197 ParenLoc = Lex.getLoc();
1198 if (!EatIfPresent(lltok::rparen))
1199 return Error(ParenLoc, "expected ')'");
1200 if (!isPowerOf2_32(Alignment))
1201 return Error(AlignLoc, "stack alignment is not a power of two");
1205 /// ParseIndexList - This parses the index list for an insert/extractvalue
1206 /// instruction. This sets AteExtraComma in the case where we eat an extra
1207 /// comma at the end of the line and find that it is followed by metadata.
1208 /// Clients that don't allow metadata can call the version of this function that
1209 /// only takes one argument.
1212 /// ::= (',' uint32)+
1214 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1215 bool &AteExtraComma) {
1216 AteExtraComma = false;
1218 if (Lex.getKind() != lltok::comma)
1219 return TokError("expected ',' as start of index list");
1221 while (EatIfPresent(lltok::comma)) {
1222 if (Lex.getKind() == lltok::MetadataVar) {
1223 AteExtraComma = true;
1227 if (ParseUInt32(Idx)) return true;
1228 Indices.push_back(Idx);
1234 //===----------------------------------------------------------------------===//
1236 //===----------------------------------------------------------------------===//
1238 /// ParseType - Parse and resolve a full type.
1239 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1240 LocTy TypeLoc = Lex.getLoc();
1241 if (ParseTypeRec(Result)) return true;
1243 // Verify no unresolved uprefs.
1244 if (!UpRefs.empty())
1245 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1247 if (!AllowVoid && Result.get()->isVoidTy())
1248 return Error(TypeLoc, "void type only allowed for function results");
1253 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1254 /// called. It loops through the UpRefs vector, which is a list of the
1255 /// currently active types. For each type, if the up-reference is contained in
1256 /// the newly completed type, we decrement the level count. When the level
1257 /// count reaches zero, the up-referenced type is the type that is passed in:
1258 /// thus we can complete the cycle.
1260 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1261 // If Ty isn't abstract, or if there are no up-references in it, then there is
1262 // nothing to resolve here.
1263 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1265 PATypeHolder Ty(ty);
1267 dbgs() << "Type '" << Ty->getDescription()
1268 << "' newly formed. Resolving upreferences.\n"
1269 << UpRefs.size() << " upreferences active!\n";
1272 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1273 // to zero), we resolve them all together before we resolve them to Ty. At
1274 // the end of the loop, if there is anything to resolve to Ty, it will be in
1276 OpaqueType *TypeToResolve = 0;
1278 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1279 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1281 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1282 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1285 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1286 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1287 << (ContainsType ? "true" : "false")
1288 << " level=" << UpRefs[i].NestingLevel << "\n";
1293 // Decrement level of upreference
1294 unsigned Level = --UpRefs[i].NestingLevel;
1295 UpRefs[i].LastContainedTy = Ty;
1297 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1302 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1305 TypeToResolve = UpRefs[i].UpRefTy;
1307 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1308 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1309 --i; // Do not skip the next element.
1313 TypeToResolve->refineAbstractTypeTo(Ty);
1319 /// ParseTypeRec - The recursive function used to process the internal
1320 /// implementation details of types.
1321 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1322 switch (Lex.getKind()) {
1324 return TokError("expected type");
1326 // TypeRec ::= 'float' | 'void' (etc)
1327 Result = Lex.getTyVal();
1330 case lltok::kw_opaque:
1331 // TypeRec ::= 'opaque'
1332 Result = OpaqueType::get(Context);
1336 // TypeRec ::= '{' ... '}'
1337 if (ParseStructType(Result, false))
1340 case lltok::kw_union:
1341 // TypeRec ::= 'union' '{' ... '}'
1342 if (ParseUnionType(Result))
1345 case lltok::lsquare:
1346 // TypeRec ::= '[' ... ']'
1347 Lex.Lex(); // eat the lsquare.
1348 if (ParseArrayVectorType(Result, false))
1351 case lltok::less: // Either vector or packed struct.
1352 // TypeRec ::= '<' ... '>'
1354 if (Lex.getKind() == lltok::lbrace) {
1355 if (ParseStructType(Result, true) ||
1356 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1358 } else if (ParseArrayVectorType(Result, true))
1361 case lltok::LocalVar:
1362 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1364 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1367 Result = OpaqueType::get(Context);
1368 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1369 std::make_pair(Result,
1371 M->addTypeName(Lex.getStrVal(), Result.get());
1376 case lltok::LocalVarID:
1378 if (Lex.getUIntVal() < NumberedTypes.size())
1379 Result = NumberedTypes[Lex.getUIntVal()];
1381 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1382 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1383 if (I != ForwardRefTypeIDs.end())
1384 Result = I->second.first;
1386 Result = OpaqueType::get(Context);
1387 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1388 std::make_pair(Result,
1394 case lltok::backslash: {
1395 // TypeRec ::= '\' 4
1398 if (ParseUInt32(Val)) return true;
1399 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1400 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1406 // Parse the type suffixes.
1408 switch (Lex.getKind()) {
1410 default: return false;
1412 // TypeRec ::= TypeRec '*'
1414 if (Result.get()->isLabelTy())
1415 return TokError("basic block pointers are invalid");
1416 if (Result.get()->isVoidTy())
1417 return TokError("pointers to void are invalid; use i8* instead");
1418 if (!PointerType::isValidElementType(Result.get()))
1419 return TokError("pointer to this type is invalid");
1420 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1424 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1425 case lltok::kw_addrspace: {
1426 if (Result.get()->isLabelTy())
1427 return TokError("basic block pointers are invalid");
1428 if (Result.get()->isVoidTy())
1429 return TokError("pointers to void are invalid; use i8* instead");
1430 if (!PointerType::isValidElementType(Result.get()))
1431 return TokError("pointer to this type is invalid");
1433 if (ParseOptionalAddrSpace(AddrSpace) ||
1434 ParseToken(lltok::star, "expected '*' in address space"))
1437 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1441 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1443 if (ParseFunctionType(Result))
1450 /// ParseParameterList
1452 /// ::= '(' Arg (',' Arg)* ')'
1454 /// ::= Type OptionalAttributes Value OptionalAttributes
1455 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1456 PerFunctionState &PFS) {
1457 if (ParseToken(lltok::lparen, "expected '(' in call"))
1460 while (Lex.getKind() != lltok::rparen) {
1461 // If this isn't the first argument, we need a comma.
1462 if (!ArgList.empty() &&
1463 ParseToken(lltok::comma, "expected ',' in argument list"))
1466 // Parse the argument.
1468 PATypeHolder ArgTy(Type::getVoidTy(Context));
1469 unsigned ArgAttrs1 = Attribute::None;
1470 unsigned ArgAttrs2 = Attribute::None;
1472 if (ParseType(ArgTy, ArgLoc))
1475 // Otherwise, handle normal operands.
1476 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1477 ParseValue(ArgTy, V, PFS) ||
1478 // FIXME: Should not allow attributes after the argument, remove this
1480 ParseOptionalAttrs(ArgAttrs2, 3))
1482 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1485 Lex.Lex(); // Lex the ')'.
1491 /// ParseArgumentList - Parse the argument list for a function type or function
1492 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1493 /// ::= '(' ArgTypeListI ')'
1497 /// ::= ArgTypeList ',' '...'
1498 /// ::= ArgType (',' ArgType)*
1500 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1501 bool &isVarArg, bool inType) {
1503 assert(Lex.getKind() == lltok::lparen);
1504 Lex.Lex(); // eat the (.
1506 if (Lex.getKind() == lltok::rparen) {
1508 } else if (Lex.getKind() == lltok::dotdotdot) {
1512 LocTy TypeLoc = Lex.getLoc();
1513 PATypeHolder ArgTy(Type::getVoidTy(Context));
1517 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1518 // types (such as a function returning a pointer to itself). If parsing a
1519 // function prototype, we require fully resolved types.
1520 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1521 ParseOptionalAttrs(Attrs, 0)) return true;
1523 if (ArgTy->isVoidTy())
1524 return Error(TypeLoc, "argument can not have void type");
1526 if (Lex.getKind() == lltok::LocalVar ||
1527 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1528 Name = Lex.getStrVal();
1532 if (!FunctionType::isValidArgumentType(ArgTy))
1533 return Error(TypeLoc, "invalid type for function argument");
1535 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1537 while (EatIfPresent(lltok::comma)) {
1538 // Handle ... at end of arg list.
1539 if (EatIfPresent(lltok::dotdotdot)) {
1544 // Otherwise must be an argument type.
1545 TypeLoc = Lex.getLoc();
1546 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1547 ParseOptionalAttrs(Attrs, 0)) return true;
1549 if (ArgTy->isVoidTy())
1550 return Error(TypeLoc, "argument can not have void type");
1552 if (Lex.getKind() == lltok::LocalVar ||
1553 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1554 Name = Lex.getStrVal();
1560 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
1561 return Error(TypeLoc, "invalid type for function argument");
1563 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1567 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1570 /// ParseFunctionType
1571 /// ::= Type ArgumentList OptionalAttrs
1572 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1573 assert(Lex.getKind() == lltok::lparen);
1575 if (!FunctionType::isValidReturnType(Result))
1576 return TokError("invalid function return type");
1578 std::vector<ArgInfo> ArgList;
1581 if (ParseArgumentList(ArgList, isVarArg, true) ||
1582 // FIXME: Allow, but ignore attributes on function types!
1583 // FIXME: Remove in LLVM 3.0
1584 ParseOptionalAttrs(Attrs, 2))
1587 // Reject names on the arguments lists.
1588 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1589 if (!ArgList[i].Name.empty())
1590 return Error(ArgList[i].Loc, "argument name invalid in function type");
1591 if (!ArgList[i].Attrs != 0) {
1592 // Allow but ignore attributes on function types; this permits
1594 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1598 std::vector<const Type*> ArgListTy;
1599 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1600 ArgListTy.push_back(ArgList[i].Type);
1602 Result = HandleUpRefs(FunctionType::get(Result.get(),
1603 ArgListTy, isVarArg));
1607 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1610 /// ::= '{' TypeRec (',' TypeRec)* '}'
1611 /// ::= '<' '{' '}' '>'
1612 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1613 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1614 assert(Lex.getKind() == lltok::lbrace);
1615 Lex.Lex(); // Consume the '{'
1617 if (EatIfPresent(lltok::rbrace)) {
1618 Result = StructType::get(Context, Packed);
1622 std::vector<PATypeHolder> ParamsList;
1623 LocTy EltTyLoc = Lex.getLoc();
1624 if (ParseTypeRec(Result)) return true;
1625 ParamsList.push_back(Result);
1627 if (Result->isVoidTy())
1628 return Error(EltTyLoc, "struct element can not have void type");
1629 if (!StructType::isValidElementType(Result))
1630 return Error(EltTyLoc, "invalid element type for struct");
1632 while (EatIfPresent(lltok::comma)) {
1633 EltTyLoc = Lex.getLoc();
1634 if (ParseTypeRec(Result)) return true;
1636 if (Result->isVoidTy())
1637 return Error(EltTyLoc, "struct element can not have void type");
1638 if (!StructType::isValidElementType(Result))
1639 return Error(EltTyLoc, "invalid element type for struct");
1641 ParamsList.push_back(Result);
1644 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1647 std::vector<const Type*> ParamsListTy;
1648 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1649 ParamsListTy.push_back(ParamsList[i].get());
1650 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1656 /// ::= 'union' '{' TypeRec (',' TypeRec)* '}'
1657 bool LLParser::ParseUnionType(PATypeHolder &Result) {
1658 assert(Lex.getKind() == lltok::kw_union);
1659 Lex.Lex(); // Consume the 'union'
1661 if (ParseToken(lltok::lbrace, "'{' expected after 'union'")) return true;
1663 SmallVector<PATypeHolder, 8> ParamsList;
1665 LocTy EltTyLoc = Lex.getLoc();
1666 if (ParseTypeRec(Result)) return true;
1667 ParamsList.push_back(Result);
1669 if (Result->isVoidTy())
1670 return Error(EltTyLoc, "union element can not have void type");
1671 if (!UnionType::isValidElementType(Result))
1672 return Error(EltTyLoc, "invalid element type for union");
1674 } while (EatIfPresent(lltok::comma)) ;
1676 if (ParseToken(lltok::rbrace, "expected '}' at end of union"))
1679 SmallVector<const Type*, 8> ParamsListTy;
1680 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1681 ParamsListTy.push_back(ParamsList[i].get());
1682 Result = HandleUpRefs(UnionType::get(&ParamsListTy[0], ParamsListTy.size()));
1686 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1687 /// token has already been consumed.
1689 /// ::= '[' APSINTVAL 'x' Types ']'
1690 /// ::= '<' APSINTVAL 'x' Types '>'
1691 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1692 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1693 Lex.getAPSIntVal().getBitWidth() > 64)
1694 return TokError("expected number in address space");
1696 LocTy SizeLoc = Lex.getLoc();
1697 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1700 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1703 LocTy TypeLoc = Lex.getLoc();
1704 PATypeHolder EltTy(Type::getVoidTy(Context));
1705 if (ParseTypeRec(EltTy)) return true;
1707 if (EltTy->isVoidTy())
1708 return Error(TypeLoc, "array and vector element type cannot be void");
1710 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1711 "expected end of sequential type"))
1716 return Error(SizeLoc, "zero element vector is illegal");
1717 if ((unsigned)Size != Size)
1718 return Error(SizeLoc, "size too large for vector");
1719 if (!VectorType::isValidElementType(EltTy))
1720 return Error(TypeLoc, "vector element type must be fp or integer");
1721 Result = VectorType::get(EltTy, unsigned(Size));
1723 if (!ArrayType::isValidElementType(EltTy))
1724 return Error(TypeLoc, "invalid array element type");
1725 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1730 //===----------------------------------------------------------------------===//
1731 // Function Semantic Analysis.
1732 //===----------------------------------------------------------------------===//
1734 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1736 : P(p), F(f), FunctionNumber(functionNumber) {
1738 // Insert unnamed arguments into the NumberedVals list.
1739 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1742 NumberedVals.push_back(AI);
1745 LLParser::PerFunctionState::~PerFunctionState() {
1746 // If there were any forward referenced non-basicblock values, delete them.
1747 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1748 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1749 if (!isa<BasicBlock>(I->second.first)) {
1750 I->second.first->replaceAllUsesWith(
1751 UndefValue::get(I->second.first->getType()));
1752 delete I->second.first;
1753 I->second.first = 0;
1756 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1757 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1758 if (!isa<BasicBlock>(I->second.first)) {
1759 I->second.first->replaceAllUsesWith(
1760 UndefValue::get(I->second.first->getType()));
1761 delete I->second.first;
1762 I->second.first = 0;
1766 bool LLParser::PerFunctionState::FinishFunction() {
1767 // Check to see if someone took the address of labels in this block.
1768 if (!P.ForwardRefBlockAddresses.empty()) {
1770 if (!F.getName().empty()) {
1771 FunctionID.Kind = ValID::t_GlobalName;
1772 FunctionID.StrVal = F.getName();
1774 FunctionID.Kind = ValID::t_GlobalID;
1775 FunctionID.UIntVal = FunctionNumber;
1778 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1779 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1780 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1781 // Resolve all these references.
1782 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1785 P.ForwardRefBlockAddresses.erase(FRBAI);
1789 if (!ForwardRefVals.empty())
1790 return P.Error(ForwardRefVals.begin()->second.second,
1791 "use of undefined value '%" + ForwardRefVals.begin()->first +
1793 if (!ForwardRefValIDs.empty())
1794 return P.Error(ForwardRefValIDs.begin()->second.second,
1795 "use of undefined value '%" +
1796 utostr(ForwardRefValIDs.begin()->first) + "'");
1801 /// GetVal - Get a value with the specified name or ID, creating a
1802 /// forward reference record if needed. This can return null if the value
1803 /// exists but does not have the right type.
1804 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1805 const Type *Ty, LocTy Loc) {
1806 // Look this name up in the normal function symbol table.
1807 Value *Val = F.getValueSymbolTable().lookup(Name);
1809 // If this is a forward reference for the value, see if we already created a
1810 // forward ref record.
1812 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1813 I = ForwardRefVals.find(Name);
1814 if (I != ForwardRefVals.end())
1815 Val = I->second.first;
1818 // If we have the value in the symbol table or fwd-ref table, return it.
1820 if (Val->getType() == Ty) return Val;
1821 if (Ty->isLabelTy())
1822 P.Error(Loc, "'%" + Name + "' is not a basic block");
1824 P.Error(Loc, "'%" + Name + "' defined with type '" +
1825 Val->getType()->getDescription() + "'");
1829 // Don't make placeholders with invalid type.
1830 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1831 P.Error(Loc, "invalid use of a non-first-class type");
1835 // Otherwise, create a new forward reference for this value and remember it.
1837 if (Ty->isLabelTy())
1838 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1840 FwdVal = new Argument(Ty, Name);
1842 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1846 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1848 // Look this name up in the normal function symbol table.
1849 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1851 // If this is a forward reference for the value, see if we already created a
1852 // forward ref record.
1854 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1855 I = ForwardRefValIDs.find(ID);
1856 if (I != ForwardRefValIDs.end())
1857 Val = I->second.first;
1860 // If we have the value in the symbol table or fwd-ref table, return it.
1862 if (Val->getType() == Ty) return Val;
1863 if (Ty->isLabelTy())
1864 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1866 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1867 Val->getType()->getDescription() + "'");
1871 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1872 P.Error(Loc, "invalid use of a non-first-class type");
1876 // Otherwise, create a new forward reference for this value and remember it.
1878 if (Ty->isLabelTy())
1879 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1881 FwdVal = new Argument(Ty);
1883 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1887 /// SetInstName - After an instruction is parsed and inserted into its
1888 /// basic block, this installs its name.
1889 bool LLParser::PerFunctionState::SetInstName(int NameID,
1890 const std::string &NameStr,
1891 LocTy NameLoc, Instruction *Inst) {
1892 // If this instruction has void type, it cannot have a name or ID specified.
1893 if (Inst->getType()->isVoidTy()) {
1894 if (NameID != -1 || !NameStr.empty())
1895 return P.Error(NameLoc, "instructions returning void cannot have a name");
1899 // If this was a numbered instruction, verify that the instruction is the
1900 // expected value and resolve any forward references.
1901 if (NameStr.empty()) {
1902 // If neither a name nor an ID was specified, just use the next ID.
1904 NameID = NumberedVals.size();
1906 if (unsigned(NameID) != NumberedVals.size())
1907 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1908 utostr(NumberedVals.size()) + "'");
1910 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1911 ForwardRefValIDs.find(NameID);
1912 if (FI != ForwardRefValIDs.end()) {
1913 if (FI->second.first->getType() != Inst->getType())
1914 return P.Error(NameLoc, "instruction forward referenced with type '" +
1915 FI->second.first->getType()->getDescription() + "'");
1916 FI->second.first->replaceAllUsesWith(Inst);
1917 delete FI->second.first;
1918 ForwardRefValIDs.erase(FI);
1921 NumberedVals.push_back(Inst);
1925 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1926 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1927 FI = ForwardRefVals.find(NameStr);
1928 if (FI != ForwardRefVals.end()) {
1929 if (FI->second.first->getType() != Inst->getType())
1930 return P.Error(NameLoc, "instruction forward referenced with type '" +
1931 FI->second.first->getType()->getDescription() + "'");
1932 FI->second.first->replaceAllUsesWith(Inst);
1933 delete FI->second.first;
1934 ForwardRefVals.erase(FI);
1937 // Set the name on the instruction.
1938 Inst->setName(NameStr);
1940 if (Inst->getNameStr() != NameStr)
1941 return P.Error(NameLoc, "multiple definition of local value named '" +
1946 /// GetBB - Get a basic block with the specified name or ID, creating a
1947 /// forward reference record if needed.
1948 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1950 return cast_or_null<BasicBlock>(GetVal(Name,
1951 Type::getLabelTy(F.getContext()), Loc));
1954 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1955 return cast_or_null<BasicBlock>(GetVal(ID,
1956 Type::getLabelTy(F.getContext()), Loc));
1959 /// DefineBB - Define the specified basic block, which is either named or
1960 /// unnamed. If there is an error, this returns null otherwise it returns
1961 /// the block being defined.
1962 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1966 BB = GetBB(NumberedVals.size(), Loc);
1968 BB = GetBB(Name, Loc);
1969 if (BB == 0) return 0; // Already diagnosed error.
1971 // Move the block to the end of the function. Forward ref'd blocks are
1972 // inserted wherever they happen to be referenced.
1973 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1975 // Remove the block from forward ref sets.
1977 ForwardRefValIDs.erase(NumberedVals.size());
1978 NumberedVals.push_back(BB);
1980 // BB forward references are already in the function symbol table.
1981 ForwardRefVals.erase(Name);
1987 //===----------------------------------------------------------------------===//
1989 //===----------------------------------------------------------------------===//
1991 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1992 /// type implied. For example, if we parse "4" we don't know what integer type
1993 /// it has. The value will later be combined with its type and checked for
1994 /// sanity. PFS is used to convert function-local operands of metadata (since
1995 /// metadata operands are not just parsed here but also converted to values).
1996 /// PFS can be null when we are not parsing metadata values inside a function.
1997 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1998 ID.Loc = Lex.getLoc();
1999 switch (Lex.getKind()) {
2000 default: return TokError("expected value token");
2001 case lltok::GlobalID: // @42
2002 ID.UIntVal = Lex.getUIntVal();
2003 ID.Kind = ValID::t_GlobalID;
2005 case lltok::GlobalVar: // @foo
2006 ID.StrVal = Lex.getStrVal();
2007 ID.Kind = ValID::t_GlobalName;
2009 case lltok::LocalVarID: // %42
2010 ID.UIntVal = Lex.getUIntVal();
2011 ID.Kind = ValID::t_LocalID;
2013 case lltok::LocalVar: // %foo
2014 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2015 ID.StrVal = Lex.getStrVal();
2016 ID.Kind = ValID::t_LocalName;
2018 case lltok::exclaim: // !42, !{...}, or !"foo"
2019 return ParseMetadataValue(ID, PFS);
2021 ID.APSIntVal = Lex.getAPSIntVal();
2022 ID.Kind = ValID::t_APSInt;
2024 case lltok::APFloat:
2025 ID.APFloatVal = Lex.getAPFloatVal();
2026 ID.Kind = ValID::t_APFloat;
2028 case lltok::kw_true:
2029 ID.ConstantVal = ConstantInt::getTrue(Context);
2030 ID.Kind = ValID::t_Constant;
2032 case lltok::kw_false:
2033 ID.ConstantVal = ConstantInt::getFalse(Context);
2034 ID.Kind = ValID::t_Constant;
2036 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2037 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2038 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2040 case lltok::lbrace: {
2041 // ValID ::= '{' ConstVector '}'
2043 SmallVector<Constant*, 16> Elts;
2044 if (ParseGlobalValueVector(Elts) ||
2045 ParseToken(lltok::rbrace, "expected end of struct constant"))
2048 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2049 Elts.size(), false);
2050 ID.Kind = ValID::t_Constant;
2054 // ValID ::= '<' ConstVector '>' --> Vector.
2055 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2057 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2059 SmallVector<Constant*, 16> Elts;
2060 LocTy FirstEltLoc = Lex.getLoc();
2061 if (ParseGlobalValueVector(Elts) ||
2063 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2064 ParseToken(lltok::greater, "expected end of constant"))
2067 if (isPackedStruct) {
2069 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
2070 ID.Kind = ValID::t_Constant;
2075 return Error(ID.Loc, "constant vector must not be empty");
2077 if (!Elts[0]->getType()->isIntegerTy() &&
2078 !Elts[0]->getType()->isFloatingPointTy())
2079 return Error(FirstEltLoc,
2080 "vector elements must have integer or floating point type");
2082 // Verify that all the vector elements have the same type.
2083 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2084 if (Elts[i]->getType() != Elts[0]->getType())
2085 return Error(FirstEltLoc,
2086 "vector element #" + utostr(i) +
2087 " is not of type '" + Elts[0]->getType()->getDescription());
2089 ID.ConstantVal = ConstantVector::get(Elts.data(), Elts.size());
2090 ID.Kind = ValID::t_Constant;
2093 case lltok::lsquare: { // Array Constant
2095 SmallVector<Constant*, 16> Elts;
2096 LocTy FirstEltLoc = Lex.getLoc();
2097 if (ParseGlobalValueVector(Elts) ||
2098 ParseToken(lltok::rsquare, "expected end of array constant"))
2101 // Handle empty element.
2103 // Use undef instead of an array because it's inconvenient to determine
2104 // the element type at this point, there being no elements to examine.
2105 ID.Kind = ValID::t_EmptyArray;
2109 if (!Elts[0]->getType()->isFirstClassType())
2110 return Error(FirstEltLoc, "invalid array element type: " +
2111 Elts[0]->getType()->getDescription());
2113 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2115 // Verify all elements are correct type!
2116 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2117 if (Elts[i]->getType() != Elts[0]->getType())
2118 return Error(FirstEltLoc,
2119 "array element #" + utostr(i) +
2120 " is not of type '" +Elts[0]->getType()->getDescription());
2123 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2124 ID.Kind = ValID::t_Constant;
2127 case lltok::kw_c: // c "foo"
2129 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2130 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2131 ID.Kind = ValID::t_Constant;
2134 case lltok::kw_asm: {
2135 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2136 bool HasSideEffect, AlignStack;
2138 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2139 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2140 ParseStringConstant(ID.StrVal) ||
2141 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2142 ParseToken(lltok::StringConstant, "expected constraint string"))
2144 ID.StrVal2 = Lex.getStrVal();
2145 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2146 ID.Kind = ValID::t_InlineAsm;
2150 case lltok::kw_blockaddress: {
2151 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2155 LocTy FnLoc, LabelLoc;
2157 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2159 ParseToken(lltok::comma, "expected comma in block address expression")||
2160 ParseValID(Label) ||
2161 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2164 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2165 return Error(Fn.Loc, "expected function name in blockaddress");
2166 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2167 return Error(Label.Loc, "expected basic block name in blockaddress");
2169 // Make a global variable as a placeholder for this reference.
2170 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2171 false, GlobalValue::InternalLinkage,
2173 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2174 ID.ConstantVal = FwdRef;
2175 ID.Kind = ValID::t_Constant;
2179 case lltok::kw_trunc:
2180 case lltok::kw_zext:
2181 case lltok::kw_sext:
2182 case lltok::kw_fptrunc:
2183 case lltok::kw_fpext:
2184 case lltok::kw_bitcast:
2185 case lltok::kw_uitofp:
2186 case lltok::kw_sitofp:
2187 case lltok::kw_fptoui:
2188 case lltok::kw_fptosi:
2189 case lltok::kw_inttoptr:
2190 case lltok::kw_ptrtoint: {
2191 unsigned Opc = Lex.getUIntVal();
2192 PATypeHolder DestTy(Type::getVoidTy(Context));
2195 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2196 ParseGlobalTypeAndValue(SrcVal) ||
2197 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2198 ParseType(DestTy) ||
2199 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2201 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2202 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2203 SrcVal->getType()->getDescription() + "' to '" +
2204 DestTy->getDescription() + "'");
2205 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2207 ID.Kind = ValID::t_Constant;
2210 case lltok::kw_extractvalue: {
2213 SmallVector<unsigned, 4> Indices;
2214 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2215 ParseGlobalTypeAndValue(Val) ||
2216 ParseIndexList(Indices) ||
2217 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2220 if (!Val->getType()->isAggregateType())
2221 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2222 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2224 return Error(ID.Loc, "invalid indices for extractvalue");
2226 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2227 ID.Kind = ValID::t_Constant;
2230 case lltok::kw_insertvalue: {
2232 Constant *Val0, *Val1;
2233 SmallVector<unsigned, 4> Indices;
2234 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2235 ParseGlobalTypeAndValue(Val0) ||
2236 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2237 ParseGlobalTypeAndValue(Val1) ||
2238 ParseIndexList(Indices) ||
2239 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2241 if (!Val0->getType()->isAggregateType())
2242 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2243 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2245 return Error(ID.Loc, "invalid indices for insertvalue");
2246 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2247 Indices.data(), Indices.size());
2248 ID.Kind = ValID::t_Constant;
2251 case lltok::kw_icmp:
2252 case lltok::kw_fcmp: {
2253 unsigned PredVal, Opc = Lex.getUIntVal();
2254 Constant *Val0, *Val1;
2256 if (ParseCmpPredicate(PredVal, Opc) ||
2257 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2258 ParseGlobalTypeAndValue(Val0) ||
2259 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2260 ParseGlobalTypeAndValue(Val1) ||
2261 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2264 if (Val0->getType() != Val1->getType())
2265 return Error(ID.Loc, "compare operands must have the same type");
2267 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2269 if (Opc == Instruction::FCmp) {
2270 if (!Val0->getType()->isFPOrFPVectorTy())
2271 return Error(ID.Loc, "fcmp requires floating point operands");
2272 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2274 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2275 if (!Val0->getType()->isIntOrIntVectorTy() &&
2276 !Val0->getType()->isPointerTy())
2277 return Error(ID.Loc, "icmp requires pointer or integer operands");
2278 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2280 ID.Kind = ValID::t_Constant;
2284 // Binary Operators.
2286 case lltok::kw_fadd:
2288 case lltok::kw_fsub:
2290 case lltok::kw_fmul:
2291 case lltok::kw_udiv:
2292 case lltok::kw_sdiv:
2293 case lltok::kw_fdiv:
2294 case lltok::kw_urem:
2295 case lltok::kw_srem:
2296 case lltok::kw_frem: {
2300 unsigned Opc = Lex.getUIntVal();
2301 Constant *Val0, *Val1;
2303 LocTy ModifierLoc = Lex.getLoc();
2304 if (Opc == Instruction::Add ||
2305 Opc == Instruction::Sub ||
2306 Opc == Instruction::Mul) {
2307 if (EatIfPresent(lltok::kw_nuw))
2309 if (EatIfPresent(lltok::kw_nsw)) {
2311 if (EatIfPresent(lltok::kw_nuw))
2314 } else if (Opc == Instruction::SDiv) {
2315 if (EatIfPresent(lltok::kw_exact))
2318 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2319 ParseGlobalTypeAndValue(Val0) ||
2320 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2321 ParseGlobalTypeAndValue(Val1) ||
2322 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2324 if (Val0->getType() != Val1->getType())
2325 return Error(ID.Loc, "operands of constexpr must have same type");
2326 if (!Val0->getType()->isIntOrIntVectorTy()) {
2328 return Error(ModifierLoc, "nuw only applies to integer operations");
2330 return Error(ModifierLoc, "nsw only applies to integer operations");
2332 // Check that the type is valid for the operator.
2334 case Instruction::Add:
2335 case Instruction::Sub:
2336 case Instruction::Mul:
2337 case Instruction::UDiv:
2338 case Instruction::SDiv:
2339 case Instruction::URem:
2340 case Instruction::SRem:
2341 if (!Val0->getType()->isIntOrIntVectorTy())
2342 return Error(ID.Loc, "constexpr requires integer operands");
2344 case Instruction::FAdd:
2345 case Instruction::FSub:
2346 case Instruction::FMul:
2347 case Instruction::FDiv:
2348 case Instruction::FRem:
2349 if (!Val0->getType()->isFPOrFPVectorTy())
2350 return Error(ID.Loc, "constexpr requires fp operands");
2352 default: llvm_unreachable("Unknown binary operator!");
2355 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2356 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2357 if (Exact) Flags |= SDivOperator::IsExact;
2358 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2360 ID.Kind = ValID::t_Constant;
2364 // Logical Operations
2366 case lltok::kw_lshr:
2367 case lltok::kw_ashr:
2370 case lltok::kw_xor: {
2371 unsigned Opc = Lex.getUIntVal();
2372 Constant *Val0, *Val1;
2374 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2375 ParseGlobalTypeAndValue(Val0) ||
2376 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2377 ParseGlobalTypeAndValue(Val1) ||
2378 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2380 if (Val0->getType() != Val1->getType())
2381 return Error(ID.Loc, "operands of constexpr must have same type");
2382 if (!Val0->getType()->isIntOrIntVectorTy())
2383 return Error(ID.Loc,
2384 "constexpr requires integer or integer vector operands");
2385 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2386 ID.Kind = ValID::t_Constant;
2390 case lltok::kw_getelementptr:
2391 case lltok::kw_shufflevector:
2392 case lltok::kw_insertelement:
2393 case lltok::kw_extractelement:
2394 case lltok::kw_select: {
2395 unsigned Opc = Lex.getUIntVal();
2396 SmallVector<Constant*, 16> Elts;
2397 bool InBounds = false;
2399 if (Opc == Instruction::GetElementPtr)
2400 InBounds = EatIfPresent(lltok::kw_inbounds);
2401 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2402 ParseGlobalValueVector(Elts) ||
2403 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2406 if (Opc == Instruction::GetElementPtr) {
2407 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2408 return Error(ID.Loc, "getelementptr requires pointer operand");
2410 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2411 (Value**)(Elts.data() + 1),
2413 return Error(ID.Loc, "invalid indices for getelementptr");
2414 ID.ConstantVal = InBounds ?
2415 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2418 ConstantExpr::getGetElementPtr(Elts[0],
2419 Elts.data() + 1, Elts.size() - 1);
2420 } else if (Opc == Instruction::Select) {
2421 if (Elts.size() != 3)
2422 return Error(ID.Loc, "expected three operands to select");
2423 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2425 return Error(ID.Loc, Reason);
2426 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2427 } else if (Opc == Instruction::ShuffleVector) {
2428 if (Elts.size() != 3)
2429 return Error(ID.Loc, "expected three operands to shufflevector");
2430 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2431 return Error(ID.Loc, "invalid operands to shufflevector");
2433 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2434 } else if (Opc == Instruction::ExtractElement) {
2435 if (Elts.size() != 2)
2436 return Error(ID.Loc, "expected two operands to extractelement");
2437 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2438 return Error(ID.Loc, "invalid extractelement operands");
2439 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2441 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2442 if (Elts.size() != 3)
2443 return Error(ID.Loc, "expected three operands to insertelement");
2444 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2445 return Error(ID.Loc, "invalid insertelement operands");
2447 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2450 ID.Kind = ValID::t_Constant;
2459 /// ParseGlobalValue - Parse a global value with the specified type.
2460 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2464 bool Parsed = ParseValID(ID) ||
2465 ConvertValIDToValue(Ty, ID, V, NULL);
2466 if (V && !(C = dyn_cast<Constant>(V)))
2467 return Error(ID.Loc, "global values must be constants");
2471 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2472 PATypeHolder Type(Type::getVoidTy(Context));
2473 return ParseType(Type) ||
2474 ParseGlobalValue(Type, V);
2477 /// ParseGlobalValueVector
2479 /// ::= TypeAndValue (',' TypeAndValue)*
2480 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2482 if (Lex.getKind() == lltok::rbrace ||
2483 Lex.getKind() == lltok::rsquare ||
2484 Lex.getKind() == lltok::greater ||
2485 Lex.getKind() == lltok::rparen)
2489 if (ParseGlobalTypeAndValue(C)) return true;
2492 while (EatIfPresent(lltok::comma)) {
2493 if (ParseGlobalTypeAndValue(C)) return true;
2500 /// ParseMetadataValue
2504 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2505 assert(Lex.getKind() == lltok::exclaim);
2510 if (EatIfPresent(lltok::lbrace)) {
2511 SmallVector<Value*, 16> Elts;
2512 if (ParseMDNodeVector(Elts, PFS) ||
2513 ParseToken(lltok::rbrace, "expected end of metadata node"))
2516 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2517 ID.Kind = ValID::t_MDNode;
2521 // Standalone metadata reference
2523 if (Lex.getKind() == lltok::APSInt) {
2524 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2525 ID.Kind = ValID::t_MDNode;
2530 // ::= '!' STRINGCONSTANT
2531 if (ParseMDString(ID.MDStringVal)) return true;
2532 ID.Kind = ValID::t_MDString;
2537 //===----------------------------------------------------------------------===//
2538 // Function Parsing.
2539 //===----------------------------------------------------------------------===//
2541 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2542 PerFunctionState *PFS) {
2543 if (Ty->isFunctionTy())
2544 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2547 default: llvm_unreachable("Unknown ValID!");
2548 case ValID::t_LocalID:
2549 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2550 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2552 case ValID::t_LocalName:
2553 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2554 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2556 case ValID::t_InlineAsm: {
2557 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2558 const FunctionType *FTy =
2559 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2560 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2561 return Error(ID.Loc, "invalid type for inline asm constraint string");
2562 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2565 case ValID::t_MDNode:
2566 if (!Ty->isMetadataTy())
2567 return Error(ID.Loc, "metadata value must have metadata type");
2570 case ValID::t_MDString:
2571 if (!Ty->isMetadataTy())
2572 return Error(ID.Loc, "metadata value must have metadata type");
2575 case ValID::t_GlobalName:
2576 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2578 case ValID::t_GlobalID:
2579 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2581 case ValID::t_APSInt:
2582 if (!Ty->isIntegerTy())
2583 return Error(ID.Loc, "integer constant must have integer type");
2584 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2585 V = ConstantInt::get(Context, ID.APSIntVal);
2587 case ValID::t_APFloat:
2588 if (!Ty->isFloatingPointTy() ||
2589 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2590 return Error(ID.Loc, "floating point constant invalid for type");
2592 // The lexer has no type info, so builds all float and double FP constants
2593 // as double. Fix this here. Long double does not need this.
2594 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2597 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2600 V = ConstantFP::get(Context, ID.APFloatVal);
2602 if (V->getType() != Ty)
2603 return Error(ID.Loc, "floating point constant does not have type '" +
2604 Ty->getDescription() + "'");
2608 if (!Ty->isPointerTy())
2609 return Error(ID.Loc, "null must be a pointer type");
2610 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2612 case ValID::t_Undef:
2613 // FIXME: LabelTy should not be a first-class type.
2614 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2616 return Error(ID.Loc, "invalid type for undef constant");
2617 V = UndefValue::get(Ty);
2619 case ValID::t_EmptyArray:
2620 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2621 return Error(ID.Loc, "invalid empty array initializer");
2622 V = UndefValue::get(Ty);
2625 // FIXME: LabelTy should not be a first-class type.
2626 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2627 return Error(ID.Loc, "invalid type for null constant");
2628 V = Constant::getNullValue(Ty);
2630 case ValID::t_Constant:
2631 if (ID.ConstantVal->getType() != Ty) {
2632 // Allow a constant struct with a single member to be converted
2633 // to a union, if the union has a member which is the same type
2634 // as the struct member.
2635 if (const UnionType* utype = dyn_cast<UnionType>(Ty)) {
2636 return ParseUnionValue(utype, ID, V);
2639 return Error(ID.Loc, "constant expression type mismatch");
2647 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2650 return ParseValID(ID, &PFS) ||
2651 ConvertValIDToValue(Ty, ID, V, &PFS);
2654 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2655 PATypeHolder T(Type::getVoidTy(Context));
2656 return ParseType(T) ||
2657 ParseValue(T, V, PFS);
2660 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2661 PerFunctionState &PFS) {
2664 if (ParseTypeAndValue(V, PFS)) return true;
2665 if (!isa<BasicBlock>(V))
2666 return Error(Loc, "expected a basic block");
2667 BB = cast<BasicBlock>(V);
2671 bool LLParser::ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V) {
2672 if (const StructType* stype = dyn_cast<StructType>(ID.ConstantVal->getType())) {
2673 if (stype->getNumContainedTypes() != 1)
2674 return Error(ID.Loc, "constant expression type mismatch");
2675 int index = utype->getElementTypeIndex(stype->getContainedType(0));
2677 return Error(ID.Loc, "initializer type is not a member of the union");
2679 V = ConstantUnion::get(
2680 utype, cast<Constant>(ID.ConstantVal->getOperand(0)));
2684 return Error(ID.Loc, "constant expression type mismatch");
2689 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2690 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2691 /// OptionalAlign OptGC
2692 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2693 // Parse the linkage.
2694 LocTy LinkageLoc = Lex.getLoc();
2697 unsigned Visibility, RetAttrs;
2699 PATypeHolder RetType(Type::getVoidTy(Context));
2700 LocTy RetTypeLoc = Lex.getLoc();
2701 if (ParseOptionalLinkage(Linkage) ||
2702 ParseOptionalVisibility(Visibility) ||
2703 ParseOptionalCallingConv(CC) ||
2704 ParseOptionalAttrs(RetAttrs, 1) ||
2705 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2708 // Verify that the linkage is ok.
2709 switch ((GlobalValue::LinkageTypes)Linkage) {
2710 case GlobalValue::ExternalLinkage:
2711 break; // always ok.
2712 case GlobalValue::DLLImportLinkage:
2713 case GlobalValue::ExternalWeakLinkage:
2715 return Error(LinkageLoc, "invalid linkage for function definition");
2717 case GlobalValue::PrivateLinkage:
2718 case GlobalValue::LinkerPrivateLinkage:
2719 case GlobalValue::LinkerPrivateWeakLinkage:
2720 case GlobalValue::InternalLinkage:
2721 case GlobalValue::AvailableExternallyLinkage:
2722 case GlobalValue::LinkOnceAnyLinkage:
2723 case GlobalValue::LinkOnceODRLinkage:
2724 case GlobalValue::WeakAnyLinkage:
2725 case GlobalValue::WeakODRLinkage:
2726 case GlobalValue::DLLExportLinkage:
2728 return Error(LinkageLoc, "invalid linkage for function declaration");
2730 case GlobalValue::AppendingLinkage:
2731 case GlobalValue::CommonLinkage:
2732 return Error(LinkageLoc, "invalid function linkage type");
2735 if (!FunctionType::isValidReturnType(RetType) ||
2736 RetType->isOpaqueTy())
2737 return Error(RetTypeLoc, "invalid function return type");
2739 LocTy NameLoc = Lex.getLoc();
2741 std::string FunctionName;
2742 if (Lex.getKind() == lltok::GlobalVar) {
2743 FunctionName = Lex.getStrVal();
2744 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2745 unsigned NameID = Lex.getUIntVal();
2747 if (NameID != NumberedVals.size())
2748 return TokError("function expected to be numbered '%" +
2749 utostr(NumberedVals.size()) + "'");
2751 return TokError("expected function name");
2756 if (Lex.getKind() != lltok::lparen)
2757 return TokError("expected '(' in function argument list");
2759 std::vector<ArgInfo> ArgList;
2762 std::string Section;
2766 if (ParseArgumentList(ArgList, isVarArg, false) ||
2767 ParseOptionalAttrs(FuncAttrs, 2) ||
2768 (EatIfPresent(lltok::kw_section) &&
2769 ParseStringConstant(Section)) ||
2770 ParseOptionalAlignment(Alignment) ||
2771 (EatIfPresent(lltok::kw_gc) &&
2772 ParseStringConstant(GC)))
2775 // If the alignment was parsed as an attribute, move to the alignment field.
2776 if (FuncAttrs & Attribute::Alignment) {
2777 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2778 FuncAttrs &= ~Attribute::Alignment;
2781 // Okay, if we got here, the function is syntactically valid. Convert types
2782 // and do semantic checks.
2783 std::vector<const Type*> ParamTypeList;
2784 SmallVector<AttributeWithIndex, 8> Attrs;
2785 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2787 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2788 if (FuncAttrs & ObsoleteFuncAttrs) {
2789 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2790 FuncAttrs &= ~ObsoleteFuncAttrs;
2793 if (RetAttrs != Attribute::None)
2794 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2796 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2797 ParamTypeList.push_back(ArgList[i].Type);
2798 if (ArgList[i].Attrs != Attribute::None)
2799 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2802 if (FuncAttrs != Attribute::None)
2803 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2805 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2807 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2808 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2810 const FunctionType *FT =
2811 FunctionType::get(RetType, ParamTypeList, isVarArg);
2812 const PointerType *PFT = PointerType::getUnqual(FT);
2815 if (!FunctionName.empty()) {
2816 // If this was a definition of a forward reference, remove the definition
2817 // from the forward reference table and fill in the forward ref.
2818 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2819 ForwardRefVals.find(FunctionName);
2820 if (FRVI != ForwardRefVals.end()) {
2821 Fn = M->getFunction(FunctionName);
2822 if (Fn->getType() != PFT)
2823 return Error(FRVI->second.second, "invalid forward reference to "
2824 "function '" + FunctionName + "' with wrong type!");
2826 ForwardRefVals.erase(FRVI);
2827 } else if ((Fn = M->getFunction(FunctionName))) {
2828 // If this function already exists in the symbol table, then it is
2829 // multiply defined. We accept a few cases for old backwards compat.
2830 // FIXME: Remove this stuff for LLVM 3.0.
2831 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2832 (!Fn->isDeclaration() && isDefine)) {
2833 // If the redefinition has different type or different attributes,
2834 // reject it. If both have bodies, reject it.
2835 return Error(NameLoc, "invalid redefinition of function '" +
2836 FunctionName + "'");
2837 } else if (Fn->isDeclaration()) {
2838 // Make sure to strip off any argument names so we can't get conflicts.
2839 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2843 } else if (M->getNamedValue(FunctionName)) {
2844 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2848 // If this is a definition of a forward referenced function, make sure the
2850 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2851 = ForwardRefValIDs.find(NumberedVals.size());
2852 if (I != ForwardRefValIDs.end()) {
2853 Fn = cast<Function>(I->second.first);
2854 if (Fn->getType() != PFT)
2855 return Error(NameLoc, "type of definition and forward reference of '@" +
2856 utostr(NumberedVals.size()) +"' disagree");
2857 ForwardRefValIDs.erase(I);
2862 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2863 else // Move the forward-reference to the correct spot in the module.
2864 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2866 if (FunctionName.empty())
2867 NumberedVals.push_back(Fn);
2869 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2870 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2871 Fn->setCallingConv(CC);
2872 Fn->setAttributes(PAL);
2873 Fn->setAlignment(Alignment);
2874 Fn->setSection(Section);
2875 if (!GC.empty()) Fn->setGC(GC.c_str());
2877 // Add all of the arguments we parsed to the function.
2878 Function::arg_iterator ArgIt = Fn->arg_begin();
2879 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2880 // If we run out of arguments in the Function prototype, exit early.
2881 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2882 if (ArgIt == Fn->arg_end()) break;
2884 // If the argument has a name, insert it into the argument symbol table.
2885 if (ArgList[i].Name.empty()) continue;
2887 // Set the name, if it conflicted, it will be auto-renamed.
2888 ArgIt->setName(ArgList[i].Name);
2890 if (ArgIt->getNameStr() != ArgList[i].Name)
2891 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2892 ArgList[i].Name + "'");
2899 /// ParseFunctionBody
2900 /// ::= '{' BasicBlock+ '}'
2901 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2903 bool LLParser::ParseFunctionBody(Function &Fn) {
2904 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2905 return TokError("expected '{' in function body");
2906 Lex.Lex(); // eat the {.
2908 int FunctionNumber = -1;
2909 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2911 PerFunctionState PFS(*this, Fn, FunctionNumber);
2913 // We need at least one basic block.
2914 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2915 return TokError("function body requires at least one basic block");
2917 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2918 if (ParseBasicBlock(PFS)) return true;
2923 // Verify function is ok.
2924 return PFS.FinishFunction();
2928 /// ::= LabelStr? Instruction*
2929 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2930 // If this basic block starts out with a name, remember it.
2932 LocTy NameLoc = Lex.getLoc();
2933 if (Lex.getKind() == lltok::LabelStr) {
2934 Name = Lex.getStrVal();
2938 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2939 if (BB == 0) return true;
2941 std::string NameStr;
2943 // Parse the instructions in this block until we get a terminator.
2945 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2947 // This instruction may have three possibilities for a name: a) none
2948 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2949 LocTy NameLoc = Lex.getLoc();
2953 if (Lex.getKind() == lltok::LocalVarID) {
2954 NameID = Lex.getUIntVal();
2956 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2958 } else if (Lex.getKind() == lltok::LocalVar ||
2959 // FIXME: REMOVE IN LLVM 3.0
2960 Lex.getKind() == lltok::StringConstant) {
2961 NameStr = Lex.getStrVal();
2963 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2967 switch (ParseInstruction(Inst, BB, PFS)) {
2968 default: assert(0 && "Unknown ParseInstruction result!");
2969 case InstError: return true;
2971 BB->getInstList().push_back(Inst);
2973 // With a normal result, we check to see if the instruction is followed by
2974 // a comma and metadata.
2975 if (EatIfPresent(lltok::comma))
2976 if (ParseInstructionMetadata(Inst))
2979 case InstExtraComma:
2980 BB->getInstList().push_back(Inst);
2982 // If the instruction parser ate an extra comma at the end of it, it
2983 // *must* be followed by metadata.
2984 if (ParseInstructionMetadata(Inst))
2989 // Set the name on the instruction.
2990 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2991 } while (!isa<TerminatorInst>(Inst));
2996 //===----------------------------------------------------------------------===//
2997 // Instruction Parsing.
2998 //===----------------------------------------------------------------------===//
3000 /// ParseInstruction - Parse one of the many different instructions.
3002 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3003 PerFunctionState &PFS) {
3004 lltok::Kind Token = Lex.getKind();
3005 if (Token == lltok::Eof)
3006 return TokError("found end of file when expecting more instructions");
3007 LocTy Loc = Lex.getLoc();
3008 unsigned KeywordVal = Lex.getUIntVal();
3009 Lex.Lex(); // Eat the keyword.
3012 default: return Error(Loc, "expected instruction opcode");
3013 // Terminator Instructions.
3014 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
3015 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3016 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3017 case lltok::kw_br: return ParseBr(Inst, PFS);
3018 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3019 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3020 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3021 // Binary Operators.
3024 case lltok::kw_mul: {
3027 LocTy ModifierLoc = Lex.getLoc();
3028 if (EatIfPresent(lltok::kw_nuw))
3030 if (EatIfPresent(lltok::kw_nsw)) {
3032 if (EatIfPresent(lltok::kw_nuw))
3035 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3037 if (!Inst->getType()->isIntOrIntVectorTy()) {
3039 return Error(ModifierLoc, "nuw only applies to integer operations");
3041 return Error(ModifierLoc, "nsw only applies to integer operations");
3044 cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3046 cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3050 case lltok::kw_fadd:
3051 case lltok::kw_fsub:
3052 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3054 case lltok::kw_sdiv: {
3056 if (EatIfPresent(lltok::kw_exact))
3058 bool Result = ParseArithmetic(Inst, PFS, KeywordVal, 1);
3061 cast<BinaryOperator>(Inst)->setIsExact(true);
3065 case lltok::kw_udiv:
3066 case lltok::kw_urem:
3067 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3068 case lltok::kw_fdiv:
3069 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3071 case lltok::kw_lshr:
3072 case lltok::kw_ashr:
3075 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3076 case lltok::kw_icmp:
3077 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3079 case lltok::kw_trunc:
3080 case lltok::kw_zext:
3081 case lltok::kw_sext:
3082 case lltok::kw_fptrunc:
3083 case lltok::kw_fpext:
3084 case lltok::kw_bitcast:
3085 case lltok::kw_uitofp:
3086 case lltok::kw_sitofp:
3087 case lltok::kw_fptoui:
3088 case lltok::kw_fptosi:
3089 case lltok::kw_inttoptr:
3090 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3092 case lltok::kw_select: return ParseSelect(Inst, PFS);
3093 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3094 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3095 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3096 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3097 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3098 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3099 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3101 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3102 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
3103 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
3104 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3105 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3106 case lltok::kw_volatile:
3107 if (EatIfPresent(lltok::kw_load))
3108 return ParseLoad(Inst, PFS, true);
3109 else if (EatIfPresent(lltok::kw_store))
3110 return ParseStore(Inst, PFS, true);
3112 return TokError("expected 'load' or 'store'");
3113 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3114 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3115 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3116 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3120 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3121 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3122 if (Opc == Instruction::FCmp) {
3123 switch (Lex.getKind()) {
3124 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3125 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3126 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3127 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3128 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3129 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3130 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3131 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3132 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3133 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3134 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3135 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3136 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3137 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3138 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3139 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3140 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3143 switch (Lex.getKind()) {
3144 default: TokError("expected icmp predicate (e.g. 'eq')");
3145 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3146 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3147 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3148 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3149 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3150 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3151 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3152 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3153 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3154 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3161 //===----------------------------------------------------------------------===//
3162 // Terminator Instructions.
3163 //===----------------------------------------------------------------------===//
3165 /// ParseRet - Parse a return instruction.
3166 /// ::= 'ret' void (',' !dbg, !1)*
3167 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3168 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
3169 /// [[obsolete: LLVM 3.0]]
3170 int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3171 PerFunctionState &PFS) {
3172 PATypeHolder Ty(Type::getVoidTy(Context));
3173 if (ParseType(Ty, true /*void allowed*/)) return true;
3175 if (Ty->isVoidTy()) {
3176 Inst = ReturnInst::Create(Context);
3181 if (ParseValue(Ty, RV, PFS)) return true;
3183 bool ExtraComma = false;
3184 if (EatIfPresent(lltok::comma)) {
3185 // Parse optional custom metadata, e.g. !dbg
3186 if (Lex.getKind() == lltok::MetadataVar) {
3189 // The normal case is one return value.
3190 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3191 // use of 'ret {i32,i32} {i32 1, i32 2}'
3192 SmallVector<Value*, 8> RVs;
3196 // If optional custom metadata, e.g. !dbg is seen then this is the
3198 if (Lex.getKind() == lltok::MetadataVar)
3200 if (ParseTypeAndValue(RV, PFS)) return true;
3202 } while (EatIfPresent(lltok::comma));
3204 RV = UndefValue::get(PFS.getFunction().getReturnType());
3205 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
3206 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3207 BB->getInstList().push_back(I);
3213 Inst = ReturnInst::Create(Context, RV);
3214 return ExtraComma ? InstExtraComma : InstNormal;
3219 /// ::= 'br' TypeAndValue
3220 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3221 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3224 BasicBlock *Op1, *Op2;
3225 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3227 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3228 Inst = BranchInst::Create(BB);
3232 if (Op0->getType() != Type::getInt1Ty(Context))
3233 return Error(Loc, "branch condition must have 'i1' type");
3235 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3236 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3237 ParseToken(lltok::comma, "expected ',' after true destination") ||
3238 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3241 Inst = BranchInst::Create(Op1, Op2, Op0);
3247 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3249 /// ::= (TypeAndValue ',' TypeAndValue)*
3250 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3251 LocTy CondLoc, BBLoc;
3253 BasicBlock *DefaultBB;
3254 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3255 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3256 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3257 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3260 if (!Cond->getType()->isIntegerTy())
3261 return Error(CondLoc, "switch condition must have integer type");
3263 // Parse the jump table pairs.
3264 SmallPtrSet<Value*, 32> SeenCases;
3265 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3266 while (Lex.getKind() != lltok::rsquare) {
3270 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3271 ParseToken(lltok::comma, "expected ',' after case value") ||
3272 ParseTypeAndBasicBlock(DestBB, PFS))
3275 if (!SeenCases.insert(Constant))
3276 return Error(CondLoc, "duplicate case value in switch");
3277 if (!isa<ConstantInt>(Constant))
3278 return Error(CondLoc, "case value is not a constant integer");
3280 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3283 Lex.Lex(); // Eat the ']'.
3285 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3286 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3287 SI->addCase(Table[i].first, Table[i].second);
3294 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3295 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3298 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3299 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3300 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3303 if (!Address->getType()->isPointerTy())
3304 return Error(AddrLoc, "indirectbr address must have pointer type");
3306 // Parse the destination list.
3307 SmallVector<BasicBlock*, 16> DestList;
3309 if (Lex.getKind() != lltok::rsquare) {
3311 if (ParseTypeAndBasicBlock(DestBB, PFS))
3313 DestList.push_back(DestBB);
3315 while (EatIfPresent(lltok::comma)) {
3316 if (ParseTypeAndBasicBlock(DestBB, PFS))
3318 DestList.push_back(DestBB);
3322 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3325 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3326 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3327 IBI->addDestination(DestList[i]);
3334 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3335 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3336 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3337 LocTy CallLoc = Lex.getLoc();
3338 unsigned RetAttrs, FnAttrs;
3340 PATypeHolder RetType(Type::getVoidTy(Context));
3343 SmallVector<ParamInfo, 16> ArgList;
3345 BasicBlock *NormalBB, *UnwindBB;
3346 if (ParseOptionalCallingConv(CC) ||
3347 ParseOptionalAttrs(RetAttrs, 1) ||
3348 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3349 ParseValID(CalleeID) ||
3350 ParseParameterList(ArgList, PFS) ||
3351 ParseOptionalAttrs(FnAttrs, 2) ||
3352 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3353 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3354 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3355 ParseTypeAndBasicBlock(UnwindBB, PFS))
3358 // If RetType is a non-function pointer type, then this is the short syntax
3359 // for the call, which means that RetType is just the return type. Infer the
3360 // rest of the function argument types from the arguments that are present.
3361 const PointerType *PFTy = 0;
3362 const FunctionType *Ty = 0;
3363 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3364 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3365 // Pull out the types of all of the arguments...
3366 std::vector<const Type*> ParamTypes;
3367 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3368 ParamTypes.push_back(ArgList[i].V->getType());
3370 if (!FunctionType::isValidReturnType(RetType))
3371 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3373 Ty = FunctionType::get(RetType, ParamTypes, false);
3374 PFTy = PointerType::getUnqual(Ty);
3377 // Look up the callee.
3379 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3381 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3382 // function attributes.
3383 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3384 if (FnAttrs & ObsoleteFuncAttrs) {
3385 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3386 FnAttrs &= ~ObsoleteFuncAttrs;
3389 // Set up the Attributes for the function.
3390 SmallVector<AttributeWithIndex, 8> Attrs;
3391 if (RetAttrs != Attribute::None)
3392 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3394 SmallVector<Value*, 8> Args;
3396 // Loop through FunctionType's arguments and ensure they are specified
3397 // correctly. Also, gather any parameter attributes.
3398 FunctionType::param_iterator I = Ty->param_begin();
3399 FunctionType::param_iterator E = Ty->param_end();
3400 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3401 const Type *ExpectedTy = 0;
3404 } else if (!Ty->isVarArg()) {
3405 return Error(ArgList[i].Loc, "too many arguments specified");
3408 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3409 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3410 ExpectedTy->getDescription() + "'");
3411 Args.push_back(ArgList[i].V);
3412 if (ArgList[i].Attrs != Attribute::None)
3413 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3417 return Error(CallLoc, "not enough parameters specified for call");
3419 if (FnAttrs != Attribute::None)
3420 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3422 // Finish off the Attributes and check them
3423 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3425 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3426 Args.begin(), Args.end());
3427 II->setCallingConv(CC);
3428 II->setAttributes(PAL);
3435 //===----------------------------------------------------------------------===//
3436 // Binary Operators.
3437 //===----------------------------------------------------------------------===//
3440 /// ::= ArithmeticOps TypeAndValue ',' Value
3442 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3443 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3444 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3445 unsigned Opc, unsigned OperandType) {
3446 LocTy Loc; Value *LHS, *RHS;
3447 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3448 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3449 ParseValue(LHS->getType(), RHS, PFS))
3453 switch (OperandType) {
3454 default: llvm_unreachable("Unknown operand type!");
3455 case 0: // int or FP.
3456 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3457 LHS->getType()->isFPOrFPVectorTy();
3459 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3460 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3464 return Error(Loc, "invalid operand type for instruction");
3466 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3471 /// ::= ArithmeticOps TypeAndValue ',' Value {
3472 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3474 LocTy Loc; Value *LHS, *RHS;
3475 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3476 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3477 ParseValue(LHS->getType(), RHS, PFS))
3480 if (!LHS->getType()->isIntOrIntVectorTy())
3481 return Error(Loc,"instruction requires integer or integer vector operands");
3483 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3489 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3490 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3491 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3493 // Parse the integer/fp comparison predicate.
3497 if (ParseCmpPredicate(Pred, Opc) ||
3498 ParseTypeAndValue(LHS, Loc, PFS) ||
3499 ParseToken(lltok::comma, "expected ',' after compare value") ||
3500 ParseValue(LHS->getType(), RHS, PFS))
3503 if (Opc == Instruction::FCmp) {
3504 if (!LHS->getType()->isFPOrFPVectorTy())
3505 return Error(Loc, "fcmp requires floating point operands");
3506 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3508 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3509 if (!LHS->getType()->isIntOrIntVectorTy() &&
3510 !LHS->getType()->isPointerTy())
3511 return Error(Loc, "icmp requires integer operands");
3512 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3517 //===----------------------------------------------------------------------===//
3518 // Other Instructions.
3519 //===----------------------------------------------------------------------===//
3523 /// ::= CastOpc TypeAndValue 'to' Type
3524 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3526 LocTy Loc; Value *Op;
3527 PATypeHolder DestTy(Type::getVoidTy(Context));
3528 if (ParseTypeAndValue(Op, Loc, PFS) ||
3529 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3533 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3534 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3535 return Error(Loc, "invalid cast opcode for cast from '" +
3536 Op->getType()->getDescription() + "' to '" +
3537 DestTy->getDescription() + "'");
3539 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3544 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3545 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3547 Value *Op0, *Op1, *Op2;
3548 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3549 ParseToken(lltok::comma, "expected ',' after select condition") ||
3550 ParseTypeAndValue(Op1, PFS) ||
3551 ParseToken(lltok::comma, "expected ',' after select value") ||
3552 ParseTypeAndValue(Op2, PFS))
3555 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3556 return Error(Loc, Reason);
3558 Inst = SelectInst::Create(Op0, Op1, Op2);
3563 /// ::= 'va_arg' TypeAndValue ',' Type
3564 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3566 PATypeHolder EltTy(Type::getVoidTy(Context));
3568 if (ParseTypeAndValue(Op, PFS) ||
3569 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3570 ParseType(EltTy, TypeLoc))
3573 if (!EltTy->isFirstClassType())
3574 return Error(TypeLoc, "va_arg requires operand with first class type");
3576 Inst = new VAArgInst(Op, EltTy);
3580 /// ParseExtractElement
3581 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3582 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3585 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3586 ParseToken(lltok::comma, "expected ',' after extract value") ||
3587 ParseTypeAndValue(Op1, PFS))
3590 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3591 return Error(Loc, "invalid extractelement operands");
3593 Inst = ExtractElementInst::Create(Op0, Op1);
3597 /// ParseInsertElement
3598 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3599 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3601 Value *Op0, *Op1, *Op2;
3602 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3603 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3604 ParseTypeAndValue(Op1, PFS) ||
3605 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3606 ParseTypeAndValue(Op2, PFS))
3609 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3610 return Error(Loc, "invalid insertelement operands");
3612 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3616 /// ParseShuffleVector
3617 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3618 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3620 Value *Op0, *Op1, *Op2;
3621 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3622 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3623 ParseTypeAndValue(Op1, PFS) ||
3624 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3625 ParseTypeAndValue(Op2, PFS))
3628 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3629 return Error(Loc, "invalid extractelement operands");
3631 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3636 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3637 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3638 PATypeHolder Ty(Type::getVoidTy(Context));
3640 LocTy TypeLoc = Lex.getLoc();
3642 if (ParseType(Ty) ||
3643 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3644 ParseValue(Ty, Op0, PFS) ||
3645 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3646 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3647 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3650 bool AteExtraComma = false;
3651 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3653 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3655 if (!EatIfPresent(lltok::comma))
3658 if (Lex.getKind() == lltok::MetadataVar) {
3659 AteExtraComma = true;
3663 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3664 ParseValue(Ty, Op0, PFS) ||
3665 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3666 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3667 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3671 if (!Ty->isFirstClassType())
3672 return Error(TypeLoc, "phi node must have first class type");
3674 PHINode *PN = PHINode::Create(Ty);
3675 PN->reserveOperandSpace(PHIVals.size());
3676 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3677 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3679 return AteExtraComma ? InstExtraComma : InstNormal;
3683 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3684 /// ParameterList OptionalAttrs
3685 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3687 unsigned RetAttrs, FnAttrs;
3689 PATypeHolder RetType(Type::getVoidTy(Context));
3692 SmallVector<ParamInfo, 16> ArgList;
3693 LocTy CallLoc = Lex.getLoc();
3695 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3696 ParseOptionalCallingConv(CC) ||
3697 ParseOptionalAttrs(RetAttrs, 1) ||
3698 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3699 ParseValID(CalleeID) ||
3700 ParseParameterList(ArgList, PFS) ||
3701 ParseOptionalAttrs(FnAttrs, 2))
3704 // If RetType is a non-function pointer type, then this is the short syntax
3705 // for the call, which means that RetType is just the return type. Infer the
3706 // rest of the function argument types from the arguments that are present.
3707 const PointerType *PFTy = 0;
3708 const FunctionType *Ty = 0;
3709 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3710 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3711 // Pull out the types of all of the arguments...
3712 std::vector<const Type*> ParamTypes;
3713 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3714 ParamTypes.push_back(ArgList[i].V->getType());
3716 if (!FunctionType::isValidReturnType(RetType))
3717 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3719 Ty = FunctionType::get(RetType, ParamTypes, false);
3720 PFTy = PointerType::getUnqual(Ty);
3723 // Look up the callee.
3725 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3727 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3728 // function attributes.
3729 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3730 if (FnAttrs & ObsoleteFuncAttrs) {
3731 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3732 FnAttrs &= ~ObsoleteFuncAttrs;
3735 // Set up the Attributes for the function.
3736 SmallVector<AttributeWithIndex, 8> Attrs;
3737 if (RetAttrs != Attribute::None)
3738 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3740 SmallVector<Value*, 8> Args;
3742 // Loop through FunctionType's arguments and ensure they are specified
3743 // correctly. Also, gather any parameter attributes.
3744 FunctionType::param_iterator I = Ty->param_begin();
3745 FunctionType::param_iterator E = Ty->param_end();
3746 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3747 const Type *ExpectedTy = 0;
3750 } else if (!Ty->isVarArg()) {
3751 return Error(ArgList[i].Loc, "too many arguments specified");
3754 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3755 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3756 ExpectedTy->getDescription() + "'");
3757 Args.push_back(ArgList[i].V);
3758 if (ArgList[i].Attrs != Attribute::None)
3759 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3763 return Error(CallLoc, "not enough parameters specified for call");
3765 if (FnAttrs != Attribute::None)
3766 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3768 // Finish off the Attributes and check them
3769 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3771 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3772 CI->setTailCall(isTail);
3773 CI->setCallingConv(CC);
3774 CI->setAttributes(PAL);
3779 //===----------------------------------------------------------------------===//
3780 // Memory Instructions.
3781 //===----------------------------------------------------------------------===//
3784 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3785 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3786 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3787 BasicBlock* BB, bool isAlloca) {
3788 PATypeHolder Ty(Type::getVoidTy(Context));
3791 unsigned Alignment = 0;
3792 if (ParseType(Ty)) return true;
3794 bool AteExtraComma = false;
3795 if (EatIfPresent(lltok::comma)) {
3796 if (Lex.getKind() == lltok::kw_align) {
3797 if (ParseOptionalAlignment(Alignment)) return true;
3798 } else if (Lex.getKind() == lltok::MetadataVar) {
3799 AteExtraComma = true;
3801 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3802 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3807 if (Size && !Size->getType()->isIntegerTy())
3808 return Error(SizeLoc, "element count must have integer type");
3811 Inst = new AllocaInst(Ty, Size, Alignment);
3812 return AteExtraComma ? InstExtraComma : InstNormal;
3815 // Autoupgrade old malloc instruction to malloc call.
3816 // FIXME: Remove in LLVM 3.0.
3817 if (Size && !Size->getType()->isIntegerTy(32))
3818 return Error(SizeLoc, "element count must be i32");
3819 const Type *IntPtrTy = Type::getInt32Ty(Context);
3820 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3821 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
3823 // Prototype malloc as "void *(int32)".
3824 // This function is renamed as "malloc" in ValidateEndOfModule().
3825 MallocF = cast<Function>(
3826 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
3827 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
3828 return AteExtraComma ? InstExtraComma : InstNormal;
3832 /// ::= 'free' TypeAndValue
3833 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3835 Value *Val; LocTy Loc;
3836 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3837 if (!Val->getType()->isPointerTy())
3838 return Error(Loc, "operand to free must be a pointer");
3839 Inst = CallInst::CreateFree(Val, BB);
3844 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3845 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3847 Value *Val; LocTy Loc;
3848 unsigned Alignment = 0;
3849 bool AteExtraComma = false;
3850 if (ParseTypeAndValue(Val, Loc, PFS) ||
3851 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3854 if (!Val->getType()->isPointerTy() ||
3855 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3856 return Error(Loc, "load operand must be a pointer to a first class type");
3858 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3859 return AteExtraComma ? InstExtraComma : InstNormal;
3863 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3864 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3866 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3867 unsigned Alignment = 0;
3868 bool AteExtraComma = false;
3869 if (ParseTypeAndValue(Val, Loc, PFS) ||
3870 ParseToken(lltok::comma, "expected ',' after store operand") ||
3871 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3872 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3875 if (!Ptr->getType()->isPointerTy())
3876 return Error(PtrLoc, "store operand must be a pointer");
3877 if (!Val->getType()->isFirstClassType())
3878 return Error(Loc, "store operand must be a first class value");
3879 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3880 return Error(Loc, "stored value and pointer type do not match");
3882 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3883 return AteExtraComma ? InstExtraComma : InstNormal;
3887 /// ::= 'getresult' TypeAndValue ',' i32
3888 /// FIXME: Remove support for getresult in LLVM 3.0
3889 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3890 Value *Val; LocTy ValLoc, EltLoc;
3892 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3893 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3894 ParseUInt32(Element, EltLoc))
3897 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
3898 return Error(ValLoc, "getresult inst requires an aggregate operand");
3899 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3900 return Error(EltLoc, "invalid getresult index for value");
3901 Inst = ExtractValueInst::Create(Val, Element);
3905 /// ParseGetElementPtr
3906 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3907 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3908 Value *Ptr, *Val; LocTy Loc, EltLoc;
3910 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3912 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3914 if (!Ptr->getType()->isPointerTy())
3915 return Error(Loc, "base of getelementptr must be a pointer");
3917 SmallVector<Value*, 16> Indices;
3918 bool AteExtraComma = false;
3919 while (EatIfPresent(lltok::comma)) {
3920 if (Lex.getKind() == lltok::MetadataVar) {
3921 AteExtraComma = true;
3924 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3925 if (!Val->getType()->isIntegerTy())
3926 return Error(EltLoc, "getelementptr index must be an integer");
3927 Indices.push_back(Val);
3930 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3931 Indices.begin(), Indices.end()))
3932 return Error(Loc, "invalid getelementptr indices");
3933 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3935 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3936 return AteExtraComma ? InstExtraComma : InstNormal;
3939 /// ParseExtractValue
3940 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3941 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3942 Value *Val; LocTy Loc;
3943 SmallVector<unsigned, 4> Indices;
3945 if (ParseTypeAndValue(Val, Loc, PFS) ||
3946 ParseIndexList(Indices, AteExtraComma))
3949 if (!Val->getType()->isAggregateType())
3950 return Error(Loc, "extractvalue operand must be aggregate type");
3952 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3954 return Error(Loc, "invalid indices for extractvalue");
3955 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3956 return AteExtraComma ? InstExtraComma : InstNormal;
3959 /// ParseInsertValue
3960 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3961 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3962 Value *Val0, *Val1; LocTy Loc0, Loc1;
3963 SmallVector<unsigned, 4> Indices;
3965 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3966 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3967 ParseTypeAndValue(Val1, Loc1, PFS) ||
3968 ParseIndexList(Indices, AteExtraComma))
3971 if (!Val0->getType()->isAggregateType())
3972 return Error(Loc0, "insertvalue operand must be aggregate type");
3974 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3976 return Error(Loc0, "invalid indices for insertvalue");
3977 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3978 return AteExtraComma ? InstExtraComma : InstNormal;
3981 //===----------------------------------------------------------------------===//
3982 // Embedded metadata.
3983 //===----------------------------------------------------------------------===//
3985 /// ParseMDNodeVector
3986 /// ::= Element (',' Element)*
3988 /// ::= 'null' | TypeAndValue
3989 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3990 PerFunctionState *PFS) {
3991 // Check for an empty list.
3992 if (Lex.getKind() == lltok::rbrace)
3996 // Null is a special case since it is typeless.
3997 if (EatIfPresent(lltok::kw_null)) {
4003 PATypeHolder Ty(Type::getVoidTy(Context));
4005 if (ParseType(Ty) || ParseValID(ID, PFS) ||
4006 ConvertValIDToValue(Ty, ID, V, PFS))
4010 } while (EatIfPresent(lltok::comma));