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/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_linker_private: // OptionalLinkage
250 case lltok::kw_linker_private_weak: // OptionalLinkage
251 case lltok::kw_internal: // 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 through visibility has been parsed already.
712 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
713 unsigned Linkage, bool HasLinkage,
714 unsigned Visibility, unsigned DLLStorageClass) {
716 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
717 GlobalVariable::ThreadLocalMode TLM;
718 LocTy UnnamedAddrLoc;
719 LocTy IsExternallyInitializedLoc;
723 if (ParseOptionalThreadLocal(TLM) ||
724 ParseOptionalAddrSpace(AddrSpace) ||
725 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
727 ParseOptionalToken(lltok::kw_externally_initialized,
728 IsExternallyInitialized,
729 &IsExternallyInitializedLoc) ||
730 ParseGlobalType(IsConstant) ||
731 ParseType(Ty, TyLoc))
734 // If the linkage is specified and is external, then no initializer is
737 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
738 Linkage != GlobalValue::ExternalLinkage)) {
739 if (ParseGlobalValue(Ty, Init))
743 if (Ty->isFunctionTy() || Ty->isLabelTy())
744 return Error(TyLoc, "invalid type for global variable");
746 GlobalVariable *GV = 0;
748 // See if the global was forward referenced, if so, use the global.
750 if (GlobalValue *GVal = M->getNamedValue(Name)) {
751 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
752 return Error(NameLoc, "redefinition of global '@" + Name + "'");
753 GV = cast<GlobalVariable>(GVal);
756 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
757 I = ForwardRefValIDs.find(NumberedVals.size());
758 if (I != ForwardRefValIDs.end()) {
759 GV = cast<GlobalVariable>(I->second.first);
760 ForwardRefValIDs.erase(I);
765 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
766 Name, 0, GlobalVariable::NotThreadLocal,
769 if (GV->getType()->getElementType() != Ty)
771 "forward reference and definition of global have different types");
773 // Move the forward-reference to the correct spot in the module.
774 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
778 NumberedVals.push_back(GV);
780 // Set the parsed properties on the global.
782 GV->setInitializer(Init);
783 GV->setConstant(IsConstant);
784 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
785 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
786 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
787 GV->setExternallyInitialized(IsExternallyInitialized);
788 GV->setThreadLocalMode(TLM);
789 GV->setUnnamedAddr(UnnamedAddr);
791 // Parse attributes on the global.
792 while (Lex.getKind() == lltok::comma) {
795 if (Lex.getKind() == lltok::kw_section) {
797 GV->setSection(Lex.getStrVal());
798 if (ParseToken(lltok::StringConstant, "expected global section string"))
800 } else if (Lex.getKind() == lltok::kw_align) {
802 if (ParseOptionalAlignment(Alignment)) return true;
803 GV->setAlignment(Alignment);
805 TokError("unknown global variable property!");
812 /// ParseUnnamedAttrGrp
813 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
814 bool LLParser::ParseUnnamedAttrGrp() {
815 assert(Lex.getKind() == lltok::kw_attributes);
816 LocTy AttrGrpLoc = Lex.getLoc();
819 assert(Lex.getKind() == lltok::AttrGrpID);
820 unsigned VarID = Lex.getUIntVal();
821 std::vector<unsigned> unused;
825 if (ParseToken(lltok::equal, "expected '=' here") ||
826 ParseToken(lltok::lbrace, "expected '{' here") ||
827 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
829 ParseToken(lltok::rbrace, "expected end of attribute group"))
832 if (!NumberedAttrBuilders[VarID].hasAttributes())
833 return Error(AttrGrpLoc, "attribute group has no attributes");
838 /// ParseFnAttributeValuePairs
839 /// ::= <attr> | <attr> '=' <value>
840 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
841 std::vector<unsigned> &FwdRefAttrGrps,
842 bool inAttrGrp, LocTy &BuiltinLoc) {
843 bool HaveError = false;
848 lltok::Kind Token = Lex.getKind();
849 if (Token == lltok::kw_builtin)
850 BuiltinLoc = Lex.getLoc();
853 if (!inAttrGrp) return HaveError;
854 return Error(Lex.getLoc(), "unterminated attribute group");
859 case lltok::AttrGrpID: {
860 // Allow a function to reference an attribute group:
862 // define void @foo() #1 { ... }
866 "cannot have an attribute group reference in an attribute group");
868 unsigned AttrGrpNum = Lex.getUIntVal();
869 if (inAttrGrp) break;
871 // Save the reference to the attribute group. We'll fill it in later.
872 FwdRefAttrGrps.push_back(AttrGrpNum);
875 // Target-dependent attributes:
876 case lltok::StringConstant: {
877 std::string Attr = Lex.getStrVal();
880 if (EatIfPresent(lltok::equal) &&
881 ParseStringConstant(Val))
884 B.addAttribute(Attr, Val);
888 // Target-independent attributes:
889 case lltok::kw_align: {
890 // As a hack, we allow function alignment to be initially parsed as an
891 // attribute on a function declaration/definition or added to an attribute
892 // group and later moved to the alignment field.
896 if (ParseToken(lltok::equal, "expected '=' here") ||
897 ParseUInt32(Alignment))
900 if (ParseOptionalAlignment(Alignment))
903 B.addAlignmentAttr(Alignment);
906 case lltok::kw_alignstack: {
910 if (ParseToken(lltok::equal, "expected '=' here") ||
911 ParseUInt32(Alignment))
914 if (ParseOptionalStackAlignment(Alignment))
917 B.addStackAlignmentAttr(Alignment);
920 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
921 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
922 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
923 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
924 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
925 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
926 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
927 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
928 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
929 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
930 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
931 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
932 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
933 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
934 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
935 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
936 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
937 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
938 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
939 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
940 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
941 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
942 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
943 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
944 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
945 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
948 case lltok::kw_inreg:
949 case lltok::kw_signext:
950 case lltok::kw_zeroext:
953 "invalid use of attribute on a function");
955 case lltok::kw_byval:
956 case lltok::kw_inalloca:
958 case lltok::kw_noalias:
959 case lltok::kw_nocapture:
960 case lltok::kw_returned:
964 "invalid use of parameter-only attribute on a function");
972 //===----------------------------------------------------------------------===//
973 // GlobalValue Reference/Resolution Routines.
974 //===----------------------------------------------------------------------===//
976 /// GetGlobalVal - Get a value with the specified name or ID, creating a
977 /// forward reference record if needed. This can return null if the value
978 /// exists but does not have the right type.
979 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
981 PointerType *PTy = dyn_cast<PointerType>(Ty);
983 Error(Loc, "global variable reference must have pointer type");
987 // Look this name up in the normal function symbol table.
989 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
991 // If this is a forward reference for the value, see if we already created a
992 // forward ref record.
994 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
995 I = ForwardRefVals.find(Name);
996 if (I != ForwardRefVals.end())
997 Val = I->second.first;
1000 // If we have the value in the symbol table or fwd-ref table, return it.
1002 if (Val->getType() == Ty) return Val;
1003 Error(Loc, "'@" + Name + "' defined with type '" +
1004 getTypeString(Val->getType()) + "'");
1008 // Otherwise, create a new forward reference for this value and remember it.
1009 GlobalValue *FwdVal;
1010 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1011 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1013 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1014 GlobalValue::ExternalWeakLinkage, 0, Name,
1015 0, GlobalVariable::NotThreadLocal,
1016 PTy->getAddressSpace());
1018 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1022 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1023 PointerType *PTy = dyn_cast<PointerType>(Ty);
1025 Error(Loc, "global variable reference must have pointer type");
1029 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1031 // If this is a forward reference for the value, see if we already created a
1032 // forward ref record.
1034 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1035 I = ForwardRefValIDs.find(ID);
1036 if (I != ForwardRefValIDs.end())
1037 Val = I->second.first;
1040 // If we have the value in the symbol table or fwd-ref table, return it.
1042 if (Val->getType() == Ty) return Val;
1043 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1044 getTypeString(Val->getType()) + "'");
1048 // Otherwise, create a new forward reference for this value and remember it.
1049 GlobalValue *FwdVal;
1050 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1051 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1053 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1054 GlobalValue::ExternalWeakLinkage, 0, "");
1056 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1061 //===----------------------------------------------------------------------===//
1063 //===----------------------------------------------------------------------===//
1065 /// ParseToken - If the current token has the specified kind, eat it and return
1066 /// success. Otherwise, emit the specified error and return failure.
1067 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1068 if (Lex.getKind() != T)
1069 return TokError(ErrMsg);
1074 /// ParseStringConstant
1075 /// ::= StringConstant
1076 bool LLParser::ParseStringConstant(std::string &Result) {
1077 if (Lex.getKind() != lltok::StringConstant)
1078 return TokError("expected string constant");
1079 Result = Lex.getStrVal();
1086 bool LLParser::ParseUInt32(unsigned &Val) {
1087 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1088 return TokError("expected integer");
1089 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1090 if (Val64 != unsigned(Val64))
1091 return TokError("expected 32-bit integer (too large)");
1098 /// := 'localdynamic'
1099 /// := 'initialexec'
1101 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1102 switch (Lex.getKind()) {
1104 return TokError("expected localdynamic, initialexec or localexec");
1105 case lltok::kw_localdynamic:
1106 TLM = GlobalVariable::LocalDynamicTLSModel;
1108 case lltok::kw_initialexec:
1109 TLM = GlobalVariable::InitialExecTLSModel;
1111 case lltok::kw_localexec:
1112 TLM = GlobalVariable::LocalExecTLSModel;
1120 /// ParseOptionalThreadLocal
1122 /// := 'thread_local'
1123 /// := 'thread_local' '(' tlsmodel ')'
1124 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1125 TLM = GlobalVariable::NotThreadLocal;
1126 if (!EatIfPresent(lltok::kw_thread_local))
1129 TLM = GlobalVariable::GeneralDynamicTLSModel;
1130 if (Lex.getKind() == lltok::lparen) {
1132 return ParseTLSModel(TLM) ||
1133 ParseToken(lltok::rparen, "expected ')' after thread local model");
1138 /// ParseOptionalAddrSpace
1140 /// := 'addrspace' '(' uint32 ')'
1141 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1143 if (!EatIfPresent(lltok::kw_addrspace))
1145 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1146 ParseUInt32(AddrSpace) ||
1147 ParseToken(lltok::rparen, "expected ')' in address space");
1150 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1151 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1152 bool HaveError = false;
1157 lltok::Kind Token = Lex.getKind();
1159 default: // End of attributes.
1161 case lltok::kw_align: {
1163 if (ParseOptionalAlignment(Alignment))
1165 B.addAlignmentAttr(Alignment);
1168 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1169 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1170 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1171 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1172 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1173 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1174 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1175 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1176 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1177 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1178 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1179 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1181 case lltok::kw_alignstack:
1182 case lltok::kw_alwaysinline:
1183 case lltok::kw_builtin:
1184 case lltok::kw_inlinehint:
1185 case lltok::kw_minsize:
1186 case lltok::kw_naked:
1187 case lltok::kw_nobuiltin:
1188 case lltok::kw_noduplicate:
1189 case lltok::kw_noimplicitfloat:
1190 case lltok::kw_noinline:
1191 case lltok::kw_nonlazybind:
1192 case lltok::kw_noredzone:
1193 case lltok::kw_noreturn:
1194 case lltok::kw_nounwind:
1195 case lltok::kw_optnone:
1196 case lltok::kw_optsize:
1197 case lltok::kw_returns_twice:
1198 case lltok::kw_sanitize_address:
1199 case lltok::kw_sanitize_memory:
1200 case lltok::kw_sanitize_thread:
1202 case lltok::kw_sspreq:
1203 case lltok::kw_sspstrong:
1204 case lltok::kw_uwtable:
1205 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1213 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1214 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1215 bool HaveError = false;
1220 lltok::Kind Token = Lex.getKind();
1222 default: // End of attributes.
1224 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1225 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1226 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1227 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1230 case lltok::kw_align:
1231 case lltok::kw_byval:
1232 case lltok::kw_inalloca:
1233 case lltok::kw_nest:
1234 case lltok::kw_nocapture:
1235 case lltok::kw_returned:
1236 case lltok::kw_sret:
1237 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1240 case lltok::kw_alignstack:
1241 case lltok::kw_alwaysinline:
1242 case lltok::kw_builtin:
1243 case lltok::kw_cold:
1244 case lltok::kw_inlinehint:
1245 case lltok::kw_minsize:
1246 case lltok::kw_naked:
1247 case lltok::kw_nobuiltin:
1248 case lltok::kw_noduplicate:
1249 case lltok::kw_noimplicitfloat:
1250 case lltok::kw_noinline:
1251 case lltok::kw_nonlazybind:
1252 case lltok::kw_noredzone:
1253 case lltok::kw_noreturn:
1254 case lltok::kw_nounwind:
1255 case lltok::kw_optnone:
1256 case lltok::kw_optsize:
1257 case lltok::kw_returns_twice:
1258 case lltok::kw_sanitize_address:
1259 case lltok::kw_sanitize_memory:
1260 case lltok::kw_sanitize_thread:
1262 case lltok::kw_sspreq:
1263 case lltok::kw_sspstrong:
1264 case lltok::kw_uwtable:
1265 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1268 case lltok::kw_readnone:
1269 case lltok::kw_readonly:
1270 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1277 /// ParseOptionalLinkage
1280 /// ::= 'linker_private'
1281 /// ::= 'linker_private_weak'
1286 /// ::= 'linkonce_odr'
1287 /// ::= 'available_externally'
1290 /// ::= 'extern_weak'
1292 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1294 switch (Lex.getKind()) {
1295 default: Res=GlobalValue::ExternalLinkage; return false;
1296 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1297 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1298 case lltok::kw_linker_private_weak:
1299 Res = GlobalValue::LinkerPrivateWeakLinkage;
1301 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1302 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1303 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1304 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1305 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1306 case lltok::kw_available_externally:
1307 Res = GlobalValue::AvailableExternallyLinkage;
1309 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1310 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1311 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1312 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1319 /// ParseOptionalVisibility
1325 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1326 switch (Lex.getKind()) {
1327 default: Res = GlobalValue::DefaultVisibility; return false;
1328 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1329 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1330 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1336 /// ParseOptionalDLLStorageClass
1341 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1342 switch (Lex.getKind()) {
1343 default: Res = GlobalValue::DefaultStorageClass; return false;
1344 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1345 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1351 /// ParseOptionalCallingConv
1355 /// ::= 'kw_intel_ocl_bicc'
1357 /// ::= 'x86_stdcallcc'
1358 /// ::= 'x86_fastcallcc'
1359 /// ::= 'x86_thiscallcc'
1360 /// ::= 'arm_apcscc'
1361 /// ::= 'arm_aapcscc'
1362 /// ::= 'arm_aapcs_vfpcc'
1363 /// ::= 'msp430_intrcc'
1364 /// ::= 'ptx_kernel'
1365 /// ::= 'ptx_device'
1367 /// ::= 'spir_kernel'
1368 /// ::= 'x86_64_sysvcc'
1369 /// ::= 'x86_64_win64cc'
1370 /// ::= 'webkit_jscc'
1374 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1375 switch (Lex.getKind()) {
1376 default: CC = CallingConv::C; return false;
1377 case lltok::kw_ccc: CC = CallingConv::C; break;
1378 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1379 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1380 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1381 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1382 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1383 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1384 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1385 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1386 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1387 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1388 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1389 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1390 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1391 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1392 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1393 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1394 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1395 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1396 case lltok::kw_cc: {
1397 unsigned ArbitraryCC;
1399 if (ParseUInt32(ArbitraryCC))
1401 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1410 /// ParseInstructionMetadata
1411 /// ::= !dbg !42 (',' !dbg !57)*
1412 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1413 PerFunctionState *PFS) {
1415 if (Lex.getKind() != lltok::MetadataVar)
1416 return TokError("expected metadata after comma");
1418 std::string Name = Lex.getStrVal();
1419 unsigned MDK = M->getMDKindID(Name);
1423 SMLoc Loc = Lex.getLoc();
1425 if (ParseToken(lltok::exclaim, "expected '!' here"))
1428 // This code is similar to that of ParseMetadataValue, however it needs to
1429 // have special-case code for a forward reference; see the comments on
1430 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1431 // at the top level here.
1432 if (Lex.getKind() == lltok::lbrace) {
1434 if (ParseMetadataListValue(ID, PFS))
1436 assert(ID.Kind == ValID::t_MDNode);
1437 Inst->setMetadata(MDK, ID.MDNodeVal);
1439 unsigned NodeID = 0;
1440 if (ParseMDNodeID(Node, NodeID))
1443 // If we got the node, add it to the instruction.
1444 Inst->setMetadata(MDK, Node);
1446 MDRef R = { Loc, MDK, NodeID };
1447 // Otherwise, remember that this should be resolved later.
1448 ForwardRefInstMetadata[Inst].push_back(R);
1452 if (MDK == LLVMContext::MD_tbaa)
1453 InstsWithTBAATag.push_back(Inst);
1455 // If this is the end of the list, we're done.
1456 } while (EatIfPresent(lltok::comma));
1460 /// ParseOptionalAlignment
1463 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1465 if (!EatIfPresent(lltok::kw_align))
1467 LocTy AlignLoc = Lex.getLoc();
1468 if (ParseUInt32(Alignment)) return true;
1469 if (!isPowerOf2_32(Alignment))
1470 return Error(AlignLoc, "alignment is not a power of two");
1471 if (Alignment > Value::MaximumAlignment)
1472 return Error(AlignLoc, "huge alignments are not supported yet");
1476 /// ParseOptionalCommaAlign
1480 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1482 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1483 bool &AteExtraComma) {
1484 AteExtraComma = false;
1485 while (EatIfPresent(lltok::comma)) {
1486 // Metadata at the end is an early exit.
1487 if (Lex.getKind() == lltok::MetadataVar) {
1488 AteExtraComma = true;
1492 if (Lex.getKind() != lltok::kw_align)
1493 return Error(Lex.getLoc(), "expected metadata or 'align'");
1495 if (ParseOptionalAlignment(Alignment)) return true;
1501 /// ParseScopeAndOrdering
1502 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1505 /// This sets Scope and Ordering to the parsed values.
1506 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1507 AtomicOrdering &Ordering) {
1511 Scope = CrossThread;
1512 if (EatIfPresent(lltok::kw_singlethread))
1513 Scope = SingleThread;
1514 switch (Lex.getKind()) {
1515 default: return TokError("Expected ordering on atomic instruction");
1516 case lltok::kw_unordered: Ordering = Unordered; break;
1517 case lltok::kw_monotonic: Ordering = Monotonic; break;
1518 case lltok::kw_acquire: Ordering = Acquire; break;
1519 case lltok::kw_release: Ordering = Release; break;
1520 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1521 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1527 /// ParseOptionalStackAlignment
1529 /// ::= 'alignstack' '(' 4 ')'
1530 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1532 if (!EatIfPresent(lltok::kw_alignstack))
1534 LocTy ParenLoc = Lex.getLoc();
1535 if (!EatIfPresent(lltok::lparen))
1536 return Error(ParenLoc, "expected '('");
1537 LocTy AlignLoc = Lex.getLoc();
1538 if (ParseUInt32(Alignment)) return true;
1539 ParenLoc = Lex.getLoc();
1540 if (!EatIfPresent(lltok::rparen))
1541 return Error(ParenLoc, "expected ')'");
1542 if (!isPowerOf2_32(Alignment))
1543 return Error(AlignLoc, "stack alignment is not a power of two");
1547 /// ParseIndexList - This parses the index list for an insert/extractvalue
1548 /// instruction. This sets AteExtraComma in the case where we eat an extra
1549 /// comma at the end of the line and find that it is followed by metadata.
1550 /// Clients that don't allow metadata can call the version of this function that
1551 /// only takes one argument.
1554 /// ::= (',' uint32)+
1556 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1557 bool &AteExtraComma) {
1558 AteExtraComma = false;
1560 if (Lex.getKind() != lltok::comma)
1561 return TokError("expected ',' as start of index list");
1563 while (EatIfPresent(lltok::comma)) {
1564 if (Lex.getKind() == lltok::MetadataVar) {
1565 AteExtraComma = true;
1569 if (ParseUInt32(Idx)) return true;
1570 Indices.push_back(Idx);
1576 //===----------------------------------------------------------------------===//
1578 //===----------------------------------------------------------------------===//
1580 /// ParseType - Parse a type.
1581 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1582 SMLoc TypeLoc = Lex.getLoc();
1583 switch (Lex.getKind()) {
1585 return TokError("expected type");
1587 // Type ::= 'float' | 'void' (etc)
1588 Result = Lex.getTyVal();
1592 // Type ::= StructType
1593 if (ParseAnonStructType(Result, false))
1596 case lltok::lsquare:
1597 // Type ::= '[' ... ']'
1598 Lex.Lex(); // eat the lsquare.
1599 if (ParseArrayVectorType(Result, false))
1602 case lltok::less: // Either vector or packed struct.
1603 // Type ::= '<' ... '>'
1605 if (Lex.getKind() == lltok::lbrace) {
1606 if (ParseAnonStructType(Result, true) ||
1607 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1609 } else if (ParseArrayVectorType(Result, true))
1612 case lltok::LocalVar: {
1614 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1616 // If the type hasn't been defined yet, create a forward definition and
1617 // remember where that forward def'n was seen (in case it never is defined).
1618 if (Entry.first == 0) {
1619 Entry.first = StructType::create(Context, Lex.getStrVal());
1620 Entry.second = Lex.getLoc();
1622 Result = Entry.first;
1627 case lltok::LocalVarID: {
1629 if (Lex.getUIntVal() >= NumberedTypes.size())
1630 NumberedTypes.resize(Lex.getUIntVal()+1);
1631 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1633 // If the type hasn't been defined yet, create a forward definition and
1634 // remember where that forward def'n was seen (in case it never is defined).
1635 if (Entry.first == 0) {
1636 Entry.first = StructType::create(Context);
1637 Entry.second = Lex.getLoc();
1639 Result = Entry.first;
1645 // Parse the type suffixes.
1647 switch (Lex.getKind()) {
1650 if (!AllowVoid && Result->isVoidTy())
1651 return Error(TypeLoc, "void type only allowed for function results");
1654 // Type ::= Type '*'
1656 if (Result->isLabelTy())
1657 return TokError("basic block pointers are invalid");
1658 if (Result->isVoidTy())
1659 return TokError("pointers to void are invalid - use i8* instead");
1660 if (!PointerType::isValidElementType(Result))
1661 return TokError("pointer to this type is invalid");
1662 Result = PointerType::getUnqual(Result);
1666 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1667 case lltok::kw_addrspace: {
1668 if (Result->isLabelTy())
1669 return TokError("basic block pointers are invalid");
1670 if (Result->isVoidTy())
1671 return TokError("pointers to void are invalid; use i8* instead");
1672 if (!PointerType::isValidElementType(Result))
1673 return TokError("pointer to this type is invalid");
1675 if (ParseOptionalAddrSpace(AddrSpace) ||
1676 ParseToken(lltok::star, "expected '*' in address space"))
1679 Result = PointerType::get(Result, AddrSpace);
1683 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1685 if (ParseFunctionType(Result))
1692 /// ParseParameterList
1694 /// ::= '(' Arg (',' Arg)* ')'
1696 /// ::= Type OptionalAttributes Value OptionalAttributes
1697 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1698 PerFunctionState &PFS) {
1699 if (ParseToken(lltok::lparen, "expected '(' in call"))
1702 unsigned AttrIndex = 1;
1703 while (Lex.getKind() != lltok::rparen) {
1704 // If this isn't the first argument, we need a comma.
1705 if (!ArgList.empty() &&
1706 ParseToken(lltok::comma, "expected ',' in argument list"))
1709 // Parse the argument.
1712 AttrBuilder ArgAttrs;
1714 if (ParseType(ArgTy, ArgLoc))
1717 // Otherwise, handle normal operands.
1718 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1720 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1725 Lex.Lex(); // Lex the ')'.
1731 /// ParseArgumentList - Parse the argument list for a function type or function
1733 /// ::= '(' ArgTypeListI ')'
1737 /// ::= ArgTypeList ',' '...'
1738 /// ::= ArgType (',' ArgType)*
1740 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1743 assert(Lex.getKind() == lltok::lparen);
1744 Lex.Lex(); // eat the (.
1746 if (Lex.getKind() == lltok::rparen) {
1748 } else if (Lex.getKind() == lltok::dotdotdot) {
1752 LocTy TypeLoc = Lex.getLoc();
1757 if (ParseType(ArgTy) ||
1758 ParseOptionalParamAttrs(Attrs)) return true;
1760 if (ArgTy->isVoidTy())
1761 return Error(TypeLoc, "argument can not have void type");
1763 if (Lex.getKind() == lltok::LocalVar) {
1764 Name = Lex.getStrVal();
1768 if (!FunctionType::isValidArgumentType(ArgTy))
1769 return Error(TypeLoc, "invalid type for function argument");
1771 unsigned AttrIndex = 1;
1772 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1773 AttributeSet::get(ArgTy->getContext(),
1774 AttrIndex++, Attrs), Name));
1776 while (EatIfPresent(lltok::comma)) {
1777 // Handle ... at end of arg list.
1778 if (EatIfPresent(lltok::dotdotdot)) {
1783 // Otherwise must be an argument type.
1784 TypeLoc = Lex.getLoc();
1785 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1787 if (ArgTy->isVoidTy())
1788 return Error(TypeLoc, "argument can not have void type");
1790 if (Lex.getKind() == lltok::LocalVar) {
1791 Name = Lex.getStrVal();
1797 if (!ArgTy->isFirstClassType())
1798 return Error(TypeLoc, "invalid type for function argument");
1800 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1801 AttributeSet::get(ArgTy->getContext(),
1802 AttrIndex++, Attrs),
1807 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1810 /// ParseFunctionType
1811 /// ::= Type ArgumentList OptionalAttrs
1812 bool LLParser::ParseFunctionType(Type *&Result) {
1813 assert(Lex.getKind() == lltok::lparen);
1815 if (!FunctionType::isValidReturnType(Result))
1816 return TokError("invalid function return type");
1818 SmallVector<ArgInfo, 8> ArgList;
1820 if (ParseArgumentList(ArgList, isVarArg))
1823 // Reject names on the arguments lists.
1824 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1825 if (!ArgList[i].Name.empty())
1826 return Error(ArgList[i].Loc, "argument name invalid in function type");
1827 if (ArgList[i].Attrs.hasAttributes(i + 1))
1828 return Error(ArgList[i].Loc,
1829 "argument attributes invalid in function type");
1832 SmallVector<Type*, 16> ArgListTy;
1833 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1834 ArgListTy.push_back(ArgList[i].Ty);
1836 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1840 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1842 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1843 SmallVector<Type*, 8> Elts;
1844 if (ParseStructBody(Elts)) return true;
1846 Result = StructType::get(Context, Elts, Packed);
1850 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1851 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1852 std::pair<Type*, LocTy> &Entry,
1854 // If the type was already defined, diagnose the redefinition.
1855 if (Entry.first && !Entry.second.isValid())
1856 return Error(TypeLoc, "redefinition of type");
1858 // If we have opaque, just return without filling in the definition for the
1859 // struct. This counts as a definition as far as the .ll file goes.
1860 if (EatIfPresent(lltok::kw_opaque)) {
1861 // This type is being defined, so clear the location to indicate this.
1862 Entry.second = SMLoc();
1864 // If this type number has never been uttered, create it.
1865 if (Entry.first == 0)
1866 Entry.first = StructType::create(Context, Name);
1867 ResultTy = Entry.first;
1871 // If the type starts with '<', then it is either a packed struct or a vector.
1872 bool isPacked = EatIfPresent(lltok::less);
1874 // If we don't have a struct, then we have a random type alias, which we
1875 // accept for compatibility with old files. These types are not allowed to be
1876 // forward referenced and not allowed to be recursive.
1877 if (Lex.getKind() != lltok::lbrace) {
1879 return Error(TypeLoc, "forward references to non-struct type");
1883 return ParseArrayVectorType(ResultTy, true);
1884 return ParseType(ResultTy);
1887 // This type is being defined, so clear the location to indicate this.
1888 Entry.second = SMLoc();
1890 // If this type number has never been uttered, create it.
1891 if (Entry.first == 0)
1892 Entry.first = StructType::create(Context, Name);
1894 StructType *STy = cast<StructType>(Entry.first);
1896 SmallVector<Type*, 8> Body;
1897 if (ParseStructBody(Body) ||
1898 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1901 STy->setBody(Body, isPacked);
1907 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1910 /// ::= '{' Type (',' Type)* '}'
1911 /// ::= '<' '{' '}' '>'
1912 /// ::= '<' '{' Type (',' Type)* '}' '>'
1913 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1914 assert(Lex.getKind() == lltok::lbrace);
1915 Lex.Lex(); // Consume the '{'
1917 // Handle the empty struct.
1918 if (EatIfPresent(lltok::rbrace))
1921 LocTy EltTyLoc = Lex.getLoc();
1923 if (ParseType(Ty)) return true;
1926 if (!StructType::isValidElementType(Ty))
1927 return Error(EltTyLoc, "invalid element type for struct");
1929 while (EatIfPresent(lltok::comma)) {
1930 EltTyLoc = Lex.getLoc();
1931 if (ParseType(Ty)) return true;
1933 if (!StructType::isValidElementType(Ty))
1934 return Error(EltTyLoc, "invalid element type for struct");
1939 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1942 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1943 /// token has already been consumed.
1945 /// ::= '[' APSINTVAL 'x' Types ']'
1946 /// ::= '<' APSINTVAL 'x' Types '>'
1947 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1948 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1949 Lex.getAPSIntVal().getBitWidth() > 64)
1950 return TokError("expected number in address space");
1952 LocTy SizeLoc = Lex.getLoc();
1953 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1956 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1959 LocTy TypeLoc = Lex.getLoc();
1961 if (ParseType(EltTy)) return true;
1963 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1964 "expected end of sequential type"))
1969 return Error(SizeLoc, "zero element vector is illegal");
1970 if ((unsigned)Size != Size)
1971 return Error(SizeLoc, "size too large for vector");
1972 if (!VectorType::isValidElementType(EltTy))
1973 return Error(TypeLoc, "invalid vector element type");
1974 Result = VectorType::get(EltTy, unsigned(Size));
1976 if (!ArrayType::isValidElementType(EltTy))
1977 return Error(TypeLoc, "invalid array element type");
1978 Result = ArrayType::get(EltTy, Size);
1983 //===----------------------------------------------------------------------===//
1984 // Function Semantic Analysis.
1985 //===----------------------------------------------------------------------===//
1987 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1989 : P(p), F(f), FunctionNumber(functionNumber) {
1991 // Insert unnamed arguments into the NumberedVals list.
1992 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1995 NumberedVals.push_back(AI);
1998 LLParser::PerFunctionState::~PerFunctionState() {
1999 // If there were any forward referenced non-basicblock values, delete them.
2000 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2001 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2002 if (!isa<BasicBlock>(I->second.first)) {
2003 I->second.first->replaceAllUsesWith(
2004 UndefValue::get(I->second.first->getType()));
2005 delete I->second.first;
2006 I->second.first = 0;
2009 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2010 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2011 if (!isa<BasicBlock>(I->second.first)) {
2012 I->second.first->replaceAllUsesWith(
2013 UndefValue::get(I->second.first->getType()));
2014 delete I->second.first;
2015 I->second.first = 0;
2019 bool LLParser::PerFunctionState::FinishFunction() {
2020 // Check to see if someone took the address of labels in this block.
2021 if (!P.ForwardRefBlockAddresses.empty()) {
2023 if (!F.getName().empty()) {
2024 FunctionID.Kind = ValID::t_GlobalName;
2025 FunctionID.StrVal = F.getName();
2027 FunctionID.Kind = ValID::t_GlobalID;
2028 FunctionID.UIntVal = FunctionNumber;
2031 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2032 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2033 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2034 // Resolve all these references.
2035 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2038 P.ForwardRefBlockAddresses.erase(FRBAI);
2042 if (!ForwardRefVals.empty())
2043 return P.Error(ForwardRefVals.begin()->second.second,
2044 "use of undefined value '%" + ForwardRefVals.begin()->first +
2046 if (!ForwardRefValIDs.empty())
2047 return P.Error(ForwardRefValIDs.begin()->second.second,
2048 "use of undefined value '%" +
2049 Twine(ForwardRefValIDs.begin()->first) + "'");
2054 /// GetVal - Get a value with the specified name or ID, creating a
2055 /// forward reference record if needed. This can return null if the value
2056 /// exists but does not have the right type.
2057 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2058 Type *Ty, LocTy Loc) {
2059 // Look this name up in the normal function symbol table.
2060 Value *Val = F.getValueSymbolTable().lookup(Name);
2062 // If this is a forward reference for the value, see if we already created a
2063 // forward ref record.
2065 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2066 I = ForwardRefVals.find(Name);
2067 if (I != ForwardRefVals.end())
2068 Val = I->second.first;
2071 // If we have the value in the symbol table or fwd-ref table, return it.
2073 if (Val->getType() == Ty) return Val;
2074 if (Ty->isLabelTy())
2075 P.Error(Loc, "'%" + Name + "' is not a basic block");
2077 P.Error(Loc, "'%" + Name + "' defined with type '" +
2078 getTypeString(Val->getType()) + "'");
2082 // Don't make placeholders with invalid type.
2083 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2084 P.Error(Loc, "invalid use of a non-first-class type");
2088 // Otherwise, create a new forward reference for this value and remember it.
2090 if (Ty->isLabelTy())
2091 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2093 FwdVal = new Argument(Ty, Name);
2095 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2099 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2101 // Look this name up in the normal function symbol table.
2102 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
2104 // If this is a forward reference for the value, see if we already created a
2105 // forward ref record.
2107 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2108 I = ForwardRefValIDs.find(ID);
2109 if (I != ForwardRefValIDs.end())
2110 Val = I->second.first;
2113 // If we have the value in the symbol table or fwd-ref table, return it.
2115 if (Val->getType() == Ty) return Val;
2116 if (Ty->isLabelTy())
2117 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2119 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2120 getTypeString(Val->getType()) + "'");
2124 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2125 P.Error(Loc, "invalid use of a non-first-class type");
2129 // Otherwise, create a new forward reference for this value and remember it.
2131 if (Ty->isLabelTy())
2132 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2134 FwdVal = new Argument(Ty);
2136 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2140 /// SetInstName - After an instruction is parsed and inserted into its
2141 /// basic block, this installs its name.
2142 bool LLParser::PerFunctionState::SetInstName(int NameID,
2143 const std::string &NameStr,
2144 LocTy NameLoc, Instruction *Inst) {
2145 // If this instruction has void type, it cannot have a name or ID specified.
2146 if (Inst->getType()->isVoidTy()) {
2147 if (NameID != -1 || !NameStr.empty())
2148 return P.Error(NameLoc, "instructions returning void cannot have a name");
2152 // If this was a numbered instruction, verify that the instruction is the
2153 // expected value and resolve any forward references.
2154 if (NameStr.empty()) {
2155 // If neither a name nor an ID was specified, just use the next ID.
2157 NameID = NumberedVals.size();
2159 if (unsigned(NameID) != NumberedVals.size())
2160 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2161 Twine(NumberedVals.size()) + "'");
2163 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2164 ForwardRefValIDs.find(NameID);
2165 if (FI != ForwardRefValIDs.end()) {
2166 if (FI->second.first->getType() != Inst->getType())
2167 return P.Error(NameLoc, "instruction forward referenced with type '" +
2168 getTypeString(FI->second.first->getType()) + "'");
2169 FI->second.first->replaceAllUsesWith(Inst);
2170 delete FI->second.first;
2171 ForwardRefValIDs.erase(FI);
2174 NumberedVals.push_back(Inst);
2178 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2179 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2180 FI = ForwardRefVals.find(NameStr);
2181 if (FI != ForwardRefVals.end()) {
2182 if (FI->second.first->getType() != Inst->getType())
2183 return P.Error(NameLoc, "instruction forward referenced with type '" +
2184 getTypeString(FI->second.first->getType()) + "'");
2185 FI->second.first->replaceAllUsesWith(Inst);
2186 delete FI->second.first;
2187 ForwardRefVals.erase(FI);
2190 // Set the name on the instruction.
2191 Inst->setName(NameStr);
2193 if (Inst->getName() != NameStr)
2194 return P.Error(NameLoc, "multiple definition of local value named '" +
2199 /// GetBB - Get a basic block with the specified name or ID, creating a
2200 /// forward reference record if needed.
2201 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2203 return cast_or_null<BasicBlock>(GetVal(Name,
2204 Type::getLabelTy(F.getContext()), Loc));
2207 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2208 return cast_or_null<BasicBlock>(GetVal(ID,
2209 Type::getLabelTy(F.getContext()), Loc));
2212 /// DefineBB - Define the specified basic block, which is either named or
2213 /// unnamed. If there is an error, this returns null otherwise it returns
2214 /// the block being defined.
2215 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2219 BB = GetBB(NumberedVals.size(), Loc);
2221 BB = GetBB(Name, Loc);
2222 if (BB == 0) return 0; // Already diagnosed error.
2224 // Move the block to the end of the function. Forward ref'd blocks are
2225 // inserted wherever they happen to be referenced.
2226 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2228 // Remove the block from forward ref sets.
2230 ForwardRefValIDs.erase(NumberedVals.size());
2231 NumberedVals.push_back(BB);
2233 // BB forward references are already in the function symbol table.
2234 ForwardRefVals.erase(Name);
2240 //===----------------------------------------------------------------------===//
2242 //===----------------------------------------------------------------------===//
2244 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2245 /// type implied. For example, if we parse "4" we don't know what integer type
2246 /// it has. The value will later be combined with its type and checked for
2247 /// sanity. PFS is used to convert function-local operands of metadata (since
2248 /// metadata operands are not just parsed here but also converted to values).
2249 /// PFS can be null when we are not parsing metadata values inside a function.
2250 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2251 ID.Loc = Lex.getLoc();
2252 switch (Lex.getKind()) {
2253 default: return TokError("expected value token");
2254 case lltok::GlobalID: // @42
2255 ID.UIntVal = Lex.getUIntVal();
2256 ID.Kind = ValID::t_GlobalID;
2258 case lltok::GlobalVar: // @foo
2259 ID.StrVal = Lex.getStrVal();
2260 ID.Kind = ValID::t_GlobalName;
2262 case lltok::LocalVarID: // %42
2263 ID.UIntVal = Lex.getUIntVal();
2264 ID.Kind = ValID::t_LocalID;
2266 case lltok::LocalVar: // %foo
2267 ID.StrVal = Lex.getStrVal();
2268 ID.Kind = ValID::t_LocalName;
2270 case lltok::exclaim: // !42, !{...}, or !"foo"
2271 return ParseMetadataValue(ID, PFS);
2273 ID.APSIntVal = Lex.getAPSIntVal();
2274 ID.Kind = ValID::t_APSInt;
2276 case lltok::APFloat:
2277 ID.APFloatVal = Lex.getAPFloatVal();
2278 ID.Kind = ValID::t_APFloat;
2280 case lltok::kw_true:
2281 ID.ConstantVal = ConstantInt::getTrue(Context);
2282 ID.Kind = ValID::t_Constant;
2284 case lltok::kw_false:
2285 ID.ConstantVal = ConstantInt::getFalse(Context);
2286 ID.Kind = ValID::t_Constant;
2288 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2289 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2290 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2292 case lltok::lbrace: {
2293 // ValID ::= '{' ConstVector '}'
2295 SmallVector<Constant*, 16> Elts;
2296 if (ParseGlobalValueVector(Elts) ||
2297 ParseToken(lltok::rbrace, "expected end of struct constant"))
2300 ID.ConstantStructElts = new Constant*[Elts.size()];
2301 ID.UIntVal = Elts.size();
2302 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2303 ID.Kind = ValID::t_ConstantStruct;
2307 // ValID ::= '<' ConstVector '>' --> Vector.
2308 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2310 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2312 SmallVector<Constant*, 16> Elts;
2313 LocTy FirstEltLoc = Lex.getLoc();
2314 if (ParseGlobalValueVector(Elts) ||
2316 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2317 ParseToken(lltok::greater, "expected end of constant"))
2320 if (isPackedStruct) {
2321 ID.ConstantStructElts = new Constant*[Elts.size()];
2322 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2323 ID.UIntVal = Elts.size();
2324 ID.Kind = ValID::t_PackedConstantStruct;
2329 return Error(ID.Loc, "constant vector must not be empty");
2331 if (!Elts[0]->getType()->isIntegerTy() &&
2332 !Elts[0]->getType()->isFloatingPointTy() &&
2333 !Elts[0]->getType()->isPointerTy())
2334 return Error(FirstEltLoc,
2335 "vector elements must have integer, pointer or floating point type");
2337 // Verify that all the vector elements have the same type.
2338 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2339 if (Elts[i]->getType() != Elts[0]->getType())
2340 return Error(FirstEltLoc,
2341 "vector element #" + Twine(i) +
2342 " is not of type '" + getTypeString(Elts[0]->getType()));
2344 ID.ConstantVal = ConstantVector::get(Elts);
2345 ID.Kind = ValID::t_Constant;
2348 case lltok::lsquare: { // Array Constant
2350 SmallVector<Constant*, 16> Elts;
2351 LocTy FirstEltLoc = Lex.getLoc();
2352 if (ParseGlobalValueVector(Elts) ||
2353 ParseToken(lltok::rsquare, "expected end of array constant"))
2356 // Handle empty element.
2358 // Use undef instead of an array because it's inconvenient to determine
2359 // the element type at this point, there being no elements to examine.
2360 ID.Kind = ValID::t_EmptyArray;
2364 if (!Elts[0]->getType()->isFirstClassType())
2365 return Error(FirstEltLoc, "invalid array element type: " +
2366 getTypeString(Elts[0]->getType()));
2368 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2370 // Verify all elements are correct type!
2371 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2372 if (Elts[i]->getType() != Elts[0]->getType())
2373 return Error(FirstEltLoc,
2374 "array element #" + Twine(i) +
2375 " is not of type '" + getTypeString(Elts[0]->getType()));
2378 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2379 ID.Kind = ValID::t_Constant;
2382 case lltok::kw_c: // c "foo"
2384 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2386 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2387 ID.Kind = ValID::t_Constant;
2390 case lltok::kw_asm: {
2391 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2393 bool HasSideEffect, AlignStack, AsmDialect;
2395 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2396 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2397 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2398 ParseStringConstant(ID.StrVal) ||
2399 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2400 ParseToken(lltok::StringConstant, "expected constraint string"))
2402 ID.StrVal2 = Lex.getStrVal();
2403 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2404 (unsigned(AsmDialect)<<2);
2405 ID.Kind = ValID::t_InlineAsm;
2409 case lltok::kw_blockaddress: {
2410 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2415 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2417 ParseToken(lltok::comma, "expected comma in block address expression")||
2418 ParseValID(Label) ||
2419 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2422 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2423 return Error(Fn.Loc, "expected function name in blockaddress");
2424 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2425 return Error(Label.Loc, "expected basic block name in blockaddress");
2427 // Make a global variable as a placeholder for this reference.
2428 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2429 false, GlobalValue::InternalLinkage,
2431 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2432 ID.ConstantVal = FwdRef;
2433 ID.Kind = ValID::t_Constant;
2437 case lltok::kw_trunc:
2438 case lltok::kw_zext:
2439 case lltok::kw_sext:
2440 case lltok::kw_fptrunc:
2441 case lltok::kw_fpext:
2442 case lltok::kw_bitcast:
2443 case lltok::kw_addrspacecast:
2444 case lltok::kw_uitofp:
2445 case lltok::kw_sitofp:
2446 case lltok::kw_fptoui:
2447 case lltok::kw_fptosi:
2448 case lltok::kw_inttoptr:
2449 case lltok::kw_ptrtoint: {
2450 unsigned Opc = Lex.getUIntVal();
2454 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2455 ParseGlobalTypeAndValue(SrcVal) ||
2456 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2457 ParseType(DestTy) ||
2458 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2460 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2461 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2462 getTypeString(SrcVal->getType()) + "' to '" +
2463 getTypeString(DestTy) + "'");
2464 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2466 ID.Kind = ValID::t_Constant;
2469 case lltok::kw_extractvalue: {
2472 SmallVector<unsigned, 4> Indices;
2473 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2474 ParseGlobalTypeAndValue(Val) ||
2475 ParseIndexList(Indices) ||
2476 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2479 if (!Val->getType()->isAggregateType())
2480 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2481 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2482 return Error(ID.Loc, "invalid indices for extractvalue");
2483 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2484 ID.Kind = ValID::t_Constant;
2487 case lltok::kw_insertvalue: {
2489 Constant *Val0, *Val1;
2490 SmallVector<unsigned, 4> Indices;
2491 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2492 ParseGlobalTypeAndValue(Val0) ||
2493 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2494 ParseGlobalTypeAndValue(Val1) ||
2495 ParseIndexList(Indices) ||
2496 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2498 if (!Val0->getType()->isAggregateType())
2499 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2500 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2501 return Error(ID.Loc, "invalid indices for insertvalue");
2502 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2503 ID.Kind = ValID::t_Constant;
2506 case lltok::kw_icmp:
2507 case lltok::kw_fcmp: {
2508 unsigned PredVal, Opc = Lex.getUIntVal();
2509 Constant *Val0, *Val1;
2511 if (ParseCmpPredicate(PredVal, Opc) ||
2512 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2513 ParseGlobalTypeAndValue(Val0) ||
2514 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2515 ParseGlobalTypeAndValue(Val1) ||
2516 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2519 if (Val0->getType() != Val1->getType())
2520 return Error(ID.Loc, "compare operands must have the same type");
2522 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2524 if (Opc == Instruction::FCmp) {
2525 if (!Val0->getType()->isFPOrFPVectorTy())
2526 return Error(ID.Loc, "fcmp requires floating point operands");
2527 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2529 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2530 if (!Val0->getType()->isIntOrIntVectorTy() &&
2531 !Val0->getType()->getScalarType()->isPointerTy())
2532 return Error(ID.Loc, "icmp requires pointer or integer operands");
2533 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2535 ID.Kind = ValID::t_Constant;
2539 // Binary Operators.
2541 case lltok::kw_fadd:
2543 case lltok::kw_fsub:
2545 case lltok::kw_fmul:
2546 case lltok::kw_udiv:
2547 case lltok::kw_sdiv:
2548 case lltok::kw_fdiv:
2549 case lltok::kw_urem:
2550 case lltok::kw_srem:
2551 case lltok::kw_frem:
2553 case lltok::kw_lshr:
2554 case lltok::kw_ashr: {
2558 unsigned Opc = Lex.getUIntVal();
2559 Constant *Val0, *Val1;
2561 LocTy ModifierLoc = Lex.getLoc();
2562 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2563 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2564 if (EatIfPresent(lltok::kw_nuw))
2566 if (EatIfPresent(lltok::kw_nsw)) {
2568 if (EatIfPresent(lltok::kw_nuw))
2571 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2572 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2573 if (EatIfPresent(lltok::kw_exact))
2576 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2577 ParseGlobalTypeAndValue(Val0) ||
2578 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2579 ParseGlobalTypeAndValue(Val1) ||
2580 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2582 if (Val0->getType() != Val1->getType())
2583 return Error(ID.Loc, "operands of constexpr must have same type");
2584 if (!Val0->getType()->isIntOrIntVectorTy()) {
2586 return Error(ModifierLoc, "nuw only applies to integer operations");
2588 return Error(ModifierLoc, "nsw only applies to integer operations");
2590 // Check that the type is valid for the operator.
2592 case Instruction::Add:
2593 case Instruction::Sub:
2594 case Instruction::Mul:
2595 case Instruction::UDiv:
2596 case Instruction::SDiv:
2597 case Instruction::URem:
2598 case Instruction::SRem:
2599 case Instruction::Shl:
2600 case Instruction::AShr:
2601 case Instruction::LShr:
2602 if (!Val0->getType()->isIntOrIntVectorTy())
2603 return Error(ID.Loc, "constexpr requires integer operands");
2605 case Instruction::FAdd:
2606 case Instruction::FSub:
2607 case Instruction::FMul:
2608 case Instruction::FDiv:
2609 case Instruction::FRem:
2610 if (!Val0->getType()->isFPOrFPVectorTy())
2611 return Error(ID.Loc, "constexpr requires fp operands");
2613 default: llvm_unreachable("Unknown binary operator!");
2616 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2617 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2618 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2619 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2621 ID.Kind = ValID::t_Constant;
2625 // Logical Operations
2628 case lltok::kw_xor: {
2629 unsigned Opc = Lex.getUIntVal();
2630 Constant *Val0, *Val1;
2632 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2633 ParseGlobalTypeAndValue(Val0) ||
2634 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2635 ParseGlobalTypeAndValue(Val1) ||
2636 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2638 if (Val0->getType() != Val1->getType())
2639 return Error(ID.Loc, "operands of constexpr must have same type");
2640 if (!Val0->getType()->isIntOrIntVectorTy())
2641 return Error(ID.Loc,
2642 "constexpr requires integer or integer vector operands");
2643 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2644 ID.Kind = ValID::t_Constant;
2648 case lltok::kw_getelementptr:
2649 case lltok::kw_shufflevector:
2650 case lltok::kw_insertelement:
2651 case lltok::kw_extractelement:
2652 case lltok::kw_select: {
2653 unsigned Opc = Lex.getUIntVal();
2654 SmallVector<Constant*, 16> Elts;
2655 bool InBounds = false;
2657 if (Opc == Instruction::GetElementPtr)
2658 InBounds = EatIfPresent(lltok::kw_inbounds);
2659 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2660 ParseGlobalValueVector(Elts) ||
2661 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2664 if (Opc == Instruction::GetElementPtr) {
2665 if (Elts.size() == 0 ||
2666 !Elts[0]->getType()->getScalarType()->isPointerTy())
2667 return Error(ID.Loc, "getelementptr requires pointer operand");
2669 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2670 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2671 return Error(ID.Loc, "invalid indices for getelementptr");
2672 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2674 } else if (Opc == Instruction::Select) {
2675 if (Elts.size() != 3)
2676 return Error(ID.Loc, "expected three operands to select");
2677 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2679 return Error(ID.Loc, Reason);
2680 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2681 } else if (Opc == Instruction::ShuffleVector) {
2682 if (Elts.size() != 3)
2683 return Error(ID.Loc, "expected three operands to shufflevector");
2684 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2685 return Error(ID.Loc, "invalid operands to shufflevector");
2687 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2688 } else if (Opc == Instruction::ExtractElement) {
2689 if (Elts.size() != 2)
2690 return Error(ID.Loc, "expected two operands to extractelement");
2691 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2692 return Error(ID.Loc, "invalid extractelement operands");
2693 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2695 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2696 if (Elts.size() != 3)
2697 return Error(ID.Loc, "expected three operands to insertelement");
2698 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2699 return Error(ID.Loc, "invalid insertelement operands");
2701 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2704 ID.Kind = ValID::t_Constant;
2713 /// ParseGlobalValue - Parse a global value with the specified type.
2714 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2718 bool Parsed = ParseValID(ID) ||
2719 ConvertValIDToValue(Ty, ID, V, NULL);
2720 if (V && !(C = dyn_cast<Constant>(V)))
2721 return Error(ID.Loc, "global values must be constants");
2725 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2727 return ParseType(Ty) ||
2728 ParseGlobalValue(Ty, V);
2731 /// ParseGlobalValueVector
2733 /// ::= TypeAndValue (',' TypeAndValue)*
2734 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2736 if (Lex.getKind() == lltok::rbrace ||
2737 Lex.getKind() == lltok::rsquare ||
2738 Lex.getKind() == lltok::greater ||
2739 Lex.getKind() == lltok::rparen)
2743 if (ParseGlobalTypeAndValue(C)) return true;
2746 while (EatIfPresent(lltok::comma)) {
2747 if (ParseGlobalTypeAndValue(C)) return true;
2754 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2755 assert(Lex.getKind() == lltok::lbrace);
2758 SmallVector<Value*, 16> Elts;
2759 if (ParseMDNodeVector(Elts, PFS) ||
2760 ParseToken(lltok::rbrace, "expected end of metadata node"))
2763 ID.MDNodeVal = MDNode::get(Context, Elts);
2764 ID.Kind = ValID::t_MDNode;
2768 /// ParseMetadataValue
2772 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2773 assert(Lex.getKind() == lltok::exclaim);
2778 if (Lex.getKind() == lltok::lbrace)
2779 return ParseMetadataListValue(ID, PFS);
2781 // Standalone metadata reference
2783 if (Lex.getKind() == lltok::APSInt) {
2784 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2785 ID.Kind = ValID::t_MDNode;
2790 // ::= '!' STRINGCONSTANT
2791 if (ParseMDString(ID.MDStringVal)) return true;
2792 ID.Kind = ValID::t_MDString;
2797 //===----------------------------------------------------------------------===//
2798 // Function Parsing.
2799 //===----------------------------------------------------------------------===//
2801 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2802 PerFunctionState *PFS) {
2803 if (Ty->isFunctionTy())
2804 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2807 case ValID::t_LocalID:
2808 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2809 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2811 case ValID::t_LocalName:
2812 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2813 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2815 case ValID::t_InlineAsm: {
2816 PointerType *PTy = dyn_cast<PointerType>(Ty);
2818 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2819 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2820 return Error(ID.Loc, "invalid type for inline asm constraint string");
2821 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2822 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2825 case ValID::t_MDNode:
2826 if (!Ty->isMetadataTy())
2827 return Error(ID.Loc, "metadata value must have metadata type");
2830 case ValID::t_MDString:
2831 if (!Ty->isMetadataTy())
2832 return Error(ID.Loc, "metadata value must have metadata type");
2835 case ValID::t_GlobalName:
2836 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2838 case ValID::t_GlobalID:
2839 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2841 case ValID::t_APSInt:
2842 if (!Ty->isIntegerTy())
2843 return Error(ID.Loc, "integer constant must have integer type");
2844 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2845 V = ConstantInt::get(Context, ID.APSIntVal);
2847 case ValID::t_APFloat:
2848 if (!Ty->isFloatingPointTy() ||
2849 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2850 return Error(ID.Loc, "floating point constant invalid for type");
2852 // The lexer has no type info, so builds all half, float, and double FP
2853 // constants as double. Fix this here. Long double does not need this.
2854 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2857 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2859 else if (Ty->isFloatTy())
2860 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2863 V = ConstantFP::get(Context, ID.APFloatVal);
2865 if (V->getType() != Ty)
2866 return Error(ID.Loc, "floating point constant does not have type '" +
2867 getTypeString(Ty) + "'");
2871 if (!Ty->isPointerTy())
2872 return Error(ID.Loc, "null must be a pointer type");
2873 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2875 case ValID::t_Undef:
2876 // FIXME: LabelTy should not be a first-class type.
2877 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2878 return Error(ID.Loc, "invalid type for undef constant");
2879 V = UndefValue::get(Ty);
2881 case ValID::t_EmptyArray:
2882 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2883 return Error(ID.Loc, "invalid empty array initializer");
2884 V = UndefValue::get(Ty);
2887 // FIXME: LabelTy should not be a first-class type.
2888 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2889 return Error(ID.Loc, "invalid type for null constant");
2890 V = Constant::getNullValue(Ty);
2892 case ValID::t_Constant:
2893 if (ID.ConstantVal->getType() != Ty)
2894 return Error(ID.Loc, "constant expression type mismatch");
2898 case ValID::t_ConstantStruct:
2899 case ValID::t_PackedConstantStruct:
2900 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2901 if (ST->getNumElements() != ID.UIntVal)
2902 return Error(ID.Loc,
2903 "initializer with struct type has wrong # elements");
2904 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2905 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2907 // Verify that the elements are compatible with the structtype.
2908 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2909 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2910 return Error(ID.Loc, "element " + Twine(i) +
2911 " of struct initializer doesn't match struct element type");
2913 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2916 return Error(ID.Loc, "constant expression type mismatch");
2919 llvm_unreachable("Invalid ValID");
2922 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2925 return ParseValID(ID, PFS) ||
2926 ConvertValIDToValue(Ty, ID, V, PFS);
2929 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2931 return ParseType(Ty) ||
2932 ParseValue(Ty, V, PFS);
2935 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2936 PerFunctionState &PFS) {
2939 if (ParseTypeAndValue(V, PFS)) return true;
2940 if (!isa<BasicBlock>(V))
2941 return Error(Loc, "expected a basic block");
2942 BB = cast<BasicBlock>(V);
2948 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2949 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2950 /// OptionalAlign OptGC OptionalPrefix
2951 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2952 // Parse the linkage.
2953 LocTy LinkageLoc = Lex.getLoc();
2956 unsigned Visibility;
2957 unsigned DLLStorageClass;
2958 AttrBuilder RetAttrs;
2961 LocTy RetTypeLoc = Lex.getLoc();
2962 if (ParseOptionalLinkage(Linkage) ||
2963 ParseOptionalVisibility(Visibility) ||
2964 ParseOptionalDLLStorageClass(DLLStorageClass) ||
2965 ParseOptionalCallingConv(CC) ||
2966 ParseOptionalReturnAttrs(RetAttrs) ||
2967 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2970 // Verify that the linkage is ok.
2971 switch ((GlobalValue::LinkageTypes)Linkage) {
2972 case GlobalValue::ExternalLinkage:
2973 break; // always ok.
2974 case GlobalValue::ExternalWeakLinkage:
2976 return Error(LinkageLoc, "invalid linkage for function definition");
2978 case GlobalValue::PrivateLinkage:
2979 case GlobalValue::LinkerPrivateLinkage:
2980 case GlobalValue::LinkerPrivateWeakLinkage:
2981 case GlobalValue::InternalLinkage:
2982 case GlobalValue::AvailableExternallyLinkage:
2983 case GlobalValue::LinkOnceAnyLinkage:
2984 case GlobalValue::LinkOnceODRLinkage:
2985 case GlobalValue::WeakAnyLinkage:
2986 case GlobalValue::WeakODRLinkage:
2988 return Error(LinkageLoc, "invalid linkage for function declaration");
2990 case GlobalValue::AppendingLinkage:
2991 case GlobalValue::CommonLinkage:
2992 return Error(LinkageLoc, "invalid function linkage type");
2995 if (!FunctionType::isValidReturnType(RetType))
2996 return Error(RetTypeLoc, "invalid function return type");
2998 LocTy NameLoc = Lex.getLoc();
3000 std::string FunctionName;
3001 if (Lex.getKind() == lltok::GlobalVar) {
3002 FunctionName = Lex.getStrVal();
3003 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3004 unsigned NameID = Lex.getUIntVal();
3006 if (NameID != NumberedVals.size())
3007 return TokError("function expected to be numbered '%" +
3008 Twine(NumberedVals.size()) + "'");
3010 return TokError("expected function name");
3015 if (Lex.getKind() != lltok::lparen)
3016 return TokError("expected '(' in function argument list");
3018 SmallVector<ArgInfo, 8> ArgList;
3020 AttrBuilder FuncAttrs;
3021 std::vector<unsigned> FwdRefAttrGrps;
3023 std::string Section;
3027 LocTy UnnamedAddrLoc;
3028 Constant *Prefix = 0;
3030 if (ParseArgumentList(ArgList, isVarArg) ||
3031 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3033 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3035 (EatIfPresent(lltok::kw_section) &&
3036 ParseStringConstant(Section)) ||
3037 ParseOptionalAlignment(Alignment) ||
3038 (EatIfPresent(lltok::kw_gc) &&
3039 ParseStringConstant(GC)) ||
3040 (EatIfPresent(lltok::kw_prefix) &&
3041 ParseGlobalTypeAndValue(Prefix)))
3044 if (FuncAttrs.contains(Attribute::Builtin))
3045 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3047 // If the alignment was parsed as an attribute, move to the alignment field.
3048 if (FuncAttrs.hasAlignmentAttr()) {
3049 Alignment = FuncAttrs.getAlignment();
3050 FuncAttrs.removeAttribute(Attribute::Alignment);
3053 // Okay, if we got here, the function is syntactically valid. Convert types
3054 // and do semantic checks.
3055 std::vector<Type*> ParamTypeList;
3056 SmallVector<AttributeSet, 8> Attrs;
3058 if (RetAttrs.hasAttributes())
3059 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3060 AttributeSet::ReturnIndex,
3063 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3064 ParamTypeList.push_back(ArgList[i].Ty);
3065 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3066 AttrBuilder B(ArgList[i].Attrs, i + 1);
3067 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3071 if (FuncAttrs.hasAttributes())
3072 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3073 AttributeSet::FunctionIndex,
3076 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3078 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3079 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3082 FunctionType::get(RetType, ParamTypeList, isVarArg);
3083 PointerType *PFT = PointerType::getUnqual(FT);
3086 if (!FunctionName.empty()) {
3087 // If this was a definition of a forward reference, remove the definition
3088 // from the forward reference table and fill in the forward ref.
3089 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3090 ForwardRefVals.find(FunctionName);
3091 if (FRVI != ForwardRefVals.end()) {
3092 Fn = M->getFunction(FunctionName);
3094 return Error(FRVI->second.second, "invalid forward reference to "
3095 "function as global value!");
3096 if (Fn->getType() != PFT)
3097 return Error(FRVI->second.second, "invalid forward reference to "
3098 "function '" + FunctionName + "' with wrong type!");
3100 ForwardRefVals.erase(FRVI);
3101 } else if ((Fn = M->getFunction(FunctionName))) {
3102 // Reject redefinitions.
3103 return Error(NameLoc, "invalid redefinition of function '" +
3104 FunctionName + "'");
3105 } else if (M->getNamedValue(FunctionName)) {
3106 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3110 // If this is a definition of a forward referenced function, make sure the
3112 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3113 = ForwardRefValIDs.find(NumberedVals.size());
3114 if (I != ForwardRefValIDs.end()) {
3115 Fn = cast<Function>(I->second.first);
3116 if (Fn->getType() != PFT)
3117 return Error(NameLoc, "type of definition and forward reference of '@" +
3118 Twine(NumberedVals.size()) + "' disagree");
3119 ForwardRefValIDs.erase(I);
3124 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3125 else // Move the forward-reference to the correct spot in the module.
3126 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3128 if (FunctionName.empty())
3129 NumberedVals.push_back(Fn);
3131 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3132 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3133 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3134 Fn->setCallingConv(CC);
3135 Fn->setAttributes(PAL);
3136 Fn->setUnnamedAddr(UnnamedAddr);
3137 Fn->setAlignment(Alignment);
3138 Fn->setSection(Section);
3139 if (!GC.empty()) Fn->setGC(GC.c_str());
3140 Fn->setPrefixData(Prefix);
3141 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3143 // Add all of the arguments we parsed to the function.
3144 Function::arg_iterator ArgIt = Fn->arg_begin();
3145 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3146 // If the argument has a name, insert it into the argument symbol table.
3147 if (ArgList[i].Name.empty()) continue;
3149 // Set the name, if it conflicted, it will be auto-renamed.
3150 ArgIt->setName(ArgList[i].Name);
3152 if (ArgIt->getName() != ArgList[i].Name)
3153 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3154 ArgList[i].Name + "'");
3161 /// ParseFunctionBody
3162 /// ::= '{' BasicBlock+ '}'
3164 bool LLParser::ParseFunctionBody(Function &Fn) {
3165 if (Lex.getKind() != lltok::lbrace)
3166 return TokError("expected '{' in function body");
3167 Lex.Lex(); // eat the {.
3169 int FunctionNumber = -1;
3170 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3172 PerFunctionState PFS(*this, Fn, FunctionNumber);
3174 // We need at least one basic block.
3175 if (Lex.getKind() == lltok::rbrace)
3176 return TokError("function body requires at least one basic block");
3178 while (Lex.getKind() != lltok::rbrace)
3179 if (ParseBasicBlock(PFS)) return true;
3184 // Verify function is ok.
3185 return PFS.FinishFunction();
3189 /// ::= LabelStr? Instruction*
3190 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3191 // If this basic block starts out with a name, remember it.
3193 LocTy NameLoc = Lex.getLoc();
3194 if (Lex.getKind() == lltok::LabelStr) {
3195 Name = Lex.getStrVal();
3199 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3200 if (BB == 0) return true;
3202 std::string NameStr;
3204 // Parse the instructions in this block until we get a terminator.
3207 // This instruction may have three possibilities for a name: a) none
3208 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3209 LocTy NameLoc = Lex.getLoc();
3213 if (Lex.getKind() == lltok::LocalVarID) {
3214 NameID = Lex.getUIntVal();
3216 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3218 } else if (Lex.getKind() == lltok::LocalVar) {
3219 NameStr = Lex.getStrVal();
3221 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3225 switch (ParseInstruction(Inst, BB, PFS)) {
3226 default: llvm_unreachable("Unknown ParseInstruction result!");
3227 case InstError: return true;
3229 BB->getInstList().push_back(Inst);
3231 // With a normal result, we check to see if the instruction is followed by
3232 // a comma and metadata.
3233 if (EatIfPresent(lltok::comma))
3234 if (ParseInstructionMetadata(Inst, &PFS))
3237 case InstExtraComma:
3238 BB->getInstList().push_back(Inst);
3240 // If the instruction parser ate an extra comma at the end of it, it
3241 // *must* be followed by metadata.
3242 if (ParseInstructionMetadata(Inst, &PFS))
3247 // Set the name on the instruction.
3248 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3249 } while (!isa<TerminatorInst>(Inst));
3254 //===----------------------------------------------------------------------===//
3255 // Instruction Parsing.
3256 //===----------------------------------------------------------------------===//
3258 /// ParseInstruction - Parse one of the many different instructions.
3260 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3261 PerFunctionState &PFS) {
3262 lltok::Kind Token = Lex.getKind();
3263 if (Token == lltok::Eof)
3264 return TokError("found end of file when expecting more instructions");
3265 LocTy Loc = Lex.getLoc();
3266 unsigned KeywordVal = Lex.getUIntVal();
3267 Lex.Lex(); // Eat the keyword.
3270 default: return Error(Loc, "expected instruction opcode");
3271 // Terminator Instructions.
3272 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3273 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3274 case lltok::kw_br: return ParseBr(Inst, PFS);
3275 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3276 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3277 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3278 case lltok::kw_resume: return ParseResume(Inst, PFS);
3279 // Binary Operators.
3283 case lltok::kw_shl: {
3284 bool NUW = EatIfPresent(lltok::kw_nuw);
3285 bool NSW = EatIfPresent(lltok::kw_nsw);
3286 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3288 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3290 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3291 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3294 case lltok::kw_fadd:
3295 case lltok::kw_fsub:
3296 case lltok::kw_fmul:
3297 case lltok::kw_fdiv:
3298 case lltok::kw_frem: {
3299 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3300 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3304 Inst->setFastMathFlags(FMF);
3308 case lltok::kw_sdiv:
3309 case lltok::kw_udiv:
3310 case lltok::kw_lshr:
3311 case lltok::kw_ashr: {
3312 bool Exact = EatIfPresent(lltok::kw_exact);
3314 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3315 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3319 case lltok::kw_urem:
3320 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3323 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3324 case lltok::kw_icmp:
3325 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3327 case lltok::kw_trunc:
3328 case lltok::kw_zext:
3329 case lltok::kw_sext:
3330 case lltok::kw_fptrunc:
3331 case lltok::kw_fpext:
3332 case lltok::kw_bitcast:
3333 case lltok::kw_addrspacecast:
3334 case lltok::kw_uitofp:
3335 case lltok::kw_sitofp:
3336 case lltok::kw_fptoui:
3337 case lltok::kw_fptosi:
3338 case lltok::kw_inttoptr:
3339 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3341 case lltok::kw_select: return ParseSelect(Inst, PFS);
3342 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3343 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3344 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3345 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3346 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3347 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3348 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3349 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3351 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3352 case lltok::kw_load: return ParseLoad(Inst, PFS);
3353 case lltok::kw_store: return ParseStore(Inst, PFS);
3354 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3355 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3356 case lltok::kw_fence: return ParseFence(Inst, PFS);
3357 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3358 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3359 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3363 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3364 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3365 if (Opc == Instruction::FCmp) {
3366 switch (Lex.getKind()) {
3367 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3368 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3369 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3370 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3371 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3372 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3373 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3374 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3375 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3376 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3377 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3378 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3379 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3380 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3381 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3382 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3383 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3386 switch (Lex.getKind()) {
3387 default: return TokError("expected icmp predicate (e.g. 'eq')");
3388 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3389 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3390 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3391 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3392 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3393 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3394 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3395 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3396 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3397 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3404 //===----------------------------------------------------------------------===//
3405 // Terminator Instructions.
3406 //===----------------------------------------------------------------------===//
3408 /// ParseRet - Parse a return instruction.
3409 /// ::= 'ret' void (',' !dbg, !1)*
3410 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3411 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3412 PerFunctionState &PFS) {
3413 SMLoc TypeLoc = Lex.getLoc();
3415 if (ParseType(Ty, true /*void allowed*/)) return true;
3417 Type *ResType = PFS.getFunction().getReturnType();
3419 if (Ty->isVoidTy()) {
3420 if (!ResType->isVoidTy())
3421 return Error(TypeLoc, "value doesn't match function result type '" +
3422 getTypeString(ResType) + "'");
3424 Inst = ReturnInst::Create(Context);
3429 if (ParseValue(Ty, RV, PFS)) return true;
3431 if (ResType != RV->getType())
3432 return Error(TypeLoc, "value doesn't match function result type '" +
3433 getTypeString(ResType) + "'");
3435 Inst = ReturnInst::Create(Context, RV);
3441 /// ::= 'br' TypeAndValue
3442 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3443 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3446 BasicBlock *Op1, *Op2;
3447 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3449 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3450 Inst = BranchInst::Create(BB);
3454 if (Op0->getType() != Type::getInt1Ty(Context))
3455 return Error(Loc, "branch condition must have 'i1' type");
3457 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3458 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3459 ParseToken(lltok::comma, "expected ',' after true destination") ||
3460 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3463 Inst = BranchInst::Create(Op1, Op2, Op0);
3469 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3471 /// ::= (TypeAndValue ',' TypeAndValue)*
3472 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3473 LocTy CondLoc, BBLoc;
3475 BasicBlock *DefaultBB;
3476 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3477 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3478 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3479 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3482 if (!Cond->getType()->isIntegerTy())
3483 return Error(CondLoc, "switch condition must have integer type");
3485 // Parse the jump table pairs.
3486 SmallPtrSet<Value*, 32> SeenCases;
3487 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3488 while (Lex.getKind() != lltok::rsquare) {
3492 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3493 ParseToken(lltok::comma, "expected ',' after case value") ||
3494 ParseTypeAndBasicBlock(DestBB, PFS))
3497 if (!SeenCases.insert(Constant))
3498 return Error(CondLoc, "duplicate case value in switch");
3499 if (!isa<ConstantInt>(Constant))
3500 return Error(CondLoc, "case value is not a constant integer");
3502 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3505 Lex.Lex(); // Eat the ']'.
3507 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3508 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3509 SI->addCase(Table[i].first, Table[i].second);
3516 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3517 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3520 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3521 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3522 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3525 if (!Address->getType()->isPointerTy())
3526 return Error(AddrLoc, "indirectbr address must have pointer type");
3528 // Parse the destination list.
3529 SmallVector<BasicBlock*, 16> DestList;
3531 if (Lex.getKind() != lltok::rsquare) {
3533 if (ParseTypeAndBasicBlock(DestBB, PFS))
3535 DestList.push_back(DestBB);
3537 while (EatIfPresent(lltok::comma)) {
3538 if (ParseTypeAndBasicBlock(DestBB, PFS))
3540 DestList.push_back(DestBB);
3544 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3547 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3548 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3549 IBI->addDestination(DestList[i]);
3556 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3557 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3558 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3559 LocTy CallLoc = Lex.getLoc();
3560 AttrBuilder RetAttrs, FnAttrs;
3561 std::vector<unsigned> FwdRefAttrGrps;
3567 SmallVector<ParamInfo, 16> ArgList;
3569 BasicBlock *NormalBB, *UnwindBB;
3570 if (ParseOptionalCallingConv(CC) ||
3571 ParseOptionalReturnAttrs(RetAttrs) ||
3572 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3573 ParseValID(CalleeID) ||
3574 ParseParameterList(ArgList, PFS) ||
3575 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3577 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3578 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3579 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3580 ParseTypeAndBasicBlock(UnwindBB, PFS))
3583 // If RetType is a non-function pointer type, then this is the short syntax
3584 // for the call, which means that RetType is just the return type. Infer the
3585 // rest of the function argument types from the arguments that are present.
3586 PointerType *PFTy = 0;
3587 FunctionType *Ty = 0;
3588 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3589 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3590 // Pull out the types of all of the arguments...
3591 std::vector<Type*> ParamTypes;
3592 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3593 ParamTypes.push_back(ArgList[i].V->getType());
3595 if (!FunctionType::isValidReturnType(RetType))
3596 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3598 Ty = FunctionType::get(RetType, ParamTypes, false);
3599 PFTy = PointerType::getUnqual(Ty);
3602 // Look up the callee.
3604 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3606 // Set up the Attribute for the function.
3607 SmallVector<AttributeSet, 8> Attrs;
3608 if (RetAttrs.hasAttributes())
3609 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3610 AttributeSet::ReturnIndex,
3613 SmallVector<Value*, 8> Args;
3615 // Loop through FunctionType's arguments and ensure they are specified
3616 // correctly. Also, gather any parameter attributes.
3617 FunctionType::param_iterator I = Ty->param_begin();
3618 FunctionType::param_iterator E = Ty->param_end();
3619 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3620 Type *ExpectedTy = 0;
3623 } else if (!Ty->isVarArg()) {
3624 return Error(ArgList[i].Loc, "too many arguments specified");
3627 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3628 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3629 getTypeString(ExpectedTy) + "'");
3630 Args.push_back(ArgList[i].V);
3631 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3632 AttrBuilder B(ArgList[i].Attrs, i + 1);
3633 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3638 return Error(CallLoc, "not enough parameters specified for call");
3640 if (FnAttrs.hasAttributes())
3641 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3642 AttributeSet::FunctionIndex,
3645 // Finish off the Attribute and check them
3646 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3648 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3649 II->setCallingConv(CC);
3650 II->setAttributes(PAL);
3651 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3657 /// ::= 'resume' TypeAndValue
3658 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3659 Value *Exn; LocTy ExnLoc;
3660 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3663 ResumeInst *RI = ResumeInst::Create(Exn);
3668 //===----------------------------------------------------------------------===//
3669 // Binary Operators.
3670 //===----------------------------------------------------------------------===//
3673 /// ::= ArithmeticOps TypeAndValue ',' Value
3675 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3676 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3677 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3678 unsigned Opc, unsigned OperandType) {
3679 LocTy Loc; Value *LHS, *RHS;
3680 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3681 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3682 ParseValue(LHS->getType(), RHS, PFS))
3686 switch (OperandType) {
3687 default: llvm_unreachable("Unknown operand type!");
3688 case 0: // int or FP.
3689 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3690 LHS->getType()->isFPOrFPVectorTy();
3692 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3693 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3697 return Error(Loc, "invalid operand type for instruction");
3699 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3704 /// ::= ArithmeticOps TypeAndValue ',' Value {
3705 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3707 LocTy Loc; Value *LHS, *RHS;
3708 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3709 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3710 ParseValue(LHS->getType(), RHS, PFS))
3713 if (!LHS->getType()->isIntOrIntVectorTy())
3714 return Error(Loc,"instruction requires integer or integer vector operands");
3716 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3722 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3723 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3724 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3726 // Parse the integer/fp comparison predicate.
3730 if (ParseCmpPredicate(Pred, Opc) ||
3731 ParseTypeAndValue(LHS, Loc, PFS) ||
3732 ParseToken(lltok::comma, "expected ',' after compare value") ||
3733 ParseValue(LHS->getType(), RHS, PFS))
3736 if (Opc == Instruction::FCmp) {
3737 if (!LHS->getType()->isFPOrFPVectorTy())
3738 return Error(Loc, "fcmp requires floating point operands");
3739 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3741 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3742 if (!LHS->getType()->isIntOrIntVectorTy() &&
3743 !LHS->getType()->getScalarType()->isPointerTy())
3744 return Error(Loc, "icmp requires integer operands");
3745 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3750 //===----------------------------------------------------------------------===//
3751 // Other Instructions.
3752 //===----------------------------------------------------------------------===//
3756 /// ::= CastOpc TypeAndValue 'to' Type
3757 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3762 if (ParseTypeAndValue(Op, Loc, PFS) ||
3763 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3767 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3768 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3769 return Error(Loc, "invalid cast opcode for cast from '" +
3770 getTypeString(Op->getType()) + "' to '" +
3771 getTypeString(DestTy) + "'");
3773 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3778 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3779 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3781 Value *Op0, *Op1, *Op2;
3782 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3783 ParseToken(lltok::comma, "expected ',' after select condition") ||
3784 ParseTypeAndValue(Op1, PFS) ||
3785 ParseToken(lltok::comma, "expected ',' after select value") ||
3786 ParseTypeAndValue(Op2, PFS))
3789 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3790 return Error(Loc, Reason);
3792 Inst = SelectInst::Create(Op0, Op1, Op2);
3797 /// ::= 'va_arg' TypeAndValue ',' Type
3798 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3802 if (ParseTypeAndValue(Op, PFS) ||
3803 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3804 ParseType(EltTy, TypeLoc))
3807 if (!EltTy->isFirstClassType())
3808 return Error(TypeLoc, "va_arg requires operand with first class type");
3810 Inst = new VAArgInst(Op, EltTy);
3814 /// ParseExtractElement
3815 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3816 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3819 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3820 ParseToken(lltok::comma, "expected ',' after extract value") ||
3821 ParseTypeAndValue(Op1, PFS))
3824 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3825 return Error(Loc, "invalid extractelement operands");
3827 Inst = ExtractElementInst::Create(Op0, Op1);
3831 /// ParseInsertElement
3832 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3833 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3835 Value *Op0, *Op1, *Op2;
3836 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3837 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3838 ParseTypeAndValue(Op1, PFS) ||
3839 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3840 ParseTypeAndValue(Op2, PFS))
3843 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3844 return Error(Loc, "invalid insertelement operands");
3846 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3850 /// ParseShuffleVector
3851 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3852 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3854 Value *Op0, *Op1, *Op2;
3855 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3856 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3857 ParseTypeAndValue(Op1, PFS) ||
3858 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3859 ParseTypeAndValue(Op2, PFS))
3862 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3863 return Error(Loc, "invalid shufflevector operands");
3865 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3870 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3871 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3872 Type *Ty = 0; LocTy TypeLoc;
3875 if (ParseType(Ty, TypeLoc) ||
3876 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3877 ParseValue(Ty, Op0, PFS) ||
3878 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3879 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3880 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3883 bool AteExtraComma = false;
3884 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3886 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3888 if (!EatIfPresent(lltok::comma))
3891 if (Lex.getKind() == lltok::MetadataVar) {
3892 AteExtraComma = true;
3896 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3897 ParseValue(Ty, Op0, PFS) ||
3898 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3899 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3900 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3904 if (!Ty->isFirstClassType())
3905 return Error(TypeLoc, "phi node must have first class type");
3907 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3908 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3909 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3911 return AteExtraComma ? InstExtraComma : InstNormal;
3915 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3917 /// ::= 'catch' TypeAndValue
3919 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3920 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3921 Type *Ty = 0; LocTy TyLoc;
3922 Value *PersFn; LocTy PersFnLoc;
3924 if (ParseType(Ty, TyLoc) ||
3925 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3926 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3929 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3930 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3932 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3933 LandingPadInst::ClauseType CT;
3934 if (EatIfPresent(lltok::kw_catch))
3935 CT = LandingPadInst::Catch;
3936 else if (EatIfPresent(lltok::kw_filter))
3937 CT = LandingPadInst::Filter;
3939 return TokError("expected 'catch' or 'filter' clause type");
3941 Value *V; LocTy VLoc;
3942 if (ParseTypeAndValue(V, VLoc, PFS)) {
3947 // A 'catch' type expects a non-array constant. A filter clause expects an
3949 if (CT == LandingPadInst::Catch) {
3950 if (isa<ArrayType>(V->getType()))
3951 Error(VLoc, "'catch' clause has an invalid type");
3953 if (!isa<ArrayType>(V->getType()))
3954 Error(VLoc, "'filter' clause has an invalid type");
3965 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3966 /// ParameterList OptionalAttrs
3967 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3969 AttrBuilder RetAttrs, FnAttrs;
3970 std::vector<unsigned> FwdRefAttrGrps;
3976 SmallVector<ParamInfo, 16> ArgList;
3977 LocTy CallLoc = Lex.getLoc();
3979 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3980 ParseOptionalCallingConv(CC) ||
3981 ParseOptionalReturnAttrs(RetAttrs) ||
3982 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3983 ParseValID(CalleeID) ||
3984 ParseParameterList(ArgList, PFS) ||
3985 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3989 // If RetType is a non-function pointer type, then this is the short syntax
3990 // for the call, which means that RetType is just the return type. Infer the
3991 // rest of the function argument types from the arguments that are present.
3992 PointerType *PFTy = 0;
3993 FunctionType *Ty = 0;
3994 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3995 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3996 // Pull out the types of all of the arguments...
3997 std::vector<Type*> ParamTypes;
3998 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3999 ParamTypes.push_back(ArgList[i].V->getType());
4001 if (!FunctionType::isValidReturnType(RetType))
4002 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4004 Ty = FunctionType::get(RetType, ParamTypes, false);
4005 PFTy = PointerType::getUnqual(Ty);
4008 // Look up the callee.
4010 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4012 // Set up the Attribute for the function.
4013 SmallVector<AttributeSet, 8> Attrs;
4014 if (RetAttrs.hasAttributes())
4015 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4016 AttributeSet::ReturnIndex,
4019 SmallVector<Value*, 8> Args;
4021 // Loop through FunctionType's arguments and ensure they are specified
4022 // correctly. Also, gather any parameter attributes.
4023 FunctionType::param_iterator I = Ty->param_begin();
4024 FunctionType::param_iterator E = Ty->param_end();
4025 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4026 Type *ExpectedTy = 0;
4029 } else if (!Ty->isVarArg()) {
4030 return Error(ArgList[i].Loc, "too many arguments specified");
4033 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4034 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4035 getTypeString(ExpectedTy) + "'");
4036 Args.push_back(ArgList[i].V);
4037 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4038 AttrBuilder B(ArgList[i].Attrs, i + 1);
4039 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4044 return Error(CallLoc, "not enough parameters specified for call");
4046 if (FnAttrs.hasAttributes())
4047 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4048 AttributeSet::FunctionIndex,
4051 // Finish off the Attribute and check them
4052 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4054 CallInst *CI = CallInst::Create(Callee, Args);
4055 CI->setTailCall(isTail);
4056 CI->setCallingConv(CC);
4057 CI->setAttributes(PAL);
4058 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4063 //===----------------------------------------------------------------------===//
4064 // Memory Instructions.
4065 //===----------------------------------------------------------------------===//
4068 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
4069 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4072 unsigned Alignment = 0;
4074 if (ParseType(Ty)) return true;
4076 bool AteExtraComma = false;
4077 if (EatIfPresent(lltok::comma)) {
4078 if (Lex.getKind() == lltok::kw_align) {
4079 if (ParseOptionalAlignment(Alignment)) return true;
4080 } else if (Lex.getKind() == lltok::MetadataVar) {
4081 AteExtraComma = true;
4083 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4084 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4089 if (Size && !Size->getType()->isIntegerTy())
4090 return Error(SizeLoc, "element count must have integer type");
4092 Inst = new AllocaInst(Ty, Size, Alignment);
4093 return AteExtraComma ? InstExtraComma : InstNormal;
4097 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4098 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4099 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4100 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4101 Value *Val; LocTy Loc;
4102 unsigned Alignment = 0;
4103 bool AteExtraComma = false;
4104 bool isAtomic = false;
4105 AtomicOrdering Ordering = NotAtomic;
4106 SynchronizationScope Scope = CrossThread;
4108 if (Lex.getKind() == lltok::kw_atomic) {
4113 bool isVolatile = false;
4114 if (Lex.getKind() == lltok::kw_volatile) {
4119 if (ParseTypeAndValue(Val, Loc, PFS) ||
4120 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4121 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4124 if (!Val->getType()->isPointerTy() ||
4125 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4126 return Error(Loc, "load operand must be a pointer to a first class type");
4127 if (isAtomic && !Alignment)
4128 return Error(Loc, "atomic load must have explicit non-zero alignment");
4129 if (Ordering == Release || Ordering == AcquireRelease)
4130 return Error(Loc, "atomic load cannot use Release ordering");
4132 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4133 return AteExtraComma ? InstExtraComma : InstNormal;
4138 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4139 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4140 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4141 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4142 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4143 unsigned Alignment = 0;
4144 bool AteExtraComma = false;
4145 bool isAtomic = false;
4146 AtomicOrdering Ordering = NotAtomic;
4147 SynchronizationScope Scope = CrossThread;
4149 if (Lex.getKind() == lltok::kw_atomic) {
4154 bool isVolatile = false;
4155 if (Lex.getKind() == lltok::kw_volatile) {
4160 if (ParseTypeAndValue(Val, Loc, PFS) ||
4161 ParseToken(lltok::comma, "expected ',' after store operand") ||
4162 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4163 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4164 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4167 if (!Ptr->getType()->isPointerTy())
4168 return Error(PtrLoc, "store operand must be a pointer");
4169 if (!Val->getType()->isFirstClassType())
4170 return Error(Loc, "store operand must be a first class value");
4171 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4172 return Error(Loc, "stored value and pointer type do not match");
4173 if (isAtomic && !Alignment)
4174 return Error(Loc, "atomic store must have explicit non-zero alignment");
4175 if (Ordering == Acquire || Ordering == AcquireRelease)
4176 return Error(Loc, "atomic store cannot use Acquire ordering");
4178 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4179 return AteExtraComma ? InstExtraComma : InstNormal;
4183 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4184 /// 'singlethread'? AtomicOrdering
4185 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4186 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4187 bool AteExtraComma = false;
4188 AtomicOrdering Ordering = NotAtomic;
4189 SynchronizationScope Scope = CrossThread;
4190 bool isVolatile = false;
4192 if (EatIfPresent(lltok::kw_volatile))
4195 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4196 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4197 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4198 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4199 ParseTypeAndValue(New, NewLoc, PFS) ||
4200 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4203 if (Ordering == Unordered)
4204 return TokError("cmpxchg cannot be unordered");
4205 if (!Ptr->getType()->isPointerTy())
4206 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4207 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4208 return Error(CmpLoc, "compare value and pointer type do not match");
4209 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4210 return Error(NewLoc, "new value and pointer type do not match");
4211 if (!New->getType()->isIntegerTy())
4212 return Error(NewLoc, "cmpxchg operand must be an integer");
4213 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4214 if (Size < 8 || (Size & (Size - 1)))
4215 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4218 AtomicCmpXchgInst *CXI =
4219 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
4220 CXI->setVolatile(isVolatile);
4222 return AteExtraComma ? InstExtraComma : InstNormal;
4226 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4227 /// 'singlethread'? AtomicOrdering
4228 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4229 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4230 bool AteExtraComma = false;
4231 AtomicOrdering Ordering = NotAtomic;
4232 SynchronizationScope Scope = CrossThread;
4233 bool isVolatile = false;
4234 AtomicRMWInst::BinOp Operation;
4236 if (EatIfPresent(lltok::kw_volatile))
4239 switch (Lex.getKind()) {
4240 default: return TokError("expected binary operation in atomicrmw");
4241 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4242 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4243 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4244 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4245 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4246 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4247 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4248 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4249 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4250 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4251 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4253 Lex.Lex(); // Eat the operation.
4255 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4256 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4257 ParseTypeAndValue(Val, ValLoc, PFS) ||
4258 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4261 if (Ordering == Unordered)
4262 return TokError("atomicrmw cannot be unordered");
4263 if (!Ptr->getType()->isPointerTy())
4264 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4265 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4266 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4267 if (!Val->getType()->isIntegerTy())
4268 return Error(ValLoc, "atomicrmw operand must be an integer");
4269 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4270 if (Size < 8 || (Size & (Size - 1)))
4271 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4274 AtomicRMWInst *RMWI =
4275 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4276 RMWI->setVolatile(isVolatile);
4278 return AteExtraComma ? InstExtraComma : InstNormal;
4282 /// ::= 'fence' 'singlethread'? AtomicOrdering
4283 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4284 AtomicOrdering Ordering = NotAtomic;
4285 SynchronizationScope Scope = CrossThread;
4286 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4289 if (Ordering == Unordered)
4290 return TokError("fence cannot be unordered");
4291 if (Ordering == Monotonic)
4292 return TokError("fence cannot be monotonic");
4294 Inst = new FenceInst(Context, Ordering, Scope);
4298 /// ParseGetElementPtr
4299 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4300 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4305 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4307 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4309 Type *BaseType = Ptr->getType();
4310 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4311 if (!BasePointerType)
4312 return Error(Loc, "base of getelementptr must be a pointer");
4314 SmallVector<Value*, 16> Indices;
4315 bool AteExtraComma = false;
4316 while (EatIfPresent(lltok::comma)) {
4317 if (Lex.getKind() == lltok::MetadataVar) {
4318 AteExtraComma = true;
4321 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4322 if (!Val->getType()->getScalarType()->isIntegerTy())
4323 return Error(EltLoc, "getelementptr index must be an integer");
4324 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4325 return Error(EltLoc, "getelementptr index type missmatch");
4326 if (Val->getType()->isVectorTy()) {
4327 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4328 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4329 if (ValNumEl != PtrNumEl)
4330 return Error(EltLoc,
4331 "getelementptr vector index has a wrong number of elements");
4333 Indices.push_back(Val);
4336 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4337 return Error(Loc, "base element of getelementptr must be sized");
4339 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4340 return Error(Loc, "invalid getelementptr indices");
4341 Inst = GetElementPtrInst::Create(Ptr, Indices);
4343 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4344 return AteExtraComma ? InstExtraComma : InstNormal;
4347 /// ParseExtractValue
4348 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4349 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4350 Value *Val; LocTy Loc;
4351 SmallVector<unsigned, 4> Indices;
4353 if (ParseTypeAndValue(Val, Loc, PFS) ||
4354 ParseIndexList(Indices, AteExtraComma))
4357 if (!Val->getType()->isAggregateType())
4358 return Error(Loc, "extractvalue operand must be aggregate type");
4360 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4361 return Error(Loc, "invalid indices for extractvalue");
4362 Inst = ExtractValueInst::Create(Val, Indices);
4363 return AteExtraComma ? InstExtraComma : InstNormal;
4366 /// ParseInsertValue
4367 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4368 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4369 Value *Val0, *Val1; LocTy Loc0, Loc1;
4370 SmallVector<unsigned, 4> Indices;
4372 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4373 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4374 ParseTypeAndValue(Val1, Loc1, PFS) ||
4375 ParseIndexList(Indices, AteExtraComma))
4378 if (!Val0->getType()->isAggregateType())
4379 return Error(Loc0, "insertvalue operand must be aggregate type");
4381 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4382 return Error(Loc0, "invalid indices for insertvalue");
4383 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4384 return AteExtraComma ? InstExtraComma : InstNormal;
4387 //===----------------------------------------------------------------------===//
4388 // Embedded metadata.
4389 //===----------------------------------------------------------------------===//
4391 /// ParseMDNodeVector
4392 /// ::= Element (',' Element)*
4394 /// ::= 'null' | TypeAndValue
4395 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4396 PerFunctionState *PFS) {
4397 // Check for an empty list.
4398 if (Lex.getKind() == lltok::rbrace)
4402 // Null is a special case since it is typeless.
4403 if (EatIfPresent(lltok::kw_null)) {
4409 if (ParseTypeAndValue(V, PFS)) return true;
4411 } while (EatIfPresent(lltok::comma));