blob: 3a4873e8bcba981d700c69d51ae403171cb4a772 [file] [log] [blame]
Chris Lattner00950542001-06-06 20:29:01 +00001//===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
2//
3// This file implements the bison parser for LLVM assembly languages files.
4//
5//===------------------------------------------------------------------------=//
6
7//
8// TODO: Parse comments and add them to an internal node... so that they may
9// be saved in the bytecode format as well as everything else. Very important
10// for a general IR format.
11//
12
13%{
14#include "ParserInternals.h"
15#include "llvm/BasicBlock.h"
16#include "llvm/Method.h"
17#include "llvm/SymbolTable.h"
18#include "llvm/Module.h"
19#include "llvm/Type.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Assembly/Parser.h"
22#include "llvm/ConstantPool.h"
23#include "llvm/iTerminators.h"
24#include "llvm/iMemory.h"
25#include <list>
26#include <utility> // Get definition of pair class
27#include <stdio.h> // This embarasment is due to our flex lexer...
28
29int yyerror(char *ErrorMsg); // Forward declarations to prevent "implicit
30int yylex(); // declaration" of xxx warnings.
31int yyparse();
32
33static Module *ParserResult;
34const ToolCommandLine *CurOptions = 0;
35
36// This contains info used when building the body of a method. It is destroyed
37// when the method is completed.
38//
39typedef vector<Value *> ValueList; // Numbered defs
40static void ResolveDefinitions(vector<ValueList> &LateResolvers);
41
42static struct PerModuleInfo {
43 Module *CurrentModule;
44 vector<ValueList> Values; // Module level numbered definitions
45 vector<ValueList> LateResolveValues;
46
47 void ModuleDone() {
48 // If we could not resolve some blocks at parsing time (forward branches)
49 // resolve the branches now...
50 ResolveDefinitions(LateResolveValues);
51
52 Values.clear(); // Clear out method local definitions
53 CurrentModule = 0;
54 }
55} CurModule;
56
57static struct PerMethodInfo {
58 Method *CurrentMethod; // Pointer to current method being created
59
60 vector<ValueList> Values; // Keep track of numbered definitions
61 vector<ValueList> LateResolveValues;
62
63 inline PerMethodInfo() {
64 CurrentMethod = 0;
65 }
66
67 inline ~PerMethodInfo() {}
68
69 inline void MethodStart(Method *M) {
70 CurrentMethod = M;
71 }
72
73 void MethodDone() {
74 // If we could not resolve some blocks at parsing time (forward branches)
75 // resolve the branches now...
76 ResolveDefinitions(LateResolveValues);
77
78 Values.clear(); // Clear out method local definitions
79 CurrentMethod = 0;
80 }
81} CurMeth; // Info for the current method...
82
83
84//===----------------------------------------------------------------------===//
85// Code to handle definitions of all the types
86//===----------------------------------------------------------------------===//
87
88static void InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values) {
89 if (!D->hasName()) { // Is this a numbered definition?
90 unsigned type = D->getType()->getUniqueID();
91 if (ValueTab.size() <= type)
92 ValueTab.resize(type+1, ValueList());
93 //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
94 ValueTab[type].push_back(D);
95 }
96}
97
98static Value *getVal(const Type *Type, ValID &D,
99 bool DoNotImprovise = false) {
100 switch (D.Type) {
101 case 0: { // Is it a numbered definition?
102 unsigned type = Type->getUniqueID();
103 unsigned Num = (unsigned)D.Num;
104
105 // Module constants occupy the lowest numbered slots...
106 if (type < CurModule.Values.size()) {
107 if (Num < CurModule.Values[type].size())
108 return CurModule.Values[type][Num];
109
110 Num -= CurModule.Values[type].size();
111 }
112
113 // Make sure that our type is within bounds
114 if (CurMeth.Values.size() <= type)
115 break;
116
117 // Check that the number is within bounds...
118 if (CurMeth.Values[type].size() <= Num)
119 break;
120
121 return CurMeth.Values[type][Num];
122 }
123 case 1: { // Is it a named definition?
124 string Name(D.Name);
125 SymbolTable *SymTab = 0;
126 if (CurMeth.CurrentMethod)
127 SymTab = CurMeth.CurrentMethod->getSymbolTable();
128 Value *N = SymTab ? SymTab->lookup(Type, Name) : 0;
129
130 if (N == 0) {
131 SymTab = CurModule.CurrentModule->getSymbolTable();
132 if (SymTab)
133 N = SymTab->lookup(Type, Name);
134 if (N == 0) break;
135 }
136
137 D.destroy(); // Free old strdup'd memory...
138 return N;
139 }
140
141 case 2: // Is it a constant pool reference??
142 case 3: // Is it an unsigned const pool reference?
143 case 4:{ // Is it a string const pool reference?
144 ConstPoolVal *CPV = 0;
145
146 // Check to make sure that "Type" is an integral type, and that our
147 // value will fit into the specified type...
148 switch (D.Type) {
149 case 2:
150 if (Type == Type::BoolTy) { // Special handling for boolean data
151 CPV = new ConstPoolBool(D.ConstPool64 != 0);
152 } else {
153 if (!ConstPoolSInt::isValueValidForType(Type, D.ConstPool64))
154 ThrowException("Symbolic constant pool reference is invalid!");
155 CPV = new ConstPoolSInt(Type, D.ConstPool64);
156 }
157 break;
158 case 3:
159 if (!ConstPoolUInt::isValueValidForType(Type, D.UConstPool64)) {
160 if (!ConstPoolSInt::isValueValidForType(Type, D.ConstPool64)) {
161 ThrowException("Symbolic constant pool reference is invalid!");
162 } else { // This is really a signed reference. Transmogrify.
163 CPV = new ConstPoolSInt(Type, D.ConstPool64);
164 }
165 } else {
166 CPV = new ConstPoolUInt(Type, D.UConstPool64);
167 }
168 break;
169 case 4:
170 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
171 abort();
172 //CPV = new ConstPoolString(D.Name);
173 D.destroy(); // Free the string memory
174 break;
175 }
176 assert(CPV && "How did we escape creating a constant??");
177
178 // Scan through the constant table and see if we already have loaded this
179 // constant.
180 //
181 ConstantPool &CP = CurMeth.CurrentMethod ?
182 CurMeth.CurrentMethod->getConstantPool() :
183 CurModule.CurrentModule->getConstantPool();
184 ConstPoolVal *C = CP.find(CPV); // Already have this constant?
185 if (C) {
186 delete CPV; // Didn't need this after all, oh well.
187 return C; // Yup, we already have one, recycle it!
188 }
189 CP.insert(CPV);
190
191 // Success, everything is kosher. Lets go!
192 return CPV;
193 } // End of case 2,3,4
194 } // End of switch
195
196
197 // If we reached here, we referenced either a symbol that we don't know about
198 // or an id number that hasn't been read yet. We may be referencing something
199 // forward, so just create an entry to be resolved later and get to it...
200 //
201 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
202
203 // TODO: Attempt to coallecse nodes that are the same with previous ones.
204 Value *d = 0;
205 switch (Type->getPrimitiveID()) {
206 case Type::LabelTyID: d = new BBPlaceHolder(Type, D); break;
207 case Type::MethodTyID:
208 d = new MethPlaceHolder(Type, D);
209 InsertValue(d, CurModule.LateResolveValues);
210 return d;
211//case Type::ClassTyID: d = new ClassPlaceHolder(Type, D); break;
212 default: d = new DefPlaceHolder(Type, D); break;
213 }
214
215 assert(d != 0 && "How did we not make something?");
216 InsertValue(d, CurMeth.LateResolveValues);
217 return d;
218}
219
220
221//===----------------------------------------------------------------------===//
222// Code to handle forward references in instructions
223//===----------------------------------------------------------------------===//
224//
225// This code handles the late binding needed with statements that reference
226// values not defined yet... for example, a forward branch, or the PHI node for
227// a loop body.
228//
229// This keeps a table (CurMeth.LateResolveValues) of all such forward references
230// and back patchs after we are done.
231//
232
233// ResolveDefinitions - If we could not resolve some defs at parsing
234// time (forward branches, phi functions for loops, etc...) resolve the
235// defs now...
236//
237static void ResolveDefinitions(vector<ValueList> &LateResolvers) {
238 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
239 for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
240 while (!LateResolvers[ty].empty()) {
241 Value *V = LateResolvers[ty].back();
242 LateResolvers[ty].pop_back();
243 ValID &DID = getValIDFromPlaceHolder(V);
244
245 Value *TheRealValue = getVal(Type::getUniqueIDType(ty), DID, true);
246
247 if (TheRealValue == 0 && DID.Type == 1)
248 ThrowException("Reference to an invalid definition: '" +DID.getName() +
249 "' of type '" + V->getType()->getName() + "'");
250 else if (TheRealValue == 0)
251 ThrowException("Reference to an invalid definition: #" +itostr(DID.Num)+
252 " of type '" + V->getType()->getName() + "'");
253
254 V->replaceAllUsesWith(TheRealValue);
255 assert(V->use_empty());
256 delete V;
257 }
258 }
259
260 LateResolvers.clear();
261}
262
263// addConstValToConstantPool - This code is used to insert a constant into the
264// current constant pool. This is designed to make maximal (but not more than
265// possible) reuse (merging) of constants in the constant pool. This means that
266// multiple references to %4, for example will all get merged.
267//
268static ConstPoolVal *addConstValToConstantPool(ConstPoolVal *C) {
269 vector<ValueList> &ValTab = CurMeth.CurrentMethod ?
270 CurMeth.Values : CurModule.Values;
271 ConstantPool &CP = CurMeth.CurrentMethod ?
272 CurMeth.CurrentMethod->getConstantPool() :
273 CurModule.CurrentModule->getConstantPool();
274
275 if (ConstPoolVal *CPV = CP.find(C)) {
276 // Constant already in constant pool. Try to merge the two constants
277 if (CPV->hasName() && !C->hasName()) {
278 // Merge the two values, we inherit the existing CPV's name.
279 // InsertValue requires that the value have no name to insert correctly
280 // (because we want to fill the slot this constant would have filled)
281 //
282 string Name = CPV->getName();
283 CPV->setName("");
284 InsertValue(CPV, ValTab);
285 CPV->setName(Name);
286 delete C;
287 return CPV;
288 } else if (!CPV->hasName() && C->hasName()) {
289 // If we have a name on this value and there isn't one in the const
290 // pool val already, propogate it.
291 //
292 CPV->setName(C->getName());
293 delete C; // Sorry, you're toast
294 return CPV;
295 } else if (CPV->hasName() && C->hasName()) {
296 // Both values have distinct names. We cannot merge them.
297 CP.insert(C);
298 InsertValue(C, ValTab);
299 return C;
300 } else if (!CPV->hasName() && !C->hasName()) {
301 // Neither value has a name, trivially merge them.
302 InsertValue(CPV, ValTab);
303 delete C;
304 return CPV;
305 }
306
307 assert(0 && "Not reached!");
308 return 0;
309 } else { // No duplication of value.
310 CP.insert(C);
311 InsertValue(C, ValTab);
312 return C;
313 }
314}
315
316//===----------------------------------------------------------------------===//
317// RunVMAsmParser - Define an interface to this parser
318//===----------------------------------------------------------------------===//
319//
320Module *RunVMAsmParser(const ToolCommandLine &Opts, FILE *F) {
321 llvmAsmin = F;
322 CurOptions = &Opts;
323 llvmAsmlineno = 1; // Reset the current line number...
324
325 CurModule.CurrentModule = new Module(); // Allocate a new module to read
326 yyparse(); // Parse the file.
327 Module *Result = ParserResult;
328 CurOptions = 0;
329 llvmAsmin = stdin; // F is about to go away, don't use it anymore...
330 ParserResult = 0;
331
332 return Result;
333}
334
335%}
336
337%union {
338 Module *ModuleVal;
339 Method *MethodVal;
340 MethodArgument *MethArgVal;
341 BasicBlock *BasicBlockVal;
342 TerminatorInst *TermInstVal;
343 Instruction *InstVal;
344 ConstPoolVal *ConstVal;
345 const Type *TypeVal;
346
347 list<MethodArgument*> *MethodArgList;
348 list<Value*> *ValueList;
349 list<const Type*> *TypeList;
350 list<pair<ConstPoolVal*, BasicBlock*> > *JumpTable;
351 vector<ConstPoolVal*> *ConstVector;
352
353 int64_t SInt64Val;
354 uint64_t UInt64Val;
355 int SIntVal;
356 unsigned UIntVal;
357
358 char *StrVal; // This memory is allocated by strdup!
359 ValID ValIDVal; // May contain memory allocated by strdup
360
361 Instruction::UnaryOps UnaryOpVal;
362 Instruction::BinaryOps BinaryOpVal;
363 Instruction::TermOps TermOpVal;
364 Instruction::MemoryOps MemOpVal;
365}
366
367%type <ModuleVal> Module MethodList
368%type <MethodVal> Method MethodHeader BasicBlockList
369%type <BasicBlockVal> BasicBlock InstructionList
370%type <TermInstVal> BBTerminatorInst
371%type <InstVal> Inst InstVal MemoryInst
372%type <ConstVal> ConstVal
373%type <ConstVector> ConstVector
374%type <MethodArgList> ArgList ArgListH
375%type <MethArgVal> ArgVal
376%type <ValueList> ValueRefList ValueRefListE
377%type <TypeList> TypeList
378%type <JumpTable> JumpTable
379
380%type <ValIDVal> ValueRef ConstValueRef // Reference to a definition or BB
381
382// Tokens and types for handling constant integer values
383//
384// ESINT64VAL - A negative number within long long range
385%token <SInt64Val> ESINT64VAL
386
387// EUINT64VAL - A positive number within uns. long long range
388%token <UInt64Val> EUINT64VAL
389%type <SInt64Val> EINT64VAL
390
391%token <SIntVal> SINTVAL // Signed 32 bit ints...
392%token <UIntVal> UINTVAL // Unsigned 32 bit ints...
393%type <SIntVal> INTVAL
394
395// Built in types...
396%type <TypeVal> Types TypesV SIntType UIntType IntType
397%token <TypeVal> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
398%token <TypeVal> FLOAT DOUBLE STRING TYPE LABEL
399
400%token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
401%type <StrVal> OptVAR_ID OptAssign
402
403
404%token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE
405%token PHI CALL
406
407// Basic Block Terminating Operators
408%token <TermOpVal> RET BR SWITCH
409
410// Unary Operators
411%type <UnaryOpVal> UnaryOps // all the unary operators
412%token <UnaryOpVal> NEG NOT
413
414// Unary Conversion Operators
415%token <UnaryOpVal> TOINT TOUINT
416
417// Binary Operators
418%type <BinaryOpVal> BinaryOps // all the binary operators
419%token <BinaryOpVal> ADD SUB MUL DIV REM
420
421// Binary Comarators
422%token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE
423
424// Memory Instructions
425%token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETFIELD PUTFIELD
426
427%start Module
428%%
429
430// Handle constant integer size restriction and conversion...
431//
432
433INTVAL : SINTVAL
434INTVAL : UINTVAL {
435 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
436 ThrowException("Value too large for type!");
437 $$ = (int32_t)$1;
438}
439
440
441EINT64VAL : ESINT64VAL // These have same type and can't cause problems...
442EINT64VAL : EUINT64VAL {
443 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
444 ThrowException("Value too large for type!");
445 $$ = (int64_t)$1;
446}
447
448// Types includes all predefined types... except void, because you can't do
449// anything with it except for certain specific things...
450//
451// User defined types are added latter...
452//
453Types : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
454Types : LONG | ULONG | FLOAT | DOUBLE | STRING | TYPE | LABEL
455
456// TypesV includes all of 'Types', but it also includes the void type.
457TypesV : Types | VOID
458
459// Operations that are notably excluded from this list include:
460// RET, BR, & SWITCH because they end basic blocks and are treated specially.
461//
462UnaryOps : NEG | NOT | TOINT | TOUINT
463BinaryOps : ADD | SUB | MUL | DIV | REM
464BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
465
466// Valueine some types that allow classification if we only want a particular
467// thing...
468SIntType : LONG | INT | SHORT | SBYTE
469UIntType : ULONG | UINT | USHORT | UBYTE
470IntType : SIntType | UIntType
471
472OptAssign : VAR_ID '=' {
473 $$ = $1;
474 }
475 | /*empty*/ {
476 $$ = 0;
477 }
478
479ConstVal : SIntType EINT64VAL { // integral constants
480 if (!ConstPoolSInt::isValueValidForType($1, $2))
481 ThrowException("Constant value doesn't fit in type!");
482 $$ = new ConstPoolSInt($1, $2);
483 }
484 | UIntType EUINT64VAL { // integral constants
485 if (!ConstPoolUInt::isValueValidForType($1, $2))
486 ThrowException("Constant value doesn't fit in type!");
487 $$ = new ConstPoolUInt($1, $2);
488 }
489 | BOOL TRUE { // Boolean constants
490 $$ = new ConstPoolBool(true);
491 }
492 | BOOL FALSE { // Boolean constants
493 $$ = new ConstPoolBool(false);
494 }
495 | STRING STRINGCONSTANT { // String constants
496 cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
497 abort();
498 //$$ = new ConstPoolString($2);
499 free($2);
500 }
501 | TYPE Types { // Type constants
502 $$ = new ConstPoolType($2);
503 }
504 | '[' Types ']' '[' ConstVector ']' { // Nonempty array constant
505 // Verify all elements are correct type!
506 const ArrayType *AT = ArrayType::getArrayType($2);
507 for (unsigned i = 0; i < $5->size(); i++) {
508 if ($2 != (*$5)[i]->getType())
509 ThrowException("Element #" + utostr(i) + " is not of type '" +
510 $2->getName() + "' as required!\nIt is of type '" +
511 (*$5)[i]->getType()->getName() + "'.");
512 }
513
514 $$ = new ConstPoolArray(AT, *$5);
515 delete $5;
516 }
517 | '[' Types ']' '[' ']' { // Empty array constant
518 vector<ConstPoolVal*> Empty;
519 $$ = new ConstPoolArray(ArrayType::getArrayType($2), Empty);
520 }
521 | '[' EUINT64VAL 'x' Types ']' '[' ConstVector ']' {
522 // Verify all elements are correct type!
523 const ArrayType *AT = ArrayType::getArrayType($4, (int)$2);
524 if ($2 != $7->size())
525 ThrowException("Type mismatch: constant sized array initialized with " +
526 utostr($7->size()) + " arguments, but has size of " +
527 itostr((int)$2) + "!");
528
529 for (unsigned i = 0; i < $7->size(); i++) {
530 if ($4 != (*$7)[i]->getType())
531 ThrowException("Element #" + utostr(i) + " is not of type '" +
532 $4->getName() + "' as required!\nIt is of type '" +
533 (*$7)[i]->getType()->getName() + "'.");
534 }
535
536 $$ = new ConstPoolArray(AT, *$7);
537 delete $7;
538 }
539 | '[' EUINT64VAL 'x' Types ']' '[' ']' {
540 if ($2 != 0)
541 ThrowException("Type mismatch: constant sized array initialized with 0"
542 " arguments, but has size of " + itostr((int)$2) + "!");
543 vector<ConstPoolVal*> Empty;
544 $$ = new ConstPoolArray(ArrayType::getArrayType($4, 0), Empty);
545 }
546 | '{' TypeList '}' '{' ConstVector '}' {
547 StructType::ElementTypes Types($2->begin(), $2->end());
548 delete $2;
549
550 const StructType *St = StructType::getStructType(Types);
551 $$ = new ConstPoolStruct(St, *$5);
552 delete $5;
553 }
554 | '{' '}' '{' '}' {
555 const StructType *St =
556 StructType::getStructType(StructType::ElementTypes());
557 vector<ConstPoolVal*> Empty;
558 $$ = new ConstPoolStruct(St, Empty);
559 }
560/*
561 | Types '*' ConstVal {
562 assert(0);
563 $$ = 0;
564 }
565*/
566
567
568ConstVector : ConstVector ',' ConstVal {
569 ($$ = $1)->push_back(addConstValToConstantPool($3));
570 }
571 | ConstVal {
572 $$ = new vector<ConstPoolVal*>();
573 $$->push_back(addConstValToConstantPool($1));
574 }
575
576
577ConstPool : ConstPool OptAssign ConstVal {
578 if ($2) {
579 $3->setName($2);
580 free($2);
581 }
582
583 addConstValToConstantPool($3);
584 }
585 | /* empty: end of list */ {
586 }
587
588
589//===----------------------------------------------------------------------===//
590// Rules to match Modules
591//===----------------------------------------------------------------------===//
592
593// Module rule: Capture the result of parsing the whole file into a result
594// variable...
595//
596Module : MethodList {
597 $$ = ParserResult = $1;
598 CurModule.ModuleDone();
599}
600
601MethodList : MethodList Method {
602 $1->getMethodList().push_back($2);
603 CurMeth.MethodDone();
604 $$ = $1;
605 }
606 | ConstPool IMPLEMENTATION {
607 $$ = CurModule.CurrentModule;
608 }
609
610
611//===----------------------------------------------------------------------===//
612// Rules to match Method Headers
613//===----------------------------------------------------------------------===//
614
615OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }
616
617ArgVal : Types OptVAR_ID {
618 $$ = new MethodArgument($1);
619 if ($2) { // Was the argument named?
620 $$->setName($2);
621 free($2); // The string was strdup'd, so free it now.
622 }
623}
624
625ArgListH : ArgVal ',' ArgListH {
626 $$ = $3;
627 $3->push_front($1);
628 }
629 | ArgVal {
630 $$ = new list<MethodArgument*>();
631 $$->push_front($1);
632 }
633
634ArgList : ArgListH {
635 $$ = $1;
636 }
637 | /* empty */ {
638 $$ = 0;
639 }
640
641MethodHeaderH : TypesV STRINGCONSTANT '(' ArgList ')' {
642 MethodType::ParamTypes ParamTypeList;
643 if ($4)
644 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); I++)
645 ParamTypeList.push_back((*I)->getType());
646
647 const MethodType *MT = MethodType::getMethodType($1, ParamTypeList);
648
649 Method *M = new Method(MT, $2);
650 free($2); // Free strdup'd memory!
651
652 InsertValue(M, CurModule.Values);
653
654 CurMeth.MethodStart(M);
655
656 // Add all of the arguments we parsed to the method...
657 if ($4) { // Is null if empty...
658 Method::ArgumentListType &ArgList = M->getArgumentList();
659
660 for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); I++) {
661 InsertValue(*I);
662 ArgList.push_back(*I);
663 }
664 delete $4; // We're now done with the argument list
665 }
666}
667
668MethodHeader : MethodHeaderH ConstPool BEGINTOK {
669 $$ = CurMeth.CurrentMethod;
670}
671
672Method : BasicBlockList END {
673 $$ = $1;
674}
675
676
677//===----------------------------------------------------------------------===//
678// Rules to match Basic Blocks
679//===----------------------------------------------------------------------===//
680
681ConstValueRef : ESINT64VAL { // A reference to a direct constant
682 $$ = ValID::create($1);
683 }
684 | EUINT64VAL {
685 $$ = ValID::create($1);
686 }
687 | TRUE {
688 $$ = ValID::create((int64_t)1);
689 }
690 | FALSE {
691 $$ = ValID::create((int64_t)0);
692 }
693 | STRINGCONSTANT { // Quoted strings work too... especially for methods
694 $$ = ValID::create_conststr($1);
695 }
696
697// ValueRef - A reference to a definition...
698ValueRef : INTVAL { // Is it an integer reference...?
699 $$ = ValID::create($1);
700 }
701 | VAR_ID { // It must be a named reference then...
702 $$ = ValID::create($1);
703 }
704 | ConstValueRef {
705 $$ = $1;
706 }
707
708// The user may refer to a user defined type by its typeplane... check for this
709// now...
710//
711Types : ValueRef {
712 Value *D = getVal(Type::TypeTy, $1, true);
713 if (D == 0) ThrowException("Invalid user defined type: " + $1.getName());
714 assert (D->getValueType() == Value::ConstantVal &&
715 "Internal error! User defined type not in const pool!");
716 ConstPoolType *CPT = (ConstPoolType*)D;
717 $$ = CPT->getValue();
718 }
719 | TypesV '(' TypeList ')' { // Method derived type?
720 MethodType::ParamTypes Params($3->begin(), $3->end());
721 delete $3;
722 $$ = MethodType::getMethodType($1, Params);
723 }
724 | TypesV '(' ')' { // Method derived type?
725 MethodType::ParamTypes Params; // Empty list
726 $$ = MethodType::getMethodType($1, Params);
727 }
728 | '[' Types ']' {
729 $$ = ArrayType::getArrayType($2);
730 }
731 | '[' EUINT64VAL 'x' Types ']' {
732 $$ = ArrayType::getArrayType($4, (int)$2);
733 }
734 | '{' TypeList '}' {
735 StructType::ElementTypes Elements($2->begin(), $2->end());
736 delete $2;
737 $$ = StructType::getStructType(Elements);
738 }
739 | '{' '}' {
740 $$ = StructType::getStructType(StructType::ElementTypes());
741 }
742 | Types '*' {
743 $$ = PointerType::getPointerType($1);
744 }
745
746
747TypeList : Types {
748 $$ = new list<const Type*>();
749 $$->push_back($1);
750 }
751 | TypeList ',' Types {
752 ($$=$1)->push_back($3);
753 }
754
755
756BasicBlockList : BasicBlockList BasicBlock {
757 $1->getBasicBlocks().push_back($2);
758 $$ = $1;
759 }
760 | MethodHeader BasicBlock { // Do not allow methods with 0 basic blocks
761 $$ = $1; // in them...
762 $1->getBasicBlocks().push_back($2);
763 }
764
765
766// Basic blocks are terminated by branching instructions:
767// br, br/cc, switch, ret
768//
769BasicBlock : InstructionList BBTerminatorInst {
770 $1->getInstList().push_back($2);
771 InsertValue($1);
772 $$ = $1;
773 }
774 | LABELSTR InstructionList BBTerminatorInst {
775 $2->getInstList().push_back($3);
776 $2->setName($1);
777 free($1); // Free the strdup'd memory...
778
779 InsertValue($2);
780 $$ = $2;
781 }
782
783InstructionList : InstructionList Inst {
784 $1->getInstList().push_back($2);
785 $$ = $1;
786 }
787 | /* empty */ {
788 $$ = new BasicBlock();
789 }
790
791BBTerminatorInst : RET Types ValueRef { // Return with a result...
792 $$ = new ReturnInst(getVal($2, $3));
793 }
794 | RET VOID { // Return with no result...
795 $$ = new ReturnInst();
796 }
797 | BR LABEL ValueRef { // Unconditional Branch...
798 $$ = new BranchInst((BasicBlock*)getVal(Type::LabelTy, $3));
799 } // Conditional Branch...
800 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
801 $$ = new BranchInst((BasicBlock*)getVal(Type::LabelTy, $6),
802 (BasicBlock*)getVal(Type::LabelTy, $9),
803 getVal(Type::BoolTy, $3));
804 }
805 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
806 SwitchInst *S = new SwitchInst(getVal($2, $3),
807 (BasicBlock*)getVal(Type::LabelTy, $6));
808 $$ = S;
809
810 list<pair<ConstPoolVal*, BasicBlock*> >::iterator I = $8->begin(),
811 end = $8->end();
812 for (; I != end; I++)
813 S->dest_push_back(I->first, I->second);
814 }
815
816JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
817 $$ = $1;
818 ConstPoolVal *V = (ConstPoolVal*)getVal($2, $3, true);
819 if (V == 0)
820 ThrowException("May only switch on a constant pool value!");
821
822 $$->push_back(make_pair(V, (BasicBlock*)getVal($5, $6)));
823 }
824 | IntType ConstValueRef ',' LABEL ValueRef {
825 $$ = new list<pair<ConstPoolVal*, BasicBlock*> >();
826 ConstPoolVal *V = (ConstPoolVal*)getVal($1, $2, true);
827
828 if (V == 0)
829 ThrowException("May only switch on a constant pool value!");
830
831 $$->push_back(make_pair(V, (BasicBlock*)getVal($4, $5)));
832 }
833
834Inst : OptAssign InstVal {
835 if ($1) // Is this definition named??
836 $2->setName($1); // if so, assign the name...
837
838 InsertValue($2);
839 $$ = $2;
840}
841
842ValueRefList : Types ValueRef { // Used for PHI nodes and call statements...
843 $$ = new list<Value*>();
844 $$->push_back(getVal($1, $2));
845 }
846 | ValueRefList ',' ValueRef {
847 $$ = $1;
848 $1->push_back(getVal($1->front()->getType(), $3));
849 }
850
851// ValueRefListE - Just like ValueRefList, except that it may also be empty!
852ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }
853
854InstVal : BinaryOps Types ValueRef ',' ValueRef {
Chris Lattner477c2ec2001-06-08 21:30:13 +0000855 $$ = BinaryOperator::getBinaryOperator($1, getVal($2, $3), getVal($2, $5));
Chris Lattner00950542001-06-06 20:29:01 +0000856 if ($$ == 0)
857 ThrowException("binary operator returned null!");
858 }
859 | UnaryOps Types ValueRef {
Chris Lattner477c2ec2001-06-08 21:30:13 +0000860 $$ = UnaryOperator::getUnaryOperator($1, getVal($2, $3));
Chris Lattner00950542001-06-06 20:29:01 +0000861 if ($$ == 0)
862 ThrowException("unary operator returned null!");
863 }
864 | PHI ValueRefList {
865 $$ = new PHINode($2->front()->getType());
866 while ($2->begin() != $2->end()) {
867 // TODO: Ensure all types are the same...
868 ((PHINode*)$$)->addIncoming($2->front());
869 $2->pop_front();
870 }
871 delete $2; // Free the list...
872 }
873 | CALL Types ValueRef '(' ValueRefListE ')' {
874 if (!$2->isMethodType())
875 ThrowException("Can only call methods: invalid type '" +
876 $2->getName() + "'!");
877
878 const MethodType *Ty = (const MethodType*)$2;
879
880 Value *V = getVal(Ty, $3);
881 if (V->getValueType() != Value::MethodVal || V->getType() != Ty)
882 ThrowException("Cannot call: " + $3.getName() + "!");
883
884 // Create or access a new type that corresponds to the function call...
885 vector<Value *> Params;
886
887 if ($5) {
888 // Pull out just the arguments...
889 Params.insert(Params.begin(), $5->begin(), $5->end());
890 delete $5;
891
892 // Loop through MethodType's arguments and ensure they are specified
893 // correctly!
894 //
895 MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
896 unsigned i;
897 for (i = 0; i < Params.size() && I != Ty->getParamTypes().end(); ++i,++I){
898 if (Params[i]->getType() != *I)
899 ThrowException("Parameter " + utostr(i) + " is not of type '" +
900 (*I)->getName() + "'!");
901 }
902
903 if (i != Params.size() || I != Ty->getParamTypes().end())
904 ThrowException("Invalid number of parameters detected!");
905 }
906
907 // Create the call node...
908 $$ = new CallInst((Method*)V, Params);
909 }
910 | MemoryInst {
911 $$ = $1;
912 }
913
914MemoryInst : MALLOC Types {
915 ConstPoolVal *TyVal = new ConstPoolType(PointerType::getPointerType($2));
916 TyVal = addConstValToConstantPool(TyVal);
917 $$ = new MallocInst((ConstPoolType*)TyVal);
918 }
919 | MALLOC Types ',' UINT ValueRef {
920 if (!$2->isArrayType() || ((const ArrayType*)$2)->isSized())
921 ThrowException("Trying to allocate " + $2->getName() +
922 " as unsized array!");
923
924 Value *ArrSize = getVal($4, $5);
925 ConstPoolVal *TyVal = new ConstPoolType(PointerType::getPointerType($2));
926 TyVal = addConstValToConstantPool(TyVal);
927 $$ = new MallocInst((ConstPoolType*)TyVal, ArrSize);
928 }
929 | ALLOCA Types {
930 ConstPoolVal *TyVal = new ConstPoolType(PointerType::getPointerType($2));
931 TyVal = addConstValToConstantPool(TyVal);
932 $$ = new AllocaInst((ConstPoolType*)TyVal);
933 }
934 | ALLOCA Types ',' UINT ValueRef {
935 if (!$2->isArrayType() || ((const ArrayType*)$2)->isSized())
936 ThrowException("Trying to allocate " + $2->getName() +
937 " as unsized array!");
938
939 Value *ArrSize = getVal($4, $5);
940 ConstPoolVal *TyVal = new ConstPoolType(PointerType::getPointerType($2));
941 TyVal = addConstValToConstantPool(TyVal);
942 $$ = new AllocaInst((ConstPoolType*)TyVal, ArrSize);
943 }
944 | FREE Types ValueRef {
945 if (!$2->isPointerType())
946 ThrowException("Trying to free nonpointer type " + $2->getName() + "!");
947 $$ = new FreeInst(getVal($2, $3));
948 }
949
950%%
951int yyerror(char *ErrorMsg) {
952 ThrowException(string("Parse error: ") + ErrorMsg);
953 return 0;
954}