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(Attributes &Attrs, unsigned AttrKind) {
920 Attrs = Attribute::None;
921 LocTy AttrLoc = Lex.getLoc();
922 bool HaveError = false;
925 lltok::Kind Token = Lex.getKind();
927 default: // End of attributes.
929 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
930 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
931 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
932 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
933 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
934 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
935 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
936 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
938 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
939 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
940 case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
941 case lltok::kw_returns_twice: Attrs |= Attribute::ReturnsTwice; break;
942 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
943 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
944 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
945 case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
946 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
947 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
948 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
949 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
950 case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
951 case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
952 case lltok::kw_naked: Attrs |= Attribute::Naked; break;
953 case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
954 case lltok::kw_address_safety: Attrs |= Attribute::AddressSafety; break;
956 case lltok::kw_alignstack: {
958 if (ParseOptionalStackAlignment(Alignment))
960 Attrs |= Attributes::constructStackAlignmentFromInt(Alignment);
964 case lltok::kw_align: {
966 if (ParseOptionalAlignment(Alignment))
968 Attrs |= Attributes::constructAlignmentFromInt(Alignment);
974 // Perform some error checking.
978 HaveError |= Error(AttrLoc, "invalid use of attribute on a function");
980 case lltok::kw_align:
981 // As a hack, we allow "align 2" on functions as a synonym for
987 case lltok::kw_nocapture:
988 case lltok::kw_byval:
991 HaveError |= Error(AttrLoc, "invalid use of parameter-only attribute");
995 case lltok::kw_noreturn:
996 case lltok::kw_nounwind:
997 case lltok::kw_readnone:
998 case lltok::kw_readonly:
999 case lltok::kw_noinline:
1000 case lltok::kw_alwaysinline:
1001 case lltok::kw_optsize:
1003 case lltok::kw_sspreq:
1004 case lltok::kw_noredzone:
1005 case lltok::kw_noimplicitfloat:
1006 case lltok::kw_naked:
1007 case lltok::kw_inlinehint:
1008 case lltok::kw_alignstack:
1009 case lltok::kw_uwtable:
1010 case lltok::kw_nonlazybind:
1011 case lltok::kw_returns_twice:
1012 case lltok::kw_address_safety:
1014 HaveError |= Error(AttrLoc, "invalid use of function-only attribute");
1022 /// ParseOptionalLinkage
1025 /// ::= 'linker_private'
1026 /// ::= 'linker_private_weak'
1031 /// ::= 'linkonce_odr'
1032 /// ::= 'linkonce_odr_auto_hide'
1033 /// ::= 'available_externally'
1038 /// ::= 'extern_weak'
1040 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1042 switch (Lex.getKind()) {
1043 default: Res=GlobalValue::ExternalLinkage; return false;
1044 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1045 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1046 case lltok::kw_linker_private_weak:
1047 Res = GlobalValue::LinkerPrivateWeakLinkage;
1049 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1050 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1051 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1052 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1053 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1054 case lltok::kw_linkonce_odr_auto_hide:
1055 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1056 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1058 case lltok::kw_available_externally:
1059 Res = GlobalValue::AvailableExternallyLinkage;
1061 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1062 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1063 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1064 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1065 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1066 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1073 /// ParseOptionalVisibility
1079 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1080 switch (Lex.getKind()) {
1081 default: Res = GlobalValue::DefaultVisibility; return false;
1082 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1083 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1084 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1090 /// ParseOptionalCallingConv
1095 /// ::= 'x86_stdcallcc'
1096 /// ::= 'x86_fastcallcc'
1097 /// ::= 'x86_thiscallcc'
1098 /// ::= 'arm_apcscc'
1099 /// ::= 'arm_aapcscc'
1100 /// ::= 'arm_aapcs_vfpcc'
1101 /// ::= 'msp430_intrcc'
1102 /// ::= 'ptx_kernel'
1103 /// ::= 'ptx_device'
1105 /// ::= 'spir_kernel'
1108 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1109 switch (Lex.getKind()) {
1110 default: CC = CallingConv::C; return false;
1111 case lltok::kw_ccc: CC = CallingConv::C; break;
1112 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1113 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1114 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1115 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1116 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1117 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1118 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1119 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1120 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1121 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1122 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1123 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1124 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1125 case lltok::kw_cc: {
1126 unsigned ArbitraryCC;
1128 if (ParseUInt32(ArbitraryCC))
1130 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1139 /// ParseInstructionMetadata
1140 /// ::= !dbg !42 (',' !dbg !57)*
1141 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1142 PerFunctionState *PFS) {
1144 if (Lex.getKind() != lltok::MetadataVar)
1145 return TokError("expected metadata after comma");
1147 std::string Name = Lex.getStrVal();
1148 unsigned MDK = M->getMDKindID(Name);
1152 SMLoc Loc = Lex.getLoc();
1154 if (ParseToken(lltok::exclaim, "expected '!' here"))
1157 // This code is similar to that of ParseMetadataValue, however it needs to
1158 // have special-case code for a forward reference; see the comments on
1159 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1160 // at the top level here.
1161 if (Lex.getKind() == lltok::lbrace) {
1163 if (ParseMetadataListValue(ID, PFS))
1165 assert(ID.Kind == ValID::t_MDNode);
1166 Inst->setMetadata(MDK, ID.MDNodeVal);
1168 unsigned NodeID = 0;
1169 if (ParseMDNodeID(Node, NodeID))
1172 // If we got the node, add it to the instruction.
1173 Inst->setMetadata(MDK, Node);
1175 MDRef R = { Loc, MDK, NodeID };
1176 // Otherwise, remember that this should be resolved later.
1177 ForwardRefInstMetadata[Inst].push_back(R);
1181 // If this is the end of the list, we're done.
1182 } while (EatIfPresent(lltok::comma));
1186 /// ParseOptionalAlignment
1189 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1191 if (!EatIfPresent(lltok::kw_align))
1193 LocTy AlignLoc = Lex.getLoc();
1194 if (ParseUInt32(Alignment)) return true;
1195 if (!isPowerOf2_32(Alignment))
1196 return Error(AlignLoc, "alignment is not a power of two");
1197 if (Alignment > Value::MaximumAlignment)
1198 return Error(AlignLoc, "huge alignments are not supported yet");
1202 /// ParseOptionalCommaAlign
1206 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1208 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1209 bool &AteExtraComma) {
1210 AteExtraComma = false;
1211 while (EatIfPresent(lltok::comma)) {
1212 // Metadata at the end is an early exit.
1213 if (Lex.getKind() == lltok::MetadataVar) {
1214 AteExtraComma = true;
1218 if (Lex.getKind() != lltok::kw_align)
1219 return Error(Lex.getLoc(), "expected metadata or 'align'");
1221 if (ParseOptionalAlignment(Alignment)) return true;
1227 /// ParseScopeAndOrdering
1228 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1231 /// This sets Scope and Ordering to the parsed values.
1232 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1233 AtomicOrdering &Ordering) {
1237 Scope = CrossThread;
1238 if (EatIfPresent(lltok::kw_singlethread))
1239 Scope = SingleThread;
1240 switch (Lex.getKind()) {
1241 default: return TokError("Expected ordering on atomic instruction");
1242 case lltok::kw_unordered: Ordering = Unordered; break;
1243 case lltok::kw_monotonic: Ordering = Monotonic; break;
1244 case lltok::kw_acquire: Ordering = Acquire; break;
1245 case lltok::kw_release: Ordering = Release; break;
1246 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1247 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1253 /// ParseOptionalStackAlignment
1255 /// ::= 'alignstack' '(' 4 ')'
1256 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1258 if (!EatIfPresent(lltok::kw_alignstack))
1260 LocTy ParenLoc = Lex.getLoc();
1261 if (!EatIfPresent(lltok::lparen))
1262 return Error(ParenLoc, "expected '('");
1263 LocTy AlignLoc = Lex.getLoc();
1264 if (ParseUInt32(Alignment)) return true;
1265 ParenLoc = Lex.getLoc();
1266 if (!EatIfPresent(lltok::rparen))
1267 return Error(ParenLoc, "expected ')'");
1268 if (!isPowerOf2_32(Alignment))
1269 return Error(AlignLoc, "stack alignment is not a power of two");
1273 /// ParseIndexList - This parses the index list for an insert/extractvalue
1274 /// instruction. This sets AteExtraComma in the case where we eat an extra
1275 /// comma at the end of the line and find that it is followed by metadata.
1276 /// Clients that don't allow metadata can call the version of this function that
1277 /// only takes one argument.
1280 /// ::= (',' uint32)+
1282 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1283 bool &AteExtraComma) {
1284 AteExtraComma = false;
1286 if (Lex.getKind() != lltok::comma)
1287 return TokError("expected ',' as start of index list");
1289 while (EatIfPresent(lltok::comma)) {
1290 if (Lex.getKind() == lltok::MetadataVar) {
1291 AteExtraComma = true;
1295 if (ParseUInt32(Idx)) return true;
1296 Indices.push_back(Idx);
1302 //===----------------------------------------------------------------------===//
1304 //===----------------------------------------------------------------------===//
1306 /// ParseType - Parse a type.
1307 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1308 SMLoc TypeLoc = Lex.getLoc();
1309 switch (Lex.getKind()) {
1311 return TokError("expected type");
1313 // Type ::= 'float' | 'void' (etc)
1314 Result = Lex.getTyVal();
1318 // Type ::= StructType
1319 if (ParseAnonStructType(Result, false))
1322 case lltok::lsquare:
1323 // Type ::= '[' ... ']'
1324 Lex.Lex(); // eat the lsquare.
1325 if (ParseArrayVectorType(Result, false))
1328 case lltok::less: // Either vector or packed struct.
1329 // Type ::= '<' ... '>'
1331 if (Lex.getKind() == lltok::lbrace) {
1332 if (ParseAnonStructType(Result, true) ||
1333 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1335 } else if (ParseArrayVectorType(Result, true))
1338 case lltok::LocalVar: {
1340 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1342 // If the type hasn't been defined yet, create a forward definition and
1343 // remember where that forward def'n was seen (in case it never is defined).
1344 if (Entry.first == 0) {
1345 Entry.first = StructType::create(Context, Lex.getStrVal());
1346 Entry.second = Lex.getLoc();
1348 Result = Entry.first;
1353 case lltok::LocalVarID: {
1355 if (Lex.getUIntVal() >= NumberedTypes.size())
1356 NumberedTypes.resize(Lex.getUIntVal()+1);
1357 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1359 // If the type hasn't been defined yet, create a forward definition and
1360 // remember where that forward def'n was seen (in case it never is defined).
1361 if (Entry.first == 0) {
1362 Entry.first = StructType::create(Context);
1363 Entry.second = Lex.getLoc();
1365 Result = Entry.first;
1371 // Parse the type suffixes.
1373 switch (Lex.getKind()) {
1376 if (!AllowVoid && Result->isVoidTy())
1377 return Error(TypeLoc, "void type only allowed for function results");
1380 // Type ::= Type '*'
1382 if (Result->isLabelTy())
1383 return TokError("basic block pointers are invalid");
1384 if (Result->isVoidTy())
1385 return TokError("pointers to void are invalid - use i8* instead");
1386 if (!PointerType::isValidElementType(Result))
1387 return TokError("pointer to this type is invalid");
1388 Result = PointerType::getUnqual(Result);
1392 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1393 case lltok::kw_addrspace: {
1394 if (Result->isLabelTy())
1395 return TokError("basic block pointers are invalid");
1396 if (Result->isVoidTy())
1397 return TokError("pointers to void are invalid; use i8* instead");
1398 if (!PointerType::isValidElementType(Result))
1399 return TokError("pointer to this type is invalid");
1401 if (ParseOptionalAddrSpace(AddrSpace) ||
1402 ParseToken(lltok::star, "expected '*' in address space"))
1405 Result = PointerType::get(Result, AddrSpace);
1409 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1411 if (ParseFunctionType(Result))
1418 /// ParseParameterList
1420 /// ::= '(' Arg (',' Arg)* ')'
1422 /// ::= Type OptionalAttributes Value OptionalAttributes
1423 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1424 PerFunctionState &PFS) {
1425 if (ParseToken(lltok::lparen, "expected '(' in call"))
1428 while (Lex.getKind() != lltok::rparen) {
1429 // If this isn't the first argument, we need a comma.
1430 if (!ArgList.empty() &&
1431 ParseToken(lltok::comma, "expected ',' in argument list"))
1434 // Parse the argument.
1437 Attributes ArgAttrs1;
1438 Attributes ArgAttrs2;
1440 if (ParseType(ArgTy, ArgLoc))
1443 // Otherwise, handle normal operands.
1444 if (ParseOptionalAttrs(ArgAttrs1, 0) || ParseValue(ArgTy, V, PFS))
1446 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1449 Lex.Lex(); // Lex the ')'.
1455 /// ParseArgumentList - Parse the argument list for a function type or function
1457 /// ::= '(' ArgTypeListI ')'
1461 /// ::= ArgTypeList ',' '...'
1462 /// ::= ArgType (',' ArgType)*
1464 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1467 assert(Lex.getKind() == lltok::lparen);
1468 Lex.Lex(); // eat the (.
1470 if (Lex.getKind() == lltok::rparen) {
1472 } else if (Lex.getKind() == lltok::dotdotdot) {
1476 LocTy TypeLoc = Lex.getLoc();
1481 if (ParseType(ArgTy) ||
1482 ParseOptionalAttrs(Attrs, 0)) return true;
1484 if (ArgTy->isVoidTy())
1485 return Error(TypeLoc, "argument can not have void type");
1487 if (Lex.getKind() == lltok::LocalVar) {
1488 Name = Lex.getStrVal();
1492 if (!FunctionType::isValidArgumentType(ArgTy))
1493 return Error(TypeLoc, "invalid type for function argument");
1495 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1497 while (EatIfPresent(lltok::comma)) {
1498 // Handle ... at end of arg list.
1499 if (EatIfPresent(lltok::dotdotdot)) {
1504 // Otherwise must be an argument type.
1505 TypeLoc = Lex.getLoc();
1506 if (ParseType(ArgTy) || ParseOptionalAttrs(Attrs, 0)) return true;
1508 if (ArgTy->isVoidTy())
1509 return Error(TypeLoc, "argument can not have void type");
1511 if (Lex.getKind() == lltok::LocalVar) {
1512 Name = Lex.getStrVal();
1518 if (!ArgTy->isFirstClassType())
1519 return Error(TypeLoc, "invalid type for function argument");
1521 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1525 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1528 /// ParseFunctionType
1529 /// ::= Type ArgumentList OptionalAttrs
1530 bool LLParser::ParseFunctionType(Type *&Result) {
1531 assert(Lex.getKind() == lltok::lparen);
1533 if (!FunctionType::isValidReturnType(Result))
1534 return TokError("invalid function return type");
1536 SmallVector<ArgInfo, 8> ArgList;
1538 if (ParseArgumentList(ArgList, isVarArg))
1541 // Reject names on the arguments lists.
1542 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1543 if (!ArgList[i].Name.empty())
1544 return Error(ArgList[i].Loc, "argument name invalid in function type");
1545 if (ArgList[i].Attrs)
1546 return Error(ArgList[i].Loc,
1547 "argument attributes invalid in function type");
1550 SmallVector<Type*, 16> ArgListTy;
1551 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1552 ArgListTy.push_back(ArgList[i].Ty);
1554 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1558 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1560 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1561 SmallVector<Type*, 8> Elts;
1562 if (ParseStructBody(Elts)) return true;
1564 Result = StructType::get(Context, Elts, Packed);
1568 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1569 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1570 std::pair<Type*, LocTy> &Entry,
1572 // If the type was already defined, diagnose the redefinition.
1573 if (Entry.first && !Entry.second.isValid())
1574 return Error(TypeLoc, "redefinition of type");
1576 // If we have opaque, just return without filling in the definition for the
1577 // struct. This counts as a definition as far as the .ll file goes.
1578 if (EatIfPresent(lltok::kw_opaque)) {
1579 // This type is being defined, so clear the location to indicate this.
1580 Entry.second = SMLoc();
1582 // If this type number has never been uttered, create it.
1583 if (Entry.first == 0)
1584 Entry.first = StructType::create(Context, Name);
1585 ResultTy = Entry.first;
1589 // If the type starts with '<', then it is either a packed struct or a vector.
1590 bool isPacked = EatIfPresent(lltok::less);
1592 // If we don't have a struct, then we have a random type alias, which we
1593 // accept for compatibility with old files. These types are not allowed to be
1594 // forward referenced and not allowed to be recursive.
1595 if (Lex.getKind() != lltok::lbrace) {
1597 return Error(TypeLoc, "forward references to non-struct type");
1601 return ParseArrayVectorType(ResultTy, true);
1602 return ParseType(ResultTy);
1605 // This type is being defined, so clear the location to indicate this.
1606 Entry.second = SMLoc();
1608 // If this type number has never been uttered, create it.
1609 if (Entry.first == 0)
1610 Entry.first = StructType::create(Context, Name);
1612 StructType *STy = cast<StructType>(Entry.first);
1614 SmallVector<Type*, 8> Body;
1615 if (ParseStructBody(Body) ||
1616 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1619 STy->setBody(Body, isPacked);
1625 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1628 /// ::= '{' Type (',' Type)* '}'
1629 /// ::= '<' '{' '}' '>'
1630 /// ::= '<' '{' Type (',' Type)* '}' '>'
1631 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1632 assert(Lex.getKind() == lltok::lbrace);
1633 Lex.Lex(); // Consume the '{'
1635 // Handle the empty struct.
1636 if (EatIfPresent(lltok::rbrace))
1639 LocTy EltTyLoc = Lex.getLoc();
1641 if (ParseType(Ty)) return true;
1644 if (!StructType::isValidElementType(Ty))
1645 return Error(EltTyLoc, "invalid element type for struct");
1647 while (EatIfPresent(lltok::comma)) {
1648 EltTyLoc = Lex.getLoc();
1649 if (ParseType(Ty)) return true;
1651 if (!StructType::isValidElementType(Ty))
1652 return Error(EltTyLoc, "invalid element type for struct");
1657 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1660 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1661 /// token has already been consumed.
1663 /// ::= '[' APSINTVAL 'x' Types ']'
1664 /// ::= '<' APSINTVAL 'x' Types '>'
1665 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1666 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1667 Lex.getAPSIntVal().getBitWidth() > 64)
1668 return TokError("expected number in address space");
1670 LocTy SizeLoc = Lex.getLoc();
1671 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1674 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1677 LocTy TypeLoc = Lex.getLoc();
1679 if (ParseType(EltTy)) return true;
1681 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1682 "expected end of sequential type"))
1687 return Error(SizeLoc, "zero element vector is illegal");
1688 if ((unsigned)Size != Size)
1689 return Error(SizeLoc, "size too large for vector");
1690 if (!VectorType::isValidElementType(EltTy))
1691 return Error(TypeLoc,
1692 "vector element type must be fp, integer or a pointer to these types");
1693 Result = VectorType::get(EltTy, unsigned(Size));
1695 if (!ArrayType::isValidElementType(EltTy))
1696 return Error(TypeLoc, "invalid array element type");
1697 Result = ArrayType::get(EltTy, Size);
1702 //===----------------------------------------------------------------------===//
1703 // Function Semantic Analysis.
1704 //===----------------------------------------------------------------------===//
1706 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1708 : P(p), F(f), FunctionNumber(functionNumber) {
1710 // Insert unnamed arguments into the NumberedVals list.
1711 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1714 NumberedVals.push_back(AI);
1717 LLParser::PerFunctionState::~PerFunctionState() {
1718 // If there were any forward referenced non-basicblock values, delete them.
1719 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1720 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1721 if (!isa<BasicBlock>(I->second.first)) {
1722 I->second.first->replaceAllUsesWith(
1723 UndefValue::get(I->second.first->getType()));
1724 delete I->second.first;
1725 I->second.first = 0;
1728 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1729 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.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;
1738 bool LLParser::PerFunctionState::FinishFunction() {
1739 // Check to see if someone took the address of labels in this block.
1740 if (!P.ForwardRefBlockAddresses.empty()) {
1742 if (!F.getName().empty()) {
1743 FunctionID.Kind = ValID::t_GlobalName;
1744 FunctionID.StrVal = F.getName();
1746 FunctionID.Kind = ValID::t_GlobalID;
1747 FunctionID.UIntVal = FunctionNumber;
1750 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1751 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1752 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1753 // Resolve all these references.
1754 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1757 P.ForwardRefBlockAddresses.erase(FRBAI);
1761 if (!ForwardRefVals.empty())
1762 return P.Error(ForwardRefVals.begin()->second.second,
1763 "use of undefined value '%" + ForwardRefVals.begin()->first +
1765 if (!ForwardRefValIDs.empty())
1766 return P.Error(ForwardRefValIDs.begin()->second.second,
1767 "use of undefined value '%" +
1768 Twine(ForwardRefValIDs.begin()->first) + "'");
1773 /// GetVal - Get a value with the specified name or ID, creating a
1774 /// forward reference record if needed. This can return null if the value
1775 /// exists but does not have the right type.
1776 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1777 Type *Ty, LocTy Loc) {
1778 // Look this name up in the normal function symbol table.
1779 Value *Val = F.getValueSymbolTable().lookup(Name);
1781 // If this is a forward reference for the value, see if we already created a
1782 // forward ref record.
1784 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1785 I = ForwardRefVals.find(Name);
1786 if (I != ForwardRefVals.end())
1787 Val = I->second.first;
1790 // If we have the value in the symbol table or fwd-ref table, return it.
1792 if (Val->getType() == Ty) return Val;
1793 if (Ty->isLabelTy())
1794 P.Error(Loc, "'%" + Name + "' is not a basic block");
1796 P.Error(Loc, "'%" + Name + "' defined with type '" +
1797 getTypeString(Val->getType()) + "'");
1801 // Don't make placeholders with invalid type.
1802 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1803 P.Error(Loc, "invalid use of a non-first-class type");
1807 // Otherwise, create a new forward reference for this value and remember it.
1809 if (Ty->isLabelTy())
1810 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
1812 FwdVal = new Argument(Ty, Name);
1814 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1818 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
1820 // Look this name up in the normal function symbol table.
1821 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1823 // If this is a forward reference for the value, see if we already created a
1824 // forward ref record.
1826 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1827 I = ForwardRefValIDs.find(ID);
1828 if (I != ForwardRefValIDs.end())
1829 Val = I->second.first;
1832 // If we have the value in the symbol table or fwd-ref table, return it.
1834 if (Val->getType() == Ty) return Val;
1835 if (Ty->isLabelTy())
1836 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
1838 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
1839 getTypeString(Val->getType()) + "'");
1843 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1844 P.Error(Loc, "invalid use of a non-first-class type");
1848 // Otherwise, create a new forward reference for this value and remember it.
1850 if (Ty->isLabelTy())
1851 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
1853 FwdVal = new Argument(Ty);
1855 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1859 /// SetInstName - After an instruction is parsed and inserted into its
1860 /// basic block, this installs its name.
1861 bool LLParser::PerFunctionState::SetInstName(int NameID,
1862 const std::string &NameStr,
1863 LocTy NameLoc, Instruction *Inst) {
1864 // If this instruction has void type, it cannot have a name or ID specified.
1865 if (Inst->getType()->isVoidTy()) {
1866 if (NameID != -1 || !NameStr.empty())
1867 return P.Error(NameLoc, "instructions returning void cannot have a name");
1871 // If this was a numbered instruction, verify that the instruction is the
1872 // expected value and resolve any forward references.
1873 if (NameStr.empty()) {
1874 // If neither a name nor an ID was specified, just use the next ID.
1876 NameID = NumberedVals.size();
1878 if (unsigned(NameID) != NumberedVals.size())
1879 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1880 Twine(NumberedVals.size()) + "'");
1882 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1883 ForwardRefValIDs.find(NameID);
1884 if (FI != ForwardRefValIDs.end()) {
1885 if (FI->second.first->getType() != Inst->getType())
1886 return P.Error(NameLoc, "instruction forward referenced with type '" +
1887 getTypeString(FI->second.first->getType()) + "'");
1888 FI->second.first->replaceAllUsesWith(Inst);
1889 delete FI->second.first;
1890 ForwardRefValIDs.erase(FI);
1893 NumberedVals.push_back(Inst);
1897 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1898 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1899 FI = ForwardRefVals.find(NameStr);
1900 if (FI != ForwardRefVals.end()) {
1901 if (FI->second.first->getType() != Inst->getType())
1902 return P.Error(NameLoc, "instruction forward referenced with type '" +
1903 getTypeString(FI->second.first->getType()) + "'");
1904 FI->second.first->replaceAllUsesWith(Inst);
1905 delete FI->second.first;
1906 ForwardRefVals.erase(FI);
1909 // Set the name on the instruction.
1910 Inst->setName(NameStr);
1912 if (Inst->getName() != NameStr)
1913 return P.Error(NameLoc, "multiple definition of local value named '" +
1918 /// GetBB - Get a basic block with the specified name or ID, creating a
1919 /// forward reference record if needed.
1920 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1922 return cast_or_null<BasicBlock>(GetVal(Name,
1923 Type::getLabelTy(F.getContext()), Loc));
1926 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1927 return cast_or_null<BasicBlock>(GetVal(ID,
1928 Type::getLabelTy(F.getContext()), Loc));
1931 /// DefineBB - Define the specified basic block, which is either named or
1932 /// unnamed. If there is an error, this returns null otherwise it returns
1933 /// the block being defined.
1934 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1938 BB = GetBB(NumberedVals.size(), Loc);
1940 BB = GetBB(Name, Loc);
1941 if (BB == 0) return 0; // Already diagnosed error.
1943 // Move the block to the end of the function. Forward ref'd blocks are
1944 // inserted wherever they happen to be referenced.
1945 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1947 // Remove the block from forward ref sets.
1949 ForwardRefValIDs.erase(NumberedVals.size());
1950 NumberedVals.push_back(BB);
1952 // BB forward references are already in the function symbol table.
1953 ForwardRefVals.erase(Name);
1959 //===----------------------------------------------------------------------===//
1961 //===----------------------------------------------------------------------===//
1963 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1964 /// type implied. For example, if we parse "4" we don't know what integer type
1965 /// it has. The value will later be combined with its type and checked for
1966 /// sanity. PFS is used to convert function-local operands of metadata (since
1967 /// metadata operands are not just parsed here but also converted to values).
1968 /// PFS can be null when we are not parsing metadata values inside a function.
1969 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
1970 ID.Loc = Lex.getLoc();
1971 switch (Lex.getKind()) {
1972 default: return TokError("expected value token");
1973 case lltok::GlobalID: // @42
1974 ID.UIntVal = Lex.getUIntVal();
1975 ID.Kind = ValID::t_GlobalID;
1977 case lltok::GlobalVar: // @foo
1978 ID.StrVal = Lex.getStrVal();
1979 ID.Kind = ValID::t_GlobalName;
1981 case lltok::LocalVarID: // %42
1982 ID.UIntVal = Lex.getUIntVal();
1983 ID.Kind = ValID::t_LocalID;
1985 case lltok::LocalVar: // %foo
1986 ID.StrVal = Lex.getStrVal();
1987 ID.Kind = ValID::t_LocalName;
1989 case lltok::exclaim: // !42, !{...}, or !"foo"
1990 return ParseMetadataValue(ID, PFS);
1992 ID.APSIntVal = Lex.getAPSIntVal();
1993 ID.Kind = ValID::t_APSInt;
1995 case lltok::APFloat:
1996 ID.APFloatVal = Lex.getAPFloatVal();
1997 ID.Kind = ValID::t_APFloat;
1999 case lltok::kw_true:
2000 ID.ConstantVal = ConstantInt::getTrue(Context);
2001 ID.Kind = ValID::t_Constant;
2003 case lltok::kw_false:
2004 ID.ConstantVal = ConstantInt::getFalse(Context);
2005 ID.Kind = ValID::t_Constant;
2007 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2008 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2009 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2011 case lltok::lbrace: {
2012 // ValID ::= '{' ConstVector '}'
2014 SmallVector<Constant*, 16> Elts;
2015 if (ParseGlobalValueVector(Elts) ||
2016 ParseToken(lltok::rbrace, "expected end of struct constant"))
2019 ID.ConstantStructElts = new Constant*[Elts.size()];
2020 ID.UIntVal = Elts.size();
2021 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2022 ID.Kind = ValID::t_ConstantStruct;
2026 // ValID ::= '<' ConstVector '>' --> Vector.
2027 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2029 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2031 SmallVector<Constant*, 16> Elts;
2032 LocTy FirstEltLoc = Lex.getLoc();
2033 if (ParseGlobalValueVector(Elts) ||
2035 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2036 ParseToken(lltok::greater, "expected end of constant"))
2039 if (isPackedStruct) {
2040 ID.ConstantStructElts = new Constant*[Elts.size()];
2041 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2042 ID.UIntVal = Elts.size();
2043 ID.Kind = ValID::t_PackedConstantStruct;
2048 return Error(ID.Loc, "constant vector must not be empty");
2050 if (!Elts[0]->getType()->isIntegerTy() &&
2051 !Elts[0]->getType()->isFloatingPointTy() &&
2052 !Elts[0]->getType()->isPointerTy())
2053 return Error(FirstEltLoc,
2054 "vector elements must have integer, pointer or floating point type");
2056 // Verify that all the vector elements have the same type.
2057 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2058 if (Elts[i]->getType() != Elts[0]->getType())
2059 return Error(FirstEltLoc,
2060 "vector element #" + Twine(i) +
2061 " is not of type '" + getTypeString(Elts[0]->getType()));
2063 ID.ConstantVal = ConstantVector::get(Elts);
2064 ID.Kind = ValID::t_Constant;
2067 case lltok::lsquare: { // Array Constant
2069 SmallVector<Constant*, 16> Elts;
2070 LocTy FirstEltLoc = Lex.getLoc();
2071 if (ParseGlobalValueVector(Elts) ||
2072 ParseToken(lltok::rsquare, "expected end of array constant"))
2075 // Handle empty element.
2077 // Use undef instead of an array because it's inconvenient to determine
2078 // the element type at this point, there being no elements to examine.
2079 ID.Kind = ValID::t_EmptyArray;
2083 if (!Elts[0]->getType()->isFirstClassType())
2084 return Error(FirstEltLoc, "invalid array element type: " +
2085 getTypeString(Elts[0]->getType()));
2087 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2089 // Verify all elements are correct type!
2090 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2091 if (Elts[i]->getType() != Elts[0]->getType())
2092 return Error(FirstEltLoc,
2093 "array element #" + Twine(i) +
2094 " is not of type '" + getTypeString(Elts[0]->getType()));
2097 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2098 ID.Kind = ValID::t_Constant;
2101 case lltok::kw_c: // c "foo"
2103 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2105 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2106 ID.Kind = ValID::t_Constant;
2109 case lltok::kw_asm: {
2110 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2111 bool HasSideEffect, AlignStack, AsmDialect;
2113 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2114 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2115 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2116 ParseStringConstant(ID.StrVal) ||
2117 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2118 ParseToken(lltok::StringConstant, "expected constraint string"))
2120 ID.StrVal2 = Lex.getStrVal();
2121 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2122 (unsigned(AsmDialect)<<2);
2123 ID.Kind = ValID::t_InlineAsm;
2127 case lltok::kw_blockaddress: {
2128 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2132 LocTy FnLoc, LabelLoc;
2134 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2136 ParseToken(lltok::comma, "expected comma in block address expression")||
2137 ParseValID(Label) ||
2138 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2141 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2142 return Error(Fn.Loc, "expected function name in blockaddress");
2143 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2144 return Error(Label.Loc, "expected basic block name in blockaddress");
2146 // Make a global variable as a placeholder for this reference.
2147 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2148 false, GlobalValue::InternalLinkage,
2150 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2151 ID.ConstantVal = FwdRef;
2152 ID.Kind = ValID::t_Constant;
2156 case lltok::kw_trunc:
2157 case lltok::kw_zext:
2158 case lltok::kw_sext:
2159 case lltok::kw_fptrunc:
2160 case lltok::kw_fpext:
2161 case lltok::kw_bitcast:
2162 case lltok::kw_uitofp:
2163 case lltok::kw_sitofp:
2164 case lltok::kw_fptoui:
2165 case lltok::kw_fptosi:
2166 case lltok::kw_inttoptr:
2167 case lltok::kw_ptrtoint: {
2168 unsigned Opc = Lex.getUIntVal();
2172 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2173 ParseGlobalTypeAndValue(SrcVal) ||
2174 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2175 ParseType(DestTy) ||
2176 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2178 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2179 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2180 getTypeString(SrcVal->getType()) + "' to '" +
2181 getTypeString(DestTy) + "'");
2182 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2184 ID.Kind = ValID::t_Constant;
2187 case lltok::kw_extractvalue: {
2190 SmallVector<unsigned, 4> Indices;
2191 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2192 ParseGlobalTypeAndValue(Val) ||
2193 ParseIndexList(Indices) ||
2194 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2197 if (!Val->getType()->isAggregateType())
2198 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2199 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2200 return Error(ID.Loc, "invalid indices for extractvalue");
2201 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2202 ID.Kind = ValID::t_Constant;
2205 case lltok::kw_insertvalue: {
2207 Constant *Val0, *Val1;
2208 SmallVector<unsigned, 4> Indices;
2209 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2210 ParseGlobalTypeAndValue(Val0) ||
2211 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2212 ParseGlobalTypeAndValue(Val1) ||
2213 ParseIndexList(Indices) ||
2214 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2216 if (!Val0->getType()->isAggregateType())
2217 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2218 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2219 return Error(ID.Loc, "invalid indices for insertvalue");
2220 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2221 ID.Kind = ValID::t_Constant;
2224 case lltok::kw_icmp:
2225 case lltok::kw_fcmp: {
2226 unsigned PredVal, Opc = Lex.getUIntVal();
2227 Constant *Val0, *Val1;
2229 if (ParseCmpPredicate(PredVal, Opc) ||
2230 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2231 ParseGlobalTypeAndValue(Val0) ||
2232 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2233 ParseGlobalTypeAndValue(Val1) ||
2234 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2237 if (Val0->getType() != Val1->getType())
2238 return Error(ID.Loc, "compare operands must have the same type");
2240 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2242 if (Opc == Instruction::FCmp) {
2243 if (!Val0->getType()->isFPOrFPVectorTy())
2244 return Error(ID.Loc, "fcmp requires floating point operands");
2245 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2247 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2248 if (!Val0->getType()->isIntOrIntVectorTy() &&
2249 !Val0->getType()->getScalarType()->isPointerTy())
2250 return Error(ID.Loc, "icmp requires pointer or integer operands");
2251 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2253 ID.Kind = ValID::t_Constant;
2257 // Binary Operators.
2259 case lltok::kw_fadd:
2261 case lltok::kw_fsub:
2263 case lltok::kw_fmul:
2264 case lltok::kw_udiv:
2265 case lltok::kw_sdiv:
2266 case lltok::kw_fdiv:
2267 case lltok::kw_urem:
2268 case lltok::kw_srem:
2269 case lltok::kw_frem:
2271 case lltok::kw_lshr:
2272 case lltok::kw_ashr: {
2276 unsigned Opc = Lex.getUIntVal();
2277 Constant *Val0, *Val1;
2279 LocTy ModifierLoc = Lex.getLoc();
2280 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2281 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2282 if (EatIfPresent(lltok::kw_nuw))
2284 if (EatIfPresent(lltok::kw_nsw)) {
2286 if (EatIfPresent(lltok::kw_nuw))
2289 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2290 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2291 if (EatIfPresent(lltok::kw_exact))
2294 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2295 ParseGlobalTypeAndValue(Val0) ||
2296 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2297 ParseGlobalTypeAndValue(Val1) ||
2298 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2300 if (Val0->getType() != Val1->getType())
2301 return Error(ID.Loc, "operands of constexpr must have same type");
2302 if (!Val0->getType()->isIntOrIntVectorTy()) {
2304 return Error(ModifierLoc, "nuw only applies to integer operations");
2306 return Error(ModifierLoc, "nsw only applies to integer operations");
2308 // Check that the type is valid for the operator.
2310 case Instruction::Add:
2311 case Instruction::Sub:
2312 case Instruction::Mul:
2313 case Instruction::UDiv:
2314 case Instruction::SDiv:
2315 case Instruction::URem:
2316 case Instruction::SRem:
2317 case Instruction::Shl:
2318 case Instruction::AShr:
2319 case Instruction::LShr:
2320 if (!Val0->getType()->isIntOrIntVectorTy())
2321 return Error(ID.Loc, "constexpr requires integer operands");
2323 case Instruction::FAdd:
2324 case Instruction::FSub:
2325 case Instruction::FMul:
2326 case Instruction::FDiv:
2327 case Instruction::FRem:
2328 if (!Val0->getType()->isFPOrFPVectorTy())
2329 return Error(ID.Loc, "constexpr requires fp operands");
2331 default: llvm_unreachable("Unknown binary operator!");
2334 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2335 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2336 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2337 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2339 ID.Kind = ValID::t_Constant;
2343 // Logical Operations
2346 case lltok::kw_xor: {
2347 unsigned Opc = Lex.getUIntVal();
2348 Constant *Val0, *Val1;
2350 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2351 ParseGlobalTypeAndValue(Val0) ||
2352 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2353 ParseGlobalTypeAndValue(Val1) ||
2354 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2356 if (Val0->getType() != Val1->getType())
2357 return Error(ID.Loc, "operands of constexpr must have same type");
2358 if (!Val0->getType()->isIntOrIntVectorTy())
2359 return Error(ID.Loc,
2360 "constexpr requires integer or integer vector operands");
2361 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2362 ID.Kind = ValID::t_Constant;
2366 case lltok::kw_getelementptr:
2367 case lltok::kw_shufflevector:
2368 case lltok::kw_insertelement:
2369 case lltok::kw_extractelement:
2370 case lltok::kw_select: {
2371 unsigned Opc = Lex.getUIntVal();
2372 SmallVector<Constant*, 16> Elts;
2373 bool InBounds = false;
2375 if (Opc == Instruction::GetElementPtr)
2376 InBounds = EatIfPresent(lltok::kw_inbounds);
2377 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2378 ParseGlobalValueVector(Elts) ||
2379 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2382 if (Opc == Instruction::GetElementPtr) {
2383 if (Elts.size() == 0 ||
2384 !Elts[0]->getType()->getScalarType()->isPointerTy())
2385 return Error(ID.Loc, "getelementptr requires pointer operand");
2387 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2388 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2389 return Error(ID.Loc, "invalid indices for getelementptr");
2390 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2392 } else if (Opc == Instruction::Select) {
2393 if (Elts.size() != 3)
2394 return Error(ID.Loc, "expected three operands to select");
2395 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2397 return Error(ID.Loc, Reason);
2398 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2399 } else if (Opc == Instruction::ShuffleVector) {
2400 if (Elts.size() != 3)
2401 return Error(ID.Loc, "expected three operands to shufflevector");
2402 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2403 return Error(ID.Loc, "invalid operands to shufflevector");
2405 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2406 } else if (Opc == Instruction::ExtractElement) {
2407 if (Elts.size() != 2)
2408 return Error(ID.Loc, "expected two operands to extractelement");
2409 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2410 return Error(ID.Loc, "invalid extractelement operands");
2411 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2413 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2414 if (Elts.size() != 3)
2415 return Error(ID.Loc, "expected three operands to insertelement");
2416 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2417 return Error(ID.Loc, "invalid insertelement operands");
2419 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2422 ID.Kind = ValID::t_Constant;
2431 /// ParseGlobalValue - Parse a global value with the specified type.
2432 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2436 bool Parsed = ParseValID(ID) ||
2437 ConvertValIDToValue(Ty, ID, V, NULL);
2438 if (V && !(C = dyn_cast<Constant>(V)))
2439 return Error(ID.Loc, "global values must be constants");
2443 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2445 return ParseType(Ty) ||
2446 ParseGlobalValue(Ty, V);
2449 /// ParseGlobalValueVector
2451 /// ::= TypeAndValue (',' TypeAndValue)*
2452 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2454 if (Lex.getKind() == lltok::rbrace ||
2455 Lex.getKind() == lltok::rsquare ||
2456 Lex.getKind() == lltok::greater ||
2457 Lex.getKind() == lltok::rparen)
2461 if (ParseGlobalTypeAndValue(C)) return true;
2464 while (EatIfPresent(lltok::comma)) {
2465 if (ParseGlobalTypeAndValue(C)) return true;
2472 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2473 assert(Lex.getKind() == lltok::lbrace);
2476 SmallVector<Value*, 16> Elts;
2477 if (ParseMDNodeVector(Elts, PFS) ||
2478 ParseToken(lltok::rbrace, "expected end of metadata node"))
2481 ID.MDNodeVal = MDNode::get(Context, Elts);
2482 ID.Kind = ValID::t_MDNode;
2486 /// ParseMetadataValue
2490 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2491 assert(Lex.getKind() == lltok::exclaim);
2496 if (Lex.getKind() == lltok::lbrace)
2497 return ParseMetadataListValue(ID, PFS);
2499 // Standalone metadata reference
2501 if (Lex.getKind() == lltok::APSInt) {
2502 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2503 ID.Kind = ValID::t_MDNode;
2508 // ::= '!' STRINGCONSTANT
2509 if (ParseMDString(ID.MDStringVal)) return true;
2510 ID.Kind = ValID::t_MDString;
2515 //===----------------------------------------------------------------------===//
2516 // Function Parsing.
2517 //===----------------------------------------------------------------------===//
2519 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2520 PerFunctionState *PFS) {
2521 if (Ty->isFunctionTy())
2522 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2525 case ValID::t_LocalID:
2526 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2527 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2529 case ValID::t_LocalName:
2530 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2531 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2533 case ValID::t_InlineAsm: {
2534 PointerType *PTy = dyn_cast<PointerType>(Ty);
2536 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2537 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2538 return Error(ID.Loc, "invalid type for inline asm constraint string");
2539 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2540 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2543 case ValID::t_MDNode:
2544 if (!Ty->isMetadataTy())
2545 return Error(ID.Loc, "metadata value must have metadata type");
2548 case ValID::t_MDString:
2549 if (!Ty->isMetadataTy())
2550 return Error(ID.Loc, "metadata value must have metadata type");
2553 case ValID::t_GlobalName:
2554 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2556 case ValID::t_GlobalID:
2557 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2559 case ValID::t_APSInt:
2560 if (!Ty->isIntegerTy())
2561 return Error(ID.Loc, "integer constant must have integer type");
2562 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2563 V = ConstantInt::get(Context, ID.APSIntVal);
2565 case ValID::t_APFloat:
2566 if (!Ty->isFloatingPointTy() ||
2567 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2568 return Error(ID.Loc, "floating point constant invalid for type");
2570 // The lexer has no type info, so builds all half, float, and double FP
2571 // constants as double. Fix this here. Long double does not need this.
2572 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2575 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2577 else if (Ty->isFloatTy())
2578 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2581 V = ConstantFP::get(Context, ID.APFloatVal);
2583 if (V->getType() != Ty)
2584 return Error(ID.Loc, "floating point constant does not have type '" +
2585 getTypeString(Ty) + "'");
2589 if (!Ty->isPointerTy())
2590 return Error(ID.Loc, "null must be a pointer type");
2591 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2593 case ValID::t_Undef:
2594 // FIXME: LabelTy should not be a first-class type.
2595 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2596 return Error(ID.Loc, "invalid type for undef constant");
2597 V = UndefValue::get(Ty);
2599 case ValID::t_EmptyArray:
2600 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2601 return Error(ID.Loc, "invalid empty array initializer");
2602 V = UndefValue::get(Ty);
2605 // FIXME: LabelTy should not be a first-class type.
2606 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2607 return Error(ID.Loc, "invalid type for null constant");
2608 V = Constant::getNullValue(Ty);
2610 case ValID::t_Constant:
2611 if (ID.ConstantVal->getType() != Ty)
2612 return Error(ID.Loc, "constant expression type mismatch");
2616 case ValID::t_ConstantStruct:
2617 case ValID::t_PackedConstantStruct:
2618 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2619 if (ST->getNumElements() != ID.UIntVal)
2620 return Error(ID.Loc,
2621 "initializer with struct type has wrong # elements");
2622 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2623 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2625 // Verify that the elements are compatible with the structtype.
2626 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2627 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2628 return Error(ID.Loc, "element " + Twine(i) +
2629 " of struct initializer doesn't match struct element type");
2631 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2634 return Error(ID.Loc, "constant expression type mismatch");
2637 llvm_unreachable("Invalid ValID");
2640 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2643 return ParseValID(ID, PFS) ||
2644 ConvertValIDToValue(Ty, ID, V, PFS);
2647 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2649 return ParseType(Ty) ||
2650 ParseValue(Ty, V, PFS);
2653 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2654 PerFunctionState &PFS) {
2657 if (ParseTypeAndValue(V, PFS)) return true;
2658 if (!isa<BasicBlock>(V))
2659 return Error(Loc, "expected a basic block");
2660 BB = cast<BasicBlock>(V);
2666 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2667 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2668 /// OptionalAlign OptGC
2669 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2670 // Parse the linkage.
2671 LocTy LinkageLoc = Lex.getLoc();
2674 unsigned Visibility;
2675 Attributes RetAttrs;
2678 LocTy RetTypeLoc = Lex.getLoc();
2679 if (ParseOptionalLinkage(Linkage) ||
2680 ParseOptionalVisibility(Visibility) ||
2681 ParseOptionalCallingConv(CC) ||
2682 ParseOptionalAttrs(RetAttrs, 1) ||
2683 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2686 // Verify that the linkage is ok.
2687 switch ((GlobalValue::LinkageTypes)Linkage) {
2688 case GlobalValue::ExternalLinkage:
2689 break; // always ok.
2690 case GlobalValue::DLLImportLinkage:
2691 case GlobalValue::ExternalWeakLinkage:
2693 return Error(LinkageLoc, "invalid linkage for function definition");
2695 case GlobalValue::PrivateLinkage:
2696 case GlobalValue::LinkerPrivateLinkage:
2697 case GlobalValue::LinkerPrivateWeakLinkage:
2698 case GlobalValue::InternalLinkage:
2699 case GlobalValue::AvailableExternallyLinkage:
2700 case GlobalValue::LinkOnceAnyLinkage:
2701 case GlobalValue::LinkOnceODRLinkage:
2702 case GlobalValue::LinkOnceODRAutoHideLinkage:
2703 case GlobalValue::WeakAnyLinkage:
2704 case GlobalValue::WeakODRLinkage:
2705 case GlobalValue::DLLExportLinkage:
2707 return Error(LinkageLoc, "invalid linkage for function declaration");
2709 case GlobalValue::AppendingLinkage:
2710 case GlobalValue::CommonLinkage:
2711 return Error(LinkageLoc, "invalid function linkage type");
2714 if (!FunctionType::isValidReturnType(RetType))
2715 return Error(RetTypeLoc, "invalid function return type");
2717 LocTy NameLoc = Lex.getLoc();
2719 std::string FunctionName;
2720 if (Lex.getKind() == lltok::GlobalVar) {
2721 FunctionName = Lex.getStrVal();
2722 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2723 unsigned NameID = Lex.getUIntVal();
2725 if (NameID != NumberedVals.size())
2726 return TokError("function expected to be numbered '%" +
2727 Twine(NumberedVals.size()) + "'");
2729 return TokError("expected function name");
2734 if (Lex.getKind() != lltok::lparen)
2735 return TokError("expected '(' in function argument list");
2737 SmallVector<ArgInfo, 8> ArgList;
2739 Attributes FuncAttrs;
2740 std::string Section;
2744 LocTy UnnamedAddrLoc;
2746 if (ParseArgumentList(ArgList, isVarArg) ||
2747 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2749 ParseOptionalAttrs(FuncAttrs, 2) ||
2750 (EatIfPresent(lltok::kw_section) &&
2751 ParseStringConstant(Section)) ||
2752 ParseOptionalAlignment(Alignment) ||
2753 (EatIfPresent(lltok::kw_gc) &&
2754 ParseStringConstant(GC)))
2757 // If the alignment was parsed as an attribute, move to the alignment field.
2758 if (FuncAttrs & Attribute::Alignment) {
2759 Alignment = FuncAttrs.getAlignment();
2760 FuncAttrs &= ~Attribute::Alignment;
2763 // Okay, if we got here, the function is syntactically valid. Convert types
2764 // and do semantic checks.
2765 std::vector<Type*> ParamTypeList;
2766 SmallVector<AttributeWithIndex, 8> Attrs;
2768 if (RetAttrs.hasAttributes())
2769 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2771 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2772 ParamTypeList.push_back(ArgList[i].Ty);
2773 if (ArgList[i].Attrs.hasAttributes())
2774 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2777 if (FuncAttrs.hasAttributes())
2778 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2780 AttrListPtr PAL = AttrListPtr::get(Attrs);
2782 if (PAL.paramHasAttr(1, Attribute::StructRet) && !RetType->isVoidTy())
2783 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2786 FunctionType::get(RetType, ParamTypeList, isVarArg);
2787 PointerType *PFT = PointerType::getUnqual(FT);
2790 if (!FunctionName.empty()) {
2791 // If this was a definition of a forward reference, remove the definition
2792 // from the forward reference table and fill in the forward ref.
2793 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2794 ForwardRefVals.find(FunctionName);
2795 if (FRVI != ForwardRefVals.end()) {
2796 Fn = M->getFunction(FunctionName);
2797 if (Fn->getType() != PFT)
2798 return Error(FRVI->second.second, "invalid forward reference to "
2799 "function '" + FunctionName + "' with wrong type!");
2801 ForwardRefVals.erase(FRVI);
2802 } else if ((Fn = M->getFunction(FunctionName))) {
2803 // Reject redefinitions.
2804 return Error(NameLoc, "invalid redefinition of function '" +
2805 FunctionName + "'");
2806 } else if (M->getNamedValue(FunctionName)) {
2807 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
2811 // If this is a definition of a forward referenced function, make sure the
2813 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2814 = ForwardRefValIDs.find(NumberedVals.size());
2815 if (I != ForwardRefValIDs.end()) {
2816 Fn = cast<Function>(I->second.first);
2817 if (Fn->getType() != PFT)
2818 return Error(NameLoc, "type of definition and forward reference of '@" +
2819 Twine(NumberedVals.size()) + "' disagree");
2820 ForwardRefValIDs.erase(I);
2825 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2826 else // Move the forward-reference to the correct spot in the module.
2827 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2829 if (FunctionName.empty())
2830 NumberedVals.push_back(Fn);
2832 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2833 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2834 Fn->setCallingConv(CC);
2835 Fn->setAttributes(PAL);
2836 Fn->setUnnamedAddr(UnnamedAddr);
2837 Fn->setAlignment(Alignment);
2838 Fn->setSection(Section);
2839 if (!GC.empty()) Fn->setGC(GC.c_str());
2841 // Add all of the arguments we parsed to the function.
2842 Function::arg_iterator ArgIt = Fn->arg_begin();
2843 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2844 // If the argument has a name, insert it into the argument symbol table.
2845 if (ArgList[i].Name.empty()) continue;
2847 // Set the name, if it conflicted, it will be auto-renamed.
2848 ArgIt->setName(ArgList[i].Name);
2850 if (ArgIt->getName() != ArgList[i].Name)
2851 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2852 ArgList[i].Name + "'");
2859 /// ParseFunctionBody
2860 /// ::= '{' BasicBlock+ '}'
2862 bool LLParser::ParseFunctionBody(Function &Fn) {
2863 if (Lex.getKind() != lltok::lbrace)
2864 return TokError("expected '{' in function body");
2865 Lex.Lex(); // eat the {.
2867 int FunctionNumber = -1;
2868 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
2870 PerFunctionState PFS(*this, Fn, FunctionNumber);
2872 // We need at least one basic block.
2873 if (Lex.getKind() == lltok::rbrace)
2874 return TokError("function body requires at least one basic block");
2876 while (Lex.getKind() != lltok::rbrace)
2877 if (ParseBasicBlock(PFS)) return true;
2882 // Verify function is ok.
2883 return PFS.FinishFunction();
2887 /// ::= LabelStr? Instruction*
2888 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2889 // If this basic block starts out with a name, remember it.
2891 LocTy NameLoc = Lex.getLoc();
2892 if (Lex.getKind() == lltok::LabelStr) {
2893 Name = Lex.getStrVal();
2897 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2898 if (BB == 0) return true;
2900 std::string NameStr;
2902 // Parse the instructions in this block until we get a terminator.
2904 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
2906 // This instruction may have three possibilities for a name: a) none
2907 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2908 LocTy NameLoc = Lex.getLoc();
2912 if (Lex.getKind() == lltok::LocalVarID) {
2913 NameID = Lex.getUIntVal();
2915 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2917 } else if (Lex.getKind() == lltok::LocalVar) {
2918 NameStr = Lex.getStrVal();
2920 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2924 switch (ParseInstruction(Inst, BB, PFS)) {
2925 default: llvm_unreachable("Unknown ParseInstruction result!");
2926 case InstError: return true;
2928 BB->getInstList().push_back(Inst);
2930 // With a normal result, we check to see if the instruction is followed by
2931 // a comma and metadata.
2932 if (EatIfPresent(lltok::comma))
2933 if (ParseInstructionMetadata(Inst, &PFS))
2936 case InstExtraComma:
2937 BB->getInstList().push_back(Inst);
2939 // If the instruction parser ate an extra comma at the end of it, it
2940 // *must* be followed by metadata.
2941 if (ParseInstructionMetadata(Inst, &PFS))
2946 // Set the name on the instruction.
2947 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2948 } while (!isa<TerminatorInst>(Inst));
2953 //===----------------------------------------------------------------------===//
2954 // Instruction Parsing.
2955 //===----------------------------------------------------------------------===//
2957 /// ParseInstruction - Parse one of the many different instructions.
2959 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2960 PerFunctionState &PFS) {
2961 lltok::Kind Token = Lex.getKind();
2962 if (Token == lltok::Eof)
2963 return TokError("found end of file when expecting more instructions");
2964 LocTy Loc = Lex.getLoc();
2965 unsigned KeywordVal = Lex.getUIntVal();
2966 Lex.Lex(); // Eat the keyword.
2969 default: return Error(Loc, "expected instruction opcode");
2970 // Terminator Instructions.
2971 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
2972 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2973 case lltok::kw_br: return ParseBr(Inst, PFS);
2974 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2975 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
2976 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2977 case lltok::kw_resume: return ParseResume(Inst, PFS);
2978 // Binary Operators.
2982 case lltok::kw_shl: {
2983 bool NUW = EatIfPresent(lltok::kw_nuw);
2984 bool NSW = EatIfPresent(lltok::kw_nsw);
2985 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
2987 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
2989 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
2990 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
2993 case lltok::kw_fadd:
2994 case lltok::kw_fsub:
2995 case lltok::kw_fmul: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2997 case lltok::kw_sdiv:
2998 case lltok::kw_udiv:
2999 case lltok::kw_lshr:
3000 case lltok::kw_ashr: {
3001 bool Exact = EatIfPresent(lltok::kw_exact);
3003 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3004 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3008 case lltok::kw_urem:
3009 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3010 case lltok::kw_fdiv:
3011 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
3014 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3015 case lltok::kw_icmp:
3016 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3018 case lltok::kw_trunc:
3019 case lltok::kw_zext:
3020 case lltok::kw_sext:
3021 case lltok::kw_fptrunc:
3022 case lltok::kw_fpext:
3023 case lltok::kw_bitcast:
3024 case lltok::kw_uitofp:
3025 case lltok::kw_sitofp:
3026 case lltok::kw_fptoui:
3027 case lltok::kw_fptosi:
3028 case lltok::kw_inttoptr:
3029 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3031 case lltok::kw_select: return ParseSelect(Inst, PFS);
3032 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3033 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3034 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3035 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3036 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3037 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3038 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3039 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3041 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3042 case lltok::kw_load: return ParseLoad(Inst, PFS);
3043 case lltok::kw_store: return ParseStore(Inst, PFS);
3044 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3045 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3046 case lltok::kw_fence: return ParseFence(Inst, PFS);
3047 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3048 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3049 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3053 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3054 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3055 if (Opc == Instruction::FCmp) {
3056 switch (Lex.getKind()) {
3057 default: TokError("expected fcmp predicate (e.g. 'oeq')");
3058 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3059 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3060 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3061 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3062 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3063 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3064 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3065 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3066 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3067 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3068 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3069 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3070 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3071 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3072 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3073 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3076 switch (Lex.getKind()) {
3077 default: TokError("expected icmp predicate (e.g. 'eq')");
3078 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3079 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3080 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3081 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3082 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3083 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3084 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3085 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3086 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3087 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3094 //===----------------------------------------------------------------------===//
3095 // Terminator Instructions.
3096 //===----------------------------------------------------------------------===//
3098 /// ParseRet - Parse a return instruction.
3099 /// ::= 'ret' void (',' !dbg, !1)*
3100 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3101 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3102 PerFunctionState &PFS) {
3103 SMLoc TypeLoc = Lex.getLoc();
3105 if (ParseType(Ty, true /*void allowed*/)) return true;
3107 Type *ResType = PFS.getFunction().getReturnType();
3109 if (Ty->isVoidTy()) {
3110 if (!ResType->isVoidTy())
3111 return Error(TypeLoc, "value doesn't match function result type '" +
3112 getTypeString(ResType) + "'");
3114 Inst = ReturnInst::Create(Context);
3119 if (ParseValue(Ty, RV, PFS)) return true;
3121 if (ResType != RV->getType())
3122 return Error(TypeLoc, "value doesn't match function result type '" +
3123 getTypeString(ResType) + "'");
3125 Inst = ReturnInst::Create(Context, RV);
3131 /// ::= 'br' TypeAndValue
3132 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3133 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3136 BasicBlock *Op1, *Op2;
3137 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3139 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3140 Inst = BranchInst::Create(BB);
3144 if (Op0->getType() != Type::getInt1Ty(Context))
3145 return Error(Loc, "branch condition must have 'i1' type");
3147 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3148 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3149 ParseToken(lltok::comma, "expected ',' after true destination") ||
3150 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3153 Inst = BranchInst::Create(Op1, Op2, Op0);
3159 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3161 /// ::= (TypeAndValue ',' TypeAndValue)*
3162 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3163 LocTy CondLoc, BBLoc;
3165 BasicBlock *DefaultBB;
3166 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3167 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3168 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3169 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3172 if (!Cond->getType()->isIntegerTy())
3173 return Error(CondLoc, "switch condition must have integer type");
3175 // Parse the jump table pairs.
3176 SmallPtrSet<Value*, 32> SeenCases;
3177 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3178 while (Lex.getKind() != lltok::rsquare) {
3182 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3183 ParseToken(lltok::comma, "expected ',' after case value") ||
3184 ParseTypeAndBasicBlock(DestBB, PFS))
3187 if (!SeenCases.insert(Constant))
3188 return Error(CondLoc, "duplicate case value in switch");
3189 if (!isa<ConstantInt>(Constant))
3190 return Error(CondLoc, "case value is not a constant integer");
3192 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3195 Lex.Lex(); // Eat the ']'.
3197 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3198 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3199 SI->addCase(Table[i].first, Table[i].second);
3206 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3207 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3210 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3211 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3212 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3215 if (!Address->getType()->isPointerTy())
3216 return Error(AddrLoc, "indirectbr address must have pointer type");
3218 // Parse the destination list.
3219 SmallVector<BasicBlock*, 16> DestList;
3221 if (Lex.getKind() != lltok::rsquare) {
3223 if (ParseTypeAndBasicBlock(DestBB, PFS))
3225 DestList.push_back(DestBB);
3227 while (EatIfPresent(lltok::comma)) {
3228 if (ParseTypeAndBasicBlock(DestBB, PFS))
3230 DestList.push_back(DestBB);
3234 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3237 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3238 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3239 IBI->addDestination(DestList[i]);
3246 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3247 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3248 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3249 LocTy CallLoc = Lex.getLoc();
3250 Attributes RetAttrs, FnAttrs;
3255 SmallVector<ParamInfo, 16> ArgList;
3257 BasicBlock *NormalBB, *UnwindBB;
3258 if (ParseOptionalCallingConv(CC) ||
3259 ParseOptionalAttrs(RetAttrs, 1) ||
3260 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3261 ParseValID(CalleeID) ||
3262 ParseParameterList(ArgList, PFS) ||
3263 ParseOptionalAttrs(FnAttrs, 2) ||
3264 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3265 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3266 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3267 ParseTypeAndBasicBlock(UnwindBB, PFS))
3270 // If RetType is a non-function pointer type, then this is the short syntax
3271 // for the call, which means that RetType is just the return type. Infer the
3272 // rest of the function argument types from the arguments that are present.
3273 PointerType *PFTy = 0;
3274 FunctionType *Ty = 0;
3275 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3276 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3277 // Pull out the types of all of the arguments...
3278 std::vector<Type*> ParamTypes;
3279 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3280 ParamTypes.push_back(ArgList[i].V->getType());
3282 if (!FunctionType::isValidReturnType(RetType))
3283 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3285 Ty = FunctionType::get(RetType, ParamTypes, false);
3286 PFTy = PointerType::getUnqual(Ty);
3289 // Look up the callee.
3291 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3293 // Set up the Attributes for the function.
3294 SmallVector<AttributeWithIndex, 8> Attrs;
3295 if (RetAttrs.hasAttributes())
3296 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3298 SmallVector<Value*, 8> Args;
3300 // Loop through FunctionType's arguments and ensure they are specified
3301 // correctly. Also, gather any parameter attributes.
3302 FunctionType::param_iterator I = Ty->param_begin();
3303 FunctionType::param_iterator E = Ty->param_end();
3304 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3305 Type *ExpectedTy = 0;
3308 } else if (!Ty->isVarArg()) {
3309 return Error(ArgList[i].Loc, "too many arguments specified");
3312 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3313 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3314 getTypeString(ExpectedTy) + "'");
3315 Args.push_back(ArgList[i].V);
3316 if (ArgList[i].Attrs.hasAttributes())
3317 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3321 return Error(CallLoc, "not enough parameters specified for call");
3323 if (FnAttrs.hasAttributes())
3324 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3326 // Finish off the Attributes and check them
3327 AttrListPtr PAL = AttrListPtr::get(Attrs);
3329 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3330 II->setCallingConv(CC);
3331 II->setAttributes(PAL);
3337 /// ::= 'resume' TypeAndValue
3338 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3339 Value *Exn; LocTy ExnLoc;
3340 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3343 ResumeInst *RI = ResumeInst::Create(Exn);
3348 //===----------------------------------------------------------------------===//
3349 // Binary Operators.
3350 //===----------------------------------------------------------------------===//
3353 /// ::= ArithmeticOps TypeAndValue ',' Value
3355 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3356 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3357 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3358 unsigned Opc, unsigned OperandType) {
3359 LocTy Loc; Value *LHS, *RHS;
3360 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3361 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3362 ParseValue(LHS->getType(), RHS, PFS))
3366 switch (OperandType) {
3367 default: llvm_unreachable("Unknown operand type!");
3368 case 0: // int or FP.
3369 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3370 LHS->getType()->isFPOrFPVectorTy();
3372 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3373 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3377 return Error(Loc, "invalid operand type for instruction");
3379 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3384 /// ::= ArithmeticOps TypeAndValue ',' Value {
3385 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3387 LocTy Loc; Value *LHS, *RHS;
3388 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3389 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3390 ParseValue(LHS->getType(), RHS, PFS))
3393 if (!LHS->getType()->isIntOrIntVectorTy())
3394 return Error(Loc,"instruction requires integer or integer vector operands");
3396 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3402 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3403 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3404 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3406 // Parse the integer/fp comparison predicate.
3410 if (ParseCmpPredicate(Pred, Opc) ||
3411 ParseTypeAndValue(LHS, Loc, PFS) ||
3412 ParseToken(lltok::comma, "expected ',' after compare value") ||
3413 ParseValue(LHS->getType(), RHS, PFS))
3416 if (Opc == Instruction::FCmp) {
3417 if (!LHS->getType()->isFPOrFPVectorTy())
3418 return Error(Loc, "fcmp requires floating point operands");
3419 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3421 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3422 if (!LHS->getType()->isIntOrIntVectorTy() &&
3423 !LHS->getType()->getScalarType()->isPointerTy())
3424 return Error(Loc, "icmp requires integer operands");
3425 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3430 //===----------------------------------------------------------------------===//
3431 // Other Instructions.
3432 //===----------------------------------------------------------------------===//
3436 /// ::= CastOpc TypeAndValue 'to' Type
3437 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3442 if (ParseTypeAndValue(Op, Loc, PFS) ||
3443 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3447 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3448 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3449 return Error(Loc, "invalid cast opcode for cast from '" +
3450 getTypeString(Op->getType()) + "' to '" +
3451 getTypeString(DestTy) + "'");
3453 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3458 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3459 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3461 Value *Op0, *Op1, *Op2;
3462 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3463 ParseToken(lltok::comma, "expected ',' after select condition") ||
3464 ParseTypeAndValue(Op1, PFS) ||
3465 ParseToken(lltok::comma, "expected ',' after select value") ||
3466 ParseTypeAndValue(Op2, PFS))
3469 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3470 return Error(Loc, Reason);
3472 Inst = SelectInst::Create(Op0, Op1, Op2);
3477 /// ::= 'va_arg' TypeAndValue ',' Type
3478 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3482 if (ParseTypeAndValue(Op, PFS) ||
3483 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3484 ParseType(EltTy, TypeLoc))
3487 if (!EltTy->isFirstClassType())
3488 return Error(TypeLoc, "va_arg requires operand with first class type");
3490 Inst = new VAArgInst(Op, EltTy);
3494 /// ParseExtractElement
3495 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3496 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3499 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3500 ParseToken(lltok::comma, "expected ',' after extract value") ||
3501 ParseTypeAndValue(Op1, PFS))
3504 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3505 return Error(Loc, "invalid extractelement operands");
3507 Inst = ExtractElementInst::Create(Op0, Op1);
3511 /// ParseInsertElement
3512 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3513 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3515 Value *Op0, *Op1, *Op2;
3516 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3517 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3518 ParseTypeAndValue(Op1, PFS) ||
3519 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3520 ParseTypeAndValue(Op2, PFS))
3523 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3524 return Error(Loc, "invalid insertelement operands");
3526 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3530 /// ParseShuffleVector
3531 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3532 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3534 Value *Op0, *Op1, *Op2;
3535 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3536 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3537 ParseTypeAndValue(Op1, PFS) ||
3538 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3539 ParseTypeAndValue(Op2, PFS))
3542 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3543 return Error(Loc, "invalid shufflevector operands");
3545 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3550 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3551 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3552 Type *Ty = 0; LocTy TypeLoc;
3555 if (ParseType(Ty, TypeLoc) ||
3556 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3557 ParseValue(Ty, Op0, PFS) ||
3558 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3559 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3560 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3563 bool AteExtraComma = false;
3564 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3566 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3568 if (!EatIfPresent(lltok::comma))
3571 if (Lex.getKind() == lltok::MetadataVar) {
3572 AteExtraComma = true;
3576 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3577 ParseValue(Ty, Op0, PFS) ||
3578 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3579 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3580 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3584 if (!Ty->isFirstClassType())
3585 return Error(TypeLoc, "phi node must have first class type");
3587 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3588 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3589 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3591 return AteExtraComma ? InstExtraComma : InstNormal;
3595 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3597 /// ::= 'catch' TypeAndValue
3599 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3600 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3601 Type *Ty = 0; LocTy TyLoc;
3602 Value *PersFn; LocTy PersFnLoc;
3604 if (ParseType(Ty, TyLoc) ||
3605 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3606 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3609 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3610 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3612 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3613 LandingPadInst::ClauseType CT;
3614 if (EatIfPresent(lltok::kw_catch))
3615 CT = LandingPadInst::Catch;
3616 else if (EatIfPresent(lltok::kw_filter))
3617 CT = LandingPadInst::Filter;
3619 return TokError("expected 'catch' or 'filter' clause type");
3621 Value *V; LocTy VLoc;
3622 if (ParseTypeAndValue(V, VLoc, PFS)) {
3627 // A 'catch' type expects a non-array constant. A filter clause expects an
3629 if (CT == LandingPadInst::Catch) {
3630 if (isa<ArrayType>(V->getType()))
3631 Error(VLoc, "'catch' clause has an invalid type");
3633 if (!isa<ArrayType>(V->getType()))
3634 Error(VLoc, "'filter' clause has an invalid type");
3645 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3646 /// ParameterList OptionalAttrs
3647 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3649 Attributes RetAttrs, FnAttrs;
3654 SmallVector<ParamInfo, 16> ArgList;
3655 LocTy CallLoc = Lex.getLoc();
3657 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3658 ParseOptionalCallingConv(CC) ||
3659 ParseOptionalAttrs(RetAttrs, 1) ||
3660 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3661 ParseValID(CalleeID) ||
3662 ParseParameterList(ArgList, PFS) ||
3663 ParseOptionalAttrs(FnAttrs, 2))
3666 // If RetType is a non-function pointer type, then this is the short syntax
3667 // for the call, which means that RetType is just the return type. Infer the
3668 // rest of the function argument types from the arguments that are present.
3669 PointerType *PFTy = 0;
3670 FunctionType *Ty = 0;
3671 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3672 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3673 // Pull out the types of all of the arguments...
3674 std::vector<Type*> ParamTypes;
3675 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3676 ParamTypes.push_back(ArgList[i].V->getType());
3678 if (!FunctionType::isValidReturnType(RetType))
3679 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3681 Ty = FunctionType::get(RetType, ParamTypes, false);
3682 PFTy = PointerType::getUnqual(Ty);
3685 // Look up the callee.
3687 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3689 // Set up the Attributes for the function.
3690 SmallVector<AttributeWithIndex, 8> Attrs;
3691 if (RetAttrs.hasAttributes())
3692 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3694 SmallVector<Value*, 8> Args;
3696 // Loop through FunctionType's arguments and ensure they are specified
3697 // correctly. Also, gather any parameter attributes.
3698 FunctionType::param_iterator I = Ty->param_begin();
3699 FunctionType::param_iterator E = Ty->param_end();
3700 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3701 Type *ExpectedTy = 0;
3704 } else if (!Ty->isVarArg()) {
3705 return Error(ArgList[i].Loc, "too many arguments specified");
3708 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3709 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3710 getTypeString(ExpectedTy) + "'");
3711 Args.push_back(ArgList[i].V);
3712 if (ArgList[i].Attrs.hasAttributes())
3713 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3717 return Error(CallLoc, "not enough parameters specified for call");
3719 if (FnAttrs.hasAttributes())
3720 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3722 // Finish off the Attributes and check them
3723 AttrListPtr PAL = AttrListPtr::get(Attrs);
3725 CallInst *CI = CallInst::Create(Callee, Args);
3726 CI->setTailCall(isTail);
3727 CI->setCallingConv(CC);
3728 CI->setAttributes(PAL);
3733 //===----------------------------------------------------------------------===//
3734 // Memory Instructions.
3735 //===----------------------------------------------------------------------===//
3738 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3739 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3742 unsigned Alignment = 0;
3744 if (ParseType(Ty)) return true;
3746 bool AteExtraComma = false;
3747 if (EatIfPresent(lltok::comma)) {
3748 if (Lex.getKind() == lltok::kw_align) {
3749 if (ParseOptionalAlignment(Alignment)) return true;
3750 } else if (Lex.getKind() == lltok::MetadataVar) {
3751 AteExtraComma = true;
3753 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3754 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3759 if (Size && !Size->getType()->isIntegerTy())
3760 return Error(SizeLoc, "element count must have integer type");
3762 Inst = new AllocaInst(Ty, Size, Alignment);
3763 return AteExtraComma ? InstExtraComma : InstNormal;
3767 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3768 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
3769 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3770 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
3771 Value *Val; LocTy Loc;
3772 unsigned Alignment = 0;
3773 bool AteExtraComma = false;
3774 bool isAtomic = false;
3775 AtomicOrdering Ordering = NotAtomic;
3776 SynchronizationScope Scope = CrossThread;
3778 if (Lex.getKind() == lltok::kw_atomic) {
3783 bool isVolatile = false;
3784 if (Lex.getKind() == lltok::kw_volatile) {
3789 if (ParseTypeAndValue(Val, Loc, PFS) ||
3790 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3791 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3794 if (!Val->getType()->isPointerTy() ||
3795 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3796 return Error(Loc, "load operand must be a pointer to a first class type");
3797 if (isAtomic && !Alignment)
3798 return Error(Loc, "atomic load must have explicit non-zero alignment");
3799 if (Ordering == Release || Ordering == AcquireRelease)
3800 return Error(Loc, "atomic load cannot use Release ordering");
3802 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
3803 return AteExtraComma ? InstExtraComma : InstNormal;
3808 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3809 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
3810 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
3811 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
3812 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3813 unsigned Alignment = 0;
3814 bool AteExtraComma = false;
3815 bool isAtomic = false;
3816 AtomicOrdering Ordering = NotAtomic;
3817 SynchronizationScope Scope = CrossThread;
3819 if (Lex.getKind() == lltok::kw_atomic) {
3824 bool isVolatile = false;
3825 if (Lex.getKind() == lltok::kw_volatile) {
3830 if (ParseTypeAndValue(Val, Loc, PFS) ||
3831 ParseToken(lltok::comma, "expected ',' after store operand") ||
3832 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3833 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
3834 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3837 if (!Ptr->getType()->isPointerTy())
3838 return Error(PtrLoc, "store operand must be a pointer");
3839 if (!Val->getType()->isFirstClassType())
3840 return Error(Loc, "store operand must be a first class value");
3841 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3842 return Error(Loc, "stored value and pointer type do not match");
3843 if (isAtomic && !Alignment)
3844 return Error(Loc, "atomic store must have explicit non-zero alignment");
3845 if (Ordering == Acquire || Ordering == AcquireRelease)
3846 return Error(Loc, "atomic store cannot use Acquire ordering");
3848 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
3849 return AteExtraComma ? InstExtraComma : InstNormal;
3853 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
3854 /// 'singlethread'? AtomicOrdering
3855 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
3856 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
3857 bool AteExtraComma = false;
3858 AtomicOrdering Ordering = NotAtomic;
3859 SynchronizationScope Scope = CrossThread;
3860 bool isVolatile = false;
3862 if (EatIfPresent(lltok::kw_volatile))
3865 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3866 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
3867 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
3868 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
3869 ParseTypeAndValue(New, NewLoc, PFS) ||
3870 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3873 if (Ordering == Unordered)
3874 return TokError("cmpxchg cannot be unordered");
3875 if (!Ptr->getType()->isPointerTy())
3876 return Error(PtrLoc, "cmpxchg operand must be a pointer");
3877 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
3878 return Error(CmpLoc, "compare value and pointer type do not match");
3879 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
3880 return Error(NewLoc, "new value and pointer type do not match");
3881 if (!New->getType()->isIntegerTy())
3882 return Error(NewLoc, "cmpxchg operand must be an integer");
3883 unsigned Size = New->getType()->getPrimitiveSizeInBits();
3884 if (Size < 8 || (Size & (Size - 1)))
3885 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
3888 AtomicCmpXchgInst *CXI =
3889 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
3890 CXI->setVolatile(isVolatile);
3892 return AteExtraComma ? InstExtraComma : InstNormal;
3896 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
3897 /// 'singlethread'? AtomicOrdering
3898 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
3899 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
3900 bool AteExtraComma = false;
3901 AtomicOrdering Ordering = NotAtomic;
3902 SynchronizationScope Scope = CrossThread;
3903 bool isVolatile = false;
3904 AtomicRMWInst::BinOp Operation;
3906 if (EatIfPresent(lltok::kw_volatile))
3909 switch (Lex.getKind()) {
3910 default: return TokError("expected binary operation in atomicrmw");
3911 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
3912 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
3913 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
3914 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
3915 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
3916 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
3917 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
3918 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
3919 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
3920 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
3921 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
3923 Lex.Lex(); // Eat the operation.
3925 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3926 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
3927 ParseTypeAndValue(Val, ValLoc, PFS) ||
3928 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3931 if (Ordering == Unordered)
3932 return TokError("atomicrmw cannot be unordered");
3933 if (!Ptr->getType()->isPointerTy())
3934 return Error(PtrLoc, "atomicrmw operand must be a pointer");
3935 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3936 return Error(ValLoc, "atomicrmw value and pointer type do not match");
3937 if (!Val->getType()->isIntegerTy())
3938 return Error(ValLoc, "atomicrmw operand must be an integer");
3939 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
3940 if (Size < 8 || (Size & (Size - 1)))
3941 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
3944 AtomicRMWInst *RMWI =
3945 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
3946 RMWI->setVolatile(isVolatile);
3948 return AteExtraComma ? InstExtraComma : InstNormal;
3952 /// ::= 'fence' 'singlethread'? AtomicOrdering
3953 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
3954 AtomicOrdering Ordering = NotAtomic;
3955 SynchronizationScope Scope = CrossThread;
3956 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
3959 if (Ordering == Unordered)
3960 return TokError("fence cannot be unordered");
3961 if (Ordering == Monotonic)
3962 return TokError("fence cannot be monotonic");
3964 Inst = new FenceInst(Context, Ordering, Scope);
3968 /// ParseGetElementPtr
3969 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3970 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3975 bool InBounds = EatIfPresent(lltok::kw_inbounds);
3977 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3979 if (!Ptr->getType()->getScalarType()->isPointerTy())
3980 return Error(Loc, "base of getelementptr must be a pointer");
3982 SmallVector<Value*, 16> Indices;
3983 bool AteExtraComma = false;
3984 while (EatIfPresent(lltok::comma)) {
3985 if (Lex.getKind() == lltok::MetadataVar) {
3986 AteExtraComma = true;
3989 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3990 if (!Val->getType()->getScalarType()->isIntegerTy())
3991 return Error(EltLoc, "getelementptr index must be an integer");
3992 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
3993 return Error(EltLoc, "getelementptr index type missmatch");
3994 if (Val->getType()->isVectorTy()) {
3995 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
3996 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
3997 if (ValNumEl != PtrNumEl)
3998 return Error(EltLoc,
3999 "getelementptr vector index has a wrong number of elements");
4001 Indices.push_back(Val);
4004 if (Val && Val->getType()->isVectorTy() && Indices.size() != 1)
4005 return Error(EltLoc, "vector getelementptrs must have a single index");
4007 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
4008 return Error(Loc, "invalid getelementptr indices");
4009 Inst = GetElementPtrInst::Create(Ptr, Indices);
4011 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4012 return AteExtraComma ? InstExtraComma : InstNormal;
4015 /// ParseExtractValue
4016 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4017 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4018 Value *Val; LocTy Loc;
4019 SmallVector<unsigned, 4> Indices;
4021 if (ParseTypeAndValue(Val, Loc, PFS) ||
4022 ParseIndexList(Indices, AteExtraComma))
4025 if (!Val->getType()->isAggregateType())
4026 return Error(Loc, "extractvalue operand must be aggregate type");
4028 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4029 return Error(Loc, "invalid indices for extractvalue");
4030 Inst = ExtractValueInst::Create(Val, Indices);
4031 return AteExtraComma ? InstExtraComma : InstNormal;
4034 /// ParseInsertValue
4035 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4036 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4037 Value *Val0, *Val1; LocTy Loc0, Loc1;
4038 SmallVector<unsigned, 4> Indices;
4040 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4041 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4042 ParseTypeAndValue(Val1, Loc1, PFS) ||
4043 ParseIndexList(Indices, AteExtraComma))
4046 if (!Val0->getType()->isAggregateType())
4047 return Error(Loc0, "insertvalue operand must be aggregate type");
4049 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4050 return Error(Loc0, "invalid indices for insertvalue");
4051 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4052 return AteExtraComma ? InstExtraComma : InstNormal;
4055 //===----------------------------------------------------------------------===//
4056 // Embedded metadata.
4057 //===----------------------------------------------------------------------===//
4059 /// ParseMDNodeVector
4060 /// ::= Element (',' Element)*
4062 /// ::= 'null' | TypeAndValue
4063 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4064 PerFunctionState *PFS) {
4065 // Check for an empty list.
4066 if (Lex.getKind() == lltok::rbrace)
4070 // Null is a special case since it is typeless.
4071 if (EatIfPresent(lltok::kw_null)) {
4077 if (ParseTypeAndValue(V, PFS)) return true;
4079 } while (EatIfPresent(lltok::comma));