1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/AutoUpgrade.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/InlineAsm.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Metadata.h"
23 #include "llvm/Module.h"
24 #include "llvm/Operator.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
33 /// ValID - Represents a reference of a definition of some sort with no type.
34 /// There are several cases where we have to parse the value but where the
35 /// type can depend on later context. This may either be a numeric reference
36 /// or a symbolic (%var) reference. This is just a discriminated union.
39 t_LocalID
, t_GlobalID
, // ID in UIntVal.
40 t_LocalName
, t_GlobalName
, // Name in StrVal.
41 t_APSInt
, t_APFloat
, // Value in APSIntVal/APFloatVal.
42 t_Null
, t_Undef
, t_Zero
, // No value.
43 t_EmptyArray
, // No value: []
44 t_Constant
, // Value in ConstantVal.
45 t_InlineAsm
, // Value in StrVal/StrVal2/UIntVal.
46 t_Metadata
// Value in MetadataVal.
51 std::string StrVal
, StrVal2
;
54 Constant
*ConstantVal
;
55 MetadataBase
*MetadataVal
;
56 ValID() : APFloatVal(0.0) {}
60 /// Run: module ::= toplevelentity*
61 bool LLParser::Run() {
65 return ParseTopLevelEntities() ||
66 ValidateEndOfModule();
69 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
71 bool LLParser::ValidateEndOfModule() {
72 if (!ForwardRefTypes
.empty())
73 return Error(ForwardRefTypes
.begin()->second
.second
,
74 "use of undefined type named '" +
75 ForwardRefTypes
.begin()->first
+ "'");
76 if (!ForwardRefTypeIDs
.empty())
77 return Error(ForwardRefTypeIDs
.begin()->second
.second
,
78 "use of undefined type '%" +
79 utostr(ForwardRefTypeIDs
.begin()->first
) + "'");
81 if (!ForwardRefVals
.empty())
82 return Error(ForwardRefVals
.begin()->second
.second
,
83 "use of undefined value '@" + ForwardRefVals
.begin()->first
+
86 if (!ForwardRefValIDs
.empty())
87 return Error(ForwardRefValIDs
.begin()->second
.second
,
88 "use of undefined value '@" +
89 utostr(ForwardRefValIDs
.begin()->first
) + "'");
91 if (!ForwardRefMDNodes
.empty())
92 return Error(ForwardRefMDNodes
.begin()->second
.second
,
93 "use of undefined metadata '!" +
94 utostr(ForwardRefMDNodes
.begin()->first
) + "'");
97 // Look for intrinsic functions and CallInst that need to be upgraded
98 for (Module::iterator FI
= M
->begin(), FE
= M
->end(); FI
!= FE
; )
99 UpgradeCallsToIntrinsic(FI
++); // must be post-increment, as we remove
104 //===----------------------------------------------------------------------===//
105 // Top-Level Entities
106 //===----------------------------------------------------------------------===//
108 bool LLParser::ParseTopLevelEntities() {
110 switch (Lex
.getKind()) {
111 default: return TokError("expected top-level entity");
112 case lltok::Eof
: return false;
113 //case lltok::kw_define:
114 case lltok::kw_declare
: if (ParseDeclare()) return true; break;
115 case lltok::kw_define
: if (ParseDefine()) return true; break;
116 case lltok::kw_module
: if (ParseModuleAsm()) return true; break;
117 case lltok::kw_target
: if (ParseTargetDefinition()) return true; break;
118 case lltok::kw_deplibs
: if (ParseDepLibs()) return true; break;
119 case lltok::kw_type
: if (ParseUnnamedType()) return true; break;
120 case lltok::StringConstant
: // FIXME: REMOVE IN LLVM 3.0
121 case lltok::LocalVar
: if (ParseNamedType()) return true; break;
122 case lltok::GlobalVar
: if (ParseNamedGlobal()) return true; break;
123 case lltok::Metadata
: if (ParseStandaloneMetadata()) return true; break;
124 case lltok::NamedMD
: if (ParseNamedMetadata()) return true; break;
126 // The Global variable production with no name can have many different
127 // optional leading prefixes, the production is:
128 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
129 // OptionalAddrSpace ('constant'|'global') ...
130 case lltok::kw_private
: // OptionalLinkage
131 case lltok::kw_linker_private
: // OptionalLinkage
132 case lltok::kw_internal
: // OptionalLinkage
133 case lltok::kw_weak
: // OptionalLinkage
134 case lltok::kw_weak_odr
: // OptionalLinkage
135 case lltok::kw_linkonce
: // OptionalLinkage
136 case lltok::kw_linkonce_odr
: // OptionalLinkage
137 case lltok::kw_appending
: // OptionalLinkage
138 case lltok::kw_dllexport
: // OptionalLinkage
139 case lltok::kw_common
: // OptionalLinkage
140 case lltok::kw_dllimport
: // OptionalLinkage
141 case lltok::kw_extern_weak
: // OptionalLinkage
142 case lltok::kw_external
: { // OptionalLinkage
143 unsigned Linkage
, Visibility
;
144 if (ParseOptionalLinkage(Linkage
) ||
145 ParseOptionalVisibility(Visibility
) ||
146 ParseGlobal("", SMLoc(), Linkage
, true, Visibility
))
150 case lltok::kw_default
: // OptionalVisibility
151 case lltok::kw_hidden
: // OptionalVisibility
152 case lltok::kw_protected
: { // OptionalVisibility
154 if (ParseOptionalVisibility(Visibility
) ||
155 ParseGlobal("", SMLoc(), 0, false, Visibility
))
160 case lltok::kw_thread_local
: // OptionalThreadLocal
161 case lltok::kw_addrspace
: // OptionalAddrSpace
162 case lltok::kw_constant
: // GlobalType
163 case lltok::kw_global
: // GlobalType
164 if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
172 /// ::= 'module' 'asm' STRINGCONSTANT
173 bool LLParser::ParseModuleAsm() {
174 assert(Lex
.getKind() == lltok::kw_module
);
178 if (ParseToken(lltok::kw_asm
, "expected 'module asm'") ||
179 ParseStringConstant(AsmStr
)) return true;
181 const std::string
&AsmSoFar
= M
->getModuleInlineAsm();
182 if (AsmSoFar
.empty())
183 M
->setModuleInlineAsm(AsmStr
);
185 M
->setModuleInlineAsm(AsmSoFar
+"\n"+AsmStr
);
190 /// ::= 'target' 'triple' '=' STRINGCONSTANT
191 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
192 bool LLParser::ParseTargetDefinition() {
193 assert(Lex
.getKind() == lltok::kw_target
);
196 default: return TokError("unknown target property");
197 case lltok::kw_triple
:
199 if (ParseToken(lltok::equal
, "expected '=' after target triple") ||
200 ParseStringConstant(Str
))
202 M
->setTargetTriple(Str
);
204 case lltok::kw_datalayout
:
206 if (ParseToken(lltok::equal
, "expected '=' after target datalayout") ||
207 ParseStringConstant(Str
))
209 M
->setDataLayout(Str
);
215 /// ::= 'deplibs' '=' '[' ']'
216 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
217 bool LLParser::ParseDepLibs() {
218 assert(Lex
.getKind() == lltok::kw_deplibs
);
220 if (ParseToken(lltok::equal
, "expected '=' after deplibs") ||
221 ParseToken(lltok::lsquare
, "expected '=' after deplibs"))
224 if (EatIfPresent(lltok::rsquare
))
228 if (ParseStringConstant(Str
)) return true;
231 while (EatIfPresent(lltok::comma
)) {
232 if (ParseStringConstant(Str
)) return true;
236 return ParseToken(lltok::rsquare
, "expected ']' at end of list");
241 bool LLParser::ParseUnnamedType() {
242 assert(Lex
.getKind() == lltok::kw_type
);
243 LocTy TypeLoc
= Lex
.getLoc();
244 Lex
.Lex(); // eat kw_type
246 PATypeHolder
Ty(Type::VoidTy
);
247 if (ParseType(Ty
)) return true;
249 unsigned TypeID
= NumberedTypes
.size();
251 // See if this type was previously referenced.
252 std::map
<unsigned, std::pair
<PATypeHolder
, LocTy
> >::iterator
253 FI
= ForwardRefTypeIDs
.find(TypeID
);
254 if (FI
!= ForwardRefTypeIDs
.end()) {
255 if (FI
->second
.first
.get() == Ty
)
256 return Error(TypeLoc
, "self referential type is invalid");
258 cast
<DerivedType
>(FI
->second
.first
.get())->refineAbstractTypeTo(Ty
);
259 Ty
= FI
->second
.first
.get();
260 ForwardRefTypeIDs
.erase(FI
);
263 NumberedTypes
.push_back(Ty
);
269 /// ::= LocalVar '=' 'type' type
270 bool LLParser::ParseNamedType() {
271 std::string Name
= Lex
.getStrVal();
272 LocTy NameLoc
= Lex
.getLoc();
273 Lex
.Lex(); // eat LocalVar.
275 PATypeHolder
Ty(Type::VoidTy
);
277 if (ParseToken(lltok::equal
, "expected '=' after name") ||
278 ParseToken(lltok::kw_type
, "expected 'type' after name") ||
282 // Set the type name, checking for conflicts as we do so.
283 bool AlreadyExists
= M
->addTypeName(Name
, Ty
);
284 if (!AlreadyExists
) return false;
286 // See if this type is a forward reference. We need to eagerly resolve
287 // types to allow recursive type redefinitions below.
288 std::map
<std::string
, std::pair
<PATypeHolder
, LocTy
> >::iterator
289 FI
= ForwardRefTypes
.find(Name
);
290 if (FI
!= ForwardRefTypes
.end()) {
291 if (FI
->second
.first
.get() == Ty
)
292 return Error(NameLoc
, "self referential type is invalid");
294 cast
<DerivedType
>(FI
->second
.first
.get())->refineAbstractTypeTo(Ty
);
295 Ty
= FI
->second
.first
.get();
296 ForwardRefTypes
.erase(FI
);
299 // Inserting a name that is already defined, get the existing name.
300 const Type
*Existing
= M
->getTypeByName(Name
);
301 assert(Existing
&& "Conflict but no matching type?!");
303 // Otherwise, this is an attempt to redefine a type. That's okay if
304 // the redefinition is identical to the original.
305 // FIXME: REMOVE REDEFINITIONS IN LLVM 3.0
306 if (Existing
== Ty
) return false;
308 // Any other kind of (non-equivalent) redefinition is an error.
309 return Error(NameLoc
, "redefinition of type named '" + Name
+ "' of type '" +
310 Ty
->getDescription() + "'");
315 /// ::= 'declare' FunctionHeader
316 bool LLParser::ParseDeclare() {
317 assert(Lex
.getKind() == lltok::kw_declare
);
321 return ParseFunctionHeader(F
, false);
325 /// ::= 'define' FunctionHeader '{' ...
326 bool LLParser::ParseDefine() {
327 assert(Lex
.getKind() == lltok::kw_define
);
331 return ParseFunctionHeader(F
, true) ||
332 ParseFunctionBody(*F
);
338 bool LLParser::ParseGlobalType(bool &IsConstant
) {
339 if (Lex
.getKind() == lltok::kw_constant
)
341 else if (Lex
.getKind() == lltok::kw_global
)
345 return TokError("expected 'global' or 'constant'");
351 /// ParseNamedGlobal:
352 /// GlobalVar '=' OptionalVisibility ALIAS ...
353 /// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
354 bool LLParser::ParseNamedGlobal() {
355 assert(Lex
.getKind() == lltok::GlobalVar
);
356 LocTy NameLoc
= Lex
.getLoc();
357 std::string Name
= Lex
.getStrVal();
361 unsigned Linkage
, Visibility
;
362 if (ParseToken(lltok::equal
, "expected '=' in global variable") ||
363 ParseOptionalLinkage(Linkage
, HasLinkage
) ||
364 ParseOptionalVisibility(Visibility
))
367 if (HasLinkage
|| Lex
.getKind() != lltok::kw_alias
)
368 return ParseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
);
369 return ParseAlias(Name
, NameLoc
, Visibility
);
373 // ::= '!' STRINGCONSTANT
374 bool LLParser::ParseMDString(MetadataBase
*&MDS
) {
376 if (ParseStringConstant(Str
)) return true;
377 MDS
= MDString::get(Context
, Str
);
382 // ::= '!' MDNodeNumber
383 bool LLParser::ParseMDNode(MetadataBase
*&Node
) {
384 // !{ ..., !42, ... }
386 if (ParseUInt32(MID
)) return true;
388 // Check existing MDNode.
389 std::map
<unsigned, MetadataBase
*>::iterator I
= MetadataCache
.find(MID
);
390 if (I
!= MetadataCache
.end()) {
395 // Check known forward references.
396 std::map
<unsigned, std::pair
<MetadataBase
*, LocTy
> >::iterator
397 FI
= ForwardRefMDNodes
.find(MID
);
398 if (FI
!= ForwardRefMDNodes
.end()) {
399 Node
= FI
->second
.first
;
403 // Create MDNode forward reference
404 SmallVector
<Value
*, 1> Elts
;
405 std::string FwdRefName
= "llvm.mdnode.fwdref." + utostr(MID
);
406 Elts
.push_back(MDString::get(Context
, FwdRefName
));
407 MDNode
*FwdNode
= MDNode::get(Context
, Elts
.data(), Elts
.size());
408 ForwardRefMDNodes
[MID
] = std::make_pair(FwdNode
, Lex
.getLoc());
413 ///ParseNamedMetadata:
414 /// !foo = !{ !1, !2 }
415 bool LLParser::ParseNamedMetadata() {
416 assert(Lex
.getKind() == lltok::NamedMD
);
418 std::string Name
= Lex
.getStrVal();
420 if (ParseToken(lltok::equal
, "expected '=' here"))
423 if (Lex
.getKind() != lltok::Metadata
)
424 return TokError("Expected '!' here");
427 if (Lex
.getKind() != lltok::lbrace
)
428 return TokError("Expected '{' here");
430 SmallVector
<MetadataBase
*, 8> Elts
;
432 if (Lex
.getKind() != lltok::Metadata
)
433 return TokError("Expected '!' here");
436 if (ParseMDNode(N
)) return true;
438 } while (EatIfPresent(lltok::comma
));
440 if (ParseToken(lltok::rbrace
, "expected end of metadata node"))
443 NamedMDNode::Create(Name
, Elts
.data(), Elts
.size(), M
);
447 /// ParseStandaloneMetadata:
449 bool LLParser::ParseStandaloneMetadata() {
450 assert(Lex
.getKind() == lltok::Metadata
);
452 unsigned MetadataID
= 0;
453 if (ParseUInt32(MetadataID
))
455 if (MetadataCache
.find(MetadataID
) != MetadataCache
.end())
456 return TokError("Metadata id is already used");
457 if (ParseToken(lltok::equal
, "expected '=' here"))
461 PATypeHolder
Ty(Type::VoidTy
);
462 if (ParseType(Ty
, TyLoc
))
465 if (Lex
.getKind() != lltok::Metadata
)
466 return TokError("Expected metadata here");
469 if (Lex
.getKind() != lltok::lbrace
)
470 return TokError("Expected '{' here");
472 SmallVector
<Value
*, 16> Elts
;
473 if (ParseMDNodeVector(Elts
)
474 || ParseToken(lltok::rbrace
, "expected end of metadata node"))
477 MDNode
*Init
= MDNode::get(Context
, Elts
.data(), Elts
.size());
478 MetadataCache
[MetadataID
] = Init
;
479 std::map
<unsigned, std::pair
<MetadataBase
*, LocTy
> >::iterator
480 FI
= ForwardRefMDNodes
.find(MetadataID
);
481 if (FI
!= ForwardRefMDNodes
.end()) {
482 MDNode
*FwdNode
= cast
<MDNode
>(FI
->second
.first
);
483 FwdNode
->replaceAllUsesWith(Init
);
484 ForwardRefMDNodes
.erase(FI
);
491 /// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
494 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
495 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
497 /// Everything through visibility has already been parsed.
499 bool LLParser::ParseAlias(const std::string
&Name
, LocTy NameLoc
,
500 unsigned Visibility
) {
501 assert(Lex
.getKind() == lltok::kw_alias
);
504 LocTy LinkageLoc
= Lex
.getLoc();
505 if (ParseOptionalLinkage(Linkage
))
508 if (Linkage
!= GlobalValue::ExternalLinkage
&&
509 Linkage
!= GlobalValue::WeakAnyLinkage
&&
510 Linkage
!= GlobalValue::WeakODRLinkage
&&
511 Linkage
!= GlobalValue::InternalLinkage
&&
512 Linkage
!= GlobalValue::PrivateLinkage
&&
513 Linkage
!= GlobalValue::LinkerPrivateLinkage
)
514 return Error(LinkageLoc
, "invalid linkage type for alias");
517 LocTy AliaseeLoc
= Lex
.getLoc();
518 if (Lex
.getKind() != lltok::kw_bitcast
&&
519 Lex
.getKind() != lltok::kw_getelementptr
) {
520 if (ParseGlobalTypeAndValue(Aliasee
)) return true;
522 // The bitcast dest type is not present, it is implied by the dest type.
524 if (ParseValID(ID
)) return true;
525 if (ID
.Kind
!= ValID::t_Constant
)
526 return Error(AliaseeLoc
, "invalid aliasee");
527 Aliasee
= ID
.ConstantVal
;
530 if (!isa
<PointerType
>(Aliasee
->getType()))
531 return Error(AliaseeLoc
, "alias must have pointer type");
533 // Okay, create the alias but do not insert it into the module yet.
534 GlobalAlias
* GA
= new GlobalAlias(Aliasee
->getType(),
535 (GlobalValue::LinkageTypes
)Linkage
, Name
,
537 GA
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
539 // See if this value already exists in the symbol table. If so, it is either
540 // a redefinition or a definition of a forward reference.
541 if (GlobalValue
*Val
=
542 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
))) {
543 // See if this was a redefinition. If so, there is no entry in
545 std::map
<std::string
, std::pair
<GlobalValue
*, LocTy
> >::iterator
546 I
= ForwardRefVals
.find(Name
);
547 if (I
== ForwardRefVals
.end())
548 return Error(NameLoc
, "redefinition of global named '@" + Name
+ "'");
550 // Otherwise, this was a definition of forward ref. Verify that types
552 if (Val
->getType() != GA
->getType())
553 return Error(NameLoc
,
554 "forward reference and definition of alias have different types");
556 // If they agree, just RAUW the old value with the alias and remove the
558 Val
->replaceAllUsesWith(GA
);
559 Val
->eraseFromParent();
560 ForwardRefVals
.erase(I
);
563 // Insert into the module, we know its name won't collide now.
564 M
->getAliasList().push_back(GA
);
565 assert(GA
->getNameStr() == Name
&& "Should not be a name conflict!");
571 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
572 /// OptionalAddrSpace GlobalType Type Const
573 /// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
574 /// OptionalAddrSpace GlobalType Type Const
576 /// Everything through visibility has been parsed already.
578 bool LLParser::ParseGlobal(const std::string
&Name
, LocTy NameLoc
,
579 unsigned Linkage
, bool HasLinkage
,
580 unsigned Visibility
) {
582 bool ThreadLocal
, IsConstant
;
585 PATypeHolder
Ty(Type::VoidTy
);
586 if (ParseOptionalToken(lltok::kw_thread_local
, ThreadLocal
) ||
587 ParseOptionalAddrSpace(AddrSpace
) ||
588 ParseGlobalType(IsConstant
) ||
589 ParseType(Ty
, TyLoc
))
592 // If the linkage is specified and is external, then no initializer is
595 if (!HasLinkage
|| (Linkage
!= GlobalValue::DLLImportLinkage
&&
596 Linkage
!= GlobalValue::ExternalWeakLinkage
&&
597 Linkage
!= GlobalValue::ExternalLinkage
)) {
598 if (ParseGlobalValue(Ty
, Init
))
602 if (isa
<FunctionType
>(Ty
) || Ty
== Type::LabelTy
)
603 return Error(TyLoc
, "invalid type for global variable");
605 GlobalVariable
*GV
= 0;
607 // See if the global was forward referenced, if so, use the global.
609 if ((GV
= M
->getGlobalVariable(Name
, true)) &&
610 !ForwardRefVals
.erase(Name
))
611 return Error(NameLoc
, "redefinition of global '@" + Name
+ "'");
613 std::map
<unsigned, std::pair
<GlobalValue
*, LocTy
> >::iterator
614 I
= ForwardRefValIDs
.find(NumberedVals
.size());
615 if (I
!= ForwardRefValIDs
.end()) {
616 GV
= cast
<GlobalVariable
>(I
->second
.first
);
617 ForwardRefValIDs
.erase(I
);
622 GV
= new GlobalVariable(*M
, Ty
, false, GlobalValue::ExternalLinkage
, 0,
623 Name
, 0, false, AddrSpace
);
625 if (GV
->getType()->getElementType() != Ty
)
627 "forward reference and definition of global have different types");
629 // Move the forward-reference to the correct spot in the module.
630 M
->getGlobalList().splice(M
->global_end(), M
->getGlobalList(), GV
);
634 NumberedVals
.push_back(GV
);
636 // Set the parsed properties on the global.
638 GV
->setInitializer(Init
);
639 GV
->setConstant(IsConstant
);
640 GV
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
641 GV
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
642 GV
->setThreadLocal(ThreadLocal
);
644 // Parse attributes on the global.
645 while (Lex
.getKind() == lltok::comma
) {
648 if (Lex
.getKind() == lltok::kw_section
) {
650 GV
->setSection(Lex
.getStrVal());
651 if (ParseToken(lltok::StringConstant
, "expected global section string"))
653 } else if (Lex
.getKind() == lltok::kw_align
) {
655 if (ParseOptionalAlignment(Alignment
)) return true;
656 GV
->setAlignment(Alignment
);
658 TokError("unknown global variable property!");
666 //===----------------------------------------------------------------------===//
667 // GlobalValue Reference/Resolution Routines.
668 //===----------------------------------------------------------------------===//
670 /// GetGlobalVal - Get a value with the specified name or ID, creating a
671 /// forward reference record if needed. This can return null if the value
672 /// exists but does not have the right type.
673 GlobalValue
*LLParser::GetGlobalVal(const std::string
&Name
, const Type
*Ty
,
675 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
677 Error(Loc
, "global variable reference must have pointer type");
681 // Look this name up in the normal function symbol table.
683 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
));
685 // If this is a forward reference for the value, see if we already created a
686 // forward ref record.
688 std::map
<std::string
, std::pair
<GlobalValue
*, LocTy
> >::iterator
689 I
= ForwardRefVals
.find(Name
);
690 if (I
!= ForwardRefVals
.end())
691 Val
= I
->second
.first
;
694 // If we have the value in the symbol table or fwd-ref table, return it.
696 if (Val
->getType() == Ty
) return Val
;
697 Error(Loc
, "'@" + Name
+ "' defined with type '" +
698 Val
->getType()->getDescription() + "'");
702 // Otherwise, create a new forward reference for this value and remember it.
704 if (const FunctionType
*FT
= dyn_cast
<FunctionType
>(PTy
->getElementType())) {
705 // Function types can return opaque but functions can't.
706 if (isa
<OpaqueType
>(FT
->getReturnType())) {
707 Error(Loc
, "function may not return opaque type");
711 FwdVal
= Function::Create(FT
, GlobalValue::ExternalWeakLinkage
, Name
, M
);
713 FwdVal
= new GlobalVariable(*M
, PTy
->getElementType(), false,
714 GlobalValue::ExternalWeakLinkage
, 0, Name
);
717 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
721 GlobalValue
*LLParser::GetGlobalVal(unsigned ID
, const Type
*Ty
, LocTy Loc
) {
722 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
724 Error(Loc
, "global variable reference must have pointer type");
728 GlobalValue
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : 0;
730 // If this is a forward reference for the value, see if we already created a
731 // forward ref record.
733 std::map
<unsigned, std::pair
<GlobalValue
*, LocTy
> >::iterator
734 I
= ForwardRefValIDs
.find(ID
);
735 if (I
!= ForwardRefValIDs
.end())
736 Val
= I
->second
.first
;
739 // If we have the value in the symbol table or fwd-ref table, return it.
741 if (Val
->getType() == Ty
) return Val
;
742 Error(Loc
, "'@" + utostr(ID
) + "' defined with type '" +
743 Val
->getType()->getDescription() + "'");
747 // Otherwise, create a new forward reference for this value and remember it.
749 if (const FunctionType
*FT
= dyn_cast
<FunctionType
>(PTy
->getElementType())) {
750 // Function types can return opaque but functions can't.
751 if (isa
<OpaqueType
>(FT
->getReturnType())) {
752 Error(Loc
, "function may not return opaque type");
755 FwdVal
= Function::Create(FT
, GlobalValue::ExternalWeakLinkage
, "", M
);
757 FwdVal
= new GlobalVariable(*M
, PTy
->getElementType(), false,
758 GlobalValue::ExternalWeakLinkage
, 0, "");
761 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
766 //===----------------------------------------------------------------------===//
768 //===----------------------------------------------------------------------===//
770 /// ParseToken - If the current token has the specified kind, eat it and return
771 /// success. Otherwise, emit the specified error and return failure.
772 bool LLParser::ParseToken(lltok::Kind T
, const char *ErrMsg
) {
773 if (Lex
.getKind() != T
)
774 return TokError(ErrMsg
);
779 /// ParseStringConstant
780 /// ::= StringConstant
781 bool LLParser::ParseStringConstant(std::string
&Result
) {
782 if (Lex
.getKind() != lltok::StringConstant
)
783 return TokError("expected string constant");
784 Result
= Lex
.getStrVal();
791 bool LLParser::ParseUInt32(unsigned &Val
) {
792 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
793 return TokError("expected integer");
794 uint64_t Val64
= Lex
.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL
+1);
795 if (Val64
!= unsigned(Val64
))
796 return TokError("expected 32-bit integer (too large)");
803 /// ParseOptionalAddrSpace
805 /// := 'addrspace' '(' uint32 ')'
806 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace
) {
808 if (!EatIfPresent(lltok::kw_addrspace
))
810 return ParseToken(lltok::lparen
, "expected '(' in address space") ||
811 ParseUInt32(AddrSpace
) ||
812 ParseToken(lltok::rparen
, "expected ')' in address space");
815 /// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
816 /// indicates what kind of attribute list this is: 0: function arg, 1: result,
817 /// 2: function attr.
818 /// 3: function arg after value: FIXME: REMOVE IN LLVM 3.0
819 bool LLParser::ParseOptionalAttrs(unsigned &Attrs
, unsigned AttrKind
) {
820 Attrs
= Attribute::None
;
821 LocTy AttrLoc
= Lex
.getLoc();
824 switch (Lex
.getKind()) {
827 // Treat these as signext/zeroext if they occur in the argument list after
828 // the value, as in "call i8 @foo(i8 10 sext)". If they occur before the
829 // value, as in "call i8 @foo(i8 sext (" then it is part of a constant
831 // FIXME: REMOVE THIS IN LLVM 3.0
833 if (Lex
.getKind() == lltok::kw_sext
)
834 Attrs
|= Attribute::SExt
;
836 Attrs
|= Attribute::ZExt
;
840 default: // End of attributes.
841 if (AttrKind
!= 2 && (Attrs
& Attribute::FunctionOnly
))
842 return Error(AttrLoc
, "invalid use of function-only attribute");
844 if (AttrKind
!= 0 && AttrKind
!= 3 && (Attrs
& Attribute::ParameterOnly
))
845 return Error(AttrLoc
, "invalid use of parameter-only attribute");
848 case lltok::kw_zeroext
: Attrs
|= Attribute::ZExt
; break;
849 case lltok::kw_signext
: Attrs
|= Attribute::SExt
; break;
850 case lltok::kw_inreg
: Attrs
|= Attribute::InReg
; break;
851 case lltok::kw_sret
: Attrs
|= Attribute::StructRet
; break;
852 case lltok::kw_noalias
: Attrs
|= Attribute::NoAlias
; break;
853 case lltok::kw_nocapture
: Attrs
|= Attribute::NoCapture
; break;
854 case lltok::kw_byval
: Attrs
|= Attribute::ByVal
; break;
855 case lltok::kw_nest
: Attrs
|= Attribute::Nest
; break;
857 case lltok::kw_noreturn
: Attrs
|= Attribute::NoReturn
; break;
858 case lltok::kw_nounwind
: Attrs
|= Attribute::NoUnwind
; break;
859 case lltok::kw_noinline
: Attrs
|= Attribute::NoInline
; break;
860 case lltok::kw_readnone
: Attrs
|= Attribute::ReadNone
; break;
861 case lltok::kw_readonly
: Attrs
|= Attribute::ReadOnly
; break;
862 case lltok::kw_alwaysinline
: Attrs
|= Attribute::AlwaysInline
; break;
863 case lltok::kw_optsize
: Attrs
|= Attribute::OptimizeForSize
; break;
864 case lltok::kw_ssp
: Attrs
|= Attribute::StackProtect
; break;
865 case lltok::kw_sspreq
: Attrs
|= Attribute::StackProtectReq
; break;
866 case lltok::kw_noredzone
: Attrs
|= Attribute::NoRedZone
; break;
867 case lltok::kw_noimplicitfloat
: Attrs
|= Attribute::NoImplicitFloat
; break;
868 case lltok::kw_naked
: Attrs
|= Attribute::Naked
; break;
870 case lltok::kw_align
: {
872 if (ParseOptionalAlignment(Alignment
))
874 Attrs
|= Attribute::constructAlignmentFromInt(Alignment
);
882 /// ParseOptionalLinkage
885 /// ::= 'linker_private'
890 /// ::= 'linkonce_odr'
895 /// ::= 'extern_weak'
897 bool LLParser::ParseOptionalLinkage(unsigned &Res
, bool &HasLinkage
) {
899 switch (Lex
.getKind()) {
900 default: Res
=GlobalValue::ExternalLinkage
; return false;
901 case lltok::kw_private
: Res
= GlobalValue::PrivateLinkage
; break;
902 case lltok::kw_linker_private
: Res
= GlobalValue::LinkerPrivateLinkage
; break;
903 case lltok::kw_internal
: Res
= GlobalValue::InternalLinkage
; break;
904 case lltok::kw_weak
: Res
= GlobalValue::WeakAnyLinkage
; break;
905 case lltok::kw_weak_odr
: Res
= GlobalValue::WeakODRLinkage
; break;
906 case lltok::kw_linkonce
: Res
= GlobalValue::LinkOnceAnyLinkage
; break;
907 case lltok::kw_linkonce_odr
: Res
= GlobalValue::LinkOnceODRLinkage
; break;
908 case lltok::kw_available_externally
:
909 Res
= GlobalValue::AvailableExternallyLinkage
;
911 case lltok::kw_appending
: Res
= GlobalValue::AppendingLinkage
; break;
912 case lltok::kw_dllexport
: Res
= GlobalValue::DLLExportLinkage
; break;
913 case lltok::kw_common
: Res
= GlobalValue::CommonLinkage
; break;
914 case lltok::kw_dllimport
: Res
= GlobalValue::DLLImportLinkage
; break;
915 case lltok::kw_extern_weak
: Res
= GlobalValue::ExternalWeakLinkage
; break;
916 case lltok::kw_external
: Res
= GlobalValue::ExternalLinkage
; break;
923 /// ParseOptionalVisibility
929 bool LLParser::ParseOptionalVisibility(unsigned &Res
) {
930 switch (Lex
.getKind()) {
931 default: Res
= GlobalValue::DefaultVisibility
; return false;
932 case lltok::kw_default
: Res
= GlobalValue::DefaultVisibility
; break;
933 case lltok::kw_hidden
: Res
= GlobalValue::HiddenVisibility
; break;
934 case lltok::kw_protected
: Res
= GlobalValue::ProtectedVisibility
; break;
940 /// ParseOptionalCallingConv
945 /// ::= 'x86_stdcallcc'
946 /// ::= 'x86_fastcallcc'
948 /// ::= 'arm_aapcscc'
949 /// ::= 'arm_aapcs_vfpcc'
952 bool LLParser::ParseOptionalCallingConv(unsigned &CC
) {
953 switch (Lex
.getKind()) {
954 default: CC
= CallingConv::C
; return false;
955 case lltok::kw_ccc
: CC
= CallingConv::C
; break;
956 case lltok::kw_fastcc
: CC
= CallingConv::Fast
; break;
957 case lltok::kw_coldcc
: CC
= CallingConv::Cold
; break;
958 case lltok::kw_x86_stdcallcc
: CC
= CallingConv::X86_StdCall
; break;
959 case lltok::kw_x86_fastcallcc
: CC
= CallingConv::X86_FastCall
; break;
960 case lltok::kw_arm_apcscc
: CC
= CallingConv::ARM_APCS
; break;
961 case lltok::kw_arm_aapcscc
: CC
= CallingConv::ARM_AAPCS
; break;
962 case lltok::kw_arm_aapcs_vfpcc
:CC
= CallingConv::ARM_AAPCS_VFP
; break;
963 case lltok::kw_cc
: Lex
.Lex(); return ParseUInt32(CC
);
969 /// ParseOptionalAlignment
972 bool LLParser::ParseOptionalAlignment(unsigned &Alignment
) {
974 if (!EatIfPresent(lltok::kw_align
))
976 LocTy AlignLoc
= Lex
.getLoc();
977 if (ParseUInt32(Alignment
)) return true;
978 if (!isPowerOf2_32(Alignment
))
979 return Error(AlignLoc
, "alignment is not a power of two");
983 /// ParseOptionalCommaAlignment
985 /// ::= ',' 'align' 4
986 bool LLParser::ParseOptionalCommaAlignment(unsigned &Alignment
) {
988 if (!EatIfPresent(lltok::comma
))
990 return ParseToken(lltok::kw_align
, "expected 'align'") ||
991 ParseUInt32(Alignment
);
995 /// ::= (',' uint32)+
996 bool LLParser::ParseIndexList(SmallVectorImpl
<unsigned> &Indices
) {
997 if (Lex
.getKind() != lltok::comma
)
998 return TokError("expected ',' as start of index list");
1000 while (EatIfPresent(lltok::comma
)) {
1002 if (ParseUInt32(Idx
)) return true;
1003 Indices
.push_back(Idx
);
1009 //===----------------------------------------------------------------------===//
1011 //===----------------------------------------------------------------------===//
1013 /// ParseType - Parse and resolve a full type.
1014 bool LLParser::ParseType(PATypeHolder
&Result
, bool AllowVoid
) {
1015 LocTy TypeLoc
= Lex
.getLoc();
1016 if (ParseTypeRec(Result
)) return true;
1018 // Verify no unresolved uprefs.
1019 if (!UpRefs
.empty())
1020 return Error(UpRefs
.back().Loc
, "invalid unresolved type up reference");
1022 if (!AllowVoid
&& Result
.get() == Type::VoidTy
)
1023 return Error(TypeLoc
, "void type only allowed for function results");
1028 /// HandleUpRefs - Every time we finish a new layer of types, this function is
1029 /// called. It loops through the UpRefs vector, which is a list of the
1030 /// currently active types. For each type, if the up-reference is contained in
1031 /// the newly completed type, we decrement the level count. When the level
1032 /// count reaches zero, the up-referenced type is the type that is passed in:
1033 /// thus we can complete the cycle.
1035 PATypeHolder
LLParser::HandleUpRefs(const Type
*ty
) {
1036 // If Ty isn't abstract, or if there are no up-references in it, then there is
1037 // nothing to resolve here.
1038 if (!ty
->isAbstract() || UpRefs
.empty()) return ty
;
1040 PATypeHolder
Ty(ty
);
1042 errs() << "Type '" << Ty
->getDescription()
1043 << "' newly formed. Resolving upreferences.\n"
1044 << UpRefs
.size() << " upreferences active!\n";
1047 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1048 // to zero), we resolve them all together before we resolve them to Ty. At
1049 // the end of the loop, if there is anything to resolve to Ty, it will be in
1051 OpaqueType
*TypeToResolve
= 0;
1053 for (unsigned i
= 0; i
!= UpRefs
.size(); ++i
) {
1054 // Determine if 'Ty' directly contains this up-references 'LastContainedTy'.
1056 std::find(Ty
->subtype_begin(), Ty
->subtype_end(),
1057 UpRefs
[i
].LastContainedTy
) != Ty
->subtype_end();
1060 errs() << " UR#" << i
<< " - TypeContains(" << Ty
->getDescription() << ", "
1061 << UpRefs
[i
].LastContainedTy
->getDescription() << ") = "
1062 << (ContainsType
? "true" : "false")
1063 << " level=" << UpRefs
[i
].NestingLevel
<< "\n";
1068 // Decrement level of upreference
1069 unsigned Level
= --UpRefs
[i
].NestingLevel
;
1070 UpRefs
[i
].LastContainedTy
= Ty
;
1072 // If the Up-reference has a non-zero level, it shouldn't be resolved yet.
1077 errs() << " * Resolving upreference for " << UpRefs
[i
].UpRefTy
<< "\n";
1080 TypeToResolve
= UpRefs
[i
].UpRefTy
;
1082 UpRefs
[i
].UpRefTy
->refineAbstractTypeTo(TypeToResolve
);
1083 UpRefs
.erase(UpRefs
.begin()+i
); // Remove from upreference list.
1084 --i
; // Do not skip the next element.
1088 TypeToResolve
->refineAbstractTypeTo(Ty
);
1094 /// ParseTypeRec - The recursive function used to process the internal
1095 /// implementation details of types.
1096 bool LLParser::ParseTypeRec(PATypeHolder
&Result
) {
1097 switch (Lex
.getKind()) {
1099 return TokError("expected type");
1101 // TypeRec ::= 'float' | 'void' (etc)
1102 Result
= Lex
.getTyVal();
1105 case lltok::kw_opaque
:
1106 // TypeRec ::= 'opaque'
1107 Result
= OpaqueType::get();
1111 // TypeRec ::= '{' ... '}'
1112 if (ParseStructType(Result
, false))
1115 case lltok::lsquare
:
1116 // TypeRec ::= '[' ... ']'
1117 Lex
.Lex(); // eat the lsquare.
1118 if (ParseArrayVectorType(Result
, false))
1121 case lltok::less
: // Either vector or packed struct.
1122 // TypeRec ::= '<' ... '>'
1124 if (Lex
.getKind() == lltok::lbrace
) {
1125 if (ParseStructType(Result
, true) ||
1126 ParseToken(lltok::greater
, "expected '>' at end of packed struct"))
1128 } else if (ParseArrayVectorType(Result
, true))
1131 case lltok::LocalVar
:
1132 case lltok::StringConstant
: // FIXME: REMOVE IN LLVM 3.0
1134 if (const Type
*T
= M
->getTypeByName(Lex
.getStrVal())) {
1137 Result
= OpaqueType::get();
1138 ForwardRefTypes
.insert(std::make_pair(Lex
.getStrVal(),
1139 std::make_pair(Result
,
1141 M
->addTypeName(Lex
.getStrVal(), Result
.get());
1146 case lltok::LocalVarID
:
1148 if (Lex
.getUIntVal() < NumberedTypes
.size())
1149 Result
= NumberedTypes
[Lex
.getUIntVal()];
1151 std::map
<unsigned, std::pair
<PATypeHolder
, LocTy
> >::iterator
1152 I
= ForwardRefTypeIDs
.find(Lex
.getUIntVal());
1153 if (I
!= ForwardRefTypeIDs
.end())
1154 Result
= I
->second
.first
;
1156 Result
= OpaqueType::get();
1157 ForwardRefTypeIDs
.insert(std::make_pair(Lex
.getUIntVal(),
1158 std::make_pair(Result
,
1164 case lltok::backslash
: {
1165 // TypeRec ::= '\' 4
1168 if (ParseUInt32(Val
)) return true;
1169 OpaqueType
*OT
= OpaqueType::get(); //Use temporary placeholder.
1170 UpRefs
.push_back(UpRefRecord(Lex
.getLoc(), Val
, OT
));
1176 // Parse the type suffixes.
1178 switch (Lex
.getKind()) {
1180 default: return false;
1182 // TypeRec ::= TypeRec '*'
1184 if (Result
.get() == Type::LabelTy
)
1185 return TokError("basic block pointers are invalid");
1186 if (Result
.get() == Type::VoidTy
)
1187 return TokError("pointers to void are invalid; use i8* instead");
1188 if (!PointerType::isValidElementType(Result
.get()))
1189 return TokError("pointer to this type is invalid");
1190 Result
= HandleUpRefs(PointerType::getUnqual(Result
.get()));
1194 // TypeRec ::= TypeRec 'addrspace' '(' uint32 ')' '*'
1195 case lltok::kw_addrspace
: {
1196 if (Result
.get() == Type::LabelTy
)
1197 return TokError("basic block pointers are invalid");
1198 if (Result
.get() == Type::VoidTy
)
1199 return TokError("pointers to void are invalid; use i8* instead");
1200 if (!PointerType::isValidElementType(Result
.get()))
1201 return TokError("pointer to this type is invalid");
1203 if (ParseOptionalAddrSpace(AddrSpace
) ||
1204 ParseToken(lltok::star
, "expected '*' in address space"))
1207 Result
= HandleUpRefs(PointerType::get(Result
.get(), AddrSpace
));
1211 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1213 if (ParseFunctionType(Result
))
1220 /// ParseParameterList
1222 /// ::= '(' Arg (',' Arg)* ')'
1224 /// ::= Type OptionalAttributes Value OptionalAttributes
1225 bool LLParser::ParseParameterList(SmallVectorImpl
<ParamInfo
> &ArgList
,
1226 PerFunctionState
&PFS
) {
1227 if (ParseToken(lltok::lparen
, "expected '(' in call"))
1230 while (Lex
.getKind() != lltok::rparen
) {
1231 // If this isn't the first argument, we need a comma.
1232 if (!ArgList
.empty() &&
1233 ParseToken(lltok::comma
, "expected ',' in argument list"))
1236 // Parse the argument.
1238 PATypeHolder
ArgTy(Type::VoidTy
);
1239 unsigned ArgAttrs1
, ArgAttrs2
;
1241 if (ParseType(ArgTy
, ArgLoc
) ||
1242 ParseOptionalAttrs(ArgAttrs1
, 0) ||
1243 ParseValue(ArgTy
, V
, PFS
) ||
1244 // FIXME: Should not allow attributes after the argument, remove this in
1246 ParseOptionalAttrs(ArgAttrs2
, 3))
1248 ArgList
.push_back(ParamInfo(ArgLoc
, V
, ArgAttrs1
|ArgAttrs2
));
1251 Lex
.Lex(); // Lex the ')'.
1257 /// ParseArgumentList - Parse the argument list for a function type or function
1258 /// prototype. If 'inType' is true then we are parsing a FunctionType.
1259 /// ::= '(' ArgTypeListI ')'
1263 /// ::= ArgTypeList ',' '...'
1264 /// ::= ArgType (',' ArgType)*
1266 bool LLParser::ParseArgumentList(std::vector
<ArgInfo
> &ArgList
,
1267 bool &isVarArg
, bool inType
) {
1269 assert(Lex
.getKind() == lltok::lparen
);
1270 Lex
.Lex(); // eat the (.
1272 if (Lex
.getKind() == lltok::rparen
) {
1274 } else if (Lex
.getKind() == lltok::dotdotdot
) {
1278 LocTy TypeLoc
= Lex
.getLoc();
1279 PATypeHolder
ArgTy(Type::VoidTy
);
1283 // If we're parsing a type, use ParseTypeRec, because we allow recursive
1284 // types (such as a function returning a pointer to itself). If parsing a
1285 // function prototype, we require fully resolved types.
1286 if ((inType
? ParseTypeRec(ArgTy
) : ParseType(ArgTy
)) ||
1287 ParseOptionalAttrs(Attrs
, 0)) return true;
1289 if (ArgTy
== Type::VoidTy
)
1290 return Error(TypeLoc
, "argument can not have void type");
1292 if (Lex
.getKind() == lltok::LocalVar
||
1293 Lex
.getKind() == lltok::StringConstant
) { // FIXME: REMOVE IN LLVM 3.0
1294 Name
= Lex
.getStrVal();
1298 if (!FunctionType::isValidArgumentType(ArgTy
))
1299 return Error(TypeLoc
, "invalid type for function argument");
1301 ArgList
.push_back(ArgInfo(TypeLoc
, ArgTy
, Attrs
, Name
));
1303 while (EatIfPresent(lltok::comma
)) {
1304 // Handle ... at end of arg list.
1305 if (EatIfPresent(lltok::dotdotdot
)) {
1310 // Otherwise must be an argument type.
1311 TypeLoc
= Lex
.getLoc();
1312 if ((inType
? ParseTypeRec(ArgTy
) : ParseType(ArgTy
)) ||
1313 ParseOptionalAttrs(Attrs
, 0)) return true;
1315 if (ArgTy
== Type::VoidTy
)
1316 return Error(TypeLoc
, "argument can not have void type");
1318 if (Lex
.getKind() == lltok::LocalVar
||
1319 Lex
.getKind() == lltok::StringConstant
) { // FIXME: REMOVE IN LLVM 3.0
1320 Name
= Lex
.getStrVal();
1326 if (!ArgTy
->isFirstClassType() && !isa
<OpaqueType
>(ArgTy
))
1327 return Error(TypeLoc
, "invalid type for function argument");
1329 ArgList
.push_back(ArgInfo(TypeLoc
, ArgTy
, Attrs
, Name
));
1333 return ParseToken(lltok::rparen
, "expected ')' at end of argument list");
1336 /// ParseFunctionType
1337 /// ::= Type ArgumentList OptionalAttrs
1338 bool LLParser::ParseFunctionType(PATypeHolder
&Result
) {
1339 assert(Lex
.getKind() == lltok::lparen
);
1341 if (!FunctionType::isValidReturnType(Result
))
1342 return TokError("invalid function return type");
1344 std::vector
<ArgInfo
> ArgList
;
1347 if (ParseArgumentList(ArgList
, isVarArg
, true) ||
1348 // FIXME: Allow, but ignore attributes on function types!
1349 // FIXME: Remove in LLVM 3.0
1350 ParseOptionalAttrs(Attrs
, 2))
1353 // Reject names on the arguments lists.
1354 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
1355 if (!ArgList
[i
].Name
.empty())
1356 return Error(ArgList
[i
].Loc
, "argument name invalid in function type");
1357 if (!ArgList
[i
].Attrs
!= 0) {
1358 // Allow but ignore attributes on function types; this permits
1360 // FIXME: REJECT ATTRIBUTES ON FUNCTION TYPES in LLVM 3.0
1364 std::vector
<const Type
*> ArgListTy
;
1365 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
1366 ArgListTy
.push_back(ArgList
[i
].Type
);
1368 Result
= HandleUpRefs(FunctionType::get(Result
.get(),
1369 ArgListTy
, isVarArg
));
1373 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1376 /// ::= '{' TypeRec (',' TypeRec)* '}'
1377 /// ::= '<' '{' '}' '>'
1378 /// ::= '<' '{' TypeRec (',' TypeRec)* '}' '>'
1379 bool LLParser::ParseStructType(PATypeHolder
&Result
, bool Packed
) {
1380 assert(Lex
.getKind() == lltok::lbrace
);
1381 Lex
.Lex(); // Consume the '{'
1383 if (EatIfPresent(lltok::rbrace
)) {
1384 Result
= StructType::get(Packed
);
1388 std::vector
<PATypeHolder
> ParamsList
;
1389 LocTy EltTyLoc
= Lex
.getLoc();
1390 if (ParseTypeRec(Result
)) return true;
1391 ParamsList
.push_back(Result
);
1393 if (Result
== Type::VoidTy
)
1394 return Error(EltTyLoc
, "struct element can not have void type");
1395 if (!StructType::isValidElementType(Result
))
1396 return Error(EltTyLoc
, "invalid element type for struct");
1398 while (EatIfPresent(lltok::comma
)) {
1399 EltTyLoc
= Lex
.getLoc();
1400 if (ParseTypeRec(Result
)) return true;
1402 if (Result
== Type::VoidTy
)
1403 return Error(EltTyLoc
, "struct element can not have void type");
1404 if (!StructType::isValidElementType(Result
))
1405 return Error(EltTyLoc
, "invalid element type for struct");
1407 ParamsList
.push_back(Result
);
1410 if (ParseToken(lltok::rbrace
, "expected '}' at end of struct"))
1413 std::vector
<const Type
*> ParamsListTy
;
1414 for (unsigned i
= 0, e
= ParamsList
.size(); i
!= e
; ++i
)
1415 ParamsListTy
.push_back(ParamsList
[i
].get());
1416 Result
= HandleUpRefs(StructType::get(ParamsListTy
, Packed
));
1420 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1421 /// token has already been consumed.
1423 /// ::= '[' APSINTVAL 'x' Types ']'
1424 /// ::= '<' APSINTVAL 'x' Types '>'
1425 bool LLParser::ParseArrayVectorType(PATypeHolder
&Result
, bool isVector
) {
1426 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned() ||
1427 Lex
.getAPSIntVal().getBitWidth() > 64)
1428 return TokError("expected number in address space");
1430 LocTy SizeLoc
= Lex
.getLoc();
1431 uint64_t Size
= Lex
.getAPSIntVal().getZExtValue();
1434 if (ParseToken(lltok::kw_x
, "expected 'x' after element count"))
1437 LocTy TypeLoc
= Lex
.getLoc();
1438 PATypeHolder
EltTy(Type::VoidTy
);
1439 if (ParseTypeRec(EltTy
)) return true;
1441 if (EltTy
== Type::VoidTy
)
1442 return Error(TypeLoc
, "array and vector element type cannot be void");
1444 if (ParseToken(isVector
? lltok::greater
: lltok::rsquare
,
1445 "expected end of sequential type"))
1450 return Error(SizeLoc
, "zero element vector is illegal");
1451 if ((unsigned)Size
!= Size
)
1452 return Error(SizeLoc
, "size too large for vector");
1453 if (!VectorType::isValidElementType(EltTy
))
1454 return Error(TypeLoc
, "vector element type must be fp or integer");
1455 Result
= VectorType::get(EltTy
, unsigned(Size
));
1457 if (!ArrayType::isValidElementType(EltTy
))
1458 return Error(TypeLoc
, "invalid array element type");
1459 Result
= HandleUpRefs(ArrayType::get(EltTy
, Size
));
1464 //===----------------------------------------------------------------------===//
1465 // Function Semantic Analysis.
1466 //===----------------------------------------------------------------------===//
1468 LLParser::PerFunctionState::PerFunctionState(LLParser
&p
, Function
&f
)
1471 // Insert unnamed arguments into the NumberedVals list.
1472 for (Function::arg_iterator AI
= F
.arg_begin(), E
= F
.arg_end();
1475 NumberedVals
.push_back(AI
);
1478 LLParser::PerFunctionState::~PerFunctionState() {
1479 // If there were any forward referenced non-basicblock values, delete them.
1480 for (std::map
<std::string
, std::pair
<Value
*, LocTy
> >::iterator
1481 I
= ForwardRefVals
.begin(), E
= ForwardRefVals
.end(); I
!= E
; ++I
)
1482 if (!isa
<BasicBlock
>(I
->second
.first
)) {
1483 I
->second
.first
->replaceAllUsesWith(
1484 UndefValue::get(I
->second
.first
->getType()));
1485 delete I
->second
.first
;
1486 I
->second
.first
= 0;
1489 for (std::map
<unsigned, std::pair
<Value
*, LocTy
> >::iterator
1490 I
= ForwardRefValIDs
.begin(), E
= ForwardRefValIDs
.end(); I
!= E
; ++I
)
1491 if (!isa
<BasicBlock
>(I
->second
.first
)) {
1492 I
->second
.first
->replaceAllUsesWith(
1493 UndefValue::get(I
->second
.first
->getType()));
1494 delete I
->second
.first
;
1495 I
->second
.first
= 0;
1499 bool LLParser::PerFunctionState::VerifyFunctionComplete() {
1500 if (!ForwardRefVals
.empty())
1501 return P
.Error(ForwardRefVals
.begin()->second
.second
,
1502 "use of undefined value '%" + ForwardRefVals
.begin()->first
+
1504 if (!ForwardRefValIDs
.empty())
1505 return P
.Error(ForwardRefValIDs
.begin()->second
.second
,
1506 "use of undefined value '%" +
1507 utostr(ForwardRefValIDs
.begin()->first
) + "'");
1512 /// GetVal - Get a value with the specified name or ID, creating a
1513 /// forward reference record if needed. This can return null if the value
1514 /// exists but does not have the right type.
1515 Value
*LLParser::PerFunctionState::GetVal(const std::string
&Name
,
1516 const Type
*Ty
, LocTy Loc
) {
1517 // Look this name up in the normal function symbol table.
1518 Value
*Val
= F
.getValueSymbolTable().lookup(Name
);
1520 // If this is a forward reference for the value, see if we already created a
1521 // forward ref record.
1523 std::map
<std::string
, std::pair
<Value
*, LocTy
> >::iterator
1524 I
= ForwardRefVals
.find(Name
);
1525 if (I
!= ForwardRefVals
.end())
1526 Val
= I
->second
.first
;
1529 // If we have the value in the symbol table or fwd-ref table, return it.
1531 if (Val
->getType() == Ty
) return Val
;
1532 if (Ty
== Type::LabelTy
)
1533 P
.Error(Loc
, "'%" + Name
+ "' is not a basic block");
1535 P
.Error(Loc
, "'%" + Name
+ "' defined with type '" +
1536 Val
->getType()->getDescription() + "'");
1540 // Don't make placeholders with invalid type.
1541 if (!Ty
->isFirstClassType() && !isa
<OpaqueType
>(Ty
) && Ty
!= Type::LabelTy
) {
1542 P
.Error(Loc
, "invalid use of a non-first-class type");
1546 // Otherwise, create a new forward reference for this value and remember it.
1548 if (Ty
== Type::LabelTy
)
1549 FwdVal
= BasicBlock::Create(Name
, &F
);
1551 FwdVal
= new Argument(Ty
, Name
);
1553 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
1557 Value
*LLParser::PerFunctionState::GetVal(unsigned ID
, const Type
*Ty
,
1559 // Look this name up in the normal function symbol table.
1560 Value
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : 0;
1562 // If this is a forward reference for the value, see if we already created a
1563 // forward ref record.
1565 std::map
<unsigned, std::pair
<Value
*, LocTy
> >::iterator
1566 I
= ForwardRefValIDs
.find(ID
);
1567 if (I
!= ForwardRefValIDs
.end())
1568 Val
= I
->second
.first
;
1571 // If we have the value in the symbol table or fwd-ref table, return it.
1573 if (Val
->getType() == Ty
) return Val
;
1574 if (Ty
== Type::LabelTy
)
1575 P
.Error(Loc
, "'%" + utostr(ID
) + "' is not a basic block");
1577 P
.Error(Loc
, "'%" + utostr(ID
) + "' defined with type '" +
1578 Val
->getType()->getDescription() + "'");
1582 if (!Ty
->isFirstClassType() && !isa
<OpaqueType
>(Ty
) && Ty
!= Type::LabelTy
) {
1583 P
.Error(Loc
, "invalid use of a non-first-class type");
1587 // Otherwise, create a new forward reference for this value and remember it.
1589 if (Ty
== Type::LabelTy
)
1590 FwdVal
= BasicBlock::Create("", &F
);
1592 FwdVal
= new Argument(Ty
);
1594 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
1598 /// SetInstName - After an instruction is parsed and inserted into its
1599 /// basic block, this installs its name.
1600 bool LLParser::PerFunctionState::SetInstName(int NameID
,
1601 const std::string
&NameStr
,
1602 LocTy NameLoc
, Instruction
*Inst
) {
1603 // If this instruction has void type, it cannot have a name or ID specified.
1604 if (Inst
->getType() == Type::VoidTy
) {
1605 if (NameID
!= -1 || !NameStr
.empty())
1606 return P
.Error(NameLoc
, "instructions returning void cannot have a name");
1610 // If this was a numbered instruction, verify that the instruction is the
1611 // expected value and resolve any forward references.
1612 if (NameStr
.empty()) {
1613 // If neither a name nor an ID was specified, just use the next ID.
1615 NameID
= NumberedVals
.size();
1617 if (unsigned(NameID
) != NumberedVals
.size())
1618 return P
.Error(NameLoc
, "instruction expected to be numbered '%" +
1619 utostr(NumberedVals
.size()) + "'");
1621 std::map
<unsigned, std::pair
<Value
*, LocTy
> >::iterator FI
=
1622 ForwardRefValIDs
.find(NameID
);
1623 if (FI
!= ForwardRefValIDs
.end()) {
1624 if (FI
->second
.first
->getType() != Inst
->getType())
1625 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
1626 FI
->second
.first
->getType()->getDescription() + "'");
1627 FI
->second
.first
->replaceAllUsesWith(Inst
);
1628 ForwardRefValIDs
.erase(FI
);
1631 NumberedVals
.push_back(Inst
);
1635 // Otherwise, the instruction had a name. Resolve forward refs and set it.
1636 std::map
<std::string
, std::pair
<Value
*, LocTy
> >::iterator
1637 FI
= ForwardRefVals
.find(NameStr
);
1638 if (FI
!= ForwardRefVals
.end()) {
1639 if (FI
->second
.first
->getType() != Inst
->getType())
1640 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
1641 FI
->second
.first
->getType()->getDescription() + "'");
1642 FI
->second
.first
->replaceAllUsesWith(Inst
);
1643 ForwardRefVals
.erase(FI
);
1646 // Set the name on the instruction.
1647 Inst
->setName(NameStr
);
1649 if (Inst
->getNameStr() != NameStr
)
1650 return P
.Error(NameLoc
, "multiple definition of local value named '" +
1655 /// GetBB - Get a basic block with the specified name or ID, creating a
1656 /// forward reference record if needed.
1657 BasicBlock
*LLParser::PerFunctionState::GetBB(const std::string
&Name
,
1659 return cast_or_null
<BasicBlock
>(GetVal(Name
, Type::LabelTy
, Loc
));
1662 BasicBlock
*LLParser::PerFunctionState::GetBB(unsigned ID
, LocTy Loc
) {
1663 return cast_or_null
<BasicBlock
>(GetVal(ID
, Type::LabelTy
, Loc
));
1666 /// DefineBB - Define the specified basic block, which is either named or
1667 /// unnamed. If there is an error, this returns null otherwise it returns
1668 /// the block being defined.
1669 BasicBlock
*LLParser::PerFunctionState::DefineBB(const std::string
&Name
,
1673 BB
= GetBB(NumberedVals
.size(), Loc
);
1675 BB
= GetBB(Name
, Loc
);
1676 if (BB
== 0) return 0; // Already diagnosed error.
1678 // Move the block to the end of the function. Forward ref'd blocks are
1679 // inserted wherever they happen to be referenced.
1680 F
.getBasicBlockList().splice(F
.end(), F
.getBasicBlockList(), BB
);
1682 // Remove the block from forward ref sets.
1684 ForwardRefValIDs
.erase(NumberedVals
.size());
1685 NumberedVals
.push_back(BB
);
1687 // BB forward references are already in the function symbol table.
1688 ForwardRefVals
.erase(Name
);
1694 //===----------------------------------------------------------------------===//
1696 //===----------------------------------------------------------------------===//
1698 /// ParseValID - Parse an abstract value that doesn't necessarily have a
1699 /// type implied. For example, if we parse "4" we don't know what integer type
1700 /// it has. The value will later be combined with its type and checked for
1702 bool LLParser::ParseValID(ValID
&ID
) {
1703 ID
.Loc
= Lex
.getLoc();
1704 switch (Lex
.getKind()) {
1705 default: return TokError("expected value token");
1706 case lltok::GlobalID
: // @42
1707 ID
.UIntVal
= Lex
.getUIntVal();
1708 ID
.Kind
= ValID::t_GlobalID
;
1710 case lltok::GlobalVar
: // @foo
1711 ID
.StrVal
= Lex
.getStrVal();
1712 ID
.Kind
= ValID::t_GlobalName
;
1714 case lltok::LocalVarID
: // %42
1715 ID
.UIntVal
= Lex
.getUIntVal();
1716 ID
.Kind
= ValID::t_LocalID
;
1718 case lltok::LocalVar
: // %foo
1719 case lltok::StringConstant
: // "foo" - FIXME: REMOVE IN LLVM 3.0
1720 ID
.StrVal
= Lex
.getStrVal();
1721 ID
.Kind
= ValID::t_LocalName
;
1723 case lltok::Metadata
: { // !{...} MDNode, !"foo" MDString
1724 ID
.Kind
= ValID::t_Metadata
;
1726 if (Lex
.getKind() == lltok::lbrace
) {
1727 SmallVector
<Value
*, 16> Elts
;
1728 if (ParseMDNodeVector(Elts
) ||
1729 ParseToken(lltok::rbrace
, "expected end of metadata node"))
1732 ID
.MetadataVal
= MDNode::get(Context
, Elts
.data(), Elts
.size());
1736 // Standalone metadata reference
1737 // !{ ..., !42, ... }
1738 if (!ParseMDNode(ID
.MetadataVal
))
1742 // ::= '!' STRINGCONSTANT
1743 if (ParseMDString(ID
.MetadataVal
)) return true;
1744 ID
.Kind
= ValID::t_Metadata
;
1748 ID
.APSIntVal
= Lex
.getAPSIntVal();
1749 ID
.Kind
= ValID::t_APSInt
;
1751 case lltok::APFloat
:
1752 ID
.APFloatVal
= Lex
.getAPFloatVal();
1753 ID
.Kind
= ValID::t_APFloat
;
1755 case lltok::kw_true
:
1756 ID
.ConstantVal
= ConstantInt::getTrue(Context
);
1757 ID
.Kind
= ValID::t_Constant
;
1759 case lltok::kw_false
:
1760 ID
.ConstantVal
= ConstantInt::getFalse(Context
);
1761 ID
.Kind
= ValID::t_Constant
;
1763 case lltok::kw_null
: ID
.Kind
= ValID::t_Null
; break;
1764 case lltok::kw_undef
: ID
.Kind
= ValID::t_Undef
; break;
1765 case lltok::kw_zeroinitializer
: ID
.Kind
= ValID::t_Zero
; break;
1767 case lltok::lbrace
: {
1768 // ValID ::= '{' ConstVector '}'
1770 SmallVector
<Constant
*, 16> Elts
;
1771 if (ParseGlobalValueVector(Elts
) ||
1772 ParseToken(lltok::rbrace
, "expected end of struct constant"))
1775 ID
.ConstantVal
= ConstantStruct::get(Elts
.data(), Elts
.size(), false);
1776 ID
.Kind
= ValID::t_Constant
;
1780 // ValID ::= '<' ConstVector '>' --> Vector.
1781 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
1783 bool isPackedStruct
= EatIfPresent(lltok::lbrace
);
1785 SmallVector
<Constant
*, 16> Elts
;
1786 LocTy FirstEltLoc
= Lex
.getLoc();
1787 if (ParseGlobalValueVector(Elts
) ||
1789 ParseToken(lltok::rbrace
, "expected end of packed struct")) ||
1790 ParseToken(lltok::greater
, "expected end of constant"))
1793 if (isPackedStruct
) {
1795 ConstantStruct::get(Elts
.data(), Elts
.size(), true);
1796 ID
.Kind
= ValID::t_Constant
;
1801 return Error(ID
.Loc
, "constant vector must not be empty");
1803 if (!Elts
[0]->getType()->isInteger() &&
1804 !Elts
[0]->getType()->isFloatingPoint())
1805 return Error(FirstEltLoc
,
1806 "vector elements must have integer or floating point type");
1808 // Verify that all the vector elements have the same type.
1809 for (unsigned i
= 1, e
= Elts
.size(); i
!= e
; ++i
)
1810 if (Elts
[i
]->getType() != Elts
[0]->getType())
1811 return Error(FirstEltLoc
,
1812 "vector element #" + utostr(i
) +
1813 " is not of type '" + Elts
[0]->getType()->getDescription());
1815 ID
.ConstantVal
= ConstantVector::get(Elts
.data(), Elts
.size());
1816 ID
.Kind
= ValID::t_Constant
;
1819 case lltok::lsquare
: { // Array Constant
1821 SmallVector
<Constant
*, 16> Elts
;
1822 LocTy FirstEltLoc
= Lex
.getLoc();
1823 if (ParseGlobalValueVector(Elts
) ||
1824 ParseToken(lltok::rsquare
, "expected end of array constant"))
1827 // Handle empty element.
1829 // Use undef instead of an array because it's inconvenient to determine
1830 // the element type at this point, there being no elements to examine.
1831 ID
.Kind
= ValID::t_EmptyArray
;
1835 if (!Elts
[0]->getType()->isFirstClassType())
1836 return Error(FirstEltLoc
, "invalid array element type: " +
1837 Elts
[0]->getType()->getDescription());
1839 ArrayType
*ATy
= ArrayType::get(Elts
[0]->getType(), Elts
.size());
1841 // Verify all elements are correct type!
1842 for (unsigned i
= 0, e
= Elts
.size(); i
!= e
; ++i
) {
1843 if (Elts
[i
]->getType() != Elts
[0]->getType())
1844 return Error(FirstEltLoc
,
1845 "array element #" + utostr(i
) +
1846 " is not of type '" +Elts
[0]->getType()->getDescription());
1849 ID
.ConstantVal
= ConstantArray::get(ATy
, Elts
.data(), Elts
.size());
1850 ID
.Kind
= ValID::t_Constant
;
1853 case lltok::kw_c
: // c "foo"
1855 ID
.ConstantVal
= ConstantArray::get(Lex
.getStrVal(), false);
1856 if (ParseToken(lltok::StringConstant
, "expected string")) return true;
1857 ID
.Kind
= ValID::t_Constant
;
1860 case lltok::kw_asm
: {
1861 // ValID ::= 'asm' SideEffect? STRINGCONSTANT ',' STRINGCONSTANT
1864 if (ParseOptionalToken(lltok::kw_sideeffect
, HasSideEffect
) ||
1865 ParseStringConstant(ID
.StrVal
) ||
1866 ParseToken(lltok::comma
, "expected comma in inline asm expression") ||
1867 ParseToken(lltok::StringConstant
, "expected constraint string"))
1869 ID
.StrVal2
= Lex
.getStrVal();
1870 ID
.UIntVal
= HasSideEffect
;
1871 ID
.Kind
= ValID::t_InlineAsm
;
1875 case lltok::kw_trunc
:
1876 case lltok::kw_zext
:
1877 case lltok::kw_sext
:
1878 case lltok::kw_fptrunc
:
1879 case lltok::kw_fpext
:
1880 case lltok::kw_bitcast
:
1881 case lltok::kw_uitofp
:
1882 case lltok::kw_sitofp
:
1883 case lltok::kw_fptoui
:
1884 case lltok::kw_fptosi
:
1885 case lltok::kw_inttoptr
:
1886 case lltok::kw_ptrtoint
: {
1887 unsigned Opc
= Lex
.getUIntVal();
1888 PATypeHolder
DestTy(Type::VoidTy
);
1891 if (ParseToken(lltok::lparen
, "expected '(' after constantexpr cast") ||
1892 ParseGlobalTypeAndValue(SrcVal
) ||
1893 ParseToken(lltok::kw_to
, "expected 'to' in constantexpr cast") ||
1894 ParseType(DestTy
) ||
1895 ParseToken(lltok::rparen
, "expected ')' at end of constantexpr cast"))
1897 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, SrcVal
, DestTy
))
1898 return Error(ID
.Loc
, "invalid cast opcode for cast from '" +
1899 SrcVal
->getType()->getDescription() + "' to '" +
1900 DestTy
->getDescription() + "'");
1901 ID
.ConstantVal
= ConstantExpr::getCast((Instruction::CastOps
)Opc
,
1903 ID
.Kind
= ValID::t_Constant
;
1906 case lltok::kw_extractvalue
: {
1909 SmallVector
<unsigned, 4> Indices
;
1910 if (ParseToken(lltok::lparen
, "expected '(' in extractvalue constantexpr")||
1911 ParseGlobalTypeAndValue(Val
) ||
1912 ParseIndexList(Indices
) ||
1913 ParseToken(lltok::rparen
, "expected ')' in extractvalue constantexpr"))
1915 if (!isa
<StructType
>(Val
->getType()) && !isa
<ArrayType
>(Val
->getType()))
1916 return Error(ID
.Loc
, "extractvalue operand must be array or struct");
1917 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
.begin(),
1919 return Error(ID
.Loc
, "invalid indices for extractvalue");
1921 ConstantExpr::getExtractValue(Val
, Indices
.data(), Indices
.size());
1922 ID
.Kind
= ValID::t_Constant
;
1925 case lltok::kw_insertvalue
: {
1927 Constant
*Val0
, *Val1
;
1928 SmallVector
<unsigned, 4> Indices
;
1929 if (ParseToken(lltok::lparen
, "expected '(' in insertvalue constantexpr")||
1930 ParseGlobalTypeAndValue(Val0
) ||
1931 ParseToken(lltok::comma
, "expected comma in insertvalue constantexpr")||
1932 ParseGlobalTypeAndValue(Val1
) ||
1933 ParseIndexList(Indices
) ||
1934 ParseToken(lltok::rparen
, "expected ')' in insertvalue constantexpr"))
1936 if (!isa
<StructType
>(Val0
->getType()) && !isa
<ArrayType
>(Val0
->getType()))
1937 return Error(ID
.Loc
, "extractvalue operand must be array or struct");
1938 if (!ExtractValueInst::getIndexedType(Val0
->getType(), Indices
.begin(),
1940 return Error(ID
.Loc
, "invalid indices for insertvalue");
1941 ID
.ConstantVal
= ConstantExpr::getInsertValue(Val0
, Val1
,
1942 Indices
.data(), Indices
.size());
1943 ID
.Kind
= ValID::t_Constant
;
1946 case lltok::kw_icmp
:
1947 case lltok::kw_fcmp
: {
1948 unsigned PredVal
, Opc
= Lex
.getUIntVal();
1949 Constant
*Val0
, *Val1
;
1951 if (ParseCmpPredicate(PredVal
, Opc
) ||
1952 ParseToken(lltok::lparen
, "expected '(' in compare constantexpr") ||
1953 ParseGlobalTypeAndValue(Val0
) ||
1954 ParseToken(lltok::comma
, "expected comma in compare constantexpr") ||
1955 ParseGlobalTypeAndValue(Val1
) ||
1956 ParseToken(lltok::rparen
, "expected ')' in compare constantexpr"))
1959 if (Val0
->getType() != Val1
->getType())
1960 return Error(ID
.Loc
, "compare operands must have the same type");
1962 CmpInst::Predicate Pred
= (CmpInst::Predicate
)PredVal
;
1964 if (Opc
== Instruction::FCmp
) {
1965 if (!Val0
->getType()->isFPOrFPVector())
1966 return Error(ID
.Loc
, "fcmp requires floating point operands");
1967 ID
.ConstantVal
= ConstantExpr::getFCmp(Pred
, Val0
, Val1
);
1969 assert(Opc
== Instruction::ICmp
&& "Unexpected opcode for CmpInst!");
1970 if (!Val0
->getType()->isIntOrIntVector() &&
1971 !isa
<PointerType
>(Val0
->getType()))
1972 return Error(ID
.Loc
, "icmp requires pointer or integer operands");
1973 ID
.ConstantVal
= ConstantExpr::getICmp(Pred
, Val0
, Val1
);
1975 ID
.Kind
= ValID::t_Constant
;
1979 // Binary Operators.
1981 case lltok::kw_fadd
:
1983 case lltok::kw_fsub
:
1985 case lltok::kw_fmul
:
1986 case lltok::kw_udiv
:
1987 case lltok::kw_sdiv
:
1988 case lltok::kw_fdiv
:
1989 case lltok::kw_urem
:
1990 case lltok::kw_srem
:
1991 case lltok::kw_frem
: {
1995 unsigned Opc
= Lex
.getUIntVal();
1996 Constant
*Val0
, *Val1
;
1998 LocTy ModifierLoc
= Lex
.getLoc();
1999 if (Opc
== Instruction::Add
||
2000 Opc
== Instruction::Sub
||
2001 Opc
== Instruction::Mul
) {
2002 if (EatIfPresent(lltok::kw_nuw
))
2004 if (EatIfPresent(lltok::kw_nsw
)) {
2006 if (EatIfPresent(lltok::kw_nuw
))
2009 } else if (Opc
== Instruction::SDiv
) {
2010 if (EatIfPresent(lltok::kw_exact
))
2013 if (ParseToken(lltok::lparen
, "expected '(' in binary constantexpr") ||
2014 ParseGlobalTypeAndValue(Val0
) ||
2015 ParseToken(lltok::comma
, "expected comma in binary constantexpr") ||
2016 ParseGlobalTypeAndValue(Val1
) ||
2017 ParseToken(lltok::rparen
, "expected ')' in binary constantexpr"))
2019 if (Val0
->getType() != Val1
->getType())
2020 return Error(ID
.Loc
, "operands of constexpr must have same type");
2021 if (!Val0
->getType()->isIntOrIntVector()) {
2023 return Error(ModifierLoc
, "nuw only applies to integer operations");
2025 return Error(ModifierLoc
, "nsw only applies to integer operations");
2027 // API compatibility: Accept either integer or floating-point types with
2028 // add, sub, and mul.
2029 if (!Val0
->getType()->isIntOrIntVector() &&
2030 !Val0
->getType()->isFPOrFPVector())
2031 return Error(ID
.Loc
,"constexpr requires integer, fp, or vector operands");
2032 Constant
*C
= ConstantExpr::get(Opc
, Val0
, Val1
);
2034 cast
<OverflowingBinaryOperator
>(C
)->setHasNoUnsignedOverflow(true);
2036 cast
<OverflowingBinaryOperator
>(C
)->setHasNoSignedOverflow(true);
2038 cast
<SDivOperator
>(C
)->setIsExact(true);
2040 ID
.Kind
= ValID::t_Constant
;
2044 // Logical Operations
2046 case lltok::kw_lshr
:
2047 case lltok::kw_ashr
:
2050 case lltok::kw_xor
: {
2051 unsigned Opc
= Lex
.getUIntVal();
2052 Constant
*Val0
, *Val1
;
2054 if (ParseToken(lltok::lparen
, "expected '(' in logical constantexpr") ||
2055 ParseGlobalTypeAndValue(Val0
) ||
2056 ParseToken(lltok::comma
, "expected comma in logical constantexpr") ||
2057 ParseGlobalTypeAndValue(Val1
) ||
2058 ParseToken(lltok::rparen
, "expected ')' in logical constantexpr"))
2060 if (Val0
->getType() != Val1
->getType())
2061 return Error(ID
.Loc
, "operands of constexpr must have same type");
2062 if (!Val0
->getType()->isIntOrIntVector())
2063 return Error(ID
.Loc
,
2064 "constexpr requires integer or integer vector operands");
2065 ID
.ConstantVal
= ConstantExpr::get(Opc
, Val0
, Val1
);
2066 ID
.Kind
= ValID::t_Constant
;
2070 case lltok::kw_getelementptr
:
2071 case lltok::kw_shufflevector
:
2072 case lltok::kw_insertelement
:
2073 case lltok::kw_extractelement
:
2074 case lltok::kw_select
: {
2075 unsigned Opc
= Lex
.getUIntVal();
2076 SmallVector
<Constant
*, 16> Elts
;
2077 bool InBounds
= false;
2079 if (Opc
== Instruction::GetElementPtr
)
2080 InBounds
= EatIfPresent(lltok::kw_inbounds
);
2081 if (ParseToken(lltok::lparen
, "expected '(' in constantexpr") ||
2082 ParseGlobalValueVector(Elts
) ||
2083 ParseToken(lltok::rparen
, "expected ')' in constantexpr"))
2086 if (Opc
== Instruction::GetElementPtr
) {
2087 if (Elts
.size() == 0 || !isa
<PointerType
>(Elts
[0]->getType()))
2088 return Error(ID
.Loc
, "getelementptr requires pointer operand");
2090 if (!GetElementPtrInst::getIndexedType(Elts
[0]->getType(),
2091 (Value
**)(Elts
.data() + 1),
2093 return Error(ID
.Loc
, "invalid indices for getelementptr");
2094 ID
.ConstantVal
= ConstantExpr::getGetElementPtr(Elts
[0],
2095 Elts
.data() + 1, Elts
.size() - 1);
2097 cast
<GEPOperator
>(ID
.ConstantVal
)->setIsInBounds(true);
2098 } else if (Opc
== Instruction::Select
) {
2099 if (Elts
.size() != 3)
2100 return Error(ID
.Loc
, "expected three operands to select");
2101 if (const char *Reason
= SelectInst::areInvalidOperands(Elts
[0], Elts
[1],
2103 return Error(ID
.Loc
, Reason
);
2104 ID
.ConstantVal
= ConstantExpr::getSelect(Elts
[0], Elts
[1], Elts
[2]);
2105 } else if (Opc
== Instruction::ShuffleVector
) {
2106 if (Elts
.size() != 3)
2107 return Error(ID
.Loc
, "expected three operands to shufflevector");
2108 if (!ShuffleVectorInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
2109 return Error(ID
.Loc
, "invalid operands to shufflevector");
2111 ConstantExpr::getShuffleVector(Elts
[0], Elts
[1],Elts
[2]);
2112 } else if (Opc
== Instruction::ExtractElement
) {
2113 if (Elts
.size() != 2)
2114 return Error(ID
.Loc
, "expected two operands to extractelement");
2115 if (!ExtractElementInst::isValidOperands(Elts
[0], Elts
[1]))
2116 return Error(ID
.Loc
, "invalid extractelement operands");
2117 ID
.ConstantVal
= ConstantExpr::getExtractElement(Elts
[0], Elts
[1]);
2119 assert(Opc
== Instruction::InsertElement
&& "Unknown opcode");
2120 if (Elts
.size() != 3)
2121 return Error(ID
.Loc
, "expected three operands to insertelement");
2122 if (!InsertElementInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
2123 return Error(ID
.Loc
, "invalid insertelement operands");
2125 ConstantExpr::getInsertElement(Elts
[0], Elts
[1],Elts
[2]);
2128 ID
.Kind
= ValID::t_Constant
;
2137 /// ParseGlobalValue - Parse a global value with the specified type.
2138 bool LLParser::ParseGlobalValue(const Type
*Ty
, Constant
*&V
) {
2141 return ParseValID(ID
) ||
2142 ConvertGlobalValIDToValue(Ty
, ID
, V
);
2145 /// ConvertGlobalValIDToValue - Apply a type to a ValID to get a fully resolved
2147 bool LLParser::ConvertGlobalValIDToValue(const Type
*Ty
, ValID
&ID
,
2149 if (isa
<FunctionType
>(Ty
))
2150 return Error(ID
.Loc
, "functions are not values, refer to them as pointers");
2153 default: llvm_unreachable("Unknown ValID!");
2154 case ValID::t_Metadata
:
2155 return Error(ID
.Loc
, "invalid use of metadata");
2156 case ValID::t_LocalID
:
2157 case ValID::t_LocalName
:
2158 return Error(ID
.Loc
, "invalid use of function-local name");
2159 case ValID::t_InlineAsm
:
2160 return Error(ID
.Loc
, "inline asm can only be an operand of call/invoke");
2161 case ValID::t_GlobalName
:
2162 V
= GetGlobalVal(ID
.StrVal
, Ty
, ID
.Loc
);
2164 case ValID::t_GlobalID
:
2165 V
= GetGlobalVal(ID
.UIntVal
, Ty
, ID
.Loc
);
2167 case ValID::t_APSInt
:
2168 if (!isa
<IntegerType
>(Ty
))
2169 return Error(ID
.Loc
, "integer constant must have integer type");
2170 ID
.APSIntVal
.extOrTrunc(Ty
->getPrimitiveSizeInBits());
2171 V
= ConstantInt::get(Context
, ID
.APSIntVal
);
2173 case ValID::t_APFloat
:
2174 if (!Ty
->isFloatingPoint() ||
2175 !ConstantFP::isValueValidForType(Ty
, ID
.APFloatVal
))
2176 return Error(ID
.Loc
, "floating point constant invalid for type");
2178 // The lexer has no type info, so builds all float and double FP constants
2179 // as double. Fix this here. Long double does not need this.
2180 if (&ID
.APFloatVal
.getSemantics() == &APFloat::IEEEdouble
&&
2181 Ty
== Type::FloatTy
) {
2183 ID
.APFloatVal
.convert(APFloat::IEEEsingle
, APFloat::rmNearestTiesToEven
,
2186 V
= ConstantFP::get(Context
, ID
.APFloatVal
);
2188 if (V
->getType() != Ty
)
2189 return Error(ID
.Loc
, "floating point constant does not have type '" +
2190 Ty
->getDescription() + "'");
2194 if (!isa
<PointerType
>(Ty
))
2195 return Error(ID
.Loc
, "null must be a pointer type");
2196 V
= ConstantPointerNull::get(cast
<PointerType
>(Ty
));
2198 case ValID::t_Undef
:
2199 // FIXME: LabelTy should not be a first-class type.
2200 if ((!Ty
->isFirstClassType() || Ty
== Type::LabelTy
) &&
2201 !isa
<OpaqueType
>(Ty
))
2202 return Error(ID
.Loc
, "invalid type for undef constant");
2203 V
= UndefValue::get(Ty
);
2205 case ValID::t_EmptyArray
:
2206 if (!isa
<ArrayType
>(Ty
) || cast
<ArrayType
>(Ty
)->getNumElements() != 0)
2207 return Error(ID
.Loc
, "invalid empty array initializer");
2208 V
= UndefValue::get(Ty
);
2211 // FIXME: LabelTy should not be a first-class type.
2212 if (!Ty
->isFirstClassType() || Ty
== Type::LabelTy
)
2213 return Error(ID
.Loc
, "invalid type for null constant");
2214 V
= Constant::getNullValue(Ty
);
2216 case ValID::t_Constant
:
2217 if (ID
.ConstantVal
->getType() != Ty
)
2218 return Error(ID
.Loc
, "constant expression type mismatch");
2224 bool LLParser::ParseGlobalTypeAndValue(Constant
*&V
) {
2225 PATypeHolder
Type(Type::VoidTy
);
2226 return ParseType(Type
) ||
2227 ParseGlobalValue(Type
, V
);
2230 /// ParseGlobalValueVector
2232 /// ::= TypeAndValue (',' TypeAndValue)*
2233 bool LLParser::ParseGlobalValueVector(SmallVectorImpl
<Constant
*> &Elts
) {
2235 if (Lex
.getKind() == lltok::rbrace
||
2236 Lex
.getKind() == lltok::rsquare
||
2237 Lex
.getKind() == lltok::greater
||
2238 Lex
.getKind() == lltok::rparen
)
2242 if (ParseGlobalTypeAndValue(C
)) return true;
2245 while (EatIfPresent(lltok::comma
)) {
2246 if (ParseGlobalTypeAndValue(C
)) return true;
2254 //===----------------------------------------------------------------------===//
2255 // Function Parsing.
2256 //===----------------------------------------------------------------------===//
2258 bool LLParser::ConvertValIDToValue(const Type
*Ty
, ValID
&ID
, Value
*&V
,
2259 PerFunctionState
&PFS
) {
2260 if (ID
.Kind
== ValID::t_LocalID
)
2261 V
= PFS
.GetVal(ID
.UIntVal
, Ty
, ID
.Loc
);
2262 else if (ID
.Kind
== ValID::t_LocalName
)
2263 V
= PFS
.GetVal(ID
.StrVal
, Ty
, ID
.Loc
);
2264 else if (ID
.Kind
== ValID::t_InlineAsm
) {
2265 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
2266 const FunctionType
*FTy
=
2267 PTy
? dyn_cast
<FunctionType
>(PTy
->getElementType()) : 0;
2268 if (!FTy
|| !InlineAsm::Verify(FTy
, ID
.StrVal2
))
2269 return Error(ID
.Loc
, "invalid type for inline asm constraint string");
2270 V
= InlineAsm::get(FTy
, ID
.StrVal
, ID
.StrVal2
, ID
.UIntVal
);
2272 } else if (ID
.Kind
== ValID::t_Metadata
) {
2276 if (ConvertGlobalValIDToValue(Ty
, ID
, C
)) return true;
2284 bool LLParser::ParseValue(const Type
*Ty
, Value
*&V
, PerFunctionState
&PFS
) {
2287 return ParseValID(ID
) ||
2288 ConvertValIDToValue(Ty
, ID
, V
, PFS
);
2291 bool LLParser::ParseTypeAndValue(Value
*&V
, PerFunctionState
&PFS
) {
2292 PATypeHolder
T(Type::VoidTy
);
2293 return ParseType(T
) ||
2294 ParseValue(T
, V
, PFS
);
2298 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2299 /// Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2300 /// OptionalAlign OptGC
2301 bool LLParser::ParseFunctionHeader(Function
*&Fn
, bool isDefine
) {
2302 // Parse the linkage.
2303 LocTy LinkageLoc
= Lex
.getLoc();
2306 unsigned Visibility
, CC
, RetAttrs
;
2307 PATypeHolder
RetType(Type::VoidTy
);
2308 LocTy RetTypeLoc
= Lex
.getLoc();
2309 if (ParseOptionalLinkage(Linkage
) ||
2310 ParseOptionalVisibility(Visibility
) ||
2311 ParseOptionalCallingConv(CC
) ||
2312 ParseOptionalAttrs(RetAttrs
, 1) ||
2313 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/))
2316 // Verify that the linkage is ok.
2317 switch ((GlobalValue::LinkageTypes
)Linkage
) {
2318 case GlobalValue::ExternalLinkage
:
2319 break; // always ok.
2320 case GlobalValue::DLLImportLinkage
:
2321 case GlobalValue::ExternalWeakLinkage
:
2323 return Error(LinkageLoc
, "invalid linkage for function definition");
2325 case GlobalValue::PrivateLinkage
:
2326 case GlobalValue::LinkerPrivateLinkage
:
2327 case GlobalValue::InternalLinkage
:
2328 case GlobalValue::AvailableExternallyLinkage
:
2329 case GlobalValue::LinkOnceAnyLinkage
:
2330 case GlobalValue::LinkOnceODRLinkage
:
2331 case GlobalValue::WeakAnyLinkage
:
2332 case GlobalValue::WeakODRLinkage
:
2333 case GlobalValue::DLLExportLinkage
:
2335 return Error(LinkageLoc
, "invalid linkage for function declaration");
2337 case GlobalValue::AppendingLinkage
:
2338 case GlobalValue::GhostLinkage
:
2339 case GlobalValue::CommonLinkage
:
2340 return Error(LinkageLoc
, "invalid function linkage type");
2343 if (!FunctionType::isValidReturnType(RetType
) ||
2344 isa
<OpaqueType
>(RetType
))
2345 return Error(RetTypeLoc
, "invalid function return type");
2347 LocTy NameLoc
= Lex
.getLoc();
2349 std::string FunctionName
;
2350 if (Lex
.getKind() == lltok::GlobalVar
) {
2351 FunctionName
= Lex
.getStrVal();
2352 } else if (Lex
.getKind() == lltok::GlobalID
) { // @42 is ok.
2353 unsigned NameID
= Lex
.getUIntVal();
2355 if (NameID
!= NumberedVals
.size())
2356 return TokError("function expected to be numbered '%" +
2357 utostr(NumberedVals
.size()) + "'");
2359 return TokError("expected function name");
2364 if (Lex
.getKind() != lltok::lparen
)
2365 return TokError("expected '(' in function argument list");
2367 std::vector
<ArgInfo
> ArgList
;
2370 std::string Section
;
2374 if (ParseArgumentList(ArgList
, isVarArg
, false) ||
2375 ParseOptionalAttrs(FuncAttrs
, 2) ||
2376 (EatIfPresent(lltok::kw_section
) &&
2377 ParseStringConstant(Section
)) ||
2378 ParseOptionalAlignment(Alignment
) ||
2379 (EatIfPresent(lltok::kw_gc
) &&
2380 ParseStringConstant(GC
)))
2383 // If the alignment was parsed as an attribute, move to the alignment field.
2384 if (FuncAttrs
& Attribute::Alignment
) {
2385 Alignment
= Attribute::getAlignmentFromAttrs(FuncAttrs
);
2386 FuncAttrs
&= ~Attribute::Alignment
;
2389 // Okay, if we got here, the function is syntactically valid. Convert types
2390 // and do semantic checks.
2391 std::vector
<const Type
*> ParamTypeList
;
2392 SmallVector
<AttributeWithIndex
, 8> Attrs
;
2393 // FIXME : In 3.0, stop accepting zext, sext and inreg as optional function
2395 unsigned ObsoleteFuncAttrs
= Attribute::ZExt
|Attribute::SExt
|Attribute::InReg
;
2396 if (FuncAttrs
& ObsoleteFuncAttrs
) {
2397 RetAttrs
|= FuncAttrs
& ObsoleteFuncAttrs
;
2398 FuncAttrs
&= ~ObsoleteFuncAttrs
;
2401 if (RetAttrs
!= Attribute::None
)
2402 Attrs
.push_back(AttributeWithIndex::get(0, RetAttrs
));
2404 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
2405 ParamTypeList
.push_back(ArgList
[i
].Type
);
2406 if (ArgList
[i
].Attrs
!= Attribute::None
)
2407 Attrs
.push_back(AttributeWithIndex::get(i
+1, ArgList
[i
].Attrs
));
2410 if (FuncAttrs
!= Attribute::None
)
2411 Attrs
.push_back(AttributeWithIndex::get(~0, FuncAttrs
));
2413 AttrListPtr PAL
= AttrListPtr::get(Attrs
.begin(), Attrs
.end());
2415 if (PAL
.paramHasAttr(1, Attribute::StructRet
) &&
2416 RetType
!= Type::VoidTy
)
2417 return Error(RetTypeLoc
, "functions with 'sret' argument must return void");
2419 const FunctionType
*FT
=
2420 FunctionType::get(RetType
, ParamTypeList
, isVarArg
);
2421 const PointerType
*PFT
= PointerType::getUnqual(FT
);
2424 if (!FunctionName
.empty()) {
2425 // If this was a definition of a forward reference, remove the definition
2426 // from the forward reference table and fill in the forward ref.
2427 std::map
<std::string
, std::pair
<GlobalValue
*, LocTy
> >::iterator FRVI
=
2428 ForwardRefVals
.find(FunctionName
);
2429 if (FRVI
!= ForwardRefVals
.end()) {
2430 Fn
= M
->getFunction(FunctionName
);
2431 ForwardRefVals
.erase(FRVI
);
2432 } else if ((Fn
= M
->getFunction(FunctionName
))) {
2433 // If this function already exists in the symbol table, then it is
2434 // multiply defined. We accept a few cases for old backwards compat.
2435 // FIXME: Remove this stuff for LLVM 3.0.
2436 if (Fn
->getType() != PFT
|| Fn
->getAttributes() != PAL
||
2437 (!Fn
->isDeclaration() && isDefine
)) {
2438 // If the redefinition has different type or different attributes,
2439 // reject it. If both have bodies, reject it.
2440 return Error(NameLoc
, "invalid redefinition of function '" +
2441 FunctionName
+ "'");
2442 } else if (Fn
->isDeclaration()) {
2443 // Make sure to strip off any argument names so we can't get conflicts.
2444 for (Function::arg_iterator AI
= Fn
->arg_begin(), AE
= Fn
->arg_end();
2450 } else if (FunctionName
.empty()) {
2451 // If this is a definition of a forward referenced function, make sure the
2453 std::map
<unsigned, std::pair
<GlobalValue
*, LocTy
> >::iterator I
2454 = ForwardRefValIDs
.find(NumberedVals
.size());
2455 if (I
!= ForwardRefValIDs
.end()) {
2456 Fn
= cast
<Function
>(I
->second
.first
);
2457 if (Fn
->getType() != PFT
)
2458 return Error(NameLoc
, "type of definition and forward reference of '@" +
2459 utostr(NumberedVals
.size()) +"' disagree");
2460 ForwardRefValIDs
.erase(I
);
2465 Fn
= Function::Create(FT
, GlobalValue::ExternalLinkage
, FunctionName
, M
);
2466 else // Move the forward-reference to the correct spot in the module.
2467 M
->getFunctionList().splice(M
->end(), M
->getFunctionList(), Fn
);
2469 if (FunctionName
.empty())
2470 NumberedVals
.push_back(Fn
);
2472 Fn
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
2473 Fn
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
2474 Fn
->setCallingConv(CC
);
2475 Fn
->setAttributes(PAL
);
2476 Fn
->setAlignment(Alignment
);
2477 Fn
->setSection(Section
);
2478 if (!GC
.empty()) Fn
->setGC(GC
.c_str());
2480 // Add all of the arguments we parsed to the function.
2481 Function::arg_iterator ArgIt
= Fn
->arg_begin();
2482 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
, ++ArgIt
) {
2483 // If the argument has a name, insert it into the argument symbol table.
2484 if (ArgList
[i
].Name
.empty()) continue;
2486 // Set the name, if it conflicted, it will be auto-renamed.
2487 ArgIt
->setName(ArgList
[i
].Name
);
2489 if (ArgIt
->getNameStr() != ArgList
[i
].Name
)
2490 return Error(ArgList
[i
].Loc
, "redefinition of argument '%" +
2491 ArgList
[i
].Name
+ "'");
2498 /// ParseFunctionBody
2499 /// ::= '{' BasicBlock+ '}'
2500 /// ::= 'begin' BasicBlock+ 'end' // FIXME: remove in LLVM 3.0
2502 bool LLParser::ParseFunctionBody(Function
&Fn
) {
2503 if (Lex
.getKind() != lltok::lbrace
&& Lex
.getKind() != lltok::kw_begin
)
2504 return TokError("expected '{' in function body");
2505 Lex
.Lex(); // eat the {.
2507 PerFunctionState
PFS(*this, Fn
);
2509 while (Lex
.getKind() != lltok::rbrace
&& Lex
.getKind() != lltok::kw_end
)
2510 if (ParseBasicBlock(PFS
)) return true;
2515 // Verify function is ok.
2516 return PFS
.VerifyFunctionComplete();
2520 /// ::= LabelStr? Instruction*
2521 bool LLParser::ParseBasicBlock(PerFunctionState
&PFS
) {
2522 // If this basic block starts out with a name, remember it.
2524 LocTy NameLoc
= Lex
.getLoc();
2525 if (Lex
.getKind() == lltok::LabelStr
) {
2526 Name
= Lex
.getStrVal();
2530 BasicBlock
*BB
= PFS
.DefineBB(Name
, NameLoc
);
2531 if (BB
== 0) return true;
2533 std::string NameStr
;
2535 // Parse the instructions in this block until we get a terminator.
2538 // This instruction may have three possibilities for a name: a) none
2539 // specified, b) name specified "%foo =", c) number specified: "%4 =".
2540 LocTy NameLoc
= Lex
.getLoc();
2544 if (Lex
.getKind() == lltok::LocalVarID
) {
2545 NameID
= Lex
.getUIntVal();
2547 if (ParseToken(lltok::equal
, "expected '=' after instruction id"))
2549 } else if (Lex
.getKind() == lltok::LocalVar
||
2550 // FIXME: REMOVE IN LLVM 3.0
2551 Lex
.getKind() == lltok::StringConstant
) {
2552 NameStr
= Lex
.getStrVal();
2554 if (ParseToken(lltok::equal
, "expected '=' after instruction name"))
2558 if (ParseInstruction(Inst
, BB
, PFS
)) return true;
2560 BB
->getInstList().push_back(Inst
);
2562 // Set the name on the instruction.
2563 if (PFS
.SetInstName(NameID
, NameStr
, NameLoc
, Inst
)) return true;
2564 } while (!isa
<TerminatorInst
>(Inst
));
2569 //===----------------------------------------------------------------------===//
2570 // Instruction Parsing.
2571 //===----------------------------------------------------------------------===//
2573 /// ParseInstruction - Parse one of the many different instructions.
2575 bool LLParser::ParseInstruction(Instruction
*&Inst
, BasicBlock
*BB
,
2576 PerFunctionState
&PFS
) {
2577 lltok::Kind Token
= Lex
.getKind();
2578 if (Token
== lltok::Eof
)
2579 return TokError("found end of file when expecting more instructions");
2580 LocTy Loc
= Lex
.getLoc();
2581 unsigned KeywordVal
= Lex
.getUIntVal();
2582 Lex
.Lex(); // Eat the keyword.
2585 default: return Error(Loc
, "expected instruction opcode");
2586 // Terminator Instructions.
2587 case lltok::kw_unwind
: Inst
= new UnwindInst(); return false;
2588 case lltok::kw_unreachable
: Inst
= new UnreachableInst(); return false;
2589 case lltok::kw_ret
: return ParseRet(Inst
, BB
, PFS
);
2590 case lltok::kw_br
: return ParseBr(Inst
, PFS
);
2591 case lltok::kw_switch
: return ParseSwitch(Inst
, PFS
);
2592 case lltok::kw_invoke
: return ParseInvoke(Inst
, PFS
);
2593 // Binary Operators.
2596 case lltok::kw_mul
: {
2599 LocTy ModifierLoc
= Lex
.getLoc();
2600 if (EatIfPresent(lltok::kw_nuw
))
2602 if (EatIfPresent(lltok::kw_nsw
)) {
2604 if (EatIfPresent(lltok::kw_nuw
))
2607 // API compatibility: Accept either integer or floating-point types.
2608 bool Result
= ParseArithmetic(Inst
, PFS
, KeywordVal
, 0);
2610 if (!Inst
->getType()->isIntOrIntVector()) {
2612 return Error(ModifierLoc
, "nuw only applies to integer operations");
2614 return Error(ModifierLoc
, "nsw only applies to integer operations");
2617 cast
<OverflowingBinaryOperator
>(Inst
)->setHasNoUnsignedOverflow(true);
2619 cast
<OverflowingBinaryOperator
>(Inst
)->setHasNoSignedOverflow(true);
2623 case lltok::kw_fadd
:
2624 case lltok::kw_fsub
:
2625 case lltok::kw_fmul
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 2);
2627 case lltok::kw_sdiv
: {
2629 if (EatIfPresent(lltok::kw_exact
))
2631 bool Result
= ParseArithmetic(Inst
, PFS
, KeywordVal
, 1);
2634 cast
<SDivOperator
>(Inst
)->setIsExact(true);
2638 case lltok::kw_udiv
:
2639 case lltok::kw_urem
:
2640 case lltok::kw_srem
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 1);
2641 case lltok::kw_fdiv
:
2642 case lltok::kw_frem
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 2);
2644 case lltok::kw_lshr
:
2645 case lltok::kw_ashr
:
2648 case lltok::kw_xor
: return ParseLogical(Inst
, PFS
, KeywordVal
);
2649 case lltok::kw_icmp
:
2650 case lltok::kw_fcmp
: return ParseCompare(Inst
, PFS
, KeywordVal
);
2652 case lltok::kw_trunc
:
2653 case lltok::kw_zext
:
2654 case lltok::kw_sext
:
2655 case lltok::kw_fptrunc
:
2656 case lltok::kw_fpext
:
2657 case lltok::kw_bitcast
:
2658 case lltok::kw_uitofp
:
2659 case lltok::kw_sitofp
:
2660 case lltok::kw_fptoui
:
2661 case lltok::kw_fptosi
:
2662 case lltok::kw_inttoptr
:
2663 case lltok::kw_ptrtoint
: return ParseCast(Inst
, PFS
, KeywordVal
);
2665 case lltok::kw_select
: return ParseSelect(Inst
, PFS
);
2666 case lltok::kw_va_arg
: return ParseVA_Arg(Inst
, PFS
);
2667 case lltok::kw_extractelement
: return ParseExtractElement(Inst
, PFS
);
2668 case lltok::kw_insertelement
: return ParseInsertElement(Inst
, PFS
);
2669 case lltok::kw_shufflevector
: return ParseShuffleVector(Inst
, PFS
);
2670 case lltok::kw_phi
: return ParsePHI(Inst
, PFS
);
2671 case lltok::kw_call
: return ParseCall(Inst
, PFS
, false);
2672 case lltok::kw_tail
: return ParseCall(Inst
, PFS
, true);
2674 case lltok::kw_alloca
:
2675 case lltok::kw_malloc
: return ParseAlloc(Inst
, PFS
, KeywordVal
);
2676 case lltok::kw_free
: return ParseFree(Inst
, PFS
);
2677 case lltok::kw_load
: return ParseLoad(Inst
, PFS
, false);
2678 case lltok::kw_store
: return ParseStore(Inst
, PFS
, false);
2679 case lltok::kw_volatile
:
2680 if (EatIfPresent(lltok::kw_load
))
2681 return ParseLoad(Inst
, PFS
, true);
2682 else if (EatIfPresent(lltok::kw_store
))
2683 return ParseStore(Inst
, PFS
, true);
2685 return TokError("expected 'load' or 'store'");
2686 case lltok::kw_getresult
: return ParseGetResult(Inst
, PFS
);
2687 case lltok::kw_getelementptr
: return ParseGetElementPtr(Inst
, PFS
);
2688 case lltok::kw_extractvalue
: return ParseExtractValue(Inst
, PFS
);
2689 case lltok::kw_insertvalue
: return ParseInsertValue(Inst
, PFS
);
2693 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
2694 bool LLParser::ParseCmpPredicate(unsigned &P
, unsigned Opc
) {
2695 if (Opc
== Instruction::FCmp
) {
2696 switch (Lex
.getKind()) {
2697 default: TokError("expected fcmp predicate (e.g. 'oeq')");
2698 case lltok::kw_oeq
: P
= CmpInst::FCMP_OEQ
; break;
2699 case lltok::kw_one
: P
= CmpInst::FCMP_ONE
; break;
2700 case lltok::kw_olt
: P
= CmpInst::FCMP_OLT
; break;
2701 case lltok::kw_ogt
: P
= CmpInst::FCMP_OGT
; break;
2702 case lltok::kw_ole
: P
= CmpInst::FCMP_OLE
; break;
2703 case lltok::kw_oge
: P
= CmpInst::FCMP_OGE
; break;
2704 case lltok::kw_ord
: P
= CmpInst::FCMP_ORD
; break;
2705 case lltok::kw_uno
: P
= CmpInst::FCMP_UNO
; break;
2706 case lltok::kw_ueq
: P
= CmpInst::FCMP_UEQ
; break;
2707 case lltok::kw_une
: P
= CmpInst::FCMP_UNE
; break;
2708 case lltok::kw_ult
: P
= CmpInst::FCMP_ULT
; break;
2709 case lltok::kw_ugt
: P
= CmpInst::FCMP_UGT
; break;
2710 case lltok::kw_ule
: P
= CmpInst::FCMP_ULE
; break;
2711 case lltok::kw_uge
: P
= CmpInst::FCMP_UGE
; break;
2712 case lltok::kw_true
: P
= CmpInst::FCMP_TRUE
; break;
2713 case lltok::kw_false
: P
= CmpInst::FCMP_FALSE
; break;
2716 switch (Lex
.getKind()) {
2717 default: TokError("expected icmp predicate (e.g. 'eq')");
2718 case lltok::kw_eq
: P
= CmpInst::ICMP_EQ
; break;
2719 case lltok::kw_ne
: P
= CmpInst::ICMP_NE
; break;
2720 case lltok::kw_slt
: P
= CmpInst::ICMP_SLT
; break;
2721 case lltok::kw_sgt
: P
= CmpInst::ICMP_SGT
; break;
2722 case lltok::kw_sle
: P
= CmpInst::ICMP_SLE
; break;
2723 case lltok::kw_sge
: P
= CmpInst::ICMP_SGE
; break;
2724 case lltok::kw_ult
: P
= CmpInst::ICMP_ULT
; break;
2725 case lltok::kw_ugt
: P
= CmpInst::ICMP_UGT
; break;
2726 case lltok::kw_ule
: P
= CmpInst::ICMP_ULE
; break;
2727 case lltok::kw_uge
: P
= CmpInst::ICMP_UGE
; break;
2734 //===----------------------------------------------------------------------===//
2735 // Terminator Instructions.
2736 //===----------------------------------------------------------------------===//
2738 /// ParseRet - Parse a return instruction.
2740 /// ::= 'ret' TypeAndValue
2741 /// ::= 'ret' TypeAndValue (',' TypeAndValue)+ [[obsolete: LLVM 3.0]]
2742 bool LLParser::ParseRet(Instruction
*&Inst
, BasicBlock
*BB
,
2743 PerFunctionState
&PFS
) {
2744 PATypeHolder
Ty(Type::VoidTy
);
2745 if (ParseType(Ty
, true /*void allowed*/)) return true;
2747 if (Ty
== Type::VoidTy
) {
2748 Inst
= ReturnInst::Create();
2753 if (ParseValue(Ty
, RV
, PFS
)) return true;
2755 // The normal case is one return value.
2756 if (Lex
.getKind() == lltok::comma
) {
2757 // FIXME: LLVM 3.0 remove MRV support for 'ret i32 1, i32 2', requiring use
2758 // of 'ret {i32,i32} {i32 1, i32 2}'
2759 SmallVector
<Value
*, 8> RVs
;
2762 while (EatIfPresent(lltok::comma
)) {
2763 if (ParseTypeAndValue(RV
, PFS
)) return true;
2767 RV
= UndefValue::get(PFS
.getFunction().getReturnType());
2768 for (unsigned i
= 0, e
= RVs
.size(); i
!= e
; ++i
) {
2769 Instruction
*I
= InsertValueInst::Create(RV
, RVs
[i
], i
, "mrv");
2770 BB
->getInstList().push_back(I
);
2774 Inst
= ReturnInst::Create(RV
);
2780 /// ::= 'br' TypeAndValue
2781 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
2782 bool LLParser::ParseBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2784 Value
*Op0
, *Op1
, *Op2
;
2785 if (ParseTypeAndValue(Op0
, Loc
, PFS
)) return true;
2787 if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(Op0
)) {
2788 Inst
= BranchInst::Create(BB
);
2792 if (Op0
->getType() != Type::Int1Ty
)
2793 return Error(Loc
, "branch condition must have 'i1' type");
2795 if (ParseToken(lltok::comma
, "expected ',' after branch condition") ||
2796 ParseTypeAndValue(Op1
, Loc
, PFS
) ||
2797 ParseToken(lltok::comma
, "expected ',' after true destination") ||
2798 ParseTypeAndValue(Op2
, Loc2
, PFS
))
2801 if (!isa
<BasicBlock
>(Op1
))
2802 return Error(Loc
, "true destination of branch must be a basic block");
2803 if (!isa
<BasicBlock
>(Op2
))
2804 return Error(Loc2
, "true destination of branch must be a basic block");
2806 Inst
= BranchInst::Create(cast
<BasicBlock
>(Op1
), cast
<BasicBlock
>(Op2
), Op0
);
2812 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
2814 /// ::= (TypeAndValue ',' TypeAndValue)*
2815 bool LLParser::ParseSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2816 LocTy CondLoc
, BBLoc
;
2817 Value
*Cond
, *DefaultBB
;
2818 if (ParseTypeAndValue(Cond
, CondLoc
, PFS
) ||
2819 ParseToken(lltok::comma
, "expected ',' after switch condition") ||
2820 ParseTypeAndValue(DefaultBB
, BBLoc
, PFS
) ||
2821 ParseToken(lltok::lsquare
, "expected '[' with switch table"))
2824 if (!isa
<IntegerType
>(Cond
->getType()))
2825 return Error(CondLoc
, "switch condition must have integer type");
2826 if (!isa
<BasicBlock
>(DefaultBB
))
2827 return Error(BBLoc
, "default destination must be a basic block");
2829 // Parse the jump table pairs.
2830 SmallPtrSet
<Value
*, 32> SeenCases
;
2831 SmallVector
<std::pair
<ConstantInt
*, BasicBlock
*>, 32> Table
;
2832 while (Lex
.getKind() != lltok::rsquare
) {
2833 Value
*Constant
, *DestBB
;
2835 if (ParseTypeAndValue(Constant
, CondLoc
, PFS
) ||
2836 ParseToken(lltok::comma
, "expected ',' after case value") ||
2837 ParseTypeAndValue(DestBB
, BBLoc
, PFS
))
2840 if (!SeenCases
.insert(Constant
))
2841 return Error(CondLoc
, "duplicate case value in switch");
2842 if (!isa
<ConstantInt
>(Constant
))
2843 return Error(CondLoc
, "case value is not a constant integer");
2844 if (!isa
<BasicBlock
>(DestBB
))
2845 return Error(BBLoc
, "case destination is not a basic block");
2847 Table
.push_back(std::make_pair(cast
<ConstantInt
>(Constant
),
2848 cast
<BasicBlock
>(DestBB
)));
2851 Lex
.Lex(); // Eat the ']'.
2853 SwitchInst
*SI
= SwitchInst::Create(Cond
, cast
<BasicBlock
>(DefaultBB
),
2855 for (unsigned i
= 0, e
= Table
.size(); i
!= e
; ++i
)
2856 SI
->addCase(Table
[i
].first
, Table
[i
].second
);
2862 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
2863 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
2864 bool LLParser::ParseInvoke(Instruction
*&Inst
, PerFunctionState
&PFS
) {
2865 LocTy CallLoc
= Lex
.getLoc();
2866 unsigned CC
, RetAttrs
, FnAttrs
;
2867 PATypeHolder
RetType(Type::VoidTy
);
2870 SmallVector
<ParamInfo
, 16> ArgList
;
2872 Value
*NormalBB
, *UnwindBB
;
2873 if (ParseOptionalCallingConv(CC
) ||
2874 ParseOptionalAttrs(RetAttrs
, 1) ||
2875 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
2876 ParseValID(CalleeID
) ||
2877 ParseParameterList(ArgList
, PFS
) ||
2878 ParseOptionalAttrs(FnAttrs
, 2) ||
2879 ParseToken(lltok::kw_to
, "expected 'to' in invoke") ||
2880 ParseTypeAndValue(NormalBB
, PFS
) ||
2881 ParseToken(lltok::kw_unwind
, "expected 'unwind' in invoke") ||
2882 ParseTypeAndValue(UnwindBB
, PFS
))
2885 if (!isa
<BasicBlock
>(NormalBB
))
2886 return Error(CallLoc
, "normal destination is not a basic block");
2887 if (!isa
<BasicBlock
>(UnwindBB
))
2888 return Error(CallLoc
, "unwind destination is not a basic block");
2890 // If RetType is a non-function pointer type, then this is the short syntax
2891 // for the call, which means that RetType is just the return type. Infer the
2892 // rest of the function argument types from the arguments that are present.
2893 const PointerType
*PFTy
= 0;
2894 const FunctionType
*Ty
= 0;
2895 if (!(PFTy
= dyn_cast
<PointerType
>(RetType
)) ||
2896 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType()))) {
2897 // Pull out the types of all of the arguments...
2898 std::vector
<const Type
*> ParamTypes
;
2899 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
2900 ParamTypes
.push_back(ArgList
[i
].V
->getType());
2902 if (!FunctionType::isValidReturnType(RetType
))
2903 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
2905 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
2906 PFTy
= PointerType::getUnqual(Ty
);
2909 // Look up the callee.
2911 if (ConvertValIDToValue(PFTy
, CalleeID
, Callee
, PFS
)) return true;
2913 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
2914 // function attributes.
2915 unsigned ObsoleteFuncAttrs
= Attribute::ZExt
|Attribute::SExt
|Attribute::InReg
;
2916 if (FnAttrs
& ObsoleteFuncAttrs
) {
2917 RetAttrs
|= FnAttrs
& ObsoleteFuncAttrs
;
2918 FnAttrs
&= ~ObsoleteFuncAttrs
;
2921 // Set up the Attributes for the function.
2922 SmallVector
<AttributeWithIndex
, 8> Attrs
;
2923 if (RetAttrs
!= Attribute::None
)
2924 Attrs
.push_back(AttributeWithIndex::get(0, RetAttrs
));
2926 SmallVector
<Value
*, 8> Args
;
2928 // Loop through FunctionType's arguments and ensure they are specified
2929 // correctly. Also, gather any parameter attributes.
2930 FunctionType::param_iterator I
= Ty
->param_begin();
2931 FunctionType::param_iterator E
= Ty
->param_end();
2932 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
2933 const Type
*ExpectedTy
= 0;
2936 } else if (!Ty
->isVarArg()) {
2937 return Error(ArgList
[i
].Loc
, "too many arguments specified");
2940 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
2941 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
2942 ExpectedTy
->getDescription() + "'");
2943 Args
.push_back(ArgList
[i
].V
);
2944 if (ArgList
[i
].Attrs
!= Attribute::None
)
2945 Attrs
.push_back(AttributeWithIndex::get(i
+1, ArgList
[i
].Attrs
));
2949 return Error(CallLoc
, "not enough parameters specified for call");
2951 if (FnAttrs
!= Attribute::None
)
2952 Attrs
.push_back(AttributeWithIndex::get(~0, FnAttrs
));
2954 // Finish off the Attributes and check them
2955 AttrListPtr PAL
= AttrListPtr::get(Attrs
.begin(), Attrs
.end());
2957 InvokeInst
*II
= InvokeInst::Create(Callee
, cast
<BasicBlock
>(NormalBB
),
2958 cast
<BasicBlock
>(UnwindBB
),
2959 Args
.begin(), Args
.end());
2960 II
->setCallingConv(CC
);
2961 II
->setAttributes(PAL
);
2968 //===----------------------------------------------------------------------===//
2969 // Binary Operators.
2970 //===----------------------------------------------------------------------===//
2973 /// ::= ArithmeticOps TypeAndValue ',' Value
2975 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
2976 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
2977 bool LLParser::ParseArithmetic(Instruction
*&Inst
, PerFunctionState
&PFS
,
2978 unsigned Opc
, unsigned OperandType
) {
2979 LocTy Loc
; Value
*LHS
, *RHS
;
2980 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
2981 ParseToken(lltok::comma
, "expected ',' in arithmetic operation") ||
2982 ParseValue(LHS
->getType(), RHS
, PFS
))
2986 switch (OperandType
) {
2987 default: llvm_unreachable("Unknown operand type!");
2988 case 0: // int or FP.
2989 Valid
= LHS
->getType()->isIntOrIntVector() ||
2990 LHS
->getType()->isFPOrFPVector();
2992 case 1: Valid
= LHS
->getType()->isIntOrIntVector(); break;
2993 case 2: Valid
= LHS
->getType()->isFPOrFPVector(); break;
2997 return Error(Loc
, "invalid operand type for instruction");
2999 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
3004 /// ::= ArithmeticOps TypeAndValue ',' Value {
3005 bool LLParser::ParseLogical(Instruction
*&Inst
, PerFunctionState
&PFS
,
3007 LocTy Loc
; Value
*LHS
, *RHS
;
3008 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
3009 ParseToken(lltok::comma
, "expected ',' in logical operation") ||
3010 ParseValue(LHS
->getType(), RHS
, PFS
))
3013 if (!LHS
->getType()->isIntOrIntVector())
3014 return Error(Loc
,"instruction requires integer or integer vector operands");
3016 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
3022 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3023 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3024 bool LLParser::ParseCompare(Instruction
*&Inst
, PerFunctionState
&PFS
,
3026 // Parse the integer/fp comparison predicate.
3030 if (ParseCmpPredicate(Pred
, Opc
) ||
3031 ParseTypeAndValue(LHS
, Loc
, PFS
) ||
3032 ParseToken(lltok::comma
, "expected ',' after compare value") ||
3033 ParseValue(LHS
->getType(), RHS
, PFS
))
3036 if (Opc
== Instruction::FCmp
) {
3037 if (!LHS
->getType()->isFPOrFPVector())
3038 return Error(Loc
, "fcmp requires floating point operands");
3039 Inst
= new FCmpInst(Context
, CmpInst::Predicate(Pred
), LHS
, RHS
);
3041 assert(Opc
== Instruction::ICmp
&& "Unknown opcode for CmpInst!");
3042 if (!LHS
->getType()->isIntOrIntVector() &&
3043 !isa
<PointerType
>(LHS
->getType()))
3044 return Error(Loc
, "icmp requires integer operands");
3045 Inst
= new ICmpInst(Context
, CmpInst::Predicate(Pred
), LHS
, RHS
);
3050 //===----------------------------------------------------------------------===//
3051 // Other Instructions.
3052 //===----------------------------------------------------------------------===//
3056 /// ::= CastOpc TypeAndValue 'to' Type
3057 bool LLParser::ParseCast(Instruction
*&Inst
, PerFunctionState
&PFS
,
3059 LocTy Loc
; Value
*Op
;
3060 PATypeHolder
DestTy(Type::VoidTy
);
3061 if (ParseTypeAndValue(Op
, Loc
, PFS
) ||
3062 ParseToken(lltok::kw_to
, "expected 'to' after cast value") ||
3066 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
)) {
3067 CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
);
3068 return Error(Loc
, "invalid cast opcode for cast from '" +
3069 Op
->getType()->getDescription() + "' to '" +
3070 DestTy
->getDescription() + "'");
3072 Inst
= CastInst::Create((Instruction::CastOps
)Opc
, Op
, DestTy
);
3077 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3078 bool LLParser::ParseSelect(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3080 Value
*Op0
, *Op1
, *Op2
;
3081 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
3082 ParseToken(lltok::comma
, "expected ',' after select condition") ||
3083 ParseTypeAndValue(Op1
, PFS
) ||
3084 ParseToken(lltok::comma
, "expected ',' after select value") ||
3085 ParseTypeAndValue(Op2
, PFS
))
3088 if (const char *Reason
= SelectInst::areInvalidOperands(Op0
, Op1
, Op2
))
3089 return Error(Loc
, Reason
);
3091 Inst
= SelectInst::Create(Op0
, Op1
, Op2
);
3096 /// ::= 'va_arg' TypeAndValue ',' Type
3097 bool LLParser::ParseVA_Arg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3099 PATypeHolder
EltTy(Type::VoidTy
);
3101 if (ParseTypeAndValue(Op
, PFS
) ||
3102 ParseToken(lltok::comma
, "expected ',' after vaarg operand") ||
3103 ParseType(EltTy
, TypeLoc
))
3106 if (!EltTy
->isFirstClassType())
3107 return Error(TypeLoc
, "va_arg requires operand with first class type");
3109 Inst
= new VAArgInst(Op
, EltTy
);
3113 /// ParseExtractElement
3114 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3115 bool LLParser::ParseExtractElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3118 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
3119 ParseToken(lltok::comma
, "expected ',' after extract value") ||
3120 ParseTypeAndValue(Op1
, PFS
))
3123 if (!ExtractElementInst::isValidOperands(Op0
, Op1
))
3124 return Error(Loc
, "invalid extractelement operands");
3126 Inst
= ExtractElementInst::Create(Op0
, Op1
);
3130 /// ParseInsertElement
3131 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3132 bool LLParser::ParseInsertElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3134 Value
*Op0
, *Op1
, *Op2
;
3135 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
3136 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
3137 ParseTypeAndValue(Op1
, PFS
) ||
3138 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
3139 ParseTypeAndValue(Op2
, PFS
))
3142 if (!InsertElementInst::isValidOperands(Op0
, Op1
, Op2
))
3143 return Error(Loc
, "invalid insertelement operands");
3145 Inst
= InsertElementInst::Create(Op0
, Op1
, Op2
);
3149 /// ParseShuffleVector
3150 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3151 bool LLParser::ParseShuffleVector(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3153 Value
*Op0
, *Op1
, *Op2
;
3154 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
3155 ParseToken(lltok::comma
, "expected ',' after shuffle mask") ||
3156 ParseTypeAndValue(Op1
, PFS
) ||
3157 ParseToken(lltok::comma
, "expected ',' after shuffle value") ||
3158 ParseTypeAndValue(Op2
, PFS
))
3161 if (!ShuffleVectorInst::isValidOperands(Op0
, Op1
, Op2
))
3162 return Error(Loc
, "invalid extractelement operands");
3164 Inst
= new ShuffleVectorInst(Op0
, Op1
, Op2
);
3169 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Valueß ']')*
3170 bool LLParser::ParsePHI(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3171 PATypeHolder
Ty(Type::VoidTy
);
3173 LocTy TypeLoc
= Lex
.getLoc();
3175 if (ParseType(Ty
) ||
3176 ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
3177 ParseValue(Ty
, Op0
, PFS
) ||
3178 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
3179 ParseValue(Type::LabelTy
, Op1
, PFS
) ||
3180 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
3183 SmallVector
<std::pair
<Value
*, BasicBlock
*>, 16> PHIVals
;
3185 PHIVals
.push_back(std::make_pair(Op0
, cast
<BasicBlock
>(Op1
)));
3187 if (!EatIfPresent(lltok::comma
))
3190 if (ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
3191 ParseValue(Ty
, Op0
, PFS
) ||
3192 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
3193 ParseValue(Type::LabelTy
, Op1
, PFS
) ||
3194 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
3198 if (!Ty
->isFirstClassType())
3199 return Error(TypeLoc
, "phi node must have first class type");
3201 PHINode
*PN
= PHINode::Create(Ty
);
3202 PN
->reserveOperandSpace(PHIVals
.size());
3203 for (unsigned i
= 0, e
= PHIVals
.size(); i
!= e
; ++i
)
3204 PN
->addIncoming(PHIVals
[i
].first
, PHIVals
[i
].second
);
3210 /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
3211 /// ParameterList OptionalAttrs
3212 bool LLParser::ParseCall(Instruction
*&Inst
, PerFunctionState
&PFS
,
3214 unsigned CC
, RetAttrs
, FnAttrs
;
3215 PATypeHolder
RetType(Type::VoidTy
);
3218 SmallVector
<ParamInfo
, 16> ArgList
;
3219 LocTy CallLoc
= Lex
.getLoc();
3221 if ((isTail
&& ParseToken(lltok::kw_call
, "expected 'tail call'")) ||
3222 ParseOptionalCallingConv(CC
) ||
3223 ParseOptionalAttrs(RetAttrs
, 1) ||
3224 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
3225 ParseValID(CalleeID
) ||
3226 ParseParameterList(ArgList
, PFS
) ||
3227 ParseOptionalAttrs(FnAttrs
, 2))
3230 // If RetType is a non-function pointer type, then this is the short syntax
3231 // for the call, which means that RetType is just the return type. Infer the
3232 // rest of the function argument types from the arguments that are present.
3233 const PointerType
*PFTy
= 0;
3234 const FunctionType
*Ty
= 0;
3235 if (!(PFTy
= dyn_cast
<PointerType
>(RetType
)) ||
3236 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType()))) {
3237 // Pull out the types of all of the arguments...
3238 std::vector
<const Type
*> ParamTypes
;
3239 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
3240 ParamTypes
.push_back(ArgList
[i
].V
->getType());
3242 if (!FunctionType::isValidReturnType(RetType
))
3243 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
3245 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
3246 PFTy
= PointerType::getUnqual(Ty
);
3249 // Look up the callee.
3251 if (ConvertValIDToValue(PFTy
, CalleeID
, Callee
, PFS
)) return true;
3253 // FIXME: In LLVM 3.0, stop accepting zext, sext and inreg as optional
3254 // function attributes.
3255 unsigned ObsoleteFuncAttrs
= Attribute::ZExt
|Attribute::SExt
|Attribute::InReg
;
3256 if (FnAttrs
& ObsoleteFuncAttrs
) {
3257 RetAttrs
|= FnAttrs
& ObsoleteFuncAttrs
;
3258 FnAttrs
&= ~ObsoleteFuncAttrs
;
3261 // Set up the Attributes for the function.
3262 SmallVector
<AttributeWithIndex
, 8> Attrs
;
3263 if (RetAttrs
!= Attribute::None
)
3264 Attrs
.push_back(AttributeWithIndex::get(0, RetAttrs
));
3266 SmallVector
<Value
*, 8> Args
;
3268 // Loop through FunctionType's arguments and ensure they are specified
3269 // correctly. Also, gather any parameter attributes.
3270 FunctionType::param_iterator I
= Ty
->param_begin();
3271 FunctionType::param_iterator E
= Ty
->param_end();
3272 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
3273 const Type
*ExpectedTy
= 0;
3276 } else if (!Ty
->isVarArg()) {
3277 return Error(ArgList
[i
].Loc
, "too many arguments specified");
3280 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
3281 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
3282 ExpectedTy
->getDescription() + "'");
3283 Args
.push_back(ArgList
[i
].V
);
3284 if (ArgList
[i
].Attrs
!= Attribute::None
)
3285 Attrs
.push_back(AttributeWithIndex::get(i
+1, ArgList
[i
].Attrs
));
3289 return Error(CallLoc
, "not enough parameters specified for call");
3291 if (FnAttrs
!= Attribute::None
)
3292 Attrs
.push_back(AttributeWithIndex::get(~0, FnAttrs
));
3294 // Finish off the Attributes and check them
3295 AttrListPtr PAL
= AttrListPtr::get(Attrs
.begin(), Attrs
.end());
3297 CallInst
*CI
= CallInst::Create(Callee
, Args
.begin(), Args
.end());
3298 CI
->setTailCall(isTail
);
3299 CI
->setCallingConv(CC
);
3300 CI
->setAttributes(PAL
);
3305 //===----------------------------------------------------------------------===//
3306 // Memory Instructions.
3307 //===----------------------------------------------------------------------===//
3310 /// ::= 'malloc' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3311 /// ::= 'alloca' Type (',' TypeAndValue)? (',' OptionalAlignment)?
3312 bool LLParser::ParseAlloc(Instruction
*&Inst
, PerFunctionState
&PFS
,
3314 PATypeHolder
Ty(Type::VoidTy
);
3317 unsigned Alignment
= 0;
3318 if (ParseType(Ty
)) return true;
3320 if (EatIfPresent(lltok::comma
)) {
3321 if (Lex
.getKind() == lltok::kw_align
) {
3322 if (ParseOptionalAlignment(Alignment
)) return true;
3323 } else if (ParseTypeAndValue(Size
, SizeLoc
, PFS
) ||
3324 ParseOptionalCommaAlignment(Alignment
)) {
3329 if (Size
&& Size
->getType() != Type::Int32Ty
)
3330 return Error(SizeLoc
, "element count must be i32");
3332 if (Opc
== Instruction::Malloc
)
3333 Inst
= new MallocInst(Ty
, Size
, Alignment
);
3335 Inst
= new AllocaInst(Ty
, Size
, Alignment
);
3340 /// ::= 'free' TypeAndValue
3341 bool LLParser::ParseFree(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3342 Value
*Val
; LocTy Loc
;
3343 if (ParseTypeAndValue(Val
, Loc
, PFS
)) return true;
3344 if (!isa
<PointerType
>(Val
->getType()))
3345 return Error(Loc
, "operand to free must be a pointer");
3346 Inst
= new FreeInst(Val
);
3351 /// ::= 'volatile'? 'load' TypeAndValue (',' 'align' i32)?
3352 bool LLParser::ParseLoad(Instruction
*&Inst
, PerFunctionState
&PFS
,
3354 Value
*Val
; LocTy Loc
;
3356 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
3357 ParseOptionalCommaAlignment(Alignment
))
3360 if (!isa
<PointerType
>(Val
->getType()) ||
3361 !cast
<PointerType
>(Val
->getType())->getElementType()->isFirstClassType())
3362 return Error(Loc
, "load operand must be a pointer to a first class type");
3364 Inst
= new LoadInst(Val
, "", isVolatile
, Alignment
);
3369 /// ::= 'volatile'? 'store' TypeAndValue ',' TypeAndValue (',' 'align' i32)?
3370 bool LLParser::ParseStore(Instruction
*&Inst
, PerFunctionState
&PFS
,
3372 Value
*Val
, *Ptr
; LocTy Loc
, PtrLoc
;
3374 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
3375 ParseToken(lltok::comma
, "expected ',' after store operand") ||
3376 ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
3377 ParseOptionalCommaAlignment(Alignment
))
3380 if (!isa
<PointerType
>(Ptr
->getType()))
3381 return Error(PtrLoc
, "store operand must be a pointer");
3382 if (!Val
->getType()->isFirstClassType())
3383 return Error(Loc
, "store operand must be a first class value");
3384 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Val
->getType())
3385 return Error(Loc
, "stored value and pointer type do not match");
3387 Inst
= new StoreInst(Val
, Ptr
, isVolatile
, Alignment
);
3392 /// ::= 'getresult' TypeAndValue ',' i32
3393 /// FIXME: Remove support for getresult in LLVM 3.0
3394 bool LLParser::ParseGetResult(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3395 Value
*Val
; LocTy ValLoc
, EltLoc
;
3397 if (ParseTypeAndValue(Val
, ValLoc
, PFS
) ||
3398 ParseToken(lltok::comma
, "expected ',' after getresult operand") ||
3399 ParseUInt32(Element
, EltLoc
))
3402 if (!isa
<StructType
>(Val
->getType()) && !isa
<ArrayType
>(Val
->getType()))
3403 return Error(ValLoc
, "getresult inst requires an aggregate operand");
3404 if (!ExtractValueInst::getIndexedType(Val
->getType(), Element
))
3405 return Error(EltLoc
, "invalid getresult index for value");
3406 Inst
= ExtractValueInst::Create(Val
, Element
);
3410 /// ParseGetElementPtr
3411 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
3412 bool LLParser::ParseGetElementPtr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3413 Value
*Ptr
, *Val
; LocTy Loc
, EltLoc
;
3415 bool InBounds
= EatIfPresent(lltok::kw_inbounds
);
3417 if (ParseTypeAndValue(Ptr
, Loc
, PFS
)) return true;
3419 if (!isa
<PointerType
>(Ptr
->getType()))
3420 return Error(Loc
, "base of getelementptr must be a pointer");
3422 SmallVector
<Value
*, 16> Indices
;
3423 while (EatIfPresent(lltok::comma
)) {
3424 if (ParseTypeAndValue(Val
, EltLoc
, PFS
)) return true;
3425 if (!isa
<IntegerType
>(Val
->getType()))
3426 return Error(EltLoc
, "getelementptr index must be an integer");
3427 Indices
.push_back(Val
);
3430 if (!GetElementPtrInst::getIndexedType(Ptr
->getType(),
3431 Indices
.begin(), Indices
.end()))
3432 return Error(Loc
, "invalid getelementptr indices");
3433 Inst
= GetElementPtrInst::Create(Ptr
, Indices
.begin(), Indices
.end());
3435 cast
<GEPOperator
>(Inst
)->setIsInBounds(true);
3439 /// ParseExtractValue
3440 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
3441 bool LLParser::ParseExtractValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3442 Value
*Val
; LocTy Loc
;
3443 SmallVector
<unsigned, 4> Indices
;
3444 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
3445 ParseIndexList(Indices
))
3448 if (!isa
<StructType
>(Val
->getType()) && !isa
<ArrayType
>(Val
->getType()))
3449 return Error(Loc
, "extractvalue operand must be array or struct");
3451 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
.begin(),
3453 return Error(Loc
, "invalid indices for extractvalue");
3454 Inst
= ExtractValueInst::Create(Val
, Indices
.begin(), Indices
.end());
3458 /// ParseInsertValue
3459 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
3460 bool LLParser::ParseInsertValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
3461 Value
*Val0
, *Val1
; LocTy Loc0
, Loc1
;
3462 SmallVector
<unsigned, 4> Indices
;
3463 if (ParseTypeAndValue(Val0
, Loc0
, PFS
) ||
3464 ParseToken(lltok::comma
, "expected comma after insertvalue operand") ||
3465 ParseTypeAndValue(Val1
, Loc1
, PFS
) ||
3466 ParseIndexList(Indices
))
3469 if (!isa
<StructType
>(Val0
->getType()) && !isa
<ArrayType
>(Val0
->getType()))
3470 return Error(Loc0
, "extractvalue operand must be array or struct");
3472 if (!ExtractValueInst::getIndexedType(Val0
->getType(), Indices
.begin(),
3474 return Error(Loc0
, "invalid indices for insertvalue");
3475 Inst
= InsertValueInst::Create(Val0
, Val1
, Indices
.begin(), Indices
.end());
3479 //===----------------------------------------------------------------------===//
3480 // Embedded metadata.
3481 //===----------------------------------------------------------------------===//
3483 /// ParseMDNodeVector
3484 /// ::= Element (',' Element)*
3486 /// ::= 'null' | TypeAndValue
3487 bool LLParser::ParseMDNodeVector(SmallVectorImpl
<Value
*> &Elts
) {
3488 assert(Lex
.getKind() == lltok::lbrace
);
3492 if (Lex
.getKind() == lltok::kw_null
) {
3496 PATypeHolder
Ty(Type::VoidTy
);
3497 if (ParseType(Ty
)) return true;
3498 if (Lex
.getKind() == lltok::Metadata
) {
3500 MetadataBase
*Node
= 0;
3501 if (!ParseMDNode(Node
))
3504 MetadataBase
*MDS
= 0;
3505 if (ParseMDString(MDS
)) return true;
3510 if (ParseGlobalValue(Ty
, C
)) return true;
3515 } while (EatIfPresent(lltok::comma
));