1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 /// Run: module ::= toplevelentity*
30 bool LLParser::Run() {
34 return ParseTopLevelEntities() ||
35 ValidateEndOfModule();
38 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
40 bool LLParser::ValidateEndOfModule() {
41 // Handle any instruction metadata forward references.
42 if (!ForwardRefInstMetadata.empty()) {
43 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
44 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
46 Instruction *Inst = I->first;
47 const std::vector<MDRef> &MDList = I->second;
49 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
50 unsigned SlotNo = MDList[i].MDSlot;
52 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
53 return Error(MDList[i].Loc, "use of undefined metadata '!" +
55 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
58 ForwardRefInstMetadata.clear();
62 // Update auto-upgraded malloc calls to "malloc".
63 // FIXME: Remove in LLVM 3.0.
65 MallocF->setName("malloc");
66 // If setName() does not set the name to "malloc", then there is already a
67 // declaration of "malloc". In that case, iterate over all calls to MallocF
68 // and get them to call the declared "malloc" instead.
69 if (MallocF->getName() != "malloc") {
70 Constant *RealMallocF = M->getFunction("malloc");
71 if (RealMallocF->getType() != MallocF->getType())
72 RealMallocF = ConstantExpr::getBitCast(RealMallocF, MallocF->getType());
73 MallocF->replaceAllUsesWith(RealMallocF);
74 MallocF->eraseFromParent();
80 // If there are entries in ForwardRefBlockAddresses at this point, they are
81 // references after the function was defined. Resolve those now.
82 while (!ForwardRefBlockAddresses.empty()) {
83 // Okay, we are referencing an already-parsed function, resolve them now.
85 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
86 if (Fn.Kind == ValID::t_GlobalName)
87 TheFn = M->getFunction(Fn.StrVal);
88 else if (Fn.UIntVal < NumberedVals.size())
89 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
92 return Error(Fn.Loc, "unknown function referenced by blockaddress");
94 // Resolve all these references.
95 if (ResolveForwardRefBlockAddresses(TheFn,
96 ForwardRefBlockAddresses.begin()->second,
100 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
104 if (!ForwardRefTypes.empty())
105 return Error(ForwardRefTypes.begin()->second.second,
106 "use of undefined type named '" +
107 ForwardRefTypes.begin()->first + "'");
108 if (!ForwardRefTypeIDs.empty())
109 return Error(ForwardRefTypeIDs.begin()->second.second,
110 "use of undefined type '%" +
111 Twine(ForwardRefTypeIDs.begin()->first) + "'");
113 if (!ForwardRefVals.empty())
114 return Error(ForwardRefVals.begin()->second.second,
115 "use of undefined value '@" + ForwardRefVals.begin()->first +
118 if (!ForwardRefValIDs.empty())
119 return Error(ForwardRefValIDs.begin()->second.second,
120 "use of undefined value '@" +
121 Twine(ForwardRefValIDs.begin()->first) + "'");
123 if (!ForwardRefMDNodes.empty())
124 return Error(ForwardRefMDNodes.begin()->second.second,
125 "use of undefined metadata '!" +
126 Twine(ForwardRefMDNodes.begin()->first) + "'");
129 // Look for intrinsic functions and CallInst that need to be upgraded
130 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
131 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
133 // Check debug info intrinsics.
134 CheckDebugInfoIntrinsics(M);
138 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
139 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
140 PerFunctionState *PFS) {
141 // Loop over all the references, resolving them.
142 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
145 if (Refs[i].first.Kind == ValID::t_LocalName)
146 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
148 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
149 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
150 return Error(Refs[i].first.Loc,
151 "cannot take address of numeric label after the function is defined");
153 Res = dyn_cast_or_null<BasicBlock>(
154 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
158 return Error(Refs[i].first.Loc,
159 "referenced value is not a basic block");
161 // Get the BlockAddress for this and update references to use it.
162 BlockAddress *BA = BlockAddress::get(TheFn, Res);
163 Refs[i].second->replaceAllUsesWith(BA);
164 Refs[i].second->eraseFromParent();
170 //===----------------------------------------------------------------------===//
171 // Top-Level Entities
172 //===----------------------------------------------------------------------===//
174 bool LLParser::ParseTopLevelEntities() {
176 switch (Lex.getKind()) {
177 default: return TokError("expected top-level entity");
178 case lltok::Eof: return false;
179 //case lltok::kw_define:
180 case lltok::kw_declare: if (ParseDeclare()) return true; break;
181 case lltok::kw_define: if (ParseDefine()) return true; break;
182 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
183 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
184 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
185 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
186 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
187 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
188 case lltok::LocalVar: if (ParseNamedType()) return true; break;
189 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
190 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
191 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
192 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
194 // The Global variable production with no name can have many different
195 // optional leading prefixes, the production is:
196 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
197 // OptionalAddrSpace OptionalUnNammedAddr
198 // ('constant'|'global') ...
199 case lltok::kw_private: // OptionalLinkage
200 case lltok::kw_linker_private: // OptionalLinkage
201 case lltok::kw_linker_private_weak: // OptionalLinkage
202 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
203 case lltok::kw_internal: // OptionalLinkage
204 case lltok::kw_weak: // OptionalLinkage
205 case lltok::kw_weak_odr: // OptionalLinkage
206 case lltok::kw_linkonce: // OptionalLinkage
207 case lltok::kw_linkonce_odr: // OptionalLinkage
208 case lltok::kw_appending: // OptionalLinkage
209 case lltok::kw_dllexport: // OptionalLinkage
210 case lltok::kw_common: // OptionalLinkage
211 case lltok::kw_dllimport: // OptionalLinkage
212 case lltok::kw_extern_weak: // OptionalLinkage
213 case lltok::kw_external: { // OptionalLinkage
214 unsigned Linkage, Visibility;
215 if (ParseOptionalLinkage(Linkage) ||
216 ParseOptionalVisibility(Visibility) ||
217 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
221 case lltok::kw_default: // OptionalVisibility
222 case lltok::kw_hidden: // OptionalVisibility
223 case lltok::kw_protected: { // OptionalVisibility
225 if (ParseOptionalVisibility(Visibility) ||
226 ParseGlobal("", SMLoc(), 0, false, Visibility))
231 case lltok::kw_thread_local: // OptionalThreadLocal
232 case lltok::kw_addrspace: // OptionalAddrSpace
233 case lltok::kw_constant: // GlobalType
234 case lltok::kw_global: // GlobalType
235 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
243 /// ::= 'module' 'asm' STRINGCONSTANT
244 bool LLParser::ParseModuleAsm() {
245 assert(Lex.getKind() == lltok::kw_module);
249 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
250 ParseStringConstant(AsmStr)) return true;
252 M->appendModuleInlineAsm(AsmStr);
257 /// ::= 'target' 'triple' '=' STRINGCONSTANT
258 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
259 bool LLParser::ParseTargetDefinition() {
260 assert(Lex.getKind() == lltok::kw_target);
263 default: return TokError("unknown target property");
264 case lltok::kw_triple:
266 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
267 ParseStringConstant(Str))
269 M->setTargetTriple(Str);
271 case lltok::kw_datalayout:
273 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
274 ParseStringConstant(Str))
276 M->setDataLayout(Str);
282 /// ::= 'deplibs' '=' '[' ']'
283 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
284 bool LLParser::ParseDepLibs() {
285 assert(Lex.getKind() == lltok::kw_deplibs);
287 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
288 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
291 if (EatIfPresent(lltok::rsquare))
295 if (ParseStringConstant(Str)) return true;
298 while (EatIfPresent(lltok::comma)) {
299 if (ParseStringConstant(Str)) return true;
303 return ParseToken(lltok::rsquare, "expected ']' at end of list");
306 /// ParseUnnamedType:
308 /// ::= LocalVarID '=' 'type' type
309 bool LLParser::ParseUnnamedType() {
310 unsigned TypeID = NumberedTypes.size();
312 // Handle the LocalVarID form.
313 if (Lex.getKind() == lltok::LocalVarID) {
314 if (Lex.getUIntVal() != TypeID)
315 return Error(Lex.getLoc(), "type expected to be numbered '%" +
316 Twine(TypeID) + "'");
317 Lex.Lex(); // eat LocalVarID;
319 if (ParseToken(lltok::equal, "expected '=' after name"))
323 LocTy TypeLoc = Lex.getLoc();
324 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
326 PATypeHolder Ty(Type::getVoidTy(Context));
327 if (ParseType(Ty)) return true;
329 // See if this type was previously referenced.
330 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
331 FI = ForwardRefTypeIDs.find(TypeID);
332 if (FI != ForwardRefTypeIDs.end()) {
333 if (FI->second.first.get() == Ty)
334 return Error(TypeLoc, "self referential type is invalid");
336 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
337 Ty = FI->second.first.get();
338 ForwardRefTypeIDs.erase(FI);
341 NumberedTypes.push_back(Ty);
347 /// ::= LocalVar '=' 'type' type
348 bool LLParser::ParseNamedType() {
349 std::string Name = Lex.getStrVal();
350 LocTy NameLoc = Lex.getLoc();
351 Lex.Lex(); // eat LocalVar.
353 PATypeHolder Ty(Type::getVoidTy(Context));
355 if (ParseToken(lltok::equal, "expected '=' after name") ||
356 ParseToken(lltok::kw_type, "expected 'type' after name") ||
360 // Set the type name, checking for conflicts as we do so.
361 bool AlreadyExists = M->addTypeName(Name, Ty);
362 if (!AlreadyExists) return false;
364 // See if this type is a forward reference. We need to eagerly resolve
365 // types to allow recursive type redefinitions below.
366 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
367 FI = ForwardRefTypes.find(Name);
368 if (FI != ForwardRefTypes.end()) {
369 if (FI->second.first.get() == Ty)
370 return Error(NameLoc, "self referential type is invalid");
372 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
373 Ty = FI->second.first.get();
374 ForwardRefTypes.erase(FI);
377 // Inserting a name that is already defined, get the existing name.
378 const Type *Existing = M->getTypeByName(Name);
379 assert(Existing && "Conflict but no matching type?!");
381 // Otherwise, this is an attempt to redefine a type. That's okay if
382 // the redefinition is identical to the original.
383 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
384 if (Existing == Ty) return false;
386 // Any other kind of (non-equivalent) redefinition is an error.
387 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
388 Ty->getDescription() + "'");
393 /// ::= 'declare' FunctionHeader
394 bool LLParser::ParseDeclare() {
395 assert(Lex.getKind() == lltok::kw_declare);
399 return ParseFunctionHeader(F, false);
403 /// ::= 'define' FunctionHeader '{' ...
404 bool LLParser::ParseDefine() {
405 assert(Lex.getKind() == lltok::kw_define);
409 return ParseFunctionHeader(F, true) ||
410 ParseFunctionBody(*F);
416 bool LLParser::ParseGlobalType(bool &IsConstant) {
417 if (Lex.getKind() == lltok::kw_constant)
419 else if (Lex.getKind() == lltok::kw_global)
423 return TokError("expected 'global' or 'constant'");
429 /// ParseUnnamedGlobal:
430 /// OptionalVisibility ALIAS ...
431 /// OptionalLinkage OptionalVisibility ... -> global variable
432 /// GlobalID '=' OptionalVisibility ALIAS ...
433 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
434 bool LLParser::ParseUnnamedGlobal() {
435 unsigned VarID = NumberedVals.size();
437 LocTy NameLoc = Lex.getLoc();
439 // Handle the GlobalID form.
440 if (Lex.getKind() == lltok::GlobalID) {
441 if (Lex.getUIntVal() != VarID)
442 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
444 Lex.Lex(); // eat GlobalID;
446 if (ParseToken(lltok::equal, "expected '=' after name"))
451 unsigned Linkage, Visibility;
452 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
453 ParseOptionalVisibility(Visibility))
456 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
457 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
458 return ParseAlias(Name, NameLoc, Visibility);
461 /// ParseNamedGlobal:
462 /// GlobalVar '=' OptionalVisibility ALIAS ...
463 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
464 bool LLParser::ParseNamedGlobal() {
465 assert(Lex.getKind() == lltok::GlobalVar);
466 LocTy NameLoc = Lex.getLoc();
467 std::string Name = Lex.getStrVal();
471 unsigned Linkage, Visibility;
472 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
473 ParseOptionalLinkage(Linkage, HasLinkage) ||
474 ParseOptionalVisibility(Visibility))
477 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
478 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
479 return ParseAlias(Name, NameLoc, Visibility);
483 // ::= '!' STRINGCONSTANT
484 bool LLParser::ParseMDString(MDString *&Result) {
486 if (ParseStringConstant(Str)) return true;
487 Result = MDString::get(Context, Str);
492 // ::= '!' MDNodeNumber
494 /// This version of ParseMDNodeID returns the slot number and null in the case
495 /// of a forward reference.
496 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
497 // !{ ..., !42, ... }
498 if (ParseUInt32(SlotNo)) return true;
500 // Check existing MDNode.
501 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
502 Result = NumberedMetadata[SlotNo];
508 bool LLParser::ParseMDNodeID(MDNode *&Result) {
509 // !{ ..., !42, ... }
511 if (ParseMDNodeID(Result, MID)) return true;
513 // If not a forward reference, just return it now.
514 if (Result) return false;
516 // Otherwise, create MDNode forward reference.
517 MDNode *FwdNode = MDNode::getTemporary(Context, 0, 0);
518 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
520 if (NumberedMetadata.size() <= MID)
521 NumberedMetadata.resize(MID+1);
522 NumberedMetadata[MID] = FwdNode;
527 /// ParseNamedMetadata:
528 /// !foo = !{ !1, !2 }
529 bool LLParser::ParseNamedMetadata() {
530 assert(Lex.getKind() == lltok::MetadataVar);
531 std::string Name = Lex.getStrVal();
534 if (ParseToken(lltok::equal, "expected '=' here") ||
535 ParseToken(lltok::exclaim, "Expected '!' here") ||
536 ParseToken(lltok::lbrace, "Expected '{' here"))
539 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
540 if (Lex.getKind() != lltok::rbrace)
542 if (ParseToken(lltok::exclaim, "Expected '!' here"))
546 if (ParseMDNodeID(N)) return true;
548 } while (EatIfPresent(lltok::comma));
550 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
556 /// ParseStandaloneMetadata:
558 bool LLParser::ParseStandaloneMetadata() {
559 assert(Lex.getKind() == lltok::exclaim);
561 unsigned MetadataID = 0;
564 PATypeHolder Ty(Type::getVoidTy(Context));
565 SmallVector<Value *, 16> Elts;
566 if (ParseUInt32(MetadataID) ||
567 ParseToken(lltok::equal, "expected '=' here") ||
568 ParseType(Ty, TyLoc) ||
569 ParseToken(lltok::exclaim, "Expected '!' here") ||
570 ParseToken(lltok::lbrace, "Expected '{' here") ||
571 ParseMDNodeVector(Elts, NULL) ||
572 ParseToken(lltok::rbrace, "expected end of metadata node"))
575 MDNode *Init = MDNode::get(Context, Elts.data(), Elts.size());
577 // See if this was forward referenced, if so, handle it.
578 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
579 FI = ForwardRefMDNodes.find(MetadataID);
580 if (FI != ForwardRefMDNodes.end()) {
581 MDNode *Temp = FI->second.first;
582 Temp->replaceAllUsesWith(Init);
583 MDNode::deleteTemporary(Temp);
584 ForwardRefMDNodes.erase(FI);
586 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
588 if (MetadataID >= NumberedMetadata.size())
589 NumberedMetadata.resize(MetadataID+1);
591 if (NumberedMetadata[MetadataID] != 0)
592 return TokError("Metadata id is already used");
593 NumberedMetadata[MetadataID] = Init;
600 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
603 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
604 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
606 /// Everything through visibility has already been parsed.
608 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
609 unsigned Visibility) {
610 assert(Lex.getKind() == lltok::kw_alias);
613 LocTy LinkageLoc = Lex.getLoc();
614 if (ParseOptionalLinkage(Linkage))
617 if (Linkage != GlobalValue::ExternalLinkage &&
618 Linkage != GlobalValue::WeakAnyLinkage &&
619 Linkage != GlobalValue::WeakODRLinkage &&
620 Linkage != GlobalValue::InternalLinkage &&
621 Linkage != GlobalValue::PrivateLinkage &&
622 Linkage != GlobalValue::LinkerPrivateLinkage &&
623 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
624 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
625 return Error(LinkageLoc, "invalid linkage type for alias");
628 LocTy AliaseeLoc = Lex.getLoc();
629 if (Lex.getKind() != lltok::kw_bitcast &&
630 Lex.getKind() != lltok::kw_getelementptr) {
631 if (ParseGlobalTypeAndValue(Aliasee)) return true;
633 // The bitcast dest type is not present, it is implied by the dest type.
635 if (ParseValID(ID)) return true;
636 if (ID.Kind != ValID::t_Constant)
637 return Error(AliaseeLoc, "invalid aliasee");
638 Aliasee = ID.ConstantVal;
641 if (!Aliasee->getType()->isPointerTy())
642 return Error(AliaseeLoc, "alias must have pointer type");
644 // Okay, create the alias but do not insert it into the module yet.
645 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
646 (GlobalValue::LinkageTypes)Linkage, Name,
648 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
650 // See if this value already exists in the symbol table. If so, it is either
651 // a redefinition or a definition of a forward reference.
652 if (GlobalValue *Val = M->getNamedValue(Name)) {
653 // See if this was a redefinition. If so, there is no entry in
655 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
656 I = ForwardRefVals.find(Name);
657 if (I == ForwardRefVals.end())
658 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
660 // Otherwise, this was a definition of forward ref. Verify that types
662 if (Val->getType() != GA->getType())
663 return Error(NameLoc,
664 "forward reference and definition of alias have different types");
666 // If they agree, just RAUW the old value with the alias and remove the
668 Val->replaceAllUsesWith(GA);
669 Val->eraseFromParent();
670 ForwardRefVals.erase(I);
673 // Insert into the module, we know its name won't collide now.
674 M->getAliasList().push_back(GA);
675 assert(GA->getName() == Name && "Should not be a name conflict!");
681 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
682 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
683 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
684 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
686 /// Everything through visibility has been parsed already.
688 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
689 unsigned Linkage, bool HasLinkage,
690 unsigned Visibility) {
692 bool ThreadLocal, IsConstant, UnnamedAddr;
693 LocTy UnnamedAddrLoc;
696 PATypeHolder Ty(Type::getVoidTy(Context));
697 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
698 ParseOptionalAddrSpace(AddrSpace) ||
699 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
701 ParseGlobalType(IsConstant) ||
702 ParseType(Ty, TyLoc))
705 // If the linkage is specified and is external, then no initializer is
708 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
709 Linkage != GlobalValue::ExternalWeakLinkage &&
710 Linkage != GlobalValue::ExternalLinkage)) {
711 if (ParseGlobalValue(Ty, Init))
715 if (Ty->isFunctionTy() || Ty->isLabelTy())
716 return Error(TyLoc, "invalid type for global variable");
718 GlobalVariable *GV = 0;
720 // See if the global was forward referenced, if so, use the global.
722 if (GlobalValue *GVal = M->getNamedValue(Name)) {
723 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
724 return Error(NameLoc, "redefinition of global '@" + Name + "'");
725 GV = cast<GlobalVariable>(GVal);
728 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
729 I = ForwardRefValIDs.find(NumberedVals.size());
730 if (I != ForwardRefValIDs.end()) {
731 GV = cast<GlobalVariable>(I->second.first);
732 ForwardRefValIDs.erase(I);
737 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
738 Name, 0, false, AddrSpace);
740 if (GV->getType()->getElementType() != Ty)
742 "forward reference and definition of global have different types");
744 // Move the forward-reference to the correct spot in the module.
745 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
749 NumberedVals.push_back(GV);
751 // Set the parsed properties on the global.
753 GV->setInitializer(Init);
754 GV->setConstant(IsConstant);
755 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
756 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
757 GV->setThreadLocal(ThreadLocal);
758 GV->setUnnamedAddr(UnnamedAddr);
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, "'@" + Twine(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;
986 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
988 case lltok::kw_alignstack: {
990 if (ParseOptionalStackAlignment(Alignment))
992 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
996 case lltok::kw_align: {
998 if (ParseOptionalAlignment(Alignment))
1000 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
1009 /// ParseOptionalLinkage
1012 /// ::= 'linker_private'
1013 /// ::= 'linker_private_weak'
1014 /// ::= 'linker_private_weak_def_auto'
1019 /// ::= 'linkonce_odr'
1020 /// ::= 'available_externally'
1025 /// ::= 'extern_weak'
1027 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1029 switch (Lex.getKind()) {
1030 default: Res=GlobalValue::ExternalLinkage; return false;
1031 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1032 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1033 case lltok::kw_linker_private_weak:
1034 Res = GlobalValue::LinkerPrivateWeakLinkage;
1036 case lltok::kw_linker_private_weak_def_auto:
1037 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1039 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1040 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1041 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1042 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1043 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1044 case lltok::kw_available_externally:
1045 Res = GlobalValue::AvailableExternallyLinkage;
1047 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1048 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1049 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1050 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1051 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1052 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1059 /// ParseOptionalVisibility
1065 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1066 switch (Lex.getKind()) {
1067 default: Res = GlobalValue::DefaultVisibility; return false;
1068 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1069 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1070 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1076 /// ParseOptionalCallingConv
1081 /// ::= 'x86_stdcallcc'
1082 /// ::= 'x86_fastcallcc'
1083 /// ::= 'x86_thiscallcc'
1084 /// ::= 'arm_apcscc'
1085 /// ::= 'arm_aapcscc'
1086 /// ::= 'arm_aapcs_vfpcc'
1087 /// ::= 'msp430_intrcc'
1088 /// ::= 'ptx_kernel'
1089 /// ::= 'ptx_device'
1090 /// ::= 'win64_thiscallcc'
1093 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1094 switch (Lex.getKind()) {
1095 default: CC = CallingConv::C; return false;
1096 case lltok::kw_ccc: CC = CallingConv::C; break;
1097 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1098 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1099 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1100 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1101 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1102 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1103 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1104 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1105 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1106 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1107 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1108 case lltok::kw_win64_thiscallcc:CC = CallingConv::Win64_ThisCall; break;
1109 case lltok::kw_cc: {
1110 unsigned ArbitraryCC;
1112 if (ParseUInt32(ArbitraryCC)) {
1115 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1125 /// ParseInstructionMetadata
1126 /// ::= !dbg !42 (',' !dbg !57)*
1127 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1128 PerFunctionState *PFS) {
1130 if (Lex.getKind() != lltok::MetadataVar)
1131 return TokError("expected metadata after comma");
1133 std::string Name = Lex.getStrVal();
1134 unsigned MDK = M->getMDKindID(Name.c_str());
1138 SMLoc Loc = Lex.getLoc();
1140 if (ParseToken(lltok::exclaim, "expected '!' here"))
1143 // This code is similar to that of ParseMetadataValue, however it needs to
1144 // have special-case code for a forward reference; see the comments on
1145 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1146 // at the top level here.
1147 if (Lex.getKind() == lltok::lbrace) {
1149 if (ParseMetadataListValue(ID, PFS))
1151 assert(ID.Kind == ValID::t_MDNode);
1152 Inst->setMetadata(MDK, ID.MDNodeVal);
1154 unsigned NodeID = 0;
1155 if (ParseMDNodeID(Node, NodeID))
1158 // If we got the node, add it to the instruction.
1159 Inst->setMetadata(MDK, Node);
1161 MDRef R = { Loc, MDK, NodeID };
1162 // Otherwise, remember that this should be resolved later.
1163 ForwardRefInstMetadata[Inst].push_back(R);
1167 // If this is the end of the list, we're done.
1168 } while (EatIfPresent(lltok::comma));
1172 /// ParseOptionalAlignment
1175 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1177 if (!EatIfPresent(lltok::kw_align))
1179 LocTy AlignLoc = Lex.getLoc();
1180 if (ParseUInt32(Alignment)) return true;
1181 if (!isPowerOf2_32(Alignment))
1182 return Error(AlignLoc, "alignment is not a power of two");
1183 if (Alignment > Value::MaximumAlignment)
1184 return Error(AlignLoc, "huge alignments are not supported yet");
1188 /// ParseOptionalCommaAlign
1192 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1194 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1195 bool &AteExtraComma) {
1196 AteExtraComma = false;
1197 while (EatIfPresent(lltok::comma)) {
1198 // Metadata at the end is an early exit.
1199 if (Lex.getKind() == lltok::MetadataVar) {
1200 AteExtraComma = true;
1204 if (Lex.getKind() != lltok::kw_align)
1205 return Error(Lex.getLoc(), "expected metadata or 'align'");
1207 if (ParseOptionalAlignment(Alignment)) return true;
1213 /// ParseOptionalStackAlignment
1215 /// ::= 'alignstack' '(' 4 ')'
1216 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1218 if (!EatIfPresent(lltok::kw_alignstack))
1220 LocTy ParenLoc = Lex.getLoc();
1221 if (!EatIfPresent(lltok::lparen))
1222 return Error(ParenLoc, "expected '('");
1223 LocTy AlignLoc = Lex.getLoc();
1224 if (ParseUInt32(Alignment)) return true;
1225 ParenLoc = Lex.getLoc();
1226 if (!EatIfPresent(lltok::rparen))
1227 return Error(ParenLoc, "expected ')'");
1228 if (!isPowerOf2_32(Alignment))
1229 return Error(AlignLoc, "stack alignment is not a power of two");
1233 /// ParseIndexList - This parses the index list for an insert/extractvalue
1234 /// instruction. This sets AteExtraComma in the case where we eat an extra
1235 /// comma at the end of the line and find that it is followed by metadata.
1236 /// Clients that don't allow metadata can call the version of this function that
1237 /// only takes one argument.
1240 /// ::= (',' uint32)+
1242 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1243 bool &AteExtraComma) {
1244 AteExtraComma = false;
1246 if (Lex.getKind() != lltok::comma)
1247 return TokError("expected ',' as start of index list");
1249 while (EatIfPresent(lltok::comma)) {
1250 if (Lex.getKind() == lltok::MetadataVar) {
1251 AteExtraComma = true;
1255 if (ParseUInt32(Idx)) return true;
1256 Indices.push_back(Idx);
1262 //===----------------------------------------------------------------------===//
1264 //===----------------------------------------------------------------------===//
1266 /// ParseType - Parse and resolve a full type.
1267 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1268 LocTy TypeLoc = Lex.getLoc();
1269 if (ParseTypeRec(Result)) return true;
1271 // Verify no unresolved uprefs.
1272 if (!UpRefs.empty())
1273 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1275 if (!AllowVoid && Result.get()->isVoidTy())
1276 return Error(TypeLoc, "void type only allowed for function results");
1281 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1282 /// called. It loops through the UpRefs vector, which is a list of the
1283 /// currently active types. For each type, if the up-reference is contained in
1284 /// the newly completed type, we decrement the level count. When the level
1285 /// count reaches zero, the up-referenced type is the type that is passed in:
1286 /// thus we can complete the cycle.
1288 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1289 // If Ty isn't abstract, or if there are no up-references in it, then there is
1290 // nothing to resolve here.
1291 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1293 PATypeHolder Ty(ty);
1295 dbgs() << "Type '" << Ty->getDescription()
1296 << "' newly formed. Resolving upreferences.\n"
1297 << UpRefs.size() << " upreferences active!\n";
1300 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1301 // to zero), we resolve them all together before we resolve them to Ty. At
1302 // the end of the loop, if there is anything to resolve to Ty, it will be in
1304 OpaqueType *TypeToResolve = 0;
1306 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1307 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1309 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1310 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1313 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1314 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1315 << (ContainsType ? "true" : "false")
1316 << " level=" << UpRefs[i].NestingLevel << "\n";
1321 // Decrement level of upreference
1322 unsigned Level = --UpRefs[i].NestingLevel;
1323 UpRefs[i].LastContainedTy = Ty;
1325 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1330 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1333 TypeToResolve = UpRefs[i].UpRefTy;
1335 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1336 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1337 --i; // Do not skip the next element.
1341 TypeToResolve->refineAbstractTypeTo(Ty);
1347 /// ParseTypeRec - The recursive function used to process the internal
1348 /// implementation details of types.
1349 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1350 switch (Lex.getKind()) {
1352 return TokError("expected type");
1354 // TypeRec ::= 'float' | 'void' (etc)
1355 Result = Lex.getTyVal();
1358 case lltok::kw_opaque:
1359 // TypeRec ::= 'opaque'
1360 Result = OpaqueType::get(Context);
1364 // TypeRec ::= '{' ... '}'
1365 if (ParseStructType(Result, false))
1368 case lltok::lsquare:
1369 // TypeRec ::= '[' ... ']'
1370 Lex.Lex(); // eat the lsquare.
1371 if (ParseArrayVectorType(Result, false))
1374 case lltok::less: // Either vector or packed struct.
1375 // TypeRec ::= '<' ... '>'
1377 if (Lex.getKind() == lltok::lbrace) {
1378 if (ParseStructType(Result, true) ||
1379 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1381 } else if (ParseArrayVectorType(Result, true))
1384 case lltok::LocalVar:
1385 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
1387 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1390 Result = OpaqueType::get(Context);
1391 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1392 std::make_pair(Result,
1394 M->addTypeName(Lex.getStrVal(), Result.get());
1399 case lltok::LocalVarID:
1401 if (Lex.getUIntVal() < NumberedTypes.size())
1402 Result = NumberedTypes[Lex.getUIntVal()];
1404 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1405 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1406 if (I != ForwardRefTypeIDs.end())
1407 Result = I->second.first;
1409 Result = OpaqueType::get(Context);
1410 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1411 std::make_pair(Result,
1417 case lltok::backslash: {
1418 // TypeRec ::= '\' 4
1421 if (ParseUInt32(Val)) return true;
1422 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1423 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1429 // Parse the type suffixes.
1431 switch (Lex.getKind()) {
1433 default: return false;
1435 // TypeRec ::= TypeRec '*'
1437 if (Result.get()->isLabelTy())
1438 return TokError("basic block pointers are invalid");
1439 if (Result.get()->isVoidTy())
1440 return TokError("pointers to void are invalid; use i8* instead");
1441 if (!PointerType::isValidElementType(Result.get()))
1442 return TokError("pointer to this type is invalid");
1443 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1447 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1448 case lltok::kw_addrspace: {
1449 if (Result.get()->isLabelTy())
1450 return TokError("basic block pointers are invalid");
1451 if (Result.get()->isVoidTy())
1452 return TokError("pointers to void are invalid; use i8* instead");
1453 if (!PointerType::isValidElementType(Result.get()))
1454 return TokError("pointer to this type is invalid");
1456 if (ParseOptionalAddrSpace(AddrSpace) ||
1457 ParseToken(lltok::star, "expected '*' in address space"))
1460 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1464 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1466 if (ParseFunctionType(Result))
1473 /// ParseParameterList
1475 /// ::= '(' Arg (',' Arg)* ')'
1477 /// ::= Type OptionalAttributes Value OptionalAttributes
1478 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1479 PerFunctionState &PFS) {
1480 if (ParseToken(lltok::lparen, "expected '(' in call"))
1483 while (Lex.getKind() != lltok::rparen) {
1484 // If this isn't the first argument, we need a comma.
1485 if (!ArgList.empty() &&
1486 ParseToken(lltok::comma, "expected ',' in argument list"))
1489 // Parse the argument.
1491 PATypeHolder ArgTy(Type::getVoidTy(Context));
1492 unsigned ArgAttrs1 = Attribute::None;
1493 unsigned ArgAttrs2 = Attribute::None;
1495 if (ParseType(ArgTy, ArgLoc))
1498 // Otherwise, handle normal operands.
1499 if (ParseOptionalAttrs(ArgAttrs1, 0) ||
1500 ParseValue(ArgTy, V, PFS) ||
1501 // FIXME: Should not allow attributes after the argument, remove this
1503 ParseOptionalAttrs(ArgAttrs2, 3))
1505 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1508 Lex.Lex(); // Lex the ')'.
1514 /// ParseArgumentList - Parse the argument list for a function type or function
1515 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1516 /// ::= '(' ArgTypeListI ')'
1520 /// ::= ArgTypeList ',' '...'
1521 /// ::= ArgType (',' ArgType)*
1523 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1524 bool &isVarArg, bool inType) {
1526 assert(Lex.getKind() == lltok::lparen);
1527 Lex.Lex(); // eat the (.
1529 if (Lex.getKind() == lltok::rparen) {
1531 } else if (Lex.getKind() == lltok::dotdotdot) {
1535 LocTy TypeLoc = Lex.getLoc();
1536 PATypeHolder ArgTy(Type::getVoidTy(Context));
1540 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1541 // types (such as a function returning a pointer to itself). If parsing a
1542 // function prototype, we require fully resolved types.
1543 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1544 ParseOptionalAttrs(Attrs, 0)) return true;
1546 if (ArgTy->isVoidTy())
1547 return Error(TypeLoc, "argument can not have void type");
1549 if (Lex.getKind() == lltok::LocalVar ||
1550 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1551 Name = Lex.getStrVal();
1555 if (!FunctionType::isValidArgumentType(ArgTy))
1556 return Error(TypeLoc, "invalid type for function argument");
1558 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1560 while (EatIfPresent(lltok::comma)) {
1561 // Handle ... at end of arg list.
1562 if (EatIfPresent(lltok::dotdotdot)) {
1567 // Otherwise must be an argument type.
1568 TypeLoc = Lex.getLoc();
1569 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1570 ParseOptionalAttrs(Attrs, 0)) return true;
1572 if (ArgTy->isVoidTy())
1573 return Error(TypeLoc, "argument can not have void type");
1575 if (Lex.getKind() == lltok::LocalVar ||
1576 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1577 Name = Lex.getStrVal();
1583 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
1584 return Error(TypeLoc, "invalid type for function argument");
1586 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1590 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1593 /// ParseFunctionType
1594 /// ::= Type ArgumentList OptionalAttrs
1595 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1596 assert(Lex.getKind() == lltok::lparen);
1598 if (!FunctionType::isValidReturnType(Result))
1599 return TokError("invalid function return type");
1601 std::vector<ArgInfo> ArgList;
1604 if (ParseArgumentList(ArgList, isVarArg, true) ||
1605 // FIXME: Allow, but ignore attributes on function types!
1606 // FIXME: Remove in LLVM 3.0
1607 ParseOptionalAttrs(Attrs, 2))
1610 // Reject names on the arguments lists.
1611 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1612 if (!ArgList[i].Name.empty())
1613 return Error(ArgList[i].Loc, "argument name invalid in function type");
1614 if (!ArgList[i].Attrs != 0) {
1615 // Allow but ignore attributes on function types; this permits
1617 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1621 std::vector<const Type*> ArgListTy;
1622 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1623 ArgListTy.push_back(ArgList[i].Type);
1625 Result = HandleUpRefs(FunctionType::get(Result.get(),
1626 ArgListTy, isVarArg));
1630 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1633 /// ::= '{' TypeRec (',' TypeRec)* '}'
1634 /// ::= '<' '{' '}' '>'
1635 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1636 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1637 assert(Lex.getKind() == lltok::lbrace);
1638 Lex.Lex(); // Consume the '{'
1640 if (EatIfPresent(lltok::rbrace)) {
1641 Result = StructType::get(Context, Packed);
1645 std::vector<PATypeHolder> ParamsList;
1646 LocTy EltTyLoc = Lex.getLoc();
1647 if (ParseTypeRec(Result)) return true;
1648 ParamsList.push_back(Result);
1650 if (Result->isVoidTy())
1651 return Error(EltTyLoc, "struct element can not have void type");
1652 if (!StructType::isValidElementType(Result))
1653 return Error(EltTyLoc, "invalid element type for struct");
1655 while (EatIfPresent(lltok::comma)) {
1656 EltTyLoc = Lex.getLoc();
1657 if (ParseTypeRec(Result)) return true;
1659 if (Result->isVoidTy())
1660 return Error(EltTyLoc, "struct element can not have void type");
1661 if (!StructType::isValidElementType(Result))
1662 return Error(EltTyLoc, "invalid element type for struct");
1664 ParamsList.push_back(Result);
1667 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1670 std::vector<const Type*> ParamsListTy;
1671 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1672 ParamsListTy.push_back(ParamsList[i].get());
1673 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1677 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1678 /// token has already been consumed.
1680 /// ::= '[' APSINTVAL 'x' Types ']'
1681 /// ::= '<' APSINTVAL 'x' Types '>'
1682 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1683 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1684 Lex.getAPSIntVal().getBitWidth() > 64)
1685 return TokError("expected number in address space");
1687 LocTy SizeLoc = Lex.getLoc();
1688 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1691 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1694 LocTy TypeLoc = Lex.getLoc();
1695 PATypeHolder EltTy(Type::getVoidTy(Context));
1696 if (ParseTypeRec(EltTy)) return true;
1698 if (EltTy->isVoidTy())
1699 return Error(TypeLoc, "array and vector element type cannot be void");
1701 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1702 "expected end of sequential type"))
1707 return Error(SizeLoc, "zero element vector is illegal");
1708 if ((unsigned)Size != Size)
1709 return Error(SizeLoc, "size too large for vector");
1710 if (!VectorType::isValidElementType(EltTy))
1711 return Error(TypeLoc, "vector element type must be fp or integer");
1712 Result = VectorType::get(EltTy, unsigned(Size));
1714 if (!ArrayType::isValidElementType(EltTy))
1715 return Error(TypeLoc, "invalid array element type");
1716 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1721 //===----------------------------------------------------------------------===//
1722 // Function Semantic Analysis.
1723 //===----------------------------------------------------------------------===//
1725 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1727 : P(p), F(f), FunctionNumber(functionNumber) {
1729 // Insert unnamed arguments into the NumberedVals list.
1730 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1733 NumberedVals.push_back(AI);
1736 LLParser::PerFunctionState::~PerFunctionState() {
1737 // If there were any forward referenced non-basicblock values, delete them.
1738 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1739 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1740 if (!isa<BasicBlock>(I->second.first)) {
1741 I->second.first->replaceAllUsesWith(
1742 UndefValue::get(I->second.first->getType()));
1743 delete I->second.first;
1744 I->second.first = 0;
1747 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1748 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.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;
1757 bool LLParser::PerFunctionState::FinishFunction() {
1758 // Check to see if someone took the address of labels in this block.
1759 if (!P.ForwardRefBlockAddresses.empty()) {
1761 if (!F.getName().empty()) {
1762 FunctionID.Kind = ValID::t_GlobalName;
1763 FunctionID.StrVal = F.getName();
1765 FunctionID.Kind = ValID::t_GlobalID;
1766 FunctionID.UIntVal = FunctionNumber;
1769 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1770 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1771 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1772 // Resolve all these references.
1773 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1776 P.ForwardRefBlockAddresses.erase(FRBAI);
1780 if (!ForwardRefVals.empty())
1781 return P.Error(ForwardRefVals.begin()->second.second,
1782 "use of undefined value '%" + ForwardRefVals.begin()->first +
1784 if (!ForwardRefValIDs.empty())
1785 return P.Error(ForwardRefValIDs.begin()->second.second,
1786 "use of undefined value '%" +
1787 Twine(ForwardRefValIDs.begin()->first) + "'");
1792 /// GetVal - Get a value with the specified name or ID, creating a
1793 /// forward reference record if needed. This can return null if the value
1794 /// exists but does not have the right type.
1795 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1796 const Type *Ty, LocTy Loc) {
1797 // Look this name up in the normal function symbol table.
1798 Value *Val = F.getValueSymbolTable().lookup(Name);
1800 // If this is a forward reference for the value, see if we already created a
1801 // forward ref record.
1803 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1804 I = ForwardRefVals.find(Name);
1805 if (I != ForwardRefVals.end())
1806 Val = I->second.first;
1809 // If we have the value in the symbol table or fwd-ref table, return it.
1811 if (Val->getType() == Ty) return Val;
1812 if (Ty->isLabelTy())
1813 P.Error(Loc, "'%" + Name + "' is not a basic block");
1815 P.Error(Loc, "'%" + Name + "' defined with type '" +
1816 Val->getType()->getDescription() + "'");
1820 // Don't make placeholders with invalid type.
1821 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1822 P.Error(Loc, "invalid use of a non-first-class type");
1826 // Otherwise, create a new forward reference for this value and remember it.
1828 if (Ty->isLabelTy())
1829 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1831 FwdVal = new Argument(Ty, Name);
1833 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1837 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1839 // Look this name up in the normal function symbol table.
1840 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1842 // If this is a forward reference for the value, see if we already created a
1843 // forward ref record.
1845 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1846 I = ForwardRefValIDs.find(ID);
1847 if (I != ForwardRefValIDs.end())
1848 Val = I->second.first;
1851 // If we have the value in the symbol table or fwd-ref table, return it.
1853 if (Val->getType() == Ty) return Val;
1854 if (Ty->isLabelTy())
1855 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1857 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1858 Val->getType()->getDescription() + "'");
1862 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1863 P.Error(Loc, "invalid use of a non-first-class type");
1867 // Otherwise, create a new forward reference for this value and remember it.
1869 if (Ty->isLabelTy())
1870 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1872 FwdVal = new Argument(Ty);
1874 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1878 /// SetInstName - After an instruction is parsed and inserted into its
1879 /// basic block, this installs its name.
1880 bool LLParser::PerFunctionState::SetInstName(int NameID,
1881 const std::string &NameStr,
1882 LocTy NameLoc, Instruction *Inst) {
1883 // If this instruction has void type, it cannot have a name or ID specified.
1884 if (Inst->getType()->isVoidTy()) {
1885 if (NameID != -1 || !NameStr.empty())
1886 return P.Error(NameLoc, "instructions returning void cannot have a name");
1890 // If this was a numbered instruction, verify that the instruction is the
1891 // expected value and resolve any forward references.
1892 if (NameStr.empty()) {
1893 // If neither a name nor an ID was specified, just use the next ID.
1895 NameID = NumberedVals.size();
1897 if (unsigned(NameID) != NumberedVals.size())
1898 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1899 Twine(NumberedVals.size()) + "'");
1901 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1902 ForwardRefValIDs.find(NameID);
1903 if (FI != ForwardRefValIDs.end()) {
1904 if (FI->second.first->getType() != Inst->getType())
1905 return P.Error(NameLoc, "instruction forward referenced with type '" +
1906 FI->second.first->getType()->getDescription() + "'");
1907 FI->second.first->replaceAllUsesWith(Inst);
1908 delete FI->second.first;
1909 ForwardRefValIDs.erase(FI);
1912 NumberedVals.push_back(Inst);
1916 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1917 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1918 FI = ForwardRefVals.find(NameStr);
1919 if (FI != ForwardRefVals.end()) {
1920 if (FI->second.first->getType() != Inst->getType())
1921 return P.Error(NameLoc, "instruction forward referenced with type '" +
1922 FI->second.first->getType()->getDescription() + "'");
1923 FI->second.first->replaceAllUsesWith(Inst);
1924 delete FI->second.first;
1925 ForwardRefVals.erase(FI);
1928 // Set the name on the instruction.
1929 Inst->setName(NameStr);
1931 if (Inst->getName() != NameStr)
1932 return P.Error(NameLoc, "multiple definition of local value named '" +
1937 /// GetBB - Get a basic block with the specified name or ID, creating a
1938 /// forward reference record if needed.
1939 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1941 return cast_or_null<BasicBlock>(GetVal(Name,
1942 Type::getLabelTy(F.getContext()), Loc));
1945 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1946 return cast_or_null<BasicBlock>(GetVal(ID,
1947 Type::getLabelTy(F.getContext()), Loc));
1950 /// DefineBB - Define the specified basic block, which is either named or
1951 /// unnamed. If there is an error, this returns null otherwise it returns
1952 /// the block being defined.
1953 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1957 BB = GetBB(NumberedVals.size(), Loc);
1959 BB = GetBB(Name, Loc);
1960 if (BB == 0) return 0; // Already diagnosed error.
1962 // Move the block to the end of the function. Forward ref'd blocks are
1963 // inserted wherever they happen to be referenced.
1964 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1966 // Remove the block from forward ref sets.
1968 ForwardRefValIDs.erase(NumberedVals.size());
1969 NumberedVals.push_back(BB);
1971 // BB forward references are already in the function symbol table.
1972 ForwardRefVals.erase(Name);
1978 //===----------------------------------------------------------------------===//
1980 //===----------------------------------------------------------------------===//
1982 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1983 /// type implied. For example, if we parse "4" we don't know what integer type
1984 /// it has. The value will later be combined with its type and checked for
1985 /// sanity. PFS is used to convert function-local operands of metadata (since
1986 /// metadata operands are not just parsed here but also converted to values).
1987 /// PFS can be null when we are not parsing metadata values inside a function.
1988 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1989 ID.Loc = Lex.getLoc();
1990 switch (Lex.getKind()) {
1991 default: return TokError("expected value token");
1992 case lltok::GlobalID: // @42
1993 ID.UIntVal = Lex.getUIntVal();
1994 ID.Kind = ValID::t_GlobalID;
1996 case lltok::GlobalVar: // @foo
1997 ID.StrVal = Lex.getStrVal();
1998 ID.Kind = ValID::t_GlobalName;
2000 case lltok::LocalVarID: // %42
2001 ID.UIntVal = Lex.getUIntVal();
2002 ID.Kind = ValID::t_LocalID;
2004 case lltok::LocalVar: // %foo
2005 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
2006 ID.StrVal = Lex.getStrVal();
2007 ID.Kind = ValID::t_LocalName;
2009 case lltok::exclaim: // !42, !{...}, or !"foo"
2010 return ParseMetadataValue(ID, PFS);
2012 ID.APSIntVal = Lex.getAPSIntVal();
2013 ID.Kind = ValID::t_APSInt;
2015 case lltok::APFloat:
2016 ID.APFloatVal = Lex.getAPFloatVal();
2017 ID.Kind = ValID::t_APFloat;
2019 case lltok::kw_true:
2020 ID.ConstantVal = ConstantInt::getTrue(Context);
2021 ID.Kind = ValID::t_Constant;
2023 case lltok::kw_false:
2024 ID.ConstantVal = ConstantInt::getFalse(Context);
2025 ID.Kind = ValID::t_Constant;
2027 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2028 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2029 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2031 case lltok::lbrace: {
2032 // ValID ::= '{' ConstVector '}'
2034 SmallVector<Constant*, 16> Elts;
2035 if (ParseGlobalValueVector(Elts) ||
2036 ParseToken(lltok::rbrace, "expected end of struct constant"))
2039 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
2040 Elts.size(), false);
2041 ID.Kind = ValID::t_Constant;
2045 // ValID ::= '<' ConstVector '>' --> Vector.
2046 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2048 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2050 SmallVector<Constant*, 16> Elts;
2051 LocTy FirstEltLoc = Lex.getLoc();
2052 if (ParseGlobalValueVector(Elts) ||
2054 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2055 ParseToken(lltok::greater, "expected end of constant"))
2058 if (isPackedStruct) {
2060 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
2061 ID.Kind = ValID::t_Constant;
2066 return Error(ID.Loc, "constant vector must not be empty");
2068 if (!Elts[0]->getType()->isIntegerTy() &&
2069 !Elts[0]->getType()->isFloatingPointTy())
2070 return Error(FirstEltLoc,
2071 "vector elements must have integer or floating point type");
2073 // Verify that all the vector elements have the same type.
2074 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2075 if (Elts[i]->getType() != Elts[0]->getType())
2076 return Error(FirstEltLoc,
2077 "vector element #" + Twine(i) +
2078 " is not of type '" + Elts[0]->getType()->getDescription());
2080 ID.ConstantVal = ConstantVector::get(Elts);
2081 ID.Kind = ValID::t_Constant;
2084 case lltok::lsquare: { // Array Constant
2086 SmallVector<Constant*, 16> Elts;
2087 LocTy FirstEltLoc = Lex.getLoc();
2088 if (ParseGlobalValueVector(Elts) ||
2089 ParseToken(lltok::rsquare, "expected end of array constant"))
2092 // Handle empty element.
2094 // Use undef instead of an array because it's inconvenient to determine
2095 // the element type at this point, there being no elements to examine.
2096 ID.Kind = ValID::t_EmptyArray;
2100 if (!Elts[0]->getType()->isFirstClassType())
2101 return Error(FirstEltLoc, "invalid array element type: " +
2102 Elts[0]->getType()->getDescription());
2104 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2106 // Verify all elements are correct type!
2107 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2108 if (Elts[i]->getType() != Elts[0]->getType())
2109 return Error(FirstEltLoc,
2110 "array element #" + Twine(i) +
2111 " is not of type '" +Elts[0]->getType()->getDescription());
2114 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2115 ID.Kind = ValID::t_Constant;
2118 case lltok::kw_c: // c "foo"
2120 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2121 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2122 ID.Kind = ValID::t_Constant;
2125 case lltok::kw_asm: {
2126 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2127 bool HasSideEffect, AlignStack;
2129 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2130 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2131 ParseStringConstant(ID.StrVal) ||
2132 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2133 ParseToken(lltok::StringConstant, "expected constraint string"))
2135 ID.StrVal2 = Lex.getStrVal();
2136 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2137 ID.Kind = ValID::t_InlineAsm;
2141 case lltok::kw_blockaddress: {
2142 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2146 LocTy FnLoc, LabelLoc;
2148 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2150 ParseToken(lltok::comma, "expected comma in block address expression")||
2151 ParseValID(Label) ||
2152 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2155 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2156 return Error(Fn.Loc, "expected function name in blockaddress");
2157 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2158 return Error(Label.Loc, "expected basic block name in blockaddress");
2160 // Make a global variable as a placeholder for this reference.
2161 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2162 false, GlobalValue::InternalLinkage,
2164 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2165 ID.ConstantVal = FwdRef;
2166 ID.Kind = ValID::t_Constant;
2170 case lltok::kw_trunc:
2171 case lltok::kw_zext:
2172 case lltok::kw_sext:
2173 case lltok::kw_fptrunc:
2174 case lltok::kw_fpext:
2175 case lltok::kw_bitcast:
2176 case lltok::kw_uitofp:
2177 case lltok::kw_sitofp:
2178 case lltok::kw_fptoui:
2179 case lltok::kw_fptosi:
2180 case lltok::kw_inttoptr:
2181 case lltok::kw_ptrtoint: {
2182 unsigned Opc = Lex.getUIntVal();
2183 PATypeHolder DestTy(Type::getVoidTy(Context));
2186 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2187 ParseGlobalTypeAndValue(SrcVal) ||
2188 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2189 ParseType(DestTy) ||
2190 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2192 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2193 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2194 SrcVal->getType()->getDescription() + "' to '" +
2195 DestTy->getDescription() + "'");
2196 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2198 ID.Kind = ValID::t_Constant;
2201 case lltok::kw_extractvalue: {
2204 SmallVector<unsigned, 4> Indices;
2205 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2206 ParseGlobalTypeAndValue(Val) ||
2207 ParseIndexList(Indices) ||
2208 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2211 if (!Val->getType()->isAggregateType())
2212 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2213 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2215 return Error(ID.Loc, "invalid indices for extractvalue");
2217 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2218 ID.Kind = ValID::t_Constant;
2221 case lltok::kw_insertvalue: {
2223 Constant *Val0, *Val1;
2224 SmallVector<unsigned, 4> Indices;
2225 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2226 ParseGlobalTypeAndValue(Val0) ||
2227 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2228 ParseGlobalTypeAndValue(Val1) ||
2229 ParseIndexList(Indices) ||
2230 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2232 if (!Val0->getType()->isAggregateType())
2233 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2234 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2236 return Error(ID.Loc, "invalid indices for insertvalue");
2237 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2238 Indices.data(), Indices.size());
2239 ID.Kind = ValID::t_Constant;
2242 case lltok::kw_icmp:
2243 case lltok::kw_fcmp: {
2244 unsigned PredVal, Opc = Lex.getUIntVal();
2245 Constant *Val0, *Val1;
2247 if (ParseCmpPredicate(PredVal, Opc) ||
2248 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2249 ParseGlobalTypeAndValue(Val0) ||
2250 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2251 ParseGlobalTypeAndValue(Val1) ||
2252 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2255 if (Val0->getType() != Val1->getType())
2256 return Error(ID.Loc, "compare operands must have the same type");
2258 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2260 if (Opc == Instruction::FCmp) {
2261 if (!Val0->getType()->isFPOrFPVectorTy())
2262 return Error(ID.Loc, "fcmp requires floating point operands");
2263 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2265 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2266 if (!Val0->getType()->isIntOrIntVectorTy() &&
2267 !Val0->getType()->isPointerTy())
2268 return Error(ID.Loc, "icmp requires pointer or integer operands");
2269 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2271 ID.Kind = ValID::t_Constant;
2275 // Binary Operators.
2277 case lltok::kw_fadd:
2279 case lltok::kw_fsub:
2281 case lltok::kw_fmul:
2282 case lltok::kw_udiv:
2283 case lltok::kw_sdiv:
2284 case lltok::kw_fdiv:
2285 case lltok::kw_urem:
2286 case lltok::kw_srem:
2287 case lltok::kw_frem:
2289 case lltok::kw_lshr:
2290 case lltok::kw_ashr: {
2294 unsigned Opc = Lex.getUIntVal();
2295 Constant *Val0, *Val1;
2297 LocTy ModifierLoc = Lex.getLoc();
2298 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2299 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2300 if (EatIfPresent(lltok::kw_nuw))
2302 if (EatIfPresent(lltok::kw_nsw)) {
2304 if (EatIfPresent(lltok::kw_nuw))
2307 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2308 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2309 if (EatIfPresent(lltok::kw_exact))
2312 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2313 ParseGlobalTypeAndValue(Val0) ||
2314 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2315 ParseGlobalTypeAndValue(Val1) ||
2316 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2318 if (Val0->getType() != Val1->getType())
2319 return Error(ID.Loc, "operands of constexpr must have same type");
2320 if (!Val0->getType()->isIntOrIntVectorTy()) {
2322 return Error(ModifierLoc, "nuw only applies to integer operations");
2324 return Error(ModifierLoc, "nsw only applies to integer operations");
2326 // Check that the type is valid for the operator.
2328 case Instruction::Add:
2329 case Instruction::Sub:
2330 case Instruction::Mul:
2331 case Instruction::UDiv:
2332 case Instruction::SDiv:
2333 case Instruction::URem:
2334 case Instruction::SRem:
2335 case Instruction::Shl:
2336 case Instruction::AShr:
2337 case Instruction::LShr:
2338 if (!Val0->getType()->isIntOrIntVectorTy())
2339 return Error(ID.Loc, "constexpr requires integer operands");
2341 case Instruction::FAdd:
2342 case Instruction::FSub:
2343 case Instruction::FMul:
2344 case Instruction::FDiv:
2345 case Instruction::FRem:
2346 if (!Val0->getType()->isFPOrFPVectorTy())
2347 return Error(ID.Loc, "constexpr requires fp operands");
2349 default: llvm_unreachable("Unknown binary operator!");
2352 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2353 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2354 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2355 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2357 ID.Kind = ValID::t_Constant;
2361 // Logical Operations
2364 case lltok::kw_xor: {
2365 unsigned Opc = Lex.getUIntVal();
2366 Constant *Val0, *Val1;
2368 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2369 ParseGlobalTypeAndValue(Val0) ||
2370 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2371 ParseGlobalTypeAndValue(Val1) ||
2372 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2374 if (Val0->getType() != Val1->getType())
2375 return Error(ID.Loc, "operands of constexpr must have same type");
2376 if (!Val0->getType()->isIntOrIntVectorTy())
2377 return Error(ID.Loc,
2378 "constexpr requires integer or integer vector operands");
2379 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2380 ID.Kind = ValID::t_Constant;
2384 case lltok::kw_getelementptr:
2385 case lltok::kw_shufflevector:
2386 case lltok::kw_insertelement:
2387 case lltok::kw_extractelement:
2388 case lltok::kw_select: {
2389 unsigned Opc = Lex.getUIntVal();
2390 SmallVector<Constant*, 16> Elts;
2391 bool InBounds = false;
2393 if (Opc == Instruction::GetElementPtr)
2394 InBounds = EatIfPresent(lltok::kw_inbounds);
2395 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2396 ParseGlobalValueVector(Elts) ||
2397 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2400 if (Opc == Instruction::GetElementPtr) {
2401 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2402 return Error(ID.Loc, "getelementptr requires pointer operand");
2404 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2405 (Value**)(Elts.data() + 1),
2407 return Error(ID.Loc, "invalid indices for getelementptr");
2408 ID.ConstantVal = InBounds ?
2409 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2412 ConstantExpr::getGetElementPtr(Elts[0],
2413 Elts.data() + 1, Elts.size() - 1);
2414 } else if (Opc == Instruction::Select) {
2415 if (Elts.size() != 3)
2416 return Error(ID.Loc, "expected three operands to select");
2417 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2419 return Error(ID.Loc, Reason);
2420 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2421 } else if (Opc == Instruction::ShuffleVector) {
2422 if (Elts.size() != 3)
2423 return Error(ID.Loc, "expected three operands to shufflevector");
2424 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2425 return Error(ID.Loc, "invalid operands to shufflevector");
2427 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2428 } else if (Opc == Instruction::ExtractElement) {
2429 if (Elts.size() != 2)
2430 return Error(ID.Loc, "expected two operands to extractelement");
2431 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2432 return Error(ID.Loc, "invalid extractelement operands");
2433 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2435 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2436 if (Elts.size() != 3)
2437 return Error(ID.Loc, "expected three operands to insertelement");
2438 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2439 return Error(ID.Loc, "invalid insertelement operands");
2441 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2444 ID.Kind = ValID::t_Constant;
2453 /// ParseGlobalValue - Parse a global value with the specified type.
2454 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2458 bool Parsed = ParseValID(ID) ||
2459 ConvertValIDToValue(Ty, ID, V, NULL);
2460 if (V && !(C = dyn_cast<Constant>(V)))
2461 return Error(ID.Loc, "global values must be constants");
2465 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2466 PATypeHolder Type(Type::getVoidTy(Context));
2467 return ParseType(Type) ||
2468 ParseGlobalValue(Type, V);
2471 /// ParseGlobalValueVector
2473 /// ::= TypeAndValue (',' TypeAndValue)*
2474 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2476 if (Lex.getKind() == lltok::rbrace ||
2477 Lex.getKind() == lltok::rsquare ||
2478 Lex.getKind() == lltok::greater ||
2479 Lex.getKind() == lltok::rparen)
2483 if (ParseGlobalTypeAndValue(C)) return true;
2486 while (EatIfPresent(lltok::comma)) {
2487 if (ParseGlobalTypeAndValue(C)) return true;
2494 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2495 assert(Lex.getKind() == lltok::lbrace);
2498 SmallVector<Value*, 16> Elts;
2499 if (ParseMDNodeVector(Elts, PFS) ||
2500 ParseToken(lltok::rbrace, "expected end of metadata node"))
2503 ID.MDNodeVal = MDNode::get(Context, Elts.data(), Elts.size());
2504 ID.Kind = ValID::t_MDNode;
2508 /// ParseMetadataValue
2512 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2513 assert(Lex.getKind() == lltok::exclaim);
2518 if (Lex.getKind() == lltok::lbrace)
2519 return ParseMetadataListValue(ID, PFS);
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 = 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 return Error(ID.Loc, "constant expression type mismatch");
2639 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2642 return ParseValID(ID, &PFS) ||
2643 ConvertValIDToValue(Ty, ID, V, &PFS);
2646 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2647 PATypeHolder T(Type::getVoidTy(Context));
2648 return ParseType(T) ||
2649 ParseValue(T, V, PFS);
2652 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2653 PerFunctionState &PFS) {
2656 if (ParseTypeAndValue(V, PFS)) return true;
2657 if (!isa<BasicBlock>(V))
2658 return Error(Loc, "expected a basic block");
2659 BB = cast<BasicBlock>(V);
2665 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2666 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2667 /// OptionalAlign OptGC
2668 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2669 // Parse the linkage.
2670 LocTy LinkageLoc = Lex.getLoc();
2673 unsigned Visibility, RetAttrs;
2675 PATypeHolder RetType(Type::getVoidTy(Context));
2676 LocTy RetTypeLoc = Lex.getLoc();
2677 if (ParseOptionalLinkage(Linkage) ||
2678 ParseOptionalVisibility(Visibility) ||
2679 ParseOptionalCallingConv(CC) ||
2680 ParseOptionalAttrs(RetAttrs, 1) ||
2681 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2684 // Verify that the linkage is ok.
2685 switch ((GlobalValue::LinkageTypes)Linkage) {
2686 case GlobalValue::ExternalLinkage:
2687 break; // always ok.
2688 case GlobalValue::DLLImportLinkage:
2689 case GlobalValue::ExternalWeakLinkage:
2691 return Error(LinkageLoc, "invalid linkage for function definition");
2693 case GlobalValue::PrivateLinkage:
2694 case GlobalValue::LinkerPrivateLinkage:
2695 case GlobalValue::LinkerPrivateWeakLinkage:
2696 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2697 case GlobalValue::InternalLinkage:
2698 case GlobalValue::AvailableExternallyLinkage:
2699 case GlobalValue::LinkOnceAnyLinkage:
2700 case GlobalValue::LinkOnceODRLinkage:
2701 case GlobalValue::WeakAnyLinkage:
2702 case GlobalValue::WeakODRLinkage:
2703 case GlobalValue::DLLExportLinkage:
2705 return Error(LinkageLoc, "invalid linkage for function declaration");
2707 case GlobalValue::AppendingLinkage:
2708 case GlobalValue::CommonLinkage:
2709 return Error(LinkageLoc, "invalid function linkage type");
2712 if (!FunctionType::isValidReturnType(RetType) ||
2713 RetType->isOpaqueTy())
2714 return Error(RetTypeLoc, "invalid function return type");
2716 LocTy NameLoc = Lex.getLoc();
2718 std::string FunctionName;
2719 if (Lex.getKind() == lltok::GlobalVar) {
2720 FunctionName = Lex.getStrVal();
2721 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2722 unsigned NameID = Lex.getUIntVal();
2724 if (NameID != NumberedVals.size())
2725 return TokError("function expected to be numbered '%" +
2726 Twine(NumberedVals.size()) + "'");
2728 return TokError("expected function name");
2733 if (Lex.getKind() != lltok::lparen)
2734 return TokError("expected '(' in function argument list");
2736 std::vector<ArgInfo> ArgList;
2739 std::string Section;
2743 LocTy UnnamedAddrLoc;
2745 if (ParseArgumentList(ArgList, isVarArg, false) ||
2746 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2748 ParseOptionalAttrs(FuncAttrs, 2) ||
2749 (EatIfPresent(lltok::kw_section) &&
2750 ParseStringConstant(Section)) ||
2751 ParseOptionalAlignment(Alignment) ||
2752 (EatIfPresent(lltok::kw_gc) &&
2753 ParseStringConstant(GC)))
2756 // If the alignment was parsed as an attribute, move to the alignment field.
2757 if (FuncAttrs & Attribute::Alignment) {
2758 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2759 FuncAttrs &= ~Attribute::Alignment;
2762 // Okay, if we got here, the function is syntactically valid. Convert types
2763 // and do semantic checks.
2764 std::vector<const Type*> ParamTypeList;
2765 SmallVector<AttributeWithIndex, 8> Attrs;
2766 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2768 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2769 if (FuncAttrs & ObsoleteFuncAttrs) {
2770 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2771 FuncAttrs &= ~ObsoleteFuncAttrs;
2774 if (RetAttrs != Attribute::None)
2775 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2777 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2778 ParamTypeList.push_back(ArgList[i].Type);
2779 if (ArgList[i].Attrs != Attribute::None)
2780 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2783 if (FuncAttrs != Attribute::None)
2784 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2786 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2788 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2789 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2791 const FunctionType *FT =
2792 FunctionType::get(RetType, ParamTypeList, isVarArg);
2793 const PointerType *PFT = PointerType::getUnqual(FT);
2796 if (!FunctionName.empty()) {
2797 // If this was a definition of a forward reference, remove the definition
2798 // from the forward reference table and fill in the forward ref.
2799 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2800 ForwardRefVals.find(FunctionName);
2801 if (FRVI != ForwardRefVals.end()) {
2802 Fn = M->getFunction(FunctionName);
2803 if (Fn->getType() != PFT)
2804 return Error(FRVI->second.second, "invalid forward reference to "
2805 "function '" + FunctionName + "' with wrong type!");
2807 ForwardRefVals.erase(FRVI);
2808 } else if ((Fn = M->getFunction(FunctionName))) {
2809 // If this function already exists in the symbol table, then it is
2810 // multiply defined. We accept a few cases for old backwards compat.
2811 // FIXME: Remove this stuff for LLVM 3.0.
2812 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2813 (!Fn->isDeclaration() && isDefine)) {
2814 // If the redefinition has different type or different attributes,
2815 // reject it. If both have bodies, reject it.
2816 return Error(NameLoc, "invalid redefinition of function '" +
2817 FunctionName + "'");
2818 } else if (Fn->isDeclaration()) {
2819 // Make sure to strip off any argument names so we can't get conflicts.
2820 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2824 } else if (M->getNamedValue(FunctionName)) {
2825 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2829 // If this is a definition of a forward referenced function, make sure the
2831 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2832 = ForwardRefValIDs.find(NumberedVals.size());
2833 if (I != ForwardRefValIDs.end()) {
2834 Fn = cast<Function>(I->second.first);
2835 if (Fn->getType() != PFT)
2836 return Error(NameLoc, "type of definition and forward reference of '@" +
2837 Twine(NumberedVals.size()) + "' disagree");
2838 ForwardRefValIDs.erase(I);
2843 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2844 else // Move the forward-reference to the correct spot in the module.
2845 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2847 if (FunctionName.empty())
2848 NumberedVals.push_back(Fn);
2850 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2851 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2852 Fn->setCallingConv(CC);
2853 Fn->setAttributes(PAL);
2854 Fn->setUnnamedAddr(UnnamedAddr);
2855 Fn->setAlignment(Alignment);
2856 Fn->setSection(Section);
2857 if (!GC.empty()) Fn->setGC(GC.c_str());
2859 // Add all of the arguments we parsed to the function.
2860 Function::arg_iterator ArgIt = Fn->arg_begin();
2861 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2862 // If we run out of arguments in the Function prototype, exit early.
2863 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2864 if (ArgIt == Fn->arg_end()) break;
2866 // If the argument has a name, insert it into the argument symbol table.
2867 if (ArgList[i].Name.empty()) continue;
2869 // Set the name, if it conflicted, it will be auto-renamed.
2870 ArgIt->setName(ArgList[i].Name);
2872 if (ArgIt->getName() != ArgList[i].Name)
2873 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2874 ArgList[i].Name + "'");
2881 /// ParseFunctionBody
2882 /// ::= '{' BasicBlock+ '}'
2883 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2885 bool LLParser::ParseFunctionBody(Function &Fn) {
2886 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2887 return TokError("expected '{' in function body");
2888 Lex.Lex(); // eat the {.
2890 int FunctionNumber = -1;
2891 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2893 PerFunctionState PFS(*this, Fn, FunctionNumber);
2895 // We need at least one basic block.
2896 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_end)
2897 return TokError("function body requires at least one basic block");
2899 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2900 if (ParseBasicBlock(PFS)) return true;
2905 // Verify function is ok.
2906 return PFS.FinishFunction();
2910 /// ::= LabelStr? Instruction*
2911 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2912 // If this basic block starts out with a name, remember it.
2914 LocTy NameLoc = Lex.getLoc();
2915 if (Lex.getKind() == lltok::LabelStr) {
2916 Name = Lex.getStrVal();
2920 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2921 if (BB == 0) return true;
2923 std::string NameStr;
2925 // Parse the instructions in this block until we get a terminator.
2927 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2929 // This instruction may have three possibilities for a name: a) none
2930 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2931 LocTy NameLoc = Lex.getLoc();
2935 if (Lex.getKind() == lltok::LocalVarID) {
2936 NameID = Lex.getUIntVal();
2938 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2940 } else if (Lex.getKind() == lltok::LocalVar ||
2941 // FIXME: REMOVE IN LLVM 3.0
2942 Lex.getKind() == lltok::StringConstant) {
2943 NameStr = Lex.getStrVal();
2945 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2949 switch (ParseInstruction(Inst, BB, PFS)) {
2950 default: assert(0 && "Unknown ParseInstruction result!");
2951 case InstError: return true;
2953 BB->getInstList().push_back(Inst);
2955 // With a normal result, we check to see if the instruction is followed by
2956 // a comma and metadata.
2957 if (EatIfPresent(lltok::comma))
2958 if (ParseInstructionMetadata(Inst, &PFS))
2961 case InstExtraComma:
2962 BB->getInstList().push_back(Inst);
2964 // If the instruction parser ate an extra comma at the end of it, it
2965 // *must* be followed by metadata.
2966 if (ParseInstructionMetadata(Inst, &PFS))
2971 // Set the name on the instruction.
2972 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2973 } while (!isa<TerminatorInst>(Inst));
2978 //===----------------------------------------------------------------------===//
2979 // Instruction Parsing.
2980 //===----------------------------------------------------------------------===//
2982 /// ParseInstruction - Parse one of the many different instructions.
2984 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2985 PerFunctionState &PFS) {
2986 lltok::Kind Token = Lex.getKind();
2987 if (Token == lltok::Eof)
2988 return TokError("found end of file when expecting more instructions");
2989 LocTy Loc = Lex.getLoc();
2990 unsigned KeywordVal = Lex.getUIntVal();
2991 Lex.Lex(); // Eat the keyword.
2994 default: return Error(Loc, "expected instruction opcode");
2995 // Terminator Instructions.
2996 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2997 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2998 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2999 case lltok::kw_br: return ParseBr(Inst, PFS);
3000 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3001 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3002 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3003 // Binary Operators.
3007 case lltok::kw_shl: {
3008 LocTy ModifierLoc = Lex.getLoc();
3009 bool NUW = EatIfPresent(lltok::kw_nuw);
3010 bool NSW = EatIfPresent(lltok::kw_nsw);
3011 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3013 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3015 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3016 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3019 case lltok::kw_fadd:
3020 case lltok::kw_fsub:
3021 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3023 case lltok::kw_sdiv:
3024 case lltok::kw_udiv:
3025 case lltok::kw_lshr:
3026 case lltok::kw_ashr: {
3027 bool Exact = EatIfPresent(lltok::kw_exact);
3029 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3030 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3034 case lltok::kw_urem:
3035 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3036 case lltok::kw_fdiv:
3037 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3040 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3041 case lltok::kw_icmp:
3042 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3044 case lltok::kw_trunc:
3045 case lltok::kw_zext:
3046 case lltok::kw_sext:
3047 case lltok::kw_fptrunc:
3048 case lltok::kw_fpext:
3049 case lltok::kw_bitcast:
3050 case lltok::kw_uitofp:
3051 case lltok::kw_sitofp:
3052 case lltok::kw_fptoui:
3053 case lltok::kw_fptosi:
3054 case lltok::kw_inttoptr:
3055 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3057 case lltok::kw_select: return ParseSelect(Inst, PFS);
3058 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3059 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3060 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3061 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3062 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3063 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3064 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3066 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3067 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, BB, false);
3068 case lltok::kw_free: return ParseFree(Inst, PFS, BB);
3069 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
3070 case lltok::kw_store: return ParseStore(Inst, PFS, false);
3071 case lltok::kw_volatile:
3072 if (EatIfPresent(lltok::kw_load))
3073 return ParseLoad(Inst, PFS, true);
3074 else if (EatIfPresent(lltok::kw_store))
3075 return ParseStore(Inst, PFS, true);
3077 return TokError("expected 'load' or 'store'");
3078 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
3079 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3080 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3081 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3085 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3086 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3087 if (Opc == Instruction::FCmp) {
3088 switch (Lex.getKind()) {
3089 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3090 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3091 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3092 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3093 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3094 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3095 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3096 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3097 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3098 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3099 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3100 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3101 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3102 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3103 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3104 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3105 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3108 switch (Lex.getKind()) {
3109 default: TokError("expected icmp predicate (e.g. 'eq')");
3110 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3111 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3112 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3113 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3114 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3115 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3116 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3117 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3118 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3119 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3126 //===----------------------------------------------------------------------===//
3127 // Terminator Instructions.
3128 //===----------------------------------------------------------------------===//
3130 /// ParseRet - Parse a return instruction.
3131 /// ::= 'ret' void (',' !dbg, !1)*
3132 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3133 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ (',' !dbg, !1)*
3134 /// [[obsolete: LLVM 3.0]]
3135 int LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3136 PerFunctionState &PFS) {
3137 PATypeHolder Ty(Type::getVoidTy(Context));
3138 if (ParseType(Ty, true /*void allowed*/)) return true;
3140 if (Ty->isVoidTy()) {
3141 Inst = ReturnInst::Create(Context);
3146 if (ParseValue(Ty, RV, PFS)) return true;
3148 bool ExtraComma = false;
3149 if (EatIfPresent(lltok::comma)) {
3150 // Parse optional custom metadata, e.g. !dbg
3151 if (Lex.getKind() == lltok::MetadataVar) {
3154 // The normal case is one return value.
3155 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring
3156 // use of 'ret {i32,i32} {i32 1, i32 2}'
3157 SmallVector<Value*, 8> RVs;
3161 // If optional custom metadata, e.g. !dbg is seen then this is the
3163 if (Lex.getKind() == lltok::MetadataVar)
3165 if (ParseTypeAndValue(RV, PFS)) return true;
3167 } while (EatIfPresent(lltok::comma));
3169 RV = UndefValue::get(PFS.getFunction().getReturnType());
3170 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
3171 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
3172 BB->getInstList().push_back(I);
3178 Inst = ReturnInst::Create(Context, RV);
3179 return ExtraComma ? InstExtraComma : InstNormal;
3184 /// ::= 'br' TypeAndValue
3185 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3186 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3189 BasicBlock *Op1, *Op2;
3190 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3192 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3193 Inst = BranchInst::Create(BB);
3197 if (Op0->getType() != Type::getInt1Ty(Context))
3198 return Error(Loc, "branch condition must have 'i1' type");
3200 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3201 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3202 ParseToken(lltok::comma, "expected ',' after true destination") ||
3203 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3206 Inst = BranchInst::Create(Op1, Op2, Op0);
3212 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3214 /// ::= (TypeAndValue ',' TypeAndValue)*
3215 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3216 LocTy CondLoc, BBLoc;
3218 BasicBlock *DefaultBB;
3219 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3220 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3221 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3222 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3225 if (!Cond->getType()->isIntegerTy())
3226 return Error(CondLoc, "switch condition must have integer type");
3228 // Parse the jump table pairs.
3229 SmallPtrSet<Value*, 32> SeenCases;
3230 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3231 while (Lex.getKind() != lltok::rsquare) {
3235 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3236 ParseToken(lltok::comma, "expected ',' after case value") ||
3237 ParseTypeAndBasicBlock(DestBB, PFS))
3240 if (!SeenCases.insert(Constant))
3241 return Error(CondLoc, "duplicate case value in switch");
3242 if (!isa<ConstantInt>(Constant))
3243 return Error(CondLoc, "case value is not a constant integer");
3245 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3248 Lex.Lex(); // Eat the ']'.
3250 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3251 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3252 SI->addCase(Table[i].first, Table[i].second);
3259 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3260 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3263 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3264 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3265 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3268 if (!Address->getType()->isPointerTy())
3269 return Error(AddrLoc, "indirectbr address must have pointer type");
3271 // Parse the destination list.
3272 SmallVector<BasicBlock*, 16> DestList;
3274 if (Lex.getKind() != lltok::rsquare) {
3276 if (ParseTypeAndBasicBlock(DestBB, PFS))
3278 DestList.push_back(DestBB);
3280 while (EatIfPresent(lltok::comma)) {
3281 if (ParseTypeAndBasicBlock(DestBB, PFS))
3283 DestList.push_back(DestBB);
3287 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3290 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3291 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3292 IBI->addDestination(DestList[i]);
3299 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3300 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3301 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3302 LocTy CallLoc = Lex.getLoc();
3303 unsigned RetAttrs, FnAttrs;
3305 PATypeHolder RetType(Type::getVoidTy(Context));
3308 SmallVector<ParamInfo, 16> ArgList;
3310 BasicBlock *NormalBB, *UnwindBB;
3311 if (ParseOptionalCallingConv(CC) ||
3312 ParseOptionalAttrs(RetAttrs, 1) ||
3313 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3314 ParseValID(CalleeID) ||
3315 ParseParameterList(ArgList, PFS) ||
3316 ParseOptionalAttrs(FnAttrs, 2) ||
3317 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3318 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3319 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3320 ParseTypeAndBasicBlock(UnwindBB, PFS))
3323 // If RetType is a non-function pointer type, then this is the short syntax
3324 // for the call, which means that RetType is just the return type. Infer the
3325 // rest of the function argument types from the arguments that are present.
3326 const PointerType *PFTy = 0;
3327 const FunctionType *Ty = 0;
3328 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3329 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3330 // Pull out the types of all of the arguments...
3331 std::vector<const Type*> ParamTypes;
3332 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3333 ParamTypes.push_back(ArgList[i].V->getType());
3335 if (!FunctionType::isValidReturnType(RetType))
3336 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3338 Ty = FunctionType::get(RetType, ParamTypes, false);
3339 PFTy = PointerType::getUnqual(Ty);
3342 // Look up the callee.
3344 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3346 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3347 // function attributes.
3348 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3349 if (FnAttrs & ObsoleteFuncAttrs) {
3350 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3351 FnAttrs &= ~ObsoleteFuncAttrs;
3354 // Set up the Attributes for the function.
3355 SmallVector<AttributeWithIndex, 8> Attrs;
3356 if (RetAttrs != Attribute::None)
3357 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3359 SmallVector<Value*, 8> Args;
3361 // Loop through FunctionType's arguments and ensure they are specified
3362 // correctly. Also, gather any parameter attributes.
3363 FunctionType::param_iterator I = Ty->param_begin();
3364 FunctionType::param_iterator E = Ty->param_end();
3365 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3366 const Type *ExpectedTy = 0;
3369 } else if (!Ty->isVarArg()) {
3370 return Error(ArgList[i].Loc, "too many arguments specified");
3373 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3374 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3375 ExpectedTy->getDescription() + "'");
3376 Args.push_back(ArgList[i].V);
3377 if (ArgList[i].Attrs != Attribute::None)
3378 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3382 return Error(CallLoc, "not enough parameters specified for call");
3384 if (FnAttrs != Attribute::None)
3385 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3387 // Finish off the Attributes and check them
3388 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3390 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3391 Args.begin(), Args.end());
3392 II->setCallingConv(CC);
3393 II->setAttributes(PAL);
3400 //===----------------------------------------------------------------------===//
3401 // Binary Operators.
3402 //===----------------------------------------------------------------------===//
3405 /// ::= ArithmeticOps TypeAndValue ',' Value
3407 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3408 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3409 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3410 unsigned Opc, unsigned OperandType) {
3411 LocTy Loc; Value *LHS, *RHS;
3412 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3413 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3414 ParseValue(LHS->getType(), RHS, PFS))
3418 switch (OperandType) {
3419 default: llvm_unreachable("Unknown operand type!");
3420 case 0: // int or FP.
3421 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3422 LHS->getType()->isFPOrFPVectorTy();
3424 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3425 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3429 return Error(Loc, "invalid operand type for instruction");
3431 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3436 /// ::= ArithmeticOps TypeAndValue ',' Value {
3437 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3439 LocTy Loc; Value *LHS, *RHS;
3440 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3441 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3442 ParseValue(LHS->getType(), RHS, PFS))
3445 if (!LHS->getType()->isIntOrIntVectorTy())
3446 return Error(Loc,"instruction requires integer or integer vector operands");
3448 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3454 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3455 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3456 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3458 // Parse the integer/fp comparison predicate.
3462 if (ParseCmpPredicate(Pred, Opc) ||
3463 ParseTypeAndValue(LHS, Loc, PFS) ||
3464 ParseToken(lltok::comma, "expected ',' after compare value") ||
3465 ParseValue(LHS->getType(), RHS, PFS))
3468 if (Opc == Instruction::FCmp) {
3469 if (!LHS->getType()->isFPOrFPVectorTy())
3470 return Error(Loc, "fcmp requires floating point operands");
3471 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3473 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3474 if (!LHS->getType()->isIntOrIntVectorTy() &&
3475 !LHS->getType()->isPointerTy())
3476 return Error(Loc, "icmp requires integer operands");
3477 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3482 //===----------------------------------------------------------------------===//
3483 // Other Instructions.
3484 //===----------------------------------------------------------------------===//
3488 /// ::= CastOpc TypeAndValue 'to' Type
3489 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3491 LocTy Loc; Value *Op;
3492 PATypeHolder DestTy(Type::getVoidTy(Context));
3493 if (ParseTypeAndValue(Op, Loc, PFS) ||
3494 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3498 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3499 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3500 return Error(Loc, "invalid cast opcode for cast from '" +
3501 Op->getType()->getDescription() + "' to '" +
3502 DestTy->getDescription() + "'");
3504 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3509 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3510 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3512 Value *Op0, *Op1, *Op2;
3513 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3514 ParseToken(lltok::comma, "expected ',' after select condition") ||
3515 ParseTypeAndValue(Op1, PFS) ||
3516 ParseToken(lltok::comma, "expected ',' after select value") ||
3517 ParseTypeAndValue(Op2, PFS))
3520 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3521 return Error(Loc, Reason);
3523 Inst = SelectInst::Create(Op0, Op1, Op2);
3528 /// ::= 'va_arg' TypeAndValue ',' Type
3529 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3531 PATypeHolder EltTy(Type::getVoidTy(Context));
3533 if (ParseTypeAndValue(Op, PFS) ||
3534 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3535 ParseType(EltTy, TypeLoc))
3538 if (!EltTy->isFirstClassType())
3539 return Error(TypeLoc, "va_arg requires operand with first class type");
3541 Inst = new VAArgInst(Op, EltTy);
3545 /// ParseExtractElement
3546 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3547 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3550 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3551 ParseToken(lltok::comma, "expected ',' after extract value") ||
3552 ParseTypeAndValue(Op1, PFS))
3555 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3556 return Error(Loc, "invalid extractelement operands");
3558 Inst = ExtractElementInst::Create(Op0, Op1);
3562 /// ParseInsertElement
3563 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3564 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3566 Value *Op0, *Op1, *Op2;
3567 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3568 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3569 ParseTypeAndValue(Op1, PFS) ||
3570 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3571 ParseTypeAndValue(Op2, PFS))
3574 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3575 return Error(Loc, "invalid insertelement operands");
3577 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3581 /// ParseShuffleVector
3582 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3583 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3585 Value *Op0, *Op1, *Op2;
3586 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3587 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3588 ParseTypeAndValue(Op1, PFS) ||
3589 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3590 ParseTypeAndValue(Op2, PFS))
3593 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3594 return Error(Loc, "invalid extractelement operands");
3596 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3601 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3602 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3603 PATypeHolder Ty(Type::getVoidTy(Context));
3605 LocTy TypeLoc = Lex.getLoc();
3607 if (ParseType(Ty) ||
3608 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3609 ParseValue(Ty, Op0, PFS) ||
3610 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3611 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3612 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3615 bool AteExtraComma = false;
3616 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3618 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3620 if (!EatIfPresent(lltok::comma))
3623 if (Lex.getKind() == lltok::MetadataVar) {
3624 AteExtraComma = true;
3628 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3629 ParseValue(Ty, Op0, PFS) ||
3630 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3631 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3632 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3636 if (!Ty->isFirstClassType())
3637 return Error(TypeLoc, "phi node must have first class type");
3639 PHINode *PN = PHINode::Create(Ty);
3640 PN->reserveOperandSpace(PHIVals.size());
3641 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3642 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3644 return AteExtraComma ? InstExtraComma : InstNormal;
3648 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3649 /// ParameterList OptionalAttrs
3650 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3652 unsigned RetAttrs, FnAttrs;
3654 PATypeHolder RetType(Type::getVoidTy(Context));
3657 SmallVector<ParamInfo, 16> ArgList;
3658 LocTy CallLoc = Lex.getLoc();
3660 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3661 ParseOptionalCallingConv(CC) ||
3662 ParseOptionalAttrs(RetAttrs, 1) ||
3663 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3664 ParseValID(CalleeID) ||
3665 ParseParameterList(ArgList, PFS) ||
3666 ParseOptionalAttrs(FnAttrs, 2))
3669 // If RetType is a non-function pointer type, then this is the short syntax
3670 // for the call, which means that RetType is just the return type. Infer the
3671 // rest of the function argument types from the arguments that are present.
3672 const PointerType *PFTy = 0;
3673 const FunctionType *Ty = 0;
3674 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3675 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3676 // Pull out the types of all of the arguments...
3677 std::vector<const Type*> ParamTypes;
3678 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3679 ParamTypes.push_back(ArgList[i].V->getType());
3681 if (!FunctionType::isValidReturnType(RetType))
3682 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3684 Ty = FunctionType::get(RetType, ParamTypes, false);
3685 PFTy = PointerType::getUnqual(Ty);
3688 // Look up the callee.
3690 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3692 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3693 // function attributes.
3694 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3695 if (FnAttrs & ObsoleteFuncAttrs) {
3696 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3697 FnAttrs &= ~ObsoleteFuncAttrs;
3700 // Set up the Attributes for the function.
3701 SmallVector<AttributeWithIndex, 8> Attrs;
3702 if (RetAttrs != Attribute::None)
3703 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3705 SmallVector<Value*, 8> Args;
3707 // Loop through FunctionType's arguments and ensure they are specified
3708 // correctly. Also, gather any parameter attributes.
3709 FunctionType::param_iterator I = Ty->param_begin();
3710 FunctionType::param_iterator E = Ty->param_end();
3711 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3712 const Type *ExpectedTy = 0;
3715 } else if (!Ty->isVarArg()) {
3716 return Error(ArgList[i].Loc, "too many arguments specified");
3719 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3720 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3721 ExpectedTy->getDescription() + "'");
3722 Args.push_back(ArgList[i].V);
3723 if (ArgList[i].Attrs != Attribute::None)
3724 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3728 return Error(CallLoc, "not enough parameters specified for call");
3730 if (FnAttrs != Attribute::None)
3731 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3733 // Finish off the Attributes and check them
3734 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3736 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3737 CI->setTailCall(isTail);
3738 CI->setCallingConv(CC);
3739 CI->setAttributes(PAL);
3744 //===----------------------------------------------------------------------===//
3745 // Memory Instructions.
3746 //===----------------------------------------------------------------------===//
3749 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalInfo)?
3750 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3751 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3752 BasicBlock* BB, bool isAlloca) {
3753 PATypeHolder Ty(Type::getVoidTy(Context));
3756 unsigned Alignment = 0;
3757 if (ParseType(Ty)) return true;
3759 bool AteExtraComma = false;
3760 if (EatIfPresent(lltok::comma)) {
3761 if (Lex.getKind() == lltok::kw_align) {
3762 if (ParseOptionalAlignment(Alignment)) return true;
3763 } else if (Lex.getKind() == lltok::MetadataVar) {
3764 AteExtraComma = true;
3766 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3767 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3772 if (Size && !Size->getType()->isIntegerTy())
3773 return Error(SizeLoc, "element count must have integer type");
3776 Inst = new AllocaInst(Ty, Size, Alignment);
3777 return AteExtraComma ? InstExtraComma : InstNormal;
3780 // Autoupgrade old malloc instruction to malloc call.
3781 // FIXME: Remove in LLVM 3.0.
3782 if (Size && !Size->getType()->isIntegerTy(32))
3783 return Error(SizeLoc, "element count must be i32");
3784 const Type *IntPtrTy = Type::getInt32Ty(Context);
3785 Constant *AllocSize = ConstantExpr::getSizeOf(Ty);
3786 AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, IntPtrTy);
3788 // Prototype malloc as "void *(int32)".
3789 // This function is renamed as "malloc" in ValidateEndOfModule().
3790 MallocF = cast<Function>(
3791 M->getOrInsertFunction("", Type::getInt8PtrTy(Context), IntPtrTy, NULL));
3792 Inst = CallInst::CreateMalloc(BB, IntPtrTy, Ty, AllocSize, Size, MallocF);
3793 return AteExtraComma ? InstExtraComma : InstNormal;
3797 /// ::= 'free' TypeAndValue
3798 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS,
3800 Value *Val; LocTy Loc;
3801 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3802 if (!Val->getType()->isPointerTy())
3803 return Error(Loc, "operand to free must be a pointer");
3804 Inst = CallInst::CreateFree(Val, BB);
3809 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3810 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3812 Value *Val; LocTy Loc;
3813 unsigned Alignment = 0;
3814 bool AteExtraComma = false;
3815 if (ParseTypeAndValue(Val, Loc, PFS) ||
3816 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3819 if (!Val->getType()->isPointerTy() ||
3820 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3821 return Error(Loc, "load operand must be a pointer to a first class type");
3823 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3824 return AteExtraComma ? InstExtraComma : InstNormal;
3828 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3829 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3831 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3832 unsigned Alignment = 0;
3833 bool AteExtraComma = false;
3834 if (ParseTypeAndValue(Val, Loc, PFS) ||
3835 ParseToken(lltok::comma, "expected ',' after store operand") ||
3836 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3837 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3840 if (!Ptr->getType()->isPointerTy())
3841 return Error(PtrLoc, "store operand must be a pointer");
3842 if (!Val->getType()->isFirstClassType())
3843 return Error(Loc, "store operand must be a first class value");
3844 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3845 return Error(Loc, "stored value and pointer type do not match");
3847 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3848 return AteExtraComma ? InstExtraComma : InstNormal;
3852 /// ::= 'getresult' TypeAndValue ',' i32
3853 /// FIXME: Remove support for getresult in LLVM 3.0
3854 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3855 Value *Val; LocTy ValLoc, EltLoc;
3857 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3858 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3859 ParseUInt32(Element, EltLoc))
3862 if (!Val->getType()->isStructTy() && !Val->getType()->isArrayTy())
3863 return Error(ValLoc, "getresult inst requires an aggregate operand");
3864 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3865 return Error(EltLoc, "invalid getresult index for value");
3866 Inst = ExtractValueInst::Create(Val, Element);
3870 /// ParseGetElementPtr
3871 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3872 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3873 Value *Ptr, *Val; LocTy Loc, EltLoc;
3875 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3877 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3879 if (!Ptr->getType()->isPointerTy())
3880 return Error(Loc, "base of getelementptr must be a pointer");
3882 SmallVector<Value*, 16> Indices;
3883 bool AteExtraComma = false;
3884 while (EatIfPresent(lltok::comma)) {
3885 if (Lex.getKind() == lltok::MetadataVar) {
3886 AteExtraComma = true;
3889 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3890 if (!Val->getType()->isIntegerTy())
3891 return Error(EltLoc, "getelementptr index must be an integer");
3892 Indices.push_back(Val);
3895 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3896 Indices.begin(), Indices.end()))
3897 return Error(Loc, "invalid getelementptr indices");
3898 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3900 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3901 return AteExtraComma ? InstExtraComma : InstNormal;
3904 /// ParseExtractValue
3905 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3906 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3907 Value *Val; LocTy Loc;
3908 SmallVector<unsigned, 4> Indices;
3910 if (ParseTypeAndValue(Val, Loc, PFS) ||
3911 ParseIndexList(Indices, AteExtraComma))
3914 if (!Val->getType()->isAggregateType())
3915 return Error(Loc, "extractvalue operand must be aggregate type");
3917 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3919 return Error(Loc, "invalid indices for extractvalue");
3920 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3921 return AteExtraComma ? InstExtraComma : InstNormal;
3924 /// ParseInsertValue
3925 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3926 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3927 Value *Val0, *Val1; LocTy Loc0, Loc1;
3928 SmallVector<unsigned, 4> Indices;
3930 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3931 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3932 ParseTypeAndValue(Val1, Loc1, PFS) ||
3933 ParseIndexList(Indices, AteExtraComma))
3936 if (!Val0->getType()->isAggregateType())
3937 return Error(Loc0, "insertvalue operand must be aggregate type");
3939 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3941 return Error(Loc0, "invalid indices for insertvalue");
3942 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3943 return AteExtraComma ? InstExtraComma : InstNormal;
3946 //===----------------------------------------------------------------------===//
3947 // Embedded metadata.
3948 //===----------------------------------------------------------------------===//
3950 /// ParseMDNodeVector
3951 /// ::= Element (',' Element)*
3953 /// ::= 'null' | TypeAndValue
3954 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3955 PerFunctionState *PFS) {
3956 // Check for an empty list.
3957 if (Lex.getKind() == lltok::rbrace)
3961 // Null is a special case since it is typeless.
3962 if (EatIfPresent(lltok::kw_null)) {
3968 PATypeHolder Ty(Type::getVoidTy(Context));
3970 if (ParseType(Ty) || ParseValID(ID, PFS) ||
3971 ConvertValIDToValue(Ty, ID, V, PFS))
3975 } while (EatIfPresent(lltok::comma));