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/ADT/SmallPtrSet.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
30 static std::string getTypeString(Type *T) {
32 raw_string_ostream Tmp(Result);
37 /// Run: module ::= toplevelentity*
38 bool LLParser::Run() {
42 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
46 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48 bool LLParser::ValidateEndOfModule() {
49 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
57 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
60 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
61 return Error(MDList[i].Loc, "use of undefined metadata '!" +
63 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
66 ForwardRefInstMetadata.clear();
69 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
70 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
72 // Handle any function attribute group forward references.
73 for (std::map<Value*, std::vector<unsigned> >::iterator
74 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
77 std::vector<unsigned> &Vec = I->second;
80 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
82 B.merge(NumberedAttrBuilders[*VI]);
84 if (Function *Fn = dyn_cast<Function>(V)) {
85 AttributeSet AS = Fn->getAttributes();
86 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
87 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
88 AS.getFnAttributes());
92 // If the alignment was parsed as an attribute, move to the alignment
94 if (FnAttrs.hasAlignmentAttr()) {
95 Fn->setAlignment(FnAttrs.getAlignment());
96 FnAttrs.removeAttribute(Attribute::Alignment);
99 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
100 AttributeSet::get(Context,
101 AttributeSet::FunctionIndex,
103 Fn->setAttributes(AS);
104 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
105 AttributeSet AS = CI->getAttributes();
106 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
107 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
108 AS.getFnAttributes());
110 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
111 AttributeSet::get(Context,
112 AttributeSet::FunctionIndex,
114 CI->setAttributes(AS);
115 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
116 AttributeSet AS = II->getAttributes();
117 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
118 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
119 AS.getFnAttributes());
121 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
122 AttributeSet::get(Context,
123 AttributeSet::FunctionIndex,
125 II->setAttributes(AS);
127 llvm_unreachable("invalid object with forward attribute group reference");
131 // If there are entries in ForwardRefBlockAddresses at this point, they are
132 // references after the function was defined. Resolve those now.
133 while (!ForwardRefBlockAddresses.empty()) {
134 // Okay, we are referencing an already-parsed function, resolve them now.
136 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
137 if (Fn.Kind == ValID::t_GlobalName)
138 TheFn = M->getFunction(Fn.StrVal);
139 else if (Fn.UIntVal < NumberedVals.size())
140 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
143 return Error(Fn.Loc, "unknown function referenced by blockaddress");
145 // Resolve all these references.
146 if (ResolveForwardRefBlockAddresses(TheFn,
147 ForwardRefBlockAddresses.begin()->second,
151 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
154 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
155 if (NumberedTypes[i].second.isValid())
156 return Error(NumberedTypes[i].second,
157 "use of undefined type '%" + Twine(i) + "'");
159 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
160 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
161 if (I->second.second.isValid())
162 return Error(I->second.second,
163 "use of undefined type named '" + I->getKey() + "'");
165 if (!ForwardRefVals.empty())
166 return Error(ForwardRefVals.begin()->second.second,
167 "use of undefined value '@" + ForwardRefVals.begin()->first +
170 if (!ForwardRefValIDs.empty())
171 return Error(ForwardRefValIDs.begin()->second.second,
172 "use of undefined value '@" +
173 Twine(ForwardRefValIDs.begin()->first) + "'");
175 if (!ForwardRefMDNodes.empty())
176 return Error(ForwardRefMDNodes.begin()->second.second,
177 "use of undefined metadata '!" +
178 Twine(ForwardRefMDNodes.begin()->first) + "'");
181 // Look for intrinsic functions and CallInst that need to be upgraded
182 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
183 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
185 UpgradeDebugInfo(*M);
190 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
191 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
192 PerFunctionState *PFS) {
193 // Loop over all the references, resolving them.
194 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
197 if (Refs[i].first.Kind == ValID::t_LocalName)
198 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
200 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
201 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
202 return Error(Refs[i].first.Loc,
203 "cannot take address of numeric label after the function is defined");
205 Res = dyn_cast_or_null<BasicBlock>(
206 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
210 return Error(Refs[i].first.Loc,
211 "referenced value is not a basic block");
213 // Get the BlockAddress for this and update references to use it.
214 BlockAddress *BA = BlockAddress::get(TheFn, Res);
215 Refs[i].second->replaceAllUsesWith(BA);
216 Refs[i].second->eraseFromParent();
222 //===----------------------------------------------------------------------===//
223 // Top-Level Entities
224 //===----------------------------------------------------------------------===//
226 bool LLParser::ParseTopLevelEntities() {
228 switch (Lex.getKind()) {
229 default: return TokError("expected top-level entity");
230 case lltok::Eof: return false;
231 case lltok::kw_declare: if (ParseDeclare()) return true; break;
232 case lltok::kw_define: if (ParseDefine()) return true; break;
233 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
234 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
235 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
236 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
237 case lltok::LocalVar: if (ParseNamedType()) return true; break;
238 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
239 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
240 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
241 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
243 // The Global variable production with no name can have many different
244 // optional leading prefixes, the production is:
245 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
246 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
247 // ('constant'|'global') ...
248 case lltok::kw_private: // OptionalLinkage
249 case lltok::kw_internal: // OptionalLinkage
250 case lltok::kw_linker_private: // Obsolete OptionalLinkage
251 case lltok::kw_linker_private_weak: // Obsolete OptionalLinkage
252 case lltok::kw_weak: // OptionalLinkage
253 case lltok::kw_weak_odr: // OptionalLinkage
254 case lltok::kw_linkonce: // OptionalLinkage
255 case lltok::kw_linkonce_odr: // OptionalLinkage
256 case lltok::kw_appending: // OptionalLinkage
257 case lltok::kw_common: // OptionalLinkage
258 case lltok::kw_extern_weak: // OptionalLinkage
259 case lltok::kw_external: { // OptionalLinkage
260 unsigned Linkage, Visibility, DLLStorageClass;
261 if (ParseOptionalLinkage(Linkage) ||
262 ParseOptionalVisibility(Visibility) ||
263 ParseOptionalDLLStorageClass(DLLStorageClass) ||
264 ParseGlobal("", SMLoc(), Linkage, true, Visibility, DLLStorageClass))
268 case lltok::kw_default: // OptionalVisibility
269 case lltok::kw_hidden: // OptionalVisibility
270 case lltok::kw_protected: { // OptionalVisibility
271 unsigned Visibility, DLLStorageClass;
272 if (ParseOptionalVisibility(Visibility) ||
273 ParseOptionalDLLStorageClass(DLLStorageClass) ||
274 ParseGlobal("", SMLoc(), 0, false, Visibility, DLLStorageClass))
279 case lltok::kw_thread_local: // OptionalThreadLocal
280 case lltok::kw_addrspace: // OptionalAddrSpace
281 case lltok::kw_constant: // GlobalType
282 case lltok::kw_global: // GlobalType
283 if (ParseGlobal("", SMLoc(), 0, false, 0, 0)) return true;
286 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
293 /// ::= 'module' 'asm' STRINGCONSTANT
294 bool LLParser::ParseModuleAsm() {
295 assert(Lex.getKind() == lltok::kw_module);
299 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
300 ParseStringConstant(AsmStr)) return true;
302 M->appendModuleInlineAsm(AsmStr);
307 /// ::= 'target' 'triple' '=' STRINGCONSTANT
308 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
309 bool LLParser::ParseTargetDefinition() {
310 assert(Lex.getKind() == lltok::kw_target);
313 default: return TokError("unknown target property");
314 case lltok::kw_triple:
316 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
317 ParseStringConstant(Str))
319 M->setTargetTriple(Str);
321 case lltok::kw_datalayout:
323 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
324 ParseStringConstant(Str))
326 M->setDataLayout(Str);
332 /// ::= 'deplibs' '=' '[' ']'
333 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
334 /// FIXME: Remove in 4.0. Currently parse, but ignore.
335 bool LLParser::ParseDepLibs() {
336 assert(Lex.getKind() == lltok::kw_deplibs);
338 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
339 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
342 if (EatIfPresent(lltok::rsquare))
347 if (ParseStringConstant(Str)) return true;
348 } while (EatIfPresent(lltok::comma));
350 return ParseToken(lltok::rsquare, "expected ']' at end of list");
353 /// ParseUnnamedType:
354 /// ::= LocalVarID '=' 'type' type
355 bool LLParser::ParseUnnamedType() {
356 LocTy TypeLoc = Lex.getLoc();
357 unsigned TypeID = Lex.getUIntVal();
358 Lex.Lex(); // eat LocalVarID;
360 if (ParseToken(lltok::equal, "expected '=' after name") ||
361 ParseToken(lltok::kw_type, "expected 'type' after '='"))
364 if (TypeID >= NumberedTypes.size())
365 NumberedTypes.resize(TypeID+1);
368 if (ParseStructDefinition(TypeLoc, "",
369 NumberedTypes[TypeID], Result)) return true;
371 if (!isa<StructType>(Result)) {
372 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
374 return Error(TypeLoc, "non-struct types may not be recursive");
375 Entry.first = Result;
376 Entry.second = SMLoc();
384 /// ::= LocalVar '=' 'type' type
385 bool LLParser::ParseNamedType() {
386 std::string Name = Lex.getStrVal();
387 LocTy NameLoc = Lex.getLoc();
388 Lex.Lex(); // eat LocalVar.
390 if (ParseToken(lltok::equal, "expected '=' after name") ||
391 ParseToken(lltok::kw_type, "expected 'type' after name"))
395 if (ParseStructDefinition(NameLoc, Name,
396 NamedTypes[Name], Result)) return true;
398 if (!isa<StructType>(Result)) {
399 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
401 return Error(NameLoc, "non-struct types may not be recursive");
402 Entry.first = Result;
403 Entry.second = SMLoc();
411 /// ::= 'declare' FunctionHeader
412 bool LLParser::ParseDeclare() {
413 assert(Lex.getKind() == lltok::kw_declare);
417 return ParseFunctionHeader(F, false);
421 /// ::= 'define' FunctionHeader '{' ...
422 bool LLParser::ParseDefine() {
423 assert(Lex.getKind() == lltok::kw_define);
427 return ParseFunctionHeader(F, true) ||
428 ParseFunctionBody(*F);
434 bool LLParser::ParseGlobalType(bool &IsConstant) {
435 if (Lex.getKind() == lltok::kw_constant)
437 else if (Lex.getKind() == lltok::kw_global)
441 return TokError("expected 'global' or 'constant'");
447 /// ParseUnnamedGlobal:
448 /// OptionalVisibility ALIAS ...
449 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
450 /// ... -> global variable
451 /// GlobalID '=' OptionalVisibility ALIAS ...
452 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
453 /// ... -> global variable
454 bool LLParser::ParseUnnamedGlobal() {
455 unsigned VarID = NumberedVals.size();
457 LocTy NameLoc = Lex.getLoc();
459 // Handle the GlobalID form.
460 if (Lex.getKind() == lltok::GlobalID) {
461 if (Lex.getUIntVal() != VarID)
462 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
464 Lex.Lex(); // eat GlobalID;
466 if (ParseToken(lltok::equal, "expected '=' after name"))
471 unsigned Linkage, Visibility, DLLStorageClass;
472 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
473 ParseOptionalVisibility(Visibility) ||
474 ParseOptionalDLLStorageClass(DLLStorageClass))
477 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
478 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
480 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
483 /// ParseNamedGlobal:
484 /// GlobalVar '=' OptionalVisibility ALIAS ...
485 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
486 /// ... -> global variable
487 bool LLParser::ParseNamedGlobal() {
488 assert(Lex.getKind() == lltok::GlobalVar);
489 LocTy NameLoc = Lex.getLoc();
490 std::string Name = Lex.getStrVal();
494 unsigned Linkage, Visibility, DLLStorageClass;
495 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
496 ParseOptionalLinkage(Linkage, HasLinkage) ||
497 ParseOptionalVisibility(Visibility) ||
498 ParseOptionalDLLStorageClass(DLLStorageClass))
501 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
502 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
504 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
508 // ::= '!' STRINGCONSTANT
509 bool LLParser::ParseMDString(MDString *&Result) {
511 if (ParseStringConstant(Str)) return true;
512 Result = MDString::get(Context, Str);
517 // ::= '!' MDNodeNumber
519 /// This version of ParseMDNodeID returns the slot number and null in the case
520 /// of a forward reference.
521 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
522 // !{ ..., !42, ... }
523 if (ParseUInt32(SlotNo)) return true;
525 // Check existing MDNode.
526 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
527 Result = NumberedMetadata[SlotNo];
533 bool LLParser::ParseMDNodeID(MDNode *&Result) {
534 // !{ ..., !42, ... }
536 if (ParseMDNodeID(Result, MID)) return true;
538 // If not a forward reference, just return it now.
539 if (Result) return false;
541 // Otherwise, create MDNode forward reference.
542 MDNode *FwdNode = MDNode::getTemporary(Context, None);
543 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
545 if (NumberedMetadata.size() <= MID)
546 NumberedMetadata.resize(MID+1);
547 NumberedMetadata[MID] = FwdNode;
552 /// ParseNamedMetadata:
553 /// !foo = !{ !1, !2 }
554 bool LLParser::ParseNamedMetadata() {
555 assert(Lex.getKind() == lltok::MetadataVar);
556 std::string Name = Lex.getStrVal();
559 if (ParseToken(lltok::equal, "expected '=' here") ||
560 ParseToken(lltok::exclaim, "Expected '!' here") ||
561 ParseToken(lltok::lbrace, "Expected '{' here"))
564 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
565 if (Lex.getKind() != lltok::rbrace)
567 if (ParseToken(lltok::exclaim, "Expected '!' here"))
571 if (ParseMDNodeID(N)) return true;
573 } while (EatIfPresent(lltok::comma));
575 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
581 /// ParseStandaloneMetadata:
583 bool LLParser::ParseStandaloneMetadata() {
584 assert(Lex.getKind() == lltok::exclaim);
586 unsigned MetadataID = 0;
590 SmallVector<Value *, 16> Elts;
591 if (ParseUInt32(MetadataID) ||
592 ParseToken(lltok::equal, "expected '=' here") ||
593 ParseType(Ty, TyLoc) ||
594 ParseToken(lltok::exclaim, "Expected '!' here") ||
595 ParseToken(lltok::lbrace, "Expected '{' here") ||
596 ParseMDNodeVector(Elts, NULL) ||
597 ParseToken(lltok::rbrace, "expected end of metadata node"))
600 MDNode *Init = MDNode::get(Context, Elts);
602 // See if this was forward referenced, if so, handle it.
603 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
604 FI = ForwardRefMDNodes.find(MetadataID);
605 if (FI != ForwardRefMDNodes.end()) {
606 MDNode *Temp = FI->second.first;
607 Temp->replaceAllUsesWith(Init);
608 MDNode::deleteTemporary(Temp);
609 ForwardRefMDNodes.erase(FI);
611 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
613 if (MetadataID >= NumberedMetadata.size())
614 NumberedMetadata.resize(MetadataID+1);
616 if (NumberedMetadata[MetadataID] != 0)
617 return TokError("Metadata id is already used");
618 NumberedMetadata[MetadataID] = Init;
625 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
626 /// OptionalLinkage Aliasee
629 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
630 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
632 /// Everything through DLL storage class has already been parsed.
634 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
635 unsigned Visibility, unsigned DLLStorageClass) {
636 assert(Lex.getKind() == lltok::kw_alias);
638 LocTy LinkageLoc = Lex.getLoc();
640 if (ParseOptionalLinkage(L))
643 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
645 if(!GlobalAlias::isValidLinkage(Linkage))
646 return Error(LinkageLoc, "invalid linkage type for alias");
649 LocTy AliaseeLoc = Lex.getLoc();
650 if (Lex.getKind() != lltok::kw_bitcast &&
651 Lex.getKind() != lltok::kw_getelementptr) {
652 if (ParseGlobalTypeAndValue(Aliasee)) return true;
654 // The bitcast dest type is not present, it is implied by the dest type.
656 if (ParseValID(ID)) return true;
657 if (ID.Kind != ValID::t_Constant)
658 return Error(AliaseeLoc, "invalid aliasee");
659 Aliasee = ID.ConstantVal;
662 if (!Aliasee->getType()->isPointerTy())
663 return Error(AliaseeLoc, "alias must have pointer type");
665 // Okay, create the alias but do not insert it into the module yet.
666 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
667 (GlobalValue::LinkageTypes)Linkage, Name,
669 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
670 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
672 // See if this value already exists in the symbol table. If so, it is either
673 // a redefinition or a definition of a forward reference.
674 if (GlobalValue *Val = M->getNamedValue(Name)) {
675 // See if this was a redefinition. If so, there is no entry in
677 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
678 I = ForwardRefVals.find(Name);
679 if (I == ForwardRefVals.end())
680 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
682 // Otherwise, this was a definition of forward ref. Verify that types
684 if (Val->getType() != GA->getType())
685 return Error(NameLoc,
686 "forward reference and definition of alias have different types");
688 // If they agree, just RAUW the old value with the alias and remove the
690 Val->replaceAllUsesWith(GA);
691 Val->eraseFromParent();
692 ForwardRefVals.erase(I);
695 // Insert into the module, we know its name won't collide now.
696 M->getAliasList().push_back(GA);
697 assert(GA->getName() == Name && "Should not be a name conflict!");
703 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
704 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
705 /// OptionalExternallyInitialized GlobalType Type Const
706 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
707 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
708 /// OptionalExternallyInitialized GlobalType Type Const
710 /// Everything up to and including OptionalDLLStorageClass has been parsed
713 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
714 unsigned Linkage, bool HasLinkage,
715 unsigned Visibility, unsigned DLLStorageClass) {
717 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
718 GlobalVariable::ThreadLocalMode TLM;
719 LocTy UnnamedAddrLoc;
720 LocTy IsExternallyInitializedLoc;
724 if (ParseOptionalThreadLocal(TLM) ||
725 ParseOptionalAddrSpace(AddrSpace) ||
726 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
728 ParseOptionalToken(lltok::kw_externally_initialized,
729 IsExternallyInitialized,
730 &IsExternallyInitializedLoc) ||
731 ParseGlobalType(IsConstant) ||
732 ParseType(Ty, TyLoc))
735 // If the linkage is specified and is external, then no initializer is
738 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
739 Linkage != GlobalValue::ExternalLinkage)) {
740 if (ParseGlobalValue(Ty, Init))
744 if (Ty->isFunctionTy() || Ty->isLabelTy())
745 return Error(TyLoc, "invalid type for global variable");
747 GlobalVariable *GV = 0;
749 // See if the global was forward referenced, if so, use the global.
751 if (GlobalValue *GVal = M->getNamedValue(Name)) {
752 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
753 return Error(NameLoc, "redefinition of global '@" + Name + "'");
754 GV = cast<GlobalVariable>(GVal);
757 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
758 I = ForwardRefValIDs.find(NumberedVals.size());
759 if (I != ForwardRefValIDs.end()) {
760 GV = cast<GlobalVariable>(I->second.first);
761 ForwardRefValIDs.erase(I);
766 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
767 Name, 0, GlobalVariable::NotThreadLocal,
770 if (GV->getType()->getElementType() != Ty)
772 "forward reference and definition of global have different types");
774 // Move the forward-reference to the correct spot in the module.
775 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
779 NumberedVals.push_back(GV);
781 // Set the parsed properties on the global.
783 GV->setInitializer(Init);
784 GV->setConstant(IsConstant);
785 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
786 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
787 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
788 GV->setExternallyInitialized(IsExternallyInitialized);
789 GV->setThreadLocalMode(TLM);
790 GV->setUnnamedAddr(UnnamedAddr);
792 // Parse attributes on the global.
793 while (Lex.getKind() == lltok::comma) {
796 if (Lex.getKind() == lltok::kw_section) {
798 GV->setSection(Lex.getStrVal());
799 if (ParseToken(lltok::StringConstant, "expected global section string"))
801 } else if (Lex.getKind() == lltok::kw_align) {
803 if (ParseOptionalAlignment(Alignment)) return true;
804 GV->setAlignment(Alignment);
806 TokError("unknown global variable property!");
813 /// ParseUnnamedAttrGrp
814 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
815 bool LLParser::ParseUnnamedAttrGrp() {
816 assert(Lex.getKind() == lltok::kw_attributes);
817 LocTy AttrGrpLoc = Lex.getLoc();
820 assert(Lex.getKind() == lltok::AttrGrpID);
821 unsigned VarID = Lex.getUIntVal();
822 std::vector<unsigned> unused;
826 if (ParseToken(lltok::equal, "expected '=' here") ||
827 ParseToken(lltok::lbrace, "expected '{' here") ||
828 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
830 ParseToken(lltok::rbrace, "expected end of attribute group"))
833 if (!NumberedAttrBuilders[VarID].hasAttributes())
834 return Error(AttrGrpLoc, "attribute group has no attributes");
839 /// ParseFnAttributeValuePairs
840 /// ::= <attr> | <attr> '=' <value>
841 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
842 std::vector<unsigned> &FwdRefAttrGrps,
843 bool inAttrGrp, LocTy &BuiltinLoc) {
844 bool HaveError = false;
849 lltok::Kind Token = Lex.getKind();
850 if (Token == lltok::kw_builtin)
851 BuiltinLoc = Lex.getLoc();
854 if (!inAttrGrp) return HaveError;
855 return Error(Lex.getLoc(), "unterminated attribute group");
860 case lltok::AttrGrpID: {
861 // Allow a function to reference an attribute group:
863 // define void @foo() #1 { ... }
867 "cannot have an attribute group reference in an attribute group");
869 unsigned AttrGrpNum = Lex.getUIntVal();
870 if (inAttrGrp) break;
872 // Save the reference to the attribute group. We'll fill it in later.
873 FwdRefAttrGrps.push_back(AttrGrpNum);
876 // Target-dependent attributes:
877 case lltok::StringConstant: {
878 std::string Attr = Lex.getStrVal();
881 if (EatIfPresent(lltok::equal) &&
882 ParseStringConstant(Val))
885 B.addAttribute(Attr, Val);
889 // Target-independent attributes:
890 case lltok::kw_align: {
891 // As a hack, we allow function alignment to be initially parsed as an
892 // attribute on a function declaration/definition or added to an attribute
893 // group and later moved to the alignment field.
897 if (ParseToken(lltok::equal, "expected '=' here") ||
898 ParseUInt32(Alignment))
901 if (ParseOptionalAlignment(Alignment))
904 B.addAlignmentAttr(Alignment);
907 case lltok::kw_alignstack: {
911 if (ParseToken(lltok::equal, "expected '=' here") ||
912 ParseUInt32(Alignment))
915 if (ParseOptionalStackAlignment(Alignment))
918 B.addStackAlignmentAttr(Alignment);
921 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
922 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
923 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
924 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
925 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
926 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
927 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
928 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
929 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
930 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
931 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
932 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
933 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
934 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
935 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
936 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
937 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
938 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
939 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
940 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
941 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
942 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
943 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
944 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
945 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
946 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
949 case lltok::kw_inreg:
950 case lltok::kw_signext:
951 case lltok::kw_zeroext:
954 "invalid use of attribute on a function");
956 case lltok::kw_byval:
957 case lltok::kw_inalloca:
959 case lltok::kw_noalias:
960 case lltok::kw_nocapture:
961 case lltok::kw_returned:
965 "invalid use of parameter-only attribute on a function");
973 //===----------------------------------------------------------------------===//
974 // GlobalValue Reference/Resolution Routines.
975 //===----------------------------------------------------------------------===//
977 /// GetGlobalVal - Get a value with the specified name or ID, creating a
978 /// forward reference record if needed. This can return null if the value
979 /// exists but does not have the right type.
980 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
982 PointerType *PTy = dyn_cast<PointerType>(Ty);
984 Error(Loc, "global variable reference must have pointer type");
988 // Look this name up in the normal function symbol table.
990 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
992 // If this is a forward reference for the value, see if we already created a
993 // forward ref record.
995 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
996 I = ForwardRefVals.find(Name);
997 if (I != ForwardRefVals.end())
998 Val = I->second.first;
1001 // If we have the value in the symbol table or fwd-ref table, return it.
1003 if (Val->getType() == Ty) return Val;
1004 Error(Loc, "'@" + Name + "' defined with type '" +
1005 getTypeString(Val->getType()) + "'");
1009 // Otherwise, create a new forward reference for this value and remember it.
1010 GlobalValue *FwdVal;
1011 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1012 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1014 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1015 GlobalValue::ExternalWeakLinkage, 0, Name,
1016 0, GlobalVariable::NotThreadLocal,
1017 PTy->getAddressSpace());
1019 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1023 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1024 PointerType *PTy = dyn_cast<PointerType>(Ty);
1026 Error(Loc, "global variable reference must have pointer type");
1030 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1032 // If this is a forward reference for the value, see if we already created a
1033 // forward ref record.
1035 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1036 I = ForwardRefValIDs.find(ID);
1037 if (I != ForwardRefValIDs.end())
1038 Val = I->second.first;
1041 // If we have the value in the symbol table or fwd-ref table, return it.
1043 if (Val->getType() == Ty) return Val;
1044 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1045 getTypeString(Val->getType()) + "'");
1049 // Otherwise, create a new forward reference for this value and remember it.
1050 GlobalValue *FwdVal;
1051 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1052 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1054 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1055 GlobalValue::ExternalWeakLinkage, 0, "");
1057 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1062 //===----------------------------------------------------------------------===//
1064 //===----------------------------------------------------------------------===//
1066 /// ParseToken - If the current token has the specified kind, eat it and return
1067 /// success. Otherwise, emit the specified error and return failure.
1068 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1069 if (Lex.getKind() != T)
1070 return TokError(ErrMsg);
1075 /// ParseStringConstant
1076 /// ::= StringConstant
1077 bool LLParser::ParseStringConstant(std::string &Result) {
1078 if (Lex.getKind() != lltok::StringConstant)
1079 return TokError("expected string constant");
1080 Result = Lex.getStrVal();
1087 bool LLParser::ParseUInt32(unsigned &Val) {
1088 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1089 return TokError("expected integer");
1090 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1091 if (Val64 != unsigned(Val64))
1092 return TokError("expected 32-bit integer (too large)");
1099 /// := 'localdynamic'
1100 /// := 'initialexec'
1102 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1103 switch (Lex.getKind()) {
1105 return TokError("expected localdynamic, initialexec or localexec");
1106 case lltok::kw_localdynamic:
1107 TLM = GlobalVariable::LocalDynamicTLSModel;
1109 case lltok::kw_initialexec:
1110 TLM = GlobalVariable::InitialExecTLSModel;
1112 case lltok::kw_localexec:
1113 TLM = GlobalVariable::LocalExecTLSModel;
1121 /// ParseOptionalThreadLocal
1123 /// := 'thread_local'
1124 /// := 'thread_local' '(' tlsmodel ')'
1125 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1126 TLM = GlobalVariable::NotThreadLocal;
1127 if (!EatIfPresent(lltok::kw_thread_local))
1130 TLM = GlobalVariable::GeneralDynamicTLSModel;
1131 if (Lex.getKind() == lltok::lparen) {
1133 return ParseTLSModel(TLM) ||
1134 ParseToken(lltok::rparen, "expected ')' after thread local model");
1139 /// ParseOptionalAddrSpace
1141 /// := 'addrspace' '(' uint32 ')'
1142 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1144 if (!EatIfPresent(lltok::kw_addrspace))
1146 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1147 ParseUInt32(AddrSpace) ||
1148 ParseToken(lltok::rparen, "expected ')' in address space");
1151 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1152 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1153 bool HaveError = false;
1158 lltok::Kind Token = Lex.getKind();
1160 default: // End of attributes.
1162 case lltok::kw_align: {
1164 if (ParseOptionalAlignment(Alignment))
1166 B.addAlignmentAttr(Alignment);
1169 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1170 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1171 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1172 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1173 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1174 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1175 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1176 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1177 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1178 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1179 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1180 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1182 case lltok::kw_alignstack:
1183 case lltok::kw_alwaysinline:
1184 case lltok::kw_builtin:
1185 case lltok::kw_inlinehint:
1186 case lltok::kw_minsize:
1187 case lltok::kw_naked:
1188 case lltok::kw_nobuiltin:
1189 case lltok::kw_noduplicate:
1190 case lltok::kw_noimplicitfloat:
1191 case lltok::kw_noinline:
1192 case lltok::kw_nonlazybind:
1193 case lltok::kw_noredzone:
1194 case lltok::kw_noreturn:
1195 case lltok::kw_nounwind:
1196 case lltok::kw_optnone:
1197 case lltok::kw_optsize:
1198 case lltok::kw_returns_twice:
1199 case lltok::kw_sanitize_address:
1200 case lltok::kw_sanitize_memory:
1201 case lltok::kw_sanitize_thread:
1203 case lltok::kw_sspreq:
1204 case lltok::kw_sspstrong:
1205 case lltok::kw_uwtable:
1206 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1214 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1215 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1216 bool HaveError = false;
1221 lltok::Kind Token = Lex.getKind();
1223 default: // End of attributes.
1225 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1226 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1227 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1228 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1231 case lltok::kw_align:
1232 case lltok::kw_byval:
1233 case lltok::kw_inalloca:
1234 case lltok::kw_nest:
1235 case lltok::kw_nocapture:
1236 case lltok::kw_returned:
1237 case lltok::kw_sret:
1238 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1241 case lltok::kw_alignstack:
1242 case lltok::kw_alwaysinline:
1243 case lltok::kw_builtin:
1244 case lltok::kw_cold:
1245 case lltok::kw_inlinehint:
1246 case lltok::kw_minsize:
1247 case lltok::kw_naked:
1248 case lltok::kw_nobuiltin:
1249 case lltok::kw_noduplicate:
1250 case lltok::kw_noimplicitfloat:
1251 case lltok::kw_noinline:
1252 case lltok::kw_nonlazybind:
1253 case lltok::kw_noredzone:
1254 case lltok::kw_noreturn:
1255 case lltok::kw_nounwind:
1256 case lltok::kw_optnone:
1257 case lltok::kw_optsize:
1258 case lltok::kw_returns_twice:
1259 case lltok::kw_sanitize_address:
1260 case lltok::kw_sanitize_memory:
1261 case lltok::kw_sanitize_thread:
1263 case lltok::kw_sspreq:
1264 case lltok::kw_sspstrong:
1265 case lltok::kw_uwtable:
1266 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1269 case lltok::kw_readnone:
1270 case lltok::kw_readonly:
1271 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1278 /// ParseOptionalLinkage
1285 /// ::= 'linkonce_odr'
1286 /// ::= 'available_externally'
1289 /// ::= 'extern_weak'
1292 /// Deprecated Values:
1293 /// ::= 'linker_private'
1294 /// ::= 'linker_private_weak'
1295 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1297 switch (Lex.getKind()) {
1298 default: Res=GlobalValue::ExternalLinkage; return false;
1299 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1300 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1301 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1302 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1303 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1304 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1305 case lltok::kw_available_externally:
1306 Res = GlobalValue::AvailableExternallyLinkage;
1308 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1309 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1310 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1311 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1313 case lltok::kw_linker_private:
1314 case lltok::kw_linker_private_weak:
1316 // treat linker_private and linker_private_weak as PrivateLinkage
1317 Res = GlobalValue::PrivateLinkage;
1325 /// ParseOptionalVisibility
1331 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1332 switch (Lex.getKind()) {
1333 default: Res = GlobalValue::DefaultVisibility; return false;
1334 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1335 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1336 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1342 /// ParseOptionalDLLStorageClass
1347 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1348 switch (Lex.getKind()) {
1349 default: Res = GlobalValue::DefaultStorageClass; return false;
1350 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1351 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1357 /// ParseOptionalCallingConv
1361 /// ::= 'kw_intel_ocl_bicc'
1363 /// ::= 'x86_stdcallcc'
1364 /// ::= 'x86_fastcallcc'
1365 /// ::= 'x86_thiscallcc'
1366 /// ::= 'x86_cdeclmethodcc'
1367 /// ::= 'arm_apcscc'
1368 /// ::= 'arm_aapcscc'
1369 /// ::= 'arm_aapcs_vfpcc'
1370 /// ::= 'msp430_intrcc'
1371 /// ::= 'ptx_kernel'
1372 /// ::= 'ptx_device'
1374 /// ::= 'spir_kernel'
1375 /// ::= 'x86_64_sysvcc'
1376 /// ::= 'x86_64_win64cc'
1377 /// ::= 'webkit_jscc'
1379 /// ::= 'preserve_mostcc'
1380 /// ::= 'preserve_allcc'
1383 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1384 switch (Lex.getKind()) {
1385 default: CC = CallingConv::C; return false;
1386 case lltok::kw_ccc: CC = CallingConv::C; break;
1387 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1388 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1389 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1390 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1391 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1392 case lltok::kw_x86_cdeclmethodcc:CC = CallingConv::X86_CDeclMethod; break;
1393 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1394 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1395 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1396 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1397 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1398 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1399 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1400 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1401 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1402 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1403 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1404 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1405 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1406 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1407 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1408 case lltok::kw_cc: {
1409 unsigned ArbitraryCC;
1411 if (ParseUInt32(ArbitraryCC))
1413 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1422 /// ParseInstructionMetadata
1423 /// ::= !dbg !42 (',' !dbg !57)*
1424 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1425 PerFunctionState *PFS) {
1427 if (Lex.getKind() != lltok::MetadataVar)
1428 return TokError("expected metadata after comma");
1430 std::string Name = Lex.getStrVal();
1431 unsigned MDK = M->getMDKindID(Name);
1435 SMLoc Loc = Lex.getLoc();
1437 if (ParseToken(lltok::exclaim, "expected '!' here"))
1440 // This code is similar to that of ParseMetadataValue, however it needs to
1441 // have special-case code for a forward reference; see the comments on
1442 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1443 // at the top level here.
1444 if (Lex.getKind() == lltok::lbrace) {
1446 if (ParseMetadataListValue(ID, PFS))
1448 assert(ID.Kind == ValID::t_MDNode);
1449 Inst->setMetadata(MDK, ID.MDNodeVal);
1451 unsigned NodeID = 0;
1452 if (ParseMDNodeID(Node, NodeID))
1455 // If we got the node, add it to the instruction.
1456 Inst->setMetadata(MDK, Node);
1458 MDRef R = { Loc, MDK, NodeID };
1459 // Otherwise, remember that this should be resolved later.
1460 ForwardRefInstMetadata[Inst].push_back(R);
1464 if (MDK == LLVMContext::MD_tbaa)
1465 InstsWithTBAATag.push_back(Inst);
1467 // If this is the end of the list, we're done.
1468 } while (EatIfPresent(lltok::comma));
1472 /// ParseOptionalAlignment
1475 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1477 if (!EatIfPresent(lltok::kw_align))
1479 LocTy AlignLoc = Lex.getLoc();
1480 if (ParseUInt32(Alignment)) return true;
1481 if (!isPowerOf2_32(Alignment))
1482 return Error(AlignLoc, "alignment is not a power of two");
1483 if (Alignment > Value::MaximumAlignment)
1484 return Error(AlignLoc, "huge alignments are not supported yet");
1488 /// ParseOptionalCommaAlign
1492 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1494 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1495 bool &AteExtraComma) {
1496 AteExtraComma = false;
1497 while (EatIfPresent(lltok::comma)) {
1498 // Metadata at the end is an early exit.
1499 if (Lex.getKind() == lltok::MetadataVar) {
1500 AteExtraComma = true;
1504 if (Lex.getKind() != lltok::kw_align)
1505 return Error(Lex.getLoc(), "expected metadata or 'align'");
1507 if (ParseOptionalAlignment(Alignment)) return true;
1513 /// ParseScopeAndOrdering
1514 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1517 /// This sets Scope and Ordering to the parsed values.
1518 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1519 AtomicOrdering &Ordering) {
1523 Scope = CrossThread;
1524 if (EatIfPresent(lltok::kw_singlethread))
1525 Scope = SingleThread;
1527 return ParseOrdering(Ordering);
1531 /// ::= AtomicOrdering
1533 /// This sets Ordering to the parsed value.
1534 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1535 switch (Lex.getKind()) {
1536 default: return TokError("Expected ordering on atomic instruction");
1537 case lltok::kw_unordered: Ordering = Unordered; break;
1538 case lltok::kw_monotonic: Ordering = Monotonic; break;
1539 case lltok::kw_acquire: Ordering = Acquire; break;
1540 case lltok::kw_release: Ordering = Release; break;
1541 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1542 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1548 /// ParseOptionalStackAlignment
1550 /// ::= 'alignstack' '(' 4 ')'
1551 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1553 if (!EatIfPresent(lltok::kw_alignstack))
1555 LocTy ParenLoc = Lex.getLoc();
1556 if (!EatIfPresent(lltok::lparen))
1557 return Error(ParenLoc, "expected '('");
1558 LocTy AlignLoc = Lex.getLoc();
1559 if (ParseUInt32(Alignment)) return true;
1560 ParenLoc = Lex.getLoc();
1561 if (!EatIfPresent(lltok::rparen))
1562 return Error(ParenLoc, "expected ')'");
1563 if (!isPowerOf2_32(Alignment))
1564 return Error(AlignLoc, "stack alignment is not a power of two");
1568 /// ParseIndexList - This parses the index list for an insert/extractvalue
1569 /// instruction. This sets AteExtraComma in the case where we eat an extra
1570 /// comma at the end of the line and find that it is followed by metadata.
1571 /// Clients that don't allow metadata can call the version of this function that
1572 /// only takes one argument.
1575 /// ::= (',' uint32)+
1577 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1578 bool &AteExtraComma) {
1579 AteExtraComma = false;
1581 if (Lex.getKind() != lltok::comma)
1582 return TokError("expected ',' as start of index list");
1584 while (EatIfPresent(lltok::comma)) {
1585 if (Lex.getKind() == lltok::MetadataVar) {
1586 AteExtraComma = true;
1590 if (ParseUInt32(Idx)) return true;
1591 Indices.push_back(Idx);
1597 //===----------------------------------------------------------------------===//
1599 //===----------------------------------------------------------------------===//
1601 /// ParseType - Parse a type.
1602 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1603 SMLoc TypeLoc = Lex.getLoc();
1604 switch (Lex.getKind()) {
1606 return TokError("expected type");
1608 // Type ::= 'float' | 'void' (etc)
1609 Result = Lex.getTyVal();
1613 // Type ::= StructType
1614 if (ParseAnonStructType(Result, false))
1617 case lltok::lsquare:
1618 // Type ::= '[' ... ']'
1619 Lex.Lex(); // eat the lsquare.
1620 if (ParseArrayVectorType(Result, false))
1623 case lltok::less: // Either vector or packed struct.
1624 // Type ::= '<' ... '>'
1626 if (Lex.getKind() == lltok::lbrace) {
1627 if (ParseAnonStructType(Result, true) ||
1628 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1630 } else if (ParseArrayVectorType(Result, true))
1633 case lltok::LocalVar: {
1635 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1637 // If the type hasn't been defined yet, create a forward definition and
1638 // remember where that forward def'n was seen (in case it never is defined).
1639 if (Entry.first == 0) {
1640 Entry.first = StructType::create(Context, Lex.getStrVal());
1641 Entry.second = Lex.getLoc();
1643 Result = Entry.first;
1648 case lltok::LocalVarID: {
1650 if (Lex.getUIntVal() >= NumberedTypes.size())
1651 NumberedTypes.resize(Lex.getUIntVal()+1);
1652 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1654 // If the type hasn't been defined yet, create a forward definition and
1655 // remember where that forward def'n was seen (in case it never is defined).
1656 if (Entry.first == 0) {
1657 Entry.first = StructType::create(Context);
1658 Entry.second = Lex.getLoc();
1660 Result = Entry.first;
1666 // Parse the type suffixes.
1668 switch (Lex.getKind()) {
1671 if (!AllowVoid && Result->isVoidTy())
1672 return Error(TypeLoc, "void type only allowed for function results");
1675 // Type ::= Type '*'
1677 if (Result->isLabelTy())
1678 return TokError("basic block pointers are invalid");
1679 if (Result->isVoidTy())
1680 return TokError("pointers to void are invalid - use i8* instead");
1681 if (!PointerType::isValidElementType(Result))
1682 return TokError("pointer to this type is invalid");
1683 Result = PointerType::getUnqual(Result);
1687 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1688 case lltok::kw_addrspace: {
1689 if (Result->isLabelTy())
1690 return TokError("basic block pointers are invalid");
1691 if (Result->isVoidTy())
1692 return TokError("pointers to void are invalid; use i8* instead");
1693 if (!PointerType::isValidElementType(Result))
1694 return TokError("pointer to this type is invalid");
1696 if (ParseOptionalAddrSpace(AddrSpace) ||
1697 ParseToken(lltok::star, "expected '*' in address space"))
1700 Result = PointerType::get(Result, AddrSpace);
1704 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1706 if (ParseFunctionType(Result))
1713 /// ParseParameterList
1715 /// ::= '(' Arg (',' Arg)* ')'
1717 /// ::= Type OptionalAttributes Value OptionalAttributes
1718 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1719 PerFunctionState &PFS) {
1720 if (ParseToken(lltok::lparen, "expected '(' in call"))
1723 unsigned AttrIndex = 1;
1724 while (Lex.getKind() != lltok::rparen) {
1725 // If this isn't the first argument, we need a comma.
1726 if (!ArgList.empty() &&
1727 ParseToken(lltok::comma, "expected ',' in argument list"))
1730 // Parse the argument.
1733 AttrBuilder ArgAttrs;
1735 if (ParseType(ArgTy, ArgLoc))
1738 // Otherwise, handle normal operands.
1739 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1741 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1746 Lex.Lex(); // Lex the ')'.
1752 /// ParseArgumentList - Parse the argument list for a function type or function
1754 /// ::= '(' ArgTypeListI ')'
1758 /// ::= ArgTypeList ',' '...'
1759 /// ::= ArgType (',' ArgType)*
1761 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1764 assert(Lex.getKind() == lltok::lparen);
1765 Lex.Lex(); // eat the (.
1767 if (Lex.getKind() == lltok::rparen) {
1769 } else if (Lex.getKind() == lltok::dotdotdot) {
1773 LocTy TypeLoc = Lex.getLoc();
1778 if (ParseType(ArgTy) ||
1779 ParseOptionalParamAttrs(Attrs)) return true;
1781 if (ArgTy->isVoidTy())
1782 return Error(TypeLoc, "argument can not have void type");
1784 if (Lex.getKind() == lltok::LocalVar) {
1785 Name = Lex.getStrVal();
1789 if (!FunctionType::isValidArgumentType(ArgTy))
1790 return Error(TypeLoc, "invalid type for function argument");
1792 unsigned AttrIndex = 1;
1793 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1794 AttributeSet::get(ArgTy->getContext(),
1795 AttrIndex++, Attrs), Name));
1797 while (EatIfPresent(lltok::comma)) {
1798 // Handle ... at end of arg list.
1799 if (EatIfPresent(lltok::dotdotdot)) {
1804 // Otherwise must be an argument type.
1805 TypeLoc = Lex.getLoc();
1806 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1808 if (ArgTy->isVoidTy())
1809 return Error(TypeLoc, "argument can not have void type");
1811 if (Lex.getKind() == lltok::LocalVar) {
1812 Name = Lex.getStrVal();
1818 if (!ArgTy->isFirstClassType())
1819 return Error(TypeLoc, "invalid type for function argument");
1821 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1822 AttributeSet::get(ArgTy->getContext(),
1823 AttrIndex++, Attrs),
1828 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1831 /// ParseFunctionType
1832 /// ::= Type ArgumentList OptionalAttrs
1833 bool LLParser::ParseFunctionType(Type *&Result) {
1834 assert(Lex.getKind() == lltok::lparen);
1836 if (!FunctionType::isValidReturnType(Result))
1837 return TokError("invalid function return type");
1839 SmallVector<ArgInfo, 8> ArgList;
1841 if (ParseArgumentList(ArgList, isVarArg))
1844 // Reject names on the arguments lists.
1845 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1846 if (!ArgList[i].Name.empty())
1847 return Error(ArgList[i].Loc, "argument name invalid in function type");
1848 if (ArgList[i].Attrs.hasAttributes(i + 1))
1849 return Error(ArgList[i].Loc,
1850 "argument attributes invalid in function type");
1853 SmallVector<Type*, 16> ArgListTy;
1854 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1855 ArgListTy.push_back(ArgList[i].Ty);
1857 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1861 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1863 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1864 SmallVector<Type*, 8> Elts;
1865 if (ParseStructBody(Elts)) return true;
1867 Result = StructType::get(Context, Elts, Packed);
1871 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1872 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1873 std::pair<Type*, LocTy> &Entry,
1875 // If the type was already defined, diagnose the redefinition.
1876 if (Entry.first && !Entry.second.isValid())
1877 return Error(TypeLoc, "redefinition of type");
1879 // If we have opaque, just return without filling in the definition for the
1880 // struct. This counts as a definition as far as the .ll file goes.
1881 if (EatIfPresent(lltok::kw_opaque)) {
1882 // This type is being defined, so clear the location to indicate this.
1883 Entry.second = SMLoc();
1885 // If this type number has never been uttered, create it.
1886 if (Entry.first == 0)
1887 Entry.first = StructType::create(Context, Name);
1888 ResultTy = Entry.first;
1892 // If the type starts with '<', then it is either a packed struct or a vector.
1893 bool isPacked = EatIfPresent(lltok::less);
1895 // If we don't have a struct, then we have a random type alias, which we
1896 // accept for compatibility with old files. These types are not allowed to be
1897 // forward referenced and not allowed to be recursive.
1898 if (Lex.getKind() != lltok::lbrace) {
1900 return Error(TypeLoc, "forward references to non-struct type");
1904 return ParseArrayVectorType(ResultTy, true);
1905 return ParseType(ResultTy);
1908 // This type is being defined, so clear the location to indicate this.
1909 Entry.second = SMLoc();
1911 // If this type number has never been uttered, create it.
1912 if (Entry.first == 0)
1913 Entry.first = StructType::create(Context, Name);
1915 StructType *STy = cast<StructType>(Entry.first);
1917 SmallVector<Type*, 8> Body;
1918 if (ParseStructBody(Body) ||
1919 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1922 STy->setBody(Body, isPacked);
1928 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1931 /// ::= '{' Type (',' Type)* '}'
1932 /// ::= '<' '{' '}' '>'
1933 /// ::= '<' '{' Type (',' Type)* '}' '>'
1934 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1935 assert(Lex.getKind() == lltok::lbrace);
1936 Lex.Lex(); // Consume the '{'
1938 // Handle the empty struct.
1939 if (EatIfPresent(lltok::rbrace))
1942 LocTy EltTyLoc = Lex.getLoc();
1944 if (ParseType(Ty)) return true;
1947 if (!StructType::isValidElementType(Ty))
1948 return Error(EltTyLoc, "invalid element type for struct");
1950 while (EatIfPresent(lltok::comma)) {
1951 EltTyLoc = Lex.getLoc();
1952 if (ParseType(Ty)) return true;
1954 if (!StructType::isValidElementType(Ty))
1955 return Error(EltTyLoc, "invalid element type for struct");
1960 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1963 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1964 /// token has already been consumed.
1966 /// ::= '[' APSINTVAL 'x' Types ']'
1967 /// ::= '<' APSINTVAL 'x' Types '>'
1968 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1969 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1970 Lex.getAPSIntVal().getBitWidth() > 64)
1971 return TokError("expected number in address space");
1973 LocTy SizeLoc = Lex.getLoc();
1974 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1977 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1980 LocTy TypeLoc = Lex.getLoc();
1982 if (ParseType(EltTy)) return true;
1984 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1985 "expected end of sequential type"))
1990 return Error(SizeLoc, "zero element vector is illegal");
1991 if ((unsigned)Size != Size)
1992 return Error(SizeLoc, "size too large for vector");
1993 if (!VectorType::isValidElementType(EltTy))
1994 return Error(TypeLoc, "invalid vector element type");
1995 Result = VectorType::get(EltTy, unsigned(Size));
1997 if (!ArrayType::isValidElementType(EltTy))
1998 return Error(TypeLoc, "invalid array element type");
1999 Result = ArrayType::get(EltTy, Size);
2004 //===----------------------------------------------------------------------===//
2005 // Function Semantic Analysis.
2006 //===----------------------------------------------------------------------===//
2008 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2010 : P(p), F(f), FunctionNumber(functionNumber) {
2012 // Insert unnamed arguments into the NumberedVals list.
2013 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2016 NumberedVals.push_back(AI);
2019 LLParser::PerFunctionState::~PerFunctionState() {
2020 // If there were any forward referenced non-basicblock values, delete them.
2021 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2022 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2023 if (!isa<BasicBlock>(I->second.first)) {
2024 I->second.first->replaceAllUsesWith(
2025 UndefValue::get(I->second.first->getType()));
2026 delete I->second.first;
2027 I->second.first = 0;
2030 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2031 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2032 if (!isa<BasicBlock>(I->second.first)) {
2033 I->second.first->replaceAllUsesWith(
2034 UndefValue::get(I->second.first->getType()));
2035 delete I->second.first;
2036 I->second.first = 0;
2040 bool LLParser::PerFunctionState::FinishFunction() {
2041 // Check to see if someone took the address of labels in this block.
2042 if (!P.ForwardRefBlockAddresses.empty()) {
2044 if (!F.getName().empty()) {
2045 FunctionID.Kind = ValID::t_GlobalName;
2046 FunctionID.StrVal = F.getName();
2048 FunctionID.Kind = ValID::t_GlobalID;
2049 FunctionID.UIntVal = FunctionNumber;
2052 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2053 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2054 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2055 // Resolve all these references.
2056 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2059 P.ForwardRefBlockAddresses.erase(FRBAI);
2063 if (!ForwardRefVals.empty())
2064 return P.Error(ForwardRefVals.begin()->second.second,
2065 "use of undefined value '%" + ForwardRefVals.begin()->first +
2067 if (!ForwardRefValIDs.empty())
2068 return P.Error(ForwardRefValIDs.begin()->second.second,
2069 "use of undefined value '%" +
2070 Twine(ForwardRefValIDs.begin()->first) + "'");
2075 /// GetVal - Get a value with the specified name or ID, creating a
2076 /// forward reference record if needed. This can return null if the value
2077 /// exists but does not have the right type.
2078 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2079 Type *Ty, LocTy Loc) {
2080 // Look this name up in the normal function symbol table.
2081 Value *Val = F.getValueSymbolTable().lookup(Name);
2083 // If this is a forward reference for the value, see if we already created a
2084 // forward ref record.
2086 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2087 I = ForwardRefVals.find(Name);
2088 if (I != ForwardRefVals.end())
2089 Val = I->second.first;
2092 // If we have the value in the symbol table or fwd-ref table, return it.
2094 if (Val->getType() == Ty) return Val;
2095 if (Ty->isLabelTy())
2096 P.Error(Loc, "'%" + Name + "' is not a basic block");
2098 P.Error(Loc, "'%" + Name + "' defined with type '" +
2099 getTypeString(Val->getType()) + "'");
2103 // Don't make placeholders with invalid type.
2104 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2105 P.Error(Loc, "invalid use of a non-first-class type");
2109 // Otherwise, create a new forward reference for this value and remember it.
2111 if (Ty->isLabelTy())
2112 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2114 FwdVal = new Argument(Ty, Name);
2116 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2120 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2122 // Look this name up in the normal function symbol table.
2123 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
2125 // If this is a forward reference for the value, see if we already created a
2126 // forward ref record.
2128 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2129 I = ForwardRefValIDs.find(ID);
2130 if (I != ForwardRefValIDs.end())
2131 Val = I->second.first;
2134 // If we have the value in the symbol table or fwd-ref table, return it.
2136 if (Val->getType() == Ty) return Val;
2137 if (Ty->isLabelTy())
2138 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2140 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2141 getTypeString(Val->getType()) + "'");
2145 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2146 P.Error(Loc, "invalid use of a non-first-class type");
2150 // Otherwise, create a new forward reference for this value and remember it.
2152 if (Ty->isLabelTy())
2153 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2155 FwdVal = new Argument(Ty);
2157 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2161 /// SetInstName - After an instruction is parsed and inserted into its
2162 /// basic block, this installs its name.
2163 bool LLParser::PerFunctionState::SetInstName(int NameID,
2164 const std::string &NameStr,
2165 LocTy NameLoc, Instruction *Inst) {
2166 // If this instruction has void type, it cannot have a name or ID specified.
2167 if (Inst->getType()->isVoidTy()) {
2168 if (NameID != -1 || !NameStr.empty())
2169 return P.Error(NameLoc, "instructions returning void cannot have a name");
2173 // If this was a numbered instruction, verify that the instruction is the
2174 // expected value and resolve any forward references.
2175 if (NameStr.empty()) {
2176 // If neither a name nor an ID was specified, just use the next ID.
2178 NameID = NumberedVals.size();
2180 if (unsigned(NameID) != NumberedVals.size())
2181 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2182 Twine(NumberedVals.size()) + "'");
2184 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2185 ForwardRefValIDs.find(NameID);
2186 if (FI != ForwardRefValIDs.end()) {
2187 if (FI->second.first->getType() != Inst->getType())
2188 return P.Error(NameLoc, "instruction forward referenced with type '" +
2189 getTypeString(FI->second.first->getType()) + "'");
2190 FI->second.first->replaceAllUsesWith(Inst);
2191 delete FI->second.first;
2192 ForwardRefValIDs.erase(FI);
2195 NumberedVals.push_back(Inst);
2199 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2200 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2201 FI = ForwardRefVals.find(NameStr);
2202 if (FI != ForwardRefVals.end()) {
2203 if (FI->second.first->getType() != Inst->getType())
2204 return P.Error(NameLoc, "instruction forward referenced with type '" +
2205 getTypeString(FI->second.first->getType()) + "'");
2206 FI->second.first->replaceAllUsesWith(Inst);
2207 delete FI->second.first;
2208 ForwardRefVals.erase(FI);
2211 // Set the name on the instruction.
2212 Inst->setName(NameStr);
2214 if (Inst->getName() != NameStr)
2215 return P.Error(NameLoc, "multiple definition of local value named '" +
2220 /// GetBB - Get a basic block with the specified name or ID, creating a
2221 /// forward reference record if needed.
2222 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2224 return cast_or_null<BasicBlock>(GetVal(Name,
2225 Type::getLabelTy(F.getContext()), Loc));
2228 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2229 return cast_or_null<BasicBlock>(GetVal(ID,
2230 Type::getLabelTy(F.getContext()), Loc));
2233 /// DefineBB - Define the specified basic block, which is either named or
2234 /// unnamed. If there is an error, this returns null otherwise it returns
2235 /// the block being defined.
2236 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2240 BB = GetBB(NumberedVals.size(), Loc);
2242 BB = GetBB(Name, Loc);
2243 if (BB == 0) return 0; // Already diagnosed error.
2245 // Move the block to the end of the function. Forward ref'd blocks are
2246 // inserted wherever they happen to be referenced.
2247 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2249 // Remove the block from forward ref sets.
2251 ForwardRefValIDs.erase(NumberedVals.size());
2252 NumberedVals.push_back(BB);
2254 // BB forward references are already in the function symbol table.
2255 ForwardRefVals.erase(Name);
2261 //===----------------------------------------------------------------------===//
2263 //===----------------------------------------------------------------------===//
2265 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2266 /// type implied. For example, if we parse "4" we don't know what integer type
2267 /// it has. The value will later be combined with its type and checked for
2268 /// sanity. PFS is used to convert function-local operands of metadata (since
2269 /// metadata operands are not just parsed here but also converted to values).
2270 /// PFS can be null when we are not parsing metadata values inside a function.
2271 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2272 ID.Loc = Lex.getLoc();
2273 switch (Lex.getKind()) {
2274 default: return TokError("expected value token");
2275 case lltok::GlobalID: // @42
2276 ID.UIntVal = Lex.getUIntVal();
2277 ID.Kind = ValID::t_GlobalID;
2279 case lltok::GlobalVar: // @foo
2280 ID.StrVal = Lex.getStrVal();
2281 ID.Kind = ValID::t_GlobalName;
2283 case lltok::LocalVarID: // %42
2284 ID.UIntVal = Lex.getUIntVal();
2285 ID.Kind = ValID::t_LocalID;
2287 case lltok::LocalVar: // %foo
2288 ID.StrVal = Lex.getStrVal();
2289 ID.Kind = ValID::t_LocalName;
2291 case lltok::exclaim: // !42, !{...}, or !"foo"
2292 return ParseMetadataValue(ID, PFS);
2294 ID.APSIntVal = Lex.getAPSIntVal();
2295 ID.Kind = ValID::t_APSInt;
2297 case lltok::APFloat:
2298 ID.APFloatVal = Lex.getAPFloatVal();
2299 ID.Kind = ValID::t_APFloat;
2301 case lltok::kw_true:
2302 ID.ConstantVal = ConstantInt::getTrue(Context);
2303 ID.Kind = ValID::t_Constant;
2305 case lltok::kw_false:
2306 ID.ConstantVal = ConstantInt::getFalse(Context);
2307 ID.Kind = ValID::t_Constant;
2309 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2310 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2311 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2313 case lltok::lbrace: {
2314 // ValID ::= '{' ConstVector '}'
2316 SmallVector<Constant*, 16> Elts;
2317 if (ParseGlobalValueVector(Elts) ||
2318 ParseToken(lltok::rbrace, "expected end of struct constant"))
2321 ID.ConstantStructElts = new Constant*[Elts.size()];
2322 ID.UIntVal = Elts.size();
2323 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2324 ID.Kind = ValID::t_ConstantStruct;
2328 // ValID ::= '<' ConstVector '>' --> Vector.
2329 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2331 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2333 SmallVector<Constant*, 16> Elts;
2334 LocTy FirstEltLoc = Lex.getLoc();
2335 if (ParseGlobalValueVector(Elts) ||
2337 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2338 ParseToken(lltok::greater, "expected end of constant"))
2341 if (isPackedStruct) {
2342 ID.ConstantStructElts = new Constant*[Elts.size()];
2343 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2344 ID.UIntVal = Elts.size();
2345 ID.Kind = ValID::t_PackedConstantStruct;
2350 return Error(ID.Loc, "constant vector must not be empty");
2352 if (!Elts[0]->getType()->isIntegerTy() &&
2353 !Elts[0]->getType()->isFloatingPointTy() &&
2354 !Elts[0]->getType()->isPointerTy())
2355 return Error(FirstEltLoc,
2356 "vector elements must have integer, pointer or floating point type");
2358 // Verify that all the vector elements have the same type.
2359 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2360 if (Elts[i]->getType() != Elts[0]->getType())
2361 return Error(FirstEltLoc,
2362 "vector element #" + Twine(i) +
2363 " is not of type '" + getTypeString(Elts[0]->getType()));
2365 ID.ConstantVal = ConstantVector::get(Elts);
2366 ID.Kind = ValID::t_Constant;
2369 case lltok::lsquare: { // Array Constant
2371 SmallVector<Constant*, 16> Elts;
2372 LocTy FirstEltLoc = Lex.getLoc();
2373 if (ParseGlobalValueVector(Elts) ||
2374 ParseToken(lltok::rsquare, "expected end of array constant"))
2377 // Handle empty element.
2379 // Use undef instead of an array because it's inconvenient to determine
2380 // the element type at this point, there being no elements to examine.
2381 ID.Kind = ValID::t_EmptyArray;
2385 if (!Elts[0]->getType()->isFirstClassType())
2386 return Error(FirstEltLoc, "invalid array element type: " +
2387 getTypeString(Elts[0]->getType()));
2389 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2391 // Verify all elements are correct type!
2392 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2393 if (Elts[i]->getType() != Elts[0]->getType())
2394 return Error(FirstEltLoc,
2395 "array element #" + Twine(i) +
2396 " is not of type '" + getTypeString(Elts[0]->getType()));
2399 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2400 ID.Kind = ValID::t_Constant;
2403 case lltok::kw_c: // c "foo"
2405 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2407 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2408 ID.Kind = ValID::t_Constant;
2411 case lltok::kw_asm: {
2412 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2414 bool HasSideEffect, AlignStack, AsmDialect;
2416 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2417 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2418 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2419 ParseStringConstant(ID.StrVal) ||
2420 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2421 ParseToken(lltok::StringConstant, "expected constraint string"))
2423 ID.StrVal2 = Lex.getStrVal();
2424 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2425 (unsigned(AsmDialect)<<2);
2426 ID.Kind = ValID::t_InlineAsm;
2430 case lltok::kw_blockaddress: {
2431 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2436 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2438 ParseToken(lltok::comma, "expected comma in block address expression")||
2439 ParseValID(Label) ||
2440 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2443 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2444 return Error(Fn.Loc, "expected function name in blockaddress");
2445 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2446 return Error(Label.Loc, "expected basic block name in blockaddress");
2448 // Make a global variable as a placeholder for this reference.
2449 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2450 false, GlobalValue::InternalLinkage,
2452 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2453 ID.ConstantVal = FwdRef;
2454 ID.Kind = ValID::t_Constant;
2458 case lltok::kw_trunc:
2459 case lltok::kw_zext:
2460 case lltok::kw_sext:
2461 case lltok::kw_fptrunc:
2462 case lltok::kw_fpext:
2463 case lltok::kw_bitcast:
2464 case lltok::kw_addrspacecast:
2465 case lltok::kw_uitofp:
2466 case lltok::kw_sitofp:
2467 case lltok::kw_fptoui:
2468 case lltok::kw_fptosi:
2469 case lltok::kw_inttoptr:
2470 case lltok::kw_ptrtoint: {
2471 unsigned Opc = Lex.getUIntVal();
2475 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2476 ParseGlobalTypeAndValue(SrcVal) ||
2477 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2478 ParseType(DestTy) ||
2479 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2481 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2482 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2483 getTypeString(SrcVal->getType()) + "' to '" +
2484 getTypeString(DestTy) + "'");
2485 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2487 ID.Kind = ValID::t_Constant;
2490 case lltok::kw_extractvalue: {
2493 SmallVector<unsigned, 4> Indices;
2494 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2495 ParseGlobalTypeAndValue(Val) ||
2496 ParseIndexList(Indices) ||
2497 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2500 if (!Val->getType()->isAggregateType())
2501 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2502 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2503 return Error(ID.Loc, "invalid indices for extractvalue");
2504 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2505 ID.Kind = ValID::t_Constant;
2508 case lltok::kw_insertvalue: {
2510 Constant *Val0, *Val1;
2511 SmallVector<unsigned, 4> Indices;
2512 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2513 ParseGlobalTypeAndValue(Val0) ||
2514 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2515 ParseGlobalTypeAndValue(Val1) ||
2516 ParseIndexList(Indices) ||
2517 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2519 if (!Val0->getType()->isAggregateType())
2520 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2521 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2522 return Error(ID.Loc, "invalid indices for insertvalue");
2523 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2524 ID.Kind = ValID::t_Constant;
2527 case lltok::kw_icmp:
2528 case lltok::kw_fcmp: {
2529 unsigned PredVal, Opc = Lex.getUIntVal();
2530 Constant *Val0, *Val1;
2532 if (ParseCmpPredicate(PredVal, Opc) ||
2533 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2534 ParseGlobalTypeAndValue(Val0) ||
2535 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2536 ParseGlobalTypeAndValue(Val1) ||
2537 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2540 if (Val0->getType() != Val1->getType())
2541 return Error(ID.Loc, "compare operands must have the same type");
2543 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2545 if (Opc == Instruction::FCmp) {
2546 if (!Val0->getType()->isFPOrFPVectorTy())
2547 return Error(ID.Loc, "fcmp requires floating point operands");
2548 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2550 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2551 if (!Val0->getType()->isIntOrIntVectorTy() &&
2552 !Val0->getType()->getScalarType()->isPointerTy())
2553 return Error(ID.Loc, "icmp requires pointer or integer operands");
2554 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2556 ID.Kind = ValID::t_Constant;
2560 // Binary Operators.
2562 case lltok::kw_fadd:
2564 case lltok::kw_fsub:
2566 case lltok::kw_fmul:
2567 case lltok::kw_udiv:
2568 case lltok::kw_sdiv:
2569 case lltok::kw_fdiv:
2570 case lltok::kw_urem:
2571 case lltok::kw_srem:
2572 case lltok::kw_frem:
2574 case lltok::kw_lshr:
2575 case lltok::kw_ashr: {
2579 unsigned Opc = Lex.getUIntVal();
2580 Constant *Val0, *Val1;
2582 LocTy ModifierLoc = Lex.getLoc();
2583 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2584 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2585 if (EatIfPresent(lltok::kw_nuw))
2587 if (EatIfPresent(lltok::kw_nsw)) {
2589 if (EatIfPresent(lltok::kw_nuw))
2592 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2593 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2594 if (EatIfPresent(lltok::kw_exact))
2597 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2598 ParseGlobalTypeAndValue(Val0) ||
2599 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2600 ParseGlobalTypeAndValue(Val1) ||
2601 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2603 if (Val0->getType() != Val1->getType())
2604 return Error(ID.Loc, "operands of constexpr must have same type");
2605 if (!Val0->getType()->isIntOrIntVectorTy()) {
2607 return Error(ModifierLoc, "nuw only applies to integer operations");
2609 return Error(ModifierLoc, "nsw only applies to integer operations");
2611 // Check that the type is valid for the operator.
2613 case Instruction::Add:
2614 case Instruction::Sub:
2615 case Instruction::Mul:
2616 case Instruction::UDiv:
2617 case Instruction::SDiv:
2618 case Instruction::URem:
2619 case Instruction::SRem:
2620 case Instruction::Shl:
2621 case Instruction::AShr:
2622 case Instruction::LShr:
2623 if (!Val0->getType()->isIntOrIntVectorTy())
2624 return Error(ID.Loc, "constexpr requires integer operands");
2626 case Instruction::FAdd:
2627 case Instruction::FSub:
2628 case Instruction::FMul:
2629 case Instruction::FDiv:
2630 case Instruction::FRem:
2631 if (!Val0->getType()->isFPOrFPVectorTy())
2632 return Error(ID.Loc, "constexpr requires fp operands");
2634 default: llvm_unreachable("Unknown binary operator!");
2637 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2638 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2639 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2640 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2642 ID.Kind = ValID::t_Constant;
2646 // Logical Operations
2649 case lltok::kw_xor: {
2650 unsigned Opc = Lex.getUIntVal();
2651 Constant *Val0, *Val1;
2653 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2654 ParseGlobalTypeAndValue(Val0) ||
2655 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2656 ParseGlobalTypeAndValue(Val1) ||
2657 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2659 if (Val0->getType() != Val1->getType())
2660 return Error(ID.Loc, "operands of constexpr must have same type");
2661 if (!Val0->getType()->isIntOrIntVectorTy())
2662 return Error(ID.Loc,
2663 "constexpr requires integer or integer vector operands");
2664 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2665 ID.Kind = ValID::t_Constant;
2669 case lltok::kw_getelementptr:
2670 case lltok::kw_shufflevector:
2671 case lltok::kw_insertelement:
2672 case lltok::kw_extractelement:
2673 case lltok::kw_select: {
2674 unsigned Opc = Lex.getUIntVal();
2675 SmallVector<Constant*, 16> Elts;
2676 bool InBounds = false;
2678 if (Opc == Instruction::GetElementPtr)
2679 InBounds = EatIfPresent(lltok::kw_inbounds);
2680 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2681 ParseGlobalValueVector(Elts) ||
2682 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2685 if (Opc == Instruction::GetElementPtr) {
2686 if (Elts.size() == 0 ||
2687 !Elts[0]->getType()->getScalarType()->isPointerTy())
2688 return Error(ID.Loc, "getelementptr requires pointer operand");
2690 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2691 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2692 return Error(ID.Loc, "invalid indices for getelementptr");
2693 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2695 } else if (Opc == Instruction::Select) {
2696 if (Elts.size() != 3)
2697 return Error(ID.Loc, "expected three operands to select");
2698 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2700 return Error(ID.Loc, Reason);
2701 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2702 } else if (Opc == Instruction::ShuffleVector) {
2703 if (Elts.size() != 3)
2704 return Error(ID.Loc, "expected three operands to shufflevector");
2705 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2706 return Error(ID.Loc, "invalid operands to shufflevector");
2708 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2709 } else if (Opc == Instruction::ExtractElement) {
2710 if (Elts.size() != 2)
2711 return Error(ID.Loc, "expected two operands to extractelement");
2712 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2713 return Error(ID.Loc, "invalid extractelement operands");
2714 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2716 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2717 if (Elts.size() != 3)
2718 return Error(ID.Loc, "expected three operands to insertelement");
2719 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2720 return Error(ID.Loc, "invalid insertelement operands");
2722 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2725 ID.Kind = ValID::t_Constant;
2734 /// ParseGlobalValue - Parse a global value with the specified type.
2735 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2739 bool Parsed = ParseValID(ID) ||
2740 ConvertValIDToValue(Ty, ID, V, NULL);
2741 if (V && !(C = dyn_cast<Constant>(V)))
2742 return Error(ID.Loc, "global values must be constants");
2746 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2748 return ParseType(Ty) ||
2749 ParseGlobalValue(Ty, V);
2752 /// ParseGlobalValueVector
2754 /// ::= TypeAndValue (',' TypeAndValue)*
2755 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2757 if (Lex.getKind() == lltok::rbrace ||
2758 Lex.getKind() == lltok::rsquare ||
2759 Lex.getKind() == lltok::greater ||
2760 Lex.getKind() == lltok::rparen)
2764 if (ParseGlobalTypeAndValue(C)) return true;
2767 while (EatIfPresent(lltok::comma)) {
2768 if (ParseGlobalTypeAndValue(C)) return true;
2775 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2776 assert(Lex.getKind() == lltok::lbrace);
2779 SmallVector<Value*, 16> Elts;
2780 if (ParseMDNodeVector(Elts, PFS) ||
2781 ParseToken(lltok::rbrace, "expected end of metadata node"))
2784 ID.MDNodeVal = MDNode::get(Context, Elts);
2785 ID.Kind = ValID::t_MDNode;
2789 /// ParseMetadataValue
2793 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2794 assert(Lex.getKind() == lltok::exclaim);
2799 if (Lex.getKind() == lltok::lbrace)
2800 return ParseMetadataListValue(ID, PFS);
2802 // Standalone metadata reference
2804 if (Lex.getKind() == lltok::APSInt) {
2805 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2806 ID.Kind = ValID::t_MDNode;
2811 // ::= '!' STRINGCONSTANT
2812 if (ParseMDString(ID.MDStringVal)) return true;
2813 ID.Kind = ValID::t_MDString;
2818 //===----------------------------------------------------------------------===//
2819 // Function Parsing.
2820 //===----------------------------------------------------------------------===//
2822 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2823 PerFunctionState *PFS) {
2824 if (Ty->isFunctionTy())
2825 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2828 case ValID::t_LocalID:
2829 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2830 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2832 case ValID::t_LocalName:
2833 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2834 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2836 case ValID::t_InlineAsm: {
2837 PointerType *PTy = dyn_cast<PointerType>(Ty);
2839 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2840 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2841 return Error(ID.Loc, "invalid type for inline asm constraint string");
2842 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2843 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2846 case ValID::t_MDNode:
2847 if (!Ty->isMetadataTy())
2848 return Error(ID.Loc, "metadata value must have metadata type");
2851 case ValID::t_MDString:
2852 if (!Ty->isMetadataTy())
2853 return Error(ID.Loc, "metadata value must have metadata type");
2856 case ValID::t_GlobalName:
2857 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2859 case ValID::t_GlobalID:
2860 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2862 case ValID::t_APSInt:
2863 if (!Ty->isIntegerTy())
2864 return Error(ID.Loc, "integer constant must have integer type");
2865 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2866 V = ConstantInt::get(Context, ID.APSIntVal);
2868 case ValID::t_APFloat:
2869 if (!Ty->isFloatingPointTy() ||
2870 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2871 return Error(ID.Loc, "floating point constant invalid for type");
2873 // The lexer has no type info, so builds all half, float, and double FP
2874 // constants as double. Fix this here. Long double does not need this.
2875 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2878 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2880 else if (Ty->isFloatTy())
2881 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2884 V = ConstantFP::get(Context, ID.APFloatVal);
2886 if (V->getType() != Ty)
2887 return Error(ID.Loc, "floating point constant does not have type '" +
2888 getTypeString(Ty) + "'");
2892 if (!Ty->isPointerTy())
2893 return Error(ID.Loc, "null must be a pointer type");
2894 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2896 case ValID::t_Undef:
2897 // FIXME: LabelTy should not be a first-class type.
2898 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2899 return Error(ID.Loc, "invalid type for undef constant");
2900 V = UndefValue::get(Ty);
2902 case ValID::t_EmptyArray:
2903 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2904 return Error(ID.Loc, "invalid empty array initializer");
2905 V = UndefValue::get(Ty);
2908 // FIXME: LabelTy should not be a first-class type.
2909 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2910 return Error(ID.Loc, "invalid type for null constant");
2911 V = Constant::getNullValue(Ty);
2913 case ValID::t_Constant:
2914 if (ID.ConstantVal->getType() != Ty)
2915 return Error(ID.Loc, "constant expression type mismatch");
2919 case ValID::t_ConstantStruct:
2920 case ValID::t_PackedConstantStruct:
2921 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2922 if (ST->getNumElements() != ID.UIntVal)
2923 return Error(ID.Loc,
2924 "initializer with struct type has wrong # elements");
2925 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2926 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2928 // Verify that the elements are compatible with the structtype.
2929 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2930 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2931 return Error(ID.Loc, "element " + Twine(i) +
2932 " of struct initializer doesn't match struct element type");
2934 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2937 return Error(ID.Loc, "constant expression type mismatch");
2940 llvm_unreachable("Invalid ValID");
2943 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2946 return ParseValID(ID, PFS) ||
2947 ConvertValIDToValue(Ty, ID, V, PFS);
2950 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2952 return ParseType(Ty) ||
2953 ParseValue(Ty, V, PFS);
2956 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2957 PerFunctionState &PFS) {
2960 if (ParseTypeAndValue(V, PFS)) return true;
2961 if (!isa<BasicBlock>(V))
2962 return Error(Loc, "expected a basic block");
2963 BB = cast<BasicBlock>(V);
2969 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2970 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2971 /// OptionalAlign OptGC OptionalPrefix
2972 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2973 // Parse the linkage.
2974 LocTy LinkageLoc = Lex.getLoc();
2977 unsigned Visibility;
2978 unsigned DLLStorageClass;
2979 AttrBuilder RetAttrs;
2982 LocTy RetTypeLoc = Lex.getLoc();
2983 if (ParseOptionalLinkage(Linkage) ||
2984 ParseOptionalVisibility(Visibility) ||
2985 ParseOptionalDLLStorageClass(DLLStorageClass) ||
2986 ParseOptionalCallingConv(CC) ||
2987 ParseOptionalReturnAttrs(RetAttrs) ||
2988 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2991 // Verify that the linkage is ok.
2992 switch ((GlobalValue::LinkageTypes)Linkage) {
2993 case GlobalValue::ExternalLinkage:
2994 break; // always ok.
2995 case GlobalValue::ExternalWeakLinkage:
2997 return Error(LinkageLoc, "invalid linkage for function definition");
2999 case GlobalValue::PrivateLinkage:
3000 case GlobalValue::InternalLinkage:
3001 case GlobalValue::AvailableExternallyLinkage:
3002 case GlobalValue::LinkOnceAnyLinkage:
3003 case GlobalValue::LinkOnceODRLinkage:
3004 case GlobalValue::WeakAnyLinkage:
3005 case GlobalValue::WeakODRLinkage:
3007 return Error(LinkageLoc, "invalid linkage for function declaration");
3009 case GlobalValue::AppendingLinkage:
3010 case GlobalValue::CommonLinkage:
3011 return Error(LinkageLoc, "invalid function linkage type");
3014 if (!FunctionType::isValidReturnType(RetType))
3015 return Error(RetTypeLoc, "invalid function return type");
3017 LocTy NameLoc = Lex.getLoc();
3019 std::string FunctionName;
3020 if (Lex.getKind() == lltok::GlobalVar) {
3021 FunctionName = Lex.getStrVal();
3022 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3023 unsigned NameID = Lex.getUIntVal();
3025 if (NameID != NumberedVals.size())
3026 return TokError("function expected to be numbered '%" +
3027 Twine(NumberedVals.size()) + "'");
3029 return TokError("expected function name");
3034 if (Lex.getKind() != lltok::lparen)
3035 return TokError("expected '(' in function argument list");
3037 SmallVector<ArgInfo, 8> ArgList;
3039 AttrBuilder FuncAttrs;
3040 std::vector<unsigned> FwdRefAttrGrps;
3042 std::string Section;
3046 LocTy UnnamedAddrLoc;
3047 Constant *Prefix = 0;
3049 if (ParseArgumentList(ArgList, isVarArg) ||
3050 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3052 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3054 (EatIfPresent(lltok::kw_section) &&
3055 ParseStringConstant(Section)) ||
3056 ParseOptionalAlignment(Alignment) ||
3057 (EatIfPresent(lltok::kw_gc) &&
3058 ParseStringConstant(GC)) ||
3059 (EatIfPresent(lltok::kw_prefix) &&
3060 ParseGlobalTypeAndValue(Prefix)))
3063 if (FuncAttrs.contains(Attribute::Builtin))
3064 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3066 // If the alignment was parsed as an attribute, move to the alignment field.
3067 if (FuncAttrs.hasAlignmentAttr()) {
3068 Alignment = FuncAttrs.getAlignment();
3069 FuncAttrs.removeAttribute(Attribute::Alignment);
3072 // Okay, if we got here, the function is syntactically valid. Convert types
3073 // and do semantic checks.
3074 std::vector<Type*> ParamTypeList;
3075 SmallVector<AttributeSet, 8> Attrs;
3077 if (RetAttrs.hasAttributes())
3078 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3079 AttributeSet::ReturnIndex,
3082 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3083 ParamTypeList.push_back(ArgList[i].Ty);
3084 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3085 AttrBuilder B(ArgList[i].Attrs, i + 1);
3086 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3090 if (FuncAttrs.hasAttributes())
3091 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3092 AttributeSet::FunctionIndex,
3095 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3097 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3098 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3101 FunctionType::get(RetType, ParamTypeList, isVarArg);
3102 PointerType *PFT = PointerType::getUnqual(FT);
3105 if (!FunctionName.empty()) {
3106 // If this was a definition of a forward reference, remove the definition
3107 // from the forward reference table and fill in the forward ref.
3108 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3109 ForwardRefVals.find(FunctionName);
3110 if (FRVI != ForwardRefVals.end()) {
3111 Fn = M->getFunction(FunctionName);
3113 return Error(FRVI->second.second, "invalid forward reference to "
3114 "function as global value!");
3115 if (Fn->getType() != PFT)
3116 return Error(FRVI->second.second, "invalid forward reference to "
3117 "function '" + FunctionName + "' with wrong type!");
3119 ForwardRefVals.erase(FRVI);
3120 } else if ((Fn = M->getFunction(FunctionName))) {
3121 // Reject redefinitions.
3122 return Error(NameLoc, "invalid redefinition of function '" +
3123 FunctionName + "'");
3124 } else if (M->getNamedValue(FunctionName)) {
3125 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3129 // If this is a definition of a forward referenced function, make sure the
3131 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3132 = ForwardRefValIDs.find(NumberedVals.size());
3133 if (I != ForwardRefValIDs.end()) {
3134 Fn = cast<Function>(I->second.first);
3135 if (Fn->getType() != PFT)
3136 return Error(NameLoc, "type of definition and forward reference of '@" +
3137 Twine(NumberedVals.size()) + "' disagree");
3138 ForwardRefValIDs.erase(I);
3143 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3144 else // Move the forward-reference to the correct spot in the module.
3145 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3147 if (FunctionName.empty())
3148 NumberedVals.push_back(Fn);
3150 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3151 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3152 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3153 Fn->setCallingConv(CC);
3154 Fn->setAttributes(PAL);
3155 Fn->setUnnamedAddr(UnnamedAddr);
3156 Fn->setAlignment(Alignment);
3157 Fn->setSection(Section);
3158 if (!GC.empty()) Fn->setGC(GC.c_str());
3159 Fn->setPrefixData(Prefix);
3160 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3162 // Add all of the arguments we parsed to the function.
3163 Function::arg_iterator ArgIt = Fn->arg_begin();
3164 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3165 // If the argument has a name, insert it into the argument symbol table.
3166 if (ArgList[i].Name.empty()) continue;
3168 // Set the name, if it conflicted, it will be auto-renamed.
3169 ArgIt->setName(ArgList[i].Name);
3171 if (ArgIt->getName() != ArgList[i].Name)
3172 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3173 ArgList[i].Name + "'");
3180 /// ParseFunctionBody
3181 /// ::= '{' BasicBlock+ '}'
3183 bool LLParser::ParseFunctionBody(Function &Fn) {
3184 if (Lex.getKind() != lltok::lbrace)
3185 return TokError("expected '{' in function body");
3186 Lex.Lex(); // eat the {.
3188 int FunctionNumber = -1;
3189 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3191 PerFunctionState PFS(*this, Fn, FunctionNumber);
3193 // We need at least one basic block.
3194 if (Lex.getKind() == lltok::rbrace)
3195 return TokError("function body requires at least one basic block");
3197 while (Lex.getKind() != lltok::rbrace)
3198 if (ParseBasicBlock(PFS)) return true;
3203 // Verify function is ok.
3204 return PFS.FinishFunction();
3208 /// ::= LabelStr? Instruction*
3209 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3210 // If this basic block starts out with a name, remember it.
3212 LocTy NameLoc = Lex.getLoc();
3213 if (Lex.getKind() == lltok::LabelStr) {
3214 Name = Lex.getStrVal();
3218 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3219 if (BB == 0) return true;
3221 std::string NameStr;
3223 // Parse the instructions in this block until we get a terminator.
3226 // This instruction may have three possibilities for a name: a) none
3227 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3228 LocTy NameLoc = Lex.getLoc();
3232 if (Lex.getKind() == lltok::LocalVarID) {
3233 NameID = Lex.getUIntVal();
3235 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3237 } else if (Lex.getKind() == lltok::LocalVar) {
3238 NameStr = Lex.getStrVal();
3240 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3244 switch (ParseInstruction(Inst, BB, PFS)) {
3245 default: llvm_unreachable("Unknown ParseInstruction result!");
3246 case InstError: return true;
3248 BB->getInstList().push_back(Inst);
3250 // With a normal result, we check to see if the instruction is followed by
3251 // a comma and metadata.
3252 if (EatIfPresent(lltok::comma))
3253 if (ParseInstructionMetadata(Inst, &PFS))
3256 case InstExtraComma:
3257 BB->getInstList().push_back(Inst);
3259 // If the instruction parser ate an extra comma at the end of it, it
3260 // *must* be followed by metadata.
3261 if (ParseInstructionMetadata(Inst, &PFS))
3266 // Set the name on the instruction.
3267 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3268 } while (!isa<TerminatorInst>(Inst));
3273 //===----------------------------------------------------------------------===//
3274 // Instruction Parsing.
3275 //===----------------------------------------------------------------------===//
3277 /// ParseInstruction - Parse one of the many different instructions.
3279 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3280 PerFunctionState &PFS) {
3281 lltok::Kind Token = Lex.getKind();
3282 if (Token == lltok::Eof)
3283 return TokError("found end of file when expecting more instructions");
3284 LocTy Loc = Lex.getLoc();
3285 unsigned KeywordVal = Lex.getUIntVal();
3286 Lex.Lex(); // Eat the keyword.
3289 default: return Error(Loc, "expected instruction opcode");
3290 // Terminator Instructions.
3291 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3292 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3293 case lltok::kw_br: return ParseBr(Inst, PFS);
3294 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3295 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3296 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3297 case lltok::kw_resume: return ParseResume(Inst, PFS);
3298 // Binary Operators.
3302 case lltok::kw_shl: {
3303 bool NUW = EatIfPresent(lltok::kw_nuw);
3304 bool NSW = EatIfPresent(lltok::kw_nsw);
3305 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3307 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3309 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3310 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3313 case lltok::kw_fadd:
3314 case lltok::kw_fsub:
3315 case lltok::kw_fmul:
3316 case lltok::kw_fdiv:
3317 case lltok::kw_frem: {
3318 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3319 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3323 Inst->setFastMathFlags(FMF);
3327 case lltok::kw_sdiv:
3328 case lltok::kw_udiv:
3329 case lltok::kw_lshr:
3330 case lltok::kw_ashr: {
3331 bool Exact = EatIfPresent(lltok::kw_exact);
3333 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3334 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3338 case lltok::kw_urem:
3339 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3342 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3343 case lltok::kw_icmp:
3344 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3346 case lltok::kw_trunc:
3347 case lltok::kw_zext:
3348 case lltok::kw_sext:
3349 case lltok::kw_fptrunc:
3350 case lltok::kw_fpext:
3351 case lltok::kw_bitcast:
3352 case lltok::kw_addrspacecast:
3353 case lltok::kw_uitofp:
3354 case lltok::kw_sitofp:
3355 case lltok::kw_fptoui:
3356 case lltok::kw_fptosi:
3357 case lltok::kw_inttoptr:
3358 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3360 case lltok::kw_select: return ParseSelect(Inst, PFS);
3361 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3362 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3363 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3364 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3365 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3366 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3367 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3368 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3370 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3371 case lltok::kw_load: return ParseLoad(Inst, PFS);
3372 case lltok::kw_store: return ParseStore(Inst, PFS);
3373 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3374 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3375 case lltok::kw_fence: return ParseFence(Inst, PFS);
3376 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3377 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3378 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3382 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3383 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3384 if (Opc == Instruction::FCmp) {
3385 switch (Lex.getKind()) {
3386 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3387 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3388 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3389 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3390 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3391 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3392 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3393 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3394 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3395 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3396 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3397 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3398 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3399 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3400 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3401 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3402 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3405 switch (Lex.getKind()) {
3406 default: return TokError("expected icmp predicate (e.g. 'eq')");
3407 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3408 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3409 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3410 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3411 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3412 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3413 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3414 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3415 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3416 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3423 //===----------------------------------------------------------------------===//
3424 // Terminator Instructions.
3425 //===----------------------------------------------------------------------===//
3427 /// ParseRet - Parse a return instruction.
3428 /// ::= 'ret' void (',' !dbg, !1)*
3429 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3430 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3431 PerFunctionState &PFS) {
3432 SMLoc TypeLoc = Lex.getLoc();
3434 if (ParseType(Ty, true /*void allowed*/)) return true;
3436 Type *ResType = PFS.getFunction().getReturnType();
3438 if (Ty->isVoidTy()) {
3439 if (!ResType->isVoidTy())
3440 return Error(TypeLoc, "value doesn't match function result type '" +
3441 getTypeString(ResType) + "'");
3443 Inst = ReturnInst::Create(Context);
3448 if (ParseValue(Ty, RV, PFS)) return true;
3450 if (ResType != RV->getType())
3451 return Error(TypeLoc, "value doesn't match function result type '" +
3452 getTypeString(ResType) + "'");
3454 Inst = ReturnInst::Create(Context, RV);
3460 /// ::= 'br' TypeAndValue
3461 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3462 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3465 BasicBlock *Op1, *Op2;
3466 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3468 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3469 Inst = BranchInst::Create(BB);
3473 if (Op0->getType() != Type::getInt1Ty(Context))
3474 return Error(Loc, "branch condition must have 'i1' type");
3476 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3477 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3478 ParseToken(lltok::comma, "expected ',' after true destination") ||
3479 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3482 Inst = BranchInst::Create(Op1, Op2, Op0);
3488 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3490 /// ::= (TypeAndValue ',' TypeAndValue)*
3491 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3492 LocTy CondLoc, BBLoc;
3494 BasicBlock *DefaultBB;
3495 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3496 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3497 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3498 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3501 if (!Cond->getType()->isIntegerTy())
3502 return Error(CondLoc, "switch condition must have integer type");
3504 // Parse the jump table pairs.
3505 SmallPtrSet<Value*, 32> SeenCases;
3506 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3507 while (Lex.getKind() != lltok::rsquare) {
3511 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3512 ParseToken(lltok::comma, "expected ',' after case value") ||
3513 ParseTypeAndBasicBlock(DestBB, PFS))
3516 if (!SeenCases.insert(Constant))
3517 return Error(CondLoc, "duplicate case value in switch");
3518 if (!isa<ConstantInt>(Constant))
3519 return Error(CondLoc, "case value is not a constant integer");
3521 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3524 Lex.Lex(); // Eat the ']'.
3526 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3527 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3528 SI->addCase(Table[i].first, Table[i].second);
3535 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3536 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3539 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3540 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3541 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3544 if (!Address->getType()->isPointerTy())
3545 return Error(AddrLoc, "indirectbr address must have pointer type");
3547 // Parse the destination list.
3548 SmallVector<BasicBlock*, 16> DestList;
3550 if (Lex.getKind() != lltok::rsquare) {
3552 if (ParseTypeAndBasicBlock(DestBB, PFS))
3554 DestList.push_back(DestBB);
3556 while (EatIfPresent(lltok::comma)) {
3557 if (ParseTypeAndBasicBlock(DestBB, PFS))
3559 DestList.push_back(DestBB);
3563 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3566 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3567 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3568 IBI->addDestination(DestList[i]);
3575 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3576 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3577 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3578 LocTy CallLoc = Lex.getLoc();
3579 AttrBuilder RetAttrs, FnAttrs;
3580 std::vector<unsigned> FwdRefAttrGrps;
3586 SmallVector<ParamInfo, 16> ArgList;
3588 BasicBlock *NormalBB, *UnwindBB;
3589 if (ParseOptionalCallingConv(CC) ||
3590 ParseOptionalReturnAttrs(RetAttrs) ||
3591 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3592 ParseValID(CalleeID) ||
3593 ParseParameterList(ArgList, PFS) ||
3594 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3596 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3597 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3598 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3599 ParseTypeAndBasicBlock(UnwindBB, PFS))
3602 // If RetType is a non-function pointer type, then this is the short syntax
3603 // for the call, which means that RetType is just the return type. Infer the
3604 // rest of the function argument types from the arguments that are present.
3605 PointerType *PFTy = 0;
3606 FunctionType *Ty = 0;
3607 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3608 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3609 // Pull out the types of all of the arguments...
3610 std::vector<Type*> ParamTypes;
3611 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3612 ParamTypes.push_back(ArgList[i].V->getType());
3614 if (!FunctionType::isValidReturnType(RetType))
3615 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3617 Ty = FunctionType::get(RetType, ParamTypes, false);
3618 PFTy = PointerType::getUnqual(Ty);
3621 // Look up the callee.
3623 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3625 // Set up the Attribute for the function.
3626 SmallVector<AttributeSet, 8> Attrs;
3627 if (RetAttrs.hasAttributes())
3628 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3629 AttributeSet::ReturnIndex,
3632 SmallVector<Value*, 8> Args;
3634 // Loop through FunctionType's arguments and ensure they are specified
3635 // correctly. Also, gather any parameter attributes.
3636 FunctionType::param_iterator I = Ty->param_begin();
3637 FunctionType::param_iterator E = Ty->param_end();
3638 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3639 Type *ExpectedTy = 0;
3642 } else if (!Ty->isVarArg()) {
3643 return Error(ArgList[i].Loc, "too many arguments specified");
3646 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3647 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3648 getTypeString(ExpectedTy) + "'");
3649 Args.push_back(ArgList[i].V);
3650 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3651 AttrBuilder B(ArgList[i].Attrs, i + 1);
3652 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3657 return Error(CallLoc, "not enough parameters specified for call");
3659 if (FnAttrs.hasAttributes())
3660 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3661 AttributeSet::FunctionIndex,
3664 // Finish off the Attribute and check them
3665 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3667 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3668 II->setCallingConv(CC);
3669 II->setAttributes(PAL);
3670 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3676 /// ::= 'resume' TypeAndValue
3677 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3678 Value *Exn; LocTy ExnLoc;
3679 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3682 ResumeInst *RI = ResumeInst::Create(Exn);
3687 //===----------------------------------------------------------------------===//
3688 // Binary Operators.
3689 //===----------------------------------------------------------------------===//
3692 /// ::= ArithmeticOps TypeAndValue ',' Value
3694 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3695 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3696 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3697 unsigned Opc, unsigned OperandType) {
3698 LocTy Loc; Value *LHS, *RHS;
3699 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3700 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3701 ParseValue(LHS->getType(), RHS, PFS))
3705 switch (OperandType) {
3706 default: llvm_unreachable("Unknown operand type!");
3707 case 0: // int or FP.
3708 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3709 LHS->getType()->isFPOrFPVectorTy();
3711 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3712 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3716 return Error(Loc, "invalid operand type for instruction");
3718 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3723 /// ::= ArithmeticOps TypeAndValue ',' Value {
3724 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3726 LocTy Loc; Value *LHS, *RHS;
3727 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3728 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3729 ParseValue(LHS->getType(), RHS, PFS))
3732 if (!LHS->getType()->isIntOrIntVectorTy())
3733 return Error(Loc,"instruction requires integer or integer vector operands");
3735 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3741 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3742 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3743 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3745 // Parse the integer/fp comparison predicate.
3749 if (ParseCmpPredicate(Pred, Opc) ||
3750 ParseTypeAndValue(LHS, Loc, PFS) ||
3751 ParseToken(lltok::comma, "expected ',' after compare value") ||
3752 ParseValue(LHS->getType(), RHS, PFS))
3755 if (Opc == Instruction::FCmp) {
3756 if (!LHS->getType()->isFPOrFPVectorTy())
3757 return Error(Loc, "fcmp requires floating point operands");
3758 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3760 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3761 if (!LHS->getType()->isIntOrIntVectorTy() &&
3762 !LHS->getType()->getScalarType()->isPointerTy())
3763 return Error(Loc, "icmp requires integer operands");
3764 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3769 //===----------------------------------------------------------------------===//
3770 // Other Instructions.
3771 //===----------------------------------------------------------------------===//
3775 /// ::= CastOpc TypeAndValue 'to' Type
3776 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3781 if (ParseTypeAndValue(Op, Loc, PFS) ||
3782 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3786 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3787 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3788 return Error(Loc, "invalid cast opcode for cast from '" +
3789 getTypeString(Op->getType()) + "' to '" +
3790 getTypeString(DestTy) + "'");
3792 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3797 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3798 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3800 Value *Op0, *Op1, *Op2;
3801 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3802 ParseToken(lltok::comma, "expected ',' after select condition") ||
3803 ParseTypeAndValue(Op1, PFS) ||
3804 ParseToken(lltok::comma, "expected ',' after select value") ||
3805 ParseTypeAndValue(Op2, PFS))
3808 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3809 return Error(Loc, Reason);
3811 Inst = SelectInst::Create(Op0, Op1, Op2);
3816 /// ::= 'va_arg' TypeAndValue ',' Type
3817 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3821 if (ParseTypeAndValue(Op, PFS) ||
3822 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3823 ParseType(EltTy, TypeLoc))
3826 if (!EltTy->isFirstClassType())
3827 return Error(TypeLoc, "va_arg requires operand with first class type");
3829 Inst = new VAArgInst(Op, EltTy);
3833 /// ParseExtractElement
3834 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3835 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3838 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3839 ParseToken(lltok::comma, "expected ',' after extract value") ||
3840 ParseTypeAndValue(Op1, PFS))
3843 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3844 return Error(Loc, "invalid extractelement operands");
3846 Inst = ExtractElementInst::Create(Op0, Op1);
3850 /// ParseInsertElement
3851 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3852 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3854 Value *Op0, *Op1, *Op2;
3855 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3856 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3857 ParseTypeAndValue(Op1, PFS) ||
3858 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3859 ParseTypeAndValue(Op2, PFS))
3862 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3863 return Error(Loc, "invalid insertelement operands");
3865 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3869 /// ParseShuffleVector
3870 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3871 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3873 Value *Op0, *Op1, *Op2;
3874 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3875 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3876 ParseTypeAndValue(Op1, PFS) ||
3877 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3878 ParseTypeAndValue(Op2, PFS))
3881 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3882 return Error(Loc, "invalid shufflevector operands");
3884 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3889 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3890 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3891 Type *Ty = 0; LocTy TypeLoc;
3894 if (ParseType(Ty, TypeLoc) ||
3895 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3896 ParseValue(Ty, Op0, PFS) ||
3897 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3898 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3899 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3902 bool AteExtraComma = false;
3903 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3905 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3907 if (!EatIfPresent(lltok::comma))
3910 if (Lex.getKind() == lltok::MetadataVar) {
3911 AteExtraComma = true;
3915 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3916 ParseValue(Ty, Op0, PFS) ||
3917 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3918 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3919 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3923 if (!Ty->isFirstClassType())
3924 return Error(TypeLoc, "phi node must have first class type");
3926 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3927 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3928 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3930 return AteExtraComma ? InstExtraComma : InstNormal;
3934 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3936 /// ::= 'catch' TypeAndValue
3938 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3939 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3940 Type *Ty = 0; LocTy TyLoc;
3941 Value *PersFn; LocTy PersFnLoc;
3943 if (ParseType(Ty, TyLoc) ||
3944 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3945 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3948 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3949 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3951 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3952 LandingPadInst::ClauseType CT;
3953 if (EatIfPresent(lltok::kw_catch))
3954 CT = LandingPadInst::Catch;
3955 else if (EatIfPresent(lltok::kw_filter))
3956 CT = LandingPadInst::Filter;
3958 return TokError("expected 'catch' or 'filter' clause type");
3960 Value *V; LocTy VLoc;
3961 if (ParseTypeAndValue(V, VLoc, PFS)) {
3966 // A 'catch' type expects a non-array constant. A filter clause expects an
3968 if (CT == LandingPadInst::Catch) {
3969 if (isa<ArrayType>(V->getType()))
3970 Error(VLoc, "'catch' clause has an invalid type");
3972 if (!isa<ArrayType>(V->getType()))
3973 Error(VLoc, "'filter' clause has an invalid type");
3984 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3985 /// ParameterList OptionalAttrs
3986 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3988 AttrBuilder RetAttrs, FnAttrs;
3989 std::vector<unsigned> FwdRefAttrGrps;
3995 SmallVector<ParamInfo, 16> ArgList;
3996 LocTy CallLoc = Lex.getLoc();
3998 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3999 ParseOptionalCallingConv(CC) ||
4000 ParseOptionalReturnAttrs(RetAttrs) ||
4001 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4002 ParseValID(CalleeID) ||
4003 ParseParameterList(ArgList, PFS) ||
4004 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4008 // If RetType is a non-function pointer type, then this is the short syntax
4009 // for the call, which means that RetType is just the return type. Infer the
4010 // rest of the function argument types from the arguments that are present.
4011 PointerType *PFTy = 0;
4012 FunctionType *Ty = 0;
4013 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4014 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4015 // Pull out the types of all of the arguments...
4016 std::vector<Type*> ParamTypes;
4017 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4018 ParamTypes.push_back(ArgList[i].V->getType());
4020 if (!FunctionType::isValidReturnType(RetType))
4021 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4023 Ty = FunctionType::get(RetType, ParamTypes, false);
4024 PFTy = PointerType::getUnqual(Ty);
4027 // Look up the callee.
4029 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4031 // Set up the Attribute for the function.
4032 SmallVector<AttributeSet, 8> Attrs;
4033 if (RetAttrs.hasAttributes())
4034 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4035 AttributeSet::ReturnIndex,
4038 SmallVector<Value*, 8> Args;
4040 // Loop through FunctionType's arguments and ensure they are specified
4041 // correctly. Also, gather any parameter attributes.
4042 FunctionType::param_iterator I = Ty->param_begin();
4043 FunctionType::param_iterator E = Ty->param_end();
4044 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4045 Type *ExpectedTy = 0;
4048 } else if (!Ty->isVarArg()) {
4049 return Error(ArgList[i].Loc, "too many arguments specified");
4052 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4053 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4054 getTypeString(ExpectedTy) + "'");
4055 Args.push_back(ArgList[i].V);
4056 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4057 AttrBuilder B(ArgList[i].Attrs, i + 1);
4058 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4063 return Error(CallLoc, "not enough parameters specified for call");
4065 if (FnAttrs.hasAttributes())
4066 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4067 AttributeSet::FunctionIndex,
4070 // Finish off the Attribute and check them
4071 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4073 CallInst *CI = CallInst::Create(Callee, Args);
4074 CI->setTailCall(isTail);
4075 CI->setCallingConv(CC);
4076 CI->setAttributes(PAL);
4077 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4082 //===----------------------------------------------------------------------===//
4083 // Memory Instructions.
4084 //===----------------------------------------------------------------------===//
4087 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4088 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4091 unsigned Alignment = 0;
4094 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4096 if (ParseType(Ty)) return true;
4098 bool AteExtraComma = false;
4099 if (EatIfPresent(lltok::comma)) {
4100 if (Lex.getKind() == lltok::kw_align) {
4101 if (ParseOptionalAlignment(Alignment)) return true;
4102 } else if (Lex.getKind() == lltok::MetadataVar) {
4103 AteExtraComma = true;
4105 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4106 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4111 if (Size && !Size->getType()->isIntegerTy())
4112 return Error(SizeLoc, "element count must have integer type");
4114 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4115 AI->setUsedWithInAlloca(IsInAlloca);
4117 return AteExtraComma ? InstExtraComma : InstNormal;
4121 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4122 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4123 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4124 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4125 Value *Val; LocTy Loc;
4126 unsigned Alignment = 0;
4127 bool AteExtraComma = false;
4128 bool isAtomic = false;
4129 AtomicOrdering Ordering = NotAtomic;
4130 SynchronizationScope Scope = CrossThread;
4132 if (Lex.getKind() == lltok::kw_atomic) {
4137 bool isVolatile = false;
4138 if (Lex.getKind() == lltok::kw_volatile) {
4143 if (ParseTypeAndValue(Val, Loc, PFS) ||
4144 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4145 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4148 if (!Val->getType()->isPointerTy() ||
4149 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4150 return Error(Loc, "load operand must be a pointer to a first class type");
4151 if (isAtomic && !Alignment)
4152 return Error(Loc, "atomic load must have explicit non-zero alignment");
4153 if (Ordering == Release || Ordering == AcquireRelease)
4154 return Error(Loc, "atomic load cannot use Release ordering");
4156 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4157 return AteExtraComma ? InstExtraComma : InstNormal;
4162 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4163 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4164 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4165 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4166 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4167 unsigned Alignment = 0;
4168 bool AteExtraComma = false;
4169 bool isAtomic = false;
4170 AtomicOrdering Ordering = NotAtomic;
4171 SynchronizationScope Scope = CrossThread;
4173 if (Lex.getKind() == lltok::kw_atomic) {
4178 bool isVolatile = false;
4179 if (Lex.getKind() == lltok::kw_volatile) {
4184 if (ParseTypeAndValue(Val, Loc, PFS) ||
4185 ParseToken(lltok::comma, "expected ',' after store operand") ||
4186 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4187 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4188 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4191 if (!Ptr->getType()->isPointerTy())
4192 return Error(PtrLoc, "store operand must be a pointer");
4193 if (!Val->getType()->isFirstClassType())
4194 return Error(Loc, "store operand must be a first class value");
4195 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4196 return Error(Loc, "stored value and pointer type do not match");
4197 if (isAtomic && !Alignment)
4198 return Error(Loc, "atomic store must have explicit non-zero alignment");
4199 if (Ordering == Acquire || Ordering == AcquireRelease)
4200 return Error(Loc, "atomic store cannot use Acquire ordering");
4202 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4203 return AteExtraComma ? InstExtraComma : InstNormal;
4207 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4208 /// 'singlethread'? AtomicOrdering AtomicOrdering
4209 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4210 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4211 bool AteExtraComma = false;
4212 AtomicOrdering SuccessOrdering = NotAtomic;
4213 AtomicOrdering FailureOrdering = NotAtomic;
4214 SynchronizationScope Scope = CrossThread;
4215 bool isVolatile = false;
4217 if (EatIfPresent(lltok::kw_volatile))
4220 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4221 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4222 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4223 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4224 ParseTypeAndValue(New, NewLoc, PFS) ||
4225 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4226 ParseOrdering(FailureOrdering))
4229 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4230 return TokError("cmpxchg cannot be unordered");
4231 if (SuccessOrdering < FailureOrdering)
4232 return TokError("cmpxchg must be at least as ordered on success as failure");
4233 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4234 return TokError("cmpxchg failure ordering cannot include release semantics");
4235 if (!Ptr->getType()->isPointerTy())
4236 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4237 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4238 return Error(CmpLoc, "compare value and pointer type do not match");
4239 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4240 return Error(NewLoc, "new value and pointer type do not match");
4241 if (!New->getType()->isIntegerTy())
4242 return Error(NewLoc, "cmpxchg operand must be an integer");
4243 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4244 if (Size < 8 || (Size & (Size - 1)))
4245 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4248 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4249 FailureOrdering, Scope);
4250 CXI->setVolatile(isVolatile);
4252 return AteExtraComma ? InstExtraComma : InstNormal;
4256 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4257 /// 'singlethread'? AtomicOrdering
4258 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4259 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4260 bool AteExtraComma = false;
4261 AtomicOrdering Ordering = NotAtomic;
4262 SynchronizationScope Scope = CrossThread;
4263 bool isVolatile = false;
4264 AtomicRMWInst::BinOp Operation;
4266 if (EatIfPresent(lltok::kw_volatile))
4269 switch (Lex.getKind()) {
4270 default: return TokError("expected binary operation in atomicrmw");
4271 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4272 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4273 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4274 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4275 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4276 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4277 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4278 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4279 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4280 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4281 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4283 Lex.Lex(); // Eat the operation.
4285 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4286 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4287 ParseTypeAndValue(Val, ValLoc, PFS) ||
4288 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4291 if (Ordering == Unordered)
4292 return TokError("atomicrmw cannot be unordered");
4293 if (!Ptr->getType()->isPointerTy())
4294 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4295 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4296 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4297 if (!Val->getType()->isIntegerTy())
4298 return Error(ValLoc, "atomicrmw operand must be an integer");
4299 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4300 if (Size < 8 || (Size & (Size - 1)))
4301 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4304 AtomicRMWInst *RMWI =
4305 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4306 RMWI->setVolatile(isVolatile);
4308 return AteExtraComma ? InstExtraComma : InstNormal;
4312 /// ::= 'fence' 'singlethread'? AtomicOrdering
4313 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4314 AtomicOrdering Ordering = NotAtomic;
4315 SynchronizationScope Scope = CrossThread;
4316 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4319 if (Ordering == Unordered)
4320 return TokError("fence cannot be unordered");
4321 if (Ordering == Monotonic)
4322 return TokError("fence cannot be monotonic");
4324 Inst = new FenceInst(Context, Ordering, Scope);
4328 /// ParseGetElementPtr
4329 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4330 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4335 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4337 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4339 Type *BaseType = Ptr->getType();
4340 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4341 if (!BasePointerType)
4342 return Error(Loc, "base of getelementptr must be a pointer");
4344 SmallVector<Value*, 16> Indices;
4345 bool AteExtraComma = false;
4346 while (EatIfPresent(lltok::comma)) {
4347 if (Lex.getKind() == lltok::MetadataVar) {
4348 AteExtraComma = true;
4351 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4352 if (!Val->getType()->getScalarType()->isIntegerTy())
4353 return Error(EltLoc, "getelementptr index must be an integer");
4354 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4355 return Error(EltLoc, "getelementptr index type missmatch");
4356 if (Val->getType()->isVectorTy()) {
4357 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4358 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4359 if (ValNumEl != PtrNumEl)
4360 return Error(EltLoc,
4361 "getelementptr vector index has a wrong number of elements");
4363 Indices.push_back(Val);
4366 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4367 return Error(Loc, "base element of getelementptr must be sized");
4369 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4370 return Error(Loc, "invalid getelementptr indices");
4371 Inst = GetElementPtrInst::Create(Ptr, Indices);
4373 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4374 return AteExtraComma ? InstExtraComma : InstNormal;
4377 /// ParseExtractValue
4378 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4379 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4380 Value *Val; LocTy Loc;
4381 SmallVector<unsigned, 4> Indices;
4383 if (ParseTypeAndValue(Val, Loc, PFS) ||
4384 ParseIndexList(Indices, AteExtraComma))
4387 if (!Val->getType()->isAggregateType())
4388 return Error(Loc, "extractvalue operand must be aggregate type");
4390 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4391 return Error(Loc, "invalid indices for extractvalue");
4392 Inst = ExtractValueInst::Create(Val, Indices);
4393 return AteExtraComma ? InstExtraComma : InstNormal;
4396 /// ParseInsertValue
4397 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4398 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4399 Value *Val0, *Val1; LocTy Loc0, Loc1;
4400 SmallVector<unsigned, 4> Indices;
4402 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4403 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4404 ParseTypeAndValue(Val1, Loc1, PFS) ||
4405 ParseIndexList(Indices, AteExtraComma))
4408 if (!Val0->getType()->isAggregateType())
4409 return Error(Loc0, "insertvalue operand must be aggregate type");
4411 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4412 return Error(Loc0, "invalid indices for insertvalue");
4413 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4414 return AteExtraComma ? InstExtraComma : InstNormal;
4417 //===----------------------------------------------------------------------===//
4418 // Embedded metadata.
4419 //===----------------------------------------------------------------------===//
4421 /// ParseMDNodeVector
4422 /// ::= Element (',' Element)*
4424 /// ::= 'null' | TypeAndValue
4425 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4426 PerFunctionState *PFS) {
4427 // Check for an empty list.
4428 if (Lex.getKind() == lltok::rbrace)
4432 // Null is a special case since it is typeless.
4433 if (EatIfPresent(lltok::kw_null)) {
4439 if (ParseTypeAndValue(V, PFS)) return true;
4441 } while (EatIfPresent(lltok::comma));