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/AutoUpgrade.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/Streams.h"
36 // The following is a gross hack. In order to rid the libAsmParser library of
37 // exceptions, we have to have a way of getting the yyparse function to go into
38 // an error situation. So, whenever we want an error to occur, the GenerateError
39 // function (see bottom of file) sets TriggerError. Then, at the end of each
40 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
41 // (a goto) to put YACC in error state. Furthermore, several calls to
42 // GenerateError are made from inside productions and they must simulate the
43 // previous exception behavior by exiting the production immediately. We have
44 // replaced these with the GEN_ERROR macro which calls GeneratError and then
45 // immediately invokes YYERROR. This would be so much cleaner if it was a
46 // recursive descent parser.
47 static bool TriggerError
= false
;
48 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
49 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
51 int yyerror(const char *ErrorMsg
); // Forward declarations to prevent "implicit
52 int yylex(); // declaration" of xxx warnings.
56 std
::string CurFilename
;
59 Debug
("debug-yacc", cl
::desc
("Print yacc debug state changes"),
60 cl
::Hidden
, cl
::init
(false
));
65 static Module
*ParserResult
;
67 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
68 // relating to upreferences in the input stream.
70 //#define DEBUG_UPREFS 1
72 #define UR_OUT(X) cerr << X
77 #define YYERROR_VERBOSE 1
79 static GlobalVariable
*CurGV
;
82 // This contains info used when building the body of a function. It is
83 // destroyed when the function is completed.
85 typedef std
::vector
<Value
*> ValueList
; // Numbered defs
88 ResolveDefinitions
(ValueList
&LateResolvers
, ValueList
*FutureLateResolvers
=0);
90 static struct PerModuleInfo
{
91 Module
*CurrentModule
;
92 ValueList Values
; // Module level numbered definitions
93 ValueList LateResolveValues
;
94 std
::vector
<PATypeHolder
> Types
;
95 std
::map
<ValID
, PATypeHolder
> LateResolveTypes
;
97 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
98 /// how they were referenced and on which line of the input they came from so
99 /// that we can resolve them later and print error messages as appropriate.
100 std
::map
<Value
*, std
::pair
<ValID
, int> > PlaceHolderInfo
;
102 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
103 // references to global values. Global values may be referenced before they
104 // are defined, and if so, the temporary object that they represent is held
105 // here. This is used for forward references of GlobalValues.
107 typedef std
::map
<std
::pair
<const PointerType
*,
108 ValID
>, GlobalValue
*> GlobalRefsType
;
109 GlobalRefsType GlobalRefs
;
112 // If we could not resolve some functions at function compilation time
113 // (calls to functions before they are defined), resolve them now... Types
114 // are resolved when the constant pool has been completely parsed.
116 ResolveDefinitions
(LateResolveValues
);
120 // Check to make sure that all global value forward references have been
123 if
(!GlobalRefs.empty
()) {
124 std
::string UndefinedReferences
= "Unresolved global references exist:\n";
126 for
(GlobalRefsType
::iterator I
= GlobalRefs.begin
(), E
=GlobalRefs.end
();
128 UndefinedReferences
+= " " + I
->first.first
->getDescription
() + " " +
129 I
->first.second.getName
() + "\n";
131 GenerateError
(UndefinedReferences
);
135 // Look for intrinsic functions and CallInst that need to be upgraded
136 for
(Module
::iterator FI
= CurrentModule
->begin
(),
137 FE
= CurrentModule
->end
(); FI
!= FE
; )
138 UpgradeCallsToIntrinsic
(FI
++); // must be post-increment, as we remove
140 Values.clear
(); // Clear out function local definitions
145 // GetForwardRefForGlobal - Check to see if there is a forward reference
146 // for this global. If so, remove it from the GlobalRefs map and return it.
147 // If not, just return null.
148 GlobalValue
*GetForwardRefForGlobal
(const PointerType
*PTy
, ValID ID
) {
149 // Check to see if there is a forward reference to this global variable...
150 // if there is, eliminate it and patch the reference to use the new def'n.
151 GlobalRefsType
::iterator I
= GlobalRefs.find
(std
::make_pair
(PTy
, ID
));
152 GlobalValue
*Ret
= 0;
153 if
(I
!= GlobalRefs.end
()) {
160 bool TypeIsUnresolved
(PATypeHolder
* PATy
) {
161 // If it isn't abstract, its resolved
162 const Type
* Ty
= PATy
->get
();
163 if
(!Ty
->isAbstract
())
165 // Traverse the type looking for abstract types. If it isn't abstract then
166 // we don't need to traverse that leg of the type.
167 std
::vector
<const Type
*> WorkList
, SeenList
;
168 WorkList.push_back
(Ty
);
169 while
(!WorkList.empty
()) {
170 const Type
* Ty
= WorkList.back
();
171 SeenList.push_back
(Ty
);
173 if
(const OpaqueType
* OpTy
= dyn_cast
<OpaqueType
>(Ty
)) {
174 // Check to see if this is an unresolved type
175 std
::map
<ValID
, PATypeHolder
>::iterator I
= LateResolveTypes.begin
();
176 std
::map
<ValID
, PATypeHolder
>::iterator E
= LateResolveTypes.end
();
177 for
( ; I
!= E
; ++I
) {
178 if
(I
->second.get
() == OpTy
)
181 } else if
(const SequentialType
* SeqTy
= dyn_cast
<SequentialType
>(Ty
)) {
182 const Type
* TheTy
= SeqTy
->getElementType
();
183 if
(TheTy
->isAbstract
() && TheTy
!= Ty
) {
184 std
::vector
<const Type
*>::iterator I
= SeenList.begin
(),
190 WorkList.push_back
(TheTy
);
192 } else if
(const StructType
* StrTy
= dyn_cast
<StructType
>(Ty
)) {
193 for
(unsigned i
= 0; i
< StrTy
->getNumElements
(); ++i
) {
194 const Type
* TheTy
= StrTy
->getElementType
(i
);
195 if
(TheTy
->isAbstract
() && TheTy
!= Ty
) {
196 std
::vector
<const Type
*>::iterator I
= SeenList.begin
(),
202 WorkList.push_back
(TheTy
);
211 static struct PerFunctionInfo
{
212 Function
*CurrentFunction
; // Pointer to current function being created
214 ValueList Values
; // Keep track of #'d definitions
216 ValueList LateResolveValues
;
217 bool isDeclare
; // Is this function a forward declararation?
218 GlobalValue
::LinkageTypes Linkage
; // Linkage for forward declaration.
219 GlobalValue
::VisibilityTypes Visibility
;
221 /// BBForwardRefs - When we see forward references to basic blocks, keep
222 /// track of them here.
223 std
::map
<ValID
, BasicBlock
*> BBForwardRefs
;
225 inline PerFunctionInfo
() {
228 Linkage
= GlobalValue
::ExternalLinkage
;
229 Visibility
= GlobalValue
::DefaultVisibility
;
232 inline
void FunctionStart
(Function
*M
) {
237 void FunctionDone
() {
238 // Any forward referenced blocks left?
239 if
(!BBForwardRefs.empty
()) {
240 GenerateError
("Undefined reference to label " +
241 BBForwardRefs.begin
()->second
->getName
());
245 // Resolve all forward references now.
246 ResolveDefinitions
(LateResolveValues
, &CurModule.LateResolveValues
);
248 Values.clear
(); // Clear out function local definitions
249 BBForwardRefs.clear
();
252 Linkage
= GlobalValue
::ExternalLinkage
;
253 Visibility
= GlobalValue
::DefaultVisibility
;
255 } CurFun
; // Info for the current function...
257 static bool inFunctionScope
() { return CurFun.CurrentFunction
!= 0; }
260 //===----------------------------------------------------------------------===//
261 // Code to handle definitions of all the types
262 //===----------------------------------------------------------------------===//
264 static void InsertValue
(Value
*V
, ValueList
&ValueTab
= CurFun.Values
) {
265 // Things that have names or are void typed don't get slot numbers
266 if
(V
->hasName
() ||
(V
->getType
() == Type
::VoidTy
))
269 // In the case of function values, we have to allow for the forward reference
270 // of basic blocks, which are included in the numbering. Consequently, we keep
271 // track of the next insertion location with NextValNum. When a BB gets
272 // inserted, it could change the size of the CurFun.Values vector.
273 if
(&ValueTab
== &CurFun.Values
) {
274 if
(ValueTab.size
() <= CurFun.NextValNum
)
275 ValueTab.resize
(CurFun.NextValNum
+1);
276 ValueTab
[CurFun.NextValNum
++] = V
;
279 // For all other lists, its okay to just tack it on the back of the vector.
280 ValueTab.push_back
(V
);
283 static const Type
*getTypeVal
(const ValID
&D
, bool DoNotImprovise
= false
) {
285 case ValID
::LocalID
: // Is it a numbered definition?
286 // Module constants occupy the lowest numbered slots...
287 if
(D.Num
< CurModule.Types.size
())
288 return CurModule.Types
[D.Num
];
290 case ValID
::LocalName
: // Is it a named definition?
291 if
(const Type
*N
= CurModule.CurrentModule
->getTypeByName
(D.getName
())) {
292 D.destroy
(); // Free old strdup'd memory...
297 GenerateError
("Internal parser error: Invalid symbol type reference");
301 // If we reached here, we referenced either a symbol that we don't know about
302 // or an id number that hasn't been read yet. We may be referencing something
303 // forward, so just create an entry to be resolved later and get to it...
305 if
(DoNotImprovise
) return
0; // Do we just want a null to be returned?
308 if
(inFunctionScope
()) {
309 if
(D.Type
== ValID
::LocalName
) {
310 GenerateError
("Reference to an undefined type: '" + D.getName
() + "'");
313 GenerateError
("Reference to an undefined type: #" + utostr
(D.Num
));
318 std
::map
<ValID
, PATypeHolder
>::iterator I
=CurModule.LateResolveTypes.find
(D
);
319 if
(I
!= CurModule.LateResolveTypes.end
())
322 Type
*Typ
= OpaqueType
::get
();
323 CurModule.LateResolveTypes.insert
(std
::make_pair
(D
, Typ
));
327 // getExistingVal - Look up the value specified by the provided type and
328 // the provided ValID. If the value exists and has already been defined, return
329 // it. Otherwise return null.
331 static Value
*getExistingVal
(const Type
*Ty
, const ValID
&D
) {
332 if
(isa
<FunctionType
>(Ty
)) {
333 GenerateError
("Functions are not values and "
334 "must be referenced as pointers");
339 case ValID
::LocalID
: { // Is it a numbered definition?
340 // Check that the number is within bounds.
341 if
(D.Num
>= CurFun.Values.size
())
343 Value
*Result
= CurFun.Values
[D.Num
];
344 if
(Ty
!= Result
->getType
()) {
345 GenerateError
("Numbered value (%" + utostr
(D.Num
) + ") of type '" +
346 Result
->getType
()->getDescription
() + "' does not match "
347 "expected type, '" + Ty
->getDescription
() + "'");
352 case ValID
::GlobalID
: { // Is it a numbered definition?
353 if
(D.Num
>= CurModule.Values.size
())
355 Value
*Result
= CurModule.Values
[D.Num
];
356 if
(Ty
!= Result
->getType
()) {
357 GenerateError
("Numbered value (@" + utostr
(D.Num
) + ") of type '" +
358 Result
->getType
()->getDescription
() + "' does not match "
359 "expected type, '" + Ty
->getDescription
() + "'");
365 case ValID
::LocalName
: { // Is it a named definition?
366 if
(!inFunctionScope
())
368 ValueSymbolTable
&SymTab
= CurFun.CurrentFunction
->getValueSymbolTable
();
369 Value
*N
= SymTab.lookup
(D.getName
());
372 if
(N
->getType
() != Ty
)
375 D.destroy
(); // Free old strdup'd memory...
378 case ValID
::GlobalName
: { // Is it a named definition?
379 ValueSymbolTable
&SymTab
= CurModule.CurrentModule
->getValueSymbolTable
();
380 Value
*N
= SymTab.lookup
(D.getName
());
383 if
(N
->getType
() != Ty
)
386 D.destroy
(); // Free old strdup'd memory...
390 // Check to make sure that "Ty" is an integral type, and that our
391 // value will fit into the specified type...
392 case ValID
::ConstSIntVal
: // Is it a constant pool reference??
393 if
(!ConstantInt
::isValueValidForType
(Ty
, D.ConstPool64
)) {
394 GenerateError
("Signed integral constant '" +
395 itostr
(D.ConstPool64
) + "' is invalid for type '" +
396 Ty
->getDescription
() + "'");
399 return ConstantInt
::get
(Ty
, D.ConstPool64
, true
);
401 case ValID
::ConstUIntVal
: // Is it an unsigned const pool reference?
402 if
(!ConstantInt
::isValueValidForType
(Ty
, D.UConstPool64
)) {
403 if
(!ConstantInt
::isValueValidForType
(Ty
, D.ConstPool64
)) {
404 GenerateError
("Integral constant '" + utostr
(D.UConstPool64
) +
405 "' is invalid or out of range");
407 } else
{ // This is really a signed reference. Transmogrify.
408 return ConstantInt
::get
(Ty
, D.ConstPool64
, true
);
411 return ConstantInt
::get
(Ty
, D.UConstPool64
);
414 case ValID
::ConstFPVal
: // Is it a floating point const pool reference?
415 if
(!ConstantFP
::isValueValidForType
(Ty
, *D.ConstPoolFP
)) {
416 GenerateError
("FP constant invalid for type");
419 // Lexer has no type info, so builds all float and double FP constants
420 // as double. Fix this here. Long double does not need this.
421 if
(&D.ConstPoolFP
->getSemantics
() == &APFloat
::IEEEdouble
&&
423 D.ConstPoolFP
->convert
(APFloat
::IEEEsingle
, APFloat
::rmNearestTiesToEven
);
424 return ConstantFP
::get
(Ty
, *D.ConstPoolFP
);
426 case ValID
::ConstNullVal
: // Is it a null value?
427 if
(!isa
<PointerType
>(Ty
)) {
428 GenerateError
("Cannot create a a non pointer null");
431 return ConstantPointerNull
::get
(cast
<PointerType
>(Ty
));
433 case ValID
::ConstUndefVal
: // Is it an undef value?
434 return UndefValue
::get
(Ty
);
436 case ValID
::ConstZeroVal
: // Is it a zero value?
437 return Constant
::getNullValue
(Ty
);
439 case ValID
::ConstantVal
: // Fully resolved constant?
440 if
(D.ConstantValue
->getType
() != Ty
) {
441 GenerateError
("Constant expression type different from required type");
444 return D.ConstantValue
;
446 case ValID
::InlineAsmVal
: { // Inline asm expression
447 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
448 const FunctionType
*FTy
=
449 PTy ? dyn_cast
<FunctionType
>(PTy
->getElementType
()) : 0;
450 if
(!FTy ||
!InlineAsm
::Verify
(FTy
, D.IAD
->Constraints
)) {
451 GenerateError
("Invalid type for asm constraint string");
454 InlineAsm
*IA
= InlineAsm
::get
(FTy
, D.IAD
->AsmString
, D.IAD
->Constraints
,
455 D.IAD
->HasSideEffects
);
456 D.destroy
(); // Free InlineAsmDescriptor.
460 assert
(0 && "Unhandled case!");
464 assert
(0 && "Unhandled case!");
468 // getVal - This function is identical to getExistingVal, except that if a
469 // value is not already defined, it "improvises" by creating a placeholder var
470 // that looks and acts just like the requested variable. When the value is
471 // defined later, all uses of the placeholder variable are replaced with the
474 static Value
*getVal
(const Type
*Ty
, const ValID
&ID
) {
475 if
(Ty
== Type
::LabelTy
) {
476 GenerateError
("Cannot use a basic block here");
480 // See if the value has already been defined.
481 Value
*V
= getExistingVal
(Ty
, ID
);
483 if
(TriggerError
) return
0;
485 if
(!Ty
->isFirstClassType
() && !isa
<OpaqueType
>(Ty
)) {
486 GenerateError
("Invalid use of a composite type");
490 // If we reached here, we referenced either a symbol that we don't know about
491 // or an id number that hasn't been read yet. We may be referencing something
492 // forward, so just create an entry to be resolved later and get to it...
495 case ValID
::GlobalName
:
496 case ValID
::GlobalID
: {
497 const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
499 GenerateError
("Invalid type for reference to global" );
502 const Type
* ElTy
= PTy
->getElementType
();
503 if
(const FunctionType
*FTy
= dyn_cast
<FunctionType
>(ElTy
))
504 V
= new Function
(FTy
, GlobalValue
::ExternalLinkage
);
506 V
= new GlobalVariable
(ElTy
, false
, GlobalValue
::ExternalLinkage
);
510 V
= new Argument
(Ty
);
513 // Remember where this forward reference came from. FIXME, shouldn't we try
514 // to recycle these things??
515 CurModule.PlaceHolderInfo.insert
(std
::make_pair
(V
, std
::make_pair
(ID
,
518 if
(inFunctionScope
())
519 InsertValue
(V
, CurFun.LateResolveValues
);
521 InsertValue
(V
, CurModule.LateResolveValues
);
525 /// defineBBVal - This is a definition of a new basic block with the specified
526 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
527 static BasicBlock
*defineBBVal
(const ValID
&ID
) {
528 assert
(inFunctionScope
() && "Can't get basic block at global scope!");
532 // First, see if this was forward referenced
534 std
::map
<ValID
, BasicBlock
*>::iterator BBI
= CurFun.BBForwardRefs.find
(ID
);
535 if
(BBI
!= CurFun.BBForwardRefs.end
()) {
537 // The forward declaration could have been inserted anywhere in the
538 // function: insert it into the correct place now.
539 CurFun.CurrentFunction
->getBasicBlockList
().remove
(BB
);
540 CurFun.CurrentFunction
->getBasicBlockList
().push_back
(BB
);
542 // We're about to erase the entry, save the key so we can clean it up.
543 ValID Tmp
= BBI
->first
;
545 // Erase the forward ref from the map as its no longer "forward"
546 CurFun.BBForwardRefs.erase
(ID
);
548 // The key has been removed from the map but so we don't want to leave
549 // strdup'd memory around so destroy it too.
552 // If its a numbered definition, bump the number and set the BB value.
553 if
(ID.Type
== ValID
::LocalID
) {
554 assert
(ID.Num
== CurFun.NextValNum
&& "Invalid new block number");
562 // We haven't seen this BB before and its first mention is a definition.
563 // Just create it and return it.
564 std
::string Name
(ID.Type
== ValID
::LocalName ? ID.getName
() : "");
565 BB
= new BasicBlock
(Name
, CurFun.CurrentFunction
);
566 if
(ID.Type
== ValID
::LocalID
) {
567 assert
(ID.Num
== CurFun.NextValNum
&& "Invalid new block number");
571 ID.destroy
(); // Free strdup'd memory
575 /// getBBVal - get an existing BB value or create a forward reference for it.
577 static BasicBlock
*getBBVal
(const ValID
&ID
) {
578 assert
(inFunctionScope
() && "Can't get basic block at global scope!");
582 std
::map
<ValID
, BasicBlock
*>::iterator BBI
= CurFun.BBForwardRefs.find
(ID
);
583 if
(BBI
!= CurFun.BBForwardRefs.end
()) {
585 } if
(ID.Type
== ValID
::LocalName
) {
586 std
::string Name
= ID.getName
();
587 Value
*N
= CurFun.CurrentFunction
->getValueSymbolTable
().lookup
(Name
);
589 if
(N
->getType
()->getTypeID
() == Type
::LabelTyID
)
590 BB
= cast
<BasicBlock
>(N
);
592 GenerateError
("Reference to label '" + Name
+ "' is actually of type '"+
593 N
->getType
()->getDescription
() + "'");
594 } else if
(ID.Type
== ValID
::LocalID
) {
595 if
(ID.Num
< CurFun.NextValNum
&& ID.Num
< CurFun.Values.size
()) {
596 if
(CurFun.Values
[ID.Num
]->getType
()->getTypeID
() == Type
::LabelTyID
)
597 BB
= cast
<BasicBlock
>(CurFun.Values
[ID.Num
]);
599 GenerateError
("Reference to label '%" + utostr
(ID.Num
) +
600 "' is actually of type '"+
601 CurFun.Values
[ID.Num
]->getType
()->getDescription
() + "'");
604 GenerateError
("Illegal label reference " + ID.getName
());
608 // If its already been defined, return it now.
610 ID.destroy
(); // Free strdup'd memory.
614 // Otherwise, this block has not been seen before, create it.
616 if
(ID.Type
== ValID
::LocalName
)
618 BB
= new BasicBlock
(Name
, CurFun.CurrentFunction
);
620 // Insert it in the forward refs map.
621 CurFun.BBForwardRefs
[ID
] = BB
;
627 //===----------------------------------------------------------------------===//
628 // Code to handle forward references in instructions
629 //===----------------------------------------------------------------------===//
631 // This code handles the late binding needed with statements that reference
632 // values not defined yet... for example, a forward branch, or the PHI node for
635 // This keeps a table (CurFun.LateResolveValues) of all such forward references
636 // and back patchs after we are done.
639 // ResolveDefinitions - If we could not resolve some defs at parsing
640 // time (forward branches, phi functions for loops, etc...) resolve the
644 ResolveDefinitions
(ValueList
&LateResolvers
, ValueList
*FutureLateResolvers
) {
645 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
646 while
(!LateResolvers.empty
()) {
647 Value
*V
= LateResolvers.back
();
648 LateResolvers.pop_back
();
650 std
::map
<Value
*, std
::pair
<ValID
, int> >::iterator PHI
=
651 CurModule.PlaceHolderInfo.find
(V
);
652 assert
(PHI
!= CurModule.PlaceHolderInfo.end
() && "Placeholder error!");
654 ValID
&DID
= PHI
->second.first
;
656 Value
*TheRealValue
= getExistingVal
(V
->getType
(), DID
);
660 V
->replaceAllUsesWith
(TheRealValue
);
662 CurModule.PlaceHolderInfo.erase
(PHI
);
663 } else if
(FutureLateResolvers
) {
664 // Functions have their unresolved items forwarded to the module late
666 InsertValue
(V
, *FutureLateResolvers
);
668 if
(DID.Type
== ValID
::LocalName || DID.Type
== ValID
::GlobalName
) {
669 GenerateError
("Reference to an invalid definition: '" +DID.getName
()+
670 "' of type '" + V
->getType
()->getDescription
() + "'",
674 GenerateError
("Reference to an invalid definition: #" +
675 itostr
(DID.Num
) + " of type '" +
676 V
->getType
()->getDescription
() + "'",
682 LateResolvers.clear
();
685 // ResolveTypeTo - A brand new type was just declared. This means that (if
686 // name is not null) things referencing Name can be resolved. Otherwise, things
687 // refering to the number can be resolved. Do this now.
689 static void ResolveTypeTo
(std
::string *Name
, const Type
*ToTy
) {
692 D
= ValID
::createLocalName
(*Name
);
694 D
= ValID
::createLocalID
(CurModule.Types.size
());
696 std
::map
<ValID
, PATypeHolder
>::iterator I
=
697 CurModule.LateResolveTypes.find
(D
);
698 if
(I
!= CurModule.LateResolveTypes.end
()) {
699 ((DerivedType
*)I
->second.get
())->refineAbstractTypeTo
(ToTy
);
700 CurModule.LateResolveTypes.erase
(I
);
704 // setValueName - Set the specified value to the name given. The name may be
705 // null potentially, in which case this is a noop. The string passed in is
706 // assumed to be a malloc'd string buffer, and is free'd by this function.
708 static void setValueName
(Value
*V
, std
::string *NameStr
) {
709 if
(!NameStr
) return
;
710 std
::string Name
(*NameStr
); // Copy string
711 delete NameStr
; // Free old string
713 if
(V
->getType
() == Type
::VoidTy
) {
714 GenerateError
("Can't assign name '" + Name
+"' to value with void type");
718 assert
(inFunctionScope
() && "Must be in function scope!");
719 ValueSymbolTable
&ST
= CurFun.CurrentFunction
->getValueSymbolTable
();
720 if
(ST.lookup
(Name
)) {
721 GenerateError
("Redefinition of value '" + Name
+ "' of type '" +
722 V
->getType
()->getDescription
() + "'");
730 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
731 /// this is a declaration, otherwise it is a definition.
732 static GlobalVariable
*
733 ParseGlobalVariable
(std
::string *NameStr
,
734 GlobalValue
::LinkageTypes Linkage
,
735 GlobalValue
::VisibilityTypes Visibility
,
736 bool isConstantGlobal
, const Type
*Ty
,
737 Constant
*Initializer
, bool IsThreadLocal
) {
738 if
(isa
<FunctionType
>(Ty
)) {
739 GenerateError
("Cannot declare global vars of function type");
743 const PointerType
*PTy
= PointerType
::get
(Ty
);
747 Name
= *NameStr
; // Copy string
748 delete NameStr
; // Free old string
751 // See if this global value was forward referenced. If so, recycle the
755 ID
= ValID
::createGlobalName
(Name
);
757 ID
= ValID
::createGlobalID
(CurModule.Values.size
());
760 if
(GlobalValue
*FWGV
= CurModule.GetForwardRefForGlobal
(PTy
, ID
)) {
761 // Move the global to the end of the list, from whereever it was
762 // previously inserted.
763 GlobalVariable
*GV
= cast
<GlobalVariable
>(FWGV
);
764 CurModule.CurrentModule
->getGlobalList
().remove
(GV
);
765 CurModule.CurrentModule
->getGlobalList
().push_back
(GV
);
766 GV
->setInitializer
(Initializer
);
767 GV
->setLinkage
(Linkage
);
768 GV
->setVisibility
(Visibility
);
769 GV
->setConstant
(isConstantGlobal
);
770 GV
->setThreadLocal
(IsThreadLocal
);
771 InsertValue
(GV
, CurModule.Values
);
775 // If this global has a name
777 // if the global we're parsing has an initializer (is a definition) and
778 // has external linkage.
779 if
(Initializer
&& Linkage
!= GlobalValue
::InternalLinkage
)
780 // If there is already a global with external linkage with this name
781 if
(CurModule.CurrentModule
->getGlobalVariable
(Name
, false
)) {
782 // If we allow this GVar to get created, it will be renamed in the
783 // symbol table because it conflicts with an existing GVar. We can't
784 // allow redefinition of GVars whose linking indicates that their name
785 // must stay the same. Issue the error.
786 GenerateError
("Redefinition of global variable named '" + Name
+
787 "' of type '" + Ty
->getDescription
() + "'");
792 // Otherwise there is no existing GV to use, create one now.
794 new GlobalVariable
(Ty
, isConstantGlobal
, Linkage
, Initializer
, Name
,
795 CurModule.CurrentModule
, IsThreadLocal
);
796 GV
->setVisibility
(Visibility
);
797 InsertValue
(GV
, CurModule.Values
);
801 // setTypeName - Set the specified type to the name given. The name may be
802 // null potentially, in which case this is a noop. The string passed in is
803 // assumed to be a malloc'd string buffer, and is freed by this function.
805 // This function returns true if the type has already been defined, but is
806 // allowed to be redefined in the specified context. If the name is a new name
807 // for the type plane, it is inserted and false is returned.
808 static bool setTypeName
(const Type
*T
, std
::string *NameStr
) {
809 assert
(!inFunctionScope
() && "Can't give types function-local names!");
810 if
(NameStr
== 0) return false
;
812 std
::string Name
(*NameStr
); // Copy string
813 delete NameStr
; // Free old string
815 // We don't allow assigning names to void type
816 if
(T
== Type
::VoidTy
) {
817 GenerateError
("Can't assign name '" + Name
+ "' to the void type");
821 // Set the type name, checking for conflicts as we do so.
822 bool AlreadyExists
= CurModule.CurrentModule
->addTypeName
(Name
, T
);
824 if
(AlreadyExists
) { // Inserting a name that is already defined???
825 const Type
*Existing
= CurModule.CurrentModule
->getTypeByName
(Name
);
826 assert
(Existing
&& "Conflict but no matching type?!");
828 // There is only one case where this is allowed: when we are refining an
829 // opaque type. In this case, Existing will be an opaque type.
830 if
(const OpaqueType
*OpTy
= dyn_cast
<OpaqueType
>(Existing
)) {
831 // We ARE replacing an opaque type!
832 const_cast
<OpaqueType
*>(OpTy
)->refineAbstractTypeTo
(T
);
836 // Otherwise, this is an attempt to redefine a type. That's okay if
837 // the redefinition is identical to the original. This will be so if
838 // Existing and T point to the same Type object. In this one case we
839 // allow the equivalent redefinition.
840 if
(Existing
== T
) return true
; // Yes, it's equal.
842 // Any other kind of (non-equivalent) redefinition is an error.
843 GenerateError
("Redefinition of type named '" + Name
+ "' of type '" +
844 T
->getDescription
() + "'");
850 //===----------------------------------------------------------------------===//
851 // Code for handling upreferences in type names...
854 // TypeContains - Returns true if Ty directly contains E in it.
856 static bool TypeContains
(const Type
*Ty
, const Type
*E
) {
857 return std
::find
(Ty
->subtype_begin
(), Ty
->subtype_end
(),
858 E
) != Ty
->subtype_end
();
863 // NestingLevel - The number of nesting levels that need to be popped before
864 // this type is resolved.
865 unsigned NestingLevel
;
867 // LastContainedTy - This is the type at the current binding level for the
868 // type. Every time we reduce the nesting level, this gets updated.
869 const Type
*LastContainedTy
;
871 // UpRefTy - This is the actual opaque type that the upreference is
875 UpRefRecord
(unsigned NL
, OpaqueType
*URTy
)
876 : NestingLevel
(NL
), LastContainedTy
(URTy
), UpRefTy
(URTy
) {}
880 // UpRefs - A list of the outstanding upreferences that need to be resolved.
881 static std
::vector
<UpRefRecord
> UpRefs
;
883 /// HandleUpRefs - Every time we finish a new layer of types, this function is
884 /// called. It loops through the UpRefs vector, which is a list of the
885 /// currently active types. For each type, if the up reference is contained in
886 /// the newly completed type, we decrement the level count. When the level
887 /// count reaches zero, the upreferenced type is the type that is passed in:
888 /// thus we can complete the cycle.
890 static PATypeHolder HandleUpRefs
(const Type
*ty
) {
891 // If Ty isn't abstract, or if there are no up-references in it, then there is
892 // nothing to resolve here.
893 if
(!ty
->isAbstract
() || UpRefs.empty
()) return ty
;
896 UR_OUT
("Type '" << Ty
->getDescription
() <<
897 "' newly formed. Resolving upreferences.\n" <<
898 UpRefs.size
() << " upreferences active!\n");
900 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
901 // to zero), we resolve them all together before we resolve them to Ty. At
902 // the end of the loop, if there is anything to resolve to Ty, it will be in
904 OpaqueType
*TypeToResolve
= 0;
906 for
(unsigned i
= 0; i
!= UpRefs.size
(); ++i
) {
907 UR_OUT
(" UR#" << i
<< " - TypeContains(" << Ty
->getDescription
() << ", "
908 << UpRefs
[i
].second
->getDescription
() << ") = "
909 << (TypeContains
(Ty
, UpRefs
[i
].second
) ?
"true" : "false") << "\n");
910 if
(TypeContains
(Ty
, UpRefs
[i
].LastContainedTy
)) {
911 // Decrement level of upreference
912 unsigned Level
= --UpRefs
[i
].NestingLevel
;
913 UpRefs
[i
].LastContainedTy
= Ty
;
914 UR_OUT
(" Uplevel Ref Level = " << Level
<< "\n");
915 if
(Level
== 0) { // Upreference should be resolved!
916 if
(!TypeToResolve
) {
917 TypeToResolve
= UpRefs
[i
].UpRefTy
;
919 UR_OUT
(" * Resolving upreference for "
920 << UpRefs
[i
].second
->getDescription
() << "\n";
921 std
::string OldName
= UpRefs
[i
].UpRefTy
->getDescription
());
922 UpRefs
[i
].UpRefTy
->refineAbstractTypeTo
(TypeToResolve
);
923 UR_OUT
(" * Type '" << OldName
<< "' refined upreference to: "
924 << (const void*)Ty
<< ", " << Ty
->getDescription
() << "\n");
926 UpRefs.erase
(UpRefs.begin
()+i
); // Remove from upreference list...
927 --i
; // Do not skip the next element...
933 UR_OUT
(" * Resolving upreference for "
934 << UpRefs
[i
].second
->getDescription
() << "\n";
935 std
::string OldName
= TypeToResolve
->getDescription
());
936 TypeToResolve
->refineAbstractTypeTo
(Ty
);
942 //===----------------------------------------------------------------------===//
943 // RunVMAsmParser - Define an interface to this parser
944 //===----------------------------------------------------------------------===//
946 static Module
* RunParser
(Module
* M
);
948 Module
*llvm
::RunVMAsmParser
(const std
::string &Filename
, FILE *F
) {
951 CurFilename
= Filename
;
952 return RunParser
(new Module
(CurFilename
));
955 Module
*llvm
::RunVMAsmParser
(const char * AsmString
, Module
* M
) {
956 set_scan_string
(AsmString
);
958 CurFilename
= "from_memory";
960 return RunParser
(new Module
(CurFilename
));
969 llvm
::Module
*ModuleVal
;
970 llvm
::Function
*FunctionVal
;
971 llvm
::BasicBlock
*BasicBlockVal
;
972 llvm
::TerminatorInst
*TermInstVal
;
973 llvm
::Instruction
*InstVal
;
974 llvm
::Constant
*ConstVal
;
976 const llvm
::Type
*PrimType
;
977 std
::list
<llvm
::PATypeHolder
> *TypeList
;
978 llvm
::PATypeHolder
*TypeVal
;
979 llvm
::Value
*ValueVal
;
980 std
::vector
<llvm
::Value
*> *ValueList
;
981 llvm
::ArgListType
*ArgList
;
982 llvm
::TypeWithAttrs TypeWithAttrs
;
983 llvm
::TypeWithAttrsList
*TypeWithAttrsList
;
984 llvm
::ValueRefList
*ValueRefList
;
986 // Represent the RHS of PHI node
987 std
::list
<std
::pair
<llvm
::Value
*,
988 llvm
::BasicBlock
*> > *PHIList
;
989 std
::vector
<std
::pair
<llvm
::Constant
*, llvm
::BasicBlock
*> > *JumpTable
;
990 std
::vector
<llvm
::Constant
*> *ConstVector
;
992 llvm
::GlobalValue
::LinkageTypes Linkage
;
993 llvm
::GlobalValue
::VisibilityTypes Visibility
;
995 llvm
::APInt
*APIntVal
;
1000 llvm
::APFloat
*FPVal
;
1003 std
::string *StrVal
; // This memory must be deleted
1004 llvm
::ValID ValIDVal
;
1006 llvm
::Instruction
::BinaryOps BinaryOpVal
;
1007 llvm
::Instruction
::TermOps TermOpVal
;
1008 llvm
::Instruction
::MemoryOps MemOpVal
;
1009 llvm
::Instruction
::CastOps CastOpVal
;
1010 llvm
::Instruction
::OtherOps OtherOpVal
;
1011 llvm
::ICmpInst
::Predicate IPredicate
;
1012 llvm
::FCmpInst
::Predicate FPredicate
;
1015 %type
<ModuleVal
> Module
1016 %type
<FunctionVal
> Function FunctionProto FunctionHeader BasicBlockList
1017 %type
<BasicBlockVal
> BasicBlock InstructionList
1018 %type
<TermInstVal
> BBTerminatorInst
1019 %type
<InstVal
> Inst InstVal MemoryInst
1020 %type
<ConstVal
> ConstVal ConstExpr AliaseeRef
1021 %type
<ConstVector
> ConstVector
1022 %type
<ArgList
> ArgList ArgListH
1023 %type
<PHIList
> PHIList
1024 %type
<ValueRefList
> ValueRefList
// For call param lists & GEP indices
1025 %type
<ValueList
> IndexList
// For GEP indices
1026 %type
<TypeList
> TypeListI
1027 %type
<TypeWithAttrsList
> ArgTypeList ArgTypeListI
1028 %type
<TypeWithAttrs
> ArgType
1029 %type
<JumpTable
> JumpTable
1030 %type
<BoolVal
> GlobalType
// GLOBAL or CONSTANT?
1031 %type
<BoolVal
> ThreadLocal
// 'thread_local' or not
1032 %type
<BoolVal
> OptVolatile
// 'volatile' or not
1033 %type
<BoolVal
> OptTailCall
// TAIL CALL or plain CALL.
1034 %type
<BoolVal
> OptSideEffect
// 'sideeffect' or not.
1035 %type
<Linkage
> GVInternalLinkage GVExternalLinkage
1036 %type
<Linkage
> FunctionDefineLinkage FunctionDeclareLinkage
1037 %type
<Linkage
> AliasLinkage
1038 %type
<Visibility
> GVVisibilityStyle
1040 // ValueRef - Unresolved reference to a definition or BB
1041 %type
<ValIDVal
> ValueRef ConstValueRef SymbolicValueRef
1042 %type
<ValueVal
> ResolvedVal
// <type> <valref> pair
1043 // Tokens and types for handling constant integer values
1045 // ESINT64VAL - A negative number within long long range
1046 %token
<SInt64Val
> ESINT64VAL
1048 // EUINT64VAL - A positive number within uns. long long range
1049 %token
<UInt64Val
> EUINT64VAL
1051 // ESAPINTVAL - A negative number with arbitrary precision
1052 %token
<APIntVal
> ESAPINTVAL
1054 // EUAPINTVAL - A positive number with arbitrary precision
1055 %token
<APIntVal
> EUAPINTVAL
1057 %token
<UIntVal
> LOCALVAL_ID GLOBALVAL_ID
// %123 @123
1058 %token
<FPVal
> FPVAL
// Float or Double constant
1060 // Built in types...
1061 %type
<TypeVal
> Types ResultTypes
1062 %type
<PrimType
> IntType FPType PrimType
// Classifications
1063 %token
<PrimType
> VOID INTTYPE
1064 %token
<PrimType
> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1068 %token
<StrVal
> LOCALVAR GLOBALVAR LABELSTR
1069 %token
<StrVal
> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1070 %type
<StrVal
> LocalName OptLocalName OptLocalAssign
1071 %type
<StrVal
> GlobalName OptGlobalAssign GlobalAssign
1072 %type
<StrVal
> OptSection SectionString
1074 %type
<UIntVal
> OptAlign OptCAlign
1076 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1077 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1078 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1079 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1080 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
1081 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1082 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1084 %type
<UIntVal
> OptCallingConv
1085 %type
<ParamAttrs
> OptParamAttrs ParamAttr
1086 %type
<ParamAttrs
> OptFuncAttrs FuncAttr
1088 // Basic Block Terminating Operators
1089 %token
<TermOpVal
> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1092 %type
<BinaryOpVal
> ArithmeticOps LogicalOps
// Binops Subcatagories
1093 %token
<BinaryOpVal
> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1094 %token
<BinaryOpVal
> SHL LSHR ASHR
1096 %token
<OtherOpVal
> ICMP FCMP
1097 %type
<IPredicate
> IPredicates
1098 %type
<FPredicate
> FPredicates
1099 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1100 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1102 // Memory Instructions
1103 %token
<MemOpVal
> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1106 %type
<CastOpVal
> CastOps
1107 %token
<CastOpVal
> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1108 %token
<CastOpVal
> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1111 %token
<OtherOpVal
> PHI_TOK SELECT VAARG
1112 %token
<OtherOpVal
> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1114 // Function Attributes
1115 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1117 // Visibility Styles
1118 %token DEFAULT HIDDEN PROTECTED
1124 // Operations that are notably excluded from this list include:
1125 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1127 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM
;
1128 LogicalOps
: SHL | LSHR | ASHR | AND | OR | XOR
;
1129 CastOps
: TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1130 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT
;
1133 : EQ
{ $$
= ICmpInst
::ICMP_EQ
; } | NE
{ $$
= ICmpInst
::ICMP_NE
; }
1134 | SLT
{ $$
= ICmpInst
::ICMP_SLT
; } | SGT
{ $$
= ICmpInst
::ICMP_SGT
; }
1135 | SLE
{ $$
= ICmpInst
::ICMP_SLE
; } | SGE
{ $$
= ICmpInst
::ICMP_SGE
; }
1136 | ULT
{ $$
= ICmpInst
::ICMP_ULT
; } | UGT
{ $$
= ICmpInst
::ICMP_UGT
; }
1137 | ULE
{ $$
= ICmpInst
::ICMP_ULE
; } | UGE
{ $$
= ICmpInst
::ICMP_UGE
; }
1141 : OEQ
{ $$
= FCmpInst
::FCMP_OEQ
; } | ONE
{ $$
= FCmpInst
::FCMP_ONE
; }
1142 | OLT
{ $$
= FCmpInst
::FCMP_OLT
; } | OGT
{ $$
= FCmpInst
::FCMP_OGT
; }
1143 | OLE
{ $$
= FCmpInst
::FCMP_OLE
; } | OGE
{ $$
= FCmpInst
::FCMP_OGE
; }
1144 | ORD
{ $$
= FCmpInst
::FCMP_ORD
; } | UNO
{ $$
= FCmpInst
::FCMP_UNO
; }
1145 | UEQ
{ $$
= FCmpInst
::FCMP_UEQ
; } | UNE
{ $$
= FCmpInst
::FCMP_UNE
; }
1146 | ULT
{ $$
= FCmpInst
::FCMP_ULT
; } | UGT
{ $$
= FCmpInst
::FCMP_UGT
; }
1147 | ULE
{ $$
= FCmpInst
::FCMP_ULE
; } | UGE
{ $$
= FCmpInst
::FCMP_UGE
; }
1148 | TRUETOK
{ $$
= FCmpInst
::FCMP_TRUE
; }
1149 | FALSETOK
{ $$
= FCmpInst
::FCMP_FALSE
; }
1152 // These are some types that allow classification if we only want a particular
1153 // thing... for example, only a signed, unsigned, or integral type.
1155 FPType
: FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80
;
1157 LocalName
: LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT
;
1158 OptLocalName
: LocalName |
/*empty*/ { $$
= 0; };
1160 /// OptLocalAssign - Value producing statements have an optional assignment
1162 OptLocalAssign
: LocalName
'=' {
1171 GlobalName
: GLOBALVAR | ATSTRINGCONSTANT
;
1173 OptGlobalAssign
: GlobalAssign
1179 GlobalAssign
: GlobalName
'=' {
1185 : INTERNAL
{ $$
= GlobalValue
::InternalLinkage
; }
1186 | WEAK
{ $$
= GlobalValue
::WeakLinkage
; }
1187 | LINKONCE
{ $$
= GlobalValue
::LinkOnceLinkage
; }
1188 | APPENDING
{ $$
= GlobalValue
::AppendingLinkage
; }
1189 | DLLEXPORT
{ $$
= GlobalValue
::DLLExportLinkage
; }
1193 : DLLIMPORT
{ $$
= GlobalValue
::DLLImportLinkage
; }
1194 | EXTERN_WEAK
{ $$
= GlobalValue
::ExternalWeakLinkage
; }
1195 | EXTERNAL
{ $$
= GlobalValue
::ExternalLinkage
; }
1199 : /*empty*/ { $$
= GlobalValue
::DefaultVisibility
; }
1200 | DEFAULT
{ $$
= GlobalValue
::DefaultVisibility
; }
1201 | HIDDEN
{ $$
= GlobalValue
::HiddenVisibility
; }
1202 | PROTECTED
{ $$
= GlobalValue
::ProtectedVisibility
; }
1205 FunctionDeclareLinkage
1206 : /*empty*/ { $$
= GlobalValue
::ExternalLinkage
; }
1207 | DLLIMPORT
{ $$
= GlobalValue
::DLLImportLinkage
; }
1208 | EXTERN_WEAK
{ $$
= GlobalValue
::ExternalWeakLinkage
; }
1211 FunctionDefineLinkage
1212 : /*empty*/ { $$
= GlobalValue
::ExternalLinkage
; }
1213 | INTERNAL
{ $$
= GlobalValue
::InternalLinkage
; }
1214 | LINKONCE
{ $$
= GlobalValue
::LinkOnceLinkage
; }
1215 | WEAK
{ $$
= GlobalValue
::WeakLinkage
; }
1216 | DLLEXPORT
{ $$
= GlobalValue
::DLLExportLinkage
; }
1220 : /*empty*/ { $$
= GlobalValue
::ExternalLinkage
; }
1221 | WEAK
{ $$
= GlobalValue
::WeakLinkage
; }
1222 | INTERNAL
{ $$
= GlobalValue
::InternalLinkage
; }
1225 OptCallingConv
: /*empty*/ { $$
= CallingConv
::C
; } |
1226 CCC_TOK
{ $$
= CallingConv
::C
; } |
1227 FASTCC_TOK
{ $$
= CallingConv
::Fast
; } |
1228 COLDCC_TOK
{ $$
= CallingConv
::Cold
; } |
1229 X86_STDCALLCC_TOK
{ $$
= CallingConv
::X86_StdCall
; } |
1230 X86_FASTCALLCC_TOK
{ $$
= CallingConv
::X86_FastCall
; } |
1232 if
((unsigned)$2 != $2)
1233 GEN_ERROR
("Calling conv too large");
1238 ParamAttr
: ZEROEXT
{ $$
= ParamAttr
::ZExt
; }
1239 | ZEXT
{ $$
= ParamAttr
::ZExt
; }
1240 | SIGNEXT
{ $$
= ParamAttr
::SExt
; }
1241 | SEXT
{ $$
= ParamAttr
::SExt
; }
1242 | INREG
{ $$
= ParamAttr
::InReg
; }
1243 | SRET
{ $$
= ParamAttr
::StructRet
; }
1244 | NOALIAS
{ $$
= ParamAttr
::NoAlias
; }
1245 | BYVAL
{ $$
= ParamAttr
::ByVal
; }
1246 | NEST
{ $$
= ParamAttr
::Nest
; }
1249 OptParamAttrs
: /* empty */ { $$
= ParamAttr
::None
; }
1250 | OptParamAttrs ParamAttr
{
1255 FuncAttr
: NORETURN
{ $$
= ParamAttr
::NoReturn
; }
1256 | NOUNWIND
{ $$
= ParamAttr
::NoUnwind
; }
1257 | ZEROEXT
{ $$
= ParamAttr
::ZExt
; }
1258 | SIGNEXT
{ $$
= ParamAttr
::SExt
; }
1261 OptFuncAttrs
: /* empty */ { $$
= ParamAttr
::None
; }
1262 | OptFuncAttrs FuncAttr
{
1267 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1268 // a comma before it.
1269 OptAlign
: /*empty*/ { $$
= 0; } |
1272 if
($$
!= 0 && !isPowerOf2_32
($$
))
1273 GEN_ERROR
("Alignment must be a power of two");
1276 OptCAlign
: /*empty*/ { $$
= 0; } |
1277 ',' ALIGN EUINT64VAL
{
1279 if
($$
!= 0 && !isPowerOf2_32
($$
))
1280 GEN_ERROR
("Alignment must be a power of two");
1285 SectionString
: SECTION STRINGCONSTANT
{
1286 for
(unsigned i
= 0, e
= $2->length
(); i
!= e
; ++i
)
1287 if
((*$2)[i
] == '"' ||
(*$2)[i
] == '\\')
1288 GEN_ERROR
("Invalid character in section name");
1293 OptSection
: /*empty*/ { $$
= 0; } |
1294 SectionString
{ $$
= $1; };
1296 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1297 // is set to be the global we are processing.
1299 GlobalVarAttributes
: /* empty */ {} |
1300 ',' GlobalVarAttribute GlobalVarAttributes
{};
1301 GlobalVarAttribute
: SectionString
{
1302 CurGV
->setSection
(*$1);
1306 | ALIGN EUINT64VAL
{
1307 if
($2 != 0 && !isPowerOf2_32
($2))
1308 GEN_ERROR
("Alignment must be a power of two");
1309 CurGV
->setAlignment
($2);
1313 //===----------------------------------------------------------------------===//
1314 // Types includes all predefined types... except void, because it can only be
1315 // used in specific contexts (function returning void for example).
1317 // Derived types are added later...
1319 PrimType
: INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL
;
1323 $$
= new PATypeHolder
(OpaqueType
::get
());
1327 $$
= new PATypeHolder
($1);
1330 | Types
'*' { // Pointer type?
1331 if
(*$1 == Type
::LabelTy
)
1332 GEN_ERROR
("Cannot form a pointer to a basic block");
1333 $$
= new PATypeHolder
(HandleUpRefs
(PointerType
::get
(*$1)));
1337 | SymbolicValueRef
{ // Named types are also simple types...
1338 const Type
* tmp
= getTypeVal
($1);
1340 $$
= new PATypeHolder
(tmp
);
1342 |
'\\' EUINT64VAL
{ // Type UpReference
1343 if
($2 > (uint64_t)~
0U) GEN_ERROR
("Value out of range");
1344 OpaqueType
*OT
= OpaqueType
::get
(); // Use temporary placeholder
1345 UpRefs.push_back
(UpRefRecord
((unsigned)$2, OT
)); // Add to vector...
1346 $$
= new PATypeHolder
(OT
);
1347 UR_OUT
("New Upreference!\n");
1350 | Types
'(' ArgTypeListI
')' OptFuncAttrs
{
1351 std
::vector
<const Type
*> Params
;
1352 ParamAttrsVector Attrs
;
1353 if
($5 != ParamAttr
::None
) {
1354 ParamAttrsWithIndex X
; X.index
= 0; X.attrs
= $5;
1358 TypeWithAttrsList
::iterator I
= $3->begin
(), E
= $3->end
();
1359 for
(; I
!= E
; ++I
, ++index
) {
1360 const Type
*Ty
= I
->Ty
->get
();
1361 Params.push_back
(Ty
);
1362 if
(Ty
!= Type
::VoidTy
)
1363 if
(I
->Attrs
!= ParamAttr
::None
) {
1364 ParamAttrsWithIndex X
; X.index
= index
; X.attrs
= I
->Attrs
;
1368 bool isVarArg
= Params.size
() && Params.back
() == Type
::VoidTy
;
1369 if
(isVarArg
) Params.pop_back
();
1371 ParamAttrsList
*ActualAttrs
= 0;
1373 ActualAttrs
= ParamAttrsList
::get
(Attrs
);
1374 FunctionType
*FT
= FunctionType
::get
(*$1, Params
, isVarArg
, ActualAttrs
);
1375 delete
$3; // Delete the argument list
1376 delete
$1; // Delete the return type handle
1377 $$
= new PATypeHolder
(HandleUpRefs
(FT
));
1380 | VOID
'(' ArgTypeListI
')' OptFuncAttrs
{
1381 std
::vector
<const Type
*> Params
;
1382 ParamAttrsVector Attrs
;
1383 if
($5 != ParamAttr
::None
) {
1384 ParamAttrsWithIndex X
; X.index
= 0; X.attrs
= $5;
1387 TypeWithAttrsList
::iterator I
= $3->begin
(), E
= $3->end
();
1389 for
( ; I
!= E
; ++I
, ++index
) {
1390 const Type
* Ty
= I
->Ty
->get
();
1391 Params.push_back
(Ty
);
1392 if
(Ty
!= Type
::VoidTy
)
1393 if
(I
->Attrs
!= ParamAttr
::None
) {
1394 ParamAttrsWithIndex X
; X.index
= index
; X.attrs
= I
->Attrs
;
1398 bool isVarArg
= Params.size
() && Params.back
() == Type
::VoidTy
;
1399 if
(isVarArg
) Params.pop_back
();
1401 ParamAttrsList
*ActualAttrs
= 0;
1403 ActualAttrs
= ParamAttrsList
::get
(Attrs
);
1405 FunctionType
*FT
= FunctionType
::get
($1, Params
, isVarArg
, ActualAttrs
);
1406 delete
$3; // Delete the argument list
1407 $$
= new PATypeHolder
(HandleUpRefs
(FT
));
1411 |
'[' EUINT64VAL
'x' Types
']' { // Sized array type?
1412 $$
= new PATypeHolder
(HandleUpRefs
(ArrayType
::get
(*$4, (unsigned)$2)));
1416 |
'<' EUINT64VAL
'x' Types
'>' { // Vector type?
1417 const llvm
::Type
* ElemTy
= $4->get
();
1418 if
((unsigned)$2 != $2)
1419 GEN_ERROR
("Unsigned result not equal to signed result");
1420 if
(!ElemTy
->isFloatingPoint
() && !ElemTy
->isInteger
())
1421 GEN_ERROR
("Element type of a VectorType must be primitive");
1422 if
(!isPowerOf2_32
($2))
1423 GEN_ERROR
("Vector length should be a power of 2");
1424 $$
= new PATypeHolder
(HandleUpRefs
(VectorType
::get
(*$4, (unsigned)$2)));
1428 |
'{' TypeListI
'}' { // Structure type?
1429 std
::vector
<const Type
*> Elements
;
1430 for
(std
::list
<llvm
::PATypeHolder
>::iterator I
= $2->begin
(),
1431 E
= $2->end
(); I
!= E
; ++I
)
1432 Elements.push_back
(*I
);
1434 $$
= new PATypeHolder
(HandleUpRefs
(StructType
::get
(Elements
)));
1438 |
'{' '}' { // Empty structure type?
1439 $$
= new PATypeHolder
(StructType
::get
(std
::vector
<const Type
*>()));
1442 |
'<' '{' TypeListI
'}' '>' {
1443 std
::vector
<const Type
*> Elements
;
1444 for
(std
::list
<llvm
::PATypeHolder
>::iterator I
= $3->begin
(),
1445 E
= $3->end
(); I
!= E
; ++I
)
1446 Elements.push_back
(*I
);
1448 $$
= new PATypeHolder
(HandleUpRefs
(StructType
::get
(Elements
, true
)));
1452 |
'<' '{' '}' '>' { // Empty structure type?
1453 $$
= new PATypeHolder
(StructType
::get
(std
::vector
<const Type
*>(), true
));
1459 : Types OptParamAttrs
{
1467 if
(!UpRefs.empty
())
1468 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1469 if
(!(*$1)->isFirstClassType
())
1470 GEN_ERROR
("LLVM functions cannot return aggregate types");
1474 $$
= new PATypeHolder
(Type
::VoidTy
);
1478 ArgTypeList
: ArgType
{
1479 $$
= new TypeWithAttrsList
();
1483 | ArgTypeList
',' ArgType
{
1484 ($$
=$1)->push_back
($3);
1491 | ArgTypeList
',' DOTDOTDOT
{
1493 TypeWithAttrs TWA
; TWA.Attrs
= ParamAttr
::None
;
1494 TWA.Ty
= new PATypeHolder
(Type
::VoidTy
);
1499 $$
= new TypeWithAttrsList
;
1500 TypeWithAttrs TWA
; TWA.Attrs
= ParamAttr
::None
;
1501 TWA.Ty
= new PATypeHolder
(Type
::VoidTy
);
1506 $$
= new TypeWithAttrsList
();
1510 // TypeList - Used for struct declarations and as a basis for function type
1511 // declaration type lists
1514 $$
= new std
::list
<PATypeHolder
>();
1519 | TypeListI
',' Types
{
1520 ($$
=$1)->push_back
(*$3);
1525 // ConstVal - The various declarations that go into the constant pool. This
1526 // production is used ONLY to represent constants that show up AFTER a 'const',
1527 // 'constant' or 'global' token at global scope. Constants that can be inlined
1528 // into other expressions (such as integers and constexprs) are handled by the
1529 // ResolvedVal, ValueRef and ConstValueRef productions.
1531 ConstVal: Types
'[' ConstVector
']' { // Nonempty unsized arr
1532 if
(!UpRefs.empty
())
1533 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1534 const ArrayType
*ATy
= dyn_cast
<ArrayType
>($1->get
());
1536 GEN_ERROR
("Cannot make array constant with type: '" +
1537 (*$1)->getDescription
() + "'");
1538 const Type
*ETy
= ATy
->getElementType
();
1539 int NumElements
= ATy
->getNumElements
();
1541 // Verify that we have the correct size...
1542 if
(NumElements
!= -1 && NumElements
!= (int)$3->size
())
1543 GEN_ERROR
("Type mismatch: constant sized array initialized with " +
1544 utostr
($3->size
()) + " arguments, but has size of " +
1545 itostr
(NumElements
) + "");
1547 // Verify all elements are correct type!
1548 for
(unsigned i
= 0; i
< $3->size
(); i
++) {
1549 if
(ETy
!= (*$3)[i
]->getType
())
1550 GEN_ERROR
("Element #" + utostr
(i
) + " is not of type '" +
1551 ETy
->getDescription
() +"' as required!\nIt is of type '"+
1552 (*$3)[i
]->getType
()->getDescription
() + "'.");
1555 $$
= ConstantArray
::get
(ATy
, *$3);
1556 delete
$1; delete
$3;
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 if
(NumElements
!= -1 && NumElements
!= 0)
1569 GEN_ERROR
("Type mismatch: constant sized array initialized with 0"
1570 " arguments, but has size of " + itostr
(NumElements
) +"");
1571 $$
= ConstantArray
::get
(ATy
, std
::vector
<Constant
*>());
1575 | Types
'c' STRINGCONSTANT
{
1576 if
(!UpRefs.empty
())
1577 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1578 const ArrayType
*ATy
= dyn_cast
<ArrayType
>($1->get
());
1580 GEN_ERROR
("Cannot make array constant with type: '" +
1581 (*$1)->getDescription
() + "'");
1583 int NumElements
= ATy
->getNumElements
();
1584 const Type
*ETy
= ATy
->getElementType
();
1585 if
(NumElements
!= -1 && NumElements
!= int($3->length
()))
1586 GEN_ERROR
("Can't build string constant of size " +
1587 itostr
((int)($3->length
())) +
1588 " when array has size " + itostr
(NumElements
) + "");
1589 std
::vector
<Constant
*> Vals
;
1590 if
(ETy
== Type
::Int8Ty
) {
1591 for
(unsigned i
= 0; i
< $3->length
(); ++i
)
1592 Vals.push_back
(ConstantInt
::get
(ETy
, (*$3)[i
]));
1595 GEN_ERROR
("Cannot build string arrays of non byte sized elements");
1598 $$
= ConstantArray
::get
(ATy
, Vals
);
1602 | Types
'<' ConstVector
'>' { // Nonempty unsized arr
1603 if
(!UpRefs.empty
())
1604 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1605 const VectorType
*PTy
= dyn_cast
<VectorType
>($1->get
());
1607 GEN_ERROR
("Cannot make packed constant with type: '" +
1608 (*$1)->getDescription
() + "'");
1609 const Type
*ETy
= PTy
->getElementType
();
1610 int NumElements
= PTy
->getNumElements
();
1612 // Verify that we have the correct size...
1613 if
(NumElements
!= -1 && NumElements
!= (int)$3->size
())
1614 GEN_ERROR
("Type mismatch: constant sized packed initialized with " +
1615 utostr
($3->size
()) + " arguments, but has size of " +
1616 itostr
(NumElements
) + "");
1618 // Verify all elements are correct type!
1619 for
(unsigned i
= 0; i
< $3->size
(); i
++) {
1620 if
(ETy
!= (*$3)[i
]->getType
())
1621 GEN_ERROR
("Element #" + utostr
(i
) + " is not of type '" +
1622 ETy
->getDescription
() +"' as required!\nIt is of type '"+
1623 (*$3)[i
]->getType
()->getDescription
() + "'.");
1626 $$
= ConstantVector
::get
(PTy
, *$3);
1627 delete
$1; delete
$3;
1630 | Types
'{' ConstVector
'}' {
1631 const StructType
*STy
= dyn_cast
<StructType
>($1->get
());
1633 GEN_ERROR
("Cannot make struct constant with type: '" +
1634 (*$1)->getDescription
() + "'");
1636 if
($3->size
() != STy
->getNumContainedTypes
())
1637 GEN_ERROR
("Illegal number of initializers for structure type");
1639 // Check to ensure that constants are compatible with the type initializer!
1640 for
(unsigned i
= 0, e
= $3->size
(); i
!= e
; ++i
)
1641 if
((*$3)[i
]->getType
() != STy
->getElementType
(i
))
1642 GEN_ERROR
("Expected type '" +
1643 STy
->getElementType
(i
)->getDescription
() +
1644 "' for element #" + utostr
(i
) +
1645 " of structure initializer");
1647 // Check to ensure that Type is not packed
1648 if
(STy
->isPacked
())
1649 GEN_ERROR
("Unpacked Initializer to vector type '" +
1650 STy
->getDescription
() + "'");
1652 $$
= ConstantStruct
::get
(STy
, *$3);
1653 delete
$1; delete
$3;
1657 if
(!UpRefs.empty
())
1658 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1659 const StructType
*STy
= dyn_cast
<StructType
>($1->get
());
1661 GEN_ERROR
("Cannot make struct constant with type: '" +
1662 (*$1)->getDescription
() + "'");
1664 if
(STy
->getNumContainedTypes
() != 0)
1665 GEN_ERROR
("Illegal number of initializers for structure type");
1667 // Check to ensure that Type is not packed
1668 if
(STy
->isPacked
())
1669 GEN_ERROR
("Unpacked Initializer to vector type '" +
1670 STy
->getDescription
() + "'");
1672 $$
= ConstantStruct
::get
(STy
, std
::vector
<Constant
*>());
1676 | Types
'<' '{' ConstVector
'}' '>' {
1677 const StructType
*STy
= dyn_cast
<StructType
>($1->get
());
1679 GEN_ERROR
("Cannot make struct constant with type: '" +
1680 (*$1)->getDescription
() + "'");
1682 if
($4->size
() != STy
->getNumContainedTypes
())
1683 GEN_ERROR
("Illegal number of initializers for structure type");
1685 // Check to ensure that constants are compatible with the type initializer!
1686 for
(unsigned i
= 0, e
= $4->size
(); i
!= e
; ++i
)
1687 if
((*$4)[i
]->getType
() != STy
->getElementType
(i
))
1688 GEN_ERROR
("Expected type '" +
1689 STy
->getElementType
(i
)->getDescription
() +
1690 "' for element #" + utostr
(i
) +
1691 " of structure initializer");
1693 // Check to ensure that Type is packed
1694 if
(!STy
->isPacked
())
1695 GEN_ERROR
("Vector initializer to non-vector type '" +
1696 STy
->getDescription
() + "'");
1698 $$
= ConstantStruct
::get
(STy
, *$4);
1699 delete
$1; delete
$4;
1702 | Types
'<' '{' '}' '>' {
1703 if
(!UpRefs.empty
())
1704 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1705 const StructType
*STy
= dyn_cast
<StructType
>($1->get
());
1707 GEN_ERROR
("Cannot make struct constant with type: '" +
1708 (*$1)->getDescription
() + "'");
1710 if
(STy
->getNumContainedTypes
() != 0)
1711 GEN_ERROR
("Illegal number of initializers for structure type");
1713 // Check to ensure that Type is packed
1714 if
(!STy
->isPacked
())
1715 GEN_ERROR
("Vector initializer to non-vector type '" +
1716 STy
->getDescription
() + "'");
1718 $$
= ConstantStruct
::get
(STy
, std
::vector
<Constant
*>());
1723 if
(!UpRefs.empty
())
1724 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1725 const PointerType
*PTy
= dyn_cast
<PointerType
>($1->get
());
1727 GEN_ERROR
("Cannot make null pointer constant with type: '" +
1728 (*$1)->getDescription
() + "'");
1730 $$
= ConstantPointerNull
::get
(PTy
);
1735 if
(!UpRefs.empty
())
1736 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1737 $$
= UndefValue
::get
($1->get
());
1741 | Types SymbolicValueRef
{
1742 if
(!UpRefs.empty
())
1743 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1744 const PointerType
*Ty
= dyn_cast
<PointerType
>($1->get
());
1746 GEN_ERROR
("Global const reference must be a pointer type");
1748 // ConstExprs can exist in the body of a function, thus creating
1749 // GlobalValues whenever they refer to a variable. Because we are in
1750 // the context of a function, getExistingVal will search the functions
1751 // symbol table instead of the module symbol table for the global symbol,
1752 // which throws things all off. To get around this, we just tell
1753 // getExistingVal that we are at global scope here.
1755 Function
*SavedCurFn
= CurFun.CurrentFunction
;
1756 CurFun.CurrentFunction
= 0;
1758 Value
*V
= getExistingVal
(Ty
, $2);
1761 CurFun.CurrentFunction
= SavedCurFn
;
1763 // If this is an initializer for a constant pointer, which is referencing a
1764 // (currently) undefined variable, create a stub now that shall be replaced
1765 // in the future with the right type of variable.
1768 assert
(isa
<PointerType
>(Ty
) && "Globals may only be used as pointers!");
1769 const PointerType
*PT
= cast
<PointerType
>(Ty
);
1771 // First check to see if the forward references value is already created!
1772 PerModuleInfo
::GlobalRefsType
::iterator I
=
1773 CurModule.GlobalRefs.find
(std
::make_pair
(PT
, $2));
1775 if
(I
!= CurModule.GlobalRefs.end
()) {
1776 V
= I
->second
; // Placeholder already exists, use it...
1780 if
($2.Type
== ValID
::GlobalName
)
1781 Name
= $2.getName
();
1782 else if
($2.Type
!= ValID
::GlobalID
)
1783 GEN_ERROR
("Invalid reference to global");
1785 // Create the forward referenced global.
1787 if
(const FunctionType
*FTy
=
1788 dyn_cast
<FunctionType
>(PT
->getElementType
())) {
1789 GV
= new Function
(FTy
, GlobalValue
::ExternalWeakLinkage
, Name
,
1790 CurModule.CurrentModule
);
1792 GV
= new GlobalVariable
(PT
->getElementType
(), false
,
1793 GlobalValue
::ExternalWeakLinkage
, 0,
1794 Name
, CurModule.CurrentModule
);
1797 // Keep track of the fact that we have a forward ref to recycle it
1798 CurModule.GlobalRefs.insert
(std
::make_pair
(std
::make_pair
(PT
, $2), GV
));
1803 $$
= cast
<GlobalValue
>(V
);
1804 delete
$1; // Free the type handle
1808 if
(!UpRefs.empty
())
1809 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1810 if
($1->get
() != $2->getType
())
1811 GEN_ERROR
("Mismatched types for constant expression: " +
1812 (*$1)->getDescription
() + " and " + $2->getType
()->getDescription
());
1817 | Types ZEROINITIALIZER
{
1818 if
(!UpRefs.empty
())
1819 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
1820 const Type
*Ty
= $1->get
();
1821 if
(isa
<FunctionType
>(Ty
) || Ty
== Type
::LabelTy || isa
<OpaqueType
>(Ty
))
1822 GEN_ERROR
("Cannot create a null initialized value of this type");
1823 $$
= Constant
::getNullValue
(Ty
);
1827 | IntType ESINT64VAL
{ // integral constants
1828 if
(!ConstantInt
::isValueValidForType
($1, $2))
1829 GEN_ERROR
("Constant value doesn't fit in type");
1830 $$
= ConstantInt
::get
($1, $2, true
);
1833 | IntType ESAPINTVAL
{ // 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->sextOrTrunc
(BitWidth
);
1839 $$
= ConstantInt
::get
(*$2);
1843 | IntType EUINT64VAL
{ // integral constants
1844 if
(!ConstantInt
::isValueValidForType
($1, $2))
1845 GEN_ERROR
("Constant value doesn't fit in type");
1846 $$
= ConstantInt
::get
($1, $2, false
);
1849 | IntType EUAPINTVAL
{ // arbitrary precision integer constants
1850 uint32_t BitWidth
= cast
<IntegerType
>($1)->getBitWidth
();
1851 if
($2->getBitWidth
() > BitWidth
) {
1852 GEN_ERROR
("Constant value does not fit in type");
1854 $2->zextOrTrunc
(BitWidth
);
1855 $$
= ConstantInt
::get
(*$2);
1859 | INTTYPE TRUETOK
{ // Boolean constants
1860 assert
(cast
<IntegerType
>($1)->getBitWidth
() == 1 && "Not Bool?");
1861 $$
= ConstantInt
::getTrue
();
1864 | INTTYPE FALSETOK
{ // Boolean constants
1865 assert
(cast
<IntegerType
>($1)->getBitWidth
() == 1 && "Not Bool?");
1866 $$
= ConstantInt
::getFalse
();
1869 | FPType FPVAL
{ // Floating point constants
1870 if
(!ConstantFP
::isValueValidForType
($1, *$2))
1871 GEN_ERROR
("Floating point constant invalid for type");
1872 // Lexer has no type info, so builds all float and double FP constants
1873 // as double. Fix this here. Long double is done right.
1874 if
(&$2->getSemantics
()==&APFloat
::IEEEdouble
&& $1==Type
::FloatTy
)
1875 $2->convert
(APFloat
::IEEEsingle
, APFloat
::rmNearestTiesToEven
);
1876 $$
= ConstantFP
::get
($1, *$2);
1882 ConstExpr: CastOps
'(' ConstVal TO Types
')' {
1883 if
(!UpRefs.empty
())
1884 GEN_ERROR
("Invalid upreference in type: " + (*$5)->getDescription
());
1886 const Type
*DestTy
= $5->get
();
1887 if
(!CastInst
::castIsValid
($1, $3, DestTy
))
1888 GEN_ERROR
("invalid cast opcode for cast from '" +
1889 Val
->getType
()->getDescription
() + "' to '" +
1890 DestTy
->getDescription
() + "'");
1891 $$
= ConstantExpr
::getCast
($1, $3, DestTy
);
1894 | GETELEMENTPTR
'(' ConstVal IndexList
')' {
1895 if
(!isa
<PointerType
>($3->getType
()))
1896 GEN_ERROR
("GetElementPtr requires a pointer operand");
1899 GetElementPtrInst
::getIndexedType
($3->getType
(), $4->begin
(), $4->end
(),
1902 GEN_ERROR
("Index list invalid for constant getelementptr");
1904 SmallVector
<Constant
*, 8> IdxVec
;
1905 for
(unsigned i
= 0, e
= $4->size
(); i
!= e
; ++i
)
1906 if
(Constant
*C
= dyn_cast
<Constant
>((*$4)[i
]))
1907 IdxVec.push_back
(C
);
1909 GEN_ERROR
("Indices to constant getelementptr must be constants");
1913 $$
= ConstantExpr
::getGetElementPtr
($3, &IdxVec
[0], IdxVec.size
());
1916 | SELECT
'(' ConstVal
',' ConstVal
',' ConstVal
')' {
1917 if
($3->getType
() != Type
::Int1Ty
)
1918 GEN_ERROR
("Select condition must be of boolean type");
1919 if
($5->getType
() != $7->getType
())
1920 GEN_ERROR
("Select operand types must match");
1921 $$
= ConstantExpr
::getSelect
($3, $5, $7);
1924 | ArithmeticOps
'(' ConstVal
',' ConstVal
')' {
1925 if
($3->getType
() != $5->getType
())
1926 GEN_ERROR
("Binary operator types must match");
1928 $$
= ConstantExpr
::get
($1, $3, $5);
1930 | LogicalOps
'(' ConstVal
',' ConstVal
')' {
1931 if
($3->getType
() != $5->getType
())
1932 GEN_ERROR
("Logical operator types must match");
1933 if
(!$3->getType
()->isInteger
()) {
1934 if
(Instruction
::isShift
($1) ||
!isa
<VectorType
>($3->getType
()) ||
1935 !cast
<VectorType
>($3->getType
())->getElementType
()->isInteger
())
1936 GEN_ERROR
("Logical operator requires integral operands");
1938 $$
= ConstantExpr
::get
($1, $3, $5);
1941 | ICMP IPredicates
'(' ConstVal
',' ConstVal
')' {
1942 if
($4->getType
() != $6->getType
())
1943 GEN_ERROR
("icmp operand types must match");
1944 $$
= ConstantExpr
::getICmp
($2, $4, $6);
1946 | FCMP FPredicates
'(' ConstVal
',' ConstVal
')' {
1947 if
($4->getType
() != $6->getType
())
1948 GEN_ERROR
("fcmp operand types must match");
1949 $$
= ConstantExpr
::getFCmp
($2, $4, $6);
1951 | EXTRACTELEMENT
'(' ConstVal
',' ConstVal
')' {
1952 if
(!ExtractElementInst
::isValidOperands
($3, $5))
1953 GEN_ERROR
("Invalid extractelement operands");
1954 $$
= ConstantExpr
::getExtractElement
($3, $5);
1957 | INSERTELEMENT
'(' ConstVal
',' ConstVal
',' ConstVal
')' {
1958 if
(!InsertElementInst
::isValidOperands
($3, $5, $7))
1959 GEN_ERROR
("Invalid insertelement operands");
1960 $$
= ConstantExpr
::getInsertElement
($3, $5, $7);
1963 | SHUFFLEVECTOR
'(' ConstVal
',' ConstVal
',' ConstVal
')' {
1964 if
(!ShuffleVectorInst
::isValidOperands
($3, $5, $7))
1965 GEN_ERROR
("Invalid shufflevector operands");
1966 $$
= ConstantExpr
::getShuffleVector
($3, $5, $7);
1971 // ConstVector - A list of comma separated constants.
1972 ConstVector
: ConstVector
',' ConstVal
{
1973 ($$
= $1)->push_back
($3);
1977 $$
= new std
::vector
<Constant
*>();
1983 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1984 GlobalType
: GLOBAL
{ $$
= false
; } | CONSTANT
{ $$
= true
; };
1987 ThreadLocal
: THREAD_LOCAL
{ $$
= true
; } |
{ $$
= false
; };
1989 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1990 AliaseeRef
: ResultTypes SymbolicValueRef
{
1991 const Type
* VTy
= $1->get
();
1992 Value
*V
= getVal
(VTy
, $2);
1994 GlobalValue
* Aliasee
= dyn_cast
<GlobalValue
>(V
);
1996 GEN_ERROR
("Aliases can be created only to global values");
2002 | BITCAST
'(' AliaseeRef TO Types
')' {
2004 const Type
*DestTy
= $5->get
();
2005 if
(!CastInst
::castIsValid
($1, $3, DestTy
))
2006 GEN_ERROR
("invalid cast opcode for cast from '" +
2007 Val
->getType
()->getDescription
() + "' to '" +
2008 DestTy
->getDescription
() + "'");
2010 $$
= ConstantExpr
::getCast
($1, $3, DestTy
);
2015 //===----------------------------------------------------------------------===//
2016 // Rules to match Modules
2017 //===----------------------------------------------------------------------===//
2019 // Module rule: Capture the result of parsing the whole file into a result
2024 $$
= ParserResult
= CurModule.CurrentModule
;
2025 CurModule.ModuleDone
();
2029 $$
= ParserResult
= CurModule.CurrentModule
;
2030 CurModule.ModuleDone
();
2037 | DefinitionList Definition
2041 : DEFINE
{ CurFun.isDeclare
= false
; } Function
{
2042 CurFun.FunctionDone
();
2045 | DECLARE
{ CurFun.isDeclare
= true
; } FunctionProto
{
2048 | MODULE ASM_TOK AsmBlock
{
2051 | OptLocalAssign TYPE Types
{
2052 if
(!UpRefs.empty
())
2053 GEN_ERROR
("Invalid upreference in type: " + (*$3)->getDescription
());
2054 // Eagerly resolve types. This is not an optimization, this is a
2055 // requirement that is due to the fact that we could have this:
2057 // %list = type { %list * }
2058 // %list = type { %list * } ; repeated type decl
2060 // If types are not resolved eagerly, then the two types will not be
2061 // determined to be the same type!
2063 ResolveTypeTo
($1, *$3);
2065 if
(!setTypeName
(*$3, $1) && !$1) {
2067 // If this is a named type that is not a redefinition, add it to the slot
2069 CurModule.Types.push_back
(*$3);
2075 | OptLocalAssign TYPE VOID
{
2076 ResolveTypeTo
($1, $3);
2078 if
(!setTypeName
($3, $1) && !$1) {
2080 // If this is a named type that is not a redefinition, add it to the slot
2082 CurModule.Types.push_back
($3);
2086 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
{
2087 /* "Externally Visible" Linkage */
2089 GEN_ERROR
("Global value initializer is not a constant");
2090 CurGV
= ParseGlobalVariable
($1, GlobalValue
::ExternalLinkage
,
2091 $2, $4, $5->getType
(), $5, $3);
2093 } GlobalVarAttributes
{
2096 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2099 GEN_ERROR
("Global value initializer is not a constant");
2100 CurGV
= ParseGlobalVariable
($1, $2, $3, $5, $6->getType
(), $6, $4);
2102 } GlobalVarAttributes
{
2105 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2107 if
(!UpRefs.empty
())
2108 GEN_ERROR
("Invalid upreference in type: " + (*$6)->getDescription
());
2109 CurGV
= ParseGlobalVariable
($1, $2, $3, $5, *$6, 0, $4);
2112 } GlobalVarAttributes
{
2116 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef
{
2123 GEN_ERROR
("Alias name cannot be empty");
2125 Constant
* Aliasee
= $5;
2127 GEN_ERROR
(std
::string("Invalid aliasee for alias: ") + Name
);
2129 GlobalAlias
* GA
= new GlobalAlias
(Aliasee
->getType
(), $4, Name
, Aliasee
,
2130 CurModule.CurrentModule
);
2131 GA
->setVisibility
($2);
2132 InsertValue
(GA
, CurModule.Values
);
2135 // If there was a forward reference of this alias, resolve it now.
2139 ID
= ValID
::createGlobalName
(Name
);
2141 ID
= ValID
::createGlobalID
(CurModule.Values.size
()-1);
2143 if
(GlobalValue
*FWGV
=
2144 CurModule.GetForwardRefForGlobal
(GA
->getType
(), ID
)) {
2145 // Replace uses of the fwdref with the actual alias.
2146 FWGV
->replaceAllUsesWith
(GA
);
2147 if
(GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(FWGV
))
2148 GV
->eraseFromParent
();
2150 cast
<Function
>(FWGV
)->eraseFromParent
();
2156 | TARGET TargetDefinition
{
2159 | DEPLIBS
'=' LibrariesDefinition
{
2165 AsmBlock
: STRINGCONSTANT
{
2166 const std
::string &AsmSoFar
= CurModule.CurrentModule
->getModuleInlineAsm
();
2167 if
(AsmSoFar.empty
())
2168 CurModule.CurrentModule
->setModuleInlineAsm
(*$1);
2170 CurModule.CurrentModule
->setModuleInlineAsm
(AsmSoFar
+"\n"+*$1);
2175 TargetDefinition
: TRIPLE
'=' STRINGCONSTANT
{
2176 CurModule.CurrentModule
->setTargetTriple
(*$3);
2179 | DATALAYOUT
'=' STRINGCONSTANT
{
2180 CurModule.CurrentModule
->setDataLayout
(*$3);
2184 LibrariesDefinition
: '[' LibList
']';
2186 LibList
: LibList
',' STRINGCONSTANT
{
2187 CurModule.CurrentModule
->addLibrary
(*$3);
2192 CurModule.CurrentModule
->addLibrary
(*$1);
2196 |
/* empty: end of list */ {
2201 //===----------------------------------------------------------------------===//
2202 // Rules to match Function Headers
2203 //===----------------------------------------------------------------------===//
2205 ArgListH
: ArgListH
',' Types OptParamAttrs OptLocalName
{
2206 if
(!UpRefs.empty
())
2207 GEN_ERROR
("Invalid upreference in type: " + (*$3)->getDescription
());
2208 if
(*$3 == Type
::VoidTy
)
2209 GEN_ERROR
("void typed arguments are invalid");
2210 ArgListEntry E
; E.Attrs
= $4; E.Ty
= $3; E.Name
= $5;
2215 | Types OptParamAttrs OptLocalName
{
2216 if
(!UpRefs.empty
())
2217 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
2218 if
(*$1 == Type
::VoidTy
)
2219 GEN_ERROR
("void typed arguments are invalid");
2220 ArgListEntry E
; E.Attrs
= $2; E.Ty
= $1; E.Name
= $3;
2221 $$
= new ArgListType
;
2226 ArgList
: ArgListH
{
2230 | ArgListH
',' DOTDOTDOT
{
2232 struct ArgListEntry E
;
2233 E.Ty
= new PATypeHolder
(Type
::VoidTy
);
2235 E.Attrs
= ParamAttr
::None
;
2240 $$
= new ArgListType
;
2241 struct ArgListEntry E
;
2242 E.Ty
= new PATypeHolder
(Type
::VoidTy
);
2244 E.Attrs
= ParamAttr
::None
;
2253 FunctionHeaderH
: OptCallingConv ResultTypes GlobalName
'(' ArgList
')'
2254 OptFuncAttrs OptSection OptAlign
{
2255 std
::string FunctionName
(*$3);
2256 delete
$3; // Free strdup'd memory!
2258 // Check the function result for abstractness if this is a define. We should
2259 // have no abstract types at this point
2260 if
(!CurFun.isDeclare
&& CurModule.TypeIsUnresolved
($2))
2261 GEN_ERROR
("Reference to abstract result: "+ $2->get
()->getDescription
());
2263 std
::vector
<const Type
*> ParamTypeList
;
2264 ParamAttrsVector Attrs
;
2265 if
($7 != ParamAttr
::None
) {
2266 ParamAttrsWithIndex PAWI
; PAWI.index
= 0; PAWI.attrs
= $7;
2267 Attrs.push_back
(PAWI
);
2269 if
($5) { // If there are arguments...
2271 for
(ArgListType
::iterator I
= $5->begin
(); I
!= $5->end
(); ++I
, ++index
) {
2272 const Type
* Ty
= I
->Ty
->get
();
2273 if
(!CurFun.isDeclare
&& CurModule.TypeIsUnresolved
(I
->Ty
))
2274 GEN_ERROR
("Reference to abstract argument: " + Ty
->getDescription
());
2275 ParamTypeList.push_back
(Ty
);
2276 if
(Ty
!= Type
::VoidTy
)
2277 if
(I
->Attrs
!= ParamAttr
::None
) {
2278 ParamAttrsWithIndex PAWI
; PAWI.index
= index
; PAWI.attrs
= I
->Attrs
;
2279 Attrs.push_back
(PAWI
);
2284 bool isVarArg
= ParamTypeList.size
() && ParamTypeList.back
() == Type
::VoidTy
;
2285 if
(isVarArg
) ParamTypeList.pop_back
();
2287 ParamAttrsList
*PAL
= 0;
2289 PAL
= ParamAttrsList
::get
(Attrs
);
2291 FunctionType
*FT
= FunctionType
::get
(*$2, ParamTypeList
, isVarArg
, PAL
);
2292 const PointerType
*PFT
= PointerType
::get
(FT
);
2296 if
(!FunctionName.empty
()) {
2297 ID
= ValID
::createGlobalName
((char*)FunctionName.c_str
());
2299 ID
= ValID
::createGlobalID
(CurModule.Values.size
());
2303 // See if this function was forward referenced. If so, recycle the object.
2304 if
(GlobalValue
*FWRef
= CurModule.GetForwardRefForGlobal
(PFT
, ID
)) {
2305 // Move the function to the end of the list, from whereever it was
2306 // previously inserted.
2307 Fn
= cast
<Function
>(FWRef
);
2308 CurModule.CurrentModule
->getFunctionList
().remove
(Fn
);
2309 CurModule.CurrentModule
->getFunctionList
().push_back
(Fn
);
2310 } else if
(!FunctionName.empty
() && // Merge with an earlier prototype?
2311 (Fn
= CurModule.CurrentModule
->getFunction
(FunctionName
))) {
2312 if
(Fn
->getFunctionType
() != FT
) {
2313 // The existing function doesn't have the same type. This is an overload
2315 GEN_ERROR
("Overload of function '" + FunctionName
+ "' not permitted.");
2316 } else if
(!CurFun.isDeclare
&& !Fn
->isDeclaration
()) {
2317 // Neither the existing or the current function is a declaration and they
2318 // have the same name and same type. Clearly this is a redefinition.
2319 GEN_ERROR
("Redefinition of function '" + FunctionName
+ "'");
2320 } if
(Fn
->isDeclaration
()) {
2321 // Make sure to strip off any argument names so we can't get conflicts.
2322 for
(Function
::arg_iterator AI
= Fn
->arg_begin
(), AE
= Fn
->arg_end
();
2326 } else
{ // Not already defined?
2327 Fn
= new Function
(FT
, GlobalValue
::ExternalWeakLinkage
, FunctionName
,
2328 CurModule.CurrentModule
);
2330 InsertValue
(Fn
, CurModule.Values
);
2333 CurFun.FunctionStart
(Fn
);
2335 if
(CurFun.isDeclare
) {
2336 // If we have declaration, always overwrite linkage. This will allow us to
2337 // correctly handle cases, when pointer to function is passed as argument to
2338 // another function.
2339 Fn
->setLinkage
(CurFun.Linkage
);
2340 Fn
->setVisibility
(CurFun.Visibility
);
2342 Fn
->setCallingConv
($1);
2343 Fn
->setAlignment
($9);
2345 Fn
->setSection
(*$8);
2349 // Add all of the arguments we parsed to the function...
2350 if
($5) { // Is null if empty...
2351 if
(isVarArg
) { // Nuke the last entry
2352 assert
($5->back
().Ty
->get
() == Type
::VoidTy
&& $5->back
().Name
== 0 &&
2353 "Not a varargs marker!");
2354 delete
$5->back
().Ty
;
2355 $5->pop_back
(); // Delete the last entry
2357 Function
::arg_iterator ArgIt
= Fn
->arg_begin
();
2358 Function
::arg_iterator ArgEnd
= Fn
->arg_end
();
2360 for
(ArgListType
::iterator I
= $5->begin
();
2361 I
!= $5->end
() && ArgIt
!= ArgEnd
; ++I
, ++ArgIt
) {
2362 delete I
->Ty
; // Delete the typeholder...
2363 setValueName
(ArgIt
, I
->Name
); // Insert arg into symtab...
2369 delete
$5; // We're now done with the argument list
2374 BEGIN
: BEGINTOK |
'{'; // Allow BEGIN or '{' to start a function
2376 FunctionHeader
: FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN
{
2377 $$
= CurFun.CurrentFunction
;
2379 // Make sure that we keep track of the linkage type even if there was a
2380 // previous "declare".
2382 $$
->setVisibility
($2);
2385 END
: ENDTOK |
'}'; // Allow end of '}' to end a function
2387 Function
: BasicBlockList END
{
2392 FunctionProto
: FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH
{
2393 CurFun.CurrentFunction
->setLinkage
($1);
2394 CurFun.CurrentFunction
->setVisibility
($2);
2395 $$
= CurFun.CurrentFunction
;
2396 CurFun.FunctionDone
();
2400 //===----------------------------------------------------------------------===//
2401 // Rules to match Basic Blocks
2402 //===----------------------------------------------------------------------===//
2404 OptSideEffect
: /* empty */ {
2413 ConstValueRef
: ESINT64VAL
{ // A reference to a direct constant
2414 $$
= ValID
::create
($1);
2418 $$
= ValID
::create
($1);
2421 | FPVAL
{ // Perhaps it's an FP constant?
2422 $$
= ValID
::create
($1);
2426 $$
= ValID
::create
(ConstantInt
::getTrue
());
2430 $$
= ValID
::create
(ConstantInt
::getFalse
());
2434 $$
= ValID
::createNull
();
2438 $$
= ValID
::createUndef
();
2441 | ZEROINITIALIZER
{ // A vector zero constant.
2442 $$
= ValID
::createZeroInit
();
2445 |
'<' ConstVector
'>' { // Nonempty unsized packed vector
2446 const Type
*ETy
= (*$2)[0]->getType
();
2447 int NumElements
= $2->size
();
2449 VectorType
* pt
= VectorType
::get
(ETy
, NumElements
);
2450 PATypeHolder
* PTy
= new PATypeHolder
(
2458 // Verify all elements are correct type!
2459 for
(unsigned i
= 0; i
< $2->size
(); i
++) {
2460 if
(ETy
!= (*$2)[i
]->getType
())
2461 GEN_ERROR
("Element #" + utostr
(i
) + " is not of type '" +
2462 ETy
->getDescription
() +"' as required!\nIt is of type '" +
2463 (*$2)[i
]->getType
()->getDescription
() + "'.");
2466 $$
= ValID
::create
(ConstantVector
::get
(pt
, *$2));
2467 delete PTy
; delete
$2;
2471 $$
= ValID
::create
($1);
2474 | ASM_TOK OptSideEffect STRINGCONSTANT
',' STRINGCONSTANT
{
2475 $$
= ValID
::createInlineAsm
(*$3, *$5, $2);
2481 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2484 SymbolicValueRef
: LOCALVAL_ID
{ // Is it an integer reference...?
2485 $$
= ValID
::createLocalID
($1);
2489 $$
= ValID
::createGlobalID
($1);
2492 | LocalName
{ // Is it a named reference...?
2493 $$
= ValID
::createLocalName
(*$1);
2497 | GlobalName
{ // Is it a named reference...?
2498 $$
= ValID
::createGlobalName
(*$1);
2503 // ValueRef - A reference to a definition... either constant or symbolic
2504 ValueRef
: SymbolicValueRef | ConstValueRef
;
2507 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2508 // type immediately preceeds the value reference, and allows complex constant
2509 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2510 ResolvedVal
: Types ValueRef
{
2511 if
(!UpRefs.empty
())
2512 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
2513 $$
= getVal
(*$1, $2);
2519 BasicBlockList
: BasicBlockList BasicBlock
{
2523 | FunctionHeader BasicBlock
{ // Do not allow functions with 0 basic blocks
2529 // Basic blocks are terminated by branching instructions:
2530 // br, br/cc, switch, ret
2532 BasicBlock
: InstructionList OptLocalAssign BBTerminatorInst
{
2533 setValueName
($3, $2);
2536 $1->getInstList
().push_back
($3);
2541 InstructionList
: InstructionList Inst
{
2542 if
(CastInst
*CI1
= dyn_cast
<CastInst
>($2))
2543 if
(CastInst
*CI2
= dyn_cast
<CastInst
>(CI1
->getOperand
(0)))
2544 if
(CI2
->getParent
() == 0)
2545 $1->getInstList
().push_back
(CI2
);
2546 $1->getInstList
().push_back
($2);
2550 |
/* empty */ { // Empty space between instruction lists
2551 $$
= defineBBVal
(ValID
::createLocalID
(CurFun.NextValNum
));
2554 | LABELSTR
{ // Labelled (named) basic block
2555 $$
= defineBBVal
(ValID
::createLocalName
(*$1));
2561 BBTerminatorInst
: RET ResolvedVal
{ // Return with a result...
2562 $$
= new ReturnInst
($2);
2565 | RET VOID
{ // Return with no result...
2566 $$
= new ReturnInst
();
2569 | BR LABEL ValueRef
{ // Unconditional Branch...
2570 BasicBlock
* tmpBB
= getBBVal
($3);
2572 $$
= new BranchInst
(tmpBB
);
2573 } // Conditional Branch...
2574 | BR INTTYPE ValueRef
',' LABEL ValueRef
',' LABEL ValueRef
{
2575 assert
(cast
<IntegerType
>($2)->getBitWidth
() == 1 && "Not Bool?");
2576 BasicBlock
* tmpBBA
= getBBVal
($6);
2578 BasicBlock
* tmpBBB
= getBBVal
($9);
2580 Value
* tmpVal
= getVal
(Type
::Int1Ty
, $3);
2582 $$
= new BranchInst
(tmpBBA
, tmpBBB
, tmpVal
);
2584 | SWITCH IntType ValueRef
',' LABEL ValueRef
'[' JumpTable
']' {
2585 Value
* tmpVal
= getVal
($2, $3);
2587 BasicBlock
* tmpBB
= getBBVal
($6);
2589 SwitchInst
*S
= new SwitchInst
(tmpVal
, tmpBB
, $8->size
());
2592 std
::vector
<std
::pair
<Constant
*,BasicBlock
*> >::iterator I
= $8->begin
(),
2594 for
(; I
!= E
; ++I
) {
2595 if
(ConstantInt
*CI
= dyn_cast
<ConstantInt
>(I
->first
))
2596 S
->addCase
(CI
, I
->second
);
2598 GEN_ERROR
("Switch case is constant, but not a simple integer");
2603 | SWITCH IntType ValueRef
',' LABEL ValueRef
'[' ']' {
2604 Value
* tmpVal
= getVal
($2, $3);
2606 BasicBlock
* tmpBB
= getBBVal
($6);
2608 SwitchInst
*S
= new SwitchInst
(tmpVal
, tmpBB
, 0);
2612 | INVOKE OptCallingConv ResultTypes ValueRef
'(' ValueRefList
')' OptFuncAttrs
2613 TO LABEL ValueRef UNWIND LABEL ValueRef
{
2615 // Handle the short syntax
2616 const PointerType
*PFTy
= 0;
2617 const FunctionType
*Ty
= 0;
2618 if
(!(PFTy
= dyn_cast
<PointerType
>($3->get
())) ||
2619 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType
()))) {
2620 // Pull out the types of all of the arguments...
2621 std
::vector
<const Type
*> ParamTypes
;
2622 ParamAttrsVector Attrs
;
2623 if
($8 != ParamAttr
::None
) {
2624 ParamAttrsWithIndex PAWI
; PAWI.index
= 0; PAWI.attrs
= $8;
2625 Attrs.push_back
(PAWI
);
2627 ValueRefList
::iterator I
= $6->begin
(), E
= $6->end
();
2629 for
(; I
!= E
; ++I
, ++index
) {
2630 const Type
*Ty
= I
->Val
->getType
();
2631 if
(Ty
== Type
::VoidTy
)
2632 GEN_ERROR
("Short call syntax cannot be used with varargs");
2633 ParamTypes.push_back
(Ty
);
2634 if
(I
->Attrs
!= ParamAttr
::None
) {
2635 ParamAttrsWithIndex PAWI
; PAWI.index
= index
; PAWI.attrs
= I
->Attrs
;
2636 Attrs.push_back
(PAWI
);
2640 ParamAttrsList
*PAL
= 0;
2642 PAL
= ParamAttrsList
::get
(Attrs
);
2643 Ty
= FunctionType
::get
($3->get
(), ParamTypes
, false
, PAL
);
2644 PFTy
= PointerType
::get
(Ty
);
2649 Value
*V
= getVal
(PFTy
, $4); // Get the function we're calling...
2651 BasicBlock
*Normal
= getBBVal
($11);
2653 BasicBlock
*Except
= getBBVal
($14);
2656 // Check the arguments
2658 if
($6->empty
()) { // Has no arguments?
2659 // Make sure no arguments is a good thing!
2660 if
(Ty
->getNumParams
() != 0)
2661 GEN_ERROR
("No arguments passed to a function that "
2662 "expects arguments");
2663 } else
{ // Has arguments?
2664 // Loop through FunctionType's arguments and ensure they are specified
2666 FunctionType
::param_iterator I
= Ty
->param_begin
();
2667 FunctionType
::param_iterator E
= Ty
->param_end
();
2668 ValueRefList
::iterator ArgI
= $6->begin
(), ArgE
= $6->end
();
2670 for
(; ArgI
!= ArgE
&& I
!= E
; ++ArgI
, ++I
) {
2671 if
(ArgI
->Val
->getType
() != *I
)
2672 GEN_ERROR
("Parameter " + ArgI
->Val
->getName
()+ " is not of type '" +
2673 (*I
)->getDescription
() + "'");
2674 Args.push_back
(ArgI
->Val
);
2677 if
(Ty
->isVarArg
()) {
2679 for
(; ArgI
!= ArgE
; ++ArgI
)
2680 Args.push_back
(ArgI
->Val
); // push the remaining varargs
2681 } else if
(I
!= E || ArgI
!= ArgE
)
2682 GEN_ERROR
("Invalid number of parameters detected");
2685 // Create the InvokeInst
2686 InvokeInst
*II
= new InvokeInst
(V
, Normal
, Except
, Args.begin
(), Args.end
());
2687 II
->setCallingConv
($2);
2693 $$
= new UnwindInst
();
2697 $$
= new UnreachableInst
();
2703 JumpTable
: JumpTable IntType ConstValueRef
',' LABEL ValueRef
{
2705 Constant
*V
= cast
<Constant
>(getExistingVal
($2, $3));
2708 GEN_ERROR
("May only switch on a constant pool value");
2710 BasicBlock
* tmpBB
= getBBVal
($6);
2712 $$
->push_back
(std
::make_pair
(V
, tmpBB
));
2714 | IntType ConstValueRef
',' LABEL ValueRef
{
2715 $$
= new std
::vector
<std
::pair
<Constant
*, BasicBlock
*> >();
2716 Constant
*V
= cast
<Constant
>(getExistingVal
($1, $2));
2720 GEN_ERROR
("May only switch on a constant pool value");
2722 BasicBlock
* tmpBB
= getBBVal
($5);
2724 $$
->push_back
(std
::make_pair
(V
, tmpBB
));
2727 Inst
: OptLocalAssign InstVal
{
2728 // Is this definition named?? if so, assign the name...
2729 setValueName
($2, $1);
2737 PHIList
: Types
'[' ValueRef
',' ValueRef
']' { // Used for PHI nodes
2738 if
(!UpRefs.empty
())
2739 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
2740 $$
= new std
::list
<std
::pair
<Value
*, BasicBlock
*> >();
2741 Value
* tmpVal
= getVal
(*$1, $3);
2743 BasicBlock
* tmpBB
= getBBVal
($5);
2745 $$
->push_back
(std
::make_pair
(tmpVal
, tmpBB
));
2748 | PHIList
',' '[' ValueRef
',' ValueRef
']' {
2750 Value
* tmpVal
= getVal
($1->front
().first
->getType
(), $4);
2752 BasicBlock
* tmpBB
= getBBVal
($6);
2754 $1->push_back
(std
::make_pair
(tmpVal
, tmpBB
));
2758 ValueRefList
: Types ValueRef OptParamAttrs
{
2759 if
(!UpRefs.empty
())
2760 GEN_ERROR
("Invalid upreference in type: " + (*$1)->getDescription
());
2761 // Used for call and invoke instructions
2762 $$
= new ValueRefList
();
2763 ValueRefListEntry E
; E.Attrs
= $3; E.Val
= getVal
($1->get
(), $2);
2767 | ValueRefList
',' Types ValueRef OptParamAttrs
{
2768 if
(!UpRefs.empty
())
2769 GEN_ERROR
("Invalid upreference in type: " + (*$3)->getDescription
());
2771 ValueRefListEntry E
; E.Attrs
= $5; E.Val
= getVal
($3->get
(), $4);
2776 |
/*empty*/ { $$
= new ValueRefList
(); };
2778 IndexList
// Used for gep instructions and constant expressions
2779 : /*empty*/ { $$
= new std
::vector
<Value
*>(); }
2780 | IndexList
',' ResolvedVal
{
2787 OptTailCall
: TAIL CALL
{
2796 InstVal
: ArithmeticOps Types ValueRef
',' ValueRef
{
2797 if
(!UpRefs.empty
())
2798 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
2799 if
(!(*$2)->isInteger
() && !(*$2)->isFloatingPoint
() &&
2800 !isa
<VectorType
>((*$2).get
()))
2802 "Arithmetic operator requires integer, FP, or packed operands");
2803 if
(isa
<VectorType
>((*$2).get
()) &&
2804 ($1 == Instruction
::URem ||
2805 $1 == Instruction
::SRem ||
2806 $1 == Instruction
::FRem
))
2807 GEN_ERROR
("Remainder not supported on vector types");
2808 Value
* val1
= getVal
(*$2, $3);
2810 Value
* val2
= getVal
(*$2, $5);
2812 $$
= BinaryOperator
::create
($1, val1
, val2
);
2814 GEN_ERROR
("binary operator returned null");
2817 | LogicalOps Types ValueRef
',' ValueRef
{
2818 if
(!UpRefs.empty
())
2819 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
2820 if
(!(*$2)->isInteger
()) {
2821 if
(Instruction
::isShift
($1) ||
!isa
<VectorType
>($2->get
()) ||
2822 !cast
<VectorType
>($2->get
())->getElementType
()->isInteger
())
2823 GEN_ERROR
("Logical operator requires integral operands");
2825 Value
* tmpVal1
= getVal
(*$2, $3);
2827 Value
* tmpVal2
= getVal
(*$2, $5);
2829 $$
= BinaryOperator
::create
($1, tmpVal1
, tmpVal2
);
2831 GEN_ERROR
("binary operator returned null");
2834 | ICMP IPredicates Types ValueRef
',' ValueRef
{
2835 if
(!UpRefs.empty
())
2836 GEN_ERROR
("Invalid upreference in type: " + (*$3)->getDescription
());
2837 if
(isa
<VectorType
>((*$3).get
()))
2838 GEN_ERROR
("Vector types not supported by icmp instruction");
2839 Value
* tmpVal1
= getVal
(*$3, $4);
2841 Value
* tmpVal2
= getVal
(*$3, $6);
2843 $$
= CmpInst
::create
($1, $2, tmpVal1
, tmpVal2
);
2845 GEN_ERROR
("icmp operator returned null");
2848 | FCMP FPredicates Types ValueRef
',' ValueRef
{
2849 if
(!UpRefs.empty
())
2850 GEN_ERROR
("Invalid upreference in type: " + (*$3)->getDescription
());
2851 if
(isa
<VectorType
>((*$3).get
()))
2852 GEN_ERROR
("Vector types not supported by fcmp instruction");
2853 Value
* tmpVal1
= getVal
(*$3, $4);
2855 Value
* tmpVal2
= getVal
(*$3, $6);
2857 $$
= CmpInst
::create
($1, $2, tmpVal1
, tmpVal2
);
2859 GEN_ERROR
("fcmp operator returned null");
2862 | CastOps ResolvedVal TO Types
{
2863 if
(!UpRefs.empty
())
2864 GEN_ERROR
("Invalid upreference in type: " + (*$4)->getDescription
());
2866 const Type
* DestTy
= $4->get
();
2867 if
(!CastInst
::castIsValid
($1, Val
, DestTy
))
2868 GEN_ERROR
("invalid cast opcode for cast from '" +
2869 Val
->getType
()->getDescription
() + "' to '" +
2870 DestTy
->getDescription
() + "'");
2871 $$
= CastInst
::create
($1, Val
, DestTy
);
2874 | SELECT ResolvedVal
',' ResolvedVal
',' ResolvedVal
{
2875 if
($2->getType
() != Type
::Int1Ty
)
2876 GEN_ERROR
("select condition must be boolean");
2877 if
($4->getType
() != $6->getType
())
2878 GEN_ERROR
("select value types should match");
2879 $$
= new SelectInst
($2, $4, $6);
2882 | VAARG ResolvedVal
',' Types
{
2883 if
(!UpRefs.empty
())
2884 GEN_ERROR
("Invalid upreference in type: " + (*$4)->getDescription
());
2885 $$
= new VAArgInst
($2, *$4);
2889 | EXTRACTELEMENT ResolvedVal
',' ResolvedVal
{
2890 if
(!ExtractElementInst
::isValidOperands
($2, $4))
2891 GEN_ERROR
("Invalid extractelement operands");
2892 $$
= new ExtractElementInst
($2, $4);
2895 | INSERTELEMENT ResolvedVal
',' ResolvedVal
',' ResolvedVal
{
2896 if
(!InsertElementInst
::isValidOperands
($2, $4, $6))
2897 GEN_ERROR
("Invalid insertelement operands");
2898 $$
= new InsertElementInst
($2, $4, $6);
2901 | SHUFFLEVECTOR ResolvedVal
',' ResolvedVal
',' ResolvedVal
{
2902 if
(!ShuffleVectorInst
::isValidOperands
($2, $4, $6))
2903 GEN_ERROR
("Invalid shufflevector operands");
2904 $$
= new ShuffleVectorInst
($2, $4, $6);
2908 const Type
*Ty
= $2->front
().first
->getType
();
2909 if
(!Ty
->isFirstClassType
())
2910 GEN_ERROR
("PHI node operands must be of first class type");
2911 $$
= new PHINode
(Ty
);
2912 ((PHINode
*)$$
)->reserveOperandSpace
($2->size
());
2913 while
($2->begin
() != $2->end
()) {
2914 if
($2->front
().first
->getType
() != Ty
)
2915 GEN_ERROR
("All elements of a PHI node must be of the same type");
2916 cast
<PHINode
>($$
)->addIncoming
($2->front
().first
, $2->front
().second
);
2919 delete
$2; // Free the list...
2922 | OptTailCall OptCallingConv ResultTypes ValueRef
'(' ValueRefList
')'
2925 // Handle the short syntax
2926 const PointerType
*PFTy
= 0;
2927 const FunctionType
*Ty
= 0;
2928 if
(!(PFTy
= dyn_cast
<PointerType
>($3->get
())) ||
2929 !(Ty
= dyn_cast
<FunctionType
>(PFTy
->getElementType
()))) {
2930 // Pull out the types of all of the arguments...
2931 std
::vector
<const Type
*> ParamTypes
;
2932 ParamAttrsVector Attrs
;
2933 if
($8 != ParamAttr
::None
) {
2934 ParamAttrsWithIndex PAWI
; PAWI.index
= 0; PAWI.attrs
= $8;
2935 Attrs.push_back
(PAWI
);
2938 ValueRefList
::iterator I
= $6->begin
(), E
= $6->end
();
2939 for
(; I
!= E
; ++I
, ++index
) {
2940 const Type
*Ty
= I
->Val
->getType
();
2941 if
(Ty
== Type
::VoidTy
)
2942 GEN_ERROR
("Short call syntax cannot be used with varargs");
2943 ParamTypes.push_back
(Ty
);
2944 if
(I
->Attrs
!= ParamAttr
::None
) {
2945 ParamAttrsWithIndex PAWI
; PAWI.index
= index
; PAWI.attrs
= I
->Attrs
;
2946 Attrs.push_back
(PAWI
);
2950 ParamAttrsList
*PAL
= 0;
2952 PAL
= ParamAttrsList
::get
(Attrs
);
2954 Ty
= FunctionType
::get
($3->get
(), ParamTypes
, false
, PAL
);
2955 PFTy
= PointerType
::get
(Ty
);
2958 Value
*V
= getVal
(PFTy
, $4); // Get the function we're calling...
2961 // Check for call to invalid intrinsic to avoid crashing later.
2962 if
(Function
*theF
= dyn_cast
<Function
>(V
)) {
2963 if
(theF
->hasName
() && (theF
->getValueName
()->getKeyLength
() >= 5) &&
2964 (0 == strncmp
(theF
->getValueName
()->getKeyData
(), "llvm.", 5)) &&
2965 !theF
->getIntrinsicID
(true
))
2966 GEN_ERROR
("Call to invalid LLVM intrinsic function '" +
2967 theF
->getName
() + "'");
2970 // Check the arguments
2972 if
($6->empty
()) { // Has no arguments?
2973 // Make sure no arguments is a good thing!
2974 if
(Ty
->getNumParams
() != 0)
2975 GEN_ERROR
("No arguments passed to a function that "
2976 "expects arguments");
2977 } else
{ // Has arguments?
2978 // Loop through FunctionType's arguments and ensure they are specified
2981 FunctionType
::param_iterator I
= Ty
->param_begin
();
2982 FunctionType
::param_iterator E
= Ty
->param_end
();
2983 ValueRefList
::iterator ArgI
= $6->begin
(), ArgE
= $6->end
();
2985 for
(; ArgI
!= ArgE
&& I
!= E
; ++ArgI
, ++I
) {
2986 if
(ArgI
->Val
->getType
() != *I
)
2987 GEN_ERROR
("Parameter " + ArgI
->Val
->getName
()+ " is not of type '" +
2988 (*I
)->getDescription
() + "'");
2989 Args.push_back
(ArgI
->Val
);
2991 if
(Ty
->isVarArg
()) {
2993 for
(; ArgI
!= ArgE
; ++ArgI
)
2994 Args.push_back
(ArgI
->Val
); // push the remaining varargs
2995 } else if
(I
!= E || ArgI
!= ArgE
)
2996 GEN_ERROR
("Invalid number of parameters detected");
2998 // Create the call node
2999 CallInst
*CI
= new CallInst
(V
, Args.begin
(), Args.end
());
3000 CI
->setTailCall
($1);
3001 CI
->setCallingConv
($2);
3012 OptVolatile
: VOLATILE
{
3023 MemoryInst
: MALLOC Types OptCAlign
{
3024 if
(!UpRefs.empty
())
3025 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
3026 $$
= new MallocInst
(*$2, 0, $3);
3030 | MALLOC Types
',' INTTYPE ValueRef OptCAlign
{
3031 if
(!UpRefs.empty
())
3032 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
3033 Value
* tmpVal
= getVal
($4, $5);
3035 $$
= new MallocInst
(*$2, tmpVal
, $6);
3038 | ALLOCA Types OptCAlign
{
3039 if
(!UpRefs.empty
())
3040 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
3041 $$
= new AllocaInst
(*$2, 0, $3);
3045 | ALLOCA Types
',' INTTYPE ValueRef OptCAlign
{
3046 if
(!UpRefs.empty
())
3047 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
3048 Value
* tmpVal
= getVal
($4, $5);
3050 $$
= new AllocaInst
(*$2, tmpVal
, $6);
3053 | FREE ResolvedVal
{
3054 if
(!isa
<PointerType
>($2->getType
()))
3055 GEN_ERROR
("Trying to free nonpointer type " +
3056 $2->getType
()->getDescription
() + "");
3057 $$
= new FreeInst
($2);
3061 | OptVolatile LOAD Types ValueRef OptCAlign
{
3062 if
(!UpRefs.empty
())
3063 GEN_ERROR
("Invalid upreference in type: " + (*$3)->getDescription
());
3064 if
(!isa
<PointerType
>($3->get
()))
3065 GEN_ERROR
("Can't load from nonpointer type: " +
3066 (*$3)->getDescription
());
3067 if
(!cast
<PointerType
>($3->get
())->getElementType
()->isFirstClassType
())
3068 GEN_ERROR
("Can't load from pointer of non-first-class type: " +
3069 (*$3)->getDescription
());
3070 Value
* tmpVal
= getVal
(*$3, $4);
3072 $$
= new LoadInst
(tmpVal
, "", $1, $5);
3075 | OptVolatile STORE ResolvedVal
',' Types ValueRef OptCAlign
{
3076 if
(!UpRefs.empty
())
3077 GEN_ERROR
("Invalid upreference in type: " + (*$5)->getDescription
());
3078 const PointerType
*PT
= dyn_cast
<PointerType
>($5->get
());
3080 GEN_ERROR
("Can't store to a nonpointer type: " +
3081 (*$5)->getDescription
());
3082 const Type
*ElTy
= PT
->getElementType
();
3083 if
(ElTy
!= $3->getType
())
3084 GEN_ERROR
("Can't store '" + $3->getType
()->getDescription
() +
3085 "' into space of type '" + ElTy
->getDescription
() + "'");
3087 Value
* tmpVal
= getVal
(*$5, $6);
3089 $$
= new StoreInst
($3, tmpVal
, $1, $7);
3092 | GETELEMENTPTR Types ValueRef IndexList
{
3093 if
(!UpRefs.empty
())
3094 GEN_ERROR
("Invalid upreference in type: " + (*$2)->getDescription
());
3095 if
(!isa
<PointerType
>($2->get
()))
3096 GEN_ERROR
("getelementptr insn requires pointer operand");
3098 if
(!GetElementPtrInst
::getIndexedType
(*$2, $4->begin
(), $4->end
(), true
))
3099 GEN_ERROR
("Invalid getelementptr indices for type '" +
3100 (*$2)->getDescription
()+ "'");
3101 Value
* tmpVal
= getVal
(*$2, $3);
3103 $$
= new GetElementPtrInst
(tmpVal
, $4->begin
(), $4->end
());
3111 // common code from the two 'RunVMAsmParser' functions
3112 static Module
* RunParser
(Module
* M
) {
3114 llvmAsmlineno
= 1; // Reset the current line number...
3115 CurModule.CurrentModule
= M
;
3120 // Check to make sure the parser succeeded
3123 delete ParserResult
;
3127 // Emit an error if there are any unresolved types left.
3128 if
(!CurModule.LateResolveTypes.empty
()) {
3129 const ValID
&DID
= CurModule.LateResolveTypes.begin
()->first
;
3130 if
(DID.Type
== ValID
::LocalName
) {
3131 GenerateError
("Undefined type remains at eof: '"+DID.getName
() + "'");
3133 GenerateError
("Undefined type remains at eof: #" + itostr
(DID.Num
));
3136 delete ParserResult
;
3140 // Emit an error if there are any unresolved values left.
3141 if
(!CurModule.LateResolveValues.empty
()) {
3142 Value
*V
= CurModule.LateResolveValues.back
();
3143 std
::map
<Value
*, std
::pair
<ValID
, int> >::iterator I
=
3144 CurModule.PlaceHolderInfo.find
(V
);
3146 if
(I
!= CurModule.PlaceHolderInfo.end
()) {
3147 ValID
&DID
= I
->second.first
;
3148 if
(DID.Type
== ValID
::LocalName
) {
3149 GenerateError
("Undefined value remains at eof: "+DID.getName
() + "'");
3151 GenerateError
("Undefined value remains at eof: #" + itostr
(DID.Num
));
3154 delete ParserResult
;
3159 // Check to make sure that parsing produced a result
3163 // Reset ParserResult variable while saving its value for the result.
3164 Module
*Result
= ParserResult
;
3170 void llvm
::GenerateError
(const std
::string &message
, int LineNo
) {
3171 if
(LineNo
== -1) LineNo
= llvmAsmlineno
;
3172 // TODO: column number in exception
3174 TheParseError
->setError
(CurFilename
, message
, LineNo
);
3178 int yyerror(const char *ErrorMsg
) {
3180 = std
::string((CurFilename
== "-") ? std
::string("<stdin>") : CurFilename
)
3181 + ":" + utostr
((unsigned) llvmAsmlineno
) + ": ";
3182 std
::string errMsg
= where
+ "error: " + std
::string(ErrorMsg
);
3183 if
(yychar != YYEMPTY
&& yychar != 0)
3184 errMsg
+= " while reading token: '" + std
::string(llvmAsmtext
, llvmAsmleng
)+
3186 GenerateError
(errMsg
);