1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Streams.h"
35 // The following is a gross hack. In order to rid the libAsmParser library of
36 // exceptions, we have to have a way of getting the yyparse function to go into
37 // an error situation. So, whenever we want an error to occur, the GenerateError
38 // function (see bottom of file) sets TriggerError. Then, at the end of each
39 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
40 // (a goto) to put YACC in error state. Furthermore, several calls to
41 // GenerateError are made from inside productions and they must simulate the
42 // previous exception behavior by exiting the production immediately. We have
43 // replaced these with the GEN_ERROR macro which calls GeneratError and then
44 // immediately invokes YYERROR. This would be so much cleaner if it was a
45 // recursive descent parser.
46 static bool TriggerError
= false
;
47 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
48 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
50 int yyerror(const char *ErrorMsg
); // Forward declarations to prevent "implicit
51 int yylex(); // declaration" of xxx warnings.
55 std
::string CurFilename
;
58 Debug
("debug-yacc", cl
::desc
("Print yacc debug state changes"),
59 cl
::Hidden
, cl
::init
(false
));
64 static Module
*ParserResult
;
66 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
67 // relating to upreferences in the input stream.
69 //#define DEBUG_UPREFS 1
71 #define UR_OUT(X) cerr << X
76 #define YYERROR_VERBOSE 1
78 static GlobalVariable
*CurGV
;
81 // This contains info used when building the body of a function. It is
82 // destroyed when the function is completed.
84 typedef std
::vector
<Value
*> ValueList
; // Numbered defs
87 ResolveDefinitions
(ValueList
&LateResolvers
, ValueList
*FutureLateResolvers
=0);
89 static struct PerModuleInfo
{
90 Module
*CurrentModule
;
91 ValueList Values
; // Module level numbered definitions
92 ValueList LateResolveValues
;
93 std
::vector
<PATypeHolder
> Types
;
94 std
::map
<ValID
, PATypeHolder
> LateResolveTypes
;
96 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
97 /// how they were referenced and on which line of the input they came from so
98 /// that we can resolve them later and print error messages as appropriate.
99 std
::map
<Value
*, std
::pair
<ValID
, int> > PlaceHolderInfo
;
101 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
102 // references to global values. Global values may be referenced before they
103 // are defined, and if so, the temporary object that they represent is held
104 // here. This is used for forward references of GlobalValues.
106 typedef std
::map
<std
::pair
<const PointerType
*,
107 ValID
>, GlobalValue
*> GlobalRefsType
;
108 GlobalRefsType GlobalRefs
;
111 // If we could not resolve some functions at function compilation time
112 // (calls to functions before they are defined), resolve them now... Types
113 // are resolved when the constant pool has been completely parsed.
115 ResolveDefinitions
(LateResolveValues
);
119 // Check to make sure that all global value forward references have been
122 if
(!GlobalRefs.empty
()) {
123 std
::string UndefinedReferences
= "Unresolved global references exist:\n";
125 for
(GlobalRefsType
::iterator I
= GlobalRefs.begin
(), E
=GlobalRefs.end
();
127 UndefinedReferences
+= " " + I
->first.first
->getDescription
() + " " +
128 I
->first.second.getName
() + "\n";
130 GenerateError
(UndefinedReferences
);
134 Values.clear
(); // Clear out function local definitions
139 // GetForwardRefForGlobal - Check to see if there is a forward reference
140 // for this global. If so, remove it from the GlobalRefs map and return it.
141 // If not, just return null.
142 GlobalValue
*GetForwardRefForGlobal
(const PointerType
*PTy
, ValID ID
) {
143 // Check to see if there is a forward reference to this global variable...
144 // if there is, eliminate it and patch the reference to use the new def'n.
145 GlobalRefsType
::iterator I
= GlobalRefs.find
(std
::make_pair
(PTy
, ID
));
146 GlobalValue
*Ret
= 0;
147 if
(I
!= GlobalRefs.end
()) {
154 bool TypeIsUnresolved
(PATypeHolder
* PATy
) {
155 // If it isn't abstract, its resolved
156 const Type
* Ty
= PATy
->get
();
157 if
(!Ty
->isAbstract
())
159 // Traverse the type looking for abstract types. If it isn't abstract then
160 // we don't need to traverse that leg of the type.
161 std
::vector
<const Type
*> WorkList
, SeenList
;
162 WorkList.push_back
(Ty
);
163 while
(!WorkList.empty
()) {
164 const Type
* Ty
= WorkList.back
();
165 SeenList.push_back
(Ty
);
167 if
(const OpaqueType
* OpTy
= dyn_cast
<OpaqueType
>(Ty
)) {
168 // Check to see if this is an unresolved type
169 std
::map
<ValID
, PATypeHolder
>::iterator I
= LateResolveTypes.begin
();
170 std
::map
<ValID
, PATypeHolder
>::iterator E
= LateResolveTypes.end
();
171 for
( ; I
!= E
; ++I
) {
172 if
(I
->second.get
() == OpTy
)
175 } else if
(const SequentialType
* SeqTy
= dyn_cast
<SequentialType
>(Ty
)) {
176 const Type
* TheTy
= SeqTy
->getElementType
();
177 if
(TheTy
->isAbstract
() && TheTy
!= Ty
) {
178 std
::vector
<const Type
*>::iterator I
= SeenList.begin
(),
184 WorkList.push_back
(TheTy
);
186 } else if
(const StructType
* StrTy
= dyn_cast
<StructType
>(Ty
)) {
187 for
(unsigned i
= 0; i
< StrTy
->getNumElements
(); ++i
) {
188 const Type
* TheTy
= StrTy
->getElementType
(i
);
189 if
(TheTy
->isAbstract
() && TheTy
!= Ty
) {
190 std
::vector
<const Type
*>::iterator I
= SeenList.begin
(),
196 WorkList.push_back
(TheTy
);
205 static struct PerFunctionInfo
{
206 Function
*CurrentFunction
; // Pointer to current function being created
208 ValueList Values
; // Keep track of #'d definitions
210 ValueList LateResolveValues
;
211 bool isDeclare
; // Is this function a forward declararation?
212 GlobalValue
::LinkageTypes Linkage
; // Linkage for forward declaration.
213 GlobalValue
::VisibilityTypes Visibility
;
215 /// BBForwardRefs - When we see forward references to basic blocks, keep
216 /// track of them here.
217 std
::map
<ValID
, BasicBlock
*> BBForwardRefs
;
219 inline PerFunctionInfo
() {
222 Linkage
= GlobalValue
::ExternalLinkage
;
223 Visibility
= GlobalValue
::DefaultVisibility
;
226 inline
void FunctionStart
(Function
*M
) {
231 void FunctionDone
() {
232 // Any forward referenced blocks left?
233 if
(!BBForwardRefs.empty
()) {
234 GenerateError
("Undefined reference to label " +
235 BBForwardRefs.begin
()->second
->getName
());
239 // Resolve all forward references now.
240 ResolveDefinitions
(LateResolveValues
, &CurModule.LateResolveValues
);
242 Values.clear
(); // Clear out function local definitions
243 BBForwardRefs.clear
();
246 Linkage
= GlobalValue
::ExternalLinkage
;
247 Visibility
= GlobalValue
::DefaultVisibility
;
249 } CurFun
; // Info for the current function...
251 static bool inFunctionScope
() { return CurFun.CurrentFunction
!= 0; }
254 //===----------------------------------------------------------------------===//
255 // Code to handle definitions of all the types
256 //===----------------------------------------------------------------------===//
258 static void InsertValue
(Value
*V
, ValueList
&ValueTab
= CurFun.Values
) {
259 // Things that have names or are void typed don't get slot numbers
260 if
(V
->hasName
() ||
(V
->getType
() == Type
::VoidTy
))
263 // In the case of function values, we have to allow for the forward reference
264 // of basic blocks, which are included in the numbering. Consequently, we keep
265 // track of the next insertion location with NextValNum. When a BB gets
266 // inserted, it could change the size of the CurFun.Values vector.
267 if
(&ValueTab
== &CurFun.Values
) {
268 if
(ValueTab.size
() <= CurFun.NextValNum
)
269 ValueTab.resize
(CurFun.NextValNum
+1);
270 ValueTab
[CurFun.NextValNum
++] = V
;
273 // For all other lists, its okay to just tack it on the back of the vector.
274 ValueTab.push_back
(V
);
277 static const Type
*getTypeVal
(const ValID
&D
, bool DoNotImprovise
= false
) {
279 case ValID
::LocalID
: // Is it a numbered definition?
280 // Module constants occupy the lowest numbered slots...
281 if
(D.Num
< CurModule.Types.size
())
282 return CurModule.Types
[D.Num
];
284 case ValID
::LocalName
: // Is it a named definition?
285 if
(const Type
*N
= CurModule.CurrentModule
->getTypeByName
(D.getName
())) {
286 D.destroy
(); // Free old strdup'd memory...
291 GenerateError
("Internal parser error: Invalid symbol type reference");
295 // If we reached here, we referenced either a symbol that we don't know about
296 // or an id number that hasn't been read yet. We may be referencing something
297 // forward, so just create an entry to be resolved later and get to it...
299 if
(DoNotImprovise
) return
0; // Do we just want a null to be returned?
302 if
(inFunctionScope
()) {
303 if
(D.Type
== ValID
::LocalName
) {
304 GenerateError
("Reference to an undefined type: '" + D.getName
() + "'");
307 GenerateError
("Reference to an undefined type: #" + utostr
(D.Num
));
312 std
::map
<ValID
, PATypeHolder
>::iterator I
=CurModule.LateResolveTypes.find
(D
);
313 if
(I
!= CurModule.LateResolveTypes.end
())
316 Type
*Typ
= OpaqueType
::get
();
317 CurModule.LateResolveTypes.insert
(std
::make_pair
(D
, Typ
));
321 // getExistingVal - Look up the value specified by the provided type and
322 // the provided ValID. If the value exists and has already been defined, return
323 // it. Otherwise return null.
325 static Value
*getExistingVal
(const Type
*Ty
, const ValID
&D
) {
326 if
(isa
<FunctionType
>(Ty
)) {
327 GenerateError
("Functions are not values and "
328 "must be referenced as pointers");
333 case ValID
::LocalID
: { // Is it a numbered definition?
334 // Check that the number is within bounds.
335 if
(D.Num
>= CurFun.Values.size
())
337 Value
*Result
= CurFun.Values
[D.Num
];
338 if
(Ty
!= Result
->getType
()) {
339 GenerateError
("Numbered value (%" + utostr
(D.Num
) + ") of type '" +
340 Result
->getType
()->getDescription
() + "' does not match "
341 "expected type, '" + Ty
->getDescription
() + "'");
346 case ValID
::GlobalID
: { // Is it a numbered definition?
347 if
(D.Num
>= CurModule.Values.size
())
349 Value
*Result
= CurModule.Values
[D.Num
];
350 if
(Ty
!= Result
->getType
()) {
351 GenerateError
("Numbered value (@" + utostr
(D.Num
) + ") of type '" +
352 Result
->getType
()->getDescription
() + "' does not match "
353 "expected type, '" + Ty
->getDescription
() + "'");
359 case ValID
::LocalName
: { // Is it a named definition?
360 if
(!inFunctionScope
())
362 ValueSymbolTable
&SymTab
= CurFun.CurrentFunction
->getValueSymbolTable
();
363 Value
*N
= SymTab.lookup
(D.getName
());
366 if
(N
->getType
() != Ty
)
369 D.destroy
(); // Free old strdup'd memory...
372 case ValID
::GlobalName
: { // Is it a named definition?
373 ValueSymbolTable
&SymTab
= CurModule.CurrentModule
->getValueSymbolTable
();
374 Value
*N
= SymTab.lookup
(D.getName
());
377 if
(N
->getType
() != Ty
)
380 D.destroy
(); // Free old strdup'd memory...
384 // Check to make sure that "Ty" is an integral type, and that our
385 // value will fit into the specified type...
386 case ValID
::ConstSIntVal
: // Is it a constant pool reference??
387 if
(!ConstantInt
::isValueValidForType
(Ty
, D.ConstPool64
)) {
388 GenerateError
("Signed integral constant '" +
389 itostr
(D.ConstPool64
) + "' is invalid for type '" +
390 Ty
->getDescription
() + "'");
393 return ConstantInt
::get
(Ty
, D.ConstPool64
, true
);
395 case ValID
::ConstUIntVal
: // Is it an unsigned const pool reference?
396 if
(!ConstantInt
::isValueValidForType
(Ty
, D.UConstPool64
)) {
397 if
(!ConstantInt
::isValueValidForType
(Ty
, D.ConstPool64
)) {
398 GenerateError
("Integral constant '" + utostr
(D.UConstPool64
) +
399 "' is invalid or out of range");
401 } else
{ // This is really a signed reference. Transmogrify.
402 return ConstantInt
::get
(Ty
, D.ConstPool64
, true
);
405 return ConstantInt
::get
(Ty
, D.UConstPool64
);
408 case ValID
::ConstFPVal
: // Is it a floating point const pool reference?
409 if
(!ConstantFP
::isValueValidForType
(Ty
, D.ConstPoolFP
)) {
410 GenerateError
("FP constant invalid for type");
413 return ConstantFP
::get
(Ty
, D.ConstPoolFP
);
415 case ValID
::ConstNullVal
: // Is it a null value?
416 if
(!isa
<PointerType
>(Ty
)) {
417 GenerateError
("Cannot create a a non pointer null");
420 return ConstantPointerNull
::get
(cast
<PointerType
>(Ty
));
422 case ValID
::ConstUndefVal
: // Is it an undef value?
423 return UndefValue
::get
(Ty
);
425 case ValID
::ConstZeroVal
: // Is it a zero value?
426 return Constant
::getNullValue
(Ty
);
428 case ValID
::ConstantVal
: // Fully resolved constant?
429 if
(D.ConstantValue
->getType
() != Ty
) {
430 GenerateError
("Constant expression type different from required type");
433 return D.ConstantValue
;
435 case ValID
::InlineAsmVal
: { // Inline asm expression
436 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
437 const FunctionType
*FTy
=
438 PTy ? dyn_cast
<FunctionType
>(PTy
->getElementType
()) : 0;
439 if
(!FTy ||
!InlineAsm
::Verify
(FTy
, D.IAD
->Constraints
)) {
440 GenerateError
("Invalid type for asm constraint string");
443 InlineAsm
*IA
= InlineAsm
::get
(FTy
, D.IAD
->AsmString
, D.IAD
->Constraints
,
444 D.IAD
->HasSideEffects
);
445 D.destroy
(); // Free InlineAsmDescriptor.
449 assert
(0 && "Unhandled case!");
453 assert
(0 && "Unhandled case!");
457 // getVal - This function is identical to getExistingVal, except that if a
458 // value is not already defined, it "improvises" by creating a placeholder var
459 // that looks and acts just like the requested variable. When the value is
460 // defined later, all uses of the placeholder variable are replaced with the
463 static Value
*getVal
(const Type
*Ty
, const ValID
&ID
) {
464 if
(Ty
== Type
::LabelTy
) {
465 GenerateError
("Cannot use a basic block here");
469 // See if the value has already been defined.
470 Value
*V
= getExistingVal
(Ty
, ID
);
472 if
(TriggerError
) return
0;
474 if
(!Ty
->isFirstClassType
() && !isa
<OpaqueType
>(Ty
)) {
475 GenerateError
("Invalid use of a composite type");
479 // If we reached here, we referenced either a symbol that we don't know about
480 // or an id number that hasn't been read yet. We may be referencing something
481 // forward, so just create an entry to be resolved later and get to it...
484 case ValID
::GlobalName
:
485 case ValID
::GlobalID
: {
486 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
488 GenerateError
("Invalid type for reference to global" );
491 const Type
* ElTy
= PTy
->getElementType
();
492 if
(const FunctionType
*FTy
= dyn_cast
<FunctionType
>(ElTy
))
493 V
= new Function
(FTy
, GlobalValue
::ExternalLinkage
);
495 V
= new GlobalVariable
(ElTy
, false
, GlobalValue
::ExternalLinkage
);
499 V
= new Argument
(Ty
);
502 // Remember where this forward reference came from. FIXME, shouldn't we try
503 // to recycle these things??
504 CurModule.PlaceHolderInfo.insert
(std
::make_pair
(V
, std
::make_pair
(ID
,
507 if
(inFunctionScope
())
508 InsertValue
(V
, CurFun.LateResolveValues
);
510 InsertValue
(V
, CurModule.LateResolveValues
);
514 /// defineBBVal - This is a definition of a new basic block with the specified
515 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
516 static BasicBlock
*defineBBVal
(const ValID
&ID
) {
517 assert
(inFunctionScope
() && "Can't get basic block at global scope!");
521 // First, see if this was forward referenced
523 std
::map
<ValID
, BasicBlock
*>::iterator BBI
= CurFun.BBForwardRefs.find
(ID
);
524 if
(BBI
!= CurFun.BBForwardRefs.end
()) {
526 // The forward declaration could have been inserted anywhere in the
527 // function: insert it into the correct place now.
528 CurFun.CurrentFunction
->getBasicBlockList
().remove
(BB
);
529 CurFun.CurrentFunction
->getBasicBlockList
().push_back
(BB
);
531 // We're about to erase the entry, save the key so we can clean it up.
532 ValID Tmp
= BBI
->first
;
534 // Erase the forward ref from the map as its no longer "forward"
535 CurFun.BBForwardRefs.erase
(ID
);
537 // The key has been removed from the map but so we don't want to leave
538 // strdup'd memory around so destroy it too.
541 // If its a numbered definition, bump the number and set the BB value.
542 if
(ID.Type
== ValID
::LocalID
) {
543 assert
(ID.Num
== CurFun.NextValNum
&& "Invalid new block number");
551 // We haven't seen this BB before and its first mention is a definition.
552 // Just create it and return it.
553 std
::string Name
(ID.Type
== ValID
::LocalName ? ID.getName
() : "");
554 BB
= new BasicBlock
(Name
, CurFun.CurrentFunction
);
555 if
(ID.Type
== ValID
::LocalID
) {
556 assert
(ID.Num
== CurFun.NextValNum
&& "Invalid new block number");
560 ID.destroy
(); // Free strdup'd memory
564 /// getBBVal - get an existing BB value or create a forward reference for it.
566 static BasicBlock
*getBBVal
(const ValID
&ID
) {
567 assert
(inFunctionScope
() && "Can't get basic block at global scope!");
571 std
::map
<ValID
, BasicBlock
*>::iterator BBI
= CurFun.BBForwardRefs.find
(ID
);
572 if
(BBI
!= CurFun.BBForwardRefs.end
()) {
574 } if
(ID.Type
== ValID
::LocalName
) {
575 std
::string Name
= ID.getName
();
576 Value
*N
= CurFun.CurrentFunction
->getValueSymbolTable
().lookup
(Name
);
578 if
(N
->getType
()->getTypeID
() == Type
::LabelTyID
)
579 BB
= cast
<BasicBlock
>(N
);
581 GenerateError
("Reference to label '" + Name
+ "' is actually of type '"+
582 N
->getType
()->getDescription
() + "'");
583 } else if
(ID.Type
== ValID
::LocalID
) {
584 if
(ID.Num
< CurFun.NextValNum
&& ID.Num
< CurFun.Values.size
()) {
585 if
(CurFun.Values
[ID.Num
]->getType
()->getTypeID
() == Type
::LabelTyID
)
586 BB
= cast
<BasicBlock
>(CurFun.Values
[ID.Num
]);
588 GenerateError
("Reference to label '%" + utostr
(ID.Num
) +
589 "' is actually of type '"+
590 CurFun.Values
[ID.Num
]->getType
()->getDescription
() + "'");
593 GenerateError
("Illegal label reference " + ID.getName
());
597 // If its already been defined, return it now.
599 ID.destroy
(); // Free strdup'd memory.
603 // Otherwise, this block has not been seen before, create it.
605 if
(ID.Type
== ValID
::LocalName
)
607 BB
= new BasicBlock
(Name
, CurFun.CurrentFunction
);
609 // Insert it in the forward refs map.
610 CurFun.BBForwardRefs
[ID
] = BB
;
616 //===----------------------------------------------------------------------===//
617 // Code to handle forward references in instructions
618 //===----------------------------------------------------------------------===//
620 // This code handles the late binding needed with statements that reference
621 // values not defined yet... for example, a forward branch, or the PHI node for
624 // This keeps a table (CurFun.LateResolveValues) of all such forward references
625 // and back patchs after we are done.
628 // ResolveDefinitions - If we could not resolve some defs at parsing
629 // time (forward branches, phi functions for loops, etc...) resolve the
633 ResolveDefinitions
(ValueList
&LateResolvers
, ValueList
*FutureLateResolvers
) {
634 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
635 while
(!LateResolvers.empty
()) {
636 Value
*V
= LateResolvers.back
();
637 LateResolvers.pop_back
();
639 std
::map
<Value
*, std
::pair
<ValID
, int> >::iterator PHI
=
640 CurModule.PlaceHolderInfo.find
(V
);
641 assert
(PHI
!= CurModule.PlaceHolderInfo.end
() && "Placeholder error!");
643 ValID
&DID
= PHI
->second.first
;
645 Value
*TheRealValue
= getExistingVal
(V
->getType
(), DID
);
649 V
->replaceAllUsesWith
(TheRealValue
);
651 CurModule.PlaceHolderInfo.erase
(PHI
);
652 } else if
(FutureLateResolvers
) {
653 // Functions have their unresolved items forwarded to the module late
655 InsertValue
(V
, *FutureLateResolvers
);
657 if
(DID.Type
== ValID
::LocalName || DID.Type
== ValID
::GlobalName
) {
658 GenerateError
("Reference to an invalid definition: '" +DID.getName
()+
659 "' of type '" + V
->getType
()->getDescription
() + "'",
663 GenerateError
("Reference to an invalid definition: #" +
664 itostr
(DID.Num
) + " of type '" +
665 V
->getType
()->getDescription
() + "'",
671 LateResolvers.clear
();
674 // ResolveTypeTo - A brand new type was just declared. This means that (if
675 // name is not null) things referencing Name can be resolved. Otherwise, things
676 // refering to the number can be resolved. Do this now.
678 static void ResolveTypeTo
(std
::string *Name
, const Type
*ToTy
) {
681 D
= ValID
::createLocalName
(*Name
);
683 D
= ValID
::createLocalID
(CurModule.Types.size
());
685 std
::map
<ValID
, PATypeHolder
>::iterator I
=
686 CurModule.LateResolveTypes.find
(D
);
687 if
(I
!= CurModule.LateResolveTypes.end
()) {
688 ((DerivedType
*)I
->second.get
())->refineAbstractTypeTo
(ToTy
);
689 CurModule.LateResolveTypes.erase
(I
);
693 // setValueName - Set the specified value to the name given. The name may be
694 // null potentially, in which case this is a noop. The string passed in is
695 // assumed to be a malloc'd string buffer, and is free'd by this function.
697 static void setValueName
(Value
*V
, std
::string *NameStr
) {
698 if
(!NameStr
) return
;
699 std
::string Name
(*NameStr
); // Copy string
700 delete NameStr
; // Free old string
702 if
(V
->getType
() == Type
::VoidTy
) {
703 GenerateError
("Can't assign name '" + Name
+"' to value with void type");
707 assert
(inFunctionScope
() && "Must be in function scope!");
708 ValueSymbolTable
&ST
= CurFun.CurrentFunction
->getValueSymbolTable
();
709 if
(ST.lookup
(Name
)) {
710 GenerateError
("Redefinition of value '" + Name
+ "' of type '" +
711 V
->getType
()->getDescription
() + "'");
719 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
720 /// this is a declaration, otherwise it is a definition.
721 static GlobalVariable
*
722 ParseGlobalVariable
(std
::string *NameStr
,
723 GlobalValue
::LinkageTypes Linkage
,
724 GlobalValue
::VisibilityTypes Visibility
,
725 bool isConstantGlobal
, const Type
*Ty
,
726 Constant
*Initializer
, bool IsThreadLocal
) {
727 if
(isa
<FunctionType
>(Ty
)) {
728 GenerateError
("Cannot declare global vars of function type");
732 const PointerType
*PTy
= PointerType
::get
(Ty
);
736 Name
= *NameStr
; // Copy string
737 delete NameStr
; // Free old string
740 // See if this global value was forward referenced. If so, recycle the
744 ID
= ValID
::createGlobalName
(Name
);
746 ID
= ValID
::createGlobalID
(CurModule.Values.size
());
749 if
(GlobalValue
*FWGV
= CurModule.GetForwardRefForGlobal
(PTy
, ID
)) {
750 // Move the global to the end of the list, from whereever it was
751 // previously inserted.
752 GlobalVariable
*GV
= cast
<GlobalVariable
>(FWGV
);
753 CurModule.CurrentModule
->getGlobalList
().remove
(GV
);
754 CurModule.CurrentModule
->getGlobalList
().push_back
(GV
);
755 GV
->setInitializer
(Initializer
);
756 GV
->setLinkage
(Linkage
);
757 GV
->setVisibility
(Visibility
);
758 GV
->setConstant
(isConstantGlobal
);
759 GV
->setThreadLocal
(IsThreadLocal
);
760 InsertValue
(GV
, CurModule.Values
);
764 // If this global has a name
766 // if the global we're parsing has an initializer (is a definition) and
767 // has external linkage.
768 if
(Initializer
&& Linkage
!= GlobalValue
::InternalLinkage
)
769 // If there is already a global with external linkage with this name
770 if
(CurModule.CurrentModule
->getGlobalVariable
(Name
, false
)) {
771 // If we allow this GVar to get created, it will be renamed in the
772 // symbol table because it conflicts with an existing GVar. We can't
773 // allow redefinition of GVars whose linking indicates that their name
774 // must stay the same. Issue the error.
775 GenerateError
("Redefinition of global variable named '" + Name
+
776 "' of type '" + Ty
->getDescription
() + "'");
781 // Otherwise there is no existing GV to use, create one now.
783 new GlobalVariable
(Ty
, isConstantGlobal
, Linkage
, Initializer
, Name
,
784 CurModule.CurrentModule
, IsThreadLocal
);
785 GV
->setVisibility
(Visibility
);
786 InsertValue
(GV
, CurModule.Values
);
790 // setTypeName - Set the specified type to the name given. The name may be
791 // null potentially, in which case this is a noop. The string passed in is
792 // assumed to be a malloc'd string buffer, and is freed by this function.
794 // This function returns true if the type has already been defined, but is
795 // allowed to be redefined in the specified context. If the name is a new name
796 // for the type plane, it is inserted and false is returned.
797 static bool setTypeName
(const Type
*T
, std
::string *NameStr
) {
798 assert
(!inFunctionScope
() && "Can't give types function-local names!");
799 if
(NameStr
== 0) return false
;
801 std
::string Name
(*NameStr
); // Copy string
802 delete NameStr
; // Free old string
804 // We don't allow assigning names to void type
805 if
(T
== Type
::VoidTy
) {
806 GenerateError
("Can't assign name '" + Name
+ "' to the void type");
810 // Set the type name, checking for conflicts as we do so.
811 bool AlreadyExists
= CurModule.CurrentModule
->addTypeName
(Name
, T
);
813 if
(AlreadyExists
) { // Inserting a name that is already defined???
814 const Type
*Existing
= CurModule.CurrentModule
->getTypeByName
(Name
);
815 assert
(Existing
&& "Conflict but no matching type?!");
817 // There is only one case where this is allowed: when we are refining an
818 // opaque type. In this case, Existing will be an opaque type.
819 if
(const OpaqueType
*OpTy
= dyn_cast
<OpaqueType
>(Existing
)) {
820 // We ARE replacing an opaque type!
821 const_cast
<OpaqueType
*>(OpTy
)->refineAbstractTypeTo
(T
);
825 // Otherwise, this is an attempt to redefine a type. That's okay if
826 // the redefinition is identical to the original. This will be so if
827 // Existing and T point to the same Type object. In this one case we
828 // allow the equivalent redefinition.
829 if
(Existing
== T
) return true
; // Yes, it's equal.
831 // Any other kind of (non-equivalent) redefinition is an error.
832 GenerateError
("Redefinition of type named '" + Name
+ "' of type '" +
833 T
->getDescription
() + "'");
839 //===----------------------------------------------------------------------===//
840 // Code for handling upreferences in type names...
843 // TypeContains - Returns true if Ty directly contains E in it.
845 static bool TypeContains
(const Type
*Ty
, const Type
*E
) {
846 return std
::find
(Ty
->subtype_begin
(), Ty
->subtype_end
(),
847 E
) != Ty
->subtype_end
();
852 // NestingLevel - The number of nesting levels that need to be popped before
853 // this type is resolved.
854 unsigned NestingLevel
;
856 // LastContainedTy - This is the type at the current binding level for the
857 // type. Every time we reduce the nesting level, this gets updated.
858 const Type
*LastContainedTy
;
860 // UpRefTy - This is the actual opaque type that the upreference is
864 UpRefRecord
(unsigned NL
, OpaqueType
*URTy
)
865 : NestingLevel
(NL
), LastContainedTy
(URTy
), UpRefTy
(URTy
) {}
869 // UpRefs - A list of the outstanding upreferences that need to be resolved.
870 static std
::vector
<UpRefRecord
> UpRefs
;
872 /// HandleUpRefs - Every time we finish a new layer of types, this function is
873 /// called. It loops through the UpRefs vector, which is a list of the
874 /// currently active types. For each type, if the up reference is contained in
875 /// the newly completed type, we decrement the level count. When the level
876 /// count reaches zero, the upreferenced type is the type that is passed in:
877 /// thus we can complete the cycle.
879 static PATypeHolder HandleUpRefs
(const Type
*ty
) {
880 // If Ty isn't abstract, or if there are no up-references in it, then there is
881 // nothing to resolve here.
882 if
(!ty
->isAbstract
() || UpRefs.empty
()) return ty
;
885 UR_OUT
("Type '" << Ty
->getDescription
() <<
886 "' newly formed. Resolving upreferences.\n" <<
887 UpRefs.size
() << " upreferences active!\n");
889 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
890 // to zero), we resolve them all together before we resolve them to Ty. At
891 // the end of the loop, if there is anything to resolve to Ty, it will be in
893 OpaqueType
*TypeToResolve
= 0;
895 for
(unsigned i
= 0; i
!= UpRefs.size
(); ++i
) {
896 UR_OUT
(" UR#" << i
<< " - TypeContains(" << Ty
->getDescription
() << ", "
897 << UpRefs
[i
].second
->getDescription
() << ") = "
898 << (TypeContains
(Ty
, UpRefs
[i
].second
) ?
"true" : "false") << "\n");
899 if
(TypeContains
(Ty
, UpRefs
[i
].LastContainedTy
)) {
900 // Decrement level of upreference
901 unsigned Level
= --UpRefs
[i
].NestingLevel
;
902 UpRefs
[i
].LastContainedTy
= Ty
;
903 UR_OUT
(" Uplevel Ref Level = " << Level
<< "\n");
904 if
(Level
== 0) { // Upreference should be resolved!
905 if
(!TypeToResolve
) {
906 TypeToResolve
= UpRefs
[i
].UpRefTy
;
908 UR_OUT
(" * Resolving upreference for "
909 << UpRefs
[i
].second
->getDescription
() << "\n";
910 std
::string OldName
= UpRefs
[i
].UpRefTy
->getDescription
());
911 UpRefs
[i
].UpRefTy
->refineAbstractTypeTo
(TypeToResolve
);
912 UR_OUT
(" * Type '" << OldName
<< "' refined upreference to: "
913 << (const void*)Ty
<< ", " << Ty
->getDescription
() << "\n");
915 UpRefs.erase
(UpRefs.begin
()+i
); // Remove from upreference list...
916 --i
; // Do not skip the next element...
922 UR_OUT
(" * Resolving upreference for "
923 << UpRefs
[i
].second
->getDescription
() << "\n";
924 std
::string OldName
= TypeToResolve
->getDescription
());
925 TypeToResolve
->refineAbstractTypeTo
(Ty
);
931 //===----------------------------------------------------------------------===//
932 // RunVMAsmParser - Define an interface to this parser
933 //===----------------------------------------------------------------------===//
935 static Module
* RunParser
(Module
* M
);
937 Module
*llvm
::RunVMAsmParser
(const std
::string &Filename
, FILE *F
) {
940 CurFilename
= Filename
;
941 return RunParser
(new Module
(CurFilename
));
944 Module
*llvm
::RunVMAsmParser
(const char * AsmString
, Module
* M
) {
945 set_scan_string
(AsmString
);
947 CurFilename
= "from_memory";
949 return RunParser
(new Module
(CurFilename
));
958 llvm
::Module
*ModuleVal
;
959 llvm
::Function
*FunctionVal
;
960 llvm
::BasicBlock
*BasicBlockVal
;
961 llvm
::TerminatorInst
*TermInstVal
;
962 llvm
::Instruction
*InstVal
;
963 llvm
::Constant
*ConstVal
;
965 const llvm
::Type
*PrimType
;
966 std
::list
<llvm
::PATypeHolder
> *TypeList
;
967 llvm
::PATypeHolder
*TypeVal
;
968 llvm
::Value
*ValueVal
;
969 std
::vector
<llvm
::Value
*> *ValueList
;
970 llvm
::ArgListType
*ArgList
;
971 llvm
::TypeWithAttrs TypeWithAttrs
;
972 llvm
::TypeWithAttrsList
*TypeWithAttrsList
;
973 llvm
::ValueRefList
*ValueRefList
;
975 // Represent the RHS of PHI node
976 std
::list
<std
::pair
<llvm
::Value
*,
977 llvm
::BasicBlock
*> > *PHIList
;
978 std
::vector
<std
::pair
<llvm
::Constant
*, llvm
::BasicBlock
*> > *JumpTable
;
979 std
::vector
<llvm
::Constant
*> *ConstVector
;
981 llvm
::GlobalValue
::LinkageTypes Linkage
;
982 llvm
::GlobalValue
::VisibilityTypes Visibility
;
984 llvm
::APInt
*APIntVal
;
992 std
::string *StrVal
; // This memory must be deleted
993 llvm
::ValID ValIDVal
;
995 llvm
::Instruction
::BinaryOps BinaryOpVal
;
996 llvm
::Instruction
::TermOps TermOpVal
;
997 llvm
::Instruction
::MemoryOps MemOpVal
;
998 llvm
::Instruction
::CastOps CastOpVal
;
999 llvm
::Instruction
::OtherOps OtherOpVal
;
1000 llvm
::ICmpInst
::Predicate IPredicate
;
1001 llvm
::FCmpInst
::Predicate FPredicate
;
1004 %type
<ModuleVal
> Module
1005 %type
<FunctionVal
> Function FunctionProto FunctionHeader BasicBlockList
1006 %type
<BasicBlockVal
> BasicBlock InstructionList
1007 %type
<TermInstVal
> BBTerminatorInst
1008 %type
<InstVal
> Inst InstVal MemoryInst
1009 %type
<ConstVal
> ConstVal ConstExpr AliaseeRef
1010 %type
<ConstVector
> ConstVector
1011 %type
<ArgList
> ArgList ArgListH
1012 %type
<PHIList
> PHIList
1013 %type
<ValueRefList
> ValueRefList
// For call param lists & GEP indices
1014 %type
<ValueList
> IndexList
// For GEP indices
1015 %type
<TypeList
> TypeListI
1016 %type
<TypeWithAttrsList
> ArgTypeList ArgTypeListI
1017 %type
<TypeWithAttrs
> ArgType
1018 %type
<JumpTable
> JumpTable
1019 %type
<BoolVal
> GlobalType
// GLOBAL or CONSTANT?
1020 %type
<BoolVal
> ThreadLocal
// 'thread_local' or not
1021 %type
<BoolVal
> OptVolatile
// 'volatile' or not
1022 %type
<BoolVal
> OptTailCall
// TAIL CALL or plain CALL.
1023 %type
<BoolVal
> OptSideEffect
// 'sideeffect' or not.
1024 %type
<Linkage
> GVInternalLinkage GVExternalLinkage
1025 %type
<Linkage
> FunctionDefineLinkage FunctionDeclareLinkage
1026 %type
<Linkage
> AliasLinkage
1027 %type
<Visibility
> GVVisibilityStyle
1029 // ValueRef - Unresolved reference to a definition or BB
1030 %type
<ValIDVal
> ValueRef ConstValueRef SymbolicValueRef
1031 %type
<ValueVal
> ResolvedVal
// <type> <valref> pair
1032 // Tokens and types for handling constant integer values
1034 // ESINT64VAL - A negative number within long long range
1035 %token
<SInt64Val
> ESINT64VAL
1037 // EUINT64VAL - A positive number within uns. long long range
1038 %token
<UInt64Val
> EUINT64VAL
1040 // ESAPINTVAL - A negative number with arbitrary precision
1041 %token
<APIntVal
> ESAPINTVAL
1043 // EUAPINTVAL - A positive number with arbitrary precision
1044 %token
<APIntVal
> EUAPINTVAL
1046 %token
<UIntVal
> LOCALVAL_ID GLOBALVAL_ID
// %123 @123
1047 %token
<FPVal
> FPVAL
// Float or Double constant
1049 // Built in types...
1050 %type
<TypeVal
> Types ResultTypes
1051 %type
<PrimType
> IntType FPType PrimType
// Classifications
1052 %token
<PrimType
> VOID INTTYPE
1053 %token
<PrimType
> FLOAT DOUBLE LABEL
1057 %token
<StrVal
> LOCALVAR GLOBALVAR LABELSTR
1058 %token
<StrVal
> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1059 %type
<StrVal
> LocalName OptLocalName OptLocalAssign
1060 %type
<StrVal
> GlobalName OptGlobalAssign GlobalAssign
1061 %type
<StrVal
> OptSection SectionString
1063 %type
<UIntVal
> OptAlign OptCAlign
1065 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1066 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1067 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1068 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1069 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
1070 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1071 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1073 %type
<UIntVal
> OptCallingConv
1074 %type
<ParamAttrs
> OptParamAttrs ParamAttr
1075 %type
<ParamAttrs
> OptFuncAttrs FuncAttr
1077 // Basic Block Terminating Operators
1078 %token
<TermOpVal
> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1081 %type
<BinaryOpVal
> ArithmeticOps LogicalOps
// Binops Subcatagories
1082 %token
<BinaryOpVal
> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1083 %token
<BinaryOpVal
> SHL LSHR ASHR
1085 %token
<OtherOpVal
> ICMP FCMP
1086 %type
<IPredicate
> IPredicates
1087 %type
<FPredicate
> FPredicates
1088 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1089 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1091 // Memory Instructions
1092 %token
<MemOpVal
> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1095 %type
<CastOpVal
> CastOps
1096 %token
<CastOpVal
> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1097 %token
<CastOpVal
> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1100 %token
<OtherOpVal
> PHI_TOK SELECT VAARG
1101 %token
<OtherOpVal
> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1103 // Function Attributes
1104 %token NORETURN INREG SRET NOUNWIND NOALIAS
1106 // Visibility Styles
1107 %token DEFAULT HIDDEN PROTECTED
1113 // Operations that are notably excluded from this list include:
1114 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1116 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM
;
1117 LogicalOps
: SHL | LSHR | ASHR | AND | OR | XOR
;
1118 CastOps
: TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1119 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT
;
1122 : EQ
{ $$
= ICmpInst
::ICMP_EQ
; } | NE
{ $$
= ICmpInst
::ICMP_NE
; }
1123 | SLT
{ $$
= ICmpInst
::ICMP_SLT
; } | SGT
{ $$
= ICmpInst
::ICMP_SGT
; }
1124 | SLE
{ $$
= ICmpInst
::ICMP_SLE
; } | SGE
{ $$
= ICmpInst
::ICMP_SGE
; }
1125 | ULT
{ $$
= ICmpInst
::ICMP_ULT
; } | UGT
{ $$
= ICmpInst
::ICMP_UGT
; }
1126 | ULE
{ $$
= ICmpInst
::ICMP_ULE
; } | UGE
{ $$
= ICmpInst
::ICMP_UGE
; }
1130 : OEQ
{ $$
= FCmpInst
::FCMP_OEQ
; } | ONE
{ $$
= FCmpInst
::FCMP_ONE
; }
1131 | OLT
{ $$
= FCmpInst
::FCMP_OLT
; } | OGT
{ $$
= FCmpInst
::FCMP_OGT
; }
1132 | OLE
{ $$
= FCmpInst
::FCMP_OLE
; } | OGE
{ $$
= FCmpInst
::FCMP_OGE
; }
1133 | ORD
{ $$
= FCmpInst
::FCMP_ORD
; } | UNO
{ $$
= FCmpInst
::FCMP_UNO
; }
1134 | UEQ
{ $$
= FCmpInst
::FCMP_UEQ
; } | UNE
{ $$
= FCmpInst
::FCMP_UNE
; }
1135 | ULT
{ $$
= FCmpInst
::FCMP_ULT
; } | UGT
{ $$
= FCmpInst
::FCMP_UGT
; }
1136 | ULE
{ $$
= FCmpInst
::FCMP_ULE
; } | UGE
{ $$
= FCmpInst
::FCMP_UGE
; }
1137 | TRUETOK
{ $$
= FCmpInst
::FCMP_TRUE
; }
1138 | FALSETOK
{ $$
= FCmpInst
::FCMP_FALSE
; }
1141 // These are some types that allow classification if we only want a particular
1142 // thing... for example, only a signed, unsigned, or integral type.
1144 FPType
: FLOAT | DOUBLE
;
1146 LocalName
: LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT
;
1147 OptLocalName
: LocalName |
/*empty*/ { $$
= 0; };
1149 /// OptLocalAssign - Value producing statements have an optional assignment
1151 OptLocalAssign
: LocalName
'=' {
1160 GlobalName
: GLOBALVAR | ATSTRINGCONSTANT
;
1162 OptGlobalAssign
: GlobalAssign
1168 GlobalAssign
: GlobalName
'=' {
1174 : INTERNAL
{ $$
= GlobalValue
::InternalLinkage
; }
1175 | WEAK
{ $$
= GlobalValue
::WeakLinkage
; }
1176 | LINKONCE
{ $$
= GlobalValue
::LinkOnceLinkage
; }
1177 | APPENDING
{ $$
= GlobalValue
::AppendingLinkage
; }
1178 | DLLEXPORT
{ $$
= GlobalValue
::DLLExportLinkage
; }
1182 : DLLIMPORT
{ $$
= GlobalValue
::DLLImportLinkage
; }
1183 | EXTERN_WEAK
{ $$
= GlobalValue
::ExternalWeakLinkage
; }
1184 | EXTERNAL
{ $$
= GlobalValue
::ExternalLinkage
; }
1188 : /*empty*/ { $$
= GlobalValue
::DefaultVisibility
; }
1189 | DEFAULT
{ $$
= GlobalValue
::DefaultVisibility
; }
1190 | HIDDEN
{ $$
= GlobalValue
::HiddenVisibility
; }
1191 | PROTECTED
{ $$
= GlobalValue
::ProtectedVisibility
; }
1194 FunctionDeclareLinkage
1195 : /*empty*/ { $$
= GlobalValue
::ExternalLinkage
; }
1196 | DLLIMPORT
{ $$
= GlobalValue
::DLLImportLinkage
; }
1197 | EXTERN_WEAK
{ $$
= GlobalValue
::ExternalWeakLinkage
; }
1200 FunctionDefineLinkage
1201 : /*empty*/ { $$
= GlobalValue
::ExternalLinkage
; }
1202 | INTERNAL
{ $$
= GlobalValue
::InternalLinkage
; }
1203 | LINKONCE
{ $$
= GlobalValue
::LinkOnceLinkage
; }
1204 | WEAK
{ $$
= GlobalValue
::WeakLinkage
; }
1205 | DLLEXPORT
{ $$
= GlobalValue
::DLLExportLinkage
; }
1209 : /*empty*/ { $$
= GlobalValue
::ExternalLinkage
; }
1210 | WEAK
{ $$
= GlobalValue
::WeakLinkage
; }
1211 | INTERNAL
{ $$
= GlobalValue
::InternalLinkage
; }
1214 OptCallingConv
: /*empty*/ { $$
= CallingConv
::C
; } |
1215 CCC_TOK
{ $$
= CallingConv
::C
; } |
1216 FASTCC_TOK
{ $$
= CallingConv
::Fast
; } |
1217 COLDCC_TOK
{ $$
= CallingConv
::Cold
; } |
1218 X86_STDCALLCC_TOK
{ $$
= CallingConv
::X86_StdCall
; } |
1219 X86_FASTCALLCC_TOK
{ $$
= CallingConv
::X86_FastCall
; } |
1221 if
((unsigned)$2 != $2)
1222 GEN_ERROR
("Calling conv too large");
1227 ParamAttr
: ZEXT
{ $$
= ParamAttr
::ZExt
; }
1228 | SEXT
{ $$
= ParamAttr
::SExt
; }
1229 | INREG
{ $$
= ParamAttr
::InReg
; }
1230 | SRET
{ $$
= ParamAttr
::StructRet
; }
1231 | NOALIAS
{ $$
= ParamAttr
::NoAlias
; }
1234 OptParamAttrs
: /* empty */ { $$
= ParamAttr
::None
; }
1235 | OptParamAttrs ParamAttr
{
1240 FuncAttr
: NORETURN
{ $$
= ParamAttr
::NoReturn
; }
1241 | NOUNWIND
{ $$
= ParamAttr
::NoUnwind
; }
1245 OptFuncAttrs
: /* empty */ { $$
= ParamAttr
::None
; }
1246 | OptFuncAttrs FuncAttr
{
1251 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1252 // a comma before it.
1253 OptAlign
: /*empty*/ { $$
= 0; } |
1256 if
($$
!= 0 && !isPowerOf2_32
($$
))
1257 GEN_ERROR
("Alignment must be a power of two");
1260 OptCAlign
: /*empty*/ { $$
= 0; } |
1261 ',' ALIGN EUINT64VAL
{
1263 if
($$
!= 0 && !isPowerOf2_32
($$
))
1264 GEN_ERROR
("Alignment must be a power of two");
1269 SectionString
: SECTION STRINGCONSTANT
{
1270 for
(unsigned i
= 0, e
= $2->length
(); i
!= e
; ++i
)
1271 if
((*$2)[i
] == '"' ||
(*$2)[i
] == '\\')
1272 GEN_ERROR
("Invalid character in section name");
1277 OptSection
: /*empty*/ { $$
= 0; } |
1278 SectionString
{ $$
= $1; };
1280 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1281 // is set to be the global we are processing.
1283 GlobalVarAttributes
: /* empty */ {} |
1284 ',' GlobalVarAttribute GlobalVarAttributes
{};
1285 GlobalVarAttribute
: SectionString
{
1286 CurGV
->setSection
(*$1);
1290 | ALIGN EUINT64VAL
{
1291 if
($2 != 0 && !isPowerOf2_32
($2))
1292 GEN_ERROR
("Alignment must be a power of two");
1293 CurGV
->setAlignment
($2);
1297 //===----------------------------------------------------------------------===//
1298 // Types includes all predefined types... except void, because it can only be
1299 // used in specific contexts (function returning void for example).
1301 // Derived types are added later...
1303 PrimType
: INTTYPE | FLOAT | DOUBLE | LABEL
;
1307 $$
= new PATypeHolder
(OpaqueType
::get
());
1311 $$
= new PATypeHolder
($1);
1314 | Types
'*' { // Pointer type?
1315 if
(*$1 == Type
::LabelTy
)
1316 GEN_ERROR
("Cannot form a pointer to a basic block");
1317 $$
= new PATypeHolder
(HandleUpRefs
(PointerType
::get
(*$1)));
1321 | SymbolicValueRef
{ // Named types are also simple types...
1322 const Type
* tmp
= getTypeVal
($1);
1324 $$
= new PATypeHolder
(tmp
);
1326 |
'\\' EUINT64VAL
{ // Type UpReference
1327 if
($2 > (uint64_t)~
0U) GEN_ERROR
("Value out of range");
1328 OpaqueType
*OT
= OpaqueType
::get
(); // Use temporary placeholder
1329 UpRefs.push_back
(UpRefRecord
((unsigned)$2, OT
)); // Add to vector...
1330 $$
= new PATypeHolder
(OT
);
1331 UR_OUT
("New Upreference!\n");
1334 | Types
'(' ArgTypeListI
')' OptFuncAttrs
{
1335 std
::vector
<const Type
*> Params
;
1336 ParamAttrsVector Attrs
;
1337 if
($5 != ParamAttr
::None
) {
1338 ParamAttrsWithIndex X
; X.index
= 0; X.attrs
= $5;
1342 TypeWithAttrsList
::iterator I
= $3->begin
(), E
= $3->end
();
1343 for
(; I
!= E
; ++I
, ++index
) {
1344 const Type
*Ty
= I
->Ty
->get
();
1345 Params.push_back
(Ty
);
1346 if
(Ty
!= Type
::VoidTy
)
1347 if
(I
->Attrs
!= ParamAttr
::None
) {
1348 ParamAttrsWithIndex X
; X.index
= index
; X.attrs
= I
->Attrs
;
1352 bool isVarArg
= Params.size
() && Params.back
() == Type
::VoidTy
;
1353 if
(isVarArg
) Params.pop_back
();
1355 ParamAttrsList
*ActualAttrs
= 0;
1357 ActualAttrs
= ParamAttrsList
::get
(Attrs
);
1358 FunctionType
*FT
= FunctionType
::get
(*$1, Params
, isVarArg
, ActualAttrs
);
1359 delete
$3; // Delete the argument list
1360 delete
$1; // Delete the return type handle
1361 $$
= new PATypeHolder
(HandleUpRefs
(FT
));
1364 | VOID
'(' ArgTypeListI
')' OptFuncAttrs
{
1365 std
::vector
<const Type
*> Params
;
1366 ParamAttrsVector Attrs
;
1367 if
($5 != ParamAttr
::None
) {
1368 ParamAttrsWithIndex X
; X.index
= 0; X.attrs
= $5;
1371 TypeWithAttrsList
::iterator I
= $3->begin
(), E
= $3->end
();
1373 for
( ; I
!= E
; ++I
, ++index
) {
1374 const Type
* Ty
= I
->Ty
->get
();
1375 Params.push_back
(Ty
);
1376 if
(Ty
!= Type
::VoidTy
)
1377 if
(I
->Attrs
!= ParamAttr
::None
) {
1378 ParamAttrsWithIndex X
; X.index
= index
; X.attrs
= I
->Attrs
;
1382 bool isVarArg
= Params.size
() && Params.back
() == Type
::VoidTy
;
1383 if
(isVarArg
) Params.pop_back
();
1385 ParamAttrsList
*ActualAttrs
= 0;
1387 ActualAttrs
= ParamAttrsList
::get
(Attrs
);
1389 FunctionType
*FT
= FunctionType
::get
($1, Params
, isVarArg
, ActualAttrs
);
1390 delete
$3; // Delete the argument list
1391 $$
= new PATypeHolder
(HandleUpRefs
(FT
));
1395 |
'[' EUINT64VAL
'x' Types
']' { // Sized array type?
1396 $$
= new PATypeHolder
(HandleUpRefs
(ArrayType
::get
(*$4, (unsigned)$2)));
1400 |
'<' EUINT64VAL
'x' Types
'>' { // Vector type?
1401 const llvm
::Type
* ElemTy
= $4->get
();
1402 if
((unsigned)$2 != $2)
1403 GEN_ERROR
("Unsigned result not equal to signed result");
1404 if
(!ElemTy
->isFloatingPoint
() && !ElemTy
->isInteger
())
1405 GEN_ERROR
("Element type of a VectorType must be primitive");
1406 if
(!isPowerOf2_32
($2))
1407 GEN_ERROR
("Vector length should be a power of 2");
1408 $$
= new PATypeHolder
(HandleUpRefs
(VectorType
::get
(*$4, (unsigned)$2)));
1412 |
'{' TypeListI
'}' { // Structure type?
1413 std
::vector
<const Type
*> Elements
;
1414 for
(std
::list
<llvm
::PATypeHolder
>::iterator I
= $2->begin
(),
1415 E
= $2->end
(); I
!= E
; ++I
)
1416 Elements.push_back
(*I
);
1418 $$
= new PATypeHolder
(HandleUpRefs
(StructType
::get
(Elements
)));
1422 |
'{' '}' { // Empty structure type?
1423 $$
= new PATypeHolder
(StructType
::get
(std
::vector
<const Type
*>()));
1426 |
'<' '{' TypeListI
'}' '>' {
1427 std
::vector
<const Type
*> Elements
;
1428 for
(std
::list
<llvm
::PATypeHolder
>::iterator I
= $3->begin
(),
1429 E
= $3->end
(); I
!= E
; ++I
)
1430 Elements.push_back
(*I
);
1432 $$
= new PATypeHolder
(HandleUpRefs
(StructType
::get
(Elements
, true
)));
1436 |
'<' '{' '}' '>' { // Empty structure type?
1437 $$
= new PATypeHolder
(StructType
::get
(std
::vector
<const Type
*>(), true
));
1443 : Types OptParamAttrs
{
1451 if
(!UpRefs.empty
())
1452 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1453 if
(!(*$1)->isFirstClassType
())
1454 GEN_ERROR
("LLVM functions cannot return aggregate types");
1458 $$
= new PATypeHolder
(Type
::VoidTy
);
1462 ArgTypeList
: ArgType
{
1463 $$
= new TypeWithAttrsList
();
1467 | ArgTypeList
',' ArgType
{
1468 ($$
=$1)->push_back
($3);
1475 | ArgTypeList
',' DOTDOTDOT
{
1477 TypeWithAttrs TWA
; TWA.Attrs
= ParamAttr
::None
;
1478 TWA.Ty
= new PATypeHolder
(Type
::VoidTy
);
1483 $$
= new TypeWithAttrsList
;
1484 TypeWithAttrs TWA
; TWA.Attrs
= ParamAttr
::None
;
1485 TWA.Ty
= new PATypeHolder
(Type
::VoidTy
);
1490 $$
= new TypeWithAttrsList
();
1494 // TypeList - Used for struct declarations and as a basis for function type
1495 // declaration type lists
1498 $$
= new std
::list
<PATypeHolder
>();
1503 | TypeListI
',' Types
{
1504 ($$
=$1)->push_back
(*$3);
1509 // ConstVal - The various declarations that go into the constant pool. This
1510 // production is used ONLY to represent constants that show up AFTER a 'const',
1511 // 'constant' or 'global' token at global scope. Constants that can be inlined
1512 // into other expressions (such as integers and constexprs) are handled by the
1513 // ResolvedVal, ValueRef and ConstValueRef productions.
1515 ConstVal: Types
'[' ConstVector
']' { // Nonempty unsized arr
1516 if
(!UpRefs.empty
())
1517 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1518 const ArrayType
*ATy
= dyn_cast
<ArrayType
>($1->get
());
1520 GEN_ERROR
("Cannot make array constant with type: '" +
1521 (*$1)->getDescription
() + "'");
1522 const Type
*ETy
= ATy
->getElementType
();
1523 int NumElements
= ATy
->getNumElements
();
1525 // Verify that we have the correct size...
1526 if
(NumElements
!= -1 && NumElements
!= (int)$3->size
())
1527 GEN_ERROR
("Type mismatch: constant sized array initialized with " +
1528 utostr
($3->size
()) + " arguments, but has size of " +
1529 itostr
(NumElements
) + "");
1531 // Verify all elements are correct type!
1532 for
(unsigned i
= 0; i
< $3->size
(); i
++) {
1533 if
(ETy
!= (*$3)[i
]->getType
())
1534 GEN_ERROR
("Element #" + utostr
(i
) + " is not of type '" +
1535 ETy
->getDescription
() +"' as required!\nIt is of type '"+
1536 (*$3)[i
]->getType
()->getDescription
() + "'.");
1539 $$
= ConstantArray
::get
(ATy
, *$3);
1540 delete
$1; delete
$3;
1544 if
(!UpRefs.empty
())
1545 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1546 const ArrayType
*ATy
= dyn_cast
<ArrayType
>($1->get
());
1548 GEN_ERROR
("Cannot make array constant with type: '" +
1549 (*$1)->getDescription
() + "'");
1551 int NumElements
= ATy
->getNumElements
();
1552 if
(NumElements
!= -1 && NumElements
!= 0)
1553 GEN_ERROR
("Type mismatch: constant sized array initialized with 0"
1554 " arguments, but has size of " + itostr
(NumElements
) +"");
1555 $$
= ConstantArray
::get
(ATy
, std
::vector
<Constant
*>());
1559 | Types
'c' STRINGCONSTANT
{
1560 if
(!UpRefs.empty
())
1561 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1562 const ArrayType
*ATy
= dyn_cast
<ArrayType
>($1->get
());
1564 GEN_ERROR
("Cannot make array constant with type: '" +
1565 (*$1)->getDescription
() + "'");
1567 int NumElements
= ATy
->getNumElements
();
1568 const Type
*ETy
= ATy
->getElementType
();
1569 if
(NumElements
!= -1 && NumElements
!= int($3->length
()))
1570 GEN_ERROR
("Can't build string constant of size " +
1571 itostr
((int)($3->length
())) +
1572 " when array has size " + itostr
(NumElements
) + "");
1573 std
::vector
<Constant
*> Vals
;
1574 if
(ETy
== Type
::Int8Ty
) {
1575 for
(unsigned i
= 0; i
< $3->length
(); ++i
)
1576 Vals.push_back
(ConstantInt
::get
(ETy
, (*$3)[i
]));
1579 GEN_ERROR
("Cannot build string arrays of non byte sized elements");
1582 $$
= ConstantArray
::get
(ATy
, Vals
);
1586 | Types
'<' ConstVector
'>' { // Nonempty unsized arr
1587 if
(!UpRefs.empty
())
1588 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1589 const VectorType
*PTy
= dyn_cast
<VectorType
>($1->get
());
1591 GEN_ERROR
("Cannot make packed constant with type: '" +
1592 (*$1)->getDescription
() + "'");
1593 const Type
*ETy
= PTy
->getElementType
();
1594 int NumElements
= PTy
->getNumElements
();
1596 // Verify that we have the correct size...
1597 if
(NumElements
!= -1 && NumElements
!= (int)$3->size
())
1598 GEN_ERROR
("Type mismatch: constant sized packed initialized with " +
1599 utostr
($3->size
()) + " arguments, but has size of " +
1600 itostr
(NumElements
) + "");
1602 // Verify all elements are correct type!
1603 for
(unsigned i
= 0; i
< $3->size
(); i
++) {
1604 if
(ETy
!= (*$3)[i
]->getType
())
1605 GEN_ERROR
("Element #" + utostr
(i
) + " is not of type '" +
1606 ETy
->getDescription
() +"' as required!\nIt is of type '"+
1607 (*$3)[i
]->getType
()->getDescription
() + "'.");
1610 $$
= ConstantVector
::get
(PTy
, *$3);
1611 delete
$1; delete
$3;
1614 | Types
'{' ConstVector
'}' {
1615 const StructType
*STy
= dyn_cast
<StructType
>($1->get
());
1617 GEN_ERROR
("Cannot make struct constant with type: '" +
1618 (*$1)->getDescription
() + "'");
1620 if
($3->size
() != STy
->getNumContainedTypes
())
1621 GEN_ERROR
("Illegal number of initializers for structure type");
1623 // Check to ensure that constants are compatible with the type initializer!
1624 for
(unsigned i
= 0, e
= $3->size
(); i
!= e
; ++i
)
1625 if
((*$3)[i
]->getType
() != STy
->getElementType
(i
))
1626 GEN_ERROR
("Expected type '" +
1627 STy
->getElementType
(i
)->getDescription
() +
1628 "' for element #" + utostr
(i
) +
1629 " of structure initializer");
1631 // Check to ensure that Type is not packed
1632 if
(STy
->isPacked
())
1633 GEN_ERROR
("Unpacked Initializer to vector type '" +
1634 STy
->getDescription
() + "'");
1636 $$
= ConstantStruct
::get
(STy
, *$3);
1637 delete
$1; delete
$3;
1641 if
(!UpRefs.empty
())
1642 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1643 const StructType
*STy
= dyn_cast
<StructType
>($1->get
());
1645 GEN_ERROR
("Cannot make struct constant with type: '" +
1646 (*$1)->getDescription
() + "'");
1648 if
(STy
->getNumContainedTypes
() != 0)
1649 GEN_ERROR
("Illegal number of initializers for structure type");
1651 // Check to ensure that Type is not packed
1652 if
(STy
->isPacked
())
1653 GEN_ERROR
("Unpacked Initializer to vector type '" +
1654 STy
->getDescription
() + "'");
1656 $$
= ConstantStruct
::get
(STy
, std
::vector
<Constant
*>());
1660 | Types
'<' '{' ConstVector
'}' '>' {
1661 const StructType
*STy
= dyn_cast
<StructType
>($1->get
());
1663 GEN_ERROR
("Cannot make struct constant with type: '" +
1664 (*$1)->getDescription
() + "'");
1666 if
($4->size
() != STy
->getNumContainedTypes
())
1667 GEN_ERROR
("Illegal number of initializers for structure type");
1669 // Check to ensure that constants are compatible with the type initializer!
1670 for
(unsigned i
= 0, e
= $4->size
(); i
!= e
; ++i
)
1671 if
((*$4)[i
]->getType
() != STy
->getElementType
(i
))
1672 GEN_ERROR
("Expected type '" +
1673 STy
->getElementType
(i
)->getDescription
() +
1674 "' for element #" + utostr
(i
) +
1675 " of structure initializer");
1677 // Check to ensure that Type is packed
1678 if
(!STy
->isPacked
())
1679 GEN_ERROR
("Vector initializer to non-vector type '" +
1680 STy
->getDescription
() + "'");
1682 $$
= ConstantStruct
::get
(STy
, *$4);
1683 delete
$1; delete
$4;
1686 | Types
'<' '{' '}' '>' {
1687 if
(!UpRefs.empty
())
1688 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1689 const StructType
*STy
= dyn_cast
<StructType
>($1->get
());
1691 GEN_ERROR
("Cannot make struct constant with type: '" +
1692 (*$1)->getDescription
() + "'");
1694 if
(STy
->getNumContainedTypes
() != 0)
1695 GEN_ERROR
("Illegal number of initializers for structure type");
1697 // Check to ensure that Type is packed
1698 if
(!STy
->isPacked
())
1699 GEN_ERROR
("Vector initializer to non-vector type '" +
1700 STy
->getDescription
() + "'");
1702 $$
= ConstantStruct
::get
(STy
, std
::vector
<Constant
*>());
1707 if
(!UpRefs.empty
())
1708 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1709 const PointerType
*PTy
= dyn_cast
<PointerType
>($1->get
());
1711 GEN_ERROR
("Cannot make null pointer constant with type: '" +
1712 (*$1)->getDescription
() + "'");
1714 $$
= ConstantPointerNull
::get
(PTy
);
1719 if
(!UpRefs.empty
())
1720 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1721 $$
= UndefValue
::get
($1->get
());
1725 | Types SymbolicValueRef
{
1726 if
(!UpRefs.empty
())
1727 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1728 const PointerType
*Ty
= dyn_cast
<PointerType
>($1->get
());
1730 GEN_ERROR
("Global const reference must be a pointer type");
1732 // ConstExprs can exist in the body of a function, thus creating
1733 // GlobalValues whenever they refer to a variable. Because we are in
1734 // the context of a function, getExistingVal will search the functions
1735 // symbol table instead of the module symbol table for the global symbol,
1736 // which throws things all off. To get around this, we just tell
1737 // getExistingVal that we are at global scope here.
1739 Function
*SavedCurFn
= CurFun.CurrentFunction
;
1740 CurFun.CurrentFunction
= 0;
1742 Value
*V
= getExistingVal
(Ty
, $2);
1745 CurFun.CurrentFunction
= SavedCurFn
;
1747 // If this is an initializer for a constant pointer, which is referencing a
1748 // (currently) undefined variable, create a stub now that shall be replaced
1749 // in the future with the right type of variable.
1752 assert
(isa
<PointerType
>(Ty
) && "Globals may only be used as pointers!");
1753 const PointerType
*PT
= cast
<PointerType
>(Ty
);
1755 // First check to see if the forward references value is already created!
1756 PerModuleInfo
::GlobalRefsType
::iterator I
=
1757 CurModule.GlobalRefs.find
(std
::make_pair
(PT
, $2));
1759 if
(I
!= CurModule.GlobalRefs.end
()) {
1760 V
= I
->second
; // Placeholder already exists, use it...
1764 if
($2.Type
== ValID
::GlobalName
)
1765 Name
= $2.getName
();
1766 else if
($2.Type
!= ValID
::GlobalID
)
1767 GEN_ERROR
("Invalid reference to global");
1769 // Create the forward referenced global.
1771 if
(const FunctionType
*FTy
=
1772 dyn_cast
<FunctionType
>(PT
->getElementType
())) {
1773 GV
= new Function
(FTy
, GlobalValue
::ExternalWeakLinkage
, Name
,
1774 CurModule.CurrentModule
);
1776 GV
= new GlobalVariable
(PT
->getElementType
(), false
,
1777 GlobalValue
::ExternalWeakLinkage
, 0,
1778 Name
, CurModule.CurrentModule
);
1781 // Keep track of the fact that we have a forward ref to recycle it
1782 CurModule.GlobalRefs.insert
(std
::make_pair
(std
::make_pair
(PT
, $2), GV
));
1787 $$
= cast
<GlobalValue
>(V
);
1788 delete
$1; // Free the type handle
1792 if
(!UpRefs.empty
())
1793 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1794 if
($1->get
() != $2->getType
())
1795 GEN_ERROR
("Mismatched types for constant expression: " +
1796 (*$1)->getDescription
() + " and " + $2->getType
()->getDescription
());
1801 | Types ZEROINITIALIZER
{
1802 if
(!UpRefs.empty
())
1803 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1804 const Type
*Ty
= $1->get
();
1805 if
(isa
<FunctionType
>(Ty
) || Ty
== Type
::LabelTy || isa
<OpaqueType
>(Ty
))
1806 GEN_ERROR
("Cannot create a null initialized value of this type");
1807 $$
= Constant
::getNullValue
(Ty
);
1811 | IntType ESINT64VAL
{ // integral constants
1812 if
(!ConstantInt
::isValueValidForType
($1, $2))
1813 GEN_ERROR
("Constant value doesn't fit in type");
1814 $$
= ConstantInt
::get
($1, $2, true
);
1817 | IntType ESAPINTVAL
{ // arbitrary precision integer constants
1818 uint32_t BitWidth
= cast
<IntegerType
>($1)->getBitWidth
();
1819 if
($2->getBitWidth
() > BitWidth
) {
1820 GEN_ERROR
("Constant value does not fit in type");
1822 $2->sextOrTrunc
(BitWidth
);
1823 $$
= ConstantInt
::get
(*$2);
1827 | IntType EUINT64VAL
{ // integral constants
1828 if
(!ConstantInt
::isValueValidForType
($1, $2))
1829 GEN_ERROR
("Constant value doesn't fit in type");
1830 $$
= ConstantInt
::get
($1, $2, false
);
1833 | IntType EUAPINTVAL
{ // arbitrary precision integer constants
1834 uint32_t BitWidth
= cast
<IntegerType
>($1)->getBitWidth
();
1835 if
($2->getBitWidth
() > BitWidth
) {
1836 GEN_ERROR
("Constant value does not fit in type");
1838 $2->zextOrTrunc
(BitWidth
);
1839 $$
= ConstantInt
::get
(*$2);
1843 | INTTYPE TRUETOK
{ // Boolean constants
1844 assert
(cast
<IntegerType
>($1)->getBitWidth
() == 1 && "Not Bool?");
1845 $$
= ConstantInt
::getTrue
();
1848 | INTTYPE FALSETOK
{ // Boolean constants
1849 assert
(cast
<IntegerType
>($1)->getBitWidth
() == 1 && "Not Bool?");
1850 $$
= ConstantInt
::getFalse
();
1853 | FPType FPVAL
{ // Float & Double constants
1854 if
(!ConstantFP
::isValueValidForType
($1, $2))
1855 GEN_ERROR
("Floating point constant invalid for type");
1856 $$
= ConstantFP
::get
($1, $2);
1861 ConstExpr: CastOps
'(' ConstVal TO Types
')' {
1862 if
(!UpRefs.empty
())
1863 GEN_ERROR
("Invalid upreference in type: " + (*$5)->getDescription
());
1865 const Type
*DestTy
= $5->get
();
1866 if
(!CastInst
::castIsValid
($1, $3, DestTy
))
1867 GEN_ERROR
("invalid cast opcode for cast from '" +
1868 Val
->getType
()->getDescription
() + "' to '" +
1869 DestTy
->getDescription
() + "'");
1870 $$
= ConstantExpr
::getCast
($1, $3, DestTy
);
1873 | GETELEMENTPTR
'(' ConstVal IndexList
')' {
1874 if
(!isa
<PointerType
>($3->getType
()))
1875 GEN_ERROR
("GetElementPtr requires a pointer operand");
1878 GetElementPtrInst
::getIndexedType
($3->getType
(), &(*$4)[0], $4->size
(),
1881 GEN_ERROR
("Index list invalid for constant getelementptr");
1883 SmallVector
<Constant
*, 8> IdxVec
;
1884 for
(unsigned i
= 0, e
= $4->size
(); i
!= e
; ++i
)
1885 if
(Constant
*C
= dyn_cast
<Constant
>((*$4)[i
]))
1886 IdxVec.push_back
(C
);
1888 GEN_ERROR
("Indices to constant getelementptr must be constants");
1892 $$
= ConstantExpr
::getGetElementPtr
($3, &IdxVec
[0], IdxVec.size
());
1895 | SELECT
'(' ConstVal
',' ConstVal
',' ConstVal
')' {
1896 if
($3->getType
() != Type
::Int1Ty
)
1897 GEN_ERROR
("Select condition must be of boolean type");
1898 if
($5->getType
() != $7->getType
())
1899 GEN_ERROR
("Select operand types must match");
1900 $$
= ConstantExpr
::getSelect
($3, $5, $7);
1903 | ArithmeticOps
'(' ConstVal
',' ConstVal
')' {
1904 if
($3->getType
() != $5->getType
())
1905 GEN_ERROR
("Binary operator types must match");
1907 $$
= ConstantExpr
::get
($1, $3, $5);
1909 | LogicalOps
'(' ConstVal
',' ConstVal
')' {
1910 if
($3->getType
() != $5->getType
())
1911 GEN_ERROR
("Logical operator types must match");
1912 if
(!$3->getType
()->isInteger
()) {
1913 if
(Instruction
::isShift
($1) ||
!isa
<VectorType
>($3->getType
()) ||
1914 !cast
<VectorType
>($3->getType
())->getElementType
()->isInteger
())
1915 GEN_ERROR
("Logical operator requires integral operands");
1917 $$
= ConstantExpr
::get
($1, $3, $5);
1920 | ICMP IPredicates
'(' ConstVal
',' ConstVal
')' {
1921 if
($4->getType
() != $6->getType
())
1922 GEN_ERROR
("icmp operand types must match");
1923 $$
= ConstantExpr
::getICmp
($2, $4, $6);
1925 | FCMP FPredicates
'(' ConstVal
',' ConstVal
')' {
1926 if
($4->getType
() != $6->getType
())
1927 GEN_ERROR
("fcmp operand types must match");
1928 $$
= ConstantExpr
::getFCmp
($2, $4, $6);
1930 | EXTRACTELEMENT
'(' ConstVal
',' ConstVal
')' {
1931 if
(!ExtractElementInst
::isValidOperands
($3, $5))
1932 GEN_ERROR
("Invalid extractelement operands");
1933 $$
= ConstantExpr
::getExtractElement
($3, $5);
1936 | INSERTELEMENT
'(' ConstVal
',' ConstVal
',' ConstVal
')' {
1937 if
(!InsertElementInst
::isValidOperands
($3, $5, $7))
1938 GEN_ERROR
("Invalid insertelement operands");
1939 $$
= ConstantExpr
::getInsertElement
($3, $5, $7);
1942 | SHUFFLEVECTOR
'(' ConstVal
',' ConstVal
',' ConstVal
')' {
1943 if
(!ShuffleVectorInst
::isValidOperands
($3, $5, $7))
1944 GEN_ERROR
("Invalid shufflevector operands");
1945 $$
= ConstantExpr
::getShuffleVector
($3, $5, $7);
1950 // ConstVector - A list of comma separated constants.
1951 ConstVector
: ConstVector
',' ConstVal
{
1952 ($$
= $1)->push_back
($3);
1956 $$
= new std
::vector
<Constant
*>();
1962 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1963 GlobalType
: GLOBAL
{ $$
= false
; } | CONSTANT
{ $$
= true
; };
1966 ThreadLocal
: THREAD_LOCAL
{ $$
= true
; } |
{ $$
= false
; };
1968 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1969 AliaseeRef
: ResultTypes SymbolicValueRef
{
1970 const Type
* VTy
= $1->get
();
1971 Value
*V
= getVal
(VTy
, $2);
1972 GlobalValue
* Aliasee
= dyn_cast
<GlobalValue
>(V
);
1974 GEN_ERROR
("Aliases can be created only to global values");
1980 | BITCAST
'(' AliaseeRef TO Types
')' {
1982 const Type
*DestTy
= $5->get
();
1983 if
(!CastInst
::castIsValid
($1, $3, DestTy
))
1984 GEN_ERROR
("invalid cast opcode for cast from '" +
1985 Val
->getType
()->getDescription
() + "' to '" +
1986 DestTy
->getDescription
() + "'");
1988 $$
= ConstantExpr
::getCast
($1, $3, DestTy
);
1993 //===----------------------------------------------------------------------===//
1994 // Rules to match Modules
1995 //===----------------------------------------------------------------------===//
1997 // Module rule: Capture the result of parsing the whole file into a result
2002 $$
= ParserResult
= CurModule.CurrentModule
;
2003 CurModule.ModuleDone
();
2007 $$
= ParserResult
= CurModule.CurrentModule
;
2008 CurModule.ModuleDone
();
2015 | DefinitionList Definition
2019 : DEFINE
{ CurFun.isDeclare
= false
; } Function
{
2020 CurFun.FunctionDone
();
2023 | DECLARE
{ CurFun.isDeclare
= true
; } FunctionProto
{
2026 | MODULE ASM_TOK AsmBlock
{
2029 | OptLocalAssign TYPE Types
{
2030 if
(!UpRefs.empty
())
2031 GEN_ERROR
("Invalid upreference in type: " + (*$3)->getDescription
());
2032 // Eagerly resolve types. This is not an optimization, this is a
2033 // requirement that is due to the fact that we could have this:
2035 // %list = type { %list * }
2036 // %list = type { %list * } ; repeated type decl
2038 // If types are not resolved eagerly, then the two types will not be
2039 // determined to be the same type!
2041 ResolveTypeTo
($1, *$3);
2043 if
(!setTypeName
(*$3, $1) && !$1) {
2045 // If this is a named type that is not a redefinition, add it to the slot
2047 CurModule.Types.push_back
(*$3);
2053 | OptLocalAssign TYPE VOID
{
2054 ResolveTypeTo
($1, $3);
2056 if
(!setTypeName
($3, $1) && !$1) {
2058 // If this is a named type that is not a redefinition, add it to the slot
2060 CurModule.Types.push_back
($3);
2064 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
{
2065 /* "Externally Visible" Linkage */
2067 GEN_ERROR
("Global value initializer is not a constant");
2068 CurGV
= ParseGlobalVariable
($1, GlobalValue
::ExternalLinkage
,
2069 $2, $4, $5->getType
(), $5, $3);
2071 } GlobalVarAttributes
{
2074 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2077 GEN_ERROR
("Global value initializer is not a constant");
2078 CurGV
= ParseGlobalVariable
($1, $2, $3, $5, $6->getType
(), $6, $4);
2080 } GlobalVarAttributes
{
2083 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2085 if
(!UpRefs.empty
())
2086 GEN_ERROR
("Invalid upreference in type: " + (*$6)->getDescription
());
2087 CurGV
= ParseGlobalVariable
($1, $2, $3, $5, *$6, 0, $4);
2090 } GlobalVarAttributes
{
2094 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef
{
2101 GEN_ERROR
("Alias name cannot be empty");
2103 Constant
* Aliasee
= $5;
2105 GEN_ERROR
(std
::string("Invalid aliasee for alias: ") + Name
);
2107 GlobalAlias
* GA
= new GlobalAlias
(Aliasee
->getType
(), $4, Name
, Aliasee
,
2108 CurModule.CurrentModule
);
2109 GA
->setVisibility
($2);
2110 InsertValue
(GA
, CurModule.Values
);
2113 | TARGET TargetDefinition
{
2116 | DEPLIBS
'=' LibrariesDefinition
{
2122 AsmBlock
: STRINGCONSTANT
{
2123 const std
::string &AsmSoFar
= CurModule.CurrentModule
->getModuleInlineAsm
();
2124 if
(AsmSoFar.empty
())
2125 CurModule.CurrentModule
->setModuleInlineAsm
(*$1);
2127 CurModule.CurrentModule
->setModuleInlineAsm
(AsmSoFar
+"\n"+*$1);
2132 TargetDefinition
: TRIPLE
'=' STRINGCONSTANT
{
2133 CurModule.CurrentModule
->setTargetTriple
(*$3);
2136 | DATALAYOUT
'=' STRINGCONSTANT
{
2137 CurModule.CurrentModule
->setDataLayout
(*$3);
2141 LibrariesDefinition
: '[' LibList
']';
2143 LibList
: LibList
',' STRINGCONSTANT
{
2144 CurModule.CurrentModule
->addLibrary
(*$3);
2149 CurModule.CurrentModule
->addLibrary
(*$1);
2153 |
/* empty: end of list */ {
2158 //===----------------------------------------------------------------------===//
2159 // Rules to match Function Headers
2160 //===----------------------------------------------------------------------===//
2162 ArgListH
: ArgListH
',' Types OptParamAttrs OptLocalName
{
2163 if
(!UpRefs.empty
())
2164 GEN_ERROR
("Invalid upreference in type: " + (*$3)->getDescription
());
2165 if
(*$3 == Type
::VoidTy
)
2166 GEN_ERROR
("void typed arguments are invalid");
2167 ArgListEntry E
; E.Attrs
= $4; E.Ty
= $3; E.Name
= $5;
2172 | Types OptParamAttrs OptLocalName
{
2173 if
(!UpRefs.empty
())
2174 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
2175 if
(*$1 == Type
::VoidTy
)
2176 GEN_ERROR
("void typed arguments are invalid");
2177 ArgListEntry E
; E.Attrs
= $2; E.Ty
= $1; E.Name
= $3;
2178 $$
= new ArgListType
;
2183 ArgList
: ArgListH
{
2187 | ArgListH
',' DOTDOTDOT
{
2189 struct ArgListEntry E
;
2190 E.Ty
= new PATypeHolder
(Type
::VoidTy
);
2192 E.Attrs
= ParamAttr
::None
;
2197 $$
= new ArgListType
;
2198 struct ArgListEntry E
;
2199 E.Ty
= new PATypeHolder
(Type
::VoidTy
);
2201 E.Attrs
= ParamAttr
::None
;
2210 FunctionHeaderH
: OptCallingConv ResultTypes GlobalName
'(' ArgList
')'
2211 OptFuncAttrs OptSection OptAlign
{
2212 std
::string FunctionName
(*$3);
2213 delete
$3; // Free strdup'd memory!
2215 // Check the function result for abstractness if this is a define. We should
2216 // have no abstract types at this point
2217 if
(!CurFun.isDeclare
&& CurModule.TypeIsUnresolved
($2))
2218 GEN_ERROR
("Reference to abstract result: "+ $2->get
()->getDescription
());
2220 std
::vector
<const Type
*> ParamTypeList
;
2221 ParamAttrsVector Attrs
;
2222 if
($7 != ParamAttr
::None
) {
2223 ParamAttrsWithIndex PAWI
; PAWI.index
= 0; PAWI.attrs
= $7;
2224 Attrs.push_back
(PAWI
);
2226 if
($5) { // If there are arguments...
2228 for
(ArgListType
::iterator I
= $5->begin
(); I
!= $5->end
(); ++I
, ++index
) {
2229 const Type
* Ty
= I
->Ty
->get
();
2230 if
(!CurFun.isDeclare
&& CurModule.TypeIsUnresolved
(I
->Ty
))
2231 GEN_ERROR
("Reference to abstract argument: " + Ty
->getDescription
());
2232 ParamTypeList.push_back
(Ty
);
2233 if
(Ty
!= Type
::VoidTy
)
2234 if
(I
->Attrs
!= ParamAttr
::None
) {
2235 ParamAttrsWithIndex PAWI
; PAWI.index
= index
; PAWI.attrs
= I
->Attrs
;
2236 Attrs.push_back
(PAWI
);
2241 bool isVarArg
= ParamTypeList.size
() && ParamTypeList.back
() == Type
::VoidTy
;
2242 if
(isVarArg
) ParamTypeList.pop_back
();
2244 ParamAttrsList
*PAL
= 0;
2246 PAL
= ParamAttrsList
::get
(Attrs
);
2248 FunctionType
*FT
= FunctionType
::get
(*$2, ParamTypeList
, isVarArg
, PAL
);
2249 const PointerType
*PFT
= PointerType
::get
(FT
);
2253 if
(!FunctionName.empty
()) {
2254 ID
= ValID
::createGlobalName
((char*)FunctionName.c_str
());
2256 ID
= ValID
::createGlobalID
(CurModule.Values.size
());
2260 // See if this function was forward referenced. If so, recycle the object.
2261 if
(GlobalValue
*FWRef
= CurModule.GetForwardRefForGlobal
(PFT
, ID
)) {
2262 // Move the function to the end of the list, from whereever it was
2263 // previously inserted.
2264 Fn
= cast
<Function
>(FWRef
);
2265 CurModule.CurrentModule
->getFunctionList
().remove
(Fn
);
2266 CurModule.CurrentModule
->getFunctionList
().push_back
(Fn
);
2267 } else if
(!FunctionName.empty
() && // Merge with an earlier prototype?
2268 (Fn
= CurModule.CurrentModule
->getFunction
(FunctionName
))) {
2269 if
(Fn
->getFunctionType
() != FT
) {
2270 // The existing function doesn't have the same type. This is an overload
2272 GEN_ERROR
("Overload of function '" + FunctionName
+ "' not permitted.");
2273 } else if
(!CurFun.isDeclare
&& !Fn
->isDeclaration
()) {
2274 // Neither the existing or the current function is a declaration and they
2275 // have the same name and same type. Clearly this is a redefinition.
2276 GEN_ERROR
("Redefinition of function '" + FunctionName
+ "'");
2277 } if
(Fn
->isDeclaration
()) {
2278 // Make sure to strip off any argument names so we can't get conflicts.
2279 for
(Function
::arg_iterator AI
= Fn
->arg_begin
(), AE
= Fn
->arg_end
();
2283 } else
{ // Not already defined?
2284 Fn
= new Function
(FT
, GlobalValue
::ExternalWeakLinkage
, FunctionName
,
2285 CurModule.CurrentModule
);
2287 InsertValue
(Fn
, CurModule.Values
);
2290 CurFun.FunctionStart
(Fn
);
2292 if
(CurFun.isDeclare
) {
2293 // If we have declaration, always overwrite linkage. This will allow us to
2294 // correctly handle cases, when pointer to function is passed as argument to
2295 // another function.
2296 Fn
->setLinkage
(CurFun.Linkage
);
2297 Fn
->setVisibility
(CurFun.Visibility
);
2299 Fn
->setCallingConv
($1);
2300 Fn
->setAlignment
($9);
2302 Fn
->setSection
(*$8);
2306 // Add all of the arguments we parsed to the function...
2307 if
($5) { // Is null if empty...
2308 if
(isVarArg
) { // Nuke the last entry
2309 assert
($5->back
().Ty
->get
() == Type
::VoidTy
&& $5->back
().Name
== 0 &&
2310 "Not a varargs marker!");
2311 delete
$5->back
().Ty
;
2312 $5->pop_back
(); // Delete the last entry
2314 Function
::arg_iterator ArgIt
= Fn
->arg_begin
();
2315 Function
::arg_iterator ArgEnd
= Fn
->arg_end
();
2317 for
(ArgListType
::iterator I
= $5->begin
();
2318 I
!= $5->end
() && ArgIt
!= ArgEnd
; ++I
, ++ArgIt
) {
2319 delete I
->Ty
; // Delete the typeholder...
2320 setValueName
(ArgIt
, I
->Name
); // Insert arg into symtab...
2326 delete
$5; // We're now done with the argument list
2331 BEGIN
: BEGINTOK |
'{'; // Allow BEGIN or '{' to start a function
2333 FunctionHeader
: FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN
{
2334 $$
= CurFun.CurrentFunction
;
2336 // Make sure that we keep track of the linkage type even if there was a
2337 // previous "declare".
2339 $$
->setVisibility
($2);
2342 END
: ENDTOK |
'}'; // Allow end of '}' to end a function
2344 Function
: BasicBlockList END
{
2349 FunctionProto
: FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH
{
2350 CurFun.CurrentFunction
->setLinkage
($1);
2351 CurFun.CurrentFunction
->setVisibility
($2);
2352 $$
= CurFun.CurrentFunction
;
2353 CurFun.FunctionDone
();
2357 //===----------------------------------------------------------------------===//
2358 // Rules to match Basic Blocks
2359 //===----------------------------------------------------------------------===//
2361 OptSideEffect
: /* empty */ {
2370 ConstValueRef
: ESINT64VAL
{ // A reference to a direct constant
2371 $$
= ValID
::create
($1);
2375 $$
= ValID
::create
($1);
2378 | FPVAL
{ // Perhaps it's an FP constant?
2379 $$
= ValID
::create
($1);
2383 $$
= ValID
::create
(ConstantInt
::getTrue
());
2387 $$
= ValID
::create
(ConstantInt
::getFalse
());
2391 $$
= ValID
::createNull
();
2395 $$
= ValID
::createUndef
();
2398 | ZEROINITIALIZER
{ // A vector zero constant.
2399 $$
= ValID
::createZeroInit
();
2402 |
'<' ConstVector
'>' { // Nonempty unsized packed vector
2403 const Type
*ETy
= (*$2)[0]->getType
();
2404 int NumElements
= $2->size
();
2406 VectorType
* pt
= VectorType
::get
(ETy
, NumElements
);
2407 PATypeHolder
* PTy
= new PATypeHolder
(
2415 // Verify all elements are correct type!
2416 for
(unsigned i
= 0; i
< $2->size
(); i
++) {
2417 if
(ETy
!= (*$2)[i
]->getType
())
2418 GEN_ERROR
("Element #" + utostr
(i
) + " is not of type '" +
2419 ETy
->getDescription
() +"' as required!\nIt is of type '" +
2420 (*$2)[i
]->getType
()->getDescription
() + "'.");
2423 $$
= ValID
::create
(ConstantVector
::get
(pt
, *$2));
2424 delete PTy
; delete
$2;
2428 $$
= ValID
::create
($1);
2431 | ASM_TOK OptSideEffect STRINGCONSTANT
',' STRINGCONSTANT
{
2432 $$
= ValID
::createInlineAsm
(*$3, *$5, $2);
2438 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2441 SymbolicValueRef
: LOCALVAL_ID
{ // Is it an integer reference...?
2442 $$
= ValID
::createLocalID
($1);
2446 $$
= ValID
::createGlobalID
($1);
2449 | LocalName
{ // Is it a named reference...?
2450 $$
= ValID
::createLocalName
(*$1);
2454 | GlobalName
{ // Is it a named reference...?
2455 $$
= ValID
::createGlobalName
(*$1);
2460 // ValueRef - A reference to a definition... either constant or symbolic
2461 ValueRef
: SymbolicValueRef | ConstValueRef
;
2464 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2465 // type immediately preceeds the value reference, and allows complex constant
2466 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2467 ResolvedVal
: Types ValueRef
{
2468 if
(!UpRefs.empty
())
2469 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
2470 $$
= getVal
(*$1, $2);
2476 BasicBlockList
: BasicBlockList BasicBlock
{
2480 | FunctionHeader BasicBlock
{ // Do not allow functions with 0 basic blocks
2486 // Basic blocks are terminated by branching instructions:
2487 // br, br/cc, switch, ret
2489 BasicBlock
: InstructionList OptLocalAssign BBTerminatorInst
{
2490 setValueName
($3, $2);
2493 $1->getInstList
().push_back
($3);
2498 InstructionList
: InstructionList Inst
{
2499 if
(CastInst
*CI1
= dyn_cast
<CastInst
>($2))
2500 if
(CastInst
*CI2
= dyn_cast
<CastInst
>(CI1
->getOperand
(0)))
2501 if
(CI2
->getParent
() == 0)
2502 $1->getInstList
().push_back
(CI2
);
2503 $1->getInstList
().push_back
($2);
2507 |
/* empty */ { // Empty space between instruction lists
2508 $$
= defineBBVal
(ValID
::createLocalID
(CurFun.NextValNum
));
2511 | LABELSTR
{ // Labelled (named) basic block
2512 $$
= defineBBVal
(ValID
::createLocalName
(*$1));
2518 BBTerminatorInst
: RET ResolvedVal
{ // Return with a result...
2519 $$
= new ReturnInst
($2);
2522 | RET VOID
{ // Return with no result...
2523 $$
= new ReturnInst
();
2526 | BR LABEL ValueRef
{ // Unconditional Branch...
2527 BasicBlock
* tmpBB
= getBBVal
($3);
2529 $$
= new BranchInst
(tmpBB
);
2530 } // Conditional Branch...
2531 | BR INTTYPE ValueRef
',' LABEL ValueRef
',' LABEL ValueRef
{
2532 assert
(cast
<IntegerType
>($2)->getBitWidth
() == 1 && "Not Bool?");
2533 BasicBlock
* tmpBBA
= getBBVal
($6);
2535 BasicBlock
* tmpBBB
= getBBVal
($9);
2537 Value
* tmpVal
= getVal
(Type
::Int1Ty
, $3);
2539 $$
= new BranchInst
(tmpBBA
, tmpBBB
, tmpVal
);
2541 | SWITCH IntType ValueRef
',' LABEL ValueRef
'[' JumpTable
']' {
2542 Value
* tmpVal
= getVal
($2, $3);
2544 BasicBlock
* tmpBB
= getBBVal
($6);
2546 SwitchInst
*S
= new SwitchInst
(tmpVal
, tmpBB
, $8->size
());
2549 std
::vector
<std
::pair
<Constant
*,BasicBlock
*> >::iterator I
= $8->begin
(),
2551 for
(; I
!= E
; ++I
) {
2552 if
(ConstantInt
*CI
= dyn_cast
<ConstantInt
>(I
->first
))
2553 S
->addCase
(CI
, I
->second
);
2555 GEN_ERROR
("Switch case is constant, but not a simple integer");
2560 | SWITCH IntType ValueRef
',' LABEL ValueRef
'[' ']' {
2561 Value
* tmpVal
= getVal
($2, $3);
2563 BasicBlock
* tmpBB
= getBBVal
($6);
2565 SwitchInst
*S
= new SwitchInst
(tmpVal
, tmpBB
, 0);
2569 | INVOKE OptCallingConv ResultTypes ValueRef
'(' ValueRefList
')' OptFuncAttrs
2570 TO LABEL ValueRef UNWIND LABEL ValueRef
{
2572 // Handle the short syntax
2573 const PointerType
*PFTy
= 0;
2574 const FunctionType
*Ty
= 0;
2575 if
(!(PFTy
= dyn_cast
<PointerType
>($3->get
())) ||
2576 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType
()))) {
2577 // Pull out the types of all of the arguments...
2578 std
::vector
<const Type
*> ParamTypes
;
2579 ParamAttrsVector Attrs
;
2580 if
($8 != ParamAttr
::None
) {
2581 ParamAttrsWithIndex PAWI
; PAWI.index
= 0; PAWI.attrs
= $8;
2582 Attrs.push_back
(PAWI
);
2584 ValueRefList
::iterator I
= $6->begin
(), E
= $6->end
();
2586 for
(; I
!= E
; ++I
, ++index
) {
2587 const Type
*Ty
= I
->Val
->getType
();
2588 if
(Ty
== Type
::VoidTy
)
2589 GEN_ERROR
("Short call syntax cannot be used with varargs");
2590 ParamTypes.push_back
(Ty
);
2591 if
(I
->Attrs
!= ParamAttr
::None
) {
2592 ParamAttrsWithIndex PAWI
; PAWI.index
= index
; PAWI.attrs
= I
->Attrs
;
2593 Attrs.push_back
(PAWI
);
2597 ParamAttrsList
*PAL
= 0;
2599 PAL
= ParamAttrsList
::get
(Attrs
);
2600 Ty
= FunctionType
::get
($3->get
(), ParamTypes
, false
, PAL
);
2601 PFTy
= PointerType
::get
(Ty
);
2606 Value
*V
= getVal
(PFTy
, $4); // Get the function we're calling...
2608 BasicBlock
*Normal
= getBBVal
($11);
2610 BasicBlock
*Except
= getBBVal
($14);
2613 // Check the arguments
2615 if
($6->empty
()) { // Has no arguments?
2616 // Make sure no arguments is a good thing!
2617 if
(Ty
->getNumParams
() != 0)
2618 GEN_ERROR
("No arguments passed to a function that "
2619 "expects arguments");
2620 } else
{ // Has arguments?
2621 // Loop through FunctionType's arguments and ensure they are specified
2623 FunctionType
::param_iterator I
= Ty
->param_begin
();
2624 FunctionType
::param_iterator E
= Ty
->param_end
();
2625 ValueRefList
::iterator ArgI
= $6->begin
(), ArgE
= $6->end
();
2627 for
(; ArgI
!= ArgE
&& I
!= E
; ++ArgI
, ++I
) {
2628 if
(ArgI
->Val
->getType
() != *I
)
2629 GEN_ERROR
("Parameter " + ArgI
->Val
->getName
()+ " is not of type '" +
2630 (*I
)->getDescription
() + "'");
2631 Args.push_back
(ArgI
->Val
);
2634 if
(Ty
->isVarArg
()) {
2636 for
(; ArgI
!= ArgE
; ++ArgI
)
2637 Args.push_back
(ArgI
->Val
); // push the remaining varargs
2638 } else if
(I
!= E || ArgI
!= ArgE
)
2639 GEN_ERROR
("Invalid number of parameters detected");
2642 // Create the InvokeInst
2643 InvokeInst
*II
= new InvokeInst
(V
, Normal
, Except
, &Args
[0], Args.size
());
2644 II
->setCallingConv
($2);
2650 $$
= new UnwindInst
();
2654 $$
= new UnreachableInst
();
2660 JumpTable
: JumpTable IntType ConstValueRef
',' LABEL ValueRef
{
2662 Constant
*V
= cast
<Constant
>(getExistingVal
($2, $3));
2665 GEN_ERROR
("May only switch on a constant pool value");
2667 BasicBlock
* tmpBB
= getBBVal
($6);
2669 $$
->push_back
(std
::make_pair
(V
, tmpBB
));
2671 | IntType ConstValueRef
',' LABEL ValueRef
{
2672 $$
= new std
::vector
<std
::pair
<Constant
*, BasicBlock
*> >();
2673 Constant
*V
= cast
<Constant
>(getExistingVal
($1, $2));
2677 GEN_ERROR
("May only switch on a constant pool value");
2679 BasicBlock
* tmpBB
= getBBVal
($5);
2681 $$
->push_back
(std
::make_pair
(V
, tmpBB
));
2684 Inst
: OptLocalAssign InstVal
{
2685 // Is this definition named?? if so, assign the name...
2686 setValueName
($2, $1);
2694 PHIList
: Types
'[' ValueRef
',' ValueRef
']' { // Used for PHI nodes
2695 if
(!UpRefs.empty
())
2696 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
2697 $$
= new std
::list
<std
::pair
<Value
*, BasicBlock
*> >();
2698 Value
* tmpVal
= getVal
(*$1, $3);
2700 BasicBlock
* tmpBB
= getBBVal
($5);
2702 $$
->push_back
(std
::make_pair
(tmpVal
, tmpBB
));
2705 | PHIList
',' '[' ValueRef
',' ValueRef
']' {
2707 Value
* tmpVal
= getVal
($1->front
().first
->getType
(), $4);
2709 BasicBlock
* tmpBB
= getBBVal
($6);
2711 $1->push_back
(std
::make_pair
(tmpVal
, tmpBB
));
2715 ValueRefList
: Types ValueRef OptParamAttrs
{
2716 if
(!UpRefs.empty
())
2717 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
2718 // Used for call and invoke instructions
2719 $$
= new ValueRefList
();
2720 ValueRefListEntry E
; E.Attrs
= $3; E.Val
= getVal
($1->get
(), $2);
2724 | ValueRefList
',' Types ValueRef OptParamAttrs
{
2725 if
(!UpRefs.empty
())
2726 GEN_ERROR
("Invalid upreference in type: " + (*$3)->getDescription
());
2728 ValueRefListEntry E
; E.Attrs
= $5; E.Val
= getVal
($3->get
(), $4);
2733 |
/*empty*/ { $$
= new ValueRefList
(); };
2735 IndexList
// Used for gep instructions and constant expressions
2736 : /*empty*/ { $$
= new std
::vector
<Value
*>(); }
2737 | IndexList
',' ResolvedVal
{
2744 OptTailCall
: TAIL CALL
{
2753 InstVal
: ArithmeticOps Types ValueRef
',' ValueRef
{
2754 if
(!UpRefs.empty
())
2755 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
2756 if
(!(*$2)->isInteger
() && !(*$2)->isFloatingPoint
() &&
2757 !isa
<VectorType
>((*$2).get
()))
2759 "Arithmetic operator requires integer, FP, or packed operands");
2760 if
(isa
<VectorType
>((*$2).get
()) &&
2761 ($1 == Instruction
::URem ||
2762 $1 == Instruction
::SRem ||
2763 $1 == Instruction
::FRem
))
2764 GEN_ERROR
("Remainder not supported on vector types");
2765 Value
* val1
= getVal
(*$2, $3);
2767 Value
* val2
= getVal
(*$2, $5);
2769 $$
= BinaryOperator
::create
($1, val1
, val2
);
2771 GEN_ERROR
("binary operator returned null");
2774 | LogicalOps Types ValueRef
',' ValueRef
{
2775 if
(!UpRefs.empty
())
2776 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
2777 if
(!(*$2)->isInteger
()) {
2778 if
(Instruction
::isShift
($1) ||
!isa
<VectorType
>($2->get
()) ||
2779 !cast
<VectorType
>($2->get
())->getElementType
()->isInteger
())
2780 GEN_ERROR
("Logical operator requires integral operands");
2782 Value
* tmpVal1
= getVal
(*$2, $3);
2784 Value
* tmpVal2
= getVal
(*$2, $5);
2786 $$
= BinaryOperator
::create
($1, tmpVal1
, tmpVal2
);
2788 GEN_ERROR
("binary operator returned null");
2791 | ICMP IPredicates Types ValueRef
',' ValueRef
{
2792 if
(!UpRefs.empty
())
2793 GEN_ERROR
("Invalid upreference in type: " + (*$3)->getDescription
());
2794 if
(isa
<VectorType
>((*$3).get
()))
2795 GEN_ERROR
("Vector types not supported by icmp instruction");
2796 Value
* tmpVal1
= getVal
(*$3, $4);
2798 Value
* tmpVal2
= getVal
(*$3, $6);
2800 $$
= CmpInst
::create
($1, $2, tmpVal1
, tmpVal2
);
2802 GEN_ERROR
("icmp operator returned null");
2805 | FCMP FPredicates Types ValueRef
',' ValueRef
{
2806 if
(!UpRefs.empty
())
2807 GEN_ERROR
("Invalid upreference in type: " + (*$3)->getDescription
());
2808 if
(isa
<VectorType
>((*$3).get
()))
2809 GEN_ERROR
("Vector types not supported by fcmp instruction");
2810 Value
* tmpVal1
= getVal
(*$3, $4);
2812 Value
* tmpVal2
= getVal
(*$3, $6);
2814 $$
= CmpInst
::create
($1, $2, tmpVal1
, tmpVal2
);
2816 GEN_ERROR
("fcmp operator returned null");
2819 | CastOps ResolvedVal TO Types
{
2820 if
(!UpRefs.empty
())
2821 GEN_ERROR
("Invalid upreference in type: " + (*$4)->getDescription
());
2823 const Type
* DestTy
= $4->get
();
2824 if
(!CastInst
::castIsValid
($1, Val
, DestTy
))
2825 GEN_ERROR
("invalid cast opcode for cast from '" +
2826 Val
->getType
()->getDescription
() + "' to '" +
2827 DestTy
->getDescription
() + "'");
2828 $$
= CastInst
::create
($1, Val
, DestTy
);
2831 | SELECT ResolvedVal
',' ResolvedVal
',' ResolvedVal
{
2832 if
($2->getType
() != Type
::Int1Ty
)
2833 GEN_ERROR
("select condition must be boolean");
2834 if
($4->getType
() != $6->getType
())
2835 GEN_ERROR
("select value types should match");
2836 $$
= new SelectInst
($2, $4, $6);
2839 | VAARG ResolvedVal
',' Types
{
2840 if
(!UpRefs.empty
())
2841 GEN_ERROR
("Invalid upreference in type: " + (*$4)->getDescription
());
2842 $$
= new VAArgInst
($2, *$4);
2846 | EXTRACTELEMENT ResolvedVal
',' ResolvedVal
{
2847 if
(!ExtractElementInst
::isValidOperands
($2, $4))
2848 GEN_ERROR
("Invalid extractelement operands");
2849 $$
= new ExtractElementInst
($2, $4);
2852 | INSERTELEMENT ResolvedVal
',' ResolvedVal
',' ResolvedVal
{
2853 if
(!InsertElementInst
::isValidOperands
($2, $4, $6))
2854 GEN_ERROR
("Invalid insertelement operands");
2855 $$
= new InsertElementInst
($2, $4, $6);
2858 | SHUFFLEVECTOR ResolvedVal
',' ResolvedVal
',' ResolvedVal
{
2859 if
(!ShuffleVectorInst
::isValidOperands
($2, $4, $6))
2860 GEN_ERROR
("Invalid shufflevector operands");
2861 $$
= new ShuffleVectorInst
($2, $4, $6);
2865 const Type
*Ty
= $2->front
().first
->getType
();
2866 if
(!Ty
->isFirstClassType
())
2867 GEN_ERROR
("PHI node operands must be of first class type");
2868 $$
= new PHINode
(Ty
);
2869 ((PHINode
*)$$
)->reserveOperandSpace
($2->size
());
2870 while
($2->begin
() != $2->end
()) {
2871 if
($2->front
().first
->getType
() != Ty
)
2872 GEN_ERROR
("All elements of a PHI node must be of the same type");
2873 cast
<PHINode
>($$
)->addIncoming
($2->front
().first
, $2->front
().second
);
2876 delete
$2; // Free the list...
2879 | OptTailCall OptCallingConv ResultTypes ValueRef
'(' ValueRefList
')'
2882 // Handle the short syntax
2883 const PointerType
*PFTy
= 0;
2884 const FunctionType
*Ty
= 0;
2885 if
(!(PFTy
= dyn_cast
<PointerType
>($3->get
())) ||
2886 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType
()))) {
2887 // Pull out the types of all of the arguments...
2888 std
::vector
<const Type
*> ParamTypes
;
2889 ParamAttrsVector Attrs
;
2890 if
($8 != ParamAttr
::None
) {
2891 ParamAttrsWithIndex PAWI
; PAWI.index
= 0; PAWI.attrs
= $8;
2892 Attrs.push_back
(PAWI
);
2895 ValueRefList
::iterator I
= $6->begin
(), E
= $6->end
();
2896 for
(; I
!= E
; ++I
, ++index
) {
2897 const Type
*Ty
= I
->Val
->getType
();
2898 if
(Ty
== Type
::VoidTy
)
2899 GEN_ERROR
("Short call syntax cannot be used with varargs");
2900 ParamTypes.push_back
(Ty
);
2901 if
(I
->Attrs
!= ParamAttr
::None
) {
2902 ParamAttrsWithIndex PAWI
; PAWI.index
= index
; PAWI.attrs
= I
->Attrs
;
2903 Attrs.push_back
(PAWI
);
2907 ParamAttrsList
*PAL
= 0;
2909 PAL
= ParamAttrsList
::get
(Attrs
);
2911 Ty
= FunctionType
::get
($3->get
(), ParamTypes
, false
, PAL
);
2912 PFTy
= PointerType
::get
(Ty
);
2915 Value
*V
= getVal
(PFTy
, $4); // Get the function we're calling...
2918 // Check for call to invalid intrinsic to avoid crashing later.
2919 if
(Function
*theF
= dyn_cast
<Function
>(V
)) {
2920 if
(theF
->hasName
() && (theF
->getValueName
()->getKeyLength
() >= 5) &&
2921 (0 == strncmp
(theF
->getValueName
()->getKeyData
(), "llvm.", 5)) &&
2922 !theF
->getIntrinsicID
(true
))
2923 GEN_ERROR
("Call to invalid LLVM intrinsic function '" +
2924 theF
->getName
() + "'");
2927 // Check the arguments
2929 if
($6->empty
()) { // Has no arguments?
2930 // Make sure no arguments is a good thing!
2931 if
(Ty
->getNumParams
() != 0)
2932 GEN_ERROR
("No arguments passed to a function that "
2933 "expects arguments");
2934 } else
{ // Has arguments?
2935 // Loop through FunctionType's arguments and ensure they are specified
2938 FunctionType
::param_iterator I
= Ty
->param_begin
();
2939 FunctionType
::param_iterator E
= Ty
->param_end
();
2940 ValueRefList
::iterator ArgI
= $6->begin
(), ArgE
= $6->end
();
2942 for
(; ArgI
!= ArgE
&& I
!= E
; ++ArgI
, ++I
) {
2943 if
(ArgI
->Val
->getType
() != *I
)
2944 GEN_ERROR
("Parameter " + ArgI
->Val
->getName
()+ " is not of type '" +
2945 (*I
)->getDescription
() + "'");
2946 Args.push_back
(ArgI
->Val
);
2948 if
(Ty
->isVarArg
()) {
2950 for
(; ArgI
!= ArgE
; ++ArgI
)
2951 Args.push_back
(ArgI
->Val
); // push the remaining varargs
2952 } else if
(I
!= E || ArgI
!= ArgE
)
2953 GEN_ERROR
("Invalid number of parameters detected");
2955 // Create the call node
2956 CallInst
*CI
= new CallInst
(V
, &Args
[0], Args.size
());
2957 CI
->setTailCall
($1);
2958 CI
->setCallingConv
($2);
2969 OptVolatile
: VOLATILE
{
2980 MemoryInst
: MALLOC Types OptCAlign
{
2981 if
(!UpRefs.empty
())
2982 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
2983 $$
= new MallocInst
(*$2, 0, $3);
2987 | MALLOC Types
',' INTTYPE ValueRef OptCAlign
{
2988 if
(!UpRefs.empty
())
2989 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
2990 Value
* tmpVal
= getVal
($4, $5);
2992 $$
= new MallocInst
(*$2, tmpVal
, $6);
2995 | ALLOCA Types OptCAlign
{
2996 if
(!UpRefs.empty
())
2997 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
2998 $$
= new AllocaInst
(*$2, 0, $3);
3002 | ALLOCA Types
',' INTTYPE ValueRef OptCAlign
{
3003 if
(!UpRefs.empty
())
3004 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
3005 Value
* tmpVal
= getVal
($4, $5);
3007 $$
= new AllocaInst
(*$2, tmpVal
, $6);
3010 | FREE ResolvedVal
{
3011 if
(!isa
<PointerType
>($2->getType
()))
3012 GEN_ERROR
("Trying to free nonpointer type " +
3013 $2->getType
()->getDescription
() + "");
3014 $$
= new FreeInst
($2);
3018 | OptVolatile LOAD Types ValueRef OptCAlign
{
3019 if
(!UpRefs.empty
())
3020 GEN_ERROR
("Invalid upreference in type: " + (*$3)->getDescription
());
3021 if
(!isa
<PointerType
>($3->get
()))
3022 GEN_ERROR
("Can't load from nonpointer type: " +
3023 (*$3)->getDescription
());
3024 if
(!cast
<PointerType
>($3->get
())->getElementType
()->isFirstClassType
())
3025 GEN_ERROR
("Can't load from pointer of non-first-class type: " +
3026 (*$3)->getDescription
());
3027 Value
* tmpVal
= getVal
(*$3, $4);
3029 $$
= new LoadInst
(tmpVal
, "", $1, $5);
3032 | OptVolatile STORE ResolvedVal
',' Types ValueRef OptCAlign
{
3033 if
(!UpRefs.empty
())
3034 GEN_ERROR
("Invalid upreference in type: " + (*$5)->getDescription
());
3035 const PointerType
*PT
= dyn_cast
<PointerType
>($5->get
());
3037 GEN_ERROR
("Can't store to a nonpointer type: " +
3038 (*$5)->getDescription
());
3039 const Type
*ElTy
= PT
->getElementType
();
3040 if
(ElTy
!= $3->getType
())
3041 GEN_ERROR
("Can't store '" + $3->getType
()->getDescription
() +
3042 "' into space of type '" + ElTy
->getDescription
() + "'");
3044 Value
* tmpVal
= getVal
(*$5, $6);
3046 $$
= new StoreInst
($3, tmpVal
, $1, $7);
3049 | GETELEMENTPTR Types ValueRef IndexList
{
3050 if
(!UpRefs.empty
())
3051 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
3052 if
(!isa
<PointerType
>($2->get
()))
3053 GEN_ERROR
("getelementptr insn requires pointer operand");
3055 if
(!GetElementPtrInst
::getIndexedType
(*$2, &(*$4)[0], $4->size
(), true
))
3056 GEN_ERROR
("Invalid getelementptr indices for type '" +
3057 (*$2)->getDescription
()+ "'");
3058 Value
* tmpVal
= getVal
(*$2, $3);
3060 $$
= new GetElementPtrInst
(tmpVal
, &(*$4)[0], $4->size
());
3068 // common code from the two 'RunVMAsmParser' functions
3069 static Module
* RunParser
(Module
* M
) {
3071 llvmAsmlineno
= 1; // Reset the current line number...
3072 CurModule.CurrentModule
= M
;
3077 // Check to make sure the parser succeeded
3080 delete ParserResult
;
3084 // Emit an error if there are any unresolved types left.
3085 if
(!CurModule.LateResolveTypes.empty
()) {
3086 const ValID
&DID
= CurModule.LateResolveTypes.begin
()->first
;
3087 if
(DID.Type
== ValID
::LocalName
) {
3088 GenerateError
("Undefined type remains at eof: '"+DID.getName
() + "'");
3090 GenerateError
("Undefined type remains at eof: #" + itostr
(DID.Num
));
3093 delete ParserResult
;
3097 // Emit an error if there are any unresolved values left.
3098 if
(!CurModule.LateResolveValues.empty
()) {
3099 Value
*V
= CurModule.LateResolveValues.back
();
3100 std
::map
<Value
*, std
::pair
<ValID
, int> >::iterator I
=
3101 CurModule.PlaceHolderInfo.find
(V
);
3103 if
(I
!= CurModule.PlaceHolderInfo.end
()) {
3104 ValID
&DID
= I
->second.first
;
3105 if
(DID.Type
== ValID
::LocalName
) {
3106 GenerateError
("Undefined value remains at eof: "+DID.getName
() + "'");
3108 GenerateError
("Undefined value remains at eof: #" + itostr
(DID.Num
));
3111 delete ParserResult
;
3116 // Check to make sure that parsing produced a result
3120 // Reset ParserResult variable while saving its value for the result.
3121 Module
*Result
= ParserResult
;
3127 void llvm
::GenerateError
(const std
::string &message
, int LineNo
) {
3128 if
(LineNo
== -1) LineNo
= llvmAsmlineno
;
3129 // TODO: column number in exception
3131 TheParseError
->setError
(CurFilename
, message
, LineNo
);
3135 int yyerror(const char *ErrorMsg
) {
3137 = std
::string((CurFilename
== "-") ? std
::string("<stdin>") : CurFilename
)
3138 + ":" + utostr
((unsigned) llvmAsmlineno
) + ": ";
3139 std
::string errMsg
= where
+ "error: " + std
::string(ErrorMsg
);
3140 if
(yychar != YYEMPTY
&& yychar != 0)
3141 errMsg
+= " while reading token: '" + std
::string(llvmAsmtext
, llvmAsmleng
)+
3143 GenerateError
(errMsg
);