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 // If there are entries in ForwardRefBlockAddresses at this point, they are
63 // references after the function was defined. Resolve those now.
64 while (!ForwardRefBlockAddresses.empty()) {
65 // Okay, we are referencing an already-parsed function, resolve them now.
67 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
68 if (Fn.Kind == ValID::t_GlobalName)
69 TheFn = M->getFunction(Fn.StrVal);
70 else if (Fn.UIntVal < NumberedVals.size())
71 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
74 return Error(Fn.Loc, "unknown function referenced by blockaddress");
76 // Resolve all these references.
77 if (ResolveForwardRefBlockAddresses(TheFn,
78 ForwardRefBlockAddresses.begin()->second,
82 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
86 if (!ForwardRefTypes.empty())
87 return Error(ForwardRefTypes.begin()->second.second,
88 "use of undefined type named '" +
89 ForwardRefTypes.begin()->first + "'");
90 if (!ForwardRefTypeIDs.empty())
91 return Error(ForwardRefTypeIDs.begin()->second.second,
92 "use of undefined type '%" +
93 Twine(ForwardRefTypeIDs.begin()->first) + "'");
95 if (!ForwardRefVals.empty())
96 return Error(ForwardRefVals.begin()->second.second,
97 "use of undefined value '@" + ForwardRefVals.begin()->first +
100 if (!ForwardRefValIDs.empty())
101 return Error(ForwardRefValIDs.begin()->second.second,
102 "use of undefined value '@" +
103 Twine(ForwardRefValIDs.begin()->first) + "'");
105 if (!ForwardRefMDNodes.empty())
106 return Error(ForwardRefMDNodes.begin()->second.second,
107 "use of undefined metadata '!" +
108 Twine(ForwardRefMDNodes.begin()->first) + "'");
111 // Look for intrinsic functions and CallInst that need to be upgraded
112 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
113 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
115 // Check debug info intrinsics.
116 CheckDebugInfoIntrinsics(M);
120 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
121 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
122 PerFunctionState *PFS) {
123 // Loop over all the references, resolving them.
124 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
127 if (Refs[i].first.Kind == ValID::t_LocalName)
128 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
130 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
131 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
132 return Error(Refs[i].first.Loc,
133 "cannot take address of numeric label after the function is defined");
135 Res = dyn_cast_or_null<BasicBlock>(
136 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
140 return Error(Refs[i].first.Loc,
141 "referenced value is not a basic block");
143 // Get the BlockAddress for this and update references to use it.
144 BlockAddress *BA = BlockAddress::get(TheFn, Res);
145 Refs[i].second->replaceAllUsesWith(BA);
146 Refs[i].second->eraseFromParent();
152 //===----------------------------------------------------------------------===//
153 // Top-Level Entities
154 //===----------------------------------------------------------------------===//
156 bool LLParser::ParseTopLevelEntities() {
158 switch (Lex.getKind()) {
159 default: return TokError("expected top-level entity");
160 case lltok::Eof: return false;
161 case lltok::kw_declare: if (ParseDeclare()) return true; break;
162 case lltok::kw_define: if (ParseDefine()) return true; break;
163 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
164 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
165 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
166 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
167 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
168 case lltok::LocalVar: if (ParseNamedType()) return true; break;
169 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
170 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
171 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
172 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
174 // The Global variable production with no name can have many different
175 // optional leading prefixes, the production is:
176 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
177 // OptionalAddrSpace OptionalUnNammedAddr
178 // ('constant'|'global') ...
179 case lltok::kw_private: // OptionalLinkage
180 case lltok::kw_linker_private: // OptionalLinkage
181 case lltok::kw_linker_private_weak: // OptionalLinkage
182 case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
183 case lltok::kw_internal: // OptionalLinkage
184 case lltok::kw_weak: // OptionalLinkage
185 case lltok::kw_weak_odr: // OptionalLinkage
186 case lltok::kw_linkonce: // OptionalLinkage
187 case lltok::kw_linkonce_odr: // OptionalLinkage
188 case lltok::kw_appending: // OptionalLinkage
189 case lltok::kw_dllexport: // OptionalLinkage
190 case lltok::kw_common: // OptionalLinkage
191 case lltok::kw_dllimport: // OptionalLinkage
192 case lltok::kw_extern_weak: // OptionalLinkage
193 case lltok::kw_external: { // OptionalLinkage
194 unsigned Linkage, Visibility;
195 if (ParseOptionalLinkage(Linkage) ||
196 ParseOptionalVisibility(Visibility) ||
197 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
201 case lltok::kw_default: // OptionalVisibility
202 case lltok::kw_hidden: // OptionalVisibility
203 case lltok::kw_protected: { // OptionalVisibility
205 if (ParseOptionalVisibility(Visibility) ||
206 ParseGlobal("", SMLoc(), 0, false, Visibility))
211 case lltok::kw_thread_local: // OptionalThreadLocal
212 case lltok::kw_addrspace: // OptionalAddrSpace
213 case lltok::kw_constant: // GlobalType
214 case lltok::kw_global: // GlobalType
215 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
223 /// ::= 'module' 'asm' STRINGCONSTANT
224 bool LLParser::ParseModuleAsm() {
225 assert(Lex.getKind() == lltok::kw_module);
229 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
230 ParseStringConstant(AsmStr)) return true;
232 M->appendModuleInlineAsm(AsmStr);
237 /// ::= 'target' 'triple' '=' STRINGCONSTANT
238 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
239 bool LLParser::ParseTargetDefinition() {
240 assert(Lex.getKind() == lltok::kw_target);
243 default: return TokError("unknown target property");
244 case lltok::kw_triple:
246 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
247 ParseStringConstant(Str))
249 M->setTargetTriple(Str);
251 case lltok::kw_datalayout:
253 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
254 ParseStringConstant(Str))
256 M->setDataLayout(Str);
262 /// ::= 'deplibs' '=' '[' ']'
263 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
264 bool LLParser::ParseDepLibs() {
265 assert(Lex.getKind() == lltok::kw_deplibs);
267 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
268 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
271 if (EatIfPresent(lltok::rsquare))
275 if (ParseStringConstant(Str)) return true;
278 while (EatIfPresent(lltok::comma)) {
279 if (ParseStringConstant(Str)) return true;
283 return ParseToken(lltok::rsquare, "expected ']' at end of list");
286 /// ParseUnnamedType:
288 /// ::= LocalVarID '=' 'type' type
289 bool LLParser::ParseUnnamedType() {
290 unsigned TypeID = NumberedTypes.size();
292 // Handle the LocalVarID form.
293 if (Lex.getKind() == lltok::LocalVarID) {
294 if (Lex.getUIntVal() != TypeID)
295 return Error(Lex.getLoc(), "type expected to be numbered '%" +
296 Twine(TypeID) + "'");
297 Lex.Lex(); // eat LocalVarID;
299 if (ParseToken(lltok::equal, "expected '=' after name"))
303 LocTy TypeLoc = Lex.getLoc();
304 if (ParseToken(lltok::kw_type, "expected 'type' after '='")) return true;
306 PATypeHolder Ty(Type::getVoidTy(Context));
307 if (ParseType(Ty)) return true;
309 // See if this type was previously referenced.
310 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
311 FI = ForwardRefTypeIDs.find(TypeID);
312 if (FI != ForwardRefTypeIDs.end()) {
313 if (FI->second.first.get() == Ty)
314 return Error(TypeLoc, "self referential type is invalid");
316 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
317 Ty = FI->second.first.get();
318 ForwardRefTypeIDs.erase(FI);
321 NumberedTypes.push_back(Ty);
327 /// ::= LocalVar '=' 'type' type
328 bool LLParser::ParseNamedType() {
329 std::string Name = Lex.getStrVal();
330 LocTy NameLoc = Lex.getLoc();
331 Lex.Lex(); // eat LocalVar.
333 PATypeHolder Ty(Type::getVoidTy(Context));
335 if (ParseToken(lltok::equal, "expected '=' after name") ||
336 ParseToken(lltok::kw_type, "expected 'type' after name") ||
340 // Set the type name, checking for conflicts as we do so.
341 bool AlreadyExists = M->addTypeName(Name, Ty);
342 if (!AlreadyExists) return false;
344 // See if this type is a forward reference. We need to eagerly resolve
345 // types to allow recursive type redefinitions below.
346 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
347 FI = ForwardRefTypes.find(Name);
348 if (FI != ForwardRefTypes.end()) {
349 if (FI->second.first.get() == Ty)
350 return Error(NameLoc, "self referential type is invalid");
352 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
353 Ty = FI->second.first.get();
354 ForwardRefTypes.erase(FI);
358 // Inserting a name that is already defined, get the existing name.
359 const Type *Existing = M->getTypeByName(Name);
360 assert(Existing && "Conflict but no matching type?!");
362 // Otherwise, this is an attempt to redefine a type, report the error.
363 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
364 Ty->getDescription() + "'");
369 /// ::= 'declare' FunctionHeader
370 bool LLParser::ParseDeclare() {
371 assert(Lex.getKind() == lltok::kw_declare);
375 return ParseFunctionHeader(F, false);
379 /// ::= 'define' FunctionHeader '{' ...
380 bool LLParser::ParseDefine() {
381 assert(Lex.getKind() == lltok::kw_define);
385 return ParseFunctionHeader(F, true) ||
386 ParseFunctionBody(*F);
392 bool LLParser::ParseGlobalType(bool &IsConstant) {
393 if (Lex.getKind() == lltok::kw_constant)
395 else if (Lex.getKind() == lltok::kw_global)
399 return TokError("expected 'global' or 'constant'");
405 /// ParseUnnamedGlobal:
406 /// OptionalVisibility ALIAS ...
407 /// OptionalLinkage OptionalVisibility ... -> global variable
408 /// GlobalID '=' OptionalVisibility ALIAS ...
409 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
410 bool LLParser::ParseUnnamedGlobal() {
411 unsigned VarID = NumberedVals.size();
413 LocTy NameLoc = Lex.getLoc();
415 // Handle the GlobalID form.
416 if (Lex.getKind() == lltok::GlobalID) {
417 if (Lex.getUIntVal() != VarID)
418 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
420 Lex.Lex(); // eat GlobalID;
422 if (ParseToken(lltok::equal, "expected '=' after name"))
427 unsigned Linkage, Visibility;
428 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
429 ParseOptionalVisibility(Visibility))
432 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
433 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
434 return ParseAlias(Name, NameLoc, Visibility);
437 /// ParseNamedGlobal:
438 /// GlobalVar '=' OptionalVisibility ALIAS ...
439 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
440 bool LLParser::ParseNamedGlobal() {
441 assert(Lex.getKind() == lltok::GlobalVar);
442 LocTy NameLoc = Lex.getLoc();
443 std::string Name = Lex.getStrVal();
447 unsigned Linkage, Visibility;
448 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
449 ParseOptionalLinkage(Linkage, HasLinkage) ||
450 ParseOptionalVisibility(Visibility))
453 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
454 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
455 return ParseAlias(Name, NameLoc, Visibility);
459 // ::= '!' STRINGCONSTANT
460 bool LLParser::ParseMDString(MDString *&Result) {
462 if (ParseStringConstant(Str)) return true;
463 Result = MDString::get(Context, Str);
468 // ::= '!' MDNodeNumber
470 /// This version of ParseMDNodeID returns the slot number and null in the case
471 /// of a forward reference.
472 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
473 // !{ ..., !42, ... }
474 if (ParseUInt32(SlotNo)) return true;
476 // Check existing MDNode.
477 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
478 Result = NumberedMetadata[SlotNo];
484 bool LLParser::ParseMDNodeID(MDNode *&Result) {
485 // !{ ..., !42, ... }
487 if (ParseMDNodeID(Result, MID)) return true;
489 // If not a forward reference, just return it now.
490 if (Result) return false;
492 // Otherwise, create MDNode forward reference.
493 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
494 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
496 if (NumberedMetadata.size() <= MID)
497 NumberedMetadata.resize(MID+1);
498 NumberedMetadata[MID] = FwdNode;
503 /// ParseNamedMetadata:
504 /// !foo = !{ !1, !2 }
505 bool LLParser::ParseNamedMetadata() {
506 assert(Lex.getKind() == lltok::MetadataVar);
507 std::string Name = Lex.getStrVal();
510 if (ParseToken(lltok::equal, "expected '=' here") ||
511 ParseToken(lltok::exclaim, "Expected '!' here") ||
512 ParseToken(lltok::lbrace, "Expected '{' here"))
515 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
516 if (Lex.getKind() != lltok::rbrace)
518 if (ParseToken(lltok::exclaim, "Expected '!' here"))
522 if (ParseMDNodeID(N)) return true;
524 } while (EatIfPresent(lltok::comma));
526 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
532 /// ParseStandaloneMetadata:
534 bool LLParser::ParseStandaloneMetadata() {
535 assert(Lex.getKind() == lltok::exclaim);
537 unsigned MetadataID = 0;
540 PATypeHolder Ty(Type::getVoidTy(Context));
541 SmallVector<Value *, 16> Elts;
542 if (ParseUInt32(MetadataID) ||
543 ParseToken(lltok::equal, "expected '=' here") ||
544 ParseType(Ty, TyLoc) ||
545 ParseToken(lltok::exclaim, "Expected '!' here") ||
546 ParseToken(lltok::lbrace, "Expected '{' here") ||
547 ParseMDNodeVector(Elts, NULL) ||
548 ParseToken(lltok::rbrace, "expected end of metadata node"))
551 MDNode *Init = MDNode::get(Context, Elts);
553 // See if this was forward referenced, if so, handle it.
554 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
555 FI = ForwardRefMDNodes.find(MetadataID);
556 if (FI != ForwardRefMDNodes.end()) {
557 MDNode *Temp = FI->second.first;
558 Temp->replaceAllUsesWith(Init);
559 MDNode::deleteTemporary(Temp);
560 ForwardRefMDNodes.erase(FI);
562 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
564 if (MetadataID >= NumberedMetadata.size())
565 NumberedMetadata.resize(MetadataID+1);
567 if (NumberedMetadata[MetadataID] != 0)
568 return TokError("Metadata id is already used");
569 NumberedMetadata[MetadataID] = Init;
576 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
579 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
580 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
582 /// Everything through visibility has already been parsed.
584 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
585 unsigned Visibility) {
586 assert(Lex.getKind() == lltok::kw_alias);
589 LocTy LinkageLoc = Lex.getLoc();
590 if (ParseOptionalLinkage(Linkage))
593 if (Linkage != GlobalValue::ExternalLinkage &&
594 Linkage != GlobalValue::WeakAnyLinkage &&
595 Linkage != GlobalValue::WeakODRLinkage &&
596 Linkage != GlobalValue::InternalLinkage &&
597 Linkage != GlobalValue::PrivateLinkage &&
598 Linkage != GlobalValue::LinkerPrivateLinkage &&
599 Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
600 Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
601 return Error(LinkageLoc, "invalid linkage type for alias");
604 LocTy AliaseeLoc = Lex.getLoc();
605 if (Lex.getKind() != lltok::kw_bitcast &&
606 Lex.getKind() != lltok::kw_getelementptr) {
607 if (ParseGlobalTypeAndValue(Aliasee)) return true;
609 // The bitcast dest type is not present, it is implied by the dest type.
611 if (ParseValID(ID)) return true;
612 if (ID.Kind != ValID::t_Constant)
613 return Error(AliaseeLoc, "invalid aliasee");
614 Aliasee = ID.ConstantVal;
617 if (!Aliasee->getType()->isPointerTy())
618 return Error(AliaseeLoc, "alias must have pointer type");
620 // Okay, create the alias but do not insert it into the module yet.
621 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
622 (GlobalValue::LinkageTypes)Linkage, Name,
624 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
626 // See if this value already exists in the symbol table. If so, it is either
627 // a redefinition or a definition of a forward reference.
628 if (GlobalValue *Val = M->getNamedValue(Name)) {
629 // See if this was a redefinition. If so, there is no entry in
631 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
632 I = ForwardRefVals.find(Name);
633 if (I == ForwardRefVals.end())
634 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
636 // Otherwise, this was a definition of forward ref. Verify that types
638 if (Val->getType() != GA->getType())
639 return Error(NameLoc,
640 "forward reference and definition of alias have different types");
642 // If they agree, just RAUW the old value with the alias and remove the
644 Val->replaceAllUsesWith(GA);
645 Val->eraseFromParent();
646 ForwardRefVals.erase(I);
649 // Insert into the module, we know its name won't collide now.
650 M->getAliasList().push_back(GA);
651 assert(GA->getName() == Name && "Should not be a name conflict!");
657 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
658 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
659 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
660 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
662 /// Everything through visibility has been parsed already.
664 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
665 unsigned Linkage, bool HasLinkage,
666 unsigned Visibility) {
668 bool ThreadLocal, IsConstant, UnnamedAddr;
669 LocTy UnnamedAddrLoc;
672 PATypeHolder Ty(Type::getVoidTy(Context));
673 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
674 ParseOptionalAddrSpace(AddrSpace) ||
675 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
677 ParseGlobalType(IsConstant) ||
678 ParseType(Ty, TyLoc))
681 // If the linkage is specified and is external, then no initializer is
684 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
685 Linkage != GlobalValue::ExternalWeakLinkage &&
686 Linkage != GlobalValue::ExternalLinkage)) {
687 if (ParseGlobalValue(Ty, Init))
691 if (Ty->isFunctionTy() || Ty->isLabelTy())
692 return Error(TyLoc, "invalid type for global variable");
694 GlobalVariable *GV = 0;
696 // See if the global was forward referenced, if so, use the global.
698 if (GlobalValue *GVal = M->getNamedValue(Name)) {
699 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
700 return Error(NameLoc, "redefinition of global '@" + Name + "'");
701 GV = cast<GlobalVariable>(GVal);
704 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
705 I = ForwardRefValIDs.find(NumberedVals.size());
706 if (I != ForwardRefValIDs.end()) {
707 GV = cast<GlobalVariable>(I->second.first);
708 ForwardRefValIDs.erase(I);
713 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
714 Name, 0, false, AddrSpace);
716 if (GV->getType()->getElementType() != Ty)
718 "forward reference and definition of global have different types");
720 // Move the forward-reference to the correct spot in the module.
721 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
725 NumberedVals.push_back(GV);
727 // Set the parsed properties on the global.
729 GV->setInitializer(Init);
730 GV->setConstant(IsConstant);
731 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
732 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
733 GV->setThreadLocal(ThreadLocal);
734 GV->setUnnamedAddr(UnnamedAddr);
736 // Parse attributes on the global.
737 while (Lex.getKind() == lltok::comma) {
740 if (Lex.getKind() == lltok::kw_section) {
742 GV->setSection(Lex.getStrVal());
743 if (ParseToken(lltok::StringConstant, "expected global section string"))
745 } else if (Lex.getKind() == lltok::kw_align) {
747 if (ParseOptionalAlignment(Alignment)) return true;
748 GV->setAlignment(Alignment);
750 TokError("unknown global variable property!");
758 //===----------------------------------------------------------------------===//
759 // GlobalValue Reference/Resolution Routines.
760 //===----------------------------------------------------------------------===//
762 /// GetGlobalVal - Get a value with the specified name or ID, creating a
763 /// forward reference record if needed. This can return null if the value
764 /// exists but does not have the right type.
765 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
767 const PointerType *PTy = dyn_cast<PointerType>(Ty);
769 Error(Loc, "global variable reference must have pointer type");
773 // Look this name up in the normal function symbol table.
775 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
777 // If this is a forward reference for the value, see if we already created a
778 // forward ref record.
780 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
781 I = ForwardRefVals.find(Name);
782 if (I != ForwardRefVals.end())
783 Val = I->second.first;
786 // If we have the value in the symbol table or fwd-ref table, return it.
788 if (Val->getType() == Ty) return Val;
789 Error(Loc, "'@" + Name + "' defined with type '" +
790 Val->getType()->getDescription() + "'");
794 // Otherwise, create a new forward reference for this value and remember it.
796 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
797 // Function types can return opaque but functions can't.
798 if (FT->getReturnType()->isOpaqueTy()) {
799 Error(Loc, "function may not return opaque type");
803 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
805 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
806 GlobalValue::ExternalWeakLinkage, 0, Name);
809 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
813 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
814 const PointerType *PTy = dyn_cast<PointerType>(Ty);
816 Error(Loc, "global variable reference must have pointer type");
820 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
822 // If this is a forward reference for the value, see if we already created a
823 // forward ref record.
825 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
826 I = ForwardRefValIDs.find(ID);
827 if (I != ForwardRefValIDs.end())
828 Val = I->second.first;
831 // If we have the value in the symbol table or fwd-ref table, return it.
833 if (Val->getType() == Ty) return Val;
834 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
835 Val->getType()->getDescription() + "'");
839 // Otherwise, create a new forward reference for this value and remember it.
841 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
842 // Function types can return opaque but functions can't.
843 if (FT->getReturnType()->isOpaqueTy()) {
844 Error(Loc, "function may not return opaque type");
847 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
849 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
850 GlobalValue::ExternalWeakLinkage, 0, "");
853 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
858 //===----------------------------------------------------------------------===//
860 //===----------------------------------------------------------------------===//
862 /// ParseToken - If the current token has the specified kind, eat it and return
863 /// success. Otherwise, emit the specified error and return failure.
864 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
865 if (Lex.getKind() != T)
866 return TokError(ErrMsg);
871 /// ParseStringConstant
872 /// ::= StringConstant
873 bool LLParser::ParseStringConstant(std::string &Result) {
874 if (Lex.getKind() != lltok::StringConstant)
875 return TokError("expected string constant");
876 Result = Lex.getStrVal();
883 bool LLParser::ParseUInt32(unsigned &Val) {
884 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
885 return TokError("expected integer");
886 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
887 if (Val64 != unsigned(Val64))
888 return TokError("expected 32-bit integer (too large)");
895 /// ParseOptionalAddrSpace
897 /// := 'addrspace' '(' uint32 ')'
898 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
900 if (!EatIfPresent(lltok::kw_addrspace))
902 return ParseToken(lltok::lparen, "expected '(' in address space") ||
903 ParseUInt32(AddrSpace) ||
904 ParseToken(lltok::rparen, "expected ')' in address space");
907 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
908 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
909 /// 2: function attr.
910 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
911 Attrs = Attribute::None;
912 LocTy AttrLoc = Lex.getLoc();
915 switch (Lex.getKind()) {
916 default: // End of attributes.
917 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
918 return Error(AttrLoc, "invalid use of function-only attribute");
920 // As a hack, we allow "align 2" on functions as a synonym for
923 (Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
924 return Error(AttrLoc, "invalid use of attribute on a function");
926 if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
927 return Error(AttrLoc, "invalid use of parameter-only attribute");
930 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
931 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
932 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
933 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
934 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
935 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
936 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
937 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
939 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
940 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
941 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
942 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
943 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
944 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
945 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
946 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
947 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
948 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
949 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
950 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
951 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
952 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
953 case lltok::kw_hotpatch: Attrs |= Attribute::Hotpatch; break;
954 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
956 case lltok::kw_alignstack: {
958 if (ParseOptionalStackAlignment(Alignment))
960 Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
964 case lltok::kw_align: {
966 if (ParseOptionalAlignment(Alignment))
968 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
977 /// ParseOptionalLinkage
980 /// ::= 'linker_private'
981 /// ::= 'linker_private_weak'
982 /// ::= 'linker_private_weak_def_auto'
987 /// ::= 'linkonce_odr'
988 /// ::= 'available_externally'
993 /// ::= 'extern_weak'
995 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
997 switch (Lex.getKind()) {
998 default: Res=GlobalValue::ExternalLinkage; return false;
999 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1000 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1001 case lltok::kw_linker_private_weak:
1002 Res = GlobalValue::LinkerPrivateWeakLinkage;
1004 case lltok::kw_linker_private_weak_def_auto:
1005 Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
1007 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1008 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1009 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1010 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1011 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1012 case lltok::kw_available_externally:
1013 Res = GlobalValue::AvailableExternallyLinkage;
1015 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1016 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1017 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1018 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1019 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1020 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1027 /// ParseOptionalVisibility
1033 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1034 switch (Lex.getKind()) {
1035 default: Res = GlobalValue::DefaultVisibility; return false;
1036 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1037 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1038 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1044 /// ParseOptionalCallingConv
1049 /// ::= 'x86_stdcallcc'
1050 /// ::= 'x86_fastcallcc'
1051 /// ::= 'x86_thiscallcc'
1052 /// ::= 'arm_apcscc'
1053 /// ::= 'arm_aapcscc'
1054 /// ::= 'arm_aapcs_vfpcc'
1055 /// ::= 'msp430_intrcc'
1056 /// ::= 'ptx_kernel'
1057 /// ::= 'ptx_device'
1060 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1061 switch (Lex.getKind()) {
1062 default: CC = CallingConv::C; return false;
1063 case lltok::kw_ccc: CC = CallingConv::C; break;
1064 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1065 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1066 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1067 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1068 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1069 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1070 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1071 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1072 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1073 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1074 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1075 case lltok::kw_cc: {
1076 unsigned ArbitraryCC;
1078 if (ParseUInt32(ArbitraryCC)) {
1081 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1091 /// ParseInstructionMetadata
1092 /// ::= !dbg !42 (',' !dbg !57)*
1093 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1094 PerFunctionState *PFS) {
1096 if (Lex.getKind() != lltok::MetadataVar)
1097 return TokError("expected metadata after comma");
1099 std::string Name = Lex.getStrVal();
1100 unsigned MDK = M->getMDKindID(Name.c_str());
1104 SMLoc Loc = Lex.getLoc();
1106 if (ParseToken(lltok::exclaim, "expected '!' here"))
1109 // This code is similar to that of ParseMetadataValue, however it needs to
1110 // have special-case code for a forward reference; see the comments on
1111 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1112 // at the top level here.
1113 if (Lex.getKind() == lltok::lbrace) {
1115 if (ParseMetadataListValue(ID, PFS))
1117 assert(ID.Kind == ValID::t_MDNode);
1118 Inst->setMetadata(MDK, ID.MDNodeVal);
1120 unsigned NodeID = 0;
1121 if (ParseMDNodeID(Node, NodeID))
1124 // If we got the node, add it to the instruction.
1125 Inst->setMetadata(MDK, Node);
1127 MDRef R = { Loc, MDK, NodeID };
1128 // Otherwise, remember that this should be resolved later.
1129 ForwardRefInstMetadata[Inst].push_back(R);
1133 // If this is the end of the list, we're done.
1134 } while (EatIfPresent(lltok::comma));
1138 /// ParseOptionalAlignment
1141 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1143 if (!EatIfPresent(lltok::kw_align))
1145 LocTy AlignLoc = Lex.getLoc();
1146 if (ParseUInt32(Alignment)) return true;
1147 if (!isPowerOf2_32(Alignment))
1148 return Error(AlignLoc, "alignment is not a power of two");
1149 if (Alignment > Value::MaximumAlignment)
1150 return Error(AlignLoc, "huge alignments are not supported yet");
1154 /// ParseOptionalCommaAlign
1158 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1160 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1161 bool &AteExtraComma) {
1162 AteExtraComma = false;
1163 while (EatIfPresent(lltok::comma)) {
1164 // Metadata at the end is an early exit.
1165 if (Lex.getKind() == lltok::MetadataVar) {
1166 AteExtraComma = true;
1170 if (Lex.getKind() != lltok::kw_align)
1171 return Error(Lex.getLoc(), "expected metadata or 'align'");
1173 if (ParseOptionalAlignment(Alignment)) return true;
1179 /// ParseOptionalStackAlignment
1181 /// ::= 'alignstack' '(' 4 ')'
1182 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1184 if (!EatIfPresent(lltok::kw_alignstack))
1186 LocTy ParenLoc = Lex.getLoc();
1187 if (!EatIfPresent(lltok::lparen))
1188 return Error(ParenLoc, "expected '('");
1189 LocTy AlignLoc = Lex.getLoc();
1190 if (ParseUInt32(Alignment)) return true;
1191 ParenLoc = Lex.getLoc();
1192 if (!EatIfPresent(lltok::rparen))
1193 return Error(ParenLoc, "expected ')'");
1194 if (!isPowerOf2_32(Alignment))
1195 return Error(AlignLoc, "stack alignment is not a power of two");
1199 /// ParseIndexList - This parses the index list for an insert/extractvalue
1200 /// instruction. This sets AteExtraComma in the case where we eat an extra
1201 /// comma at the end of the line and find that it is followed by metadata.
1202 /// Clients that don't allow metadata can call the version of this function that
1203 /// only takes one argument.
1206 /// ::= (',' uint32)+
1208 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1209 bool &AteExtraComma) {
1210 AteExtraComma = false;
1212 if (Lex.getKind() != lltok::comma)
1213 return TokError("expected ',' as start of index list");
1215 while (EatIfPresent(lltok::comma)) {
1216 if (Lex.getKind() == lltok::MetadataVar) {
1217 AteExtraComma = true;
1221 if (ParseUInt32(Idx)) return true;
1222 Indices.push_back(Idx);
1228 //===----------------------------------------------------------------------===//
1230 //===----------------------------------------------------------------------===//
1232 /// ParseType - Parse and resolve a full type.
1233 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
1234 LocTy TypeLoc = Lex.getLoc();
1235 if (ParseTypeRec(Result)) return true;
1237 // Verify no unresolved uprefs.
1238 if (!UpRefs.empty())
1239 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
1241 if (!AllowVoid && Result.get()->isVoidTy())
1242 return Error(TypeLoc, "void type only allowed for function results");
1247 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1248 /// called. It loops through the UpRefs vector, which is a list of the
1249 /// currently active types. For each type, if the up-reference is contained in
1250 /// the newly completed type, we decrement the level count. When the level
1251 /// count reaches zero, the up-referenced type is the type that is passed in:
1252 /// thus we can complete the cycle.
1254 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
1255 // If Ty isn't abstract, or if there are no up-references in it, then there is
1256 // nothing to resolve here.
1257 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1259 PATypeHolder Ty(ty);
1261 dbgs() << "Type '" << Ty->getDescription()
1262 << "' newly formed. Resolving upreferences.\n"
1263 << UpRefs.size() << " upreferences active!\n";
1266 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1267 // to zero), we resolve them all together before we resolve them to Ty. At
1268 // the end of the loop, if there is anything to resolve to Ty, it will be in
1270 OpaqueType *TypeToResolve = 0;
1272 for (unsigned i = 0; i != UpRefs.size(); ++i) {
1273 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1275 std::find(Ty->subtype_begin(), Ty->subtype_end(),
1276 UpRefs[i].LastContainedTy) != Ty->subtype_end();
1279 dbgs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1280 << UpRefs[i].LastContainedTy->getDescription() << ") = "
1281 << (ContainsType ? "true" : "false")
1282 << " level=" << UpRefs[i].NestingLevel << "\n";
1287 // Decrement level of upreference
1288 unsigned Level = --UpRefs[i].NestingLevel;
1289 UpRefs[i].LastContainedTy = Ty;
1291 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1296 dbgs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
1299 TypeToResolve = UpRefs[i].UpRefTy;
1301 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1302 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
1303 --i; // Do not skip the next element.
1307 TypeToResolve->refineAbstractTypeTo(Ty);
1313 /// ParseTypeRec - The recursive function used to process the internal
1314 /// implementation details of types.
1315 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
1316 switch (Lex.getKind()) {
1318 return TokError("expected type");
1320 // TypeRec ::= 'float' | 'void' (etc)
1321 Result = Lex.getTyVal();
1324 case lltok::kw_opaque:
1325 // TypeRec ::= 'opaque'
1326 Result = OpaqueType::get(Context);
1330 // TypeRec ::= '{' ... '}'
1331 if (ParseStructType(Result, false))
1334 case lltok::lsquare:
1335 // TypeRec ::= '[' ... ']'
1336 Lex.Lex(); // eat the lsquare.
1337 if (ParseArrayVectorType(Result, false))
1340 case lltok::less: // Either vector or packed struct.
1341 // TypeRec ::= '<' ... '>'
1343 if (Lex.getKind() == lltok::lbrace) {
1344 if (ParseStructType(Result, true) ||
1345 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1347 } else if (ParseArrayVectorType(Result, true))
1350 case lltok::LocalVar:
1352 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
1355 Result = OpaqueType::get(Context);
1356 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
1357 std::make_pair(Result,
1359 M->addTypeName(Lex.getStrVal(), Result.get());
1364 case lltok::LocalVarID:
1366 if (Lex.getUIntVal() < NumberedTypes.size())
1367 Result = NumberedTypes[Lex.getUIntVal()];
1369 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1370 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1371 if (I != ForwardRefTypeIDs.end())
1372 Result = I->second.first;
1374 Result = OpaqueType::get(Context);
1375 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1376 std::make_pair(Result,
1382 case lltok::backslash: {
1383 // TypeRec ::= '\' 4
1386 if (ParseUInt32(Val)) return true;
1387 OpaqueType *OT = OpaqueType::get(Context); //Use temporary placeholder.
1388 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1394 // Parse the type suffixes.
1396 switch (Lex.getKind()) {
1398 default: return false;
1400 // TypeRec ::= TypeRec '*'
1402 if (Result.get()->isLabelTy())
1403 return TokError("basic block pointers are invalid");
1404 if (Result.get()->isVoidTy())
1405 return TokError("pointers to void are invalid; use i8* instead");
1406 if (!PointerType::isValidElementType(Result.get()))
1407 return TokError("pointer to this type is invalid");
1408 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1412 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1413 case lltok::kw_addrspace: {
1414 if (Result.get()->isLabelTy())
1415 return TokError("basic block pointers are invalid");
1416 if (Result.get()->isVoidTy())
1417 return TokError("pointers to void are invalid; use i8* instead");
1418 if (!PointerType::isValidElementType(Result.get()))
1419 return TokError("pointer to this type is invalid");
1421 if (ParseOptionalAddrSpace(AddrSpace) ||
1422 ParseToken(lltok::star, "expected '*' in address space"))
1425 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1429 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1431 if (ParseFunctionType(Result))
1438 /// ParseParameterList
1440 /// ::= '(' Arg (',' Arg)* ')'
1442 /// ::= Type OptionalAttributes Value OptionalAttributes
1443 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1444 PerFunctionState &PFS) {
1445 if (ParseToken(lltok::lparen, "expected '(' in call"))
1448 while (Lex.getKind() != lltok::rparen) {
1449 // If this isn't the first argument, we need a comma.
1450 if (!ArgList.empty() &&
1451 ParseToken(lltok::comma, "expected ',' in argument list"))
1454 // Parse the argument.
1456 PATypeHolder ArgTy(Type::getVoidTy(Context));
1457 unsigned ArgAttrs1 = Attribute::None;
1458 unsigned ArgAttrs2 = Attribute::None;
1460 if (ParseType(ArgTy, ArgLoc))
1463 // Otherwise, handle normal operands.
1464 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
1466 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1469 Lex.Lex(); // Lex the ')'.
1475 /// ParseArgumentList - Parse the argument list for a function type or function
1476 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1477 /// ::= '(' ArgTypeListI ')'
1481 /// ::= ArgTypeList ',' '...'
1482 /// ::= ArgType (',' ArgType)*
1484 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1485 bool &isVarArg, bool inType) {
1487 assert(Lex.getKind() == lltok::lparen);
1488 Lex.Lex(); // eat the (.
1490 if (Lex.getKind() == lltok::rparen) {
1492 } else if (Lex.getKind() == lltok::dotdotdot) {
1496 LocTy TypeLoc = Lex.getLoc();
1497 PATypeHolder ArgTy(Type::getVoidTy(Context));
1501 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1502 // types (such as a function returning a pointer to itself). If parsing a
1503 // function prototype, we require fully resolved types.
1504 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1505 ParseOptionalAttrs(Attrs, 0)) return true;
1507 if (ArgTy->isVoidTy())
1508 return Error(TypeLoc, "argument can not have void type");
1510 if (Lex.getKind() == lltok::LocalVar) {
1511 Name = Lex.getStrVal();
1515 if (!FunctionType::isValidArgumentType(ArgTy))
1516 return Error(TypeLoc, "invalid type for function argument");
1518 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1520 while (EatIfPresent(lltok::comma)) {
1521 // Handle ... at end of arg list.
1522 if (EatIfPresent(lltok::dotdotdot)) {
1527 // Otherwise must be an argument type.
1528 TypeLoc = Lex.getLoc();
1529 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1530 ParseOptionalAttrs(Attrs, 0)) return true;
1532 if (ArgTy->isVoidTy())
1533 return Error(TypeLoc, "argument can not have void type");
1535 if (Lex.getKind() == lltok::LocalVar) {
1536 Name = Lex.getStrVal();
1542 if (!ArgTy->isFirstClassType() && !ArgTy->isOpaqueTy())
1543 return Error(TypeLoc, "invalid type for function argument");
1545 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1549 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1552 /// ParseFunctionType
1553 /// ::= Type ArgumentList OptionalAttrs
1554 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1555 assert(Lex.getKind() == lltok::lparen);
1557 if (!FunctionType::isValidReturnType(Result))
1558 return TokError("invalid function return type");
1560 std::vector<ArgInfo> ArgList;
1562 if (ParseArgumentList(ArgList, isVarArg, true))
1565 // Reject names on the arguments lists.
1566 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1567 if (!ArgList[i].Name.empty())
1568 return Error(ArgList[i].Loc, "argument name invalid in function type");
1569 if (ArgList[i].Attrs != 0)
1570 return Error(ArgList[i].Loc,
1571 "argument attributes invalid in function type");
1574 std::vector<const Type*> ArgListTy;
1575 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1576 ArgListTy.push_back(ArgList[i].Type);
1578 Result = HandleUpRefs(FunctionType::get(Result.get(),
1579 ArgListTy, isVarArg));
1583 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1586 /// ::= '{' TypeRec (',' TypeRec)* '}'
1587 /// ::= '<' '{' '}' '>'
1588 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1589 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1590 assert(Lex.getKind() == lltok::lbrace);
1591 Lex.Lex(); // Consume the '{'
1593 if (EatIfPresent(lltok::rbrace)) {
1594 Result = StructType::get(Context, Packed);
1598 std::vector<PATypeHolder> ParamsList;
1599 LocTy EltTyLoc = Lex.getLoc();
1600 if (ParseTypeRec(Result)) return true;
1601 ParamsList.push_back(Result);
1603 if (Result->isVoidTy())
1604 return Error(EltTyLoc, "struct element can not have void type");
1605 if (!StructType::isValidElementType(Result))
1606 return Error(EltTyLoc, "invalid element type for struct");
1608 while (EatIfPresent(lltok::comma)) {
1609 EltTyLoc = Lex.getLoc();
1610 if (ParseTypeRec(Result)) return true;
1612 if (Result->isVoidTy())
1613 return Error(EltTyLoc, "struct element can not have void type");
1614 if (!StructType::isValidElementType(Result))
1615 return Error(EltTyLoc, "invalid element type for struct");
1617 ParamsList.push_back(Result);
1620 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1623 std::vector<const Type*> ParamsListTy;
1624 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1625 ParamsListTy.push_back(ParamsList[i].get());
1626 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
1630 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1631 /// token has already been consumed.
1633 /// ::= '[' APSINTVAL 'x' Types ']'
1634 /// ::= '<' APSINTVAL 'x' Types '>'
1635 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1636 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1637 Lex.getAPSIntVal().getBitWidth() > 64)
1638 return TokError("expected number in address space");
1640 LocTy SizeLoc = Lex.getLoc();
1641 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1644 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1647 LocTy TypeLoc = Lex.getLoc();
1648 PATypeHolder EltTy(Type::getVoidTy(Context));
1649 if (ParseTypeRec(EltTy)) return true;
1651 if (EltTy->isVoidTy())
1652 return Error(TypeLoc, "array and vector element type cannot be void");
1654 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1655 "expected end of sequential type"))
1660 return Error(SizeLoc, "zero element vector is illegal");
1661 if ((unsigned)Size != Size)
1662 return Error(SizeLoc, "size too large for vector");
1663 if (!VectorType::isValidElementType(EltTy))
1664 return Error(TypeLoc, "vector element type must be fp or integer");
1665 Result = VectorType::get(EltTy, unsigned(Size));
1667 if (!ArrayType::isValidElementType(EltTy))
1668 return Error(TypeLoc, "invalid array element type");
1669 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1674 //===----------------------------------------------------------------------===//
1675 // Function Semantic Analysis.
1676 //===----------------------------------------------------------------------===//
1678 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1680 : P(p), F(f), FunctionNumber(functionNumber) {
1682 // Insert unnamed arguments into the NumberedVals list.
1683 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1686 NumberedVals.push_back(AI);
1689 LLParser::PerFunctionState::~PerFunctionState() {
1690 // If there were any forward referenced non-basicblock values, delete them.
1691 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1692 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1693 if (!isa<BasicBlock>(I->second.first)) {
1694 I->second.first->replaceAllUsesWith(
1695 UndefValue::get(I->second.first->getType()));
1696 delete I->second.first;
1697 I->second.first = 0;
1700 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1701 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1702 if (!isa<BasicBlock>(I->second.first)) {
1703 I->second.first->replaceAllUsesWith(
1704 UndefValue::get(I->second.first->getType()));
1705 delete I->second.first;
1706 I->second.first = 0;
1710 bool LLParser::PerFunctionState::FinishFunction() {
1711 // Check to see if someone took the address of labels in this block.
1712 if (!P.ForwardRefBlockAddresses.empty()) {
1714 if (!F.getName().empty()) {
1715 FunctionID.Kind = ValID::t_GlobalName;
1716 FunctionID.StrVal = F.getName();
1718 FunctionID.Kind = ValID::t_GlobalID;
1719 FunctionID.UIntVal = FunctionNumber;
1722 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1723 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1724 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1725 // Resolve all these references.
1726 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1729 P.ForwardRefBlockAddresses.erase(FRBAI);
1733 if (!ForwardRefVals.empty())
1734 return P.Error(ForwardRefVals.begin()->second.second,
1735 "use of undefined value '%" + ForwardRefVals.begin()->first +
1737 if (!ForwardRefValIDs.empty())
1738 return P.Error(ForwardRefValIDs.begin()->second.second,
1739 "use of undefined value '%" +
1740 Twine(ForwardRefValIDs.begin()->first) + "'");
1745 /// GetVal - Get a value with the specified name or ID, creating a
1746 /// forward reference record if needed. This can return null if the value
1747 /// exists but does not have the right type.
1748 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1749 const Type *Ty, LocTy Loc) {
1750 // Look this name up in the normal function symbol table.
1751 Value *Val = F.getValueSymbolTable().lookup(Name);
1753 // If this is a forward reference for the value, see if we already created a
1754 // forward ref record.
1756 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1757 I = ForwardRefVals.find(Name);
1758 if (I != ForwardRefVals.end())
1759 Val = I->second.first;
1762 // If we have the value in the symbol table or fwd-ref table, return it.
1764 if (Val->getType() == Ty) return Val;
1765 if (Ty->isLabelTy())
1766 P.Error(Loc, "'%" + Name + "' is not a basic block");
1768 P.Error(Loc, "'%" + Name + "' defined with type '" +
1769 Val->getType()->getDescription() + "'");
1773 // Don't make placeholders with invalid type.
1774 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1775 P.Error(Loc, "invalid use of a non-first-class type");
1779 // Otherwise, create a new forward reference for this value and remember it.
1781 if (Ty->isLabelTy())
1782 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1784 FwdVal = new Argument(Ty, Name);
1786 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1790 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1792 // Look this name up in the normal function symbol table.
1793 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1795 // If this is a forward reference for the value, see if we already created a
1796 // forward ref record.
1798 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1799 I = ForwardRefValIDs.find(ID);
1800 if (I != ForwardRefValIDs.end())
1801 Val = I->second.first;
1804 // If we have the value in the symbol table or fwd-ref table, return it.
1806 if (Val->getType() == Ty) return Val;
1807 if (Ty->isLabelTy())
1808 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1810 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1811 Val->getType()->getDescription() + "'");
1815 if (!Ty->isFirstClassType() && !Ty->isOpaqueTy() && !Ty->isLabelTy()) {
1816 P.Error(Loc, "invalid use of a non-first-class type");
1820 // Otherwise, create a new forward reference for this value and remember it.
1822 if (Ty->isLabelTy())
1823 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1825 FwdVal = new Argument(Ty);
1827 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1831 /// SetInstName - After an instruction is parsed and inserted into its
1832 /// basic block, this installs its name.
1833 bool LLParser::PerFunctionState::SetInstName(int NameID,
1834 const std::string &NameStr,
1835 LocTy NameLoc, Instruction *Inst) {
1836 // If this instruction has void type, it cannot have a name or ID specified.
1837 if (Inst->getType()->isVoidTy()) {
1838 if (NameID != -1 || !NameStr.empty())
1839 return P.Error(NameLoc, "instructions returning void cannot have a name");
1843 // If this was a numbered instruction, verify that the instruction is the
1844 // expected value and resolve any forward references.
1845 if (NameStr.empty()) {
1846 // If neither a name nor an ID was specified, just use the next ID.
1848 NameID = NumberedVals.size();
1850 if (unsigned(NameID) != NumberedVals.size())
1851 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1852 Twine(NumberedVals.size()) + "'");
1854 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1855 ForwardRefValIDs.find(NameID);
1856 if (FI != ForwardRefValIDs.end()) {
1857 if (FI->second.first->getType() != Inst->getType())
1858 return P.Error(NameLoc, "instruction forward referenced with type '" +
1859 FI->second.first->getType()->getDescription() + "'");
1860 FI->second.first->replaceAllUsesWith(Inst);
1861 delete FI->second.first;
1862 ForwardRefValIDs.erase(FI);
1865 NumberedVals.push_back(Inst);
1869 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1870 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1871 FI = ForwardRefVals.find(NameStr);
1872 if (FI != ForwardRefVals.end()) {
1873 if (FI->second.first->getType() != Inst->getType())
1874 return P.Error(NameLoc, "instruction forward referenced with type '" +
1875 FI->second.first->getType()->getDescription() + "'");
1876 FI->second.first->replaceAllUsesWith(Inst);
1877 delete FI->second.first;
1878 ForwardRefVals.erase(FI);
1881 // Set the name on the instruction.
1882 Inst->setName(NameStr);
1884 if (Inst->getName() != NameStr)
1885 return P.Error(NameLoc, "multiple definition of local value named '" +
1890 /// GetBB - Get a basic block with the specified name or ID, creating a
1891 /// forward reference record if needed.
1892 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1894 return cast_or_null<BasicBlock>(GetVal(Name,
1895 Type::getLabelTy(F.getContext()), Loc));
1898 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1899 return cast_or_null<BasicBlock>(GetVal(ID,
1900 Type::getLabelTy(F.getContext()), Loc));
1903 /// DefineBB - Define the specified basic block, which is either named or
1904 /// unnamed. If there is an error, this returns null otherwise it returns
1905 /// the block being defined.
1906 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1910 BB = GetBB(NumberedVals.size(), Loc);
1912 BB = GetBB(Name, Loc);
1913 if (BB == 0) return 0; // Already diagnosed error.
1915 // Move the block to the end of the function. Forward ref'd blocks are
1916 // inserted wherever they happen to be referenced.
1917 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1919 // Remove the block from forward ref sets.
1921 ForwardRefValIDs.erase(NumberedVals.size());
1922 NumberedVals.push_back(BB);
1924 // BB forward references are already in the function symbol table.
1925 ForwardRefVals.erase(Name);
1931 //===----------------------------------------------------------------------===//
1933 //===----------------------------------------------------------------------===//
1935 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1936 /// type implied. For example, if we parse "4" we don't know what integer type
1937 /// it has. The value will later be combined with its type and checked for
1938 /// sanity. PFS is used to convert function-local operands of metadata (since
1939 /// metadata operands are not just parsed here but also converted to values).
1940 /// PFS can be null when we are not parsing metadata values inside a function.
1941 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1942 ID.Loc = Lex.getLoc();
1943 switch (Lex.getKind()) {
1944 default: return TokError("expected value token");
1945 case lltok::GlobalID: // @42
1946 ID.UIntVal = Lex.getUIntVal();
1947 ID.Kind = ValID::t_GlobalID;
1949 case lltok::GlobalVar: // @foo
1950 ID.StrVal = Lex.getStrVal();
1951 ID.Kind = ValID::t_GlobalName;
1953 case lltok::LocalVarID: // %42
1954 ID.UIntVal = Lex.getUIntVal();
1955 ID.Kind = ValID::t_LocalID;
1957 case lltok::LocalVar: // %foo
1958 ID.StrVal = Lex.getStrVal();
1959 ID.Kind = ValID::t_LocalName;
1961 case lltok::exclaim: // !42, !{...}, or !"foo"
1962 return ParseMetadataValue(ID, PFS);
1964 ID.APSIntVal = Lex.getAPSIntVal();
1965 ID.Kind = ValID::t_APSInt;
1967 case lltok::APFloat:
1968 ID.APFloatVal = Lex.getAPFloatVal();
1969 ID.Kind = ValID::t_APFloat;
1971 case lltok::kw_true:
1972 ID.ConstantVal = ConstantInt::getTrue(Context);
1973 ID.Kind = ValID::t_Constant;
1975 case lltok::kw_false:
1976 ID.ConstantVal = ConstantInt::getFalse(Context);
1977 ID.Kind = ValID::t_Constant;
1979 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1980 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1981 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1983 case lltok::lbrace: {
1984 // ValID ::= '{' ConstVector '}'
1986 SmallVector<Constant*, 16> Elts;
1987 if (ParseGlobalValueVector(Elts) ||
1988 ParseToken(lltok::rbrace, "expected end of struct constant"))
1991 ID.ConstantVal = ConstantStruct::get(Context, Elts.data(),
1992 Elts.size(), false);
1993 ID.Kind = ValID::t_Constant;
1997 // ValID ::= '<' ConstVector '>' --> Vector.
1998 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2000 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2002 SmallVector<Constant*, 16> Elts;
2003 LocTy FirstEltLoc = Lex.getLoc();
2004 if (ParseGlobalValueVector(Elts) ||
2006 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2007 ParseToken(lltok::greater, "expected end of constant"))
2010 if (isPackedStruct) {
2012 ConstantStruct::get(Context, Elts.data(), Elts.size(), true);
2013 ID.Kind = ValID::t_Constant;
2018 return Error(ID.Loc, "constant vector must not be empty");
2020 if (!Elts[0]->getType()->isIntegerTy() &&
2021 !Elts[0]->getType()->isFloatingPointTy())
2022 return Error(FirstEltLoc,
2023 "vector elements must have integer or floating point type");
2025 // Verify that all the vector elements have the same type.
2026 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2027 if (Elts[i]->getType() != Elts[0]->getType())
2028 return Error(FirstEltLoc,
2029 "vector element #" + Twine(i) +
2030 " is not of type '" + Elts[0]->getType()->getDescription());
2032 ID.ConstantVal = ConstantVector::get(Elts);
2033 ID.Kind = ValID::t_Constant;
2036 case lltok::lsquare: { // Array Constant
2038 SmallVector<Constant*, 16> Elts;
2039 LocTy FirstEltLoc = Lex.getLoc();
2040 if (ParseGlobalValueVector(Elts) ||
2041 ParseToken(lltok::rsquare, "expected end of array constant"))
2044 // Handle empty element.
2046 // Use undef instead of an array because it's inconvenient to determine
2047 // the element type at this point, there being no elements to examine.
2048 ID.Kind = ValID::t_EmptyArray;
2052 if (!Elts[0]->getType()->isFirstClassType())
2053 return Error(FirstEltLoc, "invalid array element type: " +
2054 Elts[0]->getType()->getDescription());
2056 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2058 // Verify all elements are correct type!
2059 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2060 if (Elts[i]->getType() != Elts[0]->getType())
2061 return Error(FirstEltLoc,
2062 "array element #" + Twine(i) +
2063 " is not of type '" +Elts[0]->getType()->getDescription());
2066 ID.ConstantVal = ConstantArray::get(ATy, Elts.data(), Elts.size());
2067 ID.Kind = ValID::t_Constant;
2070 case lltok::kw_c: // c "foo"
2072 ID.ConstantVal = ConstantArray::get(Context, Lex.getStrVal(), false);
2073 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2074 ID.Kind = ValID::t_Constant;
2077 case lltok::kw_asm: {
2078 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2079 bool HasSideEffect, AlignStack;
2081 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2082 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2083 ParseStringConstant(ID.StrVal) ||
2084 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2085 ParseToken(lltok::StringConstant, "expected constraint string"))
2087 ID.StrVal2 = Lex.getStrVal();
2088 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1);
2089 ID.Kind = ValID::t_InlineAsm;
2093 case lltok::kw_blockaddress: {
2094 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2098 LocTy FnLoc, LabelLoc;
2100 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2102 ParseToken(lltok::comma, "expected comma in block address expression")||
2103 ParseValID(Label) ||
2104 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2107 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2108 return Error(Fn.Loc, "expected function name in blockaddress");
2109 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2110 return Error(Label.Loc, "expected basic block name in blockaddress");
2112 // Make a global variable as a placeholder for this reference.
2113 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2114 false, GlobalValue::InternalLinkage,
2116 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2117 ID.ConstantVal = FwdRef;
2118 ID.Kind = ValID::t_Constant;
2122 case lltok::kw_trunc:
2123 case lltok::kw_zext:
2124 case lltok::kw_sext:
2125 case lltok::kw_fptrunc:
2126 case lltok::kw_fpext:
2127 case lltok::kw_bitcast:
2128 case lltok::kw_uitofp:
2129 case lltok::kw_sitofp:
2130 case lltok::kw_fptoui:
2131 case lltok::kw_fptosi:
2132 case lltok::kw_inttoptr:
2133 case lltok::kw_ptrtoint: {
2134 unsigned Opc = Lex.getUIntVal();
2135 PATypeHolder DestTy(Type::getVoidTy(Context));
2138 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2139 ParseGlobalTypeAndValue(SrcVal) ||
2140 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2141 ParseType(DestTy) ||
2142 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2144 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2145 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2146 SrcVal->getType()->getDescription() + "' to '" +
2147 DestTy->getDescription() + "'");
2148 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2150 ID.Kind = ValID::t_Constant;
2153 case lltok::kw_extractvalue: {
2156 SmallVector<unsigned, 4> Indices;
2157 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2158 ParseGlobalTypeAndValue(Val) ||
2159 ParseIndexList(Indices) ||
2160 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2163 if (!Val->getType()->isAggregateType())
2164 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2165 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
2167 return Error(ID.Loc, "invalid indices for extractvalue");
2169 ConstantExpr::getExtractValue(Val, Indices.data(), Indices.size());
2170 ID.Kind = ValID::t_Constant;
2173 case lltok::kw_insertvalue: {
2175 Constant *Val0, *Val1;
2176 SmallVector<unsigned, 4> Indices;
2177 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2178 ParseGlobalTypeAndValue(Val0) ||
2179 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2180 ParseGlobalTypeAndValue(Val1) ||
2181 ParseIndexList(Indices) ||
2182 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2184 if (!Val0->getType()->isAggregateType())
2185 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2186 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
2188 return Error(ID.Loc, "invalid indices for insertvalue");
2189 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
2190 Indices.data(), Indices.size());
2191 ID.Kind = ValID::t_Constant;
2194 case lltok::kw_icmp:
2195 case lltok::kw_fcmp: {
2196 unsigned PredVal, Opc = Lex.getUIntVal();
2197 Constant *Val0, *Val1;
2199 if (ParseCmpPredicate(PredVal, Opc) ||
2200 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2201 ParseGlobalTypeAndValue(Val0) ||
2202 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2203 ParseGlobalTypeAndValue(Val1) ||
2204 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2207 if (Val0->getType() != Val1->getType())
2208 return Error(ID.Loc, "compare operands must have the same type");
2210 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2212 if (Opc == Instruction::FCmp) {
2213 if (!Val0->getType()->isFPOrFPVectorTy())
2214 return Error(ID.Loc, "fcmp requires floating point operands");
2215 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2217 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2218 if (!Val0->getType()->isIntOrIntVectorTy() &&
2219 !Val0->getType()->isPointerTy())
2220 return Error(ID.Loc, "icmp requires pointer or integer operands");
2221 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2223 ID.Kind = ValID::t_Constant;
2227 // Binary Operators.
2229 case lltok::kw_fadd:
2231 case lltok::kw_fsub:
2233 case lltok::kw_fmul:
2234 case lltok::kw_udiv:
2235 case lltok::kw_sdiv:
2236 case lltok::kw_fdiv:
2237 case lltok::kw_urem:
2238 case lltok::kw_srem:
2239 case lltok::kw_frem:
2241 case lltok::kw_lshr:
2242 case lltok::kw_ashr: {
2246 unsigned Opc = Lex.getUIntVal();
2247 Constant *Val0, *Val1;
2249 LocTy ModifierLoc = Lex.getLoc();
2250 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2251 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2252 if (EatIfPresent(lltok::kw_nuw))
2254 if (EatIfPresent(lltok::kw_nsw)) {
2256 if (EatIfPresent(lltok::kw_nuw))
2259 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2260 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2261 if (EatIfPresent(lltok::kw_exact))
2264 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2265 ParseGlobalTypeAndValue(Val0) ||
2266 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2267 ParseGlobalTypeAndValue(Val1) ||
2268 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2270 if (Val0->getType() != Val1->getType())
2271 return Error(ID.Loc, "operands of constexpr must have same type");
2272 if (!Val0->getType()->isIntOrIntVectorTy()) {
2274 return Error(ModifierLoc, "nuw only applies to integer operations");
2276 return Error(ModifierLoc, "nsw only applies to integer operations");
2278 // Check that the type is valid for the operator.
2280 case Instruction::Add:
2281 case Instruction::Sub:
2282 case Instruction::Mul:
2283 case Instruction::UDiv:
2284 case Instruction::SDiv:
2285 case Instruction::URem:
2286 case Instruction::SRem:
2287 case Instruction::Shl:
2288 case Instruction::AShr:
2289 case Instruction::LShr:
2290 if (!Val0->getType()->isIntOrIntVectorTy())
2291 return Error(ID.Loc, "constexpr requires integer operands");
2293 case Instruction::FAdd:
2294 case Instruction::FSub:
2295 case Instruction::FMul:
2296 case Instruction::FDiv:
2297 case Instruction::FRem:
2298 if (!Val0->getType()->isFPOrFPVectorTy())
2299 return Error(ID.Loc, "constexpr requires fp operands");
2301 default: llvm_unreachable("Unknown binary operator!");
2304 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2305 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2306 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2307 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2309 ID.Kind = ValID::t_Constant;
2313 // Logical Operations
2316 case lltok::kw_xor: {
2317 unsigned Opc = Lex.getUIntVal();
2318 Constant *Val0, *Val1;
2320 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2321 ParseGlobalTypeAndValue(Val0) ||
2322 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2323 ParseGlobalTypeAndValue(Val1) ||
2324 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2326 if (Val0->getType() != Val1->getType())
2327 return Error(ID.Loc, "operands of constexpr must have same type");
2328 if (!Val0->getType()->isIntOrIntVectorTy())
2329 return Error(ID.Loc,
2330 "constexpr requires integer or integer vector operands");
2331 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2332 ID.Kind = ValID::t_Constant;
2336 case lltok::kw_getelementptr:
2337 case lltok::kw_shufflevector:
2338 case lltok::kw_insertelement:
2339 case lltok::kw_extractelement:
2340 case lltok::kw_select: {
2341 unsigned Opc = Lex.getUIntVal();
2342 SmallVector<Constant*, 16> Elts;
2343 bool InBounds = false;
2345 if (Opc == Instruction::GetElementPtr)
2346 InBounds = EatIfPresent(lltok::kw_inbounds);
2347 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2348 ParseGlobalValueVector(Elts) ||
2349 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2352 if (Opc == Instruction::GetElementPtr) {
2353 if (Elts.size() == 0 || !Elts[0]->getType()->isPointerTy())
2354 return Error(ID.Loc, "getelementptr requires pointer operand");
2356 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
2357 (Value**)(Elts.data() + 1),
2359 return Error(ID.Loc, "invalid indices for getelementptr");
2360 ID.ConstantVal = InBounds ?
2361 ConstantExpr::getInBoundsGetElementPtr(Elts[0],
2364 ConstantExpr::getGetElementPtr(Elts[0],
2365 Elts.data() + 1, Elts.size() - 1);
2366 } else if (Opc == Instruction::Select) {
2367 if (Elts.size() != 3)
2368 return Error(ID.Loc, "expected three operands to select");
2369 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2371 return Error(ID.Loc, Reason);
2372 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2373 } else if (Opc == Instruction::ShuffleVector) {
2374 if (Elts.size() != 3)
2375 return Error(ID.Loc, "expected three operands to shufflevector");
2376 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2377 return Error(ID.Loc, "invalid operands to shufflevector");
2379 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2380 } else if (Opc == Instruction::ExtractElement) {
2381 if (Elts.size() != 2)
2382 return Error(ID.Loc, "expected two operands to extractelement");
2383 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2384 return Error(ID.Loc, "invalid extractelement operands");
2385 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2387 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2388 if (Elts.size() != 3)
2389 return Error(ID.Loc, "expected three operands to insertelement");
2390 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2391 return Error(ID.Loc, "invalid insertelement operands");
2393 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2396 ID.Kind = ValID::t_Constant;
2405 /// ParseGlobalValue - Parse a global value with the specified type.
2406 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&C) {
2410 bool Parsed = ParseValID(ID) ||
2411 ConvertValIDToValue(Ty, ID, V, NULL);
2412 if (V && !(C = dyn_cast<Constant>(V)))
2413 return Error(ID.Loc, "global values must be constants");
2417 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2418 PATypeHolder Type(Type::getVoidTy(Context));
2419 return ParseType(Type) ||
2420 ParseGlobalValue(Type, V);
2423 /// ParseGlobalValueVector
2425 /// ::= TypeAndValue (',' TypeAndValue)*
2426 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2428 if (Lex.getKind() == lltok::rbrace ||
2429 Lex.getKind() == lltok::rsquare ||
2430 Lex.getKind() == lltok::greater ||
2431 Lex.getKind() == lltok::rparen)
2435 if (ParseGlobalTypeAndValue(C)) return true;
2438 while (EatIfPresent(lltok::comma)) {
2439 if (ParseGlobalTypeAndValue(C)) return true;
2446 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2447 assert(Lex.getKind() == lltok::lbrace);
2450 SmallVector<Value*, 16> Elts;
2451 if (ParseMDNodeVector(Elts, PFS) ||
2452 ParseToken(lltok::rbrace, "expected end of metadata node"))
2455 ID.MDNodeVal = MDNode::get(Context, Elts);
2456 ID.Kind = ValID::t_MDNode;
2460 /// ParseMetadataValue
2464 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2465 assert(Lex.getKind() == lltok::exclaim);
2470 if (Lex.getKind() == lltok::lbrace)
2471 return ParseMetadataListValue(ID, PFS);
2473 // Standalone metadata reference
2475 if (Lex.getKind() == lltok::APSInt) {
2476 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2477 ID.Kind = ValID::t_MDNode;
2482 // ::= '!' STRINGCONSTANT
2483 if (ParseMDString(ID.MDStringVal)) return true;
2484 ID.Kind = ValID::t_MDString;
2489 //===----------------------------------------------------------------------===//
2490 // Function Parsing.
2491 //===----------------------------------------------------------------------===//
2493 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2494 PerFunctionState *PFS) {
2495 if (Ty->isFunctionTy())
2496 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2499 default: llvm_unreachable("Unknown ValID!");
2500 case ValID::t_LocalID:
2501 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2502 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2504 case ValID::t_LocalName:
2505 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2506 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2508 case ValID::t_InlineAsm: {
2509 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2510 const FunctionType *FTy =
2511 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2512 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2513 return Error(ID.Loc, "invalid type for inline asm constraint string");
2514 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1, ID.UIntVal>>1);
2517 case ValID::t_MDNode:
2518 if (!Ty->isMetadataTy())
2519 return Error(ID.Loc, "metadata value must have metadata type");
2522 case ValID::t_MDString:
2523 if (!Ty->isMetadataTy())
2524 return Error(ID.Loc, "metadata value must have metadata type");
2527 case ValID::t_GlobalName:
2528 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2530 case ValID::t_GlobalID:
2531 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2533 case ValID::t_APSInt:
2534 if (!Ty->isIntegerTy())
2535 return Error(ID.Loc, "integer constant must have integer type");
2536 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2537 V = ConstantInt::get(Context, ID.APSIntVal);
2539 case ValID::t_APFloat:
2540 if (!Ty->isFloatingPointTy() ||
2541 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2542 return Error(ID.Loc, "floating point constant invalid for type");
2544 // The lexer has no type info, so builds all float and double FP constants
2545 // as double. Fix this here. Long double does not need this.
2546 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
2549 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2552 V = ConstantFP::get(Context, ID.APFloatVal);
2554 if (V->getType() != Ty)
2555 return Error(ID.Loc, "floating point constant does not have type '" +
2556 Ty->getDescription() + "'");
2560 if (!Ty->isPointerTy())
2561 return Error(ID.Loc, "null must be a pointer type");
2562 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2564 case ValID::t_Undef:
2565 // FIXME: LabelTy should not be a first-class type.
2566 if ((!Ty->isFirstClassType() || Ty->isLabelTy()) &&
2568 return Error(ID.Loc, "invalid type for undef constant");
2569 V = UndefValue::get(Ty);
2571 case ValID::t_EmptyArray:
2572 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2573 return Error(ID.Loc, "invalid empty array initializer");
2574 V = UndefValue::get(Ty);
2577 // FIXME: LabelTy should not be a first-class type.
2578 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2579 return Error(ID.Loc, "invalid type for null constant");
2580 V = Constant::getNullValue(Ty);
2582 case ValID::t_Constant:
2583 if (ID.ConstantVal->getType() != Ty)
2584 return Error(ID.Loc, "constant expression type mismatch");
2591 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2594 return ParseValID(ID, &PFS) ||
2595 ConvertValIDToValue(Ty, ID, V, &PFS);
2598 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2599 PATypeHolder T(Type::getVoidTy(Context));
2600 return ParseType(T) ||
2601 ParseValue(T, V, PFS);
2604 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2605 PerFunctionState &PFS) {
2608 if (ParseTypeAndValue(V, PFS)) return true;
2609 if (!isa<BasicBlock>(V))
2610 return Error(Loc, "expected a basic block");
2611 BB = cast<BasicBlock>(V);
2617 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2618 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2619 /// OptionalAlign OptGC
2620 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2621 // Parse the linkage.
2622 LocTy LinkageLoc = Lex.getLoc();
2625 unsigned Visibility, RetAttrs;
2627 PATypeHolder RetType(Type::getVoidTy(Context));
2628 LocTy RetTypeLoc = Lex.getLoc();
2629 if (ParseOptionalLinkage(Linkage) ||
2630 ParseOptionalVisibility(Visibility) ||
2631 ParseOptionalCallingConv(CC) ||
2632 ParseOptionalAttrs(RetAttrs, 1) ||
2633 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2636 // Verify that the linkage is ok.
2637 switch ((GlobalValue::LinkageTypes)Linkage) {
2638 case GlobalValue::ExternalLinkage:
2639 break; // always ok.
2640 case GlobalValue::DLLImportLinkage:
2641 case GlobalValue::ExternalWeakLinkage:
2643 return Error(LinkageLoc, "invalid linkage for function definition");
2645 case GlobalValue::PrivateLinkage:
2646 case GlobalValue::LinkerPrivateLinkage:
2647 case GlobalValue::LinkerPrivateWeakLinkage:
2648 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
2649 case GlobalValue::InternalLinkage:
2650 case GlobalValue::AvailableExternallyLinkage:
2651 case GlobalValue::LinkOnceAnyLinkage:
2652 case GlobalValue::LinkOnceODRLinkage:
2653 case GlobalValue::WeakAnyLinkage:
2654 case GlobalValue::WeakODRLinkage:
2655 case GlobalValue::DLLExportLinkage:
2657 return Error(LinkageLoc, "invalid linkage for function declaration");
2659 case GlobalValue::AppendingLinkage:
2660 case GlobalValue::CommonLinkage:
2661 return Error(LinkageLoc, "invalid function linkage type");
2664 if (!FunctionType::isValidReturnType(RetType) ||
2665 RetType->isOpaqueTy())
2666 return Error(RetTypeLoc, "invalid function return type");
2668 LocTy NameLoc = Lex.getLoc();
2670 std::string FunctionName;
2671 if (Lex.getKind() == lltok::GlobalVar) {
2672 FunctionName = Lex.getStrVal();
2673 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2674 unsigned NameID = Lex.getUIntVal();
2676 if (NameID != NumberedVals.size())
2677 return TokError("function expected to be numbered '%" +
2678 Twine(NumberedVals.size()) + "'");
2680 return TokError("expected function name");
2685 if (Lex.getKind() != lltok::lparen)
2686 return TokError("expected '(' in function argument list");
2688 std::vector<ArgInfo> ArgList;
2691 std::string Section;
2695 LocTy UnnamedAddrLoc;
2697 if (ParseArgumentList(ArgList, isVarArg, false) ||
2698 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2700 ParseOptionalAttrs(FuncAttrs, 2) ||
2701 (EatIfPresent(lltok::kw_section) &&
2702 ParseStringConstant(Section)) ||
2703 ParseOptionalAlignment(Alignment) ||
2704 (EatIfPresent(lltok::kw_gc) &&
2705 ParseStringConstant(GC)))
2708 // If the alignment was parsed as an attribute, move to the alignment field.
2709 if (FuncAttrs & Attribute::Alignment) {
2710 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2711 FuncAttrs &= ~Attribute::Alignment;
2714 // Okay, if we got here, the function is syntactically valid. Convert types
2715 // and do semantic checks.
2716 std::vector<const Type*> ParamTypeList;
2717 SmallVector<AttributeWithIndex, 8> Attrs;
2719 if (RetAttrs != Attribute::None)
2720 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2722 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2723 ParamTypeList.push_back(ArgList[i].Type);
2724 if (ArgList[i].Attrs != Attribute::None)
2725 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2728 if (FuncAttrs != Attribute::None)
2729 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2731 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2733 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2734 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2736 const FunctionType *FT =
2737 FunctionType::get(RetType, ParamTypeList, isVarArg);
2738 const PointerType *PFT = PointerType::getUnqual(FT);
2741 if (!FunctionName.empty()) {
2742 // If this was a definition of a forward reference, remove the definition
2743 // from the forward reference table and fill in the forward ref.
2744 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2745 ForwardRefVals.find(FunctionName);
2746 if (FRVI != ForwardRefVals.end()) {
2747 Fn = M->getFunction(FunctionName);
2748 if (Fn->getType() != PFT)
2749 return Error(FRVI->second.second, "invalid forward reference to "
2750 "function '" + FunctionName + "' with wrong type!");
2752 ForwardRefVals.erase(FRVI);
2753 } else if ((Fn = M->getFunction(FunctionName))) {
2754 // Reject redefinitions.
2755 return Error(NameLoc, "invalid redefinition of function '" +
2756 FunctionName + "'");
2757 } else if (M->getNamedValue(FunctionName)) {
2758 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2762 // If this is a definition of a forward referenced function, make sure the
2764 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2765 = ForwardRefValIDs.find(NumberedVals.size());
2766 if (I != ForwardRefValIDs.end()) {
2767 Fn = cast<Function>(I->second.first);
2768 if (Fn->getType() != PFT)
2769 return Error(NameLoc, "type of definition and forward reference of '@" +
2770 Twine(NumberedVals.size()) + "' disagree");
2771 ForwardRefValIDs.erase(I);
2776 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2777 else // Move the forward-reference to the correct spot in the module.
2778 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2780 if (FunctionName.empty())
2781 NumberedVals.push_back(Fn);
2783 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2784 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2785 Fn->setCallingConv(CC);
2786 Fn->setAttributes(PAL);
2787 Fn->setUnnamedAddr(UnnamedAddr);
2788 Fn->setAlignment(Alignment);
2789 Fn->setSection(Section);
2790 if (!GC.empty()) Fn->setGC(GC.c_str());
2792 // Add all of the arguments we parsed to the function.
2793 Function::arg_iterator ArgIt = Fn->arg_begin();
2794 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2795 // If we run out of arguments in the Function prototype, exit early.
2796 // FIXME: REMOVE THIS IN LLVM 3.0, this is just for the mismatch case above.
2797 if (ArgIt == Fn->arg_end()) break;
2799 // If the argument has a name, insert it into the argument symbol table.
2800 if (ArgList[i].Name.empty()) continue;
2802 // Set the name, if it conflicted, it will be auto-renamed.
2803 ArgIt->setName(ArgList[i].Name);
2805 if (ArgIt->getName() != ArgList[i].Name)
2806 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2807 ArgList[i].Name + "'");
2814 /// ParseFunctionBody
2815 /// ::= '{' BasicBlock+ '}'
2817 bool LLParser::ParseFunctionBody(Function &Fn) {
2818 if (Lex.getKind() != lltok::lbrace)
2819 return TokError("expected '{' in function body");
2820 Lex.Lex(); // eat the {.
2822 int FunctionNumber = -1;
2823 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2825 PerFunctionState PFS(*this, Fn, FunctionNumber);
2827 // We need at least one basic block.
2828 if (Lex.getKind() == lltok::rbrace)
2829 return TokError("function body requires at least one basic block");
2831 while (Lex.getKind() != lltok::rbrace)
2832 if (ParseBasicBlock(PFS)) return true;
2837 // Verify function is ok.
2838 return PFS.FinishFunction();
2842 /// ::= LabelStr? Instruction*
2843 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2844 // If this basic block starts out with a name, remember it.
2846 LocTy NameLoc = Lex.getLoc();
2847 if (Lex.getKind() == lltok::LabelStr) {
2848 Name = Lex.getStrVal();
2852 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2853 if (BB == 0) return true;
2855 std::string NameStr;
2857 // Parse the instructions in this block until we get a terminator.
2859 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2861 // This instruction may have three possibilities for a name: a) none
2862 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2863 LocTy NameLoc = Lex.getLoc();
2867 if (Lex.getKind() == lltok::LocalVarID) {
2868 NameID = Lex.getUIntVal();
2870 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2872 } else if (Lex.getKind() == lltok::LocalVar) {
2873 NameStr = Lex.getStrVal();
2875 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2879 switch (ParseInstruction(Inst, BB, PFS)) {
2880 default: assert(0 && "Unknown ParseInstruction result!");
2881 case InstError: return true;
2883 BB->getInstList().push_back(Inst);
2885 // With a normal result, we check to see if the instruction is followed by
2886 // a comma and metadata.
2887 if (EatIfPresent(lltok::comma))
2888 if (ParseInstructionMetadata(Inst, &PFS))
2891 case InstExtraComma:
2892 BB->getInstList().push_back(Inst);
2894 // If the instruction parser ate an extra comma at the end of it, it
2895 // *must* be followed by metadata.
2896 if (ParseInstructionMetadata(Inst, &PFS))
2901 // Set the name on the instruction.
2902 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2903 } while (!isa<TerminatorInst>(Inst));
2908 //===----------------------------------------------------------------------===//
2909 // Instruction Parsing.
2910 //===----------------------------------------------------------------------===//
2912 /// ParseInstruction - Parse one of the many different instructions.
2914 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2915 PerFunctionState &PFS) {
2916 lltok::Kind Token = Lex.getKind();
2917 if (Token == lltok::Eof)
2918 return TokError("found end of file when expecting more instructions");
2919 LocTy Loc = Lex.getLoc();
2920 unsigned KeywordVal = Lex.getUIntVal();
2921 Lex.Lex(); // Eat the keyword.
2924 default: return Error(Loc, "expected instruction opcode");
2925 // Terminator Instructions.
2926 case lltok::kw_unwind: Inst = new UnwindInst(Context); return false;
2927 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2928 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2929 case lltok::kw_br: return ParseBr(Inst, PFS);
2930 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2931 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2932 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2933 // Binary Operators.
2937 case lltok::kw_shl: {
2938 bool NUW = EatIfPresent(lltok::kw_nuw);
2939 bool NSW = EatIfPresent(lltok::kw_nsw);
2940 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2942 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2944 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2945 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2948 case lltok::kw_fadd:
2949 case lltok::kw_fsub:
2950 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2952 case lltok::kw_sdiv:
2953 case lltok::kw_udiv:
2954 case lltok::kw_lshr:
2955 case lltok::kw_ashr: {
2956 bool Exact = EatIfPresent(lltok::kw_exact);
2958 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2959 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
2963 case lltok::kw_urem:
2964 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2965 case lltok::kw_fdiv:
2966 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2969 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2970 case lltok::kw_icmp:
2971 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
2973 case lltok::kw_trunc:
2974 case lltok::kw_zext:
2975 case lltok::kw_sext:
2976 case lltok::kw_fptrunc:
2977 case lltok::kw_fpext:
2978 case lltok::kw_bitcast:
2979 case lltok::kw_uitofp:
2980 case lltok::kw_sitofp:
2981 case lltok::kw_fptoui:
2982 case lltok::kw_fptosi:
2983 case lltok::kw_inttoptr:
2984 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2986 case lltok::kw_select: return ParseSelect(Inst, PFS);
2987 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2988 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2989 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2990 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2991 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2992 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2993 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2995 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
2996 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2997 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2998 case lltok::kw_volatile:
2999 if (EatIfPresent(lltok::kw_load))
3000 return ParseLoad(Inst, PFS, true);
3001 else if (EatIfPresent(lltok::kw_store))
3002 return ParseStore(Inst, PFS, true);
3004 return TokError("expected 'load' or 'store'");
3005 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3006 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3007 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3011 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3012 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3013 if (Opc == Instruction::FCmp) {
3014 switch (Lex.getKind()) {
3015 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3016 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3017 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3018 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3019 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3020 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3021 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3022 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3023 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3024 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3025 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3026 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3027 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3028 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3029 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3030 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3031 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3034 switch (Lex.getKind()) {
3035 default: TokError("expected icmp predicate (e.g. 'eq')");
3036 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3037 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3038 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3039 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3040 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3041 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3042 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3043 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3044 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3045 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3052 //===----------------------------------------------------------------------===//
3053 // Terminator Instructions.
3054 //===----------------------------------------------------------------------===//
3056 /// ParseRet - Parse a return instruction.
3057 /// ::= 'ret' void (',' !dbg, !1)*
3058 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3059 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3060 PerFunctionState &PFS) {
3061 PATypeHolder Ty(Type::getVoidTy(Context));
3062 if (ParseType(Ty, true /*void allowed*/)) return true;
3064 if (Ty->isVoidTy()) {
3065 Inst = ReturnInst::Create(Context);
3070 if (ParseValue(Ty, RV, PFS)) return true;
3072 Inst = ReturnInst::Create(Context, RV);
3078 /// ::= 'br' TypeAndValue
3079 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3080 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3083 BasicBlock *Op1, *Op2;
3084 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3086 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3087 Inst = BranchInst::Create(BB);
3091 if (Op0->getType() != Type::getInt1Ty(Context))
3092 return Error(Loc, "branch condition must have 'i1' type");
3094 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3095 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3096 ParseToken(lltok::comma, "expected ',' after true destination") ||
3097 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3100 Inst = BranchInst::Create(Op1, Op2, Op0);
3106 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3108 /// ::= (TypeAndValue ',' TypeAndValue)*
3109 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3110 LocTy CondLoc, BBLoc;
3112 BasicBlock *DefaultBB;
3113 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3114 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3115 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3116 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3119 if (!Cond->getType()->isIntegerTy())
3120 return Error(CondLoc, "switch condition must have integer type");
3122 // Parse the jump table pairs.
3123 SmallPtrSet<Value*, 32> SeenCases;
3124 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3125 while (Lex.getKind() != lltok::rsquare) {
3129 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3130 ParseToken(lltok::comma, "expected ',' after case value") ||
3131 ParseTypeAndBasicBlock(DestBB, PFS))
3134 if (!SeenCases.insert(Constant))
3135 return Error(CondLoc, "duplicate case value in switch");
3136 if (!isa<ConstantInt>(Constant))
3137 return Error(CondLoc, "case value is not a constant integer");
3139 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3142 Lex.Lex(); // Eat the ']'.
3144 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3145 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3146 SI->addCase(Table[i].first, Table[i].second);
3153 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3154 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3157 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3158 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3159 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3162 if (!Address->getType()->isPointerTy())
3163 return Error(AddrLoc, "indirectbr address must have pointer type");
3165 // Parse the destination list.
3166 SmallVector<BasicBlock*, 16> DestList;
3168 if (Lex.getKind() != lltok::rsquare) {
3170 if (ParseTypeAndBasicBlock(DestBB, PFS))
3172 DestList.push_back(DestBB);
3174 while (EatIfPresent(lltok::comma)) {
3175 if (ParseTypeAndBasicBlock(DestBB, PFS))
3177 DestList.push_back(DestBB);
3181 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3184 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3185 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3186 IBI->addDestination(DestList[i]);
3193 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3194 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3195 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3196 LocTy CallLoc = Lex.getLoc();
3197 unsigned RetAttrs, FnAttrs;
3199 PATypeHolder RetType(Type::getVoidTy(Context));
3202 SmallVector<ParamInfo, 16> ArgList;
3204 BasicBlock *NormalBB, *UnwindBB;
3205 if (ParseOptionalCallingConv(CC) ||
3206 ParseOptionalAttrs(RetAttrs, 1) ||
3207 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3208 ParseValID(CalleeID) ||
3209 ParseParameterList(ArgList, PFS) ||
3210 ParseOptionalAttrs(FnAttrs, 2) ||
3211 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3212 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3213 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3214 ParseTypeAndBasicBlock(UnwindBB, PFS))
3217 // If RetType is a non-function pointer type, then this is the short syntax
3218 // for the call, which means that RetType is just the return type. Infer the
3219 // rest of the function argument types from the arguments that are present.
3220 const PointerType *PFTy = 0;
3221 const FunctionType *Ty = 0;
3222 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3223 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3224 // Pull out the types of all of the arguments...
3225 std::vector<const Type*> ParamTypes;
3226 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3227 ParamTypes.push_back(ArgList[i].V->getType());
3229 if (!FunctionType::isValidReturnType(RetType))
3230 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3232 Ty = FunctionType::get(RetType, ParamTypes, false);
3233 PFTy = PointerType::getUnqual(Ty);
3236 // Look up the callee.
3238 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3240 // Set up the Attributes for the function.
3241 SmallVector<AttributeWithIndex, 8> Attrs;
3242 if (RetAttrs != Attribute::None)
3243 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3245 SmallVector<Value*, 8> Args;
3247 // Loop through FunctionType's arguments and ensure they are specified
3248 // correctly. Also, gather any parameter attributes.
3249 FunctionType::param_iterator I = Ty->param_begin();
3250 FunctionType::param_iterator E = Ty->param_end();
3251 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3252 const Type *ExpectedTy = 0;
3255 } else if (!Ty->isVarArg()) {
3256 return Error(ArgList[i].Loc, "too many arguments specified");
3259 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3260 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3261 ExpectedTy->getDescription() + "'");
3262 Args.push_back(ArgList[i].V);
3263 if (ArgList[i].Attrs != Attribute::None)
3264 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3268 return Error(CallLoc, "not enough parameters specified for call");
3270 if (FnAttrs != Attribute::None)
3271 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3273 // Finish off the Attributes and check them
3274 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3276 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB,
3277 Args.begin(), Args.end());
3278 II->setCallingConv(CC);
3279 II->setAttributes(PAL);
3286 //===----------------------------------------------------------------------===//
3287 // Binary Operators.
3288 //===----------------------------------------------------------------------===//
3291 /// ::= ArithmeticOps TypeAndValue ',' Value
3293 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3294 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3295 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3296 unsigned Opc, unsigned OperandType) {
3297 LocTy Loc; Value *LHS, *RHS;
3298 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3299 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3300 ParseValue(LHS->getType(), RHS, PFS))
3304 switch (OperandType) {
3305 default: llvm_unreachable("Unknown operand type!");
3306 case 0: // int or FP.
3307 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3308 LHS->getType()->isFPOrFPVectorTy();
3310 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3311 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3315 return Error(Loc, "invalid operand type for instruction");
3317 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3322 /// ::= ArithmeticOps TypeAndValue ',' Value {
3323 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3325 LocTy Loc; Value *LHS, *RHS;
3326 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3327 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3328 ParseValue(LHS->getType(), RHS, PFS))
3331 if (!LHS->getType()->isIntOrIntVectorTy())
3332 return Error(Loc,"instruction requires integer or integer vector operands");
3334 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3340 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3341 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3342 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3344 // Parse the integer/fp comparison predicate.
3348 if (ParseCmpPredicate(Pred, Opc) ||
3349 ParseTypeAndValue(LHS, Loc, PFS) ||
3350 ParseToken(lltok::comma, "expected ',' after compare value") ||
3351 ParseValue(LHS->getType(), RHS, PFS))
3354 if (Opc == Instruction::FCmp) {
3355 if (!LHS->getType()->isFPOrFPVectorTy())
3356 return Error(Loc, "fcmp requires floating point operands");
3357 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3359 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3360 if (!LHS->getType()->isIntOrIntVectorTy() &&
3361 !LHS->getType()->isPointerTy())
3362 return Error(Loc, "icmp requires integer operands");
3363 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3368 //===----------------------------------------------------------------------===//
3369 // Other Instructions.
3370 //===----------------------------------------------------------------------===//
3374 /// ::= CastOpc TypeAndValue 'to' Type
3375 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3377 LocTy Loc; Value *Op;
3378 PATypeHolder DestTy(Type::getVoidTy(Context));
3379 if (ParseTypeAndValue(Op, Loc, PFS) ||
3380 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3384 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3385 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3386 return Error(Loc, "invalid cast opcode for cast from '" +
3387 Op->getType()->getDescription() + "' to '" +
3388 DestTy->getDescription() + "'");
3390 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3395 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3396 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3398 Value *Op0, *Op1, *Op2;
3399 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3400 ParseToken(lltok::comma, "expected ',' after select condition") ||
3401 ParseTypeAndValue(Op1, PFS) ||
3402 ParseToken(lltok::comma, "expected ',' after select value") ||
3403 ParseTypeAndValue(Op2, PFS))
3406 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3407 return Error(Loc, Reason);
3409 Inst = SelectInst::Create(Op0, Op1, Op2);
3414 /// ::= 'va_arg' TypeAndValue ',' Type
3415 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3417 PATypeHolder EltTy(Type::getVoidTy(Context));
3419 if (ParseTypeAndValue(Op, PFS) ||
3420 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3421 ParseType(EltTy, TypeLoc))
3424 if (!EltTy->isFirstClassType())
3425 return Error(TypeLoc, "va_arg requires operand with first class type");
3427 Inst = new VAArgInst(Op, EltTy);
3431 /// ParseExtractElement
3432 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3433 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3436 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3437 ParseToken(lltok::comma, "expected ',' after extract value") ||
3438 ParseTypeAndValue(Op1, PFS))
3441 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3442 return Error(Loc, "invalid extractelement operands");
3444 Inst = ExtractElementInst::Create(Op0, Op1);
3448 /// ParseInsertElement
3449 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3450 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3452 Value *Op0, *Op1, *Op2;
3453 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3454 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3455 ParseTypeAndValue(Op1, PFS) ||
3456 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3457 ParseTypeAndValue(Op2, PFS))
3460 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3461 return Error(Loc, "invalid insertelement operands");
3463 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3467 /// ParseShuffleVector
3468 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3469 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3471 Value *Op0, *Op1, *Op2;
3472 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3473 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3474 ParseTypeAndValue(Op1, PFS) ||
3475 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3476 ParseTypeAndValue(Op2, PFS))
3479 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3480 return Error(Loc, "invalid extractelement operands");
3482 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3487 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3488 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3489 PATypeHolder Ty(Type::getVoidTy(Context));
3491 LocTy TypeLoc = Lex.getLoc();
3493 if (ParseType(Ty) ||
3494 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3495 ParseValue(Ty, Op0, PFS) ||
3496 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3497 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3498 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3501 bool AteExtraComma = false;
3502 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3504 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3506 if (!EatIfPresent(lltok::comma))
3509 if (Lex.getKind() == lltok::MetadataVar) {
3510 AteExtraComma = true;
3514 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3515 ParseValue(Ty, Op0, PFS) ||
3516 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3517 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3518 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3522 if (!Ty->isFirstClassType())
3523 return Error(TypeLoc, "phi node must have first class type");
3525 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3526 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3527 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3529 return AteExtraComma ? InstExtraComma : InstNormal;
3533 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3534 /// ParameterList OptionalAttrs
3535 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3537 unsigned RetAttrs, FnAttrs;
3539 PATypeHolder RetType(Type::getVoidTy(Context));
3542 SmallVector<ParamInfo, 16> ArgList;
3543 LocTy CallLoc = Lex.getLoc();
3545 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3546 ParseOptionalCallingConv(CC) ||
3547 ParseOptionalAttrs(RetAttrs, 1) ||
3548 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3549 ParseValID(CalleeID) ||
3550 ParseParameterList(ArgList, PFS) ||
3551 ParseOptionalAttrs(FnAttrs, 2))
3554 // If RetType is a non-function pointer type, then this is the short syntax
3555 // for the call, which means that RetType is just the return type. Infer the
3556 // rest of the function argument types from the arguments that are present.
3557 const PointerType *PFTy = 0;
3558 const FunctionType *Ty = 0;
3559 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3560 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3561 // Pull out the types of all of the arguments...
3562 std::vector<const Type*> ParamTypes;
3563 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3564 ParamTypes.push_back(ArgList[i].V->getType());
3566 if (!FunctionType::isValidReturnType(RetType))
3567 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3569 Ty = FunctionType::get(RetType, ParamTypes, false);
3570 PFTy = PointerType::getUnqual(Ty);
3573 // Look up the callee.
3575 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3577 // Set up the Attributes for the function.
3578 SmallVector<AttributeWithIndex, 8> Attrs;
3579 if (RetAttrs != Attribute::None)
3580 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3582 SmallVector<Value*, 8> Args;
3584 // Loop through FunctionType's arguments and ensure they are specified
3585 // correctly. Also, gather any parameter attributes.
3586 FunctionType::param_iterator I = Ty->param_begin();
3587 FunctionType::param_iterator E = Ty->param_end();
3588 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3589 const Type *ExpectedTy = 0;
3592 } else if (!Ty->isVarArg()) {
3593 return Error(ArgList[i].Loc, "too many arguments specified");
3596 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3597 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3598 ExpectedTy->getDescription() + "'");
3599 Args.push_back(ArgList[i].V);
3600 if (ArgList[i].Attrs != Attribute::None)
3601 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3605 return Error(CallLoc, "not enough parameters specified for call");
3607 if (FnAttrs != Attribute::None)
3608 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3610 // Finish off the Attributes and check them
3611 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3613 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3614 CI->setTailCall(isTail);
3615 CI->setCallingConv(CC);
3616 CI->setAttributes(PAL);
3621 //===----------------------------------------------------------------------===//
3622 // Memory Instructions.
3623 //===----------------------------------------------------------------------===//
3626 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3627 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3628 PATypeHolder Ty(Type::getVoidTy(Context));
3631 unsigned Alignment = 0;
3632 if (ParseType(Ty)) return true;
3634 bool AteExtraComma = false;
3635 if (EatIfPresent(lltok::comma)) {
3636 if (Lex.getKind() == lltok::kw_align) {
3637 if (ParseOptionalAlignment(Alignment)) return true;
3638 } else if (Lex.getKind() == lltok::MetadataVar) {
3639 AteExtraComma = true;
3641 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3642 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3647 if (Size && !Size->getType()->isIntegerTy())
3648 return Error(SizeLoc, "element count must have integer type");
3650 Inst = new AllocaInst(Ty, Size, Alignment);
3651 return AteExtraComma ? InstExtraComma : InstNormal;
3655 /// ::= 'volatile'? 'load' TypeAndValue (',' OptionalInfo)?
3656 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3658 Value *Val; LocTy Loc;
3659 unsigned Alignment = 0;
3660 bool AteExtraComma = false;
3661 if (ParseTypeAndValue(Val, Loc, PFS) ||
3662 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3665 if (!Val->getType()->isPointerTy() ||
3666 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3667 return Error(Loc, "load operand must be a pointer to a first class type");
3669 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3670 return AteExtraComma ? InstExtraComma : InstNormal;
3674 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3675 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3677 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3678 unsigned Alignment = 0;
3679 bool AteExtraComma = false;
3680 if (ParseTypeAndValue(Val, Loc, PFS) ||
3681 ParseToken(lltok::comma, "expected ',' after store operand") ||
3682 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3683 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3686 if (!Ptr->getType()->isPointerTy())
3687 return Error(PtrLoc, "store operand must be a pointer");
3688 if (!Val->getType()->isFirstClassType())
3689 return Error(Loc, "store operand must be a first class value");
3690 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3691 return Error(Loc, "stored value and pointer type do not match");
3693 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3694 return AteExtraComma ? InstExtraComma : InstNormal;
3697 /// ParseGetElementPtr
3698 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3699 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3700 Value *Ptr, *Val; LocTy Loc, EltLoc;
3702 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3704 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3706 if (!Ptr->getType()->isPointerTy())
3707 return Error(Loc, "base of getelementptr must be a pointer");
3709 SmallVector<Value*, 16> Indices;
3710 bool AteExtraComma = false;
3711 while (EatIfPresent(lltok::comma)) {
3712 if (Lex.getKind() == lltok::MetadataVar) {
3713 AteExtraComma = true;
3716 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3717 if (!Val->getType()->isIntegerTy())
3718 return Error(EltLoc, "getelementptr index must be an integer");
3719 Indices.push_back(Val);
3722 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3723 Indices.begin(), Indices.end()))
3724 return Error(Loc, "invalid getelementptr indices");
3725 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3727 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
3728 return AteExtraComma ? InstExtraComma : InstNormal;
3731 /// ParseExtractValue
3732 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3733 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3734 Value *Val; LocTy Loc;
3735 SmallVector<unsigned, 4> Indices;
3737 if (ParseTypeAndValue(Val, Loc, PFS) ||
3738 ParseIndexList(Indices, AteExtraComma))
3741 if (!Val->getType()->isAggregateType())
3742 return Error(Loc, "extractvalue operand must be aggregate type");
3744 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3746 return Error(Loc, "invalid indices for extractvalue");
3747 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3748 return AteExtraComma ? InstExtraComma : InstNormal;
3751 /// ParseInsertValue
3752 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3753 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3754 Value *Val0, *Val1; LocTy Loc0, Loc1;
3755 SmallVector<unsigned, 4> Indices;
3757 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3758 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3759 ParseTypeAndValue(Val1, Loc1, PFS) ||
3760 ParseIndexList(Indices, AteExtraComma))
3763 if (!Val0->getType()->isAggregateType())
3764 return Error(Loc0, "insertvalue operand must be aggregate type");
3766 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3768 return Error(Loc0, "invalid indices for insertvalue");
3769 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3770 return AteExtraComma ? InstExtraComma : InstNormal;
3773 //===----------------------------------------------------------------------===//
3774 // Embedded metadata.
3775 //===----------------------------------------------------------------------===//
3777 /// ParseMDNodeVector
3778 /// ::= Element (',' Element)*
3780 /// ::= 'null' | TypeAndValue
3781 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
3782 PerFunctionState *PFS) {
3783 // Check for an empty list.
3784 if (Lex.getKind() == lltok::rbrace)
3788 // Null is a special case since it is typeless.
3789 if (EatIfPresent(lltok::kw_null)) {
3795 PATypeHolder Ty(Type::getVoidTy(Context));
3797 if (ParseType(Ty) || ParseValID(ID, PFS) ||
3798 ConvertValIDToValue(Ty, ID, V, PFS))
3802 } while (EatIfPresent(lltok::comma));