1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ValueSymbolTable.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 static std::string getTypeString(Type *T) {
31 raw_string_ostream Tmp(Result);
36 /// Run: module ::= toplevelentity*
37 bool LLParser::Run() {
41 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
45 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47 bool LLParser::ValidateEndOfModule() {
48 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
62 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
65 ForwardRefInstMetadata.clear();
69 // If there are entries in ForwardRefBlockAddresses at this point, they are
70 // references after the function was defined. Resolve those now.
71 while (!ForwardRefBlockAddresses.empty()) {
72 // Okay, we are referencing an already-parsed function, resolve them now.
74 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
75 if (Fn.Kind == ValID::t_GlobalName)
76 TheFn = M->getFunction(Fn.StrVal);
77 else if (Fn.UIntVal < NumberedVals.size())
78 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
81 return Error(Fn.Loc, "unknown function referenced by blockaddress");
83 // Resolve all these references.
84 if (ResolveForwardRefBlockAddresses(TheFn,
85 ForwardRefBlockAddresses.begin()->second,
89 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
92 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
93 if (NumberedTypes[i].second.isValid())
94 return Error(NumberedTypes[i].second,
95 "use of undefined type '%" + Twine(i) + "'");
97 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
98 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
99 if (I->second.second.isValid())
100 return Error(I->second.second,
101 "use of undefined type named '" + I->getKey() + "'");
103 if (!ForwardRefVals.empty())
104 return Error(ForwardRefVals.begin()->second.second,
105 "use of undefined value '@" + ForwardRefVals.begin()->first +
108 if (!ForwardRefValIDs.empty())
109 return Error(ForwardRefValIDs.begin()->second.second,
110 "use of undefined value '@" +
111 Twine(ForwardRefValIDs.begin()->first) + "'");
113 if (!ForwardRefMDNodes.empty())
114 return Error(ForwardRefMDNodes.begin()->second.second,
115 "use of undefined metadata '!" +
116 Twine(ForwardRefMDNodes.begin()->first) + "'");
119 // Look for intrinsic functions and CallInst that need to be upgraded
120 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
121 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
126 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
127 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
128 PerFunctionState *PFS) {
129 // Loop over all the references, resolving them.
130 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
133 if (Refs[i].first.Kind == ValID::t_LocalName)
134 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
136 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
137 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
138 return Error(Refs[i].first.Loc,
139 "cannot take address of numeric label after the function is defined");
141 Res = dyn_cast_or_null<BasicBlock>(
142 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
146 return Error(Refs[i].first.Loc,
147 "referenced value is not a basic block");
149 // Get the BlockAddress for this and update references to use it.
150 BlockAddress *BA = BlockAddress::get(TheFn, Res);
151 Refs[i].second->replaceAllUsesWith(BA);
152 Refs[i].second->eraseFromParent();
158 //===----------------------------------------------------------------------===//
159 // Top-Level Entities
160 //===----------------------------------------------------------------------===//
162 bool LLParser::ParseTopLevelEntities() {
164 switch (Lex.getKind()) {
165 default: return TokError("expected top-level entity");
166 case lltok::Eof: return false;
167 case lltok::kw_declare: if (ParseDeclare()) return true; break;
168 case lltok::kw_define: if (ParseDefine()) return true; break;
169 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
170 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
171 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
172 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
173 case lltok::LocalVar: if (ParseNamedType()) return true; break;
174 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
175 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
176 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
177 case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
179 // The Global variable production with no name can have many different
180 // optional leading prefixes, the production is:
181 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
182 // OptionalAddrSpace OptionalUnNammedAddr
183 // ('constant'|'global') ...
184 case lltok::kw_private: // OptionalLinkage
185 case lltok::kw_linker_private: // OptionalLinkage
186 case lltok::kw_linker_private_weak: // OptionalLinkage
187 case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
188 case lltok::kw_internal: // OptionalLinkage
189 case lltok::kw_weak: // OptionalLinkage
190 case lltok::kw_weak_odr: // OptionalLinkage
191 case lltok::kw_linkonce: // OptionalLinkage
192 case lltok::kw_linkonce_odr: // OptionalLinkage
193 case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage
194 case lltok::kw_appending: // OptionalLinkage
195 case lltok::kw_dllexport: // OptionalLinkage
196 case lltok::kw_common: // OptionalLinkage
197 case lltok::kw_dllimport: // OptionalLinkage
198 case lltok::kw_extern_weak: // OptionalLinkage
199 case lltok::kw_external: { // OptionalLinkage
200 unsigned Linkage, Visibility;
201 if (ParseOptionalLinkage(Linkage) ||
202 ParseOptionalVisibility(Visibility) ||
203 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
207 case lltok::kw_default: // OptionalVisibility
208 case lltok::kw_hidden: // OptionalVisibility
209 case lltok::kw_protected: { // OptionalVisibility
211 if (ParseOptionalVisibility(Visibility) ||
212 ParseGlobal("", SMLoc(), 0, false, Visibility))
217 case lltok::kw_thread_local: // OptionalThreadLocal
218 case lltok::kw_addrspace: // OptionalAddrSpace
219 case lltok::kw_constant: // GlobalType
220 case lltok::kw_global: // GlobalType
221 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
229 /// ::= 'module' 'asm' STRINGCONSTANT
230 bool LLParser::ParseModuleAsm() {
231 assert(Lex.getKind() == lltok::kw_module);
235 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
236 ParseStringConstant(AsmStr)) return true;
238 M->appendModuleInlineAsm(AsmStr);
243 /// ::= 'target' 'triple' '=' STRINGCONSTANT
244 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
245 bool LLParser::ParseTargetDefinition() {
246 assert(Lex.getKind() == lltok::kw_target);
249 default: return TokError("unknown target property");
250 case lltok::kw_triple:
252 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
253 ParseStringConstant(Str))
255 M->setTargetTriple(Str);
257 case lltok::kw_datalayout:
259 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
260 ParseStringConstant(Str))
262 M->setDataLayout(Str);
268 /// ::= 'deplibs' '=' '[' ']'
269 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
270 bool LLParser::ParseDepLibs() {
271 assert(Lex.getKind() == lltok::kw_deplibs);
273 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
274 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
277 if (EatIfPresent(lltok::rsquare))
281 if (ParseStringConstant(Str)) return true;
284 while (EatIfPresent(lltok::comma)) {
285 if (ParseStringConstant(Str)) return true;
289 return ParseToken(lltok::rsquare, "expected ']' at end of list");
292 /// ParseUnnamedType:
293 /// ::= LocalVarID '=' 'type' type
294 bool LLParser::ParseUnnamedType() {
295 LocTy TypeLoc = Lex.getLoc();
296 unsigned TypeID = Lex.getUIntVal();
297 Lex.Lex(); // eat LocalVarID;
299 if (ParseToken(lltok::equal, "expected '=' after name") ||
300 ParseToken(lltok::kw_type, "expected 'type' after '='"))
303 if (TypeID >= NumberedTypes.size())
304 NumberedTypes.resize(TypeID+1);
307 if (ParseStructDefinition(TypeLoc, "",
308 NumberedTypes[TypeID], Result)) return true;
310 if (!isa<StructType>(Result)) {
311 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
313 return Error(TypeLoc, "non-struct types may not be recursive");
314 Entry.first = Result;
315 Entry.second = SMLoc();
323 /// ::= LocalVar '=' 'type' type
324 bool LLParser::ParseNamedType() {
325 std::string Name = Lex.getStrVal();
326 LocTy NameLoc = Lex.getLoc();
327 Lex.Lex(); // eat LocalVar.
329 if (ParseToken(lltok::equal, "expected '=' after name") ||
330 ParseToken(lltok::kw_type, "expected 'type' after name"))
334 if (ParseStructDefinition(NameLoc, Name,
335 NamedTypes[Name], Result)) return true;
337 if (!isa<StructType>(Result)) {
338 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
340 return Error(NameLoc, "non-struct types may not be recursive");
341 Entry.first = Result;
342 Entry.second = SMLoc();
350 /// ::= 'declare' FunctionHeader
351 bool LLParser::ParseDeclare() {
352 assert(Lex.getKind() == lltok::kw_declare);
356 return ParseFunctionHeader(F, false);
360 /// ::= 'define' FunctionHeader '{' ...
361 bool LLParser::ParseDefine() {
362 assert(Lex.getKind() == lltok::kw_define);
366 return ParseFunctionHeader(F, true) ||
367 ParseFunctionBody(*F);
373 bool LLParser::ParseGlobalType(bool &IsConstant) {
374 if (Lex.getKind() == lltok::kw_constant)
376 else if (Lex.getKind() == lltok::kw_global)
380 return TokError("expected 'global' or 'constant'");
386 /// ParseUnnamedGlobal:
387 /// OptionalVisibility ALIAS ...
388 /// OptionalLinkage OptionalVisibility ... -> global variable
389 /// GlobalID '=' OptionalVisibility ALIAS ...
390 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
391 bool LLParser::ParseUnnamedGlobal() {
392 unsigned VarID = NumberedVals.size();
394 LocTy NameLoc = Lex.getLoc();
396 // Handle the GlobalID form.
397 if (Lex.getKind() == lltok::GlobalID) {
398 if (Lex.getUIntVal() != VarID)
399 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
401 Lex.Lex(); // eat GlobalID;
403 if (ParseToken(lltok::equal, "expected '=' after name"))
408 unsigned Linkage, Visibility;
409 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
410 ParseOptionalVisibility(Visibility))
413 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
414 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
415 return ParseAlias(Name, NameLoc, Visibility);
418 /// ParseNamedGlobal:
419 /// GlobalVar '=' OptionalVisibility ALIAS ...
420 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
421 bool LLParser::ParseNamedGlobal() {
422 assert(Lex.getKind() == lltok::GlobalVar);
423 LocTy NameLoc = Lex.getLoc();
424 std::string Name = Lex.getStrVal();
428 unsigned Linkage, Visibility;
429 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
430 ParseOptionalLinkage(Linkage, HasLinkage) ||
431 ParseOptionalVisibility(Visibility))
434 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
435 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
436 return ParseAlias(Name, NameLoc, Visibility);
440 // ::= '!' STRINGCONSTANT
441 bool LLParser::ParseMDString(MDString *&Result) {
443 if (ParseStringConstant(Str)) return true;
444 Result = MDString::get(Context, Str);
449 // ::= '!' MDNodeNumber
451 /// This version of ParseMDNodeID returns the slot number and null in the case
452 /// of a forward reference.
453 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
454 // !{ ..., !42, ... }
455 if (ParseUInt32(SlotNo)) return true;
457 // Check existing MDNode.
458 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
459 Result = NumberedMetadata[SlotNo];
465 bool LLParser::ParseMDNodeID(MDNode *&Result) {
466 // !{ ..., !42, ... }
468 if (ParseMDNodeID(Result, MID)) return true;
470 // If not a forward reference, just return it now.
471 if (Result) return false;
473 // Otherwise, create MDNode forward reference.
474 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
475 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
477 if (NumberedMetadata.size() <= MID)
478 NumberedMetadata.resize(MID+1);
479 NumberedMetadata[MID] = FwdNode;
484 /// ParseNamedMetadata:
485 /// !foo = !{ !1, !2 }
486 bool LLParser::ParseNamedMetadata() {
487 assert(Lex.getKind() == lltok::MetadataVar);
488 std::string Name = Lex.getStrVal();
491 if (ParseToken(lltok::equal, "expected '=' here") ||
492 ParseToken(lltok::exclaim, "Expected '!' here") ||
493 ParseToken(lltok::lbrace, "Expected '{' here"))
496 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
497 if (Lex.getKind() != lltok::rbrace)
499 if (ParseToken(lltok::exclaim, "Expected '!' here"))
503 if (ParseMDNodeID(N)) return true;
505 } while (EatIfPresent(lltok::comma));
507 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
513 /// ParseStandaloneMetadata:
515 bool LLParser::ParseStandaloneMetadata() {
516 assert(Lex.getKind() == lltok::exclaim);
518 unsigned MetadataID = 0;
522 SmallVector<Value *, 16> Elts;
523 if (ParseUInt32(MetadataID) ||
524 ParseToken(lltok::equal, "expected '=' here") ||
525 ParseType(Ty, TyLoc) ||
526 ParseToken(lltok::exclaim, "Expected '!' here") ||
527 ParseToken(lltok::lbrace, "Expected '{' here") ||
528 ParseMDNodeVector(Elts, NULL) ||
529 ParseToken(lltok::rbrace, "expected end of metadata node"))
532 MDNode *Init = MDNode::get(Context, Elts);
534 // See if this was forward referenced, if so, handle it.
535 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
536 FI = ForwardRefMDNodes.find(MetadataID);
537 if (FI != ForwardRefMDNodes.end()) {
538 MDNode *Temp = FI->second.first;
539 Temp->replaceAllUsesWith(Init);
540 MDNode::deleteTemporary(Temp);
541 ForwardRefMDNodes.erase(FI);
543 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
545 if (MetadataID >= NumberedMetadata.size())
546 NumberedMetadata.resize(MetadataID+1);
548 if (NumberedMetadata[MetadataID] != 0)
549 return TokError("Metadata id is already used");
550 NumberedMetadata[MetadataID] = Init;
557 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
560 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
561 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
563 /// Everything through visibility has already been parsed.
565 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
566 unsigned Visibility) {
567 assert(Lex.getKind() == lltok::kw_alias);
570 LocTy LinkageLoc = Lex.getLoc();
571 if (ParseOptionalLinkage(Linkage))
574 if (Linkage != GlobalValue::ExternalLinkage &&
575 Linkage != GlobalValue::WeakAnyLinkage &&
576 Linkage != GlobalValue::WeakODRLinkage &&
577 Linkage != GlobalValue::InternalLinkage &&
578 Linkage != GlobalValue::PrivateLinkage &&
579 Linkage != GlobalValue::LinkerPrivateLinkage &&
580 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
581 return Error(LinkageLoc, "invalid linkage type for alias");
584 LocTy AliaseeLoc = Lex.getLoc();
585 if (Lex.getKind() != lltok::kw_bitcast &&
586 Lex.getKind() != lltok::kw_getelementptr) {
587 if (ParseGlobalTypeAndValue(Aliasee)) return true;
589 // The bitcast dest type is not present, it is implied by the dest type.
591 if (ParseValID(ID)) return true;
592 if (ID.Kind != ValID::t_Constant)
593 return Error(AliaseeLoc, "invalid aliasee");
594 Aliasee = ID.ConstantVal;
597 if (!Aliasee->getType()->isPointerTy())
598 return Error(AliaseeLoc, "alias must have pointer type");
600 // Okay, create the alias but do not insert it into the module yet.
601 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
602 (GlobalValue::LinkageTypes)Linkage, Name,
604 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
606 // See if this value already exists in the symbol table. If so, it is either
607 // a redefinition or a definition of a forward reference.
608 if (GlobalValue *Val = M->getNamedValue(Name)) {
609 // See if this was a redefinition. If so, there is no entry in
611 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
612 I = ForwardRefVals.find(Name);
613 if (I == ForwardRefVals.end())
614 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
616 // Otherwise, this was a definition of forward ref. Verify that types
618 if (Val->getType() != GA->getType())
619 return Error(NameLoc,
620 "forward reference and definition of alias have different types");
622 // If they agree, just RAUW the old value with the alias and remove the
624 Val->replaceAllUsesWith(GA);
625 Val->eraseFromParent();
626 ForwardRefVals.erase(I);
629 // Insert into the module, we know its name won't collide now.
630 M->getAliasList().push_back(GA);
631 assert(GA->getName() == Name && "Should not be a name conflict!");
637 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
638 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
639 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
640 /// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
642 /// Everything through visibility has been parsed already.
644 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
645 unsigned Linkage, bool HasLinkage,
646 unsigned Visibility) {
648 bool IsConstant, UnnamedAddr;
649 GlobalVariable::ThreadLocalMode TLM;
650 LocTy UnnamedAddrLoc;
654 if (ParseOptionalThreadLocal(TLM) ||
655 ParseOptionalAddrSpace(AddrSpace) ||
656 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
658 ParseGlobalType(IsConstant) ||
659 ParseType(Ty, TyLoc))
662 // If the linkage is specified and is external, then no initializer is
665 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
666 Linkage != GlobalValue::ExternalWeakLinkage &&
667 Linkage != GlobalValue::ExternalLinkage)) {
668 if (ParseGlobalValue(Ty, Init))
672 if (Ty->isFunctionTy() || Ty->isLabelTy())
673 return Error(TyLoc, "invalid type for global variable");
675 GlobalVariable *GV = 0;
677 // See if the global was forward referenced, if so, use the global.
679 if (GlobalValue *GVal = M->getNamedValue(Name)) {
680 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
681 return Error(NameLoc, "redefinition of global '@" + Name + "'");
682 GV = cast<GlobalVariable>(GVal);
685 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
686 I = ForwardRefValIDs.find(NumberedVals.size());
687 if (I != ForwardRefValIDs.end()) {
688 GV = cast<GlobalVariable>(I->second.first);
689 ForwardRefValIDs.erase(I);
694 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
695 Name, 0, GlobalVariable::NotThreadLocal,
698 if (GV->getType()->getElementType() != Ty)
700 "forward reference and definition of global have different types");
702 // Move the forward-reference to the correct spot in the module.
703 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
707 NumberedVals.push_back(GV);
709 // Set the parsed properties on the global.
711 GV->setInitializer(Init);
712 GV->setConstant(IsConstant);
713 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
714 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
715 GV->setThreadLocalMode(TLM);
716 GV->setUnnamedAddr(UnnamedAddr);
718 // Parse attributes on the global.
719 while (Lex.getKind() == lltok::comma) {
722 if (Lex.getKind() == lltok::kw_section) {
724 GV->setSection(Lex.getStrVal());
725 if (ParseToken(lltok::StringConstant, "expected global section string"))
727 } else if (Lex.getKind() == lltok::kw_align) {
729 if (ParseOptionalAlignment(Alignment)) return true;
730 GV->setAlignment(Alignment);
732 TokError("unknown global variable property!");
740 //===----------------------------------------------------------------------===//
741 // GlobalValue Reference/Resolution Routines.
742 //===----------------------------------------------------------------------===//
744 /// GetGlobalVal - Get a value with the specified name or ID, creating a
745 /// forward reference record if needed. This can return null if the value
746 /// exists but does not have the right type.
747 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
749 PointerType *PTy = dyn_cast<PointerType>(Ty);
751 Error(Loc, "global variable reference must have pointer type");
755 // Look this name up in the normal function symbol table.
757 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
759 // If this is a forward reference for the value, see if we already created a
760 // forward ref record.
762 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
763 I = ForwardRefVals.find(Name);
764 if (I != ForwardRefVals.end())
765 Val = I->second.first;
768 // If we have the value in the symbol table or fwd-ref table, return it.
770 if (Val->getType() == Ty) return Val;
771 Error(Loc, "'@" + Name + "' defined with type '" +
772 getTypeString(Val->getType()) + "'");
776 // Otherwise, create a new forward reference for this value and remember it.
778 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
779 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
781 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
782 GlobalValue::ExternalWeakLinkage, 0, Name);
784 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
788 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
789 PointerType *PTy = dyn_cast<PointerType>(Ty);
791 Error(Loc, "global variable reference must have pointer type");
795 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
797 // If this is a forward reference for the value, see if we already created a
798 // forward ref record.
800 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
801 I = ForwardRefValIDs.find(ID);
802 if (I != ForwardRefValIDs.end())
803 Val = I->second.first;
806 // If we have the value in the symbol table or fwd-ref table, return it.
808 if (Val->getType() == Ty) return Val;
809 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
810 getTypeString(Val->getType()) + "'");
814 // Otherwise, create a new forward reference for this value and remember it.
816 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
817 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
819 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
820 GlobalValue::ExternalWeakLinkage, 0, "");
822 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
827 //===----------------------------------------------------------------------===//
829 //===----------------------------------------------------------------------===//
831 /// ParseToken - If the current token has the specified kind, eat it and return
832 /// success. Otherwise, emit the specified error and return failure.
833 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
834 if (Lex.getKind() != T)
835 return TokError(ErrMsg);
840 /// ParseStringConstant
841 /// ::= StringConstant
842 bool LLParser::ParseStringConstant(std::string &Result) {
843 if (Lex.getKind() != lltok::StringConstant)
844 return TokError("expected string constant");
845 Result = Lex.getStrVal();
852 bool LLParser::ParseUInt32(unsigned &Val) {
853 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
854 return TokError("expected integer");
855 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
856 if (Val64 != unsigned(Val64))
857 return TokError("expected 32-bit integer (too large)");
864 /// := 'localdynamic'
867 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
868 switch (Lex.getKind()) {
870 return TokError("expected localdynamic, initialexec or localexec");
871 case lltok::kw_localdynamic:
872 TLM = GlobalVariable::LocalDynamicTLSModel;
874 case lltok::kw_initialexec:
875 TLM = GlobalVariable::InitialExecTLSModel;
877 case lltok::kw_localexec:
878 TLM = GlobalVariable::LocalExecTLSModel;
886 /// ParseOptionalThreadLocal
888 /// := 'thread_local'
889 /// := 'thread_local' '(' tlsmodel ')'
890 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
891 TLM = GlobalVariable::NotThreadLocal;
892 if (!EatIfPresent(lltok::kw_thread_local))
895 TLM = GlobalVariable::GeneralDynamicTLSModel;
896 if (Lex.getKind() == lltok::lparen) {
898 return ParseTLSModel(TLM) ||
899 ParseToken(lltok::rparen, "expected ')' after thread local model");
904 /// ParseOptionalAddrSpace
906 /// := 'addrspace' '(' uint32 ')'
907 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
909 if (!EatIfPresent(lltok::kw_addrspace))
911 return ParseToken(lltok::lparen, "expected '(' in address space") ||
912 ParseUInt32(AddrSpace) ||
913 ParseToken(lltok::rparen, "expected ')' in address space");
916 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
917 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
918 /// 2: function attr.
919 bool LLParser::ParseOptionalAttrs(AttrBuilder &B, unsigned AttrKind) {
920 LocTy AttrLoc = Lex.getLoc();
921 bool HaveError = false;
926 lltok::Kind Token = Lex.getKind();
928 default: // End of attributes.
930 case lltok::kw_zeroext: B.addAttribute(Attributes::ZExt); break;
931 case lltok::kw_signext: B.addAttribute(Attributes::SExt); break;
932 case lltok::kw_inreg: B.addAttribute(Attributes::InReg); break;
933 case lltok::kw_sret: B.addAttribute(Attributes::StructRet); break;
934 case lltok::kw_noalias: B.addAttribute(Attributes::NoAlias); break;
935 case lltok::kw_nocapture: B.addAttribute(Attributes::NoCapture); break;
936 case lltok::kw_byval: B.addAttribute(Attributes::ByVal); break;
937 case lltok::kw_nest: B.addAttribute(Attributes::Nest); break;
939 case lltok::kw_noreturn: B.addAttribute(Attributes::NoReturn); break;
940 case lltok::kw_nounwind: B.addAttribute(Attributes::NoUnwind); break;
941 case lltok::kw_uwtable: B.addAttribute(Attributes::UWTable); break;
942 case lltok::kw_returns_twice: B.addAttribute(Attributes::ReturnsTwice); break;
943 case lltok::kw_noinline: B.addAttribute(Attributes::NoInline); break;
944 case lltok::kw_readnone: B.addAttribute(Attributes::ReadNone); break;
945 case lltok::kw_readonly: B.addAttribute(Attributes::ReadOnly); break;
946 case lltok::kw_inlinehint: B.addAttribute(Attributes::InlineHint); break;
947 case lltok::kw_alwaysinline: B.addAttribute(Attributes::AlwaysInline); break;
948 case lltok::kw_optsize: B.addAttribute(Attributes::OptimizeForSize); break;
949 case lltok::kw_ssp: B.addAttribute(Attributes::StackProtect); break;
950 case lltok::kw_sspreq: B.addAttribute(Attributes::StackProtectReq); break;
951 case lltok::kw_noredzone: B.addAttribute(Attributes::NoRedZone); break;
952 case lltok::kw_noimplicitfloat: B.addAttribute(Attributes::NoImplicitFloat); break;
953 case lltok::kw_naked: B.addAttribute(Attributes::Naked); break;
954 case lltok::kw_nonlazybind: B.addAttribute(Attributes::NonLazyBind); break;
955 case lltok::kw_address_safety: B.addAttribute(Attributes::AddressSafety); break;
956 case lltok::kw_minsize: B.addAttribute(Attributes::MinSize); break;
958 case lltok::kw_alignstack: {
960 if (ParseOptionalStackAlignment(Alignment))
962 B.addStackAlignmentAttr(Alignment);
966 case lltok::kw_align: {
968 if (ParseOptionalAlignment(Alignment))
970 B.addAlignmentAttr(Alignment);
976 // Perform some error checking.
980 HaveError |= Error(AttrLoc, "invalid use of attribute on a function");
982 case lltok::kw_align:
983 // As a hack, we allow "align 2" on functions as a synonym for
989 case lltok::kw_nocapture:
990 case lltok::kw_byval:
993 HaveError |= Error(AttrLoc, "invalid use of parameter-only attribute");
997 case lltok::kw_noreturn:
998 case lltok::kw_nounwind:
999 case lltok::kw_readnone:
1000 case lltok::kw_readonly:
1001 case lltok::kw_noinline:
1002 case lltok::kw_alwaysinline:
1003 case lltok::kw_optsize:
1005 case lltok::kw_sspreq:
1006 case lltok::kw_noredzone:
1007 case lltok::kw_noimplicitfloat:
1008 case lltok::kw_naked:
1009 case lltok::kw_inlinehint:
1010 case lltok::kw_alignstack:
1011 case lltok::kw_uwtable:
1012 case lltok::kw_nonlazybind:
1013 case lltok::kw_returns_twice:
1014 case lltok::kw_address_safety:
1015 case lltok::kw_minsize:
1017 HaveError |= Error(AttrLoc, "invalid use of function-only attribute");
1025 /// ParseOptionalLinkage
1028 /// ::= 'linker_private'
1029 /// ::= 'linker_private_weak'
1034 /// ::= 'linkonce_odr'
1035 /// ::= 'linkonce_odr_auto_hide'
1036 /// ::= 'available_externally'
1041 /// ::= 'extern_weak'
1043 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1045 switch (Lex.getKind()) {
1046 default: Res=GlobalValue::ExternalLinkage; return false;
1047 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1048 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1049 case lltok::kw_linker_private_weak:
1050 Res = GlobalValue::LinkerPrivateWeakLinkage;
1052 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1053 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1054 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1055 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1056 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1057 case lltok::kw_linkonce_odr_auto_hide:
1058 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1059 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1061 case lltok::kw_available_externally:
1062 Res = GlobalValue::AvailableExternallyLinkage;
1064 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1065 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1066 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1067 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1068 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1069 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1076 /// ParseOptionalVisibility
1082 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1083 switch (Lex.getKind()) {
1084 default: Res = GlobalValue::DefaultVisibility; return false;
1085 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1086 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1087 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1093 /// ParseOptionalCallingConv
1097 /// ::= 'kw_intel_ocl_bicc'
1099 /// ::= 'x86_stdcallcc'
1100 /// ::= 'x86_fastcallcc'
1101 /// ::= 'x86_thiscallcc'
1102 /// ::= 'arm_apcscc'
1103 /// ::= 'arm_aapcscc'
1104 /// ::= 'arm_aapcs_vfpcc'
1105 /// ::= 'msp430_intrcc'
1106 /// ::= 'ptx_kernel'
1107 /// ::= 'ptx_device'
1109 /// ::= 'spir_kernel'
1112 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1113 switch (Lex.getKind()) {
1114 default: CC = CallingConv::C; return false;
1115 case lltok::kw_ccc: CC = CallingConv::C; break;
1116 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1117 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1118 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1119 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1120 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1121 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1122 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1123 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1124 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1125 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1126 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1127 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1128 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1129 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1130 case lltok::kw_cc: {
1131 unsigned ArbitraryCC;
1133 if (ParseUInt32(ArbitraryCC))
1135 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1144 /// ParseInstructionMetadata
1145 /// ::= !dbg !42 (',' !dbg !57)*
1146 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1147 PerFunctionState *PFS) {
1149 if (Lex.getKind() != lltok::MetadataVar)
1150 return TokError("expected metadata after comma");
1152 std::string Name = Lex.getStrVal();
1153 unsigned MDK = M->getMDKindID(Name);
1157 SMLoc Loc = Lex.getLoc();
1159 if (ParseToken(lltok::exclaim, "expected '!' here"))
1162 // This code is similar to that of ParseMetadataValue, however it needs to
1163 // have special-case code for a forward reference; see the comments on
1164 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1165 // at the top level here.
1166 if (Lex.getKind() == lltok::lbrace) {
1168 if (ParseMetadataListValue(ID, PFS))
1170 assert(ID.Kind == ValID::t_MDNode);
1171 Inst->setMetadata(MDK, ID.MDNodeVal);
1173 unsigned NodeID = 0;
1174 if (ParseMDNodeID(Node, NodeID))
1177 // If we got the node, add it to the instruction.
1178 Inst->setMetadata(MDK, Node);
1180 MDRef R = { Loc, MDK, NodeID };
1181 // Otherwise, remember that this should be resolved later.
1182 ForwardRefInstMetadata[Inst].push_back(R);
1186 // If this is the end of the list, we're done.
1187 } while (EatIfPresent(lltok::comma));
1191 /// ParseOptionalAlignment
1194 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1196 if (!EatIfPresent(lltok::kw_align))
1198 LocTy AlignLoc = Lex.getLoc();
1199 if (ParseUInt32(Alignment)) return true;
1200 if (!isPowerOf2_32(Alignment))
1201 return Error(AlignLoc, "alignment is not a power of two");
1202 if (Alignment > Value::MaximumAlignment)
1203 return Error(AlignLoc, "huge alignments are not supported yet");
1207 /// ParseOptionalCommaAlign
1211 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1213 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1214 bool &AteExtraComma) {
1215 AteExtraComma = false;
1216 while (EatIfPresent(lltok::comma)) {
1217 // Metadata at the end is an early exit.
1218 if (Lex.getKind() == lltok::MetadataVar) {
1219 AteExtraComma = true;
1223 if (Lex.getKind() != lltok::kw_align)
1224 return Error(Lex.getLoc(), "expected metadata or 'align'");
1226 if (ParseOptionalAlignment(Alignment)) return true;
1232 /// ParseScopeAndOrdering
1233 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1236 /// This sets Scope and Ordering to the parsed values.
1237 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1238 AtomicOrdering &Ordering) {
1242 Scope = CrossThread;
1243 if (EatIfPresent(lltok::kw_singlethread))
1244 Scope = SingleThread;
1245 switch (Lex.getKind()) {
1246 default: return TokError("Expected ordering on atomic instruction");
1247 case lltok::kw_unordered: Ordering = Unordered; break;
1248 case lltok::kw_monotonic: Ordering = Monotonic; break;
1249 case lltok::kw_acquire: Ordering = Acquire; break;
1250 case lltok::kw_release: Ordering = Release; break;
1251 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1252 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1258 /// ParseOptionalStackAlignment
1260 /// ::= 'alignstack' '(' 4 ')'
1261 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1263 if (!EatIfPresent(lltok::kw_alignstack))
1265 LocTy ParenLoc = Lex.getLoc();
1266 if (!EatIfPresent(lltok::lparen))
1267 return Error(ParenLoc, "expected '('");
1268 LocTy AlignLoc = Lex.getLoc();
1269 if (ParseUInt32(Alignment)) return true;
1270 ParenLoc = Lex.getLoc();
1271 if (!EatIfPresent(lltok::rparen))
1272 return Error(ParenLoc, "expected ')'");
1273 if (!isPowerOf2_32(Alignment))
1274 return Error(AlignLoc, "stack alignment is not a power of two");
1278 /// ParseIndexList - This parses the index list for an insert/extractvalue
1279 /// instruction. This sets AteExtraComma in the case where we eat an extra
1280 /// comma at the end of the line and find that it is followed by metadata.
1281 /// Clients that don't allow metadata can call the version of this function that
1282 /// only takes one argument.
1285 /// ::= (',' uint32)+
1287 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1288 bool &AteExtraComma) {
1289 AteExtraComma = false;
1291 if (Lex.getKind() != lltok::comma)
1292 return TokError("expected ',' as start of index list");
1294 while (EatIfPresent(lltok::comma)) {
1295 if (Lex.getKind() == lltok::MetadataVar) {
1296 AteExtraComma = true;
1300 if (ParseUInt32(Idx)) return true;
1301 Indices.push_back(Idx);
1307 //===----------------------------------------------------------------------===//
1309 //===----------------------------------------------------------------------===//
1311 /// ParseType - Parse a type.
1312 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1313 SMLoc TypeLoc = Lex.getLoc();
1314 switch (Lex.getKind()) {
1316 return TokError("expected type");
1318 // Type ::= 'float' | 'void' (etc)
1319 Result = Lex.getTyVal();
1323 // Type ::= StructType
1324 if (ParseAnonStructType(Result, false))
1327 case lltok::lsquare:
1328 // Type ::= '[' ... ']'
1329 Lex.Lex(); // eat the lsquare.
1330 if (ParseArrayVectorType(Result, false))
1333 case lltok::less: // Either vector or packed struct.
1334 // Type ::= '<' ... '>'
1336 if (Lex.getKind() == lltok::lbrace) {
1337 if (ParseAnonStructType(Result, true) ||
1338 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1340 } else if (ParseArrayVectorType(Result, true))
1343 case lltok::LocalVar: {
1345 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1347 // If the type hasn't been defined yet, create a forward definition and
1348 // remember where that forward def'n was seen (in case it never is defined).
1349 if (Entry.first == 0) {
1350 Entry.first = StructType::create(Context, Lex.getStrVal());
1351 Entry.second = Lex.getLoc();
1353 Result = Entry.first;
1358 case lltok::LocalVarID: {
1360 if (Lex.getUIntVal() >= NumberedTypes.size())
1361 NumberedTypes.resize(Lex.getUIntVal()+1);
1362 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1364 // If the type hasn't been defined yet, create a forward definition and
1365 // remember where that forward def'n was seen (in case it never is defined).
1366 if (Entry.first == 0) {
1367 Entry.first = StructType::create(Context);
1368 Entry.second = Lex.getLoc();
1370 Result = Entry.first;
1376 // Parse the type suffixes.
1378 switch (Lex.getKind()) {
1381 if (!AllowVoid && Result->isVoidTy())
1382 return Error(TypeLoc, "void type only allowed for function results");
1385 // Type ::= Type '*'
1387 if (Result->isLabelTy())
1388 return TokError("basic block pointers are invalid");
1389 if (Result->isVoidTy())
1390 return TokError("pointers to void are invalid - use i8* instead");
1391 if (!PointerType::isValidElementType(Result))
1392 return TokError("pointer to this type is invalid");
1393 Result = PointerType::getUnqual(Result);
1397 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1398 case lltok::kw_addrspace: {
1399 if (Result->isLabelTy())
1400 return TokError("basic block pointers are invalid");
1401 if (Result->isVoidTy())
1402 return TokError("pointers to void are invalid; use i8* instead");
1403 if (!PointerType::isValidElementType(Result))
1404 return TokError("pointer to this type is invalid");
1406 if (ParseOptionalAddrSpace(AddrSpace) ||
1407 ParseToken(lltok::star, "expected '*' in address space"))
1410 Result = PointerType::get(Result, AddrSpace);
1414 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1416 if (ParseFunctionType(Result))
1423 /// ParseParameterList
1425 /// ::= '(' Arg (',' Arg)* ')'
1427 /// ::= Type OptionalAttributes Value OptionalAttributes
1428 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1429 PerFunctionState &PFS) {
1430 if (ParseToken(lltok::lparen, "expected '(' in call"))
1433 while (Lex.getKind() != lltok::rparen) {
1434 // If this isn't the first argument, we need a comma.
1435 if (!ArgList.empty() &&
1436 ParseToken(lltok::comma, "expected ',' in argument list"))
1439 // Parse the argument.
1442 AttrBuilder ArgAttrs;
1444 if (ParseType(ArgTy, ArgLoc))
1447 // Otherwise, handle normal operands.
1448 if (ParseOptionalAttrs(ArgAttrs, 0) || ParseValue(ArgTy, V, PFS))
1450 ArgList.push_back(ParamInfo(ArgLoc, V, Attributes::get(V->getContext(),
1454 Lex.Lex(); // Lex the ')'.
1460 /// ParseArgumentList - Parse the argument list for a function type or function
1462 /// ::= '(' ArgTypeListI ')'
1466 /// ::= ArgTypeList ',' '...'
1467 /// ::= ArgType (',' ArgType)*
1469 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1472 assert(Lex.getKind() == lltok::lparen);
1473 Lex.Lex(); // eat the (.
1475 if (Lex.getKind() == lltok::rparen) {
1477 } else if (Lex.getKind() == lltok::dotdotdot) {
1481 LocTy TypeLoc = Lex.getLoc();
1486 if (ParseType(ArgTy) ||
1487 ParseOptionalAttrs(Attrs, 0)) return true;
1489 if (ArgTy->isVoidTy())
1490 return Error(TypeLoc, "argument can not have void type");
1492 if (Lex.getKind() == lltok::LocalVar) {
1493 Name = Lex.getStrVal();
1497 if (!FunctionType::isValidArgumentType(ArgTy))
1498 return Error(TypeLoc, "invalid type for function argument");
1500 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1501 Attributes::get(ArgTy->getContext(),
1504 while (EatIfPresent(lltok::comma)) {
1505 // Handle ... at end of arg list.
1506 if (EatIfPresent(lltok::dotdotdot)) {
1511 // Otherwise must be an argument type.
1512 TypeLoc = Lex.getLoc();
1513 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
1515 if (ArgTy->isVoidTy())
1516 return Error(TypeLoc, "argument can not have void type");
1518 if (Lex.getKind() == lltok::LocalVar) {
1519 Name = Lex.getStrVal();
1525 if (!ArgTy->isFirstClassType())
1526 return Error(TypeLoc, "invalid type for function argument");
1528 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1529 Attributes::get(ArgTy->getContext(), Attrs),
1534 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1537 /// ParseFunctionType
1538 /// ::= Type ArgumentList OptionalAttrs
1539 bool LLParser::ParseFunctionType(Type *&Result) {
1540 assert(Lex.getKind() == lltok::lparen);
1542 if (!FunctionType::isValidReturnType(Result))
1543 return TokError("invalid function return type");
1545 SmallVector<ArgInfo, 8> ArgList;
1547 if (ParseArgumentList(ArgList, isVarArg))
1550 // Reject names on the arguments lists.
1551 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1552 if (!ArgList[i].Name.empty())
1553 return Error(ArgList[i].Loc, "argument name invalid in function type");
1554 if (ArgList[i].Attrs.hasAttributes())
1555 return Error(ArgList[i].Loc,
1556 "argument attributes invalid in function type");
1559 SmallVector<Type*, 16> ArgListTy;
1560 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1561 ArgListTy.push_back(ArgList[i].Ty);
1563 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1567 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1569 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1570 SmallVector<Type*, 8> Elts;
1571 if (ParseStructBody(Elts)) return true;
1573 Result = StructType::get(Context, Elts, Packed);
1577 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1578 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1579 std::pair<Type*, LocTy> &Entry,
1581 // If the type was already defined, diagnose the redefinition.
1582 if (Entry.first && !Entry.second.isValid())
1583 return Error(TypeLoc, "redefinition of type");
1585 // If we have opaque, just return without filling in the definition for the
1586 // struct. This counts as a definition as far as the .ll file goes.
1587 if (EatIfPresent(lltok::kw_opaque)) {
1588 // This type is being defined, so clear the location to indicate this.
1589 Entry.second = SMLoc();
1591 // If this type number has never been uttered, create it.
1592 if (Entry.first == 0)
1593 Entry.first = StructType::create(Context, Name);
1594 ResultTy = Entry.first;
1598 // If the type starts with '<', then it is either a packed struct or a vector.
1599 bool isPacked = EatIfPresent(lltok::less);
1601 // If we don't have a struct, then we have a random type alias, which we
1602 // accept for compatibility with old files. These types are not allowed to be
1603 // forward referenced and not allowed to be recursive.
1604 if (Lex.getKind() != lltok::lbrace) {
1606 return Error(TypeLoc, "forward references to non-struct type");
1610 return ParseArrayVectorType(ResultTy, true);
1611 return ParseType(ResultTy);
1614 // This type is being defined, so clear the location to indicate this.
1615 Entry.second = SMLoc();
1617 // If this type number has never been uttered, create it.
1618 if (Entry.first == 0)
1619 Entry.first = StructType::create(Context, Name);
1621 StructType *STy = cast<StructType>(Entry.first);
1623 SmallVector<Type*, 8> Body;
1624 if (ParseStructBody(Body) ||
1625 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1628 STy->setBody(Body, isPacked);
1634 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1637 /// ::= '{' Type (',' Type)* '}'
1638 /// ::= '<' '{' '}' '>'
1639 /// ::= '<' '{' Type (',' Type)* '}' '>'
1640 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1641 assert(Lex.getKind() == lltok::lbrace);
1642 Lex.Lex(); // Consume the '{'
1644 // Handle the empty struct.
1645 if (EatIfPresent(lltok::rbrace))
1648 LocTy EltTyLoc = Lex.getLoc();
1650 if (ParseType(Ty)) return true;
1653 if (!StructType::isValidElementType(Ty))
1654 return Error(EltTyLoc, "invalid element type for struct");
1656 while (EatIfPresent(lltok::comma)) {
1657 EltTyLoc = Lex.getLoc();
1658 if (ParseType(Ty)) return true;
1660 if (!StructType::isValidElementType(Ty))
1661 return Error(EltTyLoc, "invalid element type for struct");
1666 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1669 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1670 /// token has already been consumed.
1672 /// ::= '[' APSINTVAL 'x' Types ']'
1673 /// ::= '<' APSINTVAL 'x' Types '>'
1674 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1675 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1676 Lex.getAPSIntVal().getBitWidth() > 64)
1677 return TokError("expected number in address space");
1679 LocTy SizeLoc = Lex.getLoc();
1680 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1683 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1686 LocTy TypeLoc = Lex.getLoc();
1688 if (ParseType(EltTy)) return true;
1690 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1691 "expected end of sequential type"))
1696 return Error(SizeLoc, "zero element vector is illegal");
1697 if ((unsigned)Size != Size)
1698 return Error(SizeLoc, "size too large for vector");
1699 if (!VectorType::isValidElementType(EltTy))
1700 return Error(TypeLoc,
1701 "vector element type must be fp, integer or a pointer to these types");
1702 Result = VectorType::get(EltTy, unsigned(Size));
1704 if (!ArrayType::isValidElementType(EltTy))
1705 return Error(TypeLoc, "invalid array element type");
1706 Result = ArrayType::get(EltTy, Size);
1711 //===----------------------------------------------------------------------===//
1712 // Function Semantic Analysis.
1713 //===----------------------------------------------------------------------===//
1715 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1717 : P(p), F(f), FunctionNumber(functionNumber) {
1719 // Insert unnamed arguments into the NumberedVals list.
1720 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1723 NumberedVals.push_back(AI);
1726 LLParser::PerFunctionState::~PerFunctionState() {
1727 // If there were any forward referenced non-basicblock values, delete them.
1728 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1729 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1730 if (!isa<BasicBlock>(I->second.first)) {
1731 I->second.first->replaceAllUsesWith(
1732 UndefValue::get(I->second.first->getType()));
1733 delete I->second.first;
1734 I->second.first = 0;
1737 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1738 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1739 if (!isa<BasicBlock>(I->second.first)) {
1740 I->second.first->replaceAllUsesWith(
1741 UndefValue::get(I->second.first->getType()));
1742 delete I->second.first;
1743 I->second.first = 0;
1747 bool LLParser::PerFunctionState::FinishFunction() {
1748 // Check to see if someone took the address of labels in this block.
1749 if (!P.ForwardRefBlockAddresses.empty()) {
1751 if (!F.getName().empty()) {
1752 FunctionID.Kind = ValID::t_GlobalName;
1753 FunctionID.StrVal = F.getName();
1755 FunctionID.Kind = ValID::t_GlobalID;
1756 FunctionID.UIntVal = FunctionNumber;
1759 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1760 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1761 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1762 // Resolve all these references.
1763 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1766 P.ForwardRefBlockAddresses.erase(FRBAI);
1770 if (!ForwardRefVals.empty())
1771 return P.Error(ForwardRefVals.begin()->second.second,
1772 "use of undefined value '%" + ForwardRefVals.begin()->first +
1774 if (!ForwardRefValIDs.empty())
1775 return P.Error(ForwardRefValIDs.begin()->second.second,
1776 "use of undefined value '%" +
1777 Twine(ForwardRefValIDs.begin()->first) + "'");
1782 /// GetVal - Get a value with the specified name or ID, creating a
1783 /// forward reference record if needed. This can return null if the value
1784 /// exists but does not have the right type.
1785 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1786 Type *Ty, LocTy Loc) {
1787 // Look this name up in the normal function symbol table.
1788 Value *Val = F.getValueSymbolTable().lookup(Name);
1790 // If this is a forward reference for the value, see if we already created a
1791 // forward ref record.
1793 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1794 I = ForwardRefVals.find(Name);
1795 if (I != ForwardRefVals.end())
1796 Val = I->second.first;
1799 // If we have the value in the symbol table or fwd-ref table, return it.
1801 if (Val->getType() == Ty) return Val;
1802 if (Ty->isLabelTy())
1803 P.Error(Loc, "'%" + Name + "' is not a basic block");
1805 P.Error(Loc, "'%" + Name + "' defined with type '" +
1806 getTypeString(Val->getType()) + "'");
1810 // Don't make placeholders with invalid type.
1811 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1812 P.Error(Loc, "invalid use of a non-first-class type");
1816 // Otherwise, create a new forward reference for this value and remember it.
1818 if (Ty->isLabelTy())
1819 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1821 FwdVal = new Argument(Ty, Name);
1823 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1827 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1829 // Look this name up in the normal function symbol table.
1830 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1832 // If this is a forward reference for the value, see if we already created a
1833 // forward ref record.
1835 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1836 I = ForwardRefValIDs.find(ID);
1837 if (I != ForwardRefValIDs.end())
1838 Val = I->second.first;
1841 // If we have the value in the symbol table or fwd-ref table, return it.
1843 if (Val->getType() == Ty) return Val;
1844 if (Ty->isLabelTy())
1845 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1847 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1848 getTypeString(Val->getType()) + "'");
1852 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1853 P.Error(Loc, "invalid use of a non-first-class type");
1857 // Otherwise, create a new forward reference for this value and remember it.
1859 if (Ty->isLabelTy())
1860 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1862 FwdVal = new Argument(Ty);
1864 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1868 /// SetInstName - After an instruction is parsed and inserted into its
1869 /// basic block, this installs its name.
1870 bool LLParser::PerFunctionState::SetInstName(int NameID,
1871 const std::string &NameStr,
1872 LocTy NameLoc, Instruction *Inst) {
1873 // If this instruction has void type, it cannot have a name or ID specified.
1874 if (Inst->getType()->isVoidTy()) {
1875 if (NameID != -1 || !NameStr.empty())
1876 return P.Error(NameLoc, "instructions returning void cannot have a name");
1880 // If this was a numbered instruction, verify that the instruction is the
1881 // expected value and resolve any forward references.
1882 if (NameStr.empty()) {
1883 // If neither a name nor an ID was specified, just use the next ID.
1885 NameID = NumberedVals.size();
1887 if (unsigned(NameID) != NumberedVals.size())
1888 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1889 Twine(NumberedVals.size()) + "'");
1891 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1892 ForwardRefValIDs.find(NameID);
1893 if (FI != ForwardRefValIDs.end()) {
1894 if (FI->second.first->getType() != Inst->getType())
1895 return P.Error(NameLoc, "instruction forward referenced with type '" +
1896 getTypeString(FI->second.first->getType()) + "'");
1897 FI->second.first->replaceAllUsesWith(Inst);
1898 delete FI->second.first;
1899 ForwardRefValIDs.erase(FI);
1902 NumberedVals.push_back(Inst);
1906 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1907 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1908 FI = ForwardRefVals.find(NameStr);
1909 if (FI != ForwardRefVals.end()) {
1910 if (FI->second.first->getType() != Inst->getType())
1911 return P.Error(NameLoc, "instruction forward referenced with type '" +
1912 getTypeString(FI->second.first->getType()) + "'");
1913 FI->second.first->replaceAllUsesWith(Inst);
1914 delete FI->second.first;
1915 ForwardRefVals.erase(FI);
1918 // Set the name on the instruction.
1919 Inst->setName(NameStr);
1921 if (Inst->getName() != NameStr)
1922 return P.Error(NameLoc, "multiple definition of local value named '" +
1927 /// GetBB - Get a basic block with the specified name or ID, creating a
1928 /// forward reference record if needed.
1929 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1931 return cast_or_null<BasicBlock>(GetVal(Name,
1932 Type::getLabelTy(F.getContext()), Loc));
1935 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1936 return cast_or_null<BasicBlock>(GetVal(ID,
1937 Type::getLabelTy(F.getContext()), Loc));
1940 /// DefineBB - Define the specified basic block, which is either named or
1941 /// unnamed. If there is an error, this returns null otherwise it returns
1942 /// the block being defined.
1943 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1947 BB = GetBB(NumberedVals.size(), Loc);
1949 BB = GetBB(Name, Loc);
1950 if (BB == 0) return 0; // Already diagnosed error.
1952 // Move the block to the end of the function. Forward ref'd blocks are
1953 // inserted wherever they happen to be referenced.
1954 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1956 // Remove the block from forward ref sets.
1958 ForwardRefValIDs.erase(NumberedVals.size());
1959 NumberedVals.push_back(BB);
1961 // BB forward references are already in the function symbol table.
1962 ForwardRefVals.erase(Name);
1968 //===----------------------------------------------------------------------===//
1970 //===----------------------------------------------------------------------===//
1972 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1973 /// type implied. For example, if we parse "4" we don't know what integer type
1974 /// it has. The value will later be combined with its type and checked for
1975 /// sanity. PFS is used to convert function-local operands of metadata (since
1976 /// metadata operands are not just parsed here but also converted to values).
1977 /// PFS can be null when we are not parsing metadata values inside a function.
1978 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1979 ID.Loc = Lex.getLoc();
1980 switch (Lex.getKind()) {
1981 default: return TokError("expected value token");
1982 case lltok::GlobalID: // @42
1983 ID.UIntVal = Lex.getUIntVal();
1984 ID.Kind = ValID::t_GlobalID;
1986 case lltok::GlobalVar: // @foo
1987 ID.StrVal = Lex.getStrVal();
1988 ID.Kind = ValID::t_GlobalName;
1990 case lltok::LocalVarID: // %42
1991 ID.UIntVal = Lex.getUIntVal();
1992 ID.Kind = ValID::t_LocalID;
1994 case lltok::LocalVar: // %foo
1995 ID.StrVal = Lex.getStrVal();
1996 ID.Kind = ValID::t_LocalName;
1998 case lltok::exclaim: // !42, !{...}, or !"foo"
1999 return ParseMetadataValue(ID, PFS);
2001 ID.APSIntVal = Lex.getAPSIntVal();
2002 ID.Kind = ValID::t_APSInt;
2004 case lltok::APFloat:
2005 ID.APFloatVal = Lex.getAPFloatVal();
2006 ID.Kind = ValID::t_APFloat;
2008 case lltok::kw_true:
2009 ID.ConstantVal = ConstantInt::getTrue(Context);
2010 ID.Kind = ValID::t_Constant;
2012 case lltok::kw_false:
2013 ID.ConstantVal = ConstantInt::getFalse(Context);
2014 ID.Kind = ValID::t_Constant;
2016 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2017 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2018 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2020 case lltok::lbrace: {
2021 // ValID ::= '{' ConstVector '}'
2023 SmallVector<Constant*, 16> Elts;
2024 if (ParseGlobalValueVector(Elts) ||
2025 ParseToken(lltok::rbrace, "expected end of struct constant"))
2028 ID.ConstantStructElts = new Constant*[Elts.size()];
2029 ID.UIntVal = Elts.size();
2030 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2031 ID.Kind = ValID::t_ConstantStruct;
2035 // ValID ::= '<' ConstVector '>' --> Vector.
2036 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2038 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2040 SmallVector<Constant*, 16> Elts;
2041 LocTy FirstEltLoc = Lex.getLoc();
2042 if (ParseGlobalValueVector(Elts) ||
2044 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2045 ParseToken(lltok::greater, "expected end of constant"))
2048 if (isPackedStruct) {
2049 ID.ConstantStructElts = new Constant*[Elts.size()];
2050 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2051 ID.UIntVal = Elts.size();
2052 ID.Kind = ValID::t_PackedConstantStruct;
2057 return Error(ID.Loc, "constant vector must not be empty");
2059 if (!Elts[0]->getType()->isIntegerTy() &&
2060 !Elts[0]->getType()->isFloatingPointTy() &&
2061 !Elts[0]->getType()->isPointerTy())
2062 return Error(FirstEltLoc,
2063 "vector elements must have integer, pointer or floating point type");
2065 // Verify that all the vector elements have the same type.
2066 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2067 if (Elts[i]->getType() != Elts[0]->getType())
2068 return Error(FirstEltLoc,
2069 "vector element #" + Twine(i) +
2070 " is not of type '" + getTypeString(Elts[0]->getType()));
2072 ID.ConstantVal = ConstantVector::get(Elts);
2073 ID.Kind = ValID::t_Constant;
2076 case lltok::lsquare: { // Array Constant
2078 SmallVector<Constant*, 16> Elts;
2079 LocTy FirstEltLoc = Lex.getLoc();
2080 if (ParseGlobalValueVector(Elts) ||
2081 ParseToken(lltok::rsquare, "expected end of array constant"))
2084 // Handle empty element.
2086 // Use undef instead of an array because it's inconvenient to determine
2087 // the element type at this point, there being no elements to examine.
2088 ID.Kind = ValID::t_EmptyArray;
2092 if (!Elts[0]->getType()->isFirstClassType())
2093 return Error(FirstEltLoc, "invalid array element type: " +
2094 getTypeString(Elts[0]->getType()));
2096 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2098 // Verify all elements are correct type!
2099 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2100 if (Elts[i]->getType() != Elts[0]->getType())
2101 return Error(FirstEltLoc,
2102 "array element #" + Twine(i) +
2103 " is not of type '" + getTypeString(Elts[0]->getType()));
2106 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2107 ID.Kind = ValID::t_Constant;
2110 case lltok::kw_c: // c "foo"
2112 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2114 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2115 ID.Kind = ValID::t_Constant;
2118 case lltok::kw_asm: {
2119 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2120 bool HasSideEffect, AlignStack, AsmDialect;
2122 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2123 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2124 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2125 ParseStringConstant(ID.StrVal) ||
2126 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2127 ParseToken(lltok::StringConstant, "expected constraint string"))
2129 ID.StrVal2 = Lex.getStrVal();
2130 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2131 (unsigned(AsmDialect)<<2);
2132 ID.Kind = ValID::t_InlineAsm;
2136 case lltok::kw_blockaddress: {
2137 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2141 LocTy FnLoc, LabelLoc;
2143 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2145 ParseToken(lltok::comma, "expected comma in block address expression")||
2146 ParseValID(Label) ||
2147 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2150 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2151 return Error(Fn.Loc, "expected function name in blockaddress");
2152 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2153 return Error(Label.Loc, "expected basic block name in blockaddress");
2155 // Make a global variable as a placeholder for this reference.
2156 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2157 false, GlobalValue::InternalLinkage,
2159 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2160 ID.ConstantVal = FwdRef;
2161 ID.Kind = ValID::t_Constant;
2165 case lltok::kw_trunc:
2166 case lltok::kw_zext:
2167 case lltok::kw_sext:
2168 case lltok::kw_fptrunc:
2169 case lltok::kw_fpext:
2170 case lltok::kw_bitcast:
2171 case lltok::kw_uitofp:
2172 case lltok::kw_sitofp:
2173 case lltok::kw_fptoui:
2174 case lltok::kw_fptosi:
2175 case lltok::kw_inttoptr:
2176 case lltok::kw_ptrtoint: {
2177 unsigned Opc = Lex.getUIntVal();
2181 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2182 ParseGlobalTypeAndValue(SrcVal) ||
2183 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2184 ParseType(DestTy) ||
2185 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2187 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2188 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2189 getTypeString(SrcVal->getType()) + "' to '" +
2190 getTypeString(DestTy) + "'");
2191 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2193 ID.Kind = ValID::t_Constant;
2196 case lltok::kw_extractvalue: {
2199 SmallVector<unsigned, 4> Indices;
2200 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2201 ParseGlobalTypeAndValue(Val) ||
2202 ParseIndexList(Indices) ||
2203 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2206 if (!Val->getType()->isAggregateType())
2207 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2208 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2209 return Error(ID.Loc, "invalid indices for extractvalue");
2210 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2211 ID.Kind = ValID::t_Constant;
2214 case lltok::kw_insertvalue: {
2216 Constant *Val0, *Val1;
2217 SmallVector<unsigned, 4> Indices;
2218 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2219 ParseGlobalTypeAndValue(Val0) ||
2220 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2221 ParseGlobalTypeAndValue(Val1) ||
2222 ParseIndexList(Indices) ||
2223 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2225 if (!Val0->getType()->isAggregateType())
2226 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2227 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2228 return Error(ID.Loc, "invalid indices for insertvalue");
2229 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2230 ID.Kind = ValID::t_Constant;
2233 case lltok::kw_icmp:
2234 case lltok::kw_fcmp: {
2235 unsigned PredVal, Opc = Lex.getUIntVal();
2236 Constant *Val0, *Val1;
2238 if (ParseCmpPredicate(PredVal, Opc) ||
2239 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2240 ParseGlobalTypeAndValue(Val0) ||
2241 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2242 ParseGlobalTypeAndValue(Val1) ||
2243 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2246 if (Val0->getType() != Val1->getType())
2247 return Error(ID.Loc, "compare operands must have the same type");
2249 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2251 if (Opc == Instruction::FCmp) {
2252 if (!Val0->getType()->isFPOrFPVectorTy())
2253 return Error(ID.Loc, "fcmp requires floating point operands");
2254 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2256 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2257 if (!Val0->getType()->isIntOrIntVectorTy() &&
2258 !Val0->getType()->getScalarType()->isPointerTy())
2259 return Error(ID.Loc, "icmp requires pointer or integer operands");
2260 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2262 ID.Kind = ValID::t_Constant;
2266 // Binary Operators.
2268 case lltok::kw_fadd:
2270 case lltok::kw_fsub:
2272 case lltok::kw_fmul:
2273 case lltok::kw_udiv:
2274 case lltok::kw_sdiv:
2275 case lltok::kw_fdiv:
2276 case lltok::kw_urem:
2277 case lltok::kw_srem:
2278 case lltok::kw_frem:
2280 case lltok::kw_lshr:
2281 case lltok::kw_ashr: {
2285 unsigned Opc = Lex.getUIntVal();
2286 Constant *Val0, *Val1;
2288 LocTy ModifierLoc = Lex.getLoc();
2289 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2290 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2291 if (EatIfPresent(lltok::kw_nuw))
2293 if (EatIfPresent(lltok::kw_nsw)) {
2295 if (EatIfPresent(lltok::kw_nuw))
2298 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2299 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2300 if (EatIfPresent(lltok::kw_exact))
2303 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2304 ParseGlobalTypeAndValue(Val0) ||
2305 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2306 ParseGlobalTypeAndValue(Val1) ||
2307 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2309 if (Val0->getType() != Val1->getType())
2310 return Error(ID.Loc, "operands of constexpr must have same type");
2311 if (!Val0->getType()->isIntOrIntVectorTy()) {
2313 return Error(ModifierLoc, "nuw only applies to integer operations");
2315 return Error(ModifierLoc, "nsw only applies to integer operations");
2317 // Check that the type is valid for the operator.
2319 case Instruction::Add:
2320 case Instruction::Sub:
2321 case Instruction::Mul:
2322 case Instruction::UDiv:
2323 case Instruction::SDiv:
2324 case Instruction::URem:
2325 case Instruction::SRem:
2326 case Instruction::Shl:
2327 case Instruction::AShr:
2328 case Instruction::LShr:
2329 if (!Val0->getType()->isIntOrIntVectorTy())
2330 return Error(ID.Loc, "constexpr requires integer operands");
2332 case Instruction::FAdd:
2333 case Instruction::FSub:
2334 case Instruction::FMul:
2335 case Instruction::FDiv:
2336 case Instruction::FRem:
2337 if (!Val0->getType()->isFPOrFPVectorTy())
2338 return Error(ID.Loc, "constexpr requires fp operands");
2340 default: llvm_unreachable("Unknown binary operator!");
2343 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2344 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2345 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2346 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2348 ID.Kind = ValID::t_Constant;
2352 // Logical Operations
2355 case lltok::kw_xor: {
2356 unsigned Opc = Lex.getUIntVal();
2357 Constant *Val0, *Val1;
2359 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2360 ParseGlobalTypeAndValue(Val0) ||
2361 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2362 ParseGlobalTypeAndValue(Val1) ||
2363 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2365 if (Val0->getType() != Val1->getType())
2366 return Error(ID.Loc, "operands of constexpr must have same type");
2367 if (!Val0->getType()->isIntOrIntVectorTy())
2368 return Error(ID.Loc,
2369 "constexpr requires integer or integer vector operands");
2370 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2371 ID.Kind = ValID::t_Constant;
2375 case lltok::kw_getelementptr:
2376 case lltok::kw_shufflevector:
2377 case lltok::kw_insertelement:
2378 case lltok::kw_extractelement:
2379 case lltok::kw_select: {
2380 unsigned Opc = Lex.getUIntVal();
2381 SmallVector<Constant*, 16> Elts;
2382 bool InBounds = false;
2384 if (Opc == Instruction::GetElementPtr)
2385 InBounds = EatIfPresent(lltok::kw_inbounds);
2386 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2387 ParseGlobalValueVector(Elts) ||
2388 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2391 if (Opc == Instruction::GetElementPtr) {
2392 if (Elts.size() == 0 ||
2393 !Elts[0]->getType()->getScalarType()->isPointerTy())
2394 return Error(ID.Loc, "getelementptr requires pointer operand");
2396 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2397 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2398 return Error(ID.Loc, "invalid indices for getelementptr");
2399 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2401 } else if (Opc == Instruction::Select) {
2402 if (Elts.size() != 3)
2403 return Error(ID.Loc, "expected three operands to select");
2404 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2406 return Error(ID.Loc, Reason);
2407 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2408 } else if (Opc == Instruction::ShuffleVector) {
2409 if (Elts.size() != 3)
2410 return Error(ID.Loc, "expected three operands to shufflevector");
2411 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2412 return Error(ID.Loc, "invalid operands to shufflevector");
2414 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2415 } else if (Opc == Instruction::ExtractElement) {
2416 if (Elts.size() != 2)
2417 return Error(ID.Loc, "expected two operands to extractelement");
2418 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2419 return Error(ID.Loc, "invalid extractelement operands");
2420 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2422 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2423 if (Elts.size() != 3)
2424 return Error(ID.Loc, "expected three operands to insertelement");
2425 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2426 return Error(ID.Loc, "invalid insertelement operands");
2428 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2431 ID.Kind = ValID::t_Constant;
2440 /// ParseGlobalValue - Parse a global value with the specified type.
2441 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2445 bool Parsed = ParseValID(ID) ||
2446 ConvertValIDToValue(Ty, ID, V, NULL);
2447 if (V && !(C = dyn_cast<Constant>(V)))
2448 return Error(ID.Loc, "global values must be constants");
2452 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2454 return ParseType(Ty) ||
2455 ParseGlobalValue(Ty, V);
2458 /// ParseGlobalValueVector
2460 /// ::= TypeAndValue (',' TypeAndValue)*
2461 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2463 if (Lex.getKind() == lltok::rbrace ||
2464 Lex.getKind() == lltok::rsquare ||
2465 Lex.getKind() == lltok::greater ||
2466 Lex.getKind() == lltok::rparen)
2470 if (ParseGlobalTypeAndValue(C)) return true;
2473 while (EatIfPresent(lltok::comma)) {
2474 if (ParseGlobalTypeAndValue(C)) return true;
2481 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2482 assert(Lex.getKind() == lltok::lbrace);
2485 SmallVector<Value*, 16> Elts;
2486 if (ParseMDNodeVector(Elts, PFS) ||
2487 ParseToken(lltok::rbrace, "expected end of metadata node"))
2490 ID.MDNodeVal = MDNode::get(Context, Elts);
2491 ID.Kind = ValID::t_MDNode;
2495 /// ParseMetadataValue
2499 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2500 assert(Lex.getKind() == lltok::exclaim);
2505 if (Lex.getKind() == lltok::lbrace)
2506 return ParseMetadataListValue(ID, PFS);
2508 // Standalone metadata reference
2510 if (Lex.getKind() == lltok::APSInt) {
2511 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2512 ID.Kind = ValID::t_MDNode;
2517 // ::= '!' STRINGCONSTANT
2518 if (ParseMDString(ID.MDStringVal)) return true;
2519 ID.Kind = ValID::t_MDString;
2524 //===----------------------------------------------------------------------===//
2525 // Function Parsing.
2526 //===----------------------------------------------------------------------===//
2528 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2529 PerFunctionState *PFS) {
2530 if (Ty->isFunctionTy())
2531 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2534 case ValID::t_LocalID:
2535 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2536 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2538 case ValID::t_LocalName:
2539 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2540 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2542 case ValID::t_InlineAsm: {
2543 PointerType *PTy = dyn_cast<PointerType>(Ty);
2545 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2546 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2547 return Error(ID.Loc, "invalid type for inline asm constraint string");
2548 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2549 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2552 case ValID::t_MDNode:
2553 if (!Ty->isMetadataTy())
2554 return Error(ID.Loc, "metadata value must have metadata type");
2557 case ValID::t_MDString:
2558 if (!Ty->isMetadataTy())
2559 return Error(ID.Loc, "metadata value must have metadata type");
2562 case ValID::t_GlobalName:
2563 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2565 case ValID::t_GlobalID:
2566 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2568 case ValID::t_APSInt:
2569 if (!Ty->isIntegerTy())
2570 return Error(ID.Loc, "integer constant must have integer type");
2571 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2572 V = ConstantInt::get(Context, ID.APSIntVal);
2574 case ValID::t_APFloat:
2575 if (!Ty->isFloatingPointTy() ||
2576 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2577 return Error(ID.Loc, "floating point constant invalid for type");
2579 // The lexer has no type info, so builds all half, float, and double FP
2580 // constants as double. Fix this here. Long double does not need this.
2581 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2584 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2586 else if (Ty->isFloatTy())
2587 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2590 V = ConstantFP::get(Context, ID.APFloatVal);
2592 if (V->getType() != Ty)
2593 return Error(ID.Loc, "floating point constant does not have type '" +
2594 getTypeString(Ty) + "'");
2598 if (!Ty->isPointerTy())
2599 return Error(ID.Loc, "null must be a pointer type");
2600 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2602 case ValID::t_Undef:
2603 // FIXME: LabelTy should not be a first-class type.
2604 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2605 return Error(ID.Loc, "invalid type for undef constant");
2606 V = UndefValue::get(Ty);
2608 case ValID::t_EmptyArray:
2609 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2610 return Error(ID.Loc, "invalid empty array initializer");
2611 V = UndefValue::get(Ty);
2614 // FIXME: LabelTy should not be a first-class type.
2615 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2616 return Error(ID.Loc, "invalid type for null constant");
2617 V = Constant::getNullValue(Ty);
2619 case ValID::t_Constant:
2620 if (ID.ConstantVal->getType() != Ty)
2621 return Error(ID.Loc, "constant expression type mismatch");
2625 case ValID::t_ConstantStruct:
2626 case ValID::t_PackedConstantStruct:
2627 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2628 if (ST->getNumElements() != ID.UIntVal)
2629 return Error(ID.Loc,
2630 "initializer with struct type has wrong # elements");
2631 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2632 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2634 // Verify that the elements are compatible with the structtype.
2635 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2636 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2637 return Error(ID.Loc, "element " + Twine(i) +
2638 " of struct initializer doesn't match struct element type");
2640 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2643 return Error(ID.Loc, "constant expression type mismatch");
2646 llvm_unreachable("Invalid ValID");
2649 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2652 return ParseValID(ID, PFS) ||
2653 ConvertValIDToValue(Ty, ID, V, PFS);
2656 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2658 return ParseType(Ty) ||
2659 ParseValue(Ty, V, PFS);
2662 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2663 PerFunctionState &PFS) {
2666 if (ParseTypeAndValue(V, PFS)) return true;
2667 if (!isa<BasicBlock>(V))
2668 return Error(Loc, "expected a basic block");
2669 BB = cast<BasicBlock>(V);
2675 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2676 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2677 /// OptionalAlign OptGC
2678 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2679 // Parse the linkage.
2680 LocTy LinkageLoc = Lex.getLoc();
2683 unsigned Visibility;
2684 AttrBuilder RetAttrs;
2687 LocTy RetTypeLoc = Lex.getLoc();
2688 if (ParseOptionalLinkage(Linkage) ||
2689 ParseOptionalVisibility(Visibility) ||
2690 ParseOptionalCallingConv(CC) ||
2691 ParseOptionalAttrs(RetAttrs, 1) ||
2692 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2695 // Verify that the linkage is ok.
2696 switch ((GlobalValue::LinkageTypes)Linkage) {
2697 case GlobalValue::ExternalLinkage:
2698 break; // always ok.
2699 case GlobalValue::DLLImportLinkage:
2700 case GlobalValue::ExternalWeakLinkage:
2702 return Error(LinkageLoc, "invalid linkage for function definition");
2704 case GlobalValue::PrivateLinkage:
2705 case GlobalValue::LinkerPrivateLinkage:
2706 case GlobalValue::LinkerPrivateWeakLinkage:
2707 case GlobalValue::InternalLinkage:
2708 case GlobalValue::AvailableExternallyLinkage:
2709 case GlobalValue::LinkOnceAnyLinkage:
2710 case GlobalValue::LinkOnceODRLinkage:
2711 case GlobalValue::LinkOnceODRAutoHideLinkage:
2712 case GlobalValue::WeakAnyLinkage:
2713 case GlobalValue::WeakODRLinkage:
2714 case GlobalValue::DLLExportLinkage:
2716 return Error(LinkageLoc, "invalid linkage for function declaration");
2718 case GlobalValue::AppendingLinkage:
2719 case GlobalValue::CommonLinkage:
2720 return Error(LinkageLoc, "invalid function linkage type");
2723 if (!FunctionType::isValidReturnType(RetType))
2724 return Error(RetTypeLoc, "invalid function return type");
2726 LocTy NameLoc = Lex.getLoc();
2728 std::string FunctionName;
2729 if (Lex.getKind() == lltok::GlobalVar) {
2730 FunctionName = Lex.getStrVal();
2731 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2732 unsigned NameID = Lex.getUIntVal();
2734 if (NameID != NumberedVals.size())
2735 return TokError("function expected to be numbered '%" +
2736 Twine(NumberedVals.size()) + "'");
2738 return TokError("expected function name");
2743 if (Lex.getKind() != lltok::lparen)
2744 return TokError("expected '(' in function argument list");
2746 SmallVector<ArgInfo, 8> ArgList;
2748 AttrBuilder FuncAttrs;
2749 std::string Section;
2753 LocTy UnnamedAddrLoc;
2755 if (ParseArgumentList(ArgList, isVarArg) ||
2756 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2758 ParseOptionalAttrs(FuncAttrs, 2) ||
2759 (EatIfPresent(lltok::kw_section) &&
2760 ParseStringConstant(Section)) ||
2761 ParseOptionalAlignment(Alignment) ||
2762 (EatIfPresent(lltok::kw_gc) &&
2763 ParseStringConstant(GC)))
2766 // If the alignment was parsed as an attribute, move to the alignment field.
2767 if (FuncAttrs.hasAlignmentAttr()) {
2768 Alignment = FuncAttrs.getAlignment();
2769 FuncAttrs.removeAttribute(Attributes::Alignment);
2772 // Okay, if we got here, the function is syntactically valid. Convert types
2773 // and do semantic checks.
2774 std::vector<Type*> ParamTypeList;
2775 SmallVector<AttributeWithIndex, 8> Attrs;
2777 if (RetAttrs.hasAttributes())
2779 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
2780 Attributes::get(RetType->getContext(),
2783 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2784 ParamTypeList.push_back(ArgList[i].Ty);
2785 if (ArgList[i].Attrs.hasAttributes())
2786 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2789 if (FuncAttrs.hasAttributes())
2791 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
2792 Attributes::get(RetType->getContext(),
2795 AttrListPtr PAL = AttrListPtr::get(Attrs);
2797 if (PAL.getParamAttributes(1).hasAttribute(Attributes::StructRet) &&
2798 !RetType->isVoidTy())
2799 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2802 FunctionType::get(RetType, ParamTypeList, isVarArg);
2803 PointerType *PFT = PointerType::getUnqual(FT);
2806 if (!FunctionName.empty()) {
2807 // If this was a definition of a forward reference, remove the definition
2808 // from the forward reference table and fill in the forward ref.
2809 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2810 ForwardRefVals.find(FunctionName);
2811 if (FRVI != ForwardRefVals.end()) {
2812 Fn = M->getFunction(FunctionName);
2814 return Error(FRVI->second.second, "invalid forward reference to "
2815 "function as global value!");
2816 if (Fn->getType() != PFT)
2817 return Error(FRVI->second.second, "invalid forward reference to "
2818 "function '" + FunctionName + "' with wrong type!");
2820 ForwardRefVals.erase(FRVI);
2821 } else if ((Fn = M->getFunction(FunctionName))) {
2822 // Reject redefinitions.
2823 return Error(NameLoc, "invalid redefinition of function '" +
2824 FunctionName + "'");
2825 } else if (M->getNamedValue(FunctionName)) {
2826 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2830 // If this is a definition of a forward referenced function, make sure the
2832 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2833 = ForwardRefValIDs.find(NumberedVals.size());
2834 if (I != ForwardRefValIDs.end()) {
2835 Fn = cast<Function>(I->second.first);
2836 if (Fn->getType() != PFT)
2837 return Error(NameLoc, "type of definition and forward reference of '@" +
2838 Twine(NumberedVals.size()) + "' disagree");
2839 ForwardRefValIDs.erase(I);
2844 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2845 else // Move the forward-reference to the correct spot in the module.
2846 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2848 if (FunctionName.empty())
2849 NumberedVals.push_back(Fn);
2851 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2852 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2853 Fn->setCallingConv(CC);
2854 Fn->setAttributes(PAL);
2855 Fn->setUnnamedAddr(UnnamedAddr);
2856 Fn->setAlignment(Alignment);
2857 Fn->setSection(Section);
2858 if (!GC.empty()) Fn->setGC(GC.c_str());
2860 // Add all of the arguments we parsed to the function.
2861 Function::arg_iterator ArgIt = Fn->arg_begin();
2862 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2863 // If the argument has a name, insert it into the argument symbol table.
2864 if (ArgList[i].Name.empty()) continue;
2866 // Set the name, if it conflicted, it will be auto-renamed.
2867 ArgIt->setName(ArgList[i].Name);
2869 if (ArgIt->getName() != ArgList[i].Name)
2870 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2871 ArgList[i].Name + "'");
2878 /// ParseFunctionBody
2879 /// ::= '{' BasicBlock+ '}'
2881 bool LLParser::ParseFunctionBody(Function &Fn) {
2882 if (Lex.getKind() != lltok::lbrace)
2883 return TokError("expected '{' in function body");
2884 Lex.Lex(); // eat the {.
2886 int FunctionNumber = -1;
2887 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2889 PerFunctionState PFS(*this, Fn, FunctionNumber);
2891 // We need at least one basic block.
2892 if (Lex.getKind() == lltok::rbrace)
2893 return TokError("function body requires at least one basic block");
2895 while (Lex.getKind() != lltok::rbrace)
2896 if (ParseBasicBlock(PFS)) return true;
2901 // Verify function is ok.
2902 return PFS.FinishFunction();
2906 /// ::= LabelStr? Instruction*
2907 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2908 // If this basic block starts out with a name, remember it.
2910 LocTy NameLoc = Lex.getLoc();
2911 if (Lex.getKind() == lltok::LabelStr) {
2912 Name = Lex.getStrVal();
2916 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2917 if (BB == 0) return true;
2919 std::string NameStr;
2921 // Parse the instructions in this block until we get a terminator.
2923 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2925 // This instruction may have three possibilities for a name: a) none
2926 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2927 LocTy NameLoc = Lex.getLoc();
2931 if (Lex.getKind() == lltok::LocalVarID) {
2932 NameID = Lex.getUIntVal();
2934 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2936 } else if (Lex.getKind() == lltok::LocalVar) {
2937 NameStr = Lex.getStrVal();
2939 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2943 switch (ParseInstruction(Inst, BB, PFS)) {
2944 default: llvm_unreachable("Unknown ParseInstruction result!");
2945 case InstError: return true;
2947 BB->getInstList().push_back(Inst);
2949 // With a normal result, we check to see if the instruction is followed by
2950 // a comma and metadata.
2951 if (EatIfPresent(lltok::comma))
2952 if (ParseInstructionMetadata(Inst, &PFS))
2955 case InstExtraComma:
2956 BB->getInstList().push_back(Inst);
2958 // If the instruction parser ate an extra comma at the end of it, it
2959 // *must* be followed by metadata.
2960 if (ParseInstructionMetadata(Inst, &PFS))
2965 // Set the name on the instruction.
2966 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2967 } while (!isa<TerminatorInst>(Inst));
2972 //===----------------------------------------------------------------------===//
2973 // Instruction Parsing.
2974 //===----------------------------------------------------------------------===//
2976 /// ParseInstruction - Parse one of the many different instructions.
2978 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2979 PerFunctionState &PFS) {
2980 lltok::Kind Token = Lex.getKind();
2981 if (Token == lltok::Eof)
2982 return TokError("found end of file when expecting more instructions");
2983 LocTy Loc = Lex.getLoc();
2984 unsigned KeywordVal = Lex.getUIntVal();
2985 Lex.Lex(); // Eat the keyword.
2988 default: return Error(Loc, "expected instruction opcode");
2989 // Terminator Instructions.
2990 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2991 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2992 case lltok::kw_br: return ParseBr(Inst, PFS);
2993 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2994 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2995 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2996 case lltok::kw_resume: return ParseResume(Inst, PFS);
2997 // Binary Operators.
3001 case lltok::kw_shl: {
3002 bool NUW = EatIfPresent(lltok::kw_nuw);
3003 bool NSW = EatIfPresent(lltok::kw_nsw);
3004 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3006 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3008 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3009 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3012 case lltok::kw_fadd:
3013 case lltok::kw_fsub:
3014 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3016 case lltok::kw_sdiv:
3017 case lltok::kw_udiv:
3018 case lltok::kw_lshr:
3019 case lltok::kw_ashr: {
3020 bool Exact = EatIfPresent(lltok::kw_exact);
3022 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3023 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3027 case lltok::kw_urem:
3028 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3029 case lltok::kw_fdiv:
3030 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3033 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3034 case lltok::kw_icmp:
3035 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3037 case lltok::kw_trunc:
3038 case lltok::kw_zext:
3039 case lltok::kw_sext:
3040 case lltok::kw_fptrunc:
3041 case lltok::kw_fpext:
3042 case lltok::kw_bitcast:
3043 case lltok::kw_uitofp:
3044 case lltok::kw_sitofp:
3045 case lltok::kw_fptoui:
3046 case lltok::kw_fptosi:
3047 case lltok::kw_inttoptr:
3048 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3050 case lltok::kw_select: return ParseSelect(Inst, PFS);
3051 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3052 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3053 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3054 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3055 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3056 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3057 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3058 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3060 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3061 case lltok::kw_load: return ParseLoad(Inst, PFS);
3062 case lltok::kw_store: return ParseStore(Inst, PFS);
3063 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3064 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3065 case lltok::kw_fence: return ParseFence(Inst, PFS);
3066 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3067 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3068 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3072 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3073 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3074 if (Opc == Instruction::FCmp) {
3075 switch (Lex.getKind()) {
3076 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3077 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3078 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3079 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3080 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3081 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3082 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3083 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3084 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3085 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3086 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3087 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3088 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3089 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3090 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3091 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3092 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3095 switch (Lex.getKind()) {
3096 default: TokError("expected icmp predicate (e.g. 'eq')");
3097 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3098 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3099 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3100 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3101 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3102 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3103 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3104 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3105 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3106 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3113 //===----------------------------------------------------------------------===//
3114 // Terminator Instructions.
3115 //===----------------------------------------------------------------------===//
3117 /// ParseRet - Parse a return instruction.
3118 /// ::= 'ret' void (',' !dbg, !1)*
3119 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3120 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3121 PerFunctionState &PFS) {
3122 SMLoc TypeLoc = Lex.getLoc();
3124 if (ParseType(Ty, true /*void allowed*/)) return true;
3126 Type *ResType = PFS.getFunction().getReturnType();
3128 if (Ty->isVoidTy()) {
3129 if (!ResType->isVoidTy())
3130 return Error(TypeLoc, "value doesn't match function result type '" +
3131 getTypeString(ResType) + "'");
3133 Inst = ReturnInst::Create(Context);
3138 if (ParseValue(Ty, RV, PFS)) return true;
3140 if (ResType != RV->getType())
3141 return Error(TypeLoc, "value doesn't match function result type '" +
3142 getTypeString(ResType) + "'");
3144 Inst = ReturnInst::Create(Context, RV);
3150 /// ::= 'br' TypeAndValue
3151 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3152 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3155 BasicBlock *Op1, *Op2;
3156 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3158 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3159 Inst = BranchInst::Create(BB);
3163 if (Op0->getType() != Type::getInt1Ty(Context))
3164 return Error(Loc, "branch condition must have 'i1' type");
3166 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3167 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3168 ParseToken(lltok::comma, "expected ',' after true destination") ||
3169 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3172 Inst = BranchInst::Create(Op1, Op2, Op0);
3178 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3180 /// ::= (TypeAndValue ',' TypeAndValue)*
3181 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3182 LocTy CondLoc, BBLoc;
3184 BasicBlock *DefaultBB;
3185 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3186 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3187 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3188 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3191 if (!Cond->getType()->isIntegerTy())
3192 return Error(CondLoc, "switch condition must have integer type");
3194 // Parse the jump table pairs.
3195 SmallPtrSet<Value*, 32> SeenCases;
3196 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3197 while (Lex.getKind() != lltok::rsquare) {
3201 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3202 ParseToken(lltok::comma, "expected ',' after case value") ||
3203 ParseTypeAndBasicBlock(DestBB, PFS))
3206 if (!SeenCases.insert(Constant))
3207 return Error(CondLoc, "duplicate case value in switch");
3208 if (!isa<ConstantInt>(Constant))
3209 return Error(CondLoc, "case value is not a constant integer");
3211 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3214 Lex.Lex(); // Eat the ']'.
3216 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3217 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3218 SI->addCase(Table[i].first, Table[i].second);
3225 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3226 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3229 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3230 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3231 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3234 if (!Address->getType()->isPointerTy())
3235 return Error(AddrLoc, "indirectbr address must have pointer type");
3237 // Parse the destination list.
3238 SmallVector<BasicBlock*, 16> DestList;
3240 if (Lex.getKind() != lltok::rsquare) {
3242 if (ParseTypeAndBasicBlock(DestBB, PFS))
3244 DestList.push_back(DestBB);
3246 while (EatIfPresent(lltok::comma)) {
3247 if (ParseTypeAndBasicBlock(DestBB, PFS))
3249 DestList.push_back(DestBB);
3253 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3256 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3257 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3258 IBI->addDestination(DestList[i]);
3265 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3266 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3267 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3268 LocTy CallLoc = Lex.getLoc();
3269 AttrBuilder RetAttrs, FnAttrs;
3274 SmallVector<ParamInfo, 16> ArgList;
3276 BasicBlock *NormalBB, *UnwindBB;
3277 if (ParseOptionalCallingConv(CC) ||
3278 ParseOptionalAttrs(RetAttrs, 1) ||
3279 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3280 ParseValID(CalleeID) ||
3281 ParseParameterList(ArgList, PFS) ||
3282 ParseOptionalAttrs(FnAttrs, 2) ||
3283 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3284 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3285 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3286 ParseTypeAndBasicBlock(UnwindBB, PFS))
3289 // If RetType is a non-function pointer type, then this is the short syntax
3290 // for the call, which means that RetType is just the return type. Infer the
3291 // rest of the function argument types from the arguments that are present.
3292 PointerType *PFTy = 0;
3293 FunctionType *Ty = 0;
3294 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3295 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3296 // Pull out the types of all of the arguments...
3297 std::vector<Type*> ParamTypes;
3298 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3299 ParamTypes.push_back(ArgList[i].V->getType());
3301 if (!FunctionType::isValidReturnType(RetType))
3302 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3304 Ty = FunctionType::get(RetType, ParamTypes, false);
3305 PFTy = PointerType::getUnqual(Ty);
3308 // Look up the callee.
3310 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3312 // Set up the Attributes for the function.
3313 SmallVector<AttributeWithIndex, 8> Attrs;
3314 if (RetAttrs.hasAttributes())
3316 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
3317 Attributes::get(Callee->getContext(),
3320 SmallVector<Value*, 8> Args;
3322 // Loop through FunctionType's arguments and ensure they are specified
3323 // correctly. Also, gather any parameter attributes.
3324 FunctionType::param_iterator I = Ty->param_begin();
3325 FunctionType::param_iterator E = Ty->param_end();
3326 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3327 Type *ExpectedTy = 0;
3330 } else if (!Ty->isVarArg()) {
3331 return Error(ArgList[i].Loc, "too many arguments specified");
3334 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3335 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3336 getTypeString(ExpectedTy) + "'");
3337 Args.push_back(ArgList[i].V);
3338 if (ArgList[i].Attrs.hasAttributes())
3339 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3343 return Error(CallLoc, "not enough parameters specified for call");
3345 if (FnAttrs.hasAttributes())
3347 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
3348 Attributes::get(Callee->getContext(),
3351 // Finish off the Attributes and check them
3352 AttrListPtr PAL = AttrListPtr::get(Attrs);
3354 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3355 II->setCallingConv(CC);
3356 II->setAttributes(PAL);
3362 /// ::= 'resume' TypeAndValue
3363 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3364 Value *Exn; LocTy ExnLoc;
3365 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3368 ResumeInst *RI = ResumeInst::Create(Exn);
3373 //===----------------------------------------------------------------------===//
3374 // Binary Operators.
3375 //===----------------------------------------------------------------------===//
3378 /// ::= ArithmeticOps TypeAndValue ',' Value
3380 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3381 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3382 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3383 unsigned Opc, unsigned OperandType) {
3384 LocTy Loc; Value *LHS, *RHS;
3385 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3386 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3387 ParseValue(LHS->getType(), RHS, PFS))
3391 switch (OperandType) {
3392 default: llvm_unreachable("Unknown operand type!");
3393 case 0: // int or FP.
3394 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3395 LHS->getType()->isFPOrFPVectorTy();
3397 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3398 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3402 return Error(Loc, "invalid operand type for instruction");
3404 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3409 /// ::= ArithmeticOps TypeAndValue ',' Value {
3410 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3412 LocTy Loc; Value *LHS, *RHS;
3413 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3414 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3415 ParseValue(LHS->getType(), RHS, PFS))
3418 if (!LHS->getType()->isIntOrIntVectorTy())
3419 return Error(Loc,"instruction requires integer or integer vector operands");
3421 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3427 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3428 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3429 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3431 // Parse the integer/fp comparison predicate.
3435 if (ParseCmpPredicate(Pred, Opc) ||
3436 ParseTypeAndValue(LHS, Loc, PFS) ||
3437 ParseToken(lltok::comma, "expected ',' after compare value") ||
3438 ParseValue(LHS->getType(), RHS, PFS))
3441 if (Opc == Instruction::FCmp) {
3442 if (!LHS->getType()->isFPOrFPVectorTy())
3443 return Error(Loc, "fcmp requires floating point operands");
3444 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3446 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3447 if (!LHS->getType()->isIntOrIntVectorTy() &&
3448 !LHS->getType()->getScalarType()->isPointerTy())
3449 return Error(Loc, "icmp requires integer operands");
3450 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3455 //===----------------------------------------------------------------------===//
3456 // Other Instructions.
3457 //===----------------------------------------------------------------------===//
3461 /// ::= CastOpc TypeAndValue 'to' Type
3462 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3467 if (ParseTypeAndValue(Op, Loc, PFS) ||
3468 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3472 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3473 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3474 return Error(Loc, "invalid cast opcode for cast from '" +
3475 getTypeString(Op->getType()) + "' to '" +
3476 getTypeString(DestTy) + "'");
3478 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3483 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3484 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3486 Value *Op0, *Op1, *Op2;
3487 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3488 ParseToken(lltok::comma, "expected ',' after select condition") ||
3489 ParseTypeAndValue(Op1, PFS) ||
3490 ParseToken(lltok::comma, "expected ',' after select value") ||
3491 ParseTypeAndValue(Op2, PFS))
3494 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3495 return Error(Loc, Reason);
3497 Inst = SelectInst::Create(Op0, Op1, Op2);
3502 /// ::= 'va_arg' TypeAndValue ',' Type
3503 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3507 if (ParseTypeAndValue(Op, PFS) ||
3508 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3509 ParseType(EltTy, TypeLoc))
3512 if (!EltTy->isFirstClassType())
3513 return Error(TypeLoc, "va_arg requires operand with first class type");
3515 Inst = new VAArgInst(Op, EltTy);
3519 /// ParseExtractElement
3520 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3521 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3524 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3525 ParseToken(lltok::comma, "expected ',' after extract value") ||
3526 ParseTypeAndValue(Op1, PFS))
3529 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3530 return Error(Loc, "invalid extractelement operands");
3532 Inst = ExtractElementInst::Create(Op0, Op1);
3536 /// ParseInsertElement
3537 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3538 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3540 Value *Op0, *Op1, *Op2;
3541 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3542 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3543 ParseTypeAndValue(Op1, PFS) ||
3544 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3545 ParseTypeAndValue(Op2, PFS))
3548 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3549 return Error(Loc, "invalid insertelement operands");
3551 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3555 /// ParseShuffleVector
3556 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3557 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3559 Value *Op0, *Op1, *Op2;
3560 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3561 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3562 ParseTypeAndValue(Op1, PFS) ||
3563 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3564 ParseTypeAndValue(Op2, PFS))
3567 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3568 return Error(Loc, "invalid shufflevector operands");
3570 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3575 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3576 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3577 Type *Ty = 0; LocTy TypeLoc;
3580 if (ParseType(Ty, TypeLoc) ||
3581 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3582 ParseValue(Ty, Op0, PFS) ||
3583 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3584 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3585 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3588 bool AteExtraComma = false;
3589 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3591 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3593 if (!EatIfPresent(lltok::comma))
3596 if (Lex.getKind() == lltok::MetadataVar) {
3597 AteExtraComma = true;
3601 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3602 ParseValue(Ty, Op0, PFS) ||
3603 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3604 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3605 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3609 if (!Ty->isFirstClassType())
3610 return Error(TypeLoc, "phi node must have first class type");
3612 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3613 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3614 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3616 return AteExtraComma ? InstExtraComma : InstNormal;
3620 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3622 /// ::= 'catch' TypeAndValue
3624 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3625 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3626 Type *Ty = 0; LocTy TyLoc;
3627 Value *PersFn; LocTy PersFnLoc;
3629 if (ParseType(Ty, TyLoc) ||
3630 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3631 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3634 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3635 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3637 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3638 LandingPadInst::ClauseType CT;
3639 if (EatIfPresent(lltok::kw_catch))
3640 CT = LandingPadInst::Catch;
3641 else if (EatIfPresent(lltok::kw_filter))
3642 CT = LandingPadInst::Filter;
3644 return TokError("expected 'catch' or 'filter' clause type");
3646 Value *V; LocTy VLoc;
3647 if (ParseTypeAndValue(V, VLoc, PFS)) {
3652 // A 'catch' type expects a non-array constant. A filter clause expects an
3654 if (CT == LandingPadInst::Catch) {
3655 if (isa<ArrayType>(V->getType()))
3656 Error(VLoc, "'catch' clause has an invalid type");
3658 if (!isa<ArrayType>(V->getType()))
3659 Error(VLoc, "'filter' clause has an invalid type");
3670 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3671 /// ParameterList OptionalAttrs
3672 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3674 AttrBuilder RetAttrs, FnAttrs;
3679 SmallVector<ParamInfo, 16> ArgList;
3680 LocTy CallLoc = Lex.getLoc();
3682 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3683 ParseOptionalCallingConv(CC) ||
3684 ParseOptionalAttrs(RetAttrs, 1) ||
3685 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3686 ParseValID(CalleeID) ||
3687 ParseParameterList(ArgList, PFS) ||
3688 ParseOptionalAttrs(FnAttrs, 2))
3691 // If RetType is a non-function pointer type, then this is the short syntax
3692 // for the call, which means that RetType is just the return type. Infer the
3693 // rest of the function argument types from the arguments that are present.
3694 PointerType *PFTy = 0;
3695 FunctionType *Ty = 0;
3696 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3697 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3698 // Pull out the types of all of the arguments...
3699 std::vector<Type*> ParamTypes;
3700 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3701 ParamTypes.push_back(ArgList[i].V->getType());
3703 if (!FunctionType::isValidReturnType(RetType))
3704 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3706 Ty = FunctionType::get(RetType, ParamTypes, false);
3707 PFTy = PointerType::getUnqual(Ty);
3710 // Look up the callee.
3712 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3714 // Set up the Attributes for the function.
3715 SmallVector<AttributeWithIndex, 8> Attrs;
3716 if (RetAttrs.hasAttributes())
3718 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
3719 Attributes::get(Callee->getContext(),
3722 SmallVector<Value*, 8> Args;
3724 // Loop through FunctionType's arguments and ensure they are specified
3725 // correctly. Also, gather any parameter attributes.
3726 FunctionType::param_iterator I = Ty->param_begin();
3727 FunctionType::param_iterator E = Ty->param_end();
3728 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3729 Type *ExpectedTy = 0;
3732 } else if (!Ty->isVarArg()) {
3733 return Error(ArgList[i].Loc, "too many arguments specified");
3736 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3737 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3738 getTypeString(ExpectedTy) + "'");
3739 Args.push_back(ArgList[i].V);
3740 if (ArgList[i].Attrs.hasAttributes())
3741 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3745 return Error(CallLoc, "not enough parameters specified for call");
3747 if (FnAttrs.hasAttributes())
3749 AttributeWithIndex::get(AttrListPtr::FunctionIndex,
3750 Attributes::get(Callee->getContext(),
3753 // Finish off the Attributes and check them
3754 AttrListPtr PAL = AttrListPtr::get(Attrs);
3756 CallInst *CI = CallInst::Create(Callee, Args);
3757 CI->setTailCall(isTail);
3758 CI->setCallingConv(CC);
3759 CI->setAttributes(PAL);
3764 //===----------------------------------------------------------------------===//
3765 // Memory Instructions.
3766 //===----------------------------------------------------------------------===//
3769 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3770 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3773 unsigned Alignment = 0;
3775 if (ParseType(Ty)) return true;
3777 bool AteExtraComma = false;
3778 if (EatIfPresent(lltok::comma)) {
3779 if (Lex.getKind() == lltok::kw_align) {
3780 if (ParseOptionalAlignment(Alignment)) return true;
3781 } else if (Lex.getKind() == lltok::MetadataVar) {
3782 AteExtraComma = true;
3784 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3785 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3790 if (Size && !Size->getType()->isIntegerTy())
3791 return Error(SizeLoc, "element count must have integer type");
3793 Inst = new AllocaInst(Ty, Size, Alignment);
3794 return AteExtraComma ? InstExtraComma : InstNormal;
3798 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3799 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3800 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3801 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
3802 Value *Val; LocTy Loc;
3803 unsigned Alignment = 0;
3804 bool AteExtraComma = false;
3805 bool isAtomic = false;
3806 AtomicOrdering Ordering = NotAtomic;
3807 SynchronizationScope Scope = CrossThread;
3809 if (Lex.getKind() == lltok::kw_atomic) {
3814 bool isVolatile = false;
3815 if (Lex.getKind() == lltok::kw_volatile) {
3820 if (ParseTypeAndValue(Val, Loc, PFS) ||
3821 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3822 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3825 if (!Val->getType()->isPointerTy() ||
3826 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3827 return Error(Loc, "load operand must be a pointer to a first class type");
3828 if (isAtomic && !Alignment)
3829 return Error(Loc, "atomic load must have explicit non-zero alignment");
3830 if (Ordering == Release || Ordering == AcquireRelease)
3831 return Error(Loc, "atomic load cannot use Release ordering");
3833 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
3834 return AteExtraComma ? InstExtraComma : InstNormal;
3839 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3840 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
3841 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3842 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
3843 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3844 unsigned Alignment = 0;
3845 bool AteExtraComma = false;
3846 bool isAtomic = false;
3847 AtomicOrdering Ordering = NotAtomic;
3848 SynchronizationScope Scope = CrossThread;
3850 if (Lex.getKind() == lltok::kw_atomic) {
3855 bool isVolatile = false;
3856 if (Lex.getKind() == lltok::kw_volatile) {
3861 if (ParseTypeAndValue(Val, Loc, PFS) ||
3862 ParseToken(lltok::comma, "expected ',' after store operand") ||
3863 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3864 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3865 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3868 if (!Ptr->getType()->isPointerTy())
3869 return Error(PtrLoc, "store operand must be a pointer");
3870 if (!Val->getType()->isFirstClassType())
3871 return Error(Loc, "store operand must be a first class value");
3872 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3873 return Error(Loc, "stored value and pointer type do not match");
3874 if (isAtomic && !Alignment)
3875 return Error(Loc, "atomic store must have explicit non-zero alignment");
3876 if (Ordering == Acquire || Ordering == AcquireRelease)
3877 return Error(Loc, "atomic store cannot use Acquire ordering");
3879 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
3880 return AteExtraComma ? InstExtraComma : InstNormal;
3884 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3885 /// 'singlethread'? AtomicOrdering
3886 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
3887 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3888 bool AteExtraComma = false;
3889 AtomicOrdering Ordering = NotAtomic;
3890 SynchronizationScope Scope = CrossThread;
3891 bool isVolatile = false;
3893 if (EatIfPresent(lltok::kw_volatile))
3896 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3897 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3898 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3899 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3900 ParseTypeAndValue(New, NewLoc, PFS) ||
3901 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3904 if (Ordering == Unordered)
3905 return TokError("cmpxchg cannot be unordered");
3906 if (!Ptr->getType()->isPointerTy())
3907 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3908 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3909 return Error(CmpLoc, "compare value and pointer type do not match");
3910 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3911 return Error(NewLoc, "new value and pointer type do not match");
3912 if (!New->getType()->isIntegerTy())
3913 return Error(NewLoc, "cmpxchg operand must be an integer");
3914 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3915 if (Size < 8 || (Size & (Size - 1)))
3916 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3919 AtomicCmpXchgInst *CXI =
3920 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3921 CXI->setVolatile(isVolatile);
3923 return AteExtraComma ? InstExtraComma : InstNormal;
3927 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3928 /// 'singlethread'? AtomicOrdering
3929 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
3930 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3931 bool AteExtraComma = false;
3932 AtomicOrdering Ordering = NotAtomic;
3933 SynchronizationScope Scope = CrossThread;
3934 bool isVolatile = false;
3935 AtomicRMWInst::BinOp Operation;
3937 if (EatIfPresent(lltok::kw_volatile))
3940 switch (Lex.getKind()) {
3941 default: return TokError("expected binary operation in atomicrmw");
3942 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3943 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3944 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3945 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3946 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3947 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3948 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3949 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3950 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3951 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3952 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3954 Lex.Lex(); // Eat the operation.
3956 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3957 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3958 ParseTypeAndValue(Val, ValLoc, PFS) ||
3959 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3962 if (Ordering == Unordered)
3963 return TokError("atomicrmw cannot be unordered");
3964 if (!Ptr->getType()->isPointerTy())
3965 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3966 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3967 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3968 if (!Val->getType()->isIntegerTy())
3969 return Error(ValLoc, "atomicrmw operand must be an integer");
3970 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3971 if (Size < 8 || (Size & (Size - 1)))
3972 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3975 AtomicRMWInst *RMWI =
3976 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3977 RMWI->setVolatile(isVolatile);
3979 return AteExtraComma ? InstExtraComma : InstNormal;
3983 /// ::= 'fence' 'singlethread'? AtomicOrdering
3984 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3985 AtomicOrdering Ordering = NotAtomic;
3986 SynchronizationScope Scope = CrossThread;
3987 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3990 if (Ordering == Unordered)
3991 return TokError("fence cannot be unordered");
3992 if (Ordering == Monotonic)
3993 return TokError("fence cannot be monotonic");
3995 Inst = new FenceInst(Context, Ordering, Scope);
3999 /// ParseGetElementPtr
4000 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4001 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4006 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4008 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4010 if (!Ptr->getType()->getScalarType()->isPointerTy())
4011 return Error(Loc, "base of getelementptr must be a pointer");
4013 SmallVector<Value*, 16> Indices;
4014 bool AteExtraComma = false;
4015 while (EatIfPresent(lltok::comma)) {
4016 if (Lex.getKind() == lltok::MetadataVar) {
4017 AteExtraComma = true;
4020 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4021 if (!Val->getType()->getScalarType()->isIntegerTy())
4022 return Error(EltLoc, "getelementptr index must be an integer");
4023 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4024 return Error(EltLoc, "getelementptr index type missmatch");
4025 if (Val->getType()->isVectorTy()) {
4026 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4027 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4028 if (ValNumEl != PtrNumEl)
4029 return Error(EltLoc,
4030 "getelementptr vector index has a wrong number of elements");
4032 Indices.push_back(Val);
4035 if (Val && Val->getType()->isVectorTy() && Indices.size() != 1)
4036 return Error(EltLoc, "vector getelementptrs must have a single index");
4038 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
4039 return Error(Loc, "invalid getelementptr indices");
4040 Inst = GetElementPtrInst::Create(Ptr, Indices);
4042 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4043 return AteExtraComma ? InstExtraComma : InstNormal;
4046 /// ParseExtractValue
4047 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4048 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4049 Value *Val; LocTy Loc;
4050 SmallVector<unsigned, 4> Indices;
4052 if (ParseTypeAndValue(Val, Loc, PFS) ||
4053 ParseIndexList(Indices, AteExtraComma))
4056 if (!Val->getType()->isAggregateType())
4057 return Error(Loc, "extractvalue operand must be aggregate type");
4059 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4060 return Error(Loc, "invalid indices for extractvalue");
4061 Inst = ExtractValueInst::Create(Val, Indices);
4062 return AteExtraComma ? InstExtraComma : InstNormal;
4065 /// ParseInsertValue
4066 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4067 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4068 Value *Val0, *Val1; LocTy Loc0, Loc1;
4069 SmallVector<unsigned, 4> Indices;
4071 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4072 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4073 ParseTypeAndValue(Val1, Loc1, PFS) ||
4074 ParseIndexList(Indices, AteExtraComma))
4077 if (!Val0->getType()->isAggregateType())
4078 return Error(Loc0, "insertvalue operand must be aggregate type");
4080 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4081 return Error(Loc0, "invalid indices for insertvalue");
4082 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4083 return AteExtraComma ? InstExtraComma : InstNormal;
4086 //===----------------------------------------------------------------------===//
4087 // Embedded metadata.
4088 //===----------------------------------------------------------------------===//
4090 /// ParseMDNodeVector
4091 /// ::= Element (',' Element)*
4093 /// ::= 'null' | TypeAndValue
4094 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4095 PerFunctionState *PFS) {
4096 // Check for an empty list.
4097 if (Lex.getKind() == lltok::rbrace)
4101 // Null is a special case since it is typeless.
4102 if (EatIfPresent(lltok::kw_null)) {
4108 if (ParseTypeAndValue(V, PFS)) return true;
4110 } while (EatIfPresent(lltok::comma));