Update comments.
[llvm/msp430.git] / lib / AsmParser / LLParser.cpp
blobaf309926afd615f7b82cc30f2366df21864ccd86
1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
14 #include "LLParser.h"
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/ValueSymbolTable.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Support/raw_ostream.h"
26 using namespace llvm;
28 namespace llvm {
29 /// ValID - Represents a reference of a definition of some sort with no type.
30 /// There are several cases where we have to parse the value but where the
31 /// type can depend on later context. This may either be a numeric reference
32 /// or a symbolic (%var) reference. This is just a discriminated union.
33 struct ValID {
34 enum {
35 t_LocalID, t_GlobalID, // ID in UIntVal.
36 t_LocalName, t_GlobalName, // Name in StrVal.
37 t_APSInt, t_APFloat, // Value in APSIntVal/APFloatVal.
38 t_Null, t_Undef, t_Zero, // No value.
39 t_EmptyArray, // No value: []
40 t_Constant, // Value in ConstantVal.
41 t_InlineAsm // Value in StrVal/StrVal2/UIntVal.
42 } Kind;
44 LLParser::LocTy Loc;
45 unsigned UIntVal;
46 std::string StrVal, StrVal2;
47 APSInt APSIntVal;
48 APFloat APFloatVal;
49 Constant *ConstantVal;
50 ValID() : APFloatVal(0.0) {}
54 /// Run: module ::= toplevelentity*
55 bool LLParser::Run() {
56 // Prime the lexer.
57 Lex.Lex();
59 return ParseTopLevelEntities() ||
60 ValidateEndOfModule();
63 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
64 /// module.
65 bool LLParser::ValidateEndOfModule() {
66 if (!ForwardRefTypes.empty())
67 return Error(ForwardRefTypes.begin()->second.second,
68 "use of undefined type named '" +
69 ForwardRefTypes.begin()->first + "'");
70 if (!ForwardRefTypeIDs.empty())
71 return Error(ForwardRefTypeIDs.begin()->second.second,
72 "use of undefined type '%" +
73 utostr(ForwardRefTypeIDs.begin()->first) + "'");
75 if (!ForwardRefVals.empty())
76 return Error(ForwardRefVals.begin()->second.second,
77 "use of undefined value '@" + ForwardRefVals.begin()->first +
78 "'");
80 if (!ForwardRefValIDs.empty())
81 return Error(ForwardRefValIDs.begin()->second.second,
82 "use of undefined value '@" +
83 utostr(ForwardRefValIDs.begin()->first) + "'");
85 // Look for intrinsic functions and CallInst that need to be upgraded
86 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
87 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
89 return false;
92 //===----------------------------------------------------------------------===//
93 // Top-Level Entities
94 //===----------------------------------------------------------------------===//
96 bool LLParser::ParseTopLevelEntities() {
97 while (1) {
98 switch (Lex.getKind()) {
99 default: return TokError("expected top-level entity");
100 case lltok::Eof: return false;
101 //case lltok::kw_define:
102 case lltok::kw_declare: if (ParseDeclare()) return true; break;
103 case lltok::kw_define: if (ParseDefine()) return true; break;
104 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
105 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
106 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
107 case lltok::kw_type: if (ParseUnnamedType()) return true; break;
108 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
109 case lltok::LocalVar: if (ParseNamedType()) return true; break;
110 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
112 // The Global variable production with no name can have many different
113 // optional leading prefixes, the production is:
114 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
115 // OptionalAddrSpace ('constant'|'global') ...
116 case lltok::kw_private: // OptionalLinkage
117 case lltok::kw_internal: // OptionalLinkage
118 case lltok::kw_weak: // OptionalLinkage
119 case lltok::kw_weak_odr: // OptionalLinkage
120 case lltok::kw_linkonce: // OptionalLinkage
121 case lltok::kw_linkonce_odr: // OptionalLinkage
122 case lltok::kw_appending: // OptionalLinkage
123 case lltok::kw_dllexport: // OptionalLinkage
124 case lltok::kw_common: // OptionalLinkage
125 case lltok::kw_dllimport: // OptionalLinkage
126 case lltok::kw_extern_weak: // OptionalLinkage
127 case lltok::kw_external: { // OptionalLinkage
128 unsigned Linkage, Visibility;
129 if (ParseOptionalLinkage(Linkage) ||
130 ParseOptionalVisibility(Visibility) ||
131 ParseGlobal("", 0, Linkage, true, Visibility))
132 return true;
133 break;
135 case lltok::kw_default: // OptionalVisibility
136 case lltok::kw_hidden: // OptionalVisibility
137 case lltok::kw_protected: { // OptionalVisibility
138 unsigned Visibility;
139 if (ParseOptionalVisibility(Visibility) ||
140 ParseGlobal("", 0, 0, false, Visibility))
141 return true;
142 break;
145 case lltok::kw_thread_local: // OptionalThreadLocal
146 case lltok::kw_addrspace: // OptionalAddrSpace
147 case lltok::kw_constant: // GlobalType
148 case lltok::kw_global: // GlobalType
149 if (ParseGlobal("", 0, 0, false, 0)) return true;
150 break;
156 /// toplevelentity
157 /// ::= 'module' 'asm' STRINGCONSTANT
158 bool LLParser::ParseModuleAsm() {
159 assert(Lex.getKind() == lltok::kw_module);
160 Lex.Lex();
162 std::string AsmStr;
163 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
164 ParseStringConstant(AsmStr)) return true;
166 const std::string &AsmSoFar = M->getModuleInlineAsm();
167 if (AsmSoFar.empty())
168 M->setModuleInlineAsm(AsmStr);
169 else
170 M->setModuleInlineAsm(AsmSoFar+"\n"+AsmStr);
171 return false;
174 /// toplevelentity
175 /// ::= 'target' 'triple' '=' STRINGCONSTANT
176 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
177 bool LLParser::ParseTargetDefinition() {
178 assert(Lex.getKind() == lltok::kw_target);
179 std::string Str;
180 switch (Lex.Lex()) {
181 default: return TokError("unknown target property");
182 case lltok::kw_triple:
183 Lex.Lex();
184 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
185 ParseStringConstant(Str))
186 return true;
187 M->setTargetTriple(Str);
188 return false;
189 case lltok::kw_datalayout:
190 Lex.Lex();
191 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
192 ParseStringConstant(Str))
193 return true;
194 M->setDataLayout(Str);
195 return false;
199 /// toplevelentity
200 /// ::= 'deplibs' '=' '[' ']'
201 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
202 bool LLParser::ParseDepLibs() {
203 assert(Lex.getKind() == lltok::kw_deplibs);
204 Lex.Lex();
205 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
206 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
207 return true;
209 if (EatIfPresent(lltok::rsquare))
210 return false;
212 std::string Str;
213 if (ParseStringConstant(Str)) return true;
214 M->addLibrary(Str);
216 while (EatIfPresent(lltok::comma)) {
217 if (ParseStringConstant(Str)) return true;
218 M->addLibrary(Str);
221 return ParseToken(lltok::rsquare, "expected ']' at end of list");
224 /// toplevelentity
225 /// ::= 'type' type
226 bool LLParser::ParseUnnamedType() {
227 assert(Lex.getKind() == lltok::kw_type);
228 LocTy TypeLoc = Lex.getLoc();
229 Lex.Lex(); // eat kw_type
231 PATypeHolder Ty(Type::VoidTy);
232 if (ParseType(Ty)) return true;
234 unsigned TypeID = NumberedTypes.size();
236 // See if this type was previously referenced.
237 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
238 FI = ForwardRefTypeIDs.find(TypeID);
239 if (FI != ForwardRefTypeIDs.end()) {
240 if (FI->second.first.get() == Ty)
241 return Error(TypeLoc, "self referential type is invalid");
243 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
244 Ty = FI->second.first.get();
245 ForwardRefTypeIDs.erase(FI);
248 NumberedTypes.push_back(Ty);
250 return false;
253 /// toplevelentity
254 /// ::= LocalVar '=' 'type' type
255 bool LLParser::ParseNamedType() {
256 std::string Name = Lex.getStrVal();
257 LocTy NameLoc = Lex.getLoc();
258 Lex.Lex(); // eat LocalVar.
260 PATypeHolder Ty(Type::VoidTy);
262 if (ParseToken(lltok::equal, "expected '=' after name") ||
263 ParseToken(lltok::kw_type, "expected 'type' after name") ||
264 ParseType(Ty))
265 return true;
267 // Set the type name, checking for conflicts as we do so.
268 bool AlreadyExists = M->addTypeName(Name, Ty);
269 if (!AlreadyExists) return false;
271 // See if this type is a forward reference. We need to eagerly resolve
272 // types to allow recursive type redefinitions below.
273 std::map<std::string, std::pair<PATypeHolder, LocTy> >::iterator
274 FI = ForwardRefTypes.find(Name);
275 if (FI != ForwardRefTypes.end()) {
276 if (FI->second.first.get() == Ty)
277 return Error(NameLoc, "self referential type is invalid");
279 cast<DerivedType>(FI->second.first.get())->refineAbstractTypeTo(Ty);
280 Ty = FI->second.first.get();
281 ForwardRefTypes.erase(FI);
284 // Inserting a name that is already defined, get the existing name.
285 const Type *Existing = M->getTypeByName(Name);
286 assert(Existing && "Conflict but no matching type?!");
288 // Otherwise, this is an attempt to redefine a type. That's okay if
289 // the redefinition is identical to the original.
290 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
291 if (Existing == Ty) return false;
293 // Any other kind of (non-equivalent) redefinition is an error.
294 return Error(NameLoc, "redefinition of type named '" + Name + "' of type '" +
295 Ty->getDescription() + "'");
299 /// toplevelentity
300 /// ::= 'declare' FunctionHeader
301 bool LLParser::ParseDeclare() {
302 assert(Lex.getKind() == lltok::kw_declare);
303 Lex.Lex();
305 Function *F;
306 return ParseFunctionHeader(F, false);
309 /// toplevelentity
310 /// ::= 'define' FunctionHeader '{' ...
311 bool LLParser::ParseDefine() {
312 assert(Lex.getKind() == lltok::kw_define);
313 Lex.Lex();
315 Function *F;
316 return ParseFunctionHeader(F, true) ||
317 ParseFunctionBody(*F);
320 /// ParseGlobalType
321 /// ::= 'constant'
322 /// ::= 'global'
323 bool LLParser::ParseGlobalType(bool &IsConstant) {
324 if (Lex.getKind() == lltok::kw_constant)
325 IsConstant = true;
326 else if (Lex.getKind() == lltok::kw_global)
327 IsConstant = false;
328 else {
329 IsConstant = false;
330 return TokError("expected 'global' or 'constant'");
332 Lex.Lex();
333 return false;
336 /// ParseNamedGlobal:
337 /// GlobalVar '=' OptionalVisibility ALIAS ...
338 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
339 bool LLParser::ParseNamedGlobal() {
340 assert(Lex.getKind() == lltok::GlobalVar);
341 LocTy NameLoc = Lex.getLoc();
342 std::string Name = Lex.getStrVal();
343 Lex.Lex();
345 bool HasLinkage;
346 unsigned Linkage, Visibility;
347 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
348 ParseOptionalLinkage(Linkage, HasLinkage) ||
349 ParseOptionalVisibility(Visibility))
350 return true;
352 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
353 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
354 return ParseAlias(Name, NameLoc, Visibility);
357 /// ParseAlias:
358 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
359 /// Aliasee
360 /// ::= TypeAndValue | 'bitcast' '(' TypeAndValue 'to' Type ')'
362 /// Everything through visibility has already been parsed.
364 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
365 unsigned Visibility) {
366 assert(Lex.getKind() == lltok::kw_alias);
367 Lex.Lex();
368 unsigned Linkage;
369 LocTy LinkageLoc = Lex.getLoc();
370 if (ParseOptionalLinkage(Linkage))
371 return true;
373 if (Linkage != GlobalValue::ExternalLinkage &&
374 Linkage != GlobalValue::WeakAnyLinkage &&
375 Linkage != GlobalValue::WeakODRLinkage &&
376 Linkage != GlobalValue::InternalLinkage &&
377 Linkage != GlobalValue::PrivateLinkage)
378 return Error(LinkageLoc, "invalid linkage type for alias");
380 Constant *Aliasee;
381 LocTy AliaseeLoc = Lex.getLoc();
382 if (Lex.getKind() != lltok::kw_bitcast) {
383 if (ParseGlobalTypeAndValue(Aliasee)) return true;
384 } else {
385 // The bitcast dest type is not present, it is implied by the dest type.
386 ValID ID;
387 if (ParseValID(ID)) return true;
388 if (ID.Kind != ValID::t_Constant)
389 return Error(AliaseeLoc, "invalid aliasee");
390 Aliasee = ID.ConstantVal;
393 if (!isa<PointerType>(Aliasee->getType()))
394 return Error(AliaseeLoc, "alias must have pointer type");
396 // Okay, create the alias but do not insert it into the module yet.
397 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
398 (GlobalValue::LinkageTypes)Linkage, Name,
399 Aliasee);
400 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
402 // See if this value already exists in the symbol table. If so, it is either
403 // a redefinition or a definition of a forward reference.
404 if (GlobalValue *Val =
405 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name))) {
406 // See if this was a redefinition. If so, there is no entry in
407 // ForwardRefVals.
408 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
409 I = ForwardRefVals.find(Name);
410 if (I == ForwardRefVals.end())
411 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
413 // Otherwise, this was a definition of forward ref. Verify that types
414 // agree.
415 if (Val->getType() != GA->getType())
416 return Error(NameLoc,
417 "forward reference and definition of alias have different types");
419 // If they agree, just RAUW the old value with the alias and remove the
420 // forward ref info.
421 Val->replaceAllUsesWith(GA);
422 Val->eraseFromParent();
423 ForwardRefVals.erase(I);
426 // Insert into the module, we know its name won't collide now.
427 M->getAliasList().push_back(GA);
428 assert(GA->getNameStr() == Name && "Should not be a name conflict!");
430 return false;
433 /// ParseGlobal
434 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
435 /// OptionalAddrSpace GlobalType Type Const
436 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
437 /// OptionalAddrSpace GlobalType Type Const
439 /// Everything through visibility has been parsed already.
441 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
442 unsigned Linkage, bool HasLinkage,
443 unsigned Visibility) {
444 unsigned AddrSpace;
445 bool ThreadLocal, IsConstant;
446 LocTy TyLoc;
448 PATypeHolder Ty(Type::VoidTy);
449 if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
450 ParseOptionalAddrSpace(AddrSpace) ||
451 ParseGlobalType(IsConstant) ||
452 ParseType(Ty, TyLoc))
453 return true;
455 // If the linkage is specified and is external, then no initializer is
456 // present.
457 Constant *Init = 0;
458 if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
459 Linkage != GlobalValue::ExternalWeakLinkage &&
460 Linkage != GlobalValue::ExternalLinkage)) {
461 if (ParseGlobalValue(Ty, Init))
462 return true;
465 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy)
466 return Error(TyLoc, "invalid type for global variable");
468 GlobalVariable *GV = 0;
470 // See if the global was forward referenced, if so, use the global.
471 if (!Name.empty()) {
472 if ((GV = M->getGlobalVariable(Name, true)) &&
473 !ForwardRefVals.erase(Name))
474 return Error(NameLoc, "redefinition of global '@" + Name + "'");
475 } else {
476 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
477 I = ForwardRefValIDs.find(NumberedVals.size());
478 if (I != ForwardRefValIDs.end()) {
479 GV = cast<GlobalVariable>(I->second.first);
480 ForwardRefValIDs.erase(I);
484 if (GV == 0) {
485 GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0, Name,
486 M, false, AddrSpace);
487 } else {
488 if (GV->getType()->getElementType() != Ty)
489 return Error(TyLoc,
490 "forward reference and definition of global have different types");
492 // Move the forward-reference to the correct spot in the module.
493 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
496 if (Name.empty())
497 NumberedVals.push_back(GV);
499 // Set the parsed properties on the global.
500 if (Init)
501 GV->setInitializer(Init);
502 GV->setConstant(IsConstant);
503 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
504 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
505 GV->setThreadLocal(ThreadLocal);
507 // Parse attributes on the global.
508 while (Lex.getKind() == lltok::comma) {
509 Lex.Lex();
511 if (Lex.getKind() == lltok::kw_section) {
512 Lex.Lex();
513 GV->setSection(Lex.getStrVal());
514 if (ParseToken(lltok::StringConstant, "expected global section string"))
515 return true;
516 } else if (Lex.getKind() == lltok::kw_align) {
517 unsigned Alignment;
518 if (ParseOptionalAlignment(Alignment)) return true;
519 GV->setAlignment(Alignment);
520 } else {
521 TokError("unknown global variable property!");
525 return false;
529 //===----------------------------------------------------------------------===//
530 // GlobalValue Reference/Resolution Routines.
531 //===----------------------------------------------------------------------===//
533 /// GetGlobalVal - Get a value with the specified name or ID, creating a
534 /// forward reference record if needed. This can return null if the value
535 /// exists but does not have the right type.
536 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, const Type *Ty,
537 LocTy Loc) {
538 const PointerType *PTy = dyn_cast<PointerType>(Ty);
539 if (PTy == 0) {
540 Error(Loc, "global variable reference must have pointer type");
541 return 0;
544 // Look this name up in the normal function symbol table.
545 GlobalValue *Val =
546 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
548 // If this is a forward reference for the value, see if we already created a
549 // forward ref record.
550 if (Val == 0) {
551 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
552 I = ForwardRefVals.find(Name);
553 if (I != ForwardRefVals.end())
554 Val = I->second.first;
557 // If we have the value in the symbol table or fwd-ref table, return it.
558 if (Val) {
559 if (Val->getType() == Ty) return Val;
560 Error(Loc, "'@" + Name + "' defined with type '" +
561 Val->getType()->getDescription() + "'");
562 return 0;
565 // Otherwise, create a new forward reference for this value and remember it.
566 GlobalValue *FwdVal;
567 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
568 // Function types can return opaque but functions can't.
569 if (isa<OpaqueType>(FT->getReturnType())) {
570 Error(Loc, "function may not return opaque type");
571 return 0;
574 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
575 } else {
576 FwdVal = new GlobalVariable(PTy->getElementType(), false,
577 GlobalValue::ExternalWeakLinkage, 0, Name, M);
580 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
581 return FwdVal;
584 GlobalValue *LLParser::GetGlobalVal(unsigned ID, const Type *Ty, LocTy Loc) {
585 const PointerType *PTy = dyn_cast<PointerType>(Ty);
586 if (PTy == 0) {
587 Error(Loc, "global variable reference must have pointer type");
588 return 0;
591 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
593 // If this is a forward reference for the value, see if we already created a
594 // forward ref record.
595 if (Val == 0) {
596 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
597 I = ForwardRefValIDs.find(ID);
598 if (I != ForwardRefValIDs.end())
599 Val = I->second.first;
602 // If we have the value in the symbol table or fwd-ref table, return it.
603 if (Val) {
604 if (Val->getType() == Ty) return Val;
605 Error(Loc, "'@" + utostr(ID) + "' defined with type '" +
606 Val->getType()->getDescription() + "'");
607 return 0;
610 // Otherwise, create a new forward reference for this value and remember it.
611 GlobalValue *FwdVal;
612 if (const FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType())) {
613 // Function types can return opaque but functions can't.
614 if (isa<OpaqueType>(FT->getReturnType())) {
615 Error(Loc, "function may not return opaque type");
616 return 0;
618 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
619 } else {
620 FwdVal = new GlobalVariable(PTy->getElementType(), false,
621 GlobalValue::ExternalWeakLinkage, 0, "", M);
624 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
625 return FwdVal;
629 //===----------------------------------------------------------------------===//
630 // Helper Routines.
631 //===----------------------------------------------------------------------===//
633 /// ParseToken - If the current token has the specified kind, eat it and return
634 /// success. Otherwise, emit the specified error and return failure.
635 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
636 if (Lex.getKind() != T)
637 return TokError(ErrMsg);
638 Lex.Lex();
639 return false;
642 /// ParseStringConstant
643 /// ::= StringConstant
644 bool LLParser::ParseStringConstant(std::string &Result) {
645 if (Lex.getKind() != lltok::StringConstant)
646 return TokError("expected string constant");
647 Result = Lex.getStrVal();
648 Lex.Lex();
649 return false;
652 /// ParseUInt32
653 /// ::= uint32
654 bool LLParser::ParseUInt32(unsigned &Val) {
655 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
656 return TokError("expected integer");
657 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
658 if (Val64 != unsigned(Val64))
659 return TokError("expected 32-bit integer (too large)");
660 Val = Val64;
661 Lex.Lex();
662 return false;
666 /// ParseOptionalAddrSpace
667 /// := /*empty*/
668 /// := 'addrspace' '(' uint32 ')'
669 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
670 AddrSpace = 0;
671 if (!EatIfPresent(lltok::kw_addrspace))
672 return false;
673 return ParseToken(lltok::lparen, "expected '(' in address space") ||
674 ParseUInt32(AddrSpace) ||
675 ParseToken(lltok::rparen, "expected ')' in address space");
678 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
679 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
680 /// 2: function attr.
681 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
682 bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
683 Attrs = Attribute::None;
684 LocTy AttrLoc = Lex.getLoc();
686 while (1) {
687 switch (Lex.getKind()) {
688 case lltok::kw_sext:
689 case lltok::kw_zext:
690 // Treat these as signext/zeroext if they occur in the argument list after
691 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
692 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
693 // expr.
694 // FIXME: REMOVE THIS IN LLVM 3.0
695 if (AttrKind == 3) {
696 if (Lex.getKind() == lltok::kw_sext)
697 Attrs |= Attribute::SExt;
698 else
699 Attrs |= Attribute::ZExt;
700 break;
702 // FALL THROUGH.
703 default: // End of attributes.
704 if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
705 return Error(AttrLoc, "invalid use of function-only attribute");
707 if (AttrKind != 0 && AttrKind != 3 && (Attrs & Attribute::ParameterOnly))
708 return Error(AttrLoc, "invalid use of parameter-only attribute");
710 return false;
711 case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
712 case lltok::kw_signext: Attrs |= Attribute::SExt; break;
713 case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
714 case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
715 case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
716 case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
717 case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
718 case lltok::kw_nest: Attrs |= Attribute::Nest; break;
720 case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
721 case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
722 case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
723 case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
724 case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
725 case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
726 case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
727 case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
728 case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
731 case lltok::kw_align: {
732 unsigned Alignment;
733 if (ParseOptionalAlignment(Alignment))
734 return true;
735 Attrs |= Attribute::constructAlignmentFromInt(Alignment);
736 continue;
739 Lex.Lex();
743 /// ParseOptionalLinkage
744 /// ::= /*empty*/
745 /// ::= 'private'
746 /// ::= 'internal'
747 /// ::= 'weak'
748 /// ::= 'weak_odr'
749 /// ::= 'linkonce'
750 /// ::= 'linkonce_odr'
751 /// ::= 'appending'
752 /// ::= 'dllexport'
753 /// ::= 'common'
754 /// ::= 'dllimport'
755 /// ::= 'extern_weak'
756 /// ::= 'external'
757 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
758 HasLinkage = false;
759 switch (Lex.getKind()) {
760 default: Res = GlobalValue::ExternalLinkage; return false;
761 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
762 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
763 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
764 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
765 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
766 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
767 case lltok::kw_available_externally:
768 Res = GlobalValue::AvailableExternallyLinkage;
769 break;
770 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
771 case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
772 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
773 case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
774 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
775 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
777 Lex.Lex();
778 HasLinkage = true;
779 return false;
782 /// ParseOptionalVisibility
783 /// ::= /*empty*/
784 /// ::= 'default'
785 /// ::= 'hidden'
786 /// ::= 'protected'
787 ///
788 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
789 switch (Lex.getKind()) {
790 default: Res = GlobalValue::DefaultVisibility; return false;
791 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
792 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
793 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
795 Lex.Lex();
796 return false;
799 /// ParseOptionalCallingConv
800 /// ::= /*empty*/
801 /// ::= 'ccc'
802 /// ::= 'fastcc'
803 /// ::= 'coldcc'
804 /// ::= 'x86_stdcallcc'
805 /// ::= 'x86_fastcallcc'
806 /// ::= 'cc' UINT
807 ///
808 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
809 switch (Lex.getKind()) {
810 default: CC = CallingConv::C; return false;
811 case lltok::kw_ccc: CC = CallingConv::C; break;
812 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
813 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
814 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
815 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
816 case lltok::kw_cc: Lex.Lex(); return ParseUInt32(CC);
818 Lex.Lex();
819 return false;
822 /// ParseOptionalAlignment
823 /// ::= /* empty */
824 /// ::= 'align' 4
825 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
826 Alignment = 0;
827 if (!EatIfPresent(lltok::kw_align))
828 return false;
829 LocTy AlignLoc = Lex.getLoc();
830 if (ParseUInt32(Alignment)) return true;
831 if (!isPowerOf2_32(Alignment))
832 return Error(AlignLoc, "alignment is not a power of two");
833 return false;
836 /// ParseOptionalCommaAlignment
837 /// ::= /* empty */
838 /// ::= ',' 'align' 4
839 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment) {
840 Alignment = 0;
841 if (!EatIfPresent(lltok::comma))
842 return false;
843 return ParseToken(lltok::kw_align, "expected 'align'") ||
844 ParseUInt32(Alignment);
847 /// ParseIndexList
848 /// ::= (',' uint32)+
849 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices) {
850 if (Lex.getKind() != lltok::comma)
851 return TokError("expected ',' as start of index list");
853 while (EatIfPresent(lltok::comma)) {
854 unsigned Idx;
855 if (ParseUInt32(Idx)) return true;
856 Indices.push_back(Idx);
859 return false;
862 //===----------------------------------------------------------------------===//
863 // Type Parsing.
864 //===----------------------------------------------------------------------===//
866 /// ParseType - Parse and resolve a full type.
867 bool LLParser::ParseType(PATypeHolder &Result, bool AllowVoid) {
868 LocTy TypeLoc = Lex.getLoc();
869 if (ParseTypeRec(Result)) return true;
871 // Verify no unresolved uprefs.
872 if (!UpRefs.empty())
873 return Error(UpRefs.back().Loc, "invalid unresolved type up reference");
875 if (!AllowVoid && Result.get() == Type::VoidTy)
876 return Error(TypeLoc, "void type only allowed for function results");
878 return false;
881 /// HandleUpRefs - Every time we finish a new layer of types, this function is
882 /// called. It loops through the UpRefs vector, which is a list of the
883 /// currently active types. For each type, if the up-reference is contained in
884 /// the newly completed type, we decrement the level count. When the level
885 /// count reaches zero, the up-referenced type is the type that is passed in:
886 /// thus we can complete the cycle.
888 PATypeHolder LLParser::HandleUpRefs(const Type *ty) {
889 // If Ty isn't abstract, or if there are no up-references in it, then there is
890 // nothing to resolve here.
891 if (!ty->isAbstract() || UpRefs.empty()) return ty;
893 PATypeHolder Ty(ty);
894 #if 0
895 errs() << "Type '" << Ty->getDescription()
896 << "' newly formed. Resolving upreferences.\n"
897 << UpRefs.size() << " upreferences active!\n";
898 #endif
900 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
901 // to zero), we resolve them all together before we resolve them to Ty. At
902 // the end of the loop, if there is anything to resolve to Ty, it will be in
903 // this variable.
904 OpaqueType *TypeToResolve = 0;
906 for (unsigned i = 0; i != UpRefs.size(); ++i) {
907 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
908 bool ContainsType =
909 std::find(Ty->subtype_begin(), Ty->subtype_end(),
910 UpRefs[i].LastContainedTy) != Ty->subtype_end();
912 #if 0
913 errs() << " UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
914 << UpRefs[i].LastContainedTy->getDescription() << ") = "
915 << (ContainsType ? "true" : "false")
916 << " level=" << UpRefs[i].NestingLevel << "\n";
917 #endif
918 if (!ContainsType)
919 continue;
921 // Decrement level of upreference
922 unsigned Level = --UpRefs[i].NestingLevel;
923 UpRefs[i].LastContainedTy = Ty;
925 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
926 if (Level != 0)
927 continue;
929 #if 0
930 errs() << " * Resolving upreference for " << UpRefs[i].UpRefTy << "\n";
931 #endif
932 if (!TypeToResolve)
933 TypeToResolve = UpRefs[i].UpRefTy;
934 else
935 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
936 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list.
937 --i; // Do not skip the next element.
940 if (TypeToResolve)
941 TypeToResolve->refineAbstractTypeTo(Ty);
943 return Ty;
947 /// ParseTypeRec - The recursive function used to process the internal
948 /// implementation details of types.
949 bool LLParser::ParseTypeRec(PATypeHolder &Result) {
950 switch (Lex.getKind()) {
951 default:
952 return TokError("expected type");
953 case lltok::Type:
954 // TypeRec ::= 'float' | 'void' (etc)
955 Result = Lex.getTyVal();
956 Lex.Lex();
957 break;
958 case lltok::kw_opaque:
959 // TypeRec ::= 'opaque'
960 Result = OpaqueType::get();
961 Lex.Lex();
962 break;
963 case lltok::lbrace:
964 // TypeRec ::= '{' ... '}'
965 if (ParseStructType(Result, false))
966 return true;
967 break;
968 case lltok::lsquare:
969 // TypeRec ::= '[' ... ']'
970 Lex.Lex(); // eat the lsquare.
971 if (ParseArrayVectorType(Result, false))
972 return true;
973 break;
974 case lltok::less: // Either vector or packed struct.
975 // TypeRec ::= '<' ... '>'
976 Lex.Lex();
977 if (Lex.getKind() == lltok::lbrace) {
978 if (ParseStructType(Result, true) ||
979 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
980 return true;
981 } else if (ParseArrayVectorType(Result, true))
982 return true;
983 break;
984 case lltok::LocalVar:
985 case lltok::StringConstant: // FIXME: REMOVE IN LLVM 3.0
986 // TypeRec ::= %foo
987 if (const Type *T = M->getTypeByName(Lex.getStrVal())) {
988 Result = T;
989 } else {
990 Result = OpaqueType::get();
991 ForwardRefTypes.insert(std::make_pair(Lex.getStrVal(),
992 std::make_pair(Result,
993 Lex.getLoc())));
994 M->addTypeName(Lex.getStrVal(), Result.get());
996 Lex.Lex();
997 break;
999 case lltok::LocalVarID:
1000 // TypeRec ::= %4
1001 if (Lex.getUIntVal() < NumberedTypes.size())
1002 Result = NumberedTypes[Lex.getUIntVal()];
1003 else {
1004 std::map<unsigned, std::pair<PATypeHolder, LocTy> >::iterator
1005 I = ForwardRefTypeIDs.find(Lex.getUIntVal());
1006 if (I != ForwardRefTypeIDs.end())
1007 Result = I->second.first;
1008 else {
1009 Result = OpaqueType::get();
1010 ForwardRefTypeIDs.insert(std::make_pair(Lex.getUIntVal(),
1011 std::make_pair(Result,
1012 Lex.getLoc())));
1015 Lex.Lex();
1016 break;
1017 case lltok::backslash: {
1018 // TypeRec ::= '\' 4
1019 Lex.Lex();
1020 unsigned Val;
1021 if (ParseUInt32(Val)) return true;
1022 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder.
1023 UpRefs.push_back(UpRefRecord(Lex.getLoc(), Val, OT));
1024 Result = OT;
1025 break;
1029 // Parse the type suffixes.
1030 while (1) {
1031 switch (Lex.getKind()) {
1032 // End of type.
1033 default: return false;
1035 // TypeRec ::= TypeRec '*'
1036 case lltok::star:
1037 if (Result.get() == Type::LabelTy)
1038 return TokError("basic block pointers are invalid");
1039 if (Result.get() == Type::VoidTy)
1040 return TokError("pointers to void are invalid; use i8* instead");
1041 Result = HandleUpRefs(PointerType::getUnqual(Result.get()));
1042 Lex.Lex();
1043 break;
1045 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1046 case lltok::kw_addrspace: {
1047 if (Result.get() == Type::LabelTy)
1048 return TokError("basic block pointers are invalid");
1049 if (Result.get() == Type::VoidTy)
1050 return TokError("pointers to void are invalid; use i8* instead");
1051 unsigned AddrSpace;
1052 if (ParseOptionalAddrSpace(AddrSpace) ||
1053 ParseToken(lltok::star, "expected '*' in address space"))
1054 return true;
1056 Result = HandleUpRefs(PointerType::get(Result.get(), AddrSpace));
1057 break;
1060 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1061 case lltok::lparen:
1062 if (ParseFunctionType(Result))
1063 return true;
1064 break;
1069 /// ParseParameterList
1070 /// ::= '(' ')'
1071 /// ::= '(' Arg (',' Arg)* ')'
1072 /// Arg
1073 /// ::= Type OptionalAttributes Value OptionalAttributes
1074 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1075 PerFunctionState &PFS) {
1076 if (ParseToken(lltok::lparen, "expected '(' in call"))
1077 return true;
1079 while (Lex.getKind() != lltok::rparen) {
1080 // If this isn't the first argument, we need a comma.
1081 if (!ArgList.empty() &&
1082 ParseToken(lltok::comma, "expected ',' in argument list"))
1083 return true;
1085 // Parse the argument.
1086 LocTy ArgLoc;
1087 PATypeHolder ArgTy(Type::VoidTy);
1088 unsigned ArgAttrs1, ArgAttrs2;
1089 Value *V;
1090 if (ParseType(ArgTy, ArgLoc) ||
1091 ParseOptionalAttrs(ArgAttrs1, 0) ||
1092 ParseValue(ArgTy, V, PFS) ||
1093 // FIXME: Should not allow attributes after the argument, remove this in
1094 // LLVM 3.0.
1095 ParseOptionalAttrs(ArgAttrs2, 3))
1096 return true;
1097 ArgList.push_back(ParamInfo(ArgLoc, V, ArgAttrs1|ArgAttrs2));
1100 Lex.Lex(); // Lex the ')'.
1101 return false;
1106 /// ParseArgumentList - Parse the argument list for a function type or function
1107 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1108 /// ::= '(' ArgTypeListI ')'
1109 /// ArgTypeListI
1110 /// ::= /*empty*/
1111 /// ::= '...'
1112 /// ::= ArgTypeList ',' '...'
1113 /// ::= ArgType (',' ArgType)*
1115 bool LLParser::ParseArgumentList(std::vector<ArgInfo> &ArgList,
1116 bool &isVarArg, bool inType) {
1117 isVarArg = false;
1118 assert(Lex.getKind() == lltok::lparen);
1119 Lex.Lex(); // eat the (.
1121 if (Lex.getKind() == lltok::rparen) {
1122 // empty
1123 } else if (Lex.getKind() == lltok::dotdotdot) {
1124 isVarArg = true;
1125 Lex.Lex();
1126 } else {
1127 LocTy TypeLoc = Lex.getLoc();
1128 PATypeHolder ArgTy(Type::VoidTy);
1129 unsigned Attrs;
1130 std::string Name;
1132 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1133 // types (such as a function returning a pointer to itself). If parsing a
1134 // function prototype, we require fully resolved types.
1135 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1136 ParseOptionalAttrs(Attrs, 0)) return true;
1138 if (ArgTy == Type::VoidTy)
1139 return Error(TypeLoc, "argument can not have void type");
1141 if (Lex.getKind() == lltok::LocalVar ||
1142 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1143 Name = Lex.getStrVal();
1144 Lex.Lex();
1147 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1148 return Error(TypeLoc, "invalid type for function argument");
1150 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1152 while (EatIfPresent(lltok::comma)) {
1153 // Handle ... at end of arg list.
1154 if (EatIfPresent(lltok::dotdotdot)) {
1155 isVarArg = true;
1156 break;
1159 // Otherwise must be an argument type.
1160 TypeLoc = Lex.getLoc();
1161 if ((inType ? ParseTypeRec(ArgTy) : ParseType(ArgTy)) ||
1162 ParseOptionalAttrs(Attrs, 0)) return true;
1164 if (ArgTy == Type::VoidTy)
1165 return Error(TypeLoc, "argument can not have void type");
1167 if (Lex.getKind() == lltok::LocalVar ||
1168 Lex.getKind() == lltok::StringConstant) { // FIXME: REMOVE IN LLVM 3.0
1169 Name = Lex.getStrVal();
1170 Lex.Lex();
1171 } else {
1172 Name = "";
1175 if (!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy))
1176 return Error(TypeLoc, "invalid type for function argument");
1178 ArgList.push_back(ArgInfo(TypeLoc, ArgTy, Attrs, Name));
1182 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1185 /// ParseFunctionType
1186 /// ::= Type ArgumentList OptionalAttrs
1187 bool LLParser::ParseFunctionType(PATypeHolder &Result) {
1188 assert(Lex.getKind() == lltok::lparen);
1190 if (!FunctionType::isValidReturnType(Result))
1191 return TokError("invalid function return type");
1193 std::vector<ArgInfo> ArgList;
1194 bool isVarArg;
1195 unsigned Attrs;
1196 if (ParseArgumentList(ArgList, isVarArg, true) ||
1197 // FIXME: Allow, but ignore attributes on function types!
1198 // FIXME: Remove in LLVM 3.0
1199 ParseOptionalAttrs(Attrs, 2))
1200 return true;
1202 // Reject names on the arguments lists.
1203 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1204 if (!ArgList[i].Name.empty())
1205 return Error(ArgList[i].Loc, "argument name invalid in function type");
1206 if (!ArgList[i].Attrs != 0) {
1207 // Allow but ignore attributes on function types; this permits
1208 // auto-upgrade.
1209 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1213 std::vector<const Type*> ArgListTy;
1214 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1215 ArgListTy.push_back(ArgList[i].Type);
1217 Result = HandleUpRefs(FunctionType::get(Result.get(), ArgListTy, isVarArg));
1218 return false;
1221 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1222 /// TypeRec
1223 /// ::= '{' '}'
1224 /// ::= '{' TypeRec (',' TypeRec)* '}'
1225 /// ::= '<' '{' '}' '>'
1226 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1227 bool LLParser::ParseStructType(PATypeHolder &Result, bool Packed) {
1228 assert(Lex.getKind() == lltok::lbrace);
1229 Lex.Lex(); // Consume the '{'
1231 if (EatIfPresent(lltok::rbrace)) {
1232 Result = StructType::get(std::vector<const Type*>(), Packed);
1233 return false;
1236 std::vector<PATypeHolder> ParamsList;
1237 LocTy EltTyLoc = Lex.getLoc();
1238 if (ParseTypeRec(Result)) return true;
1239 ParamsList.push_back(Result);
1241 if (Result == Type::VoidTy)
1242 return Error(EltTyLoc, "struct element can not have void type");
1244 while (EatIfPresent(lltok::comma)) {
1245 EltTyLoc = Lex.getLoc();
1246 if (ParseTypeRec(Result)) return true;
1248 if (Result == Type::VoidTy)
1249 return Error(EltTyLoc, "struct element can not have void type");
1251 ParamsList.push_back(Result);
1254 if (ParseToken(lltok::rbrace, "expected '}' at end of struct"))
1255 return true;
1257 std::vector<const Type*> ParamsListTy;
1258 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
1259 ParamsListTy.push_back(ParamsList[i].get());
1260 Result = HandleUpRefs(StructType::get(ParamsListTy, Packed));
1261 return false;
1264 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1265 /// token has already been consumed.
1266 /// TypeRec
1267 /// ::= '[' APSINTVAL 'x' Types ']'
1268 /// ::= '<' APSINTVAL 'x' Types '>'
1269 bool LLParser::ParseArrayVectorType(PATypeHolder &Result, bool isVector) {
1270 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1271 Lex.getAPSIntVal().getBitWidth() > 64)
1272 return TokError("expected number in address space");
1274 LocTy SizeLoc = Lex.getLoc();
1275 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1276 Lex.Lex();
1278 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1279 return true;
1281 LocTy TypeLoc = Lex.getLoc();
1282 PATypeHolder EltTy(Type::VoidTy);
1283 if (ParseTypeRec(EltTy)) return true;
1285 if (EltTy == Type::VoidTy)
1286 return Error(TypeLoc, "array and vector element type cannot be void");
1288 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1289 "expected end of sequential type"))
1290 return true;
1292 if (isVector) {
1293 if (Size == 0)
1294 return Error(SizeLoc, "zero element vector is illegal");
1295 if ((unsigned)Size != Size)
1296 return Error(SizeLoc, "size too large for vector");
1297 if (!EltTy->isFloatingPoint() && !EltTy->isInteger())
1298 return Error(TypeLoc, "vector element type must be fp or integer");
1299 Result = VectorType::get(EltTy, unsigned(Size));
1300 } else {
1301 if (!EltTy->isFirstClassType() && !isa<OpaqueType>(EltTy))
1302 return Error(TypeLoc, "invalid array element type");
1303 Result = HandleUpRefs(ArrayType::get(EltTy, Size));
1305 return false;
1308 //===----------------------------------------------------------------------===//
1309 // Function Semantic Analysis.
1310 //===----------------------------------------------------------------------===//
1312 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f)
1313 : P(p), F(f) {
1315 // Insert unnamed arguments into the NumberedVals list.
1316 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1317 AI != E; ++AI)
1318 if (!AI->hasName())
1319 NumberedVals.push_back(AI);
1322 LLParser::PerFunctionState::~PerFunctionState() {
1323 // If there were any forward referenced non-basicblock values, delete them.
1324 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
1325 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
1326 if (!isa<BasicBlock>(I->second.first)) {
1327 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1328 ->getType()));
1329 delete I->second.first;
1330 I->second.first = 0;
1333 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1334 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
1335 if (!isa<BasicBlock>(I->second.first)) {
1336 I->second.first->replaceAllUsesWith(UndefValue::get(I->second.first
1337 ->getType()));
1338 delete I->second.first;
1339 I->second.first = 0;
1343 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1344 if (!ForwardRefVals.empty())
1345 return P.Error(ForwardRefVals.begin()->second.second,
1346 "use of undefined value '%" + ForwardRefVals.begin()->first +
1347 "'");
1348 if (!ForwardRefValIDs.empty())
1349 return P.Error(ForwardRefValIDs.begin()->second.second,
1350 "use of undefined value '%" +
1351 utostr(ForwardRefValIDs.begin()->first) + "'");
1352 return false;
1356 /// GetVal - Get a value with the specified name or ID, creating a
1357 /// forward reference record if needed. This can return null if the value
1358 /// exists but does not have the right type.
1359 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
1360 const Type *Ty, LocTy Loc) {
1361 // Look this name up in the normal function symbol table.
1362 Value *Val = F.getValueSymbolTable().lookup(Name);
1364 // If this is a forward reference for the value, see if we already created a
1365 // forward ref record.
1366 if (Val == 0) {
1367 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1368 I = ForwardRefVals.find(Name);
1369 if (I != ForwardRefVals.end())
1370 Val = I->second.first;
1373 // If we have the value in the symbol table or fwd-ref table, return it.
1374 if (Val) {
1375 if (Val->getType() == Ty) return Val;
1376 if (Ty == Type::LabelTy)
1377 P.Error(Loc, "'%" + Name + "' is not a basic block");
1378 else
1379 P.Error(Loc, "'%" + Name + "' defined with type '" +
1380 Val->getType()->getDescription() + "'");
1381 return 0;
1384 // Don't make placeholders with invalid type.
1385 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1386 P.Error(Loc, "invalid use of a non-first-class type");
1387 return 0;
1390 // Otherwise, create a new forward reference for this value and remember it.
1391 Value *FwdVal;
1392 if (Ty == Type::LabelTy)
1393 FwdVal = BasicBlock::Create(Name, &F);
1394 else
1395 FwdVal = new Argument(Ty, Name);
1397 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1398 return FwdVal;
1401 Value *LLParser::PerFunctionState::GetVal(unsigned ID, const Type *Ty,
1402 LocTy Loc) {
1403 // Look this name up in the normal function symbol table.
1404 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
1406 // If this is a forward reference for the value, see if we already created a
1407 // forward ref record.
1408 if (Val == 0) {
1409 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
1410 I = ForwardRefValIDs.find(ID);
1411 if (I != ForwardRefValIDs.end())
1412 Val = I->second.first;
1415 // If we have the value in the symbol table or fwd-ref table, return it.
1416 if (Val) {
1417 if (Val->getType() == Ty) return Val;
1418 if (Ty == Type::LabelTy)
1419 P.Error(Loc, "'%" + utostr(ID) + "' is not a basic block");
1420 else
1421 P.Error(Loc, "'%" + utostr(ID) + "' defined with type '" +
1422 Val->getType()->getDescription() + "'");
1423 return 0;
1426 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty) && Ty != Type::LabelTy) {
1427 P.Error(Loc, "invalid use of a non-first-class type");
1428 return 0;
1431 // Otherwise, create a new forward reference for this value and remember it.
1432 Value *FwdVal;
1433 if (Ty == Type::LabelTy)
1434 FwdVal = BasicBlock::Create("", &F);
1435 else
1436 FwdVal = new Argument(Ty);
1438 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1439 return FwdVal;
1442 /// SetInstName - After an instruction is parsed and inserted into its
1443 /// basic block, this installs its name.
1444 bool LLParser::PerFunctionState::SetInstName(int NameID,
1445 const std::string &NameStr,
1446 LocTy NameLoc, Instruction *Inst) {
1447 // If this instruction has void type, it cannot have a name or ID specified.
1448 if (Inst->getType() == Type::VoidTy) {
1449 if (NameID != -1 || !NameStr.empty())
1450 return P.Error(NameLoc, "instructions returning void cannot have a name");
1451 return false;
1454 // If this was a numbered instruction, verify that the instruction is the
1455 // expected value and resolve any forward references.
1456 if (NameStr.empty()) {
1457 // If neither a name nor an ID was specified, just use the next ID.
1458 if (NameID == -1)
1459 NameID = NumberedVals.size();
1461 if (unsigned(NameID) != NumberedVals.size())
1462 return P.Error(NameLoc, "instruction expected to be numbered '%" +
1463 utostr(NumberedVals.size()) + "'");
1465 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
1466 ForwardRefValIDs.find(NameID);
1467 if (FI != ForwardRefValIDs.end()) {
1468 if (FI->second.first->getType() != Inst->getType())
1469 return P.Error(NameLoc, "instruction forward referenced with type '" +
1470 FI->second.first->getType()->getDescription() + "'");
1471 FI->second.first->replaceAllUsesWith(Inst);
1472 ForwardRefValIDs.erase(FI);
1475 NumberedVals.push_back(Inst);
1476 return false;
1479 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1480 std::map<std::string, std::pair<Value*, LocTy> >::iterator
1481 FI = ForwardRefVals.find(NameStr);
1482 if (FI != ForwardRefVals.end()) {
1483 if (FI->second.first->getType() != Inst->getType())
1484 return P.Error(NameLoc, "instruction forward referenced with type '" +
1485 FI->second.first->getType()->getDescription() + "'");
1486 FI->second.first->replaceAllUsesWith(Inst);
1487 ForwardRefVals.erase(FI);
1490 // Set the name on the instruction.
1491 Inst->setName(NameStr);
1493 if (Inst->getNameStr() != NameStr)
1494 return P.Error(NameLoc, "multiple definition of local value named '" +
1495 NameStr + "'");
1496 return false;
1499 /// GetBB - Get a basic block with the specified name or ID, creating a
1500 /// forward reference record if needed.
1501 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
1502 LocTy Loc) {
1503 return cast_or_null<BasicBlock>(GetVal(Name, Type::LabelTy, Loc));
1506 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
1507 return cast_or_null<BasicBlock>(GetVal(ID, Type::LabelTy, Loc));
1510 /// DefineBB - Define the specified basic block, which is either named or
1511 /// unnamed. If there is an error, this returns null otherwise it returns
1512 /// the block being defined.
1513 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
1514 LocTy Loc) {
1515 BasicBlock *BB;
1516 if (Name.empty())
1517 BB = GetBB(NumberedVals.size(), Loc);
1518 else
1519 BB = GetBB(Name, Loc);
1520 if (BB == 0) return 0; // Already diagnosed error.
1522 // Move the block to the end of the function. Forward ref'd blocks are
1523 // inserted wherever they happen to be referenced.
1524 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
1526 // Remove the block from forward ref sets.
1527 if (Name.empty()) {
1528 ForwardRefValIDs.erase(NumberedVals.size());
1529 NumberedVals.push_back(BB);
1530 } else {
1531 // BB forward references are already in the function symbol table.
1532 ForwardRefVals.erase(Name);
1535 return BB;
1538 //===----------------------------------------------------------------------===//
1539 // Constants.
1540 //===----------------------------------------------------------------------===//
1542 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1543 /// type implied. For example, if we parse "4" we don't know what integer type
1544 /// it has. The value will later be combined with its type and checked for
1545 /// sanity.
1546 bool LLParser::ParseValID(ValID &ID) {
1547 ID.Loc = Lex.getLoc();
1548 switch (Lex.getKind()) {
1549 default: return TokError("expected value token");
1550 case lltok::GlobalID: // @42
1551 ID.UIntVal = Lex.getUIntVal();
1552 ID.Kind = ValID::t_GlobalID;
1553 break;
1554 case lltok::GlobalVar: // @foo
1555 ID.StrVal = Lex.getStrVal();
1556 ID.Kind = ValID::t_GlobalName;
1557 break;
1558 case lltok::LocalVarID: // %42
1559 ID.UIntVal = Lex.getUIntVal();
1560 ID.Kind = ValID::t_LocalID;
1561 break;
1562 case lltok::LocalVar: // %foo
1563 case lltok::StringConstant: // "foo" - FIXME: REMOVE IN LLVM 3.0
1564 ID.StrVal = Lex.getStrVal();
1565 ID.Kind = ValID::t_LocalName;
1566 break;
1567 case lltok::Metadata: { // !{...} MDNode, !"foo" MDString
1568 ID.Kind = ValID::t_Constant;
1569 Lex.Lex();
1570 if (Lex.getKind() == lltok::lbrace) {
1571 // MDNode:
1572 // ::= '!' '{' TypeAndValue (',' TypeAndValue)* '}'
1573 SmallVector<Constant*, 16> Elts;
1574 if (ParseMDNodeVector(Elts) ||
1575 ParseToken(lltok::rbrace, "expected end of metadata node"))
1576 return true;
1578 ID.ConstantVal = MDNode::get(&Elts[0], Elts.size());
1579 return false;
1582 // MDString:
1583 // ::= '!' STRINGCONSTANT
1584 std::string Str;
1585 if (ParseStringConstant(Str)) return true;
1587 ID.ConstantVal = MDString::get(Str.data(), Str.data() + Str.size());
1588 return false;
1590 case lltok::APSInt:
1591 ID.APSIntVal = Lex.getAPSIntVal();
1592 ID.Kind = ValID::t_APSInt;
1593 break;
1594 case lltok::APFloat:
1595 ID.APFloatVal = Lex.getAPFloatVal();
1596 ID.Kind = ValID::t_APFloat;
1597 break;
1598 case lltok::kw_true:
1599 ID.ConstantVal = ConstantInt::getTrue();
1600 ID.Kind = ValID::t_Constant;
1601 break;
1602 case lltok::kw_false:
1603 ID.ConstantVal = ConstantInt::getFalse();
1604 ID.Kind = ValID::t_Constant;
1605 break;
1606 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
1607 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
1608 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
1610 case lltok::lbrace: {
1611 // ValID ::= '{' ConstVector '}'
1612 Lex.Lex();
1613 SmallVector<Constant*, 16> Elts;
1614 if (ParseGlobalValueVector(Elts) ||
1615 ParseToken(lltok::rbrace, "expected end of struct constant"))
1616 return true;
1618 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), false);
1619 ID.Kind = ValID::t_Constant;
1620 return false;
1622 case lltok::less: {
1623 // ValID ::= '<' ConstVector '>' --> Vector.
1624 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1625 Lex.Lex();
1626 bool isPackedStruct = EatIfPresent(lltok::lbrace);
1628 SmallVector<Constant*, 16> Elts;
1629 LocTy FirstEltLoc = Lex.getLoc();
1630 if (ParseGlobalValueVector(Elts) ||
1631 (isPackedStruct &&
1632 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
1633 ParseToken(lltok::greater, "expected end of constant"))
1634 return true;
1636 if (isPackedStruct) {
1637 ID.ConstantVal = ConstantStruct::get(&Elts[0], Elts.size(), true);
1638 ID.Kind = ValID::t_Constant;
1639 return false;
1642 if (Elts.empty())
1643 return Error(ID.Loc, "constant vector must not be empty");
1645 if (!Elts[0]->getType()->isInteger() &&
1646 !Elts[0]->getType()->isFloatingPoint())
1647 return Error(FirstEltLoc,
1648 "vector elements must have integer or floating point type");
1650 // Verify that all the vector elements have the same type.
1651 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
1652 if (Elts[i]->getType() != Elts[0]->getType())
1653 return Error(FirstEltLoc,
1654 "vector element #" + utostr(i) +
1655 " is not of type '" + Elts[0]->getType()->getDescription());
1657 ID.ConstantVal = ConstantVector::get(&Elts[0], Elts.size());
1658 ID.Kind = ValID::t_Constant;
1659 return false;
1661 case lltok::lsquare: { // Array Constant
1662 Lex.Lex();
1663 SmallVector<Constant*, 16> Elts;
1664 LocTy FirstEltLoc = Lex.getLoc();
1665 if (ParseGlobalValueVector(Elts) ||
1666 ParseToken(lltok::rsquare, "expected end of array constant"))
1667 return true;
1669 // Handle empty element.
1670 if (Elts.empty()) {
1671 // Use undef instead of an array because it's inconvenient to determine
1672 // the element type at this point, there being no elements to examine.
1673 ID.Kind = ValID::t_EmptyArray;
1674 return false;
1677 if (!Elts[0]->getType()->isFirstClassType())
1678 return Error(FirstEltLoc, "invalid array element type: " +
1679 Elts[0]->getType()->getDescription());
1681 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
1683 // Verify all elements are correct type!
1684 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
1685 if (Elts[i]->getType() != Elts[0]->getType())
1686 return Error(FirstEltLoc,
1687 "array element #" + utostr(i) +
1688 " is not of type '" +Elts[0]->getType()->getDescription());
1691 ID.ConstantVal = ConstantArray::get(ATy, &Elts[0], Elts.size());
1692 ID.Kind = ValID::t_Constant;
1693 return false;
1695 case lltok::kw_c: // c "foo"
1696 Lex.Lex();
1697 ID.ConstantVal = ConstantArray::get(Lex.getStrVal(), false);
1698 if (ParseToken(lltok::StringConstant, "expected string")) return true;
1699 ID.Kind = ValID::t_Constant;
1700 return false;
1702 case lltok::kw_asm: {
1703 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1704 bool HasSideEffect;
1705 Lex.Lex();
1706 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
1707 ParseStringConstant(ID.StrVal) ||
1708 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
1709 ParseToken(lltok::StringConstant, "expected constraint string"))
1710 return true;
1711 ID.StrVal2 = Lex.getStrVal();
1712 ID.UIntVal = HasSideEffect;
1713 ID.Kind = ValID::t_InlineAsm;
1714 return false;
1717 case lltok::kw_trunc:
1718 case lltok::kw_zext:
1719 case lltok::kw_sext:
1720 case lltok::kw_fptrunc:
1721 case lltok::kw_fpext:
1722 case lltok::kw_bitcast:
1723 case lltok::kw_uitofp:
1724 case lltok::kw_sitofp:
1725 case lltok::kw_fptoui:
1726 case lltok::kw_fptosi:
1727 case lltok::kw_inttoptr:
1728 case lltok::kw_ptrtoint: {
1729 unsigned Opc = Lex.getUIntVal();
1730 PATypeHolder DestTy(Type::VoidTy);
1731 Constant *SrcVal;
1732 Lex.Lex();
1733 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
1734 ParseGlobalTypeAndValue(SrcVal) ||
1735 ParseToken(lltok::kw_to, "expected 'to' int constantexpr cast") ||
1736 ParseType(DestTy) ||
1737 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
1738 return true;
1739 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
1740 return Error(ID.Loc, "invalid cast opcode for cast from '" +
1741 SrcVal->getType()->getDescription() + "' to '" +
1742 DestTy->getDescription() + "'");
1743 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc, SrcVal,
1744 DestTy);
1745 ID.Kind = ValID::t_Constant;
1746 return false;
1748 case lltok::kw_extractvalue: {
1749 Lex.Lex();
1750 Constant *Val;
1751 SmallVector<unsigned, 4> Indices;
1752 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
1753 ParseGlobalTypeAndValue(Val) ||
1754 ParseIndexList(Indices) ||
1755 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
1756 return true;
1757 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
1758 return Error(ID.Loc, "extractvalue operand must be array or struct");
1759 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
1760 Indices.end()))
1761 return Error(ID.Loc, "invalid indices for extractvalue");
1762 ID.ConstantVal = ConstantExpr::getExtractValue(Val,
1763 &Indices[0], Indices.size());
1764 ID.Kind = ValID::t_Constant;
1765 return false;
1767 case lltok::kw_insertvalue: {
1768 Lex.Lex();
1769 Constant *Val0, *Val1;
1770 SmallVector<unsigned, 4> Indices;
1771 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
1772 ParseGlobalTypeAndValue(Val0) ||
1773 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
1774 ParseGlobalTypeAndValue(Val1) ||
1775 ParseIndexList(Indices) ||
1776 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
1777 return true;
1778 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
1779 return Error(ID.Loc, "extractvalue operand must be array or struct");
1780 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
1781 Indices.end()))
1782 return Error(ID.Loc, "invalid indices for insertvalue");
1783 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1,
1784 &Indices[0], Indices.size());
1785 ID.Kind = ValID::t_Constant;
1786 return false;
1788 case lltok::kw_icmp:
1789 case lltok::kw_fcmp:
1790 case lltok::kw_vicmp:
1791 case lltok::kw_vfcmp: {
1792 unsigned PredVal, Opc = Lex.getUIntVal();
1793 Constant *Val0, *Val1;
1794 Lex.Lex();
1795 if (ParseCmpPredicate(PredVal, Opc) ||
1796 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
1797 ParseGlobalTypeAndValue(Val0) ||
1798 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
1799 ParseGlobalTypeAndValue(Val1) ||
1800 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
1801 return true;
1803 if (Val0->getType() != Val1->getType())
1804 return Error(ID.Loc, "compare operands must have the same type");
1806 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
1808 if (Opc == Instruction::FCmp) {
1809 if (!Val0->getType()->isFPOrFPVector())
1810 return Error(ID.Loc, "fcmp requires floating point operands");
1811 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
1812 } else if (Opc == Instruction::ICmp) {
1813 if (!Val0->getType()->isIntOrIntVector() &&
1814 !isa<PointerType>(Val0->getType()))
1815 return Error(ID.Loc, "icmp requires pointer or integer operands");
1816 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
1817 } else if (Opc == Instruction::VFCmp) {
1818 // FIXME: REMOVE VFCMP Support
1819 if (!Val0->getType()->isFPOrFPVector() ||
1820 !isa<VectorType>(Val0->getType()))
1821 return Error(ID.Loc, "vfcmp requires vector floating point operands");
1822 ID.ConstantVal = ConstantExpr::getVFCmp(Pred, Val0, Val1);
1823 } else if (Opc == Instruction::VICmp) {
1824 // FIXME: REMOVE VICMP Support
1825 if (!Val0->getType()->isIntOrIntVector() ||
1826 !isa<VectorType>(Val0->getType()))
1827 return Error(ID.Loc, "vicmp requires vector floating point operands");
1828 ID.ConstantVal = ConstantExpr::getVICmp(Pred, Val0, Val1);
1830 ID.Kind = ValID::t_Constant;
1831 return false;
1834 // Binary Operators.
1835 case lltok::kw_add:
1836 case lltok::kw_sub:
1837 case lltok::kw_mul:
1838 case lltok::kw_udiv:
1839 case lltok::kw_sdiv:
1840 case lltok::kw_fdiv:
1841 case lltok::kw_urem:
1842 case lltok::kw_srem:
1843 case lltok::kw_frem: {
1844 unsigned Opc = Lex.getUIntVal();
1845 Constant *Val0, *Val1;
1846 Lex.Lex();
1847 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
1848 ParseGlobalTypeAndValue(Val0) ||
1849 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
1850 ParseGlobalTypeAndValue(Val1) ||
1851 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
1852 return true;
1853 if (Val0->getType() != Val1->getType())
1854 return Error(ID.Loc, "operands of constexpr must have same type");
1855 if (!Val0->getType()->isIntOrIntVector() &&
1856 !Val0->getType()->isFPOrFPVector())
1857 return Error(ID.Loc,"constexpr requires integer, fp, or vector operands");
1858 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1859 ID.Kind = ValID::t_Constant;
1860 return false;
1863 // Logical Operations
1864 case lltok::kw_shl:
1865 case lltok::kw_lshr:
1866 case lltok::kw_ashr:
1867 case lltok::kw_and:
1868 case lltok::kw_or:
1869 case lltok::kw_xor: {
1870 unsigned Opc = Lex.getUIntVal();
1871 Constant *Val0, *Val1;
1872 Lex.Lex();
1873 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
1874 ParseGlobalTypeAndValue(Val0) ||
1875 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
1876 ParseGlobalTypeAndValue(Val1) ||
1877 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
1878 return true;
1879 if (Val0->getType() != Val1->getType())
1880 return Error(ID.Loc, "operands of constexpr must have same type");
1881 if (!Val0->getType()->isIntOrIntVector())
1882 return Error(ID.Loc,
1883 "constexpr requires integer or integer vector operands");
1884 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
1885 ID.Kind = ValID::t_Constant;
1886 return false;
1889 case lltok::kw_getelementptr:
1890 case lltok::kw_shufflevector:
1891 case lltok::kw_insertelement:
1892 case lltok::kw_extractelement:
1893 case lltok::kw_select: {
1894 unsigned Opc = Lex.getUIntVal();
1895 SmallVector<Constant*, 16> Elts;
1896 Lex.Lex();
1897 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
1898 ParseGlobalValueVector(Elts) ||
1899 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
1900 return true;
1902 if (Opc == Instruction::GetElementPtr) {
1903 if (Elts.size() == 0 || !isa<PointerType>(Elts[0]->getType()))
1904 return Error(ID.Loc, "getelementptr requires pointer operand");
1906 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(),
1907 (Value**)&Elts[1], Elts.size()-1))
1908 return Error(ID.Loc, "invalid indices for getelementptr");
1909 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0],
1910 &Elts[1], Elts.size()-1);
1911 } else if (Opc == Instruction::Select) {
1912 if (Elts.size() != 3)
1913 return Error(ID.Loc, "expected three operands to select");
1914 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
1915 Elts[2]))
1916 return Error(ID.Loc, Reason);
1917 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
1918 } else if (Opc == Instruction::ShuffleVector) {
1919 if (Elts.size() != 3)
1920 return Error(ID.Loc, "expected three operands to shufflevector");
1921 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1922 return Error(ID.Loc, "invalid operands to shufflevector");
1923 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
1924 } else if (Opc == Instruction::ExtractElement) {
1925 if (Elts.size() != 2)
1926 return Error(ID.Loc, "expected two operands to extractelement");
1927 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
1928 return Error(ID.Loc, "invalid extractelement operands");
1929 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
1930 } else {
1931 assert(Opc == Instruction::InsertElement && "Unknown opcode");
1932 if (Elts.size() != 3)
1933 return Error(ID.Loc, "expected three operands to insertelement");
1934 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
1935 return Error(ID.Loc, "invalid insertelement operands");
1936 ID.ConstantVal = ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
1939 ID.Kind = ValID::t_Constant;
1940 return false;
1944 Lex.Lex();
1945 return false;
1948 /// ParseGlobalValue - Parse a global value with the specified type.
1949 bool LLParser::ParseGlobalValue(const Type *Ty, Constant *&V) {
1950 V = 0;
1951 ValID ID;
1952 return ParseValID(ID) ||
1953 ConvertGlobalValIDToValue(Ty, ID, V);
1956 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
1957 /// constant.
1958 bool LLParser::ConvertGlobalValIDToValue(const Type *Ty, ValID &ID,
1959 Constant *&V) {
1960 if (isa<FunctionType>(Ty))
1961 return Error(ID.Loc, "functions are not values, refer to them as pointers");
1963 switch (ID.Kind) {
1964 default: assert(0 && "Unknown ValID!");
1965 case ValID::t_LocalID:
1966 case ValID::t_LocalName:
1967 return Error(ID.Loc, "invalid use of function-local name");
1968 case ValID::t_InlineAsm:
1969 return Error(ID.Loc, "inline asm can only be an operand of call/invoke");
1970 case ValID::t_GlobalName:
1971 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
1972 return V == 0;
1973 case ValID::t_GlobalID:
1974 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
1975 return V == 0;
1976 case ValID::t_APSInt:
1977 if (!isa<IntegerType>(Ty))
1978 return Error(ID.Loc, "integer constant must have integer type");
1979 ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
1980 V = ConstantInt::get(ID.APSIntVal);
1981 return false;
1982 case ValID::t_APFloat:
1983 if (!Ty->isFloatingPoint() ||
1984 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
1985 return Error(ID.Loc, "floating point constant invalid for type");
1987 // The lexer has no type info, so builds all float and double FP constants
1988 // as double. Fix this here. Long double does not need this.
1989 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble &&
1990 Ty == Type::FloatTy) {
1991 bool Ignored;
1992 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1993 &Ignored);
1995 V = ConstantFP::get(ID.APFloatVal);
1997 if (V->getType() != Ty)
1998 return Error(ID.Loc, "floating point constant does not have type '" +
1999 Ty->getDescription() + "'");
2001 return false;
2002 case ValID::t_Null:
2003 if (!isa<PointerType>(Ty))
2004 return Error(ID.Loc, "null must be a pointer type");
2005 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2006 return false;
2007 case ValID::t_Undef:
2008 // FIXME: LabelTy should not be a first-class type.
2009 if ((!Ty->isFirstClassType() || Ty == Type::LabelTy) &&
2010 !isa<OpaqueType>(Ty))
2011 return Error(ID.Loc, "invalid type for undef constant");
2012 V = UndefValue::get(Ty);
2013 return false;
2014 case ValID::t_EmptyArray:
2015 if (!isa<ArrayType>(Ty) || cast<ArrayType>(Ty)->getNumElements() != 0)
2016 return Error(ID.Loc, "invalid empty array initializer");
2017 V = UndefValue::get(Ty);
2018 return false;
2019 case ValID::t_Zero:
2020 // FIXME: LabelTy should not be a first-class type.
2021 if (!Ty->isFirstClassType() || Ty == Type::LabelTy)
2022 return Error(ID.Loc, "invalid type for null constant");
2023 V = Constant::getNullValue(Ty);
2024 return false;
2025 case ValID::t_Constant:
2026 if (ID.ConstantVal->getType() != Ty)
2027 return Error(ID.Loc, "constant expression type mismatch");
2028 V = ID.ConstantVal;
2029 return false;
2033 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2034 PATypeHolder Type(Type::VoidTy);
2035 return ParseType(Type) ||
2036 ParseGlobalValue(Type, V);
2039 /// ParseGlobalValueVector
2040 /// ::= /*empty*/
2041 /// ::= TypeAndValue (',' TypeAndValue)*
2042 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2043 // Empty list.
2044 if (Lex.getKind() == lltok::rbrace ||
2045 Lex.getKind() == lltok::rsquare ||
2046 Lex.getKind() == lltok::greater ||
2047 Lex.getKind() == lltok::rparen)
2048 return false;
2050 Constant *C;
2051 if (ParseGlobalTypeAndValue(C)) return true;
2052 Elts.push_back(C);
2054 while (EatIfPresent(lltok::comma)) {
2055 if (ParseGlobalTypeAndValue(C)) return true;
2056 Elts.push_back(C);
2059 return false;
2063 //===----------------------------------------------------------------------===//
2064 // Function Parsing.
2065 //===----------------------------------------------------------------------===//
2067 bool LLParser::ConvertValIDToValue(const Type *Ty, ValID &ID, Value *&V,
2068 PerFunctionState &PFS) {
2069 if (ID.Kind == ValID::t_LocalID)
2070 V = PFS.GetVal(ID.UIntVal, Ty, ID.Loc);
2071 else if (ID.Kind == ValID::t_LocalName)
2072 V = PFS.GetVal(ID.StrVal, Ty, ID.Loc);
2073 else if (ID.Kind == ValID::t_InlineAsm) {
2074 const PointerType *PTy = dyn_cast<PointerType>(Ty);
2075 const FunctionType *FTy =
2076 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
2077 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2078 return Error(ID.Loc, "invalid type for inline asm constraint string");
2079 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal);
2080 return false;
2081 } else {
2082 Constant *C;
2083 if (ConvertGlobalValIDToValue(Ty, ID, C)) return true;
2084 V = C;
2085 return false;
2088 return V == 0;
2091 bool LLParser::ParseValue(const Type *Ty, Value *&V, PerFunctionState &PFS) {
2092 V = 0;
2093 ValID ID;
2094 return ParseValID(ID) ||
2095 ConvertValIDToValue(Ty, ID, V, PFS);
2098 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState &PFS) {
2099 PATypeHolder T(Type::VoidTy);
2100 return ParseType(T) ||
2101 ParseValue(T, V, PFS);
2104 /// FunctionHeader
2105 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2106 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2107 /// OptionalAlign OptGC
2108 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2109 // Parse the linkage.
2110 LocTy LinkageLoc = Lex.getLoc();
2111 unsigned Linkage;
2113 unsigned Visibility, CC, RetAttrs;
2114 PATypeHolder RetType(Type::VoidTy);
2115 LocTy RetTypeLoc = Lex.getLoc();
2116 if (ParseOptionalLinkage(Linkage) ||
2117 ParseOptionalVisibility(Visibility) ||
2118 ParseOptionalCallingConv(CC) ||
2119 ParseOptionalAttrs(RetAttrs, 1) ||
2120 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2121 return true;
2123 // Verify that the linkage is ok.
2124 switch ((GlobalValue::LinkageTypes)Linkage) {
2125 case GlobalValue::ExternalLinkage:
2126 break; // always ok.
2127 case GlobalValue::DLLImportLinkage:
2128 case GlobalValue::ExternalWeakLinkage:
2129 if (isDefine)
2130 return Error(LinkageLoc, "invalid linkage for function definition");
2131 break;
2132 case GlobalValue::PrivateLinkage:
2133 case GlobalValue::InternalLinkage:
2134 case GlobalValue::AvailableExternallyLinkage:
2135 case GlobalValue::LinkOnceAnyLinkage:
2136 case GlobalValue::LinkOnceODRLinkage:
2137 case GlobalValue::WeakAnyLinkage:
2138 case GlobalValue::WeakODRLinkage:
2139 case GlobalValue::DLLExportLinkage:
2140 if (!isDefine)
2141 return Error(LinkageLoc, "invalid linkage for function declaration");
2142 break;
2143 case GlobalValue::AppendingLinkage:
2144 case GlobalValue::GhostLinkage:
2145 case GlobalValue::CommonLinkage:
2146 return Error(LinkageLoc, "invalid function linkage type");
2149 if (!FunctionType::isValidReturnType(RetType) ||
2150 isa<OpaqueType>(RetType))
2151 return Error(RetTypeLoc, "invalid function return type");
2153 LocTy NameLoc = Lex.getLoc();
2155 std::string FunctionName;
2156 if (Lex.getKind() == lltok::GlobalVar) {
2157 FunctionName = Lex.getStrVal();
2158 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
2159 unsigned NameID = Lex.getUIntVal();
2161 if (NameID != NumberedVals.size())
2162 return TokError("function expected to be numbered '%" +
2163 utostr(NumberedVals.size()) + "'");
2164 } else {
2165 return TokError("expected function name");
2168 Lex.Lex();
2170 if (Lex.getKind() != lltok::lparen)
2171 return TokError("expected '(' in function argument list");
2173 std::vector<ArgInfo> ArgList;
2174 bool isVarArg;
2175 unsigned FuncAttrs;
2176 std::string Section;
2177 unsigned Alignment;
2178 std::string GC;
2180 if (ParseArgumentList(ArgList, isVarArg, false) ||
2181 ParseOptionalAttrs(FuncAttrs, 2) ||
2182 (EatIfPresent(lltok::kw_section) &&
2183 ParseStringConstant(Section)) ||
2184 ParseOptionalAlignment(Alignment) ||
2185 (EatIfPresent(lltok::kw_gc) &&
2186 ParseStringConstant(GC)))
2187 return true;
2189 // If the alignment was parsed as an attribute, move to the alignment field.
2190 if (FuncAttrs & Attribute::Alignment) {
2191 Alignment = Attribute::getAlignmentFromAttrs(FuncAttrs);
2192 FuncAttrs &= ~Attribute::Alignment;
2195 // Okay, if we got here, the function is syntactically valid. Convert types
2196 // and do semantic checks.
2197 std::vector<const Type*> ParamTypeList;
2198 SmallVector<AttributeWithIndex, 8> Attrs;
2199 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2200 // attributes.
2201 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2202 if (FuncAttrs & ObsoleteFuncAttrs) {
2203 RetAttrs |= FuncAttrs & ObsoleteFuncAttrs;
2204 FuncAttrs &= ~ObsoleteFuncAttrs;
2207 if (RetAttrs != Attribute::None)
2208 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2210 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2211 ParamTypeList.push_back(ArgList[i].Type);
2212 if (ArgList[i].Attrs != Attribute::None)
2213 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2216 if (FuncAttrs != Attribute::None)
2217 Attrs.push_back(AttributeWithIndex::get(~0, FuncAttrs));
2219 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2221 if (PAL.paramHasAttr(1, Attribute::StructRet) &&
2222 RetType != Type::VoidTy)
2223 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
2225 const FunctionType *FT = FunctionType::get(RetType, ParamTypeList, isVarArg);
2226 const PointerType *PFT = PointerType::getUnqual(FT);
2228 Fn = 0;
2229 if (!FunctionName.empty()) {
2230 // If this was a definition of a forward reference, remove the definition
2231 // from the forward reference table and fill in the forward ref.
2232 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
2233 ForwardRefVals.find(FunctionName);
2234 if (FRVI != ForwardRefVals.end()) {
2235 Fn = M->getFunction(FunctionName);
2236 ForwardRefVals.erase(FRVI);
2237 } else if ((Fn = M->getFunction(FunctionName))) {
2238 // If this function already exists in the symbol table, then it is
2239 // multiply defined. We accept a few cases for old backwards compat.
2240 // FIXME: Remove this stuff for LLVM 3.0.
2241 if (Fn->getType() != PFT || Fn->getAttributes() != PAL ||
2242 (!Fn->isDeclaration() && isDefine)) {
2243 // If the redefinition has different type or different attributes,
2244 // reject it. If both have bodies, reject it.
2245 return Error(NameLoc, "invalid redefinition of function '" +
2246 FunctionName + "'");
2247 } else if (Fn->isDeclaration()) {
2248 // Make sure to strip off any argument names so we can't get conflicts.
2249 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2250 AI != AE; ++AI)
2251 AI->setName("");
2255 } else if (FunctionName.empty()) {
2256 // If this is a definition of a forward referenced function, make sure the
2257 // types agree.
2258 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
2259 = ForwardRefValIDs.find(NumberedVals.size());
2260 if (I != ForwardRefValIDs.end()) {
2261 Fn = cast<Function>(I->second.first);
2262 if (Fn->getType() != PFT)
2263 return Error(NameLoc, "type of definition and forward reference of '@" +
2264 utostr(NumberedVals.size()) +"' disagree");
2265 ForwardRefValIDs.erase(I);
2269 if (Fn == 0)
2270 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
2271 else // Move the forward-reference to the correct spot in the module.
2272 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
2274 if (FunctionName.empty())
2275 NumberedVals.push_back(Fn);
2277 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
2278 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
2279 Fn->setCallingConv(CC);
2280 Fn->setAttributes(PAL);
2281 Fn->setAlignment(Alignment);
2282 Fn->setSection(Section);
2283 if (!GC.empty()) Fn->setGC(GC.c_str());
2285 // Add all of the arguments we parsed to the function.
2286 Function::arg_iterator ArgIt = Fn->arg_begin();
2287 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
2288 // If the argument has a name, insert it into the argument symbol table.
2289 if (ArgList[i].Name.empty()) continue;
2291 // Set the name, if it conflicted, it will be auto-renamed.
2292 ArgIt->setName(ArgList[i].Name);
2294 if (ArgIt->getNameStr() != ArgList[i].Name)
2295 return Error(ArgList[i].Loc, "redefinition of argument '%" +
2296 ArgList[i].Name + "'");
2299 return false;
2303 /// ParseFunctionBody
2304 /// ::= '{' BasicBlock+ '}'
2305 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2307 bool LLParser::ParseFunctionBody(Function &Fn) {
2308 if (Lex.getKind() != lltok::lbrace && Lex.getKind() != lltok::kw_begin)
2309 return TokError("expected '{' in function body");
2310 Lex.Lex(); // eat the {.
2312 PerFunctionState PFS(*this, Fn);
2314 while (Lex.getKind() != lltok::rbrace && Lex.getKind() != lltok::kw_end)
2315 if (ParseBasicBlock(PFS)) return true;
2317 // Eat the }.
2318 Lex.Lex();
2320 // Verify function is ok.
2321 return PFS.VerifyFunctionComplete();
2324 /// ParseBasicBlock
2325 /// ::= LabelStr? Instruction*
2326 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
2327 // If this basic block starts out with a name, remember it.
2328 std::string Name;
2329 LocTy NameLoc = Lex.getLoc();
2330 if (Lex.getKind() == lltok::LabelStr) {
2331 Name = Lex.getStrVal();
2332 Lex.Lex();
2335 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
2336 if (BB == 0) return true;
2338 std::string NameStr;
2340 // Parse the instructions in this block until we get a terminator.
2341 Instruction *Inst;
2342 do {
2343 // This instruction may have three possibilities for a name: a) none
2344 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2345 LocTy NameLoc = Lex.getLoc();
2346 int NameID = -1;
2347 NameStr = "";
2349 if (Lex.getKind() == lltok::LocalVarID) {
2350 NameID = Lex.getUIntVal();
2351 Lex.Lex();
2352 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
2353 return true;
2354 } else if (Lex.getKind() == lltok::LocalVar ||
2355 // FIXME: REMOVE IN LLVM 3.0
2356 Lex.getKind() == lltok::StringConstant) {
2357 NameStr = Lex.getStrVal();
2358 Lex.Lex();
2359 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
2360 return true;
2363 if (ParseInstruction(Inst, BB, PFS)) return true;
2365 BB->getInstList().push_back(Inst);
2367 // Set the name on the instruction.
2368 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
2369 } while (!isa<TerminatorInst>(Inst));
2371 return false;
2374 //===----------------------------------------------------------------------===//
2375 // Instruction Parsing.
2376 //===----------------------------------------------------------------------===//
2378 /// ParseInstruction - Parse one of the many different instructions.
2380 bool LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
2381 PerFunctionState &PFS) {
2382 lltok::Kind Token = Lex.getKind();
2383 if (Token == lltok::Eof)
2384 return TokError("found end of file when expecting more instructions");
2385 LocTy Loc = Lex.getLoc();
2386 unsigned KeywordVal = Lex.getUIntVal();
2387 Lex.Lex(); // Eat the keyword.
2389 switch (Token) {
2390 default: return Error(Loc, "expected instruction opcode");
2391 // Terminator Instructions.
2392 case lltok::kw_unwind: Inst = new UnwindInst(); return false;
2393 case lltok::kw_unreachable: Inst = new UnreachableInst(); return false;
2394 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
2395 case lltok::kw_br: return ParseBr(Inst, PFS);
2396 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
2397 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
2398 // Binary Operators.
2399 case lltok::kw_add:
2400 case lltok::kw_sub:
2401 case lltok::kw_mul: return ParseArithmetic(Inst, PFS, KeywordVal, 0);
2403 case lltok::kw_udiv:
2404 case lltok::kw_sdiv:
2405 case lltok::kw_urem:
2406 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
2407 case lltok::kw_fdiv:
2408 case lltok::kw_frem: return ParseArithmetic(Inst, PFS, KeywordVal, 2);
2409 case lltok::kw_shl:
2410 case lltok::kw_lshr:
2411 case lltok::kw_ashr:
2412 case lltok::kw_and:
2413 case lltok::kw_or:
2414 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
2415 case lltok::kw_icmp:
2416 case lltok::kw_fcmp:
2417 case lltok::kw_vicmp:
2418 case lltok::kw_vfcmp: return ParseCompare(Inst, PFS, KeywordVal);
2419 // Casts.
2420 case lltok::kw_trunc:
2421 case lltok::kw_zext:
2422 case lltok::kw_sext:
2423 case lltok::kw_fptrunc:
2424 case lltok::kw_fpext:
2425 case lltok::kw_bitcast:
2426 case lltok::kw_uitofp:
2427 case lltok::kw_sitofp:
2428 case lltok::kw_fptoui:
2429 case lltok::kw_fptosi:
2430 case lltok::kw_inttoptr:
2431 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
2432 // Other.
2433 case lltok::kw_select: return ParseSelect(Inst, PFS);
2434 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
2435 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
2436 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
2437 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
2438 case lltok::kw_phi: return ParsePHI(Inst, PFS);
2439 case lltok::kw_call: return ParseCall(Inst, PFS, false);
2440 case lltok::kw_tail: return ParseCall(Inst, PFS, true);
2441 // Memory.
2442 case lltok::kw_alloca:
2443 case lltok::kw_malloc: return ParseAlloc(Inst, PFS, KeywordVal);
2444 case lltok::kw_free: return ParseFree(Inst, PFS);
2445 case lltok::kw_load: return ParseLoad(Inst, PFS, false);
2446 case lltok::kw_store: return ParseStore(Inst, PFS, false);
2447 case lltok::kw_volatile:
2448 if (EatIfPresent(lltok::kw_load))
2449 return ParseLoad(Inst, PFS, true);
2450 else if (EatIfPresent(lltok::kw_store))
2451 return ParseStore(Inst, PFS, true);
2452 else
2453 return TokError("expected 'load' or 'store'");
2454 case lltok::kw_getresult: return ParseGetResult(Inst, PFS);
2455 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
2456 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
2457 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
2461 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2462 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
2463 // FIXME: REMOVE vicmp/vfcmp!
2464 if (Opc == Instruction::FCmp || Opc == Instruction::VFCmp) {
2465 switch (Lex.getKind()) {
2466 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2467 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
2468 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
2469 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
2470 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
2471 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
2472 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
2473 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
2474 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
2475 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
2476 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
2477 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
2478 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
2479 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
2480 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
2481 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
2482 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
2484 } else {
2485 switch (Lex.getKind()) {
2486 default: TokError("expected icmp predicate (e.g. 'eq')");
2487 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
2488 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
2489 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
2490 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
2491 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
2492 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
2493 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
2494 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
2495 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
2496 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
2499 Lex.Lex();
2500 return false;
2503 //===----------------------------------------------------------------------===//
2504 // Terminator Instructions.
2505 //===----------------------------------------------------------------------===//
2507 /// ParseRet - Parse a return instruction.
2508 /// ::= 'ret' void
2509 /// ::= 'ret' TypeAndValue
2510 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2511 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
2512 PerFunctionState &PFS) {
2513 PATypeHolder Ty(Type::VoidTy);
2514 if (ParseType(Ty, true /*void allowed*/)) return true;
2516 if (Ty == Type::VoidTy) {
2517 Inst = ReturnInst::Create();
2518 return false;
2521 Value *RV;
2522 if (ParseValue(Ty, RV, PFS)) return true;
2524 // The normal case is one return value.
2525 if (Lex.getKind() == lltok::comma) {
2526 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2527 // of 'ret {i32,i32} {i32 1, i32 2}'
2528 SmallVector<Value*, 8> RVs;
2529 RVs.push_back(RV);
2531 while (EatIfPresent(lltok::comma)) {
2532 if (ParseTypeAndValue(RV, PFS)) return true;
2533 RVs.push_back(RV);
2536 RV = UndefValue::get(PFS.getFunction().getReturnType());
2537 for (unsigned i = 0, e = RVs.size(); i != e; ++i) {
2538 Instruction *I = InsertValueInst::Create(RV, RVs[i], i, "mrv");
2539 BB->getInstList().push_back(I);
2540 RV = I;
2543 Inst = ReturnInst::Create(RV);
2544 return false;
2548 /// ParseBr
2549 /// ::= 'br' TypeAndValue
2550 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2551 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
2552 LocTy Loc, Loc2;
2553 Value *Op0, *Op1, *Op2;
2554 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
2556 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
2557 Inst = BranchInst::Create(BB);
2558 return false;
2561 if (Op0->getType() != Type::Int1Ty)
2562 return Error(Loc, "branch condition must have 'i1' type");
2564 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
2565 ParseTypeAndValue(Op1, Loc, PFS) ||
2566 ParseToken(lltok::comma, "expected ',' after true destination") ||
2567 ParseTypeAndValue(Op2, Loc2, PFS))
2568 return true;
2570 if (!isa<BasicBlock>(Op1))
2571 return Error(Loc, "true destination of branch must be a basic block");
2572 if (!isa<BasicBlock>(Op2))
2573 return Error(Loc2, "true destination of branch must be a basic block");
2575 Inst = BranchInst::Create(cast<BasicBlock>(Op1), cast<BasicBlock>(Op2), Op0);
2576 return false;
2579 /// ParseSwitch
2580 /// Instruction
2581 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2582 /// JumpTable
2583 /// ::= (TypeAndValue ',' TypeAndValue)*
2584 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
2585 LocTy CondLoc, BBLoc;
2586 Value *Cond, *DefaultBB;
2587 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
2588 ParseToken(lltok::comma, "expected ',' after switch condition") ||
2589 ParseTypeAndValue(DefaultBB, BBLoc, PFS) ||
2590 ParseToken(lltok::lsquare, "expected '[' with switch table"))
2591 return true;
2593 if (!isa<IntegerType>(Cond->getType()))
2594 return Error(CondLoc, "switch condition must have integer type");
2595 if (!isa<BasicBlock>(DefaultBB))
2596 return Error(BBLoc, "default destination must be a basic block");
2598 // Parse the jump table pairs.
2599 SmallPtrSet<Value*, 32> SeenCases;
2600 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
2601 while (Lex.getKind() != lltok::rsquare) {
2602 Value *Constant, *DestBB;
2604 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
2605 ParseToken(lltok::comma, "expected ',' after case value") ||
2606 ParseTypeAndValue(DestBB, BBLoc, PFS))
2607 return true;
2609 if (!SeenCases.insert(Constant))
2610 return Error(CondLoc, "duplicate case value in switch");
2611 if (!isa<ConstantInt>(Constant))
2612 return Error(CondLoc, "case value is not a constant integer");
2613 if (!isa<BasicBlock>(DestBB))
2614 return Error(BBLoc, "case destination is not a basic block");
2616 Table.push_back(std::make_pair(cast<ConstantInt>(Constant),
2617 cast<BasicBlock>(DestBB)));
2620 Lex.Lex(); // Eat the ']'.
2622 SwitchInst *SI = SwitchInst::Create(Cond, cast<BasicBlock>(DefaultBB),
2623 Table.size());
2624 for (unsigned i = 0, e = Table.size(); i != e; ++i)
2625 SI->addCase(Table[i].first, Table[i].second);
2626 Inst = SI;
2627 return false;
2630 /// ParseInvoke
2631 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2632 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2633 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
2634 LocTy CallLoc = Lex.getLoc();
2635 unsigned CC, RetAttrs, FnAttrs;
2636 PATypeHolder RetType(Type::VoidTy);
2637 LocTy RetTypeLoc;
2638 ValID CalleeID;
2639 SmallVector<ParamInfo, 16> ArgList;
2641 Value *NormalBB, *UnwindBB;
2642 if (ParseOptionalCallingConv(CC) ||
2643 ParseOptionalAttrs(RetAttrs, 1) ||
2644 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
2645 ParseValID(CalleeID) ||
2646 ParseParameterList(ArgList, PFS) ||
2647 ParseOptionalAttrs(FnAttrs, 2) ||
2648 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
2649 ParseTypeAndValue(NormalBB, PFS) ||
2650 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
2651 ParseTypeAndValue(UnwindBB, PFS))
2652 return true;
2654 if (!isa<BasicBlock>(NormalBB))
2655 return Error(CallLoc, "normal destination is not a basic block");
2656 if (!isa<BasicBlock>(UnwindBB))
2657 return Error(CallLoc, "unwind destination is not a basic block");
2659 // If RetType is a non-function pointer type, then this is the short syntax
2660 // for the call, which means that RetType is just the return type. Infer the
2661 // rest of the function argument types from the arguments that are present.
2662 const PointerType *PFTy = 0;
2663 const FunctionType *Ty = 0;
2664 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
2665 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2666 // Pull out the types of all of the arguments...
2667 std::vector<const Type*> ParamTypes;
2668 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2669 ParamTypes.push_back(ArgList[i].V->getType());
2671 if (!FunctionType::isValidReturnType(RetType))
2672 return Error(RetTypeLoc, "Invalid result type for LLVM function");
2674 Ty = FunctionType::get(RetType, ParamTypes, false);
2675 PFTy = PointerType::getUnqual(Ty);
2678 // Look up the callee.
2679 Value *Callee;
2680 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
2682 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2683 // function attributes.
2684 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
2685 if (FnAttrs & ObsoleteFuncAttrs) {
2686 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
2687 FnAttrs &= ~ObsoleteFuncAttrs;
2690 // Set up the Attributes for the function.
2691 SmallVector<AttributeWithIndex, 8> Attrs;
2692 if (RetAttrs != Attribute::None)
2693 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
2695 SmallVector<Value*, 8> Args;
2697 // Loop through FunctionType's arguments and ensure they are specified
2698 // correctly. Also, gather any parameter attributes.
2699 FunctionType::param_iterator I = Ty->param_begin();
2700 FunctionType::param_iterator E = Ty->param_end();
2701 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2702 const Type *ExpectedTy = 0;
2703 if (I != E) {
2704 ExpectedTy = *I++;
2705 } else if (!Ty->isVarArg()) {
2706 return Error(ArgList[i].Loc, "too many arguments specified");
2709 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
2710 return Error(ArgList[i].Loc, "argument is not of expected type '" +
2711 ExpectedTy->getDescription() + "'");
2712 Args.push_back(ArgList[i].V);
2713 if (ArgList[i].Attrs != Attribute::None)
2714 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
2717 if (I != E)
2718 return Error(CallLoc, "not enough parameters specified for call");
2720 if (FnAttrs != Attribute::None)
2721 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
2723 // Finish off the Attributes and check them
2724 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
2726 InvokeInst *II = InvokeInst::Create(Callee, cast<BasicBlock>(NormalBB),
2727 cast<BasicBlock>(UnwindBB),
2728 Args.begin(), Args.end());
2729 II->setCallingConv(CC);
2730 II->setAttributes(PAL);
2731 Inst = II;
2732 return false;
2737 //===----------------------------------------------------------------------===//
2738 // Binary Operators.
2739 //===----------------------------------------------------------------------===//
2741 /// ParseArithmetic
2742 /// ::= ArithmeticOps TypeAndValue ',' Value
2744 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2745 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2746 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
2747 unsigned Opc, unsigned OperandType) {
2748 LocTy Loc; Value *LHS, *RHS;
2749 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2750 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
2751 ParseValue(LHS->getType(), RHS, PFS))
2752 return true;
2754 bool Valid;
2755 switch (OperandType) {
2756 default: assert(0 && "Unknown operand type!");
2757 case 0: // int or FP.
2758 Valid = LHS->getType()->isIntOrIntVector() ||
2759 LHS->getType()->isFPOrFPVector();
2760 break;
2761 case 1: Valid = LHS->getType()->isIntOrIntVector(); break;
2762 case 2: Valid = LHS->getType()->isFPOrFPVector(); break;
2765 if (!Valid)
2766 return Error(Loc, "invalid operand type for instruction");
2768 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2769 return false;
2772 /// ParseLogical
2773 /// ::= ArithmeticOps TypeAndValue ',' Value {
2774 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
2775 unsigned Opc) {
2776 LocTy Loc; Value *LHS, *RHS;
2777 if (ParseTypeAndValue(LHS, Loc, PFS) ||
2778 ParseToken(lltok::comma, "expected ',' in logical operation") ||
2779 ParseValue(LHS->getType(), RHS, PFS))
2780 return true;
2782 if (!LHS->getType()->isIntOrIntVector())
2783 return Error(Loc,"instruction requires integer or integer vector operands");
2785 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2786 return false;
2790 /// ParseCompare
2791 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
2792 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
2793 /// ::= 'vicmp' IPredicates TypeAndValue ',' Value
2794 /// ::= 'vfcmp' FPredicates TypeAndValue ',' Value
2795 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
2796 unsigned Opc) {
2797 // Parse the integer/fp comparison predicate.
2798 LocTy Loc;
2799 unsigned Pred;
2800 Value *LHS, *RHS;
2801 if (ParseCmpPredicate(Pred, Opc) ||
2802 ParseTypeAndValue(LHS, Loc, PFS) ||
2803 ParseToken(lltok::comma, "expected ',' after compare value") ||
2804 ParseValue(LHS->getType(), RHS, PFS))
2805 return true;
2807 if (Opc == Instruction::FCmp) {
2808 if (!LHS->getType()->isFPOrFPVector())
2809 return Error(Loc, "fcmp requires floating point operands");
2810 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2811 } else if (Opc == Instruction::ICmp) {
2812 if (!LHS->getType()->isIntOrIntVector() &&
2813 !isa<PointerType>(LHS->getType()))
2814 return Error(Loc, "icmp requires integer operands");
2815 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2816 } else if (Opc == Instruction::VFCmp) {
2817 if (!LHS->getType()->isFPOrFPVector() || !isa<VectorType>(LHS->getType()))
2818 return Error(Loc, "vfcmp requires vector floating point operands");
2819 Inst = new VFCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2820 } else if (Opc == Instruction::VICmp) {
2821 if (!LHS->getType()->isIntOrIntVector() || !isa<VectorType>(LHS->getType()))
2822 return Error(Loc, "vicmp requires vector floating point operands");
2823 Inst = new VICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
2825 return false;
2828 //===----------------------------------------------------------------------===//
2829 // Other Instructions.
2830 //===----------------------------------------------------------------------===//
2833 /// ParseCast
2834 /// ::= CastOpc TypeAndValue 'to' Type
2835 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
2836 unsigned Opc) {
2837 LocTy Loc; Value *Op;
2838 PATypeHolder DestTy(Type::VoidTy);
2839 if (ParseTypeAndValue(Op, Loc, PFS) ||
2840 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
2841 ParseType(DestTy))
2842 return true;
2844 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
2845 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
2846 return Error(Loc, "invalid cast opcode for cast from '" +
2847 Op->getType()->getDescription() + "' to '" +
2848 DestTy->getDescription() + "'");
2850 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
2851 return false;
2854 /// ParseSelect
2855 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2856 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
2857 LocTy Loc;
2858 Value *Op0, *Op1, *Op2;
2859 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2860 ParseToken(lltok::comma, "expected ',' after select condition") ||
2861 ParseTypeAndValue(Op1, PFS) ||
2862 ParseToken(lltok::comma, "expected ',' after select value") ||
2863 ParseTypeAndValue(Op2, PFS))
2864 return true;
2866 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
2867 return Error(Loc, Reason);
2869 Inst = SelectInst::Create(Op0, Op1, Op2);
2870 return false;
2873 /// ParseVA_Arg
2874 /// ::= 'va_arg' TypeAndValue ',' Type
2875 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
2876 Value *Op;
2877 PATypeHolder EltTy(Type::VoidTy);
2878 LocTy TypeLoc;
2879 if (ParseTypeAndValue(Op, PFS) ||
2880 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
2881 ParseType(EltTy, TypeLoc))
2882 return true;
2884 if (!EltTy->isFirstClassType())
2885 return Error(TypeLoc, "va_arg requires operand with first class type");
2887 Inst = new VAArgInst(Op, EltTy);
2888 return false;
2891 /// ParseExtractElement
2892 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
2893 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
2894 LocTy Loc;
2895 Value *Op0, *Op1;
2896 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2897 ParseToken(lltok::comma, "expected ',' after extract value") ||
2898 ParseTypeAndValue(Op1, PFS))
2899 return true;
2901 if (!ExtractElementInst::isValidOperands(Op0, Op1))
2902 return Error(Loc, "invalid extractelement operands");
2904 Inst = new ExtractElementInst(Op0, Op1);
2905 return false;
2908 /// ParseInsertElement
2909 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2910 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
2911 LocTy Loc;
2912 Value *Op0, *Op1, *Op2;
2913 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2914 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2915 ParseTypeAndValue(Op1, PFS) ||
2916 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2917 ParseTypeAndValue(Op2, PFS))
2918 return true;
2920 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
2921 return Error(Loc, "invalid extractelement operands");
2923 Inst = InsertElementInst::Create(Op0, Op1, Op2);
2924 return false;
2927 /// ParseShuffleVector
2928 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2929 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
2930 LocTy Loc;
2931 Value *Op0, *Op1, *Op2;
2932 if (ParseTypeAndValue(Op0, Loc, PFS) ||
2933 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
2934 ParseTypeAndValue(Op1, PFS) ||
2935 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
2936 ParseTypeAndValue(Op2, PFS))
2937 return true;
2939 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2940 return Error(Loc, "invalid extractelement operands");
2942 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
2943 return false;
2946 /// ParsePHI
2947 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
2948 bool LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
2949 PATypeHolder Ty(Type::VoidTy);
2950 Value *Op0, *Op1;
2951 LocTy TypeLoc = Lex.getLoc();
2953 if (ParseType(Ty) ||
2954 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2955 ParseValue(Ty, Op0, PFS) ||
2956 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2957 ParseValue(Type::LabelTy, Op1, PFS) ||
2958 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2959 return true;
2961 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
2962 while (1) {
2963 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
2965 if (!EatIfPresent(lltok::comma))
2966 break;
2968 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
2969 ParseValue(Ty, Op0, PFS) ||
2970 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
2971 ParseValue(Type::LabelTy, Op1, PFS) ||
2972 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
2973 return true;
2976 if (!Ty->isFirstClassType())
2977 return Error(TypeLoc, "phi node must have first class type");
2979 PHINode *PN = PHINode::Create(Ty);
2980 PN->reserveOperandSpace(PHIVals.size());
2981 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
2982 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
2983 Inst = PN;
2984 return false;
2987 /// ParseCall
2988 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
2989 /// ParameterList OptionalAttrs
2990 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
2991 bool isTail) {
2992 unsigned CC, RetAttrs, FnAttrs;
2993 PATypeHolder RetType(Type::VoidTy);
2994 LocTy RetTypeLoc;
2995 ValID CalleeID;
2996 SmallVector<ParamInfo, 16> ArgList;
2997 LocTy CallLoc = Lex.getLoc();
2999 if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
3000 ParseOptionalCallingConv(CC) ||
3001 ParseOptionalAttrs(RetAttrs, 1) ||
3002 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3003 ParseValID(CalleeID) ||
3004 ParseParameterList(ArgList, PFS) ||
3005 ParseOptionalAttrs(FnAttrs, 2))
3006 return true;
3008 // If RetType is a non-function pointer type, then this is the short syntax
3009 // for the call, which means that RetType is just the return type. Infer the
3010 // rest of the function argument types from the arguments that are present.
3011 const PointerType *PFTy = 0;
3012 const FunctionType *Ty = 0;
3013 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3014 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3015 // Pull out the types of all of the arguments...
3016 std::vector<const Type*> ParamTypes;
3017 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3018 ParamTypes.push_back(ArgList[i].V->getType());
3020 if (!FunctionType::isValidReturnType(RetType))
3021 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3023 Ty = FunctionType::get(RetType, ParamTypes, false);
3024 PFTy = PointerType::getUnqual(Ty);
3027 // Look up the callee.
3028 Value *Callee;
3029 if (ConvertValIDToValue(PFTy, CalleeID, Callee, PFS)) return true;
3031 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3032 // function attributes.
3033 unsigned ObsoleteFuncAttrs = Attribute::ZExt|Attribute::SExt|Attribute::InReg;
3034 if (FnAttrs & ObsoleteFuncAttrs) {
3035 RetAttrs |= FnAttrs & ObsoleteFuncAttrs;
3036 FnAttrs &= ~ObsoleteFuncAttrs;
3039 // Set up the Attributes for the function.
3040 SmallVector<AttributeWithIndex, 8> Attrs;
3041 if (RetAttrs != Attribute::None)
3042 Attrs.push_back(AttributeWithIndex::get(0, RetAttrs));
3044 SmallVector<Value*, 8> Args;
3046 // Loop through FunctionType's arguments and ensure they are specified
3047 // correctly. Also, gather any parameter attributes.
3048 FunctionType::param_iterator I = Ty->param_begin();
3049 FunctionType::param_iterator E = Ty->param_end();
3050 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3051 const Type *ExpectedTy = 0;
3052 if (I != E) {
3053 ExpectedTy = *I++;
3054 } else if (!Ty->isVarArg()) {
3055 return Error(ArgList[i].Loc, "too many arguments specified");
3058 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3059 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3060 ExpectedTy->getDescription() + "'");
3061 Args.push_back(ArgList[i].V);
3062 if (ArgList[i].Attrs != Attribute::None)
3063 Attrs.push_back(AttributeWithIndex::get(i+1, ArgList[i].Attrs));
3066 if (I != E)
3067 return Error(CallLoc, "not enough parameters specified for call");
3069 if (FnAttrs != Attribute::None)
3070 Attrs.push_back(AttributeWithIndex::get(~0, FnAttrs));
3072 // Finish off the Attributes and check them
3073 AttrListPtr PAL = AttrListPtr::get(Attrs.begin(), Attrs.end());
3075 CallInst *CI = CallInst::Create(Callee, Args.begin(), Args.end());
3076 CI->setTailCall(isTail);
3077 CI->setCallingConv(CC);
3078 CI->setAttributes(PAL);
3079 Inst = CI;
3080 return false;
3083 //===----------------------------------------------------------------------===//
3084 // Memory Instructions.
3085 //===----------------------------------------------------------------------===//
3087 /// ParseAlloc
3088 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3089 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3090 bool LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS,
3091 unsigned Opc) {
3092 PATypeHolder Ty(Type::VoidTy);
3093 Value *Size = 0;
3094 LocTy SizeLoc = 0;
3095 unsigned Alignment = 0;
3096 if (ParseType(Ty)) return true;
3098 if (EatIfPresent(lltok::comma)) {
3099 if (Lex.getKind() == lltok::kw_align) {
3100 if (ParseOptionalAlignment(Alignment)) return true;
3101 } else if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
3102 ParseOptionalCommaAlignment(Alignment)) {
3103 return true;
3107 if (Size && Size->getType() != Type::Int32Ty)
3108 return Error(SizeLoc, "element count must be i32");
3110 if (Opc == Instruction::Malloc)
3111 Inst = new MallocInst(Ty, Size, Alignment);
3112 else
3113 Inst = new AllocaInst(Ty, Size, Alignment);
3114 return false;
3117 /// ParseFree
3118 /// ::= 'free' TypeAndValue
3119 bool LLParser::ParseFree(Instruction *&Inst, PerFunctionState &PFS) {
3120 Value *Val; LocTy Loc;
3121 if (ParseTypeAndValue(Val, Loc, PFS)) return true;
3122 if (!isa<PointerType>(Val->getType()))
3123 return Error(Loc, "operand to free must be a pointer");
3124 Inst = new FreeInst(Val);
3125 return false;
3128 /// ParseLoad
3129 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' uint)?
3130 bool LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
3131 bool isVolatile) {
3132 Value *Val; LocTy Loc;
3133 unsigned Alignment;
3134 if (ParseTypeAndValue(Val, Loc, PFS) ||
3135 ParseOptionalCommaAlignment(Alignment))
3136 return true;
3138 if (!isa<PointerType>(Val->getType()) ||
3139 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
3140 return Error(Loc, "load operand must be a pointer to a first class type");
3142 Inst = new LoadInst(Val, "", isVolatile, Alignment);
3143 return false;
3146 /// ParseStore
3147 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' uint)?
3148 bool LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
3149 bool isVolatile) {
3150 Value *Val, *Ptr; LocTy Loc, PtrLoc;
3151 unsigned Alignment;
3152 if (ParseTypeAndValue(Val, Loc, PFS) ||
3153 ParseToken(lltok::comma, "expected ',' after store operand") ||
3154 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
3155 ParseOptionalCommaAlignment(Alignment))
3156 return true;
3158 if (!isa<PointerType>(Ptr->getType()))
3159 return Error(PtrLoc, "store operand must be a pointer");
3160 if (!Val->getType()->isFirstClassType())
3161 return Error(Loc, "store operand must be a first class value");
3162 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
3163 return Error(Loc, "stored value and pointer type do not match");
3165 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment);
3166 return false;
3169 /// ParseGetResult
3170 /// ::= 'getresult' TypeAndValue ',' uint
3171 /// FIXME: Remove support for getresult in LLVM 3.0
3172 bool LLParser::ParseGetResult(Instruction *&Inst, PerFunctionState &PFS) {
3173 Value *Val; LocTy ValLoc, EltLoc;
3174 unsigned Element;
3175 if (ParseTypeAndValue(Val, ValLoc, PFS) ||
3176 ParseToken(lltok::comma, "expected ',' after getresult operand") ||
3177 ParseUInt32(Element, EltLoc))
3178 return true;
3180 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3181 return Error(ValLoc, "getresult inst requires an aggregate operand");
3182 if (!ExtractValueInst::getIndexedType(Val->getType(), Element))
3183 return Error(EltLoc, "invalid getresult index for value");
3184 Inst = ExtractValueInst::Create(Val, Element);
3185 return false;
3188 /// ParseGetElementPtr
3189 /// ::= 'getelementptr' TypeAndValue (',' TypeAndValue)*
3190 bool LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
3191 Value *Ptr, *Val; LocTy Loc, EltLoc;
3192 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
3194 if (!isa<PointerType>(Ptr->getType()))
3195 return Error(Loc, "base of getelementptr must be a pointer");
3197 SmallVector<Value*, 16> Indices;
3198 while (EatIfPresent(lltok::comma)) {
3199 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
3200 if (!isa<IntegerType>(Val->getType()))
3201 return Error(EltLoc, "getelementptr index must be an integer");
3202 Indices.push_back(Val);
3205 if (!GetElementPtrInst::getIndexedType(Ptr->getType(),
3206 Indices.begin(), Indices.end()))
3207 return Error(Loc, "invalid getelementptr indices");
3208 Inst = GetElementPtrInst::Create(Ptr, Indices.begin(), Indices.end());
3209 return false;
3212 /// ParseExtractValue
3213 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3214 bool LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
3215 Value *Val; LocTy Loc;
3216 SmallVector<unsigned, 4> Indices;
3217 if (ParseTypeAndValue(Val, Loc, PFS) ||
3218 ParseIndexList(Indices))
3219 return true;
3221 if (!isa<StructType>(Val->getType()) && !isa<ArrayType>(Val->getType()))
3222 return Error(Loc, "extractvalue operand must be array or struct");
3224 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
3225 Indices.end()))
3226 return Error(Loc, "invalid indices for extractvalue");
3227 Inst = ExtractValueInst::Create(Val, Indices.begin(), Indices.end());
3228 return false;
3231 /// ParseInsertValue
3232 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3233 bool LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
3234 Value *Val0, *Val1; LocTy Loc0, Loc1;
3235 SmallVector<unsigned, 4> Indices;
3236 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
3237 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
3238 ParseTypeAndValue(Val1, Loc1, PFS) ||
3239 ParseIndexList(Indices))
3240 return true;
3242 if (!isa<StructType>(Val0->getType()) && !isa<ArrayType>(Val0->getType()))
3243 return Error(Loc0, "extractvalue operand must be array or struct");
3245 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
3246 Indices.end()))
3247 return Error(Loc0, "invalid indices for insertvalue");
3248 Inst = InsertValueInst::Create(Val0, Val1, Indices.begin(), Indices.end());
3249 return false;
3252 //===----------------------------------------------------------------------===//
3253 // Embedded metadata.
3254 //===----------------------------------------------------------------------===//
3256 /// ParseMDNodeVector
3257 /// ::= TypeAndValue (',' TypeAndValue)*
3258 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Constant*> &Elts) {
3259 assert(Lex.getKind() == lltok::lbrace);
3260 Lex.Lex();
3261 do {
3262 Constant *C;
3263 if (ParseGlobalTypeAndValue(C)) return true;
3264 Elts.push_back(C);
3265 } while (EatIfPresent(lltok::comma));
3267 return false;