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/Module.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/IR/ValueSymbolTable.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
29 static std::string getTypeString(Type *T) {
31 raw_string_ostream Tmp(Result);
36 /// Run: module ::= toplevelentity*
37 bool LLParser::Run() {
41 return ParseTopLevelEntities() ||
42 ValidateEndOfModule();
45 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
47 bool LLParser::ValidateEndOfModule() {
48 // Handle any instruction metadata forward references.
49 if (!ForwardRefInstMetadata.empty()) {
50 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
51 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
53 Instruction *Inst = I->first;
54 const std::vector<MDRef> &MDList = I->second;
56 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
57 unsigned SlotNo = MDList[i].MDSlot;
59 if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
60 return Error(MDList[i].Loc, "use of undefined metadata '!" +
62 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
65 ForwardRefInstMetadata.clear();
68 // Handle any function attribute group forward references.
69 for (std::map<Value*, std::vector<unsigned> >::iterator
70 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
73 std::vector<unsigned> &Vec = I->second;
76 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
78 B.merge(NumberedAttrBuilders[*VI]);
80 if (Function *Fn = dyn_cast<Function>(V)) {
81 AttributeSet AS = Fn->getAttributes();
82 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
83 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
84 AS.getFnAttributes());
88 // If the alignment was parsed as an attribute, move to the alignment
90 if (FnAttrs.hasAlignmentAttr()) {
91 Fn->setAlignment(FnAttrs.getAlignment());
92 FnAttrs.removeAttribute(Attribute::Alignment);
95 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
96 AttributeSet::get(Context,
97 AttributeSet::FunctionIndex,
99 Fn->setAttributes(AS);
100 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
101 AttributeSet AS = CI->getAttributes();
102 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
103 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
104 AS.getFnAttributes());
106 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
107 AttributeSet::get(Context,
108 AttributeSet::FunctionIndex,
110 CI->setAttributes(AS);
111 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
112 AttributeSet AS = II->getAttributes();
113 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
114 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
115 AS.getFnAttributes());
117 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
118 AttributeSet::get(Context,
119 AttributeSet::FunctionIndex,
121 II->setAttributes(AS);
123 llvm_unreachable("invalid object with forward attribute group reference");
127 // If there are entries in ForwardRefBlockAddresses at this point, they are
128 // references after the function was defined. Resolve those now.
129 while (!ForwardRefBlockAddresses.empty()) {
130 // Okay, we are referencing an already-parsed function, resolve them now.
132 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
133 if (Fn.Kind == ValID::t_GlobalName)
134 TheFn = M->getFunction(Fn.StrVal);
135 else if (Fn.UIntVal < NumberedVals.size())
136 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
139 return Error(Fn.Loc, "unknown function referenced by blockaddress");
141 // Resolve all these references.
142 if (ResolveForwardRefBlockAddresses(TheFn,
143 ForwardRefBlockAddresses.begin()->second,
147 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
150 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
151 if (NumberedTypes[i].second.isValid())
152 return Error(NumberedTypes[i].second,
153 "use of undefined type '%" + Twine(i) + "'");
155 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
156 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
157 if (I->second.second.isValid())
158 return Error(I->second.second,
159 "use of undefined type named '" + I->getKey() + "'");
161 if (!ForwardRefVals.empty())
162 return Error(ForwardRefVals.begin()->second.second,
163 "use of undefined value '@" + ForwardRefVals.begin()->first +
166 if (!ForwardRefValIDs.empty())
167 return Error(ForwardRefValIDs.begin()->second.second,
168 "use of undefined value '@" +
169 Twine(ForwardRefValIDs.begin()->first) + "'");
171 if (!ForwardRefMDNodes.empty())
172 return Error(ForwardRefMDNodes.begin()->second.second,
173 "use of undefined metadata '!" +
174 Twine(ForwardRefMDNodes.begin()->first) + "'");
177 // Look for intrinsic functions and CallInst that need to be upgraded
178 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
179 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
184 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
185 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
186 PerFunctionState *PFS) {
187 // Loop over all the references, resolving them.
188 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
191 if (Refs[i].first.Kind == ValID::t_LocalName)
192 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
194 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
195 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
196 return Error(Refs[i].first.Loc,
197 "cannot take address of numeric label after the function is defined");
199 Res = dyn_cast_or_null<BasicBlock>(
200 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
204 return Error(Refs[i].first.Loc,
205 "referenced value is not a basic block");
207 // Get the BlockAddress for this and update references to use it.
208 BlockAddress *BA = BlockAddress::get(TheFn, Res);
209 Refs[i].second->replaceAllUsesWith(BA);
210 Refs[i].second->eraseFromParent();
216 //===----------------------------------------------------------------------===//
217 // Top-Level Entities
218 //===----------------------------------------------------------------------===//
220 bool LLParser::ParseTopLevelEntities() {
222 switch (Lex.getKind()) {
223 default: return TokError("expected top-level entity");
224 case lltok::Eof: return false;
225 case lltok::kw_declare: if (ParseDeclare()) return true; break;
226 case lltok::kw_define: if (ParseDefine()) return true; break;
227 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
228 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
229 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
230 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
231 case lltok::LocalVar: if (ParseNamedType()) return true; break;
232 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
233 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
234 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
235 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
236 case lltok::AttrGrpID: if (ParseUnnamedAttrGrp()) return true; break;
238 // The Global variable production with no name can have many different
239 // optional leading prefixes, the production is:
240 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
241 // OptionalAddrSpace OptionalUnNammedAddr
242 // ('constant'|'global') ...
243 case lltok::kw_private: // OptionalLinkage
244 case lltok::kw_linker_private: // OptionalLinkage
245 case lltok::kw_linker_private_weak: // OptionalLinkage
246 case lltok::kw_linker_private_weak_def_auto: // FIXME: backwards compat.
247 case lltok::kw_internal: // OptionalLinkage
248 case lltok::kw_weak: // OptionalLinkage
249 case lltok::kw_weak_odr: // OptionalLinkage
250 case lltok::kw_linkonce: // OptionalLinkage
251 case lltok::kw_linkonce_odr: // OptionalLinkage
252 case lltok::kw_linkonce_odr_auto_hide: // OptionalLinkage
253 case lltok::kw_appending: // OptionalLinkage
254 case lltok::kw_dllexport: // OptionalLinkage
255 case lltok::kw_common: // OptionalLinkage
256 case lltok::kw_dllimport: // OptionalLinkage
257 case lltok::kw_extern_weak: // OptionalLinkage
258 case lltok::kw_external: { // OptionalLinkage
259 unsigned Linkage, Visibility;
260 if (ParseOptionalLinkage(Linkage) ||
261 ParseOptionalVisibility(Visibility) ||
262 ParseGlobal("", SMLoc(), Linkage, true, Visibility))
266 case lltok::kw_default: // OptionalVisibility
267 case lltok::kw_hidden: // OptionalVisibility
268 case lltok::kw_protected: { // OptionalVisibility
270 if (ParseOptionalVisibility(Visibility) ||
271 ParseGlobal("", SMLoc(), 0, false, Visibility))
276 case lltok::kw_thread_local: // OptionalThreadLocal
277 case lltok::kw_addrspace: // OptionalAddrSpace
278 case lltok::kw_constant: // GlobalType
279 case lltok::kw_global: // GlobalType
280 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
288 /// ::= 'module' 'asm' STRINGCONSTANT
289 bool LLParser::ParseModuleAsm() {
290 assert(Lex.getKind() == lltok::kw_module);
294 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
295 ParseStringConstant(AsmStr)) return true;
297 M->appendModuleInlineAsm(AsmStr);
302 /// ::= 'target' 'triple' '=' STRINGCONSTANT
303 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
304 bool LLParser::ParseTargetDefinition() {
305 assert(Lex.getKind() == lltok::kw_target);
308 default: return TokError("unknown target property");
309 case lltok::kw_triple:
311 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
312 ParseStringConstant(Str))
314 M->setTargetTriple(Str);
316 case lltok::kw_datalayout:
318 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
319 ParseStringConstant(Str))
321 M->setDataLayout(Str);
327 /// ::= 'deplibs' '=' '[' ']'
328 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
329 /// FIXME: Remove in 4.0. Currently parse, but ignore.
330 bool LLParser::ParseDepLibs() {
331 assert(Lex.getKind() == lltok::kw_deplibs);
333 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
334 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
337 if (EatIfPresent(lltok::rsquare))
342 if (ParseStringConstant(Str)) return true;
343 } while (EatIfPresent(lltok::comma));
345 return ParseToken(lltok::rsquare, "expected ']' at end of list");
348 /// ParseUnnamedType:
349 /// ::= LocalVarID '=' 'type' type
350 bool LLParser::ParseUnnamedType() {
351 LocTy TypeLoc = Lex.getLoc();
352 unsigned TypeID = Lex.getUIntVal();
353 Lex.Lex(); // eat LocalVarID;
355 if (ParseToken(lltok::equal, "expected '=' after name") ||
356 ParseToken(lltok::kw_type, "expected 'type' after '='"))
359 if (TypeID >= NumberedTypes.size())
360 NumberedTypes.resize(TypeID+1);
363 if (ParseStructDefinition(TypeLoc, "",
364 NumberedTypes[TypeID], Result)) return true;
366 if (!isa<StructType>(Result)) {
367 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
369 return Error(TypeLoc, "non-struct types may not be recursive");
370 Entry.first = Result;
371 Entry.second = SMLoc();
379 /// ::= LocalVar '=' 'type' type
380 bool LLParser::ParseNamedType() {
381 std::string Name = Lex.getStrVal();
382 LocTy NameLoc = Lex.getLoc();
383 Lex.Lex(); // eat LocalVar.
385 if (ParseToken(lltok::equal, "expected '=' after name") ||
386 ParseToken(lltok::kw_type, "expected 'type' after name"))
390 if (ParseStructDefinition(NameLoc, Name,
391 NamedTypes[Name], Result)) return true;
393 if (!isa<StructType>(Result)) {
394 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
396 return Error(NameLoc, "non-struct types may not be recursive");
397 Entry.first = Result;
398 Entry.second = SMLoc();
406 /// ::= 'declare' FunctionHeader
407 bool LLParser::ParseDeclare() {
408 assert(Lex.getKind() == lltok::kw_declare);
412 return ParseFunctionHeader(F, false);
416 /// ::= 'define' FunctionHeader '{' ...
417 bool LLParser::ParseDefine() {
418 assert(Lex.getKind() == lltok::kw_define);
422 return ParseFunctionHeader(F, true) ||
423 ParseFunctionBody(*F);
429 bool LLParser::ParseGlobalType(bool &IsConstant) {
430 if (Lex.getKind() == lltok::kw_constant)
432 else if (Lex.getKind() == lltok::kw_global)
436 return TokError("expected 'global' or 'constant'");
442 /// ParseUnnamedGlobal:
443 /// OptionalVisibility ALIAS ...
444 /// OptionalLinkage OptionalVisibility ... -> global variable
445 /// GlobalID '=' OptionalVisibility ALIAS ...
446 /// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
447 bool LLParser::ParseUnnamedGlobal() {
448 unsigned VarID = NumberedVals.size();
450 LocTy NameLoc = Lex.getLoc();
452 // Handle the GlobalID form.
453 if (Lex.getKind() == lltok::GlobalID) {
454 if (Lex.getUIntVal() != VarID)
455 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
457 Lex.Lex(); // eat GlobalID;
459 if (ParseToken(lltok::equal, "expected '=' after name"))
464 unsigned Linkage, Visibility;
465 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
466 ParseOptionalVisibility(Visibility))
469 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
470 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
471 return ParseAlias(Name, NameLoc, Visibility);
474 /// ParseNamedGlobal:
475 /// GlobalVar '=' OptionalVisibility ALIAS ...
476 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
477 bool LLParser::ParseNamedGlobal() {
478 assert(Lex.getKind() == lltok::GlobalVar);
479 LocTy NameLoc = Lex.getLoc();
480 std::string Name = Lex.getStrVal();
484 unsigned Linkage, Visibility;
485 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
486 ParseOptionalLinkage(Linkage, HasLinkage) ||
487 ParseOptionalVisibility(Visibility))
490 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
491 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
492 return ParseAlias(Name, NameLoc, Visibility);
496 // ::= '!' STRINGCONSTANT
497 bool LLParser::ParseMDString(MDString *&Result) {
499 if (ParseStringConstant(Str)) return true;
500 Result = MDString::get(Context, Str);
505 // ::= '!' MDNodeNumber
507 /// This version of ParseMDNodeID returns the slot number and null in the case
508 /// of a forward reference.
509 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
510 // !{ ..., !42, ... }
511 if (ParseUInt32(SlotNo)) return true;
513 // Check existing MDNode.
514 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
515 Result = NumberedMetadata[SlotNo];
521 bool LLParser::ParseMDNodeID(MDNode *&Result) {
522 // !{ ..., !42, ... }
524 if (ParseMDNodeID(Result, MID)) return true;
526 // If not a forward reference, just return it now.
527 if (Result) return false;
529 // Otherwise, create MDNode forward reference.
530 MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
531 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
533 if (NumberedMetadata.size() <= MID)
534 NumberedMetadata.resize(MID+1);
535 NumberedMetadata[MID] = FwdNode;
540 /// ParseNamedMetadata:
541 /// !foo = !{ !1, !2 }
542 bool LLParser::ParseNamedMetadata() {
543 assert(Lex.getKind() == lltok::MetadataVar);
544 std::string Name = Lex.getStrVal();
547 if (ParseToken(lltok::equal, "expected '=' here") ||
548 ParseToken(lltok::exclaim, "Expected '!' here") ||
549 ParseToken(lltok::lbrace, "Expected '{' here"))
552 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
553 if (Lex.getKind() != lltok::rbrace)
555 if (ParseToken(lltok::exclaim, "Expected '!' here"))
559 if (ParseMDNodeID(N)) return true;
561 } while (EatIfPresent(lltok::comma));
563 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
569 /// ParseStandaloneMetadata:
571 bool LLParser::ParseStandaloneMetadata() {
572 assert(Lex.getKind() == lltok::exclaim);
574 unsigned MetadataID = 0;
578 SmallVector<Value *, 16> Elts;
579 if (ParseUInt32(MetadataID) ||
580 ParseToken(lltok::equal, "expected '=' here") ||
581 ParseType(Ty, TyLoc) ||
582 ParseToken(lltok::exclaim, "Expected '!' here") ||
583 ParseToken(lltok::lbrace, "Expected '{' here") ||
584 ParseMDNodeVector(Elts, NULL) ||
585 ParseToken(lltok::rbrace, "expected end of metadata node"))
588 MDNode *Init = MDNode::get(Context, Elts);
590 // See if this was forward referenced, if so, handle it.
591 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
592 FI = ForwardRefMDNodes.find(MetadataID);
593 if (FI != ForwardRefMDNodes.end()) {
594 MDNode *Temp = FI->second.first;
595 Temp->replaceAllUsesWith(Init);
596 MDNode::deleteTemporary(Temp);
597 ForwardRefMDNodes.erase(FI);
599 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
601 if (MetadataID >= NumberedMetadata.size())
602 NumberedMetadata.resize(MetadataID+1);
604 if (NumberedMetadata[MetadataID] != 0)
605 return TokError("Metadata id is already used");
606 NumberedMetadata[MetadataID] = Init;
613 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
616 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
617 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
619 /// Everything through visibility has already been parsed.
621 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
622 unsigned Visibility) {
623 assert(Lex.getKind() == lltok::kw_alias);
626 LocTy LinkageLoc = Lex.getLoc();
627 if (ParseOptionalLinkage(Linkage))
630 if (Linkage != GlobalValue::ExternalLinkage &&
631 Linkage != GlobalValue::WeakAnyLinkage &&
632 Linkage != GlobalValue::WeakODRLinkage &&
633 Linkage != GlobalValue::InternalLinkage &&
634 Linkage != GlobalValue::PrivateLinkage &&
635 Linkage != GlobalValue::LinkerPrivateLinkage &&
636 Linkage != GlobalValue::LinkerPrivateWeakLinkage)
637 return Error(LinkageLoc, "invalid linkage type for alias");
640 LocTy AliaseeLoc = Lex.getLoc();
641 if (Lex.getKind() != lltok::kw_bitcast &&
642 Lex.getKind() != lltok::kw_getelementptr) {
643 if (ParseGlobalTypeAndValue(Aliasee)) return true;
645 // The bitcast dest type is not present, it is implied by the dest type.
647 if (ParseValID(ID)) return true;
648 if (ID.Kind != ValID::t_Constant)
649 return Error(AliaseeLoc, "invalid aliasee");
650 Aliasee = ID.ConstantVal;
653 if (!Aliasee->getType()->isPointerTy())
654 return Error(AliaseeLoc, "alias must have pointer type");
656 // Okay, create the alias but do not insert it into the module yet.
657 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
658 (GlobalValue::LinkageTypes)Linkage, Name,
660 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
662 // See if this value already exists in the symbol table. If so, it is either
663 // a redefinition or a definition of a forward reference.
664 if (GlobalValue *Val = M->getNamedValue(Name)) {
665 // See if this was a redefinition. If so, there is no entry in
667 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
668 I = ForwardRefVals.find(Name);
669 if (I == ForwardRefVals.end())
670 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
672 // Otherwise, this was a definition of forward ref. Verify that types
674 if (Val->getType() != GA->getType())
675 return Error(NameLoc,
676 "forward reference and definition of alias have different types");
678 // If they agree, just RAUW the old value with the alias and remove the
680 Val->replaceAllUsesWith(GA);
681 Val->eraseFromParent();
682 ForwardRefVals.erase(I);
685 // Insert into the module, we know its name won't collide now.
686 M->getAliasList().push_back(GA);
687 assert(GA->getName() == Name && "Should not be a name conflict!");
693 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
694 /// OptionalAddrSpace OptionalUnNammedAddr
695 /// OptionalExternallyInitialized GlobalType Type Const
696 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
697 /// OptionalAddrSpace OptionalUnNammedAddr
698 /// OptionalExternallyInitialized GlobalType Type Const
700 /// Everything through visibility has been parsed already.
702 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
703 unsigned Linkage, bool HasLinkage,
704 unsigned Visibility) {
706 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
707 GlobalVariable::ThreadLocalMode TLM;
708 LocTy UnnamedAddrLoc;
709 LocTy IsExternallyInitializedLoc;
713 if (ParseOptionalThreadLocal(TLM) ||
714 ParseOptionalAddrSpace(AddrSpace) ||
715 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
717 ParseOptionalToken(lltok::kw_externally_initialized,
718 IsExternallyInitialized,
719 &IsExternallyInitializedLoc) ||
720 ParseGlobalType(IsConstant) ||
721 ParseType(Ty, TyLoc))
724 // If the linkage is specified and is external, then no initializer is
727 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
728 Linkage != GlobalValue::ExternalWeakLinkage &&
729 Linkage != GlobalValue::ExternalLinkage)) {
730 if (ParseGlobalValue(Ty, Init))
734 if (Ty->isFunctionTy() || Ty->isLabelTy())
735 return Error(TyLoc, "invalid type for global variable");
737 GlobalVariable *GV = 0;
739 // See if the global was forward referenced, if so, use the global.
741 if (GlobalValue *GVal = M->getNamedValue(Name)) {
742 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
743 return Error(NameLoc, "redefinition of global '@" + Name + "'");
744 GV = cast<GlobalVariable>(GVal);
747 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
748 I = ForwardRefValIDs.find(NumberedVals.size());
749 if (I != ForwardRefValIDs.end()) {
750 GV = cast<GlobalVariable>(I->second.first);
751 ForwardRefValIDs.erase(I);
756 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
757 Name, 0, GlobalVariable::NotThreadLocal,
760 if (GV->getType()->getElementType() != Ty)
762 "forward reference and definition of global have different types");
764 // Move the forward-reference to the correct spot in the module.
765 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
769 NumberedVals.push_back(GV);
771 // Set the parsed properties on the global.
773 GV->setInitializer(Init);
774 GV->setConstant(IsConstant);
775 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
776 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
777 GV->setExternallyInitialized(IsExternallyInitialized);
778 GV->setThreadLocalMode(TLM);
779 GV->setUnnamedAddr(UnnamedAddr);
781 // Parse attributes on the global.
782 while (Lex.getKind() == lltok::comma) {
785 if (Lex.getKind() == lltok::kw_section) {
787 GV->setSection(Lex.getStrVal());
788 if (ParseToken(lltok::StringConstant, "expected global section string"))
790 } else if (Lex.getKind() == lltok::kw_align) {
792 if (ParseOptionalAlignment(Alignment)) return true;
793 GV->setAlignment(Alignment);
795 TokError("unknown global variable property!");
802 /// ParseUnnamedAttrGrp
803 /// ::= AttrGrpID '=' '{' AttrValPair+ '}'
804 bool LLParser::ParseUnnamedAttrGrp() {
805 assert(Lex.getKind() == lltok::AttrGrpID);
806 LocTy AttrGrpLoc = Lex.getLoc();
807 unsigned VarID = Lex.getUIntVal();
808 std::vector<unsigned> unused;
811 if (ParseToken(lltok::equal, "expected '=' here") ||
812 ParseToken(lltok::kw_attributes, "expected 'attributes' keyword here") ||
813 ParseToken(lltok::lbrace, "expected '{' here") ||
814 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true) ||
815 ParseToken(lltok::rbrace, "expected end of attribute group"))
818 if (!NumberedAttrBuilders[VarID].hasAttributes())
819 return Error(AttrGrpLoc, "attribute group has no attributes");
824 /// ParseFnAttributeValuePairs
825 /// ::= <attr> | <attr> '=' <value>
826 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
827 std::vector<unsigned> &FwdRefAttrGrps,
829 bool HaveError = false;
834 lltok::Kind Token = Lex.getKind();
837 if (!inAttrGrp) return HaveError;
838 return Error(Lex.getLoc(), "unterminated attribute group");
843 case lltok::AttrGrpID: {
844 // Allow a function to reference an attribute group:
846 // define void @foo() #1 { ... }
850 "cannot have an attribute group reference in an attribute group");
852 unsigned AttrGrpNum = Lex.getUIntVal();
853 if (inAttrGrp) break;
855 // Save the reference to the attribute group. We'll fill it in later.
856 FwdRefAttrGrps.push_back(AttrGrpNum);
859 // Target-dependent attributes:
860 case lltok::StringConstant: {
861 std::string Attr = Lex.getStrVal();
864 if (EatIfPresent(lltok::equal) &&
865 ParseStringConstant(Val))
868 B.addAttribute(Attr, Val);
872 // Target-independent attributes:
873 case lltok::kw_align: {
874 // As a hack, we allow "align 2" on functions as a synonym for "alignstack
878 if (ParseToken(lltok::equal, "expected '=' here") ||
879 ParseUInt32(Alignment))
882 if (ParseOptionalAlignment(Alignment))
885 B.addAlignmentAttr(Alignment);
888 case lltok::kw_alignstack: {
891 if (ParseToken(lltok::equal, "expected '=' here") ||
892 ParseUInt32(Alignment))
895 if (ParseOptionalStackAlignment(Alignment))
898 B.addStackAlignmentAttr(Alignment);
901 case lltok::kw_address_safety: B.addAttribute(Attribute::AddressSafety); break;
902 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
903 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
904 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
905 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
906 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
907 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
908 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
909 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
910 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
911 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
912 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
913 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
914 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
915 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
916 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
917 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
918 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
919 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
920 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
923 case lltok::kw_inreg:
924 case lltok::kw_signext:
925 case lltok::kw_zeroext:
928 "invalid use of attribute on a function");
930 case lltok::kw_byval:
932 case lltok::kw_noalias:
933 case lltok::kw_nocapture:
937 "invalid use of parameter-only attribute on a function");
945 //===----------------------------------------------------------------------===//
946 // GlobalValue Reference/Resolution Routines.
947 //===----------------------------------------------------------------------===//
949 /// GetGlobalVal - Get a value with the specified name or ID, creating a
950 /// forward reference record if needed. This can return null if the value
951 /// exists but does not have the right type.
952 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
954 PointerType *PTy = dyn_cast<PointerType>(Ty);
956 Error(Loc, "global variable reference must have pointer type");
960 // Look this name up in the normal function symbol table.
962 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
964 // If this is a forward reference for the value, see if we already created a
965 // forward ref record.
967 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
968 I = ForwardRefVals.find(Name);
969 if (I != ForwardRefVals.end())
970 Val = I->second.first;
973 // If we have the value in the symbol table or fwd-ref table, return it.
975 if (Val->getType() == Ty) return Val;
976 Error(Loc, "'@" + Name + "' defined with type '" +
977 getTypeString(Val->getType()) + "'");
981 // Otherwise, create a new forward reference for this value and remember it.
983 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
984 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
986 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
987 GlobalValue::ExternalWeakLinkage, 0, Name,
988 0, GlobalVariable::NotThreadLocal,
989 PTy->getAddressSpace());
991 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
995 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
996 PointerType *PTy = dyn_cast<PointerType>(Ty);
998 Error(Loc, "global variable reference must have pointer type");
1002 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1004 // If this is a forward reference for the value, see if we already created a
1005 // forward ref record.
1007 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1008 I = ForwardRefValIDs.find(ID);
1009 if (I != ForwardRefValIDs.end())
1010 Val = I->second.first;
1013 // If we have the value in the symbol table or fwd-ref table, return it.
1015 if (Val->getType() == Ty) return Val;
1016 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1017 getTypeString(Val->getType()) + "'");
1021 // Otherwise, create a new forward reference for this value and remember it.
1022 GlobalValue *FwdVal;
1023 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1024 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1026 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1027 GlobalValue::ExternalWeakLinkage, 0, "");
1029 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1034 //===----------------------------------------------------------------------===//
1036 //===----------------------------------------------------------------------===//
1038 /// ParseToken - If the current token has the specified kind, eat it and return
1039 /// success. Otherwise, emit the specified error and return failure.
1040 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1041 if (Lex.getKind() != T)
1042 return TokError(ErrMsg);
1047 /// ParseStringConstant
1048 /// ::= StringConstant
1049 bool LLParser::ParseStringConstant(std::string &Result) {
1050 if (Lex.getKind() != lltok::StringConstant)
1051 return TokError("expected string constant");
1052 Result = Lex.getStrVal();
1059 bool LLParser::ParseUInt32(unsigned &Val) {
1060 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1061 return TokError("expected integer");
1062 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1063 if (Val64 != unsigned(Val64))
1064 return TokError("expected 32-bit integer (too large)");
1071 /// := 'localdynamic'
1072 /// := 'initialexec'
1074 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1075 switch (Lex.getKind()) {
1077 return TokError("expected localdynamic, initialexec or localexec");
1078 case lltok::kw_localdynamic:
1079 TLM = GlobalVariable::LocalDynamicTLSModel;
1081 case lltok::kw_initialexec:
1082 TLM = GlobalVariable::InitialExecTLSModel;
1084 case lltok::kw_localexec:
1085 TLM = GlobalVariable::LocalExecTLSModel;
1093 /// ParseOptionalThreadLocal
1095 /// := 'thread_local'
1096 /// := 'thread_local' '(' tlsmodel ')'
1097 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1098 TLM = GlobalVariable::NotThreadLocal;
1099 if (!EatIfPresent(lltok::kw_thread_local))
1102 TLM = GlobalVariable::GeneralDynamicTLSModel;
1103 if (Lex.getKind() == lltok::lparen) {
1105 return ParseTLSModel(TLM) ||
1106 ParseToken(lltok::rparen, "expected ')' after thread local model");
1111 /// ParseOptionalAddrSpace
1113 /// := 'addrspace' '(' uint32 ')'
1114 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1116 if (!EatIfPresent(lltok::kw_addrspace))
1118 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1119 ParseUInt32(AddrSpace) ||
1120 ParseToken(lltok::rparen, "expected ')' in address space");
1123 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1124 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1125 bool HaveError = false;
1130 lltok::Kind Token = Lex.getKind();
1132 default: // End of attributes.
1134 case lltok::kw_align: {
1136 if (ParseOptionalAlignment(Alignment))
1138 B.addAlignmentAttr(Alignment);
1141 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1142 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1143 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1144 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1145 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1146 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1147 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1148 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1150 case lltok::kw_noreturn: case lltok::kw_nounwind:
1151 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1152 case lltok::kw_noinline: case lltok::kw_readnone:
1153 case lltok::kw_readonly: case lltok::kw_inlinehint:
1154 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1155 case lltok::kw_ssp: case lltok::kw_sspreq:
1156 case lltok::kw_noredzone: case lltok::kw_noimplicitfloat:
1157 case lltok::kw_naked: case lltok::kw_nonlazybind:
1158 case lltok::kw_address_safety: case lltok::kw_minsize:
1159 case lltok::kw_alignstack:
1160 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1168 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1169 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1170 bool HaveError = false;
1175 lltok::Kind Token = Lex.getKind();
1177 default: // End of attributes.
1179 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1180 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1181 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1182 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1185 case lltok::kw_sret: case lltok::kw_nocapture:
1186 case lltok::kw_byval: case lltok::kw_nest:
1187 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1190 case lltok::kw_noreturn: case lltok::kw_nounwind:
1191 case lltok::kw_uwtable: case lltok::kw_returns_twice:
1192 case lltok::kw_noinline: case lltok::kw_readnone:
1193 case lltok::kw_readonly: case lltok::kw_inlinehint:
1194 case lltok::kw_alwaysinline: case lltok::kw_optsize:
1195 case lltok::kw_ssp: case lltok::kw_sspreq:
1196 case lltok::kw_sspstrong: case lltok::kw_noimplicitfloat:
1197 case lltok::kw_noredzone: case lltok::kw_naked:
1198 case lltok::kw_nonlazybind: case lltok::kw_address_safety:
1199 case lltok::kw_minsize: case lltok::kw_alignstack:
1200 case lltok::kw_align: case lltok::kw_noduplicate:
1201 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1209 /// ParseOptionalLinkage
1212 /// ::= 'linker_private'
1213 /// ::= 'linker_private_weak'
1218 /// ::= 'linkonce_odr'
1219 /// ::= 'linkonce_odr_auto_hide'
1220 /// ::= 'available_externally'
1225 /// ::= 'extern_weak'
1227 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1229 switch (Lex.getKind()) {
1230 default: Res=GlobalValue::ExternalLinkage; return false;
1231 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1232 case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
1233 case lltok::kw_linker_private_weak:
1234 Res = GlobalValue::LinkerPrivateWeakLinkage;
1236 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1237 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1238 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1239 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1240 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1241 case lltok::kw_linkonce_odr_auto_hide:
1242 case lltok::kw_linker_private_weak_def_auto: // FIXME: For backwards compat.
1243 Res = GlobalValue::LinkOnceODRAutoHideLinkage;
1245 case lltok::kw_available_externally:
1246 Res = GlobalValue::AvailableExternallyLinkage;
1248 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1249 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
1250 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1251 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
1252 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1253 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1260 /// ParseOptionalVisibility
1266 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1267 switch (Lex.getKind()) {
1268 default: Res = GlobalValue::DefaultVisibility; return false;
1269 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1270 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1271 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1277 /// ParseOptionalCallingConv
1281 /// ::= 'kw_intel_ocl_bicc'
1283 /// ::= 'x86_stdcallcc'
1284 /// ::= 'x86_fastcallcc'
1285 /// ::= 'x86_thiscallcc'
1286 /// ::= 'arm_apcscc'
1287 /// ::= 'arm_aapcscc'
1288 /// ::= 'arm_aapcs_vfpcc'
1289 /// ::= 'msp430_intrcc'
1290 /// ::= 'ptx_kernel'
1291 /// ::= 'ptx_device'
1293 /// ::= 'spir_kernel'
1296 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1297 switch (Lex.getKind()) {
1298 default: CC = CallingConv::C; return false;
1299 case lltok::kw_ccc: CC = CallingConv::C; break;
1300 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1301 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1302 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1303 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1304 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1305 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1306 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1307 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1308 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1309 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1310 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1311 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1312 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1313 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1314 case lltok::kw_cc: {
1315 unsigned ArbitraryCC;
1317 if (ParseUInt32(ArbitraryCC))
1319 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1328 /// ParseInstructionMetadata
1329 /// ::= !dbg !42 (',' !dbg !57)*
1330 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1331 PerFunctionState *PFS) {
1333 if (Lex.getKind() != lltok::MetadataVar)
1334 return TokError("expected metadata after comma");
1336 std::string Name = Lex.getStrVal();
1337 unsigned MDK = M->getMDKindID(Name);
1341 SMLoc Loc = Lex.getLoc();
1343 if (ParseToken(lltok::exclaim, "expected '!' here"))
1346 // This code is similar to that of ParseMetadataValue, however it needs to
1347 // have special-case code for a forward reference; see the comments on
1348 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1349 // at the top level here.
1350 if (Lex.getKind() == lltok::lbrace) {
1352 if (ParseMetadataListValue(ID, PFS))
1354 assert(ID.Kind == ValID::t_MDNode);
1355 Inst->setMetadata(MDK, ID.MDNodeVal);
1357 unsigned NodeID = 0;
1358 if (ParseMDNodeID(Node, NodeID))
1361 // If we got the node, add it to the instruction.
1362 Inst->setMetadata(MDK, Node);
1364 MDRef R = { Loc, MDK, NodeID };
1365 // Otherwise, remember that this should be resolved later.
1366 ForwardRefInstMetadata[Inst].push_back(R);
1370 // If this is the end of the list, we're done.
1371 } while (EatIfPresent(lltok::comma));
1375 /// ParseOptionalAlignment
1378 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1380 if (!EatIfPresent(lltok::kw_align))
1382 LocTy AlignLoc = Lex.getLoc();
1383 if (ParseUInt32(Alignment)) return true;
1384 if (!isPowerOf2_32(Alignment))
1385 return Error(AlignLoc, "alignment is not a power of two");
1386 if (Alignment > Value::MaximumAlignment)
1387 return Error(AlignLoc, "huge alignments are not supported yet");
1391 /// ParseOptionalCommaAlign
1395 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1397 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1398 bool &AteExtraComma) {
1399 AteExtraComma = false;
1400 while (EatIfPresent(lltok::comma)) {
1401 // Metadata at the end is an early exit.
1402 if (Lex.getKind() == lltok::MetadataVar) {
1403 AteExtraComma = true;
1407 if (Lex.getKind() != lltok::kw_align)
1408 return Error(Lex.getLoc(), "expected metadata or 'align'");
1410 if (ParseOptionalAlignment(Alignment)) return true;
1416 /// ParseScopeAndOrdering
1417 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1420 /// This sets Scope and Ordering to the parsed values.
1421 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1422 AtomicOrdering &Ordering) {
1426 Scope = CrossThread;
1427 if (EatIfPresent(lltok::kw_singlethread))
1428 Scope = SingleThread;
1429 switch (Lex.getKind()) {
1430 default: return TokError("Expected ordering on atomic instruction");
1431 case lltok::kw_unordered: Ordering = Unordered; break;
1432 case lltok::kw_monotonic: Ordering = Monotonic; break;
1433 case lltok::kw_acquire: Ordering = Acquire; break;
1434 case lltok::kw_release: Ordering = Release; break;
1435 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1436 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1442 /// ParseOptionalStackAlignment
1444 /// ::= 'alignstack' '(' 4 ')'
1445 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1447 if (!EatIfPresent(lltok::kw_alignstack))
1449 LocTy ParenLoc = Lex.getLoc();
1450 if (!EatIfPresent(lltok::lparen))
1451 return Error(ParenLoc, "expected '('");
1452 LocTy AlignLoc = Lex.getLoc();
1453 if (ParseUInt32(Alignment)) return true;
1454 ParenLoc = Lex.getLoc();
1455 if (!EatIfPresent(lltok::rparen))
1456 return Error(ParenLoc, "expected ')'");
1457 if (!isPowerOf2_32(Alignment))
1458 return Error(AlignLoc, "stack alignment is not a power of two");
1462 /// ParseIndexList - This parses the index list for an insert/extractvalue
1463 /// instruction. This sets AteExtraComma in the case where we eat an extra
1464 /// comma at the end of the line and find that it is followed by metadata.
1465 /// Clients that don't allow metadata can call the version of this function that
1466 /// only takes one argument.
1469 /// ::= (',' uint32)+
1471 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1472 bool &AteExtraComma) {
1473 AteExtraComma = false;
1475 if (Lex.getKind() != lltok::comma)
1476 return TokError("expected ',' as start of index list");
1478 while (EatIfPresent(lltok::comma)) {
1479 if (Lex.getKind() == lltok::MetadataVar) {
1480 AteExtraComma = true;
1484 if (ParseUInt32(Idx)) return true;
1485 Indices.push_back(Idx);
1491 //===----------------------------------------------------------------------===//
1493 //===----------------------------------------------------------------------===//
1495 /// ParseType - Parse a type.
1496 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1497 SMLoc TypeLoc = Lex.getLoc();
1498 switch (Lex.getKind()) {
1500 return TokError("expected type");
1502 // Type ::= 'float' | 'void' (etc)
1503 Result = Lex.getTyVal();
1507 // Type ::= StructType
1508 if (ParseAnonStructType(Result, false))
1511 case lltok::lsquare:
1512 // Type ::= '[' ... ']'
1513 Lex.Lex(); // eat the lsquare.
1514 if (ParseArrayVectorType(Result, false))
1517 case lltok::less: // Either vector or packed struct.
1518 // Type ::= '<' ... '>'
1520 if (Lex.getKind() == lltok::lbrace) {
1521 if (ParseAnonStructType(Result, true) ||
1522 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1524 } else if (ParseArrayVectorType(Result, true))
1527 case lltok::LocalVar: {
1529 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1531 // If the type hasn't been defined yet, create a forward definition and
1532 // remember where that forward def'n was seen (in case it never is defined).
1533 if (Entry.first == 0) {
1534 Entry.first = StructType::create(Context, Lex.getStrVal());
1535 Entry.second = Lex.getLoc();
1537 Result = Entry.first;
1542 case lltok::LocalVarID: {
1544 if (Lex.getUIntVal() >= NumberedTypes.size())
1545 NumberedTypes.resize(Lex.getUIntVal()+1);
1546 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1548 // If the type hasn't been defined yet, create a forward definition and
1549 // remember where that forward def'n was seen (in case it never is defined).
1550 if (Entry.first == 0) {
1551 Entry.first = StructType::create(Context);
1552 Entry.second = Lex.getLoc();
1554 Result = Entry.first;
1560 // Parse the type suffixes.
1562 switch (Lex.getKind()) {
1565 if (!AllowVoid && Result->isVoidTy())
1566 return Error(TypeLoc, "void type only allowed for function results");
1569 // Type ::= Type '*'
1571 if (Result->isLabelTy())
1572 return TokError("basic block pointers are invalid");
1573 if (Result->isVoidTy())
1574 return TokError("pointers to void are invalid - use i8* instead");
1575 if (!PointerType::isValidElementType(Result))
1576 return TokError("pointer to this type is invalid");
1577 Result = PointerType::getUnqual(Result);
1581 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1582 case lltok::kw_addrspace: {
1583 if (Result->isLabelTy())
1584 return TokError("basic block pointers are invalid");
1585 if (Result->isVoidTy())
1586 return TokError("pointers to void are invalid; use i8* instead");
1587 if (!PointerType::isValidElementType(Result))
1588 return TokError("pointer to this type is invalid");
1590 if (ParseOptionalAddrSpace(AddrSpace) ||
1591 ParseToken(lltok::star, "expected '*' in address space"))
1594 Result = PointerType::get(Result, AddrSpace);
1598 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1600 if (ParseFunctionType(Result))
1607 /// ParseParameterList
1609 /// ::= '(' Arg (',' Arg)* ')'
1611 /// ::= Type OptionalAttributes Value OptionalAttributes
1612 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1613 PerFunctionState &PFS) {
1614 if (ParseToken(lltok::lparen, "expected '(' in call"))
1617 unsigned AttrIndex = 1;
1618 while (Lex.getKind() != lltok::rparen) {
1619 // If this isn't the first argument, we need a comma.
1620 if (!ArgList.empty() &&
1621 ParseToken(lltok::comma, "expected ',' in argument list"))
1624 // Parse the argument.
1627 AttrBuilder ArgAttrs;
1629 if (ParseType(ArgTy, ArgLoc))
1632 // Otherwise, handle normal operands.
1633 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1635 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1640 Lex.Lex(); // Lex the ')'.
1646 /// ParseArgumentList - Parse the argument list for a function type or function
1648 /// ::= '(' ArgTypeListI ')'
1652 /// ::= ArgTypeList ',' '...'
1653 /// ::= ArgType (',' ArgType)*
1655 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1658 assert(Lex.getKind() == lltok::lparen);
1659 Lex.Lex(); // eat the (.
1661 if (Lex.getKind() == lltok::rparen) {
1663 } else if (Lex.getKind() == lltok::dotdotdot) {
1667 LocTy TypeLoc = Lex.getLoc();
1672 if (ParseType(ArgTy) ||
1673 ParseOptionalParamAttrs(Attrs)) return true;
1675 if (ArgTy->isVoidTy())
1676 return Error(TypeLoc, "argument can not have void type");
1678 if (Lex.getKind() == lltok::LocalVar) {
1679 Name = Lex.getStrVal();
1683 if (!FunctionType::isValidArgumentType(ArgTy))
1684 return Error(TypeLoc, "invalid type for function argument");
1686 unsigned AttrIndex = 1;
1687 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1688 AttributeSet::get(ArgTy->getContext(),
1689 AttrIndex++, Attrs), Name));
1691 while (EatIfPresent(lltok::comma)) {
1692 // Handle ... at end of arg list.
1693 if (EatIfPresent(lltok::dotdotdot)) {
1698 // Otherwise must be an argument type.
1699 TypeLoc = Lex.getLoc();
1700 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1702 if (ArgTy->isVoidTy())
1703 return Error(TypeLoc, "argument can not have void type");
1705 if (Lex.getKind() == lltok::LocalVar) {
1706 Name = Lex.getStrVal();
1712 if (!ArgTy->isFirstClassType())
1713 return Error(TypeLoc, "invalid type for function argument");
1715 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1716 AttributeSet::get(ArgTy->getContext(),
1717 AttrIndex++, Attrs),
1722 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1725 /// ParseFunctionType
1726 /// ::= Type ArgumentList OptionalAttrs
1727 bool LLParser::ParseFunctionType(Type *&Result) {
1728 assert(Lex.getKind() == lltok::lparen);
1730 if (!FunctionType::isValidReturnType(Result))
1731 return TokError("invalid function return type");
1733 SmallVector<ArgInfo, 8> ArgList;
1735 if (ParseArgumentList(ArgList, isVarArg))
1738 // Reject names on the arguments lists.
1739 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1740 if (!ArgList[i].Name.empty())
1741 return Error(ArgList[i].Loc, "argument name invalid in function type");
1742 if (ArgList[i].Attrs.hasAttributes(i + 1))
1743 return Error(ArgList[i].Loc,
1744 "argument attributes invalid in function type");
1747 SmallVector<Type*, 16> ArgListTy;
1748 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1749 ArgListTy.push_back(ArgList[i].Ty);
1751 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1755 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1757 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1758 SmallVector<Type*, 8> Elts;
1759 if (ParseStructBody(Elts)) return true;
1761 Result = StructType::get(Context, Elts, Packed);
1765 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1766 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1767 std::pair<Type*, LocTy> &Entry,
1769 // If the type was already defined, diagnose the redefinition.
1770 if (Entry.first && !Entry.second.isValid())
1771 return Error(TypeLoc, "redefinition of type");
1773 // If we have opaque, just return without filling in the definition for the
1774 // struct. This counts as a definition as far as the .ll file goes.
1775 if (EatIfPresent(lltok::kw_opaque)) {
1776 // This type is being defined, so clear the location to indicate this.
1777 Entry.second = SMLoc();
1779 // If this type number has never been uttered, create it.
1780 if (Entry.first == 0)
1781 Entry.first = StructType::create(Context, Name);
1782 ResultTy = Entry.first;
1786 // If the type starts with '<', then it is either a packed struct or a vector.
1787 bool isPacked = EatIfPresent(lltok::less);
1789 // If we don't have a struct, then we have a random type alias, which we
1790 // accept for compatibility with old files. These types are not allowed to be
1791 // forward referenced and not allowed to be recursive.
1792 if (Lex.getKind() != lltok::lbrace) {
1794 return Error(TypeLoc, "forward references to non-struct type");
1798 return ParseArrayVectorType(ResultTy, true);
1799 return ParseType(ResultTy);
1802 // This type is being defined, so clear the location to indicate this.
1803 Entry.second = SMLoc();
1805 // If this type number has never been uttered, create it.
1806 if (Entry.first == 0)
1807 Entry.first = StructType::create(Context, Name);
1809 StructType *STy = cast<StructType>(Entry.first);
1811 SmallVector<Type*, 8> Body;
1812 if (ParseStructBody(Body) ||
1813 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1816 STy->setBody(Body, isPacked);
1822 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1825 /// ::= '{' Type (',' Type)* '}'
1826 /// ::= '<' '{' '}' '>'
1827 /// ::= '<' '{' Type (',' Type)* '}' '>'
1828 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1829 assert(Lex.getKind() == lltok::lbrace);
1830 Lex.Lex(); // Consume the '{'
1832 // Handle the empty struct.
1833 if (EatIfPresent(lltok::rbrace))
1836 LocTy EltTyLoc = Lex.getLoc();
1838 if (ParseType(Ty)) return true;
1841 if (!StructType::isValidElementType(Ty))
1842 return Error(EltTyLoc, "invalid element type for struct");
1844 while (EatIfPresent(lltok::comma)) {
1845 EltTyLoc = Lex.getLoc();
1846 if (ParseType(Ty)) return true;
1848 if (!StructType::isValidElementType(Ty))
1849 return Error(EltTyLoc, "invalid element type for struct");
1854 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1857 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1858 /// token has already been consumed.
1860 /// ::= '[' APSINTVAL 'x' Types ']'
1861 /// ::= '<' APSINTVAL 'x' Types '>'
1862 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1863 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1864 Lex.getAPSIntVal().getBitWidth() > 64)
1865 return TokError("expected number in address space");
1867 LocTy SizeLoc = Lex.getLoc();
1868 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1871 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1874 LocTy TypeLoc = Lex.getLoc();
1876 if (ParseType(EltTy)) return true;
1878 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1879 "expected end of sequential type"))
1884 return Error(SizeLoc, "zero element vector is illegal");
1885 if ((unsigned)Size != Size)
1886 return Error(SizeLoc, "size too large for vector");
1887 if (!VectorType::isValidElementType(EltTy))
1888 return Error(TypeLoc, "invalid vector element type");
1889 Result = VectorType::get(EltTy, unsigned(Size));
1891 if (!ArrayType::isValidElementType(EltTy))
1892 return Error(TypeLoc, "invalid array element type");
1893 Result = ArrayType::get(EltTy, Size);
1898 //===----------------------------------------------------------------------===//
1899 // Function Semantic Analysis.
1900 //===----------------------------------------------------------------------===//
1902 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
1904 : P(p), F(f), FunctionNumber(functionNumber) {
1906 // Insert unnamed arguments into the NumberedVals list.
1907 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1910 NumberedVals.push_back(AI);
1913 LLParser::PerFunctionState::~PerFunctionState() {
1914 // If there were any forward referenced non-basicblock values, delete them.
1915 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1916 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1917 if (!isa<BasicBlock>(I->second.first)) {
1918 I->second.first->replaceAllUsesWith(
1919 UndefValue::get(I->second.first->getType()));
1920 delete I->second.first;
1921 I->second.first = 0;
1924 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1925 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1926 if (!isa<BasicBlock>(I->second.first)) {
1927 I->second.first->replaceAllUsesWith(
1928 UndefValue::get(I->second.first->getType()));
1929 delete I->second.first;
1930 I->second.first = 0;
1934 bool LLParser::PerFunctionState::FinishFunction() {
1935 // Check to see if someone took the address of labels in this block.
1936 if (!P.ForwardRefBlockAddresses.empty()) {
1938 if (!F.getName().empty()) {
1939 FunctionID.Kind = ValID::t_GlobalName;
1940 FunctionID.StrVal = F.getName();
1942 FunctionID.Kind = ValID::t_GlobalID;
1943 FunctionID.UIntVal = FunctionNumber;
1946 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
1947 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
1948 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
1949 // Resolve all these references.
1950 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
1953 P.ForwardRefBlockAddresses.erase(FRBAI);
1957 if (!ForwardRefVals.empty())
1958 return P.Error(ForwardRefVals.begin()->second.second,
1959 "use of undefined value '%" + ForwardRefVals.begin()->first +
1961 if (!ForwardRefValIDs.empty())
1962 return P.Error(ForwardRefValIDs.begin()->second.second,
1963 "use of undefined value '%" +
1964 Twine(ForwardRefValIDs.begin()->first) + "'");
1969 /// GetVal - Get a value with the specified name or ID, creating a
1970 /// forward reference record if needed. This can return null if the value
1971 /// exists but does not have the right type.
1972 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1973 Type *Ty, LocTy Loc) {
1974 // Look this name up in the normal function symbol table.
1975 Value *Val = F.getValueSymbolTable().lookup(Name);
1977 // If this is a forward reference for the value, see if we already created a
1978 // forward ref record.
1980 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1981 I = ForwardRefVals.find(Name);
1982 if (I != ForwardRefVals.end())
1983 Val = I->second.first;
1986 // If we have the value in the symbol table or fwd-ref table, return it.
1988 if (Val->getType() == Ty) return Val;
1989 if (Ty->isLabelTy())
1990 P.Error(Loc, "'%" + Name + "' is not a basic block");
1992 P.Error(Loc, "'%" + Name + "' defined with type '" +
1993 getTypeString(Val->getType()) + "'");
1997 // Don't make placeholders with invalid type.
1998 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
1999 P.Error(Loc, "invalid use of a non-first-class type");
2003 // Otherwise, create a new forward reference for this value and remember it.
2005 if (Ty->isLabelTy())
2006 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2008 FwdVal = new Argument(Ty, Name);
2010 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2014 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2016 // Look this name up in the normal function symbol table.
2017 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
2019 // If this is a forward reference for the value, see if we already created a
2020 // forward ref record.
2022 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2023 I = ForwardRefValIDs.find(ID);
2024 if (I != ForwardRefValIDs.end())
2025 Val = I->second.first;
2028 // If we have the value in the symbol table or fwd-ref table, return it.
2030 if (Val->getType() == Ty) return Val;
2031 if (Ty->isLabelTy())
2032 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2034 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2035 getTypeString(Val->getType()) + "'");
2039 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2040 P.Error(Loc, "invalid use of a non-first-class type");
2044 // Otherwise, create a new forward reference for this value and remember it.
2046 if (Ty->isLabelTy())
2047 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2049 FwdVal = new Argument(Ty);
2051 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2055 /// SetInstName - After an instruction is parsed and inserted into its
2056 /// basic block, this installs its name.
2057 bool LLParser::PerFunctionState::SetInstName(int NameID,
2058 const std::string &NameStr,
2059 LocTy NameLoc, Instruction *Inst) {
2060 // If this instruction has void type, it cannot have a name or ID specified.
2061 if (Inst->getType()->isVoidTy()) {
2062 if (NameID != -1 || !NameStr.empty())
2063 return P.Error(NameLoc, "instructions returning void cannot have a name");
2067 // If this was a numbered instruction, verify that the instruction is the
2068 // expected value and resolve any forward references.
2069 if (NameStr.empty()) {
2070 // If neither a name nor an ID was specified, just use the next ID.
2072 NameID = NumberedVals.size();
2074 if (unsigned(NameID) != NumberedVals.size())
2075 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2076 Twine(NumberedVals.size()) + "'");
2078 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2079 ForwardRefValIDs.find(NameID);
2080 if (FI != ForwardRefValIDs.end()) {
2081 if (FI->second.first->getType() != Inst->getType())
2082 return P.Error(NameLoc, "instruction forward referenced with type '" +
2083 getTypeString(FI->second.first->getType()) + "'");
2084 FI->second.first->replaceAllUsesWith(Inst);
2085 delete FI->second.first;
2086 ForwardRefValIDs.erase(FI);
2089 NumberedVals.push_back(Inst);
2093 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2094 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2095 FI = ForwardRefVals.find(NameStr);
2096 if (FI != ForwardRefVals.end()) {
2097 if (FI->second.first->getType() != Inst->getType())
2098 return P.Error(NameLoc, "instruction forward referenced with type '" +
2099 getTypeString(FI->second.first->getType()) + "'");
2100 FI->second.first->replaceAllUsesWith(Inst);
2101 delete FI->second.first;
2102 ForwardRefVals.erase(FI);
2105 // Set the name on the instruction.
2106 Inst->setName(NameStr);
2108 if (Inst->getName() != NameStr)
2109 return P.Error(NameLoc, "multiple definition of local value named '" +
2114 /// GetBB - Get a basic block with the specified name or ID, creating a
2115 /// forward reference record if needed.
2116 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2118 return cast_or_null<BasicBlock>(GetVal(Name,
2119 Type::getLabelTy(F.getContext()), Loc));
2122 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2123 return cast_or_null<BasicBlock>(GetVal(ID,
2124 Type::getLabelTy(F.getContext()), Loc));
2127 /// DefineBB - Define the specified basic block, which is either named or
2128 /// unnamed. If there is an error, this returns null otherwise it returns
2129 /// the block being defined.
2130 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2134 BB = GetBB(NumberedVals.size(), Loc);
2136 BB = GetBB(Name, Loc);
2137 if (BB == 0) return 0; // Already diagnosed error.
2139 // Move the block to the end of the function. Forward ref'd blocks are
2140 // inserted wherever they happen to be referenced.
2141 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2143 // Remove the block from forward ref sets.
2145 ForwardRefValIDs.erase(NumberedVals.size());
2146 NumberedVals.push_back(BB);
2148 // BB forward references are already in the function symbol table.
2149 ForwardRefVals.erase(Name);
2155 //===----------------------------------------------------------------------===//
2157 //===----------------------------------------------------------------------===//
2159 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2160 /// type implied. For example, if we parse "4" we don't know what integer type
2161 /// it has. The value will later be combined with its type and checked for
2162 /// sanity. PFS is used to convert function-local operands of metadata (since
2163 /// metadata operands are not just parsed here but also converted to values).
2164 /// PFS can be null when we are not parsing metadata values inside a function.
2165 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2166 ID.Loc = Lex.getLoc();
2167 switch (Lex.getKind()) {
2168 default: return TokError("expected value token");
2169 case lltok::GlobalID: // @42
2170 ID.UIntVal = Lex.getUIntVal();
2171 ID.Kind = ValID::t_GlobalID;
2173 case lltok::GlobalVar: // @foo
2174 ID.StrVal = Lex.getStrVal();
2175 ID.Kind = ValID::t_GlobalName;
2177 case lltok::LocalVarID: // %42
2178 ID.UIntVal = Lex.getUIntVal();
2179 ID.Kind = ValID::t_LocalID;
2181 case lltok::LocalVar: // %foo
2182 ID.StrVal = Lex.getStrVal();
2183 ID.Kind = ValID::t_LocalName;
2185 case lltok::exclaim: // !42, !{...}, or !"foo"
2186 return ParseMetadataValue(ID, PFS);
2188 ID.APSIntVal = Lex.getAPSIntVal();
2189 ID.Kind = ValID::t_APSInt;
2191 case lltok::APFloat:
2192 ID.APFloatVal = Lex.getAPFloatVal();
2193 ID.Kind = ValID::t_APFloat;
2195 case lltok::kw_true:
2196 ID.ConstantVal = ConstantInt::getTrue(Context);
2197 ID.Kind = ValID::t_Constant;
2199 case lltok::kw_false:
2200 ID.ConstantVal = ConstantInt::getFalse(Context);
2201 ID.Kind = ValID::t_Constant;
2203 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2204 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2205 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2207 case lltok::lbrace: {
2208 // ValID ::= '{' ConstVector '}'
2210 SmallVector<Constant*, 16> Elts;
2211 if (ParseGlobalValueVector(Elts) ||
2212 ParseToken(lltok::rbrace, "expected end of struct constant"))
2215 ID.ConstantStructElts = new Constant*[Elts.size()];
2216 ID.UIntVal = Elts.size();
2217 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2218 ID.Kind = ValID::t_ConstantStruct;
2222 // ValID ::= '<' ConstVector '>' --> Vector.
2223 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2225 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2227 SmallVector<Constant*, 16> Elts;
2228 LocTy FirstEltLoc = Lex.getLoc();
2229 if (ParseGlobalValueVector(Elts) ||
2231 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2232 ParseToken(lltok::greater, "expected end of constant"))
2235 if (isPackedStruct) {
2236 ID.ConstantStructElts = new Constant*[Elts.size()];
2237 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2238 ID.UIntVal = Elts.size();
2239 ID.Kind = ValID::t_PackedConstantStruct;
2244 return Error(ID.Loc, "constant vector must not be empty");
2246 if (!Elts[0]->getType()->isIntegerTy() &&
2247 !Elts[0]->getType()->isFloatingPointTy() &&
2248 !Elts[0]->getType()->isPointerTy())
2249 return Error(FirstEltLoc,
2250 "vector elements must have integer, pointer or floating point type");
2252 // Verify that all the vector elements have the same type.
2253 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2254 if (Elts[i]->getType() != Elts[0]->getType())
2255 return Error(FirstEltLoc,
2256 "vector element #" + Twine(i) +
2257 " is not of type '" + getTypeString(Elts[0]->getType()));
2259 ID.ConstantVal = ConstantVector::get(Elts);
2260 ID.Kind = ValID::t_Constant;
2263 case lltok::lsquare: { // Array Constant
2265 SmallVector<Constant*, 16> Elts;
2266 LocTy FirstEltLoc = Lex.getLoc();
2267 if (ParseGlobalValueVector(Elts) ||
2268 ParseToken(lltok::rsquare, "expected end of array constant"))
2271 // Handle empty element.
2273 // Use undef instead of an array because it's inconvenient to determine
2274 // the element type at this point, there being no elements to examine.
2275 ID.Kind = ValID::t_EmptyArray;
2279 if (!Elts[0]->getType()->isFirstClassType())
2280 return Error(FirstEltLoc, "invalid array element type: " +
2281 getTypeString(Elts[0]->getType()));
2283 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2285 // Verify all elements are correct type!
2286 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2287 if (Elts[i]->getType() != Elts[0]->getType())
2288 return Error(FirstEltLoc,
2289 "array element #" + Twine(i) +
2290 " is not of type '" + getTypeString(Elts[0]->getType()));
2293 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2294 ID.Kind = ValID::t_Constant;
2297 case lltok::kw_c: // c "foo"
2299 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2301 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2302 ID.Kind = ValID::t_Constant;
2305 case lltok::kw_asm: {
2306 // ValID ::= 'asm' SideEffect? AlignStack? STRINGCONSTANT ',' STRINGCONSTANT
2307 bool HasSideEffect, AlignStack, AsmDialect;
2309 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2310 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2311 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2312 ParseStringConstant(ID.StrVal) ||
2313 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2314 ParseToken(lltok::StringConstant, "expected constraint string"))
2316 ID.StrVal2 = Lex.getStrVal();
2317 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2318 (unsigned(AsmDialect)<<2);
2319 ID.Kind = ValID::t_InlineAsm;
2323 case lltok::kw_blockaddress: {
2324 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2328 LocTy FnLoc, LabelLoc;
2330 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2332 ParseToken(lltok::comma, "expected comma in block address expression")||
2333 ParseValID(Label) ||
2334 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2337 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2338 return Error(Fn.Loc, "expected function name in blockaddress");
2339 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2340 return Error(Label.Loc, "expected basic block name in blockaddress");
2342 // Make a global variable as a placeholder for this reference.
2343 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2344 false, GlobalValue::InternalLinkage,
2346 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2347 ID.ConstantVal = FwdRef;
2348 ID.Kind = ValID::t_Constant;
2352 case lltok::kw_trunc:
2353 case lltok::kw_zext:
2354 case lltok::kw_sext:
2355 case lltok::kw_fptrunc:
2356 case lltok::kw_fpext:
2357 case lltok::kw_bitcast:
2358 case lltok::kw_uitofp:
2359 case lltok::kw_sitofp:
2360 case lltok::kw_fptoui:
2361 case lltok::kw_fptosi:
2362 case lltok::kw_inttoptr:
2363 case lltok::kw_ptrtoint: {
2364 unsigned Opc = Lex.getUIntVal();
2368 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2369 ParseGlobalTypeAndValue(SrcVal) ||
2370 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2371 ParseType(DestTy) ||
2372 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2374 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2375 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2376 getTypeString(SrcVal->getType()) + "' to '" +
2377 getTypeString(DestTy) + "'");
2378 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2380 ID.Kind = ValID::t_Constant;
2383 case lltok::kw_extractvalue: {
2386 SmallVector<unsigned, 4> Indices;
2387 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2388 ParseGlobalTypeAndValue(Val) ||
2389 ParseIndexList(Indices) ||
2390 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2393 if (!Val->getType()->isAggregateType())
2394 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2395 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2396 return Error(ID.Loc, "invalid indices for extractvalue");
2397 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2398 ID.Kind = ValID::t_Constant;
2401 case lltok::kw_insertvalue: {
2403 Constant *Val0, *Val1;
2404 SmallVector<unsigned, 4> Indices;
2405 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2406 ParseGlobalTypeAndValue(Val0) ||
2407 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2408 ParseGlobalTypeAndValue(Val1) ||
2409 ParseIndexList(Indices) ||
2410 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2412 if (!Val0->getType()->isAggregateType())
2413 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2414 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2415 return Error(ID.Loc, "invalid indices for insertvalue");
2416 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2417 ID.Kind = ValID::t_Constant;
2420 case lltok::kw_icmp:
2421 case lltok::kw_fcmp: {
2422 unsigned PredVal, Opc = Lex.getUIntVal();
2423 Constant *Val0, *Val1;
2425 if (ParseCmpPredicate(PredVal, Opc) ||
2426 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2427 ParseGlobalTypeAndValue(Val0) ||
2428 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2429 ParseGlobalTypeAndValue(Val1) ||
2430 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2433 if (Val0->getType() != Val1->getType())
2434 return Error(ID.Loc, "compare operands must have the same type");
2436 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2438 if (Opc == Instruction::FCmp) {
2439 if (!Val0->getType()->isFPOrFPVectorTy())
2440 return Error(ID.Loc, "fcmp requires floating point operands");
2441 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2443 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2444 if (!Val0->getType()->isIntOrIntVectorTy() &&
2445 !Val0->getType()->getScalarType()->isPointerTy())
2446 return Error(ID.Loc, "icmp requires pointer or integer operands");
2447 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2449 ID.Kind = ValID::t_Constant;
2453 // Binary Operators.
2455 case lltok::kw_fadd:
2457 case lltok::kw_fsub:
2459 case lltok::kw_fmul:
2460 case lltok::kw_udiv:
2461 case lltok::kw_sdiv:
2462 case lltok::kw_fdiv:
2463 case lltok::kw_urem:
2464 case lltok::kw_srem:
2465 case lltok::kw_frem:
2467 case lltok::kw_lshr:
2468 case lltok::kw_ashr: {
2472 unsigned Opc = Lex.getUIntVal();
2473 Constant *Val0, *Val1;
2475 LocTy ModifierLoc = Lex.getLoc();
2476 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2477 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2478 if (EatIfPresent(lltok::kw_nuw))
2480 if (EatIfPresent(lltok::kw_nsw)) {
2482 if (EatIfPresent(lltok::kw_nuw))
2485 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2486 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2487 if (EatIfPresent(lltok::kw_exact))
2490 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2491 ParseGlobalTypeAndValue(Val0) ||
2492 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2493 ParseGlobalTypeAndValue(Val1) ||
2494 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2496 if (Val0->getType() != Val1->getType())
2497 return Error(ID.Loc, "operands of constexpr must have same type");
2498 if (!Val0->getType()->isIntOrIntVectorTy()) {
2500 return Error(ModifierLoc, "nuw only applies to integer operations");
2502 return Error(ModifierLoc, "nsw only applies to integer operations");
2504 // Check that the type is valid for the operator.
2506 case Instruction::Add:
2507 case Instruction::Sub:
2508 case Instruction::Mul:
2509 case Instruction::UDiv:
2510 case Instruction::SDiv:
2511 case Instruction::URem:
2512 case Instruction::SRem:
2513 case Instruction::Shl:
2514 case Instruction::AShr:
2515 case Instruction::LShr:
2516 if (!Val0->getType()->isIntOrIntVectorTy())
2517 return Error(ID.Loc, "constexpr requires integer operands");
2519 case Instruction::FAdd:
2520 case Instruction::FSub:
2521 case Instruction::FMul:
2522 case Instruction::FDiv:
2523 case Instruction::FRem:
2524 if (!Val0->getType()->isFPOrFPVectorTy())
2525 return Error(ID.Loc, "constexpr requires fp operands");
2527 default: llvm_unreachable("Unknown binary operator!");
2530 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2531 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2532 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2533 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2535 ID.Kind = ValID::t_Constant;
2539 // Logical Operations
2542 case lltok::kw_xor: {
2543 unsigned Opc = Lex.getUIntVal();
2544 Constant *Val0, *Val1;
2546 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2547 ParseGlobalTypeAndValue(Val0) ||
2548 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2549 ParseGlobalTypeAndValue(Val1) ||
2550 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2552 if (Val0->getType() != Val1->getType())
2553 return Error(ID.Loc, "operands of constexpr must have same type");
2554 if (!Val0->getType()->isIntOrIntVectorTy())
2555 return Error(ID.Loc,
2556 "constexpr requires integer or integer vector operands");
2557 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2558 ID.Kind = ValID::t_Constant;
2562 case lltok::kw_getelementptr:
2563 case lltok::kw_shufflevector:
2564 case lltok::kw_insertelement:
2565 case lltok::kw_extractelement:
2566 case lltok::kw_select: {
2567 unsigned Opc = Lex.getUIntVal();
2568 SmallVector<Constant*, 16> Elts;
2569 bool InBounds = false;
2571 if (Opc == Instruction::GetElementPtr)
2572 InBounds = EatIfPresent(lltok::kw_inbounds);
2573 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2574 ParseGlobalValueVector(Elts) ||
2575 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2578 if (Opc == Instruction::GetElementPtr) {
2579 if (Elts.size() == 0 ||
2580 !Elts[0]->getType()->getScalarType()->isPointerTy())
2581 return Error(ID.Loc, "getelementptr requires pointer operand");
2583 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2584 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2585 return Error(ID.Loc, "invalid indices for getelementptr");
2586 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2588 } else if (Opc == Instruction::Select) {
2589 if (Elts.size() != 3)
2590 return Error(ID.Loc, "expected three operands to select");
2591 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2593 return Error(ID.Loc, Reason);
2594 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2595 } else if (Opc == Instruction::ShuffleVector) {
2596 if (Elts.size() != 3)
2597 return Error(ID.Loc, "expected three operands to shufflevector");
2598 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2599 return Error(ID.Loc, "invalid operands to shufflevector");
2601 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2602 } else if (Opc == Instruction::ExtractElement) {
2603 if (Elts.size() != 2)
2604 return Error(ID.Loc, "expected two operands to extractelement");
2605 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2606 return Error(ID.Loc, "invalid extractelement operands");
2607 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2609 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2610 if (Elts.size() != 3)
2611 return Error(ID.Loc, "expected three operands to insertelement");
2612 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2613 return Error(ID.Loc, "invalid insertelement operands");
2615 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2618 ID.Kind = ValID::t_Constant;
2627 /// ParseGlobalValue - Parse a global value with the specified type.
2628 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2632 bool Parsed = ParseValID(ID) ||
2633 ConvertValIDToValue(Ty, ID, V, NULL);
2634 if (V && !(C = dyn_cast<Constant>(V)))
2635 return Error(ID.Loc, "global values must be constants");
2639 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2641 return ParseType(Ty) ||
2642 ParseGlobalValue(Ty, V);
2645 /// ParseGlobalValueVector
2647 /// ::= TypeAndValue (',' TypeAndValue)*
2648 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2650 if (Lex.getKind() == lltok::rbrace ||
2651 Lex.getKind() == lltok::rsquare ||
2652 Lex.getKind() == lltok::greater ||
2653 Lex.getKind() == lltok::rparen)
2657 if (ParseGlobalTypeAndValue(C)) return true;
2660 while (EatIfPresent(lltok::comma)) {
2661 if (ParseGlobalTypeAndValue(C)) return true;
2668 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2669 assert(Lex.getKind() == lltok::lbrace);
2672 SmallVector<Value*, 16> Elts;
2673 if (ParseMDNodeVector(Elts, PFS) ||
2674 ParseToken(lltok::rbrace, "expected end of metadata node"))
2677 ID.MDNodeVal = MDNode::get(Context, Elts);
2678 ID.Kind = ValID::t_MDNode;
2682 /// ParseMetadataValue
2686 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2687 assert(Lex.getKind() == lltok::exclaim);
2692 if (Lex.getKind() == lltok::lbrace)
2693 return ParseMetadataListValue(ID, PFS);
2695 // Standalone metadata reference
2697 if (Lex.getKind() == lltok::APSInt) {
2698 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2699 ID.Kind = ValID::t_MDNode;
2704 // ::= '!' STRINGCONSTANT
2705 if (ParseMDString(ID.MDStringVal)) return true;
2706 ID.Kind = ValID::t_MDString;
2711 //===----------------------------------------------------------------------===//
2712 // Function Parsing.
2713 //===----------------------------------------------------------------------===//
2715 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2716 PerFunctionState *PFS) {
2717 if (Ty->isFunctionTy())
2718 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2721 case ValID::t_LocalID:
2722 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2723 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2725 case ValID::t_LocalName:
2726 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2727 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2729 case ValID::t_InlineAsm: {
2730 PointerType *PTy = dyn_cast<PointerType>(Ty);
2732 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2733 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2734 return Error(ID.Loc, "invalid type for inline asm constraint string");
2735 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2736 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2739 case ValID::t_MDNode:
2740 if (!Ty->isMetadataTy())
2741 return Error(ID.Loc, "metadata value must have metadata type");
2744 case ValID::t_MDString:
2745 if (!Ty->isMetadataTy())
2746 return Error(ID.Loc, "metadata value must have metadata type");
2749 case ValID::t_GlobalName:
2750 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2752 case ValID::t_GlobalID:
2753 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2755 case ValID::t_APSInt:
2756 if (!Ty->isIntegerTy())
2757 return Error(ID.Loc, "integer constant must have integer type");
2758 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2759 V = ConstantInt::get(Context, ID.APSIntVal);
2761 case ValID::t_APFloat:
2762 if (!Ty->isFloatingPointTy() ||
2763 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2764 return Error(ID.Loc, "floating point constant invalid for type");
2766 // The lexer has no type info, so builds all half, float, and double FP
2767 // constants as double. Fix this here. Long double does not need this.
2768 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2771 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2773 else if (Ty->isFloatTy())
2774 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2777 V = ConstantFP::get(Context, ID.APFloatVal);
2779 if (V->getType() != Ty)
2780 return Error(ID.Loc, "floating point constant does not have type '" +
2781 getTypeString(Ty) + "'");
2785 if (!Ty->isPointerTy())
2786 return Error(ID.Loc, "null must be a pointer type");
2787 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2789 case ValID::t_Undef:
2790 // FIXME: LabelTy should not be a first-class type.
2791 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2792 return Error(ID.Loc, "invalid type for undef constant");
2793 V = UndefValue::get(Ty);
2795 case ValID::t_EmptyArray:
2796 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2797 return Error(ID.Loc, "invalid empty array initializer");
2798 V = UndefValue::get(Ty);
2801 // FIXME: LabelTy should not be a first-class type.
2802 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2803 return Error(ID.Loc, "invalid type for null constant");
2804 V = Constant::getNullValue(Ty);
2806 case ValID::t_Constant:
2807 if (ID.ConstantVal->getType() != Ty)
2808 return Error(ID.Loc, "constant expression type mismatch");
2812 case ValID::t_ConstantStruct:
2813 case ValID::t_PackedConstantStruct:
2814 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2815 if (ST->getNumElements() != ID.UIntVal)
2816 return Error(ID.Loc,
2817 "initializer with struct type has wrong # elements");
2818 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2819 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2821 // Verify that the elements are compatible with the structtype.
2822 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2823 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2824 return Error(ID.Loc, "element " + Twine(i) +
2825 " of struct initializer doesn't match struct element type");
2827 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2830 return Error(ID.Loc, "constant expression type mismatch");
2833 llvm_unreachable("Invalid ValID");
2836 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2839 return ParseValID(ID, PFS) ||
2840 ConvertValIDToValue(Ty, ID, V, PFS);
2843 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2845 return ParseType(Ty) ||
2846 ParseValue(Ty, V, PFS);
2849 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2850 PerFunctionState &PFS) {
2853 if (ParseTypeAndValue(V, PFS)) return true;
2854 if (!isa<BasicBlock>(V))
2855 return Error(Loc, "expected a basic block");
2856 BB = cast<BasicBlock>(V);
2862 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2863 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2864 /// OptionalAlign OptGC
2865 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2866 // Parse the linkage.
2867 LocTy LinkageLoc = Lex.getLoc();
2870 unsigned Visibility;
2871 AttrBuilder RetAttrs;
2874 LocTy RetTypeLoc = Lex.getLoc();
2875 if (ParseOptionalLinkage(Linkage) ||
2876 ParseOptionalVisibility(Visibility) ||
2877 ParseOptionalCallingConv(CC) ||
2878 ParseOptionalReturnAttrs(RetAttrs) ||
2879 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2882 // Verify that the linkage is ok.
2883 switch ((GlobalValue::LinkageTypes)Linkage) {
2884 case GlobalValue::ExternalLinkage:
2885 break; // always ok.
2886 case GlobalValue::DLLImportLinkage:
2887 case GlobalValue::ExternalWeakLinkage:
2889 return Error(LinkageLoc, "invalid linkage for function definition");
2891 case GlobalValue::PrivateLinkage:
2892 case GlobalValue::LinkerPrivateLinkage:
2893 case GlobalValue::LinkerPrivateWeakLinkage:
2894 case GlobalValue::InternalLinkage:
2895 case GlobalValue::AvailableExternallyLinkage:
2896 case GlobalValue::LinkOnceAnyLinkage:
2897 case GlobalValue::LinkOnceODRLinkage:
2898 case GlobalValue::LinkOnceODRAutoHideLinkage:
2899 case GlobalValue::WeakAnyLinkage:
2900 case GlobalValue::WeakODRLinkage:
2901 case GlobalValue::DLLExportLinkage:
2903 return Error(LinkageLoc, "invalid linkage for function declaration");
2905 case GlobalValue::AppendingLinkage:
2906 case GlobalValue::CommonLinkage:
2907 return Error(LinkageLoc, "invalid function linkage type");
2910 if (!FunctionType::isValidReturnType(RetType))
2911 return Error(RetTypeLoc, "invalid function return type");
2913 LocTy NameLoc = Lex.getLoc();
2915 std::string FunctionName;
2916 if (Lex.getKind() == lltok::GlobalVar) {
2917 FunctionName = Lex.getStrVal();
2918 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2919 unsigned NameID = Lex.getUIntVal();
2921 if (NameID != NumberedVals.size())
2922 return TokError("function expected to be numbered '%" +
2923 Twine(NumberedVals.size()) + "'");
2925 return TokError("expected function name");
2930 if (Lex.getKind() != lltok::lparen)
2931 return TokError("expected '(' in function argument list");
2933 SmallVector<ArgInfo, 8> ArgList;
2935 AttrBuilder FuncAttrs;
2936 std::vector<unsigned> FwdRefAttrGrps;
2937 std::string Section;
2941 LocTy UnnamedAddrLoc;
2943 if (ParseArgumentList(ArgList, isVarArg) ||
2944 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
2946 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false) ||
2947 (EatIfPresent(lltok::kw_section) &&
2948 ParseStringConstant(Section)) ||
2949 ParseOptionalAlignment(Alignment) ||
2950 (EatIfPresent(lltok::kw_gc) &&
2951 ParseStringConstant(GC)))
2954 // If the alignment was parsed as an attribute, move to the alignment field.
2955 if (FuncAttrs.hasAlignmentAttr()) {
2956 Alignment = FuncAttrs.getAlignment();
2957 FuncAttrs.removeAttribute(Attribute::Alignment);
2960 // Okay, if we got here, the function is syntactically valid. Convert types
2961 // and do semantic checks.
2962 std::vector<Type*> ParamTypeList;
2963 SmallVector<AttributeSet, 8> Attrs;
2965 if (RetAttrs.hasAttributes())
2966 Attrs.push_back(AttributeSet::get(RetType->getContext(),
2967 AttributeSet::ReturnIndex,
2970 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2971 ParamTypeList.push_back(ArgList[i].Ty);
2972 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
2973 AttrBuilder B(ArgList[i].Attrs, i + 1);
2974 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
2978 if (FuncAttrs.hasAttributes())
2979 Attrs.push_back(AttributeSet::get(RetType->getContext(),
2980 AttributeSet::FunctionIndex,
2983 AttributeSet PAL = AttributeSet::get(Context, Attrs);
2985 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
2986 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2989 FunctionType::get(RetType, ParamTypeList, isVarArg);
2990 PointerType *PFT = PointerType::getUnqual(FT);
2993 if (!FunctionName.empty()) {
2994 // If this was a definition of a forward reference, remove the definition
2995 // from the forward reference table and fill in the forward ref.
2996 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2997 ForwardRefVals.find(FunctionName);
2998 if (FRVI != ForwardRefVals.end()) {
2999 Fn = M->getFunction(FunctionName);
3001 return Error(FRVI->second.second, "invalid forward reference to "
3002 "function as global value!");
3003 if (Fn->getType() != PFT)
3004 return Error(FRVI->second.second, "invalid forward reference to "
3005 "function '" + FunctionName + "' with wrong type!");
3007 ForwardRefVals.erase(FRVI);
3008 } else if ((Fn = M->getFunction(FunctionName))) {
3009 // Reject redefinitions.
3010 return Error(NameLoc, "invalid redefinition of function '" +
3011 FunctionName + "'");
3012 } else if (M->getNamedValue(FunctionName)) {
3013 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3017 // If this is a definition of a forward referenced function, make sure the
3019 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3020 = ForwardRefValIDs.find(NumberedVals.size());
3021 if (I != ForwardRefValIDs.end()) {
3022 Fn = cast<Function>(I->second.first);
3023 if (Fn->getType() != PFT)
3024 return Error(NameLoc, "type of definition and forward reference of '@" +
3025 Twine(NumberedVals.size()) + "' disagree");
3026 ForwardRefValIDs.erase(I);
3031 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3032 else // Move the forward-reference to the correct spot in the module.
3033 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3035 if (FunctionName.empty())
3036 NumberedVals.push_back(Fn);
3038 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3039 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3040 Fn->setCallingConv(CC);
3041 Fn->setAttributes(PAL);
3042 Fn->setUnnamedAddr(UnnamedAddr);
3043 Fn->setAlignment(Alignment);
3044 Fn->setSection(Section);
3045 if (!GC.empty()) Fn->setGC(GC.c_str());
3046 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3048 // Add all of the arguments we parsed to the function.
3049 Function::arg_iterator ArgIt = Fn->arg_begin();
3050 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3051 // If the argument has a name, insert it into the argument symbol table.
3052 if (ArgList[i].Name.empty()) continue;
3054 // Set the name, if it conflicted, it will be auto-renamed.
3055 ArgIt->setName(ArgList[i].Name);
3057 if (ArgIt->getName() != ArgList[i].Name)
3058 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3059 ArgList[i].Name + "'");
3066 /// ParseFunctionBody
3067 /// ::= '{' BasicBlock+ '}'
3069 bool LLParser::ParseFunctionBody(Function &Fn) {
3070 if (Lex.getKind() != lltok::lbrace)
3071 return TokError("expected '{' in function body");
3072 Lex.Lex(); // eat the {.
3074 int FunctionNumber = -1;
3075 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3077 PerFunctionState PFS(*this, Fn, FunctionNumber);
3079 // We need at least one basic block.
3080 if (Lex.getKind() == lltok::rbrace)
3081 return TokError("function body requires at least one basic block");
3083 while (Lex.getKind() != lltok::rbrace)
3084 if (ParseBasicBlock(PFS)) return true;
3089 // Verify function is ok.
3090 return PFS.FinishFunction();
3094 /// ::= LabelStr? Instruction*
3095 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3096 // If this basic block starts out with a name, remember it.
3098 LocTy NameLoc = Lex.getLoc();
3099 if (Lex.getKind() == lltok::LabelStr) {
3100 Name = Lex.getStrVal();
3104 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3105 if (BB == 0) return true;
3107 std::string NameStr;
3109 // Parse the instructions in this block until we get a terminator.
3111 SmallVector<std::pair<unsigned, MDNode *>, 4> MetadataOnInst;
3113 // This instruction may have three possibilities for a name: a) none
3114 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3115 LocTy NameLoc = Lex.getLoc();
3119 if (Lex.getKind() == lltok::LocalVarID) {
3120 NameID = Lex.getUIntVal();
3122 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3124 } else if (Lex.getKind() == lltok::LocalVar) {
3125 NameStr = Lex.getStrVal();
3127 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3131 switch (ParseInstruction(Inst, BB, PFS)) {
3132 default: llvm_unreachable("Unknown ParseInstruction result!");
3133 case InstError: return true;
3135 BB->getInstList().push_back(Inst);
3137 // With a normal result, we check to see if the instruction is followed by
3138 // a comma and metadata.
3139 if (EatIfPresent(lltok::comma))
3140 if (ParseInstructionMetadata(Inst, &PFS))
3143 case InstExtraComma:
3144 BB->getInstList().push_back(Inst);
3146 // If the instruction parser ate an extra comma at the end of it, it
3147 // *must* be followed by metadata.
3148 if (ParseInstructionMetadata(Inst, &PFS))
3153 // Set the name on the instruction.
3154 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3155 } while (!isa<TerminatorInst>(Inst));
3160 //===----------------------------------------------------------------------===//
3161 // Instruction Parsing.
3162 //===----------------------------------------------------------------------===//
3164 /// ParseInstruction - Parse one of the many different instructions.
3166 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3167 PerFunctionState &PFS) {
3168 lltok::Kind Token = Lex.getKind();
3169 if (Token == lltok::Eof)
3170 return TokError("found end of file when expecting more instructions");
3171 LocTy Loc = Lex.getLoc();
3172 unsigned KeywordVal = Lex.getUIntVal();
3173 Lex.Lex(); // Eat the keyword.
3176 default: return Error(Loc, "expected instruction opcode");
3177 // Terminator Instructions.
3178 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3179 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3180 case lltok::kw_br: return ParseBr(Inst, PFS);
3181 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3182 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3183 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3184 case lltok::kw_resume: return ParseResume(Inst, PFS);
3185 // Binary Operators.
3189 case lltok::kw_shl: {
3190 bool NUW = EatIfPresent(lltok::kw_nuw);
3191 bool NSW = EatIfPresent(lltok::kw_nsw);
3192 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3194 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3196 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3197 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3200 case lltok::kw_fadd:
3201 case lltok::kw_fsub:
3202 case lltok::kw_fmul:
3203 case lltok::kw_fdiv:
3204 case lltok::kw_frem: {
3205 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3206 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3210 Inst->setFastMathFlags(FMF);
3214 case lltok::kw_sdiv:
3215 case lltok::kw_udiv:
3216 case lltok::kw_lshr:
3217 case lltok::kw_ashr: {
3218 bool Exact = EatIfPresent(lltok::kw_exact);
3220 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3221 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3225 case lltok::kw_urem:
3226 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3229 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3230 case lltok::kw_icmp:
3231 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3233 case lltok::kw_trunc:
3234 case lltok::kw_zext:
3235 case lltok::kw_sext:
3236 case lltok::kw_fptrunc:
3237 case lltok::kw_fpext:
3238 case lltok::kw_bitcast:
3239 case lltok::kw_uitofp:
3240 case lltok::kw_sitofp:
3241 case lltok::kw_fptoui:
3242 case lltok::kw_fptosi:
3243 case lltok::kw_inttoptr:
3244 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3246 case lltok::kw_select: return ParseSelect(Inst, PFS);
3247 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3248 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3249 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3250 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3251 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3252 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3253 case lltok::kw_call: return ParseCall(Inst, PFS, false);
3254 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
3256 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3257 case lltok::kw_load: return ParseLoad(Inst, PFS);
3258 case lltok::kw_store: return ParseStore(Inst, PFS);
3259 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3260 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3261 case lltok::kw_fence: return ParseFence(Inst, PFS);
3262 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3263 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3264 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3268 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3269 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3270 if (Opc == Instruction::FCmp) {
3271 switch (Lex.getKind()) {
3272 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3273 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3274 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3275 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3276 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3277 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3278 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3279 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3280 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3281 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3282 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3283 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3284 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3285 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3286 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3287 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3288 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3291 switch (Lex.getKind()) {
3292 default: return TokError("expected icmp predicate (e.g. 'eq')");
3293 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3294 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3295 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3296 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3297 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3298 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3299 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3300 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3301 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3302 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3309 //===----------------------------------------------------------------------===//
3310 // Terminator Instructions.
3311 //===----------------------------------------------------------------------===//
3313 /// ParseRet - Parse a return instruction.
3314 /// ::= 'ret' void (',' !dbg, !1)*
3315 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3316 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3317 PerFunctionState &PFS) {
3318 SMLoc TypeLoc = Lex.getLoc();
3320 if (ParseType(Ty, true /*void allowed*/)) return true;
3322 Type *ResType = PFS.getFunction().getReturnType();
3324 if (Ty->isVoidTy()) {
3325 if (!ResType->isVoidTy())
3326 return Error(TypeLoc, "value doesn't match function result type '" +
3327 getTypeString(ResType) + "'");
3329 Inst = ReturnInst::Create(Context);
3334 if (ParseValue(Ty, RV, PFS)) return true;
3336 if (ResType != RV->getType())
3337 return Error(TypeLoc, "value doesn't match function result type '" +
3338 getTypeString(ResType) + "'");
3340 Inst = ReturnInst::Create(Context, RV);
3346 /// ::= 'br' TypeAndValue
3347 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3348 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3351 BasicBlock *Op1, *Op2;
3352 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3354 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3355 Inst = BranchInst::Create(BB);
3359 if (Op0->getType() != Type::getInt1Ty(Context))
3360 return Error(Loc, "branch condition must have 'i1' type");
3362 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3363 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3364 ParseToken(lltok::comma, "expected ',' after true destination") ||
3365 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3368 Inst = BranchInst::Create(Op1, Op2, Op0);
3374 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3376 /// ::= (TypeAndValue ',' TypeAndValue)*
3377 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3378 LocTy CondLoc, BBLoc;
3380 BasicBlock *DefaultBB;
3381 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3382 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3383 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3384 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3387 if (!Cond->getType()->isIntegerTy())
3388 return Error(CondLoc, "switch condition must have integer type");
3390 // Parse the jump table pairs.
3391 SmallPtrSet<Value*, 32> SeenCases;
3392 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3393 while (Lex.getKind() != lltok::rsquare) {
3397 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3398 ParseToken(lltok::comma, "expected ',' after case value") ||
3399 ParseTypeAndBasicBlock(DestBB, PFS))
3402 if (!SeenCases.insert(Constant))
3403 return Error(CondLoc, "duplicate case value in switch");
3404 if (!isa<ConstantInt>(Constant))
3405 return Error(CondLoc, "case value is not a constant integer");
3407 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3410 Lex.Lex(); // Eat the ']'.
3412 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3413 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3414 SI->addCase(Table[i].first, Table[i].second);
3421 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3422 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3425 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3426 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3427 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3430 if (!Address->getType()->isPointerTy())
3431 return Error(AddrLoc, "indirectbr address must have pointer type");
3433 // Parse the destination list.
3434 SmallVector<BasicBlock*, 16> DestList;
3436 if (Lex.getKind() != lltok::rsquare) {
3438 if (ParseTypeAndBasicBlock(DestBB, PFS))
3440 DestList.push_back(DestBB);
3442 while (EatIfPresent(lltok::comma)) {
3443 if (ParseTypeAndBasicBlock(DestBB, PFS))
3445 DestList.push_back(DestBB);
3449 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3452 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3453 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3454 IBI->addDestination(DestList[i]);
3461 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3462 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3463 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3464 LocTy CallLoc = Lex.getLoc();
3465 AttrBuilder RetAttrs, FnAttrs;
3466 std::vector<unsigned> FwdRefAttrGrps;
3471 SmallVector<ParamInfo, 16> ArgList;
3473 BasicBlock *NormalBB, *UnwindBB;
3474 if (ParseOptionalCallingConv(CC) ||
3475 ParseOptionalReturnAttrs(RetAttrs) ||
3476 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3477 ParseValID(CalleeID) ||
3478 ParseParameterList(ArgList, PFS) ||
3479 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false) ||
3480 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3481 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3482 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3483 ParseTypeAndBasicBlock(UnwindBB, PFS))
3486 // If RetType is a non-function pointer type, then this is the short syntax
3487 // for the call, which means that RetType is just the return type. Infer the
3488 // rest of the function argument types from the arguments that are present.
3489 PointerType *PFTy = 0;
3490 FunctionType *Ty = 0;
3491 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3492 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3493 // Pull out the types of all of the arguments...
3494 std::vector<Type*> ParamTypes;
3495 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3496 ParamTypes.push_back(ArgList[i].V->getType());
3498 if (!FunctionType::isValidReturnType(RetType))
3499 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3501 Ty = FunctionType::get(RetType, ParamTypes, false);
3502 PFTy = PointerType::getUnqual(Ty);
3505 // Look up the callee.
3507 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3509 // Set up the Attribute for the function.
3510 SmallVector<AttributeSet, 8> Attrs;
3511 if (RetAttrs.hasAttributes())
3512 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3513 AttributeSet::ReturnIndex,
3516 SmallVector<Value*, 8> Args;
3518 // Loop through FunctionType's arguments and ensure they are specified
3519 // correctly. Also, gather any parameter attributes.
3520 FunctionType::param_iterator I = Ty->param_begin();
3521 FunctionType::param_iterator E = Ty->param_end();
3522 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3523 Type *ExpectedTy = 0;
3526 } else if (!Ty->isVarArg()) {
3527 return Error(ArgList[i].Loc, "too many arguments specified");
3530 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3531 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3532 getTypeString(ExpectedTy) + "'");
3533 Args.push_back(ArgList[i].V);
3534 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3535 AttrBuilder B(ArgList[i].Attrs, i + 1);
3536 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3541 return Error(CallLoc, "not enough parameters specified for call");
3543 if (FnAttrs.hasAttributes())
3544 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3545 AttributeSet::FunctionIndex,
3548 // Finish off the Attribute and check them
3549 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3551 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3552 II->setCallingConv(CC);
3553 II->setAttributes(PAL);
3554 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3560 /// ::= 'resume' TypeAndValue
3561 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3562 Value *Exn; LocTy ExnLoc;
3563 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3566 ResumeInst *RI = ResumeInst::Create(Exn);
3571 //===----------------------------------------------------------------------===//
3572 // Binary Operators.
3573 //===----------------------------------------------------------------------===//
3576 /// ::= ArithmeticOps TypeAndValue ',' Value
3578 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3579 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3580 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3581 unsigned Opc, unsigned OperandType) {
3582 LocTy Loc; Value *LHS, *RHS;
3583 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3584 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3585 ParseValue(LHS->getType(), RHS, PFS))
3589 switch (OperandType) {
3590 default: llvm_unreachable("Unknown operand type!");
3591 case 0: // int or FP.
3592 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3593 LHS->getType()->isFPOrFPVectorTy();
3595 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3596 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3600 return Error(Loc, "invalid operand type for instruction");
3602 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3607 /// ::= ArithmeticOps TypeAndValue ',' Value {
3608 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3610 LocTy Loc; Value *LHS, *RHS;
3611 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3612 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3613 ParseValue(LHS->getType(), RHS, PFS))
3616 if (!LHS->getType()->isIntOrIntVectorTy())
3617 return Error(Loc,"instruction requires integer or integer vector operands");
3619 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3625 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3626 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3627 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3629 // Parse the integer/fp comparison predicate.
3633 if (ParseCmpPredicate(Pred, Opc) ||
3634 ParseTypeAndValue(LHS, Loc, PFS) ||
3635 ParseToken(lltok::comma, "expected ',' after compare value") ||
3636 ParseValue(LHS->getType(), RHS, PFS))
3639 if (Opc == Instruction::FCmp) {
3640 if (!LHS->getType()->isFPOrFPVectorTy())
3641 return Error(Loc, "fcmp requires floating point operands");
3642 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3644 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3645 if (!LHS->getType()->isIntOrIntVectorTy() &&
3646 !LHS->getType()->getScalarType()->isPointerTy())
3647 return Error(Loc, "icmp requires integer operands");
3648 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3653 //===----------------------------------------------------------------------===//
3654 // Other Instructions.
3655 //===----------------------------------------------------------------------===//
3659 /// ::= CastOpc TypeAndValue 'to' Type
3660 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3665 if (ParseTypeAndValue(Op, Loc, PFS) ||
3666 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3670 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3671 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3672 return Error(Loc, "invalid cast opcode for cast from '" +
3673 getTypeString(Op->getType()) + "' to '" +
3674 getTypeString(DestTy) + "'");
3676 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3681 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3682 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3684 Value *Op0, *Op1, *Op2;
3685 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3686 ParseToken(lltok::comma, "expected ',' after select condition") ||
3687 ParseTypeAndValue(Op1, PFS) ||
3688 ParseToken(lltok::comma, "expected ',' after select value") ||
3689 ParseTypeAndValue(Op2, PFS))
3692 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3693 return Error(Loc, Reason);
3695 Inst = SelectInst::Create(Op0, Op1, Op2);
3700 /// ::= 'va_arg' TypeAndValue ',' Type
3701 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3705 if (ParseTypeAndValue(Op, PFS) ||
3706 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3707 ParseType(EltTy, TypeLoc))
3710 if (!EltTy->isFirstClassType())
3711 return Error(TypeLoc, "va_arg requires operand with first class type");
3713 Inst = new VAArgInst(Op, EltTy);
3717 /// ParseExtractElement
3718 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3719 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3722 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3723 ParseToken(lltok::comma, "expected ',' after extract value") ||
3724 ParseTypeAndValue(Op1, PFS))
3727 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3728 return Error(Loc, "invalid extractelement operands");
3730 Inst = ExtractElementInst::Create(Op0, Op1);
3734 /// ParseInsertElement
3735 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3736 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3738 Value *Op0, *Op1, *Op2;
3739 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3740 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3741 ParseTypeAndValue(Op1, PFS) ||
3742 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3743 ParseTypeAndValue(Op2, PFS))
3746 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3747 return Error(Loc, "invalid insertelement operands");
3749 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3753 /// ParseShuffleVector
3754 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3755 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3757 Value *Op0, *Op1, *Op2;
3758 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3759 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3760 ParseTypeAndValue(Op1, PFS) ||
3761 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3762 ParseTypeAndValue(Op2, PFS))
3765 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3766 return Error(Loc, "invalid shufflevector operands");
3768 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3773 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3774 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3775 Type *Ty = 0; LocTy TypeLoc;
3778 if (ParseType(Ty, TypeLoc) ||
3779 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3780 ParseValue(Ty, Op0, PFS) ||
3781 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3782 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3783 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3786 bool AteExtraComma = false;
3787 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3789 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3791 if (!EatIfPresent(lltok::comma))
3794 if (Lex.getKind() == lltok::MetadataVar) {
3795 AteExtraComma = true;
3799 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3800 ParseValue(Ty, Op0, PFS) ||
3801 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3802 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3803 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3807 if (!Ty->isFirstClassType())
3808 return Error(TypeLoc, "phi node must have first class type");
3810 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3811 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3812 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3814 return AteExtraComma ? InstExtraComma : InstNormal;
3818 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3820 /// ::= 'catch' TypeAndValue
3822 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3823 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3824 Type *Ty = 0; LocTy TyLoc;
3825 Value *PersFn; LocTy PersFnLoc;
3827 if (ParseType(Ty, TyLoc) ||
3828 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3829 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3832 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3833 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3835 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3836 LandingPadInst::ClauseType CT;
3837 if (EatIfPresent(lltok::kw_catch))
3838 CT = LandingPadInst::Catch;
3839 else if (EatIfPresent(lltok::kw_filter))
3840 CT = LandingPadInst::Filter;
3842 return TokError("expected 'catch' or 'filter' clause type");
3844 Value *V; LocTy VLoc;
3845 if (ParseTypeAndValue(V, VLoc, PFS)) {
3850 // A 'catch' type expects a non-array constant. A filter clause expects an
3852 if (CT == LandingPadInst::Catch) {
3853 if (isa<ArrayType>(V->getType()))
3854 Error(VLoc, "'catch' clause has an invalid type");
3856 if (!isa<ArrayType>(V->getType()))
3857 Error(VLoc, "'filter' clause has an invalid type");
3868 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3869 /// ParameterList OptionalAttrs
3870 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3872 AttrBuilder RetAttrs, FnAttrs;
3873 std::vector<unsigned> FwdRefAttrGrps;
3878 SmallVector<ParamInfo, 16> ArgList;
3879 LocTy CallLoc = Lex.getLoc();
3881 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3882 ParseOptionalCallingConv(CC) ||
3883 ParseOptionalReturnAttrs(RetAttrs) ||
3884 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3885 ParseValID(CalleeID) ||
3886 ParseParameterList(ArgList, PFS) ||
3887 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false))
3890 // If RetType is a non-function pointer type, then this is the short syntax
3891 // for the call, which means that RetType is just the return type. Infer the
3892 // rest of the function argument types from the arguments that are present.
3893 PointerType *PFTy = 0;
3894 FunctionType *Ty = 0;
3895 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3896 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3897 // Pull out the types of all of the arguments...
3898 std::vector<Type*> ParamTypes;
3899 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3900 ParamTypes.push_back(ArgList[i].V->getType());
3902 if (!FunctionType::isValidReturnType(RetType))
3903 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3905 Ty = FunctionType::get(RetType, ParamTypes, false);
3906 PFTy = PointerType::getUnqual(Ty);
3909 // Look up the callee.
3911 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3913 // Set up the Attribute for the function.
3914 SmallVector<AttributeSet, 8> Attrs;
3915 if (RetAttrs.hasAttributes())
3916 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3917 AttributeSet::ReturnIndex,
3920 SmallVector<Value*, 8> Args;
3922 // Loop through FunctionType's arguments and ensure they are specified
3923 // correctly. Also, gather any parameter attributes.
3924 FunctionType::param_iterator I = Ty->param_begin();
3925 FunctionType::param_iterator E = Ty->param_end();
3926 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3927 Type *ExpectedTy = 0;
3930 } else if (!Ty->isVarArg()) {
3931 return Error(ArgList[i].Loc, "too many arguments specified");
3934 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3935 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3936 getTypeString(ExpectedTy) + "'");
3937 Args.push_back(ArgList[i].V);
3938 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3939 AttrBuilder B(ArgList[i].Attrs, i + 1);
3940 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3945 return Error(CallLoc, "not enough parameters specified for call");
3947 if (FnAttrs.hasAttributes())
3948 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3949 AttributeSet::FunctionIndex,
3952 // Finish off the Attribute and check them
3953 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3955 CallInst *CI = CallInst::Create(Callee, Args);
3956 CI->setTailCall(isTail);
3957 CI->setCallingConv(CC);
3958 CI->setAttributes(PAL);
3959 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
3964 //===----------------------------------------------------------------------===//
3965 // Memory Instructions.
3966 //===----------------------------------------------------------------------===//
3969 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalInfo)?
3970 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
3973 unsigned Alignment = 0;
3975 if (ParseType(Ty)) return true;
3977 bool AteExtraComma = false;
3978 if (EatIfPresent(lltok::comma)) {
3979 if (Lex.getKind() == lltok::kw_align) {
3980 if (ParseOptionalAlignment(Alignment)) return true;
3981 } else if (Lex.getKind() == lltok::MetadataVar) {
3982 AteExtraComma = true;
3984 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3985 ParseOptionalCommaAlign(Alignment, AteExtraComma))
3990 if (Size && !Size->getType()->isIntegerTy())
3991 return Error(SizeLoc, "element count must have integer type");
3993 Inst = new AllocaInst(Ty, Size, Alignment);
3994 return AteExtraComma ? InstExtraComma : InstNormal;
3998 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
3999 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4000 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4001 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4002 Value *Val; LocTy Loc;
4003 unsigned Alignment = 0;
4004 bool AteExtraComma = false;
4005 bool isAtomic = false;
4006 AtomicOrdering Ordering = NotAtomic;
4007 SynchronizationScope Scope = CrossThread;
4009 if (Lex.getKind() == lltok::kw_atomic) {
4014 bool isVolatile = false;
4015 if (Lex.getKind() == lltok::kw_volatile) {
4020 if (ParseTypeAndValue(Val, Loc, PFS) ||
4021 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4022 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4025 if (!Val->getType()->isPointerTy() ||
4026 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4027 return Error(Loc, "load operand must be a pointer to a first class type");
4028 if (isAtomic && !Alignment)
4029 return Error(Loc, "atomic load must have explicit non-zero alignment");
4030 if (Ordering == Release || Ordering == AcquireRelease)
4031 return Error(Loc, "atomic load cannot use Release ordering");
4033 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4034 return AteExtraComma ? InstExtraComma : InstNormal;
4039 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4040 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4041 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4042 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4043 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4044 unsigned Alignment = 0;
4045 bool AteExtraComma = false;
4046 bool isAtomic = false;
4047 AtomicOrdering Ordering = NotAtomic;
4048 SynchronizationScope Scope = CrossThread;
4050 if (Lex.getKind() == lltok::kw_atomic) {
4055 bool isVolatile = false;
4056 if (Lex.getKind() == lltok::kw_volatile) {
4061 if (ParseTypeAndValue(Val, Loc, PFS) ||
4062 ParseToken(lltok::comma, "expected ',' after store operand") ||
4063 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4064 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4065 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4068 if (!Ptr->getType()->isPointerTy())
4069 return Error(PtrLoc, "store operand must be a pointer");
4070 if (!Val->getType()->isFirstClassType())
4071 return Error(Loc, "store operand must be a first class value");
4072 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4073 return Error(Loc, "stored value and pointer type do not match");
4074 if (isAtomic && !Alignment)
4075 return Error(Loc, "atomic store must have explicit non-zero alignment");
4076 if (Ordering == Acquire || Ordering == AcquireRelease)
4077 return Error(Loc, "atomic store cannot use Acquire ordering");
4079 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4080 return AteExtraComma ? InstExtraComma : InstNormal;
4084 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4085 /// 'singlethread'? AtomicOrdering
4086 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4087 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4088 bool AteExtraComma = false;
4089 AtomicOrdering Ordering = NotAtomic;
4090 SynchronizationScope Scope = CrossThread;
4091 bool isVolatile = false;
4093 if (EatIfPresent(lltok::kw_volatile))
4096 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4097 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4098 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4099 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4100 ParseTypeAndValue(New, NewLoc, PFS) ||
4101 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4104 if (Ordering == Unordered)
4105 return TokError("cmpxchg cannot be unordered");
4106 if (!Ptr->getType()->isPointerTy())
4107 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4108 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4109 return Error(CmpLoc, "compare value and pointer type do not match");
4110 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4111 return Error(NewLoc, "new value and pointer type do not match");
4112 if (!New->getType()->isIntegerTy())
4113 return Error(NewLoc, "cmpxchg operand must be an integer");
4114 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4115 if (Size < 8 || (Size & (Size - 1)))
4116 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4119 AtomicCmpXchgInst *CXI =
4120 new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, Scope);
4121 CXI->setVolatile(isVolatile);
4123 return AteExtraComma ? InstExtraComma : InstNormal;
4127 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4128 /// 'singlethread'? AtomicOrdering
4129 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4130 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4131 bool AteExtraComma = false;
4132 AtomicOrdering Ordering = NotAtomic;
4133 SynchronizationScope Scope = CrossThread;
4134 bool isVolatile = false;
4135 AtomicRMWInst::BinOp Operation;
4137 if (EatIfPresent(lltok::kw_volatile))
4140 switch (Lex.getKind()) {
4141 default: return TokError("expected binary operation in atomicrmw");
4142 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4143 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4144 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4145 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4146 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4147 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4148 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4149 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4150 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4151 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4152 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4154 Lex.Lex(); // Eat the operation.
4156 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4157 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4158 ParseTypeAndValue(Val, ValLoc, PFS) ||
4159 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4162 if (Ordering == Unordered)
4163 return TokError("atomicrmw cannot be unordered");
4164 if (!Ptr->getType()->isPointerTy())
4165 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4166 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4167 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4168 if (!Val->getType()->isIntegerTy())
4169 return Error(ValLoc, "atomicrmw operand must be an integer");
4170 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4171 if (Size < 8 || (Size & (Size - 1)))
4172 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4175 AtomicRMWInst *RMWI =
4176 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4177 RMWI->setVolatile(isVolatile);
4179 return AteExtraComma ? InstExtraComma : InstNormal;
4183 /// ::= 'fence' 'singlethread'? AtomicOrdering
4184 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4185 AtomicOrdering Ordering = NotAtomic;
4186 SynchronizationScope Scope = CrossThread;
4187 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4190 if (Ordering == Unordered)
4191 return TokError("fence cannot be unordered");
4192 if (Ordering == Monotonic)
4193 return TokError("fence cannot be monotonic");
4195 Inst = new FenceInst(Context, Ordering, Scope);
4199 /// ParseGetElementPtr
4200 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4201 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4206 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4208 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4210 if (!Ptr->getType()->getScalarType()->isPointerTy())
4211 return Error(Loc, "base of getelementptr must be a pointer");
4213 SmallVector<Value*, 16> Indices;
4214 bool AteExtraComma = false;
4215 while (EatIfPresent(lltok::comma)) {
4216 if (Lex.getKind() == lltok::MetadataVar) {
4217 AteExtraComma = true;
4220 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4221 if (!Val->getType()->getScalarType()->isIntegerTy())
4222 return Error(EltLoc, "getelementptr index must be an integer");
4223 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4224 return Error(EltLoc, "getelementptr index type missmatch");
4225 if (Val->getType()->isVectorTy()) {
4226 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4227 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4228 if (ValNumEl != PtrNumEl)
4229 return Error(EltLoc,
4230 "getelementptr vector index has a wrong number of elements");
4232 Indices.push_back(Val);
4235 if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
4236 return Error(Loc, "invalid getelementptr indices");
4237 Inst = GetElementPtrInst::Create(Ptr, Indices);
4239 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4240 return AteExtraComma ? InstExtraComma : InstNormal;
4243 /// ParseExtractValue
4244 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4245 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4246 Value *Val; LocTy Loc;
4247 SmallVector<unsigned, 4> Indices;
4249 if (ParseTypeAndValue(Val, Loc, PFS) ||
4250 ParseIndexList(Indices, AteExtraComma))
4253 if (!Val->getType()->isAggregateType())
4254 return Error(Loc, "extractvalue operand must be aggregate type");
4256 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4257 return Error(Loc, "invalid indices for extractvalue");
4258 Inst = ExtractValueInst::Create(Val, Indices);
4259 return AteExtraComma ? InstExtraComma : InstNormal;
4262 /// ParseInsertValue
4263 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4264 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4265 Value *Val0, *Val1; LocTy Loc0, Loc1;
4266 SmallVector<unsigned, 4> Indices;
4268 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4269 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4270 ParseTypeAndValue(Val1, Loc1, PFS) ||
4271 ParseIndexList(Indices, AteExtraComma))
4274 if (!Val0->getType()->isAggregateType())
4275 return Error(Loc0, "insertvalue operand must be aggregate type");
4277 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4278 return Error(Loc0, "invalid indices for insertvalue");
4279 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4280 return AteExtraComma ? InstExtraComma : InstNormal;
4283 //===----------------------------------------------------------------------===//
4284 // Embedded metadata.
4285 //===----------------------------------------------------------------------===//
4287 /// ParseMDNodeVector
4288 /// ::= Element (',' Element)*
4290 /// ::= 'null' | TypeAndValue
4291 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4292 PerFunctionState *PFS) {
4293 // Check for an empty list.
4294 if (Lex.getKind() == lltok::rbrace)
4298 // Null is a special case since it is typeless.
4299 if (EatIfPresent(lltok::kw_null)) {
4305 if (ParseTypeAndValue(V, PFS)) return true;
4307 } while (EatIfPresent(lltok::comma));