summaryrefslogtreecommitdiff
path: root/lib/AsmParser/llvmAsmParser.y
blob: 01709ca5deb30a9ddff9f6a345cb8956db9265ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
//===-- llvmAsmParser.y - Parser for llvm assembly files ---------*- C++ -*--=//
//
//  This file implements the bison parser for LLVM assembly languages files.
//
//===------------------------------------------------------------------------=//

//
// TODO: Parse comments and add them to an internal node... so that they may
// be saved in the bytecode format as well as everything else.  Very important
// for a general IR format.
//

%{
#include "ParserInternals.h"
#include "llvm/BasicBlock.h"
#include "llvm/Method.h"
#include "llvm/SymbolTable.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/ConstantPool.h"
#include "llvm/iTerminators.h"
#include "llvm/iMemory.h"
#include <list>
#include <utility>            // Get definition of pair class
#include <stdio.h>            // This embarasment is due to our flex lexer...

int yyerror(char *ErrorMsg);  // Forward declarations to prevent "implicit 
int yylex();                  // declaration" of xxx warnings.
int yyparse();

static Module *ParserResult;
const ToolCommandLine *CurOptions = 0;

// This contains info used when building the body of a method.  It is destroyed
// when the method is completed.
//
typedef vector<Value *> ValueList;           // Numbered defs
static void ResolveDefinitions(vector<ValueList> &LateResolvers);

static struct PerModuleInfo {
  Module *CurrentModule;
  vector<ValueList> Values;     // Module level numbered definitions
  vector<ValueList> LateResolveValues;

  void ModuleDone() {
    // If we could not resolve some blocks at parsing time (forward branches)
    // resolve the branches now...
    ResolveDefinitions(LateResolveValues);

    Values.clear();         // Clear out method local definitions
    CurrentModule = 0;
  }
} CurModule;

static struct PerMethodInfo {
  Method *CurrentMethod;         // Pointer to current method being created

  vector<ValueList> Values;          // Keep track of numbered definitions
  vector<ValueList> LateResolveValues;

  inline PerMethodInfo() {
    CurrentMethod = 0;
  }

  inline ~PerMethodInfo() {}

  inline void MethodStart(Method *M) {
    CurrentMethod = M;
  }

  void MethodDone() {
    // If we could not resolve some blocks at parsing time (forward branches)
    // resolve the branches now...
    ResolveDefinitions(LateResolveValues);

    Values.clear();         // Clear out method local definitions
    CurrentMethod = 0;
  }
} CurMeth;  // Info for the current method...


//===----------------------------------------------------------------------===//
//               Code to handle definitions of all the types
//===----------------------------------------------------------------------===//

static void InsertValue(Value *D, vector<ValueList> &ValueTab = CurMeth.Values) {
  if (!D->hasName()) {             // Is this a numbered definition?
    unsigned type = D->getType()->getUniqueID();
    if (ValueTab.size() <= type)
      ValueTab.resize(type+1, ValueList());
    //printf("Values[%d][%d] = %d\n", type, ValueTab[type].size(), D);
    ValueTab[type].push_back(D);
  }
}

static Value *getVal(const Type *Type, ValID &D, 
                     bool DoNotImprovise = false) {
  switch (D.Type) {
  case 0: {                 // Is it a numbered definition?
    unsigned type = Type->getUniqueID();
    unsigned Num = (unsigned)D.Num;

    // Module constants occupy the lowest numbered slots...
    if (type < CurModule.Values.size()) {
      if (Num < CurModule.Values[type].size()) 
        return CurModule.Values[type][Num];

      Num -= CurModule.Values[type].size();
    }

    // Make sure that our type is within bounds
    if (CurMeth.Values.size() <= type)
      break;

    // Check that the number is within bounds...
    if (CurMeth.Values[type].size() <= Num)
      break;
  
    return CurMeth.Values[type][Num];
  }
  case 1: {                // Is it a named definition?
    string Name(D.Name);
    SymbolTable *SymTab = 0;
    if (CurMeth.CurrentMethod) 
      SymTab = CurMeth.CurrentMethod->getSymbolTable();
    Value *N = SymTab ? SymTab->lookup(Type, Name) : 0;

    if (N == 0) {
      SymTab = CurModule.CurrentModule->getSymbolTable();
      if (SymTab)
        N = SymTab->lookup(Type, Name);
      if (N == 0) break;
    }

    D.destroy();  // Free old strdup'd memory...
    return N;
  }

  case 2:                 // Is it a constant pool reference??
  case 3:                 // Is it an unsigned const pool reference?
  case 4:{                // Is it a string const pool reference?
    ConstPoolVal *CPV = 0;

    // Check to make sure that "Type" is an integral type, and that our 
    // value will fit into the specified type...
    switch (D.Type) {
    case 2:
      if (Type == Type::BoolTy) {  // Special handling for boolean data
        CPV = new ConstPoolBool(D.ConstPool64 != 0);
      } else {
        if (!ConstPoolSInt::isValueValidForType(Type, D.ConstPool64))
          ThrowException("Symbolic constant pool reference is invalid!");
        CPV = new ConstPoolSInt(Type, D.ConstPool64);
      }
      break;
    case 3:
      if (!ConstPoolUInt::isValueValidForType(Type, D.UConstPool64)) {
        if (!ConstPoolSInt::isValueValidForType(Type, D.ConstPool64)) {
          ThrowException("Symbolic constant pool reference is invalid!");
        } else {     // This is really a signed reference.  Transmogrify.
          CPV = new ConstPoolSInt(Type, D.ConstPool64);
        }
      } else {
        CPV = new ConstPoolUInt(Type, D.UConstPool64);
      }
      break;
    case 4:
      cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
      abort();
      //CPV = new ConstPoolString(D.Name);
      D.destroy();   // Free the string memory
      break;
    }
    assert(CPV && "How did we escape creating a constant??");

    // Scan through the constant table and see if we already have loaded this
    // constant.
    //
    ConstantPool &CP = CurMeth.CurrentMethod ? 
                         CurMeth.CurrentMethod->getConstantPool() :
                           CurModule.CurrentModule->getConstantPool();
    ConstPoolVal *C = CP.find(CPV);      // Already have this constant?
    if (C) {
      delete CPV;  // Didn't need this after all, oh well.
      return C;    // Yup, we already have one, recycle it!
    }
    CP.insert(CPV);
      
    // Success, everything is kosher. Lets go!
    return CPV;
  }   // End of case 2,3,4
  }   // End of switch


  // If we reached here, we referenced either a symbol that we don't know about
  // or an id number that hasn't been read yet.  We may be referencing something
  // forward, so just create an entry to be resolved later and get to it...
  //
  if (DoNotImprovise) return 0;  // Do we just want a null to be returned?

  // TODO: Attempt to coallecse nodes that are the same with previous ones.
  Value *d = 0;
  switch (Type->getPrimitiveID()) {
  case Type::LabelTyID: d = new    BBPlaceHolder(Type, D); break;
  case Type::MethodTyID:
    d = new MethPlaceHolder(Type, D); 
    InsertValue(d, CurModule.LateResolveValues);
    return d;
//case Type::ClassTyID:      d = new ClassPlaceHolder(Type, D); break;
  default:                   d = new   DefPlaceHolder(Type, D); break;
  }

  assert(d != 0 && "How did we not make something?");
  InsertValue(d, CurMeth.LateResolveValues);
  return d;
}


//===----------------------------------------------------------------------===//
//              Code to handle forward references in instructions
//===----------------------------------------------------------------------===//
//
// This code handles the late binding needed with statements that reference
// values not defined yet... for example, a forward branch, or the PHI node for
// a loop body.
//
// This keeps a table (CurMeth.LateResolveValues) of all such forward references
// and back patchs after we are done.
//

// ResolveDefinitions - If we could not resolve some defs at parsing 
// time (forward branches, phi functions for loops, etc...) resolve the 
// defs now...
//
static void ResolveDefinitions(vector<ValueList> &LateResolvers) {
  // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
  for (unsigned ty = 0; ty < LateResolvers.size(); ty++) {
    while (!LateResolvers[ty].empty()) {
      Value *V = LateResolvers[ty].back();
      LateResolvers[ty].pop_back();
      ValID &DID = getValIDFromPlaceHolder(V);

      Value *TheRealValue = getVal(Type::getUniqueIDType(ty), DID, true);

      if (TheRealValue == 0 && DID.Type == 1)
        ThrowException("Reference to an invalid definition: '" +DID.getName() +
                       "' of type '" + V->getType()->getName() + "'");
      else if (TheRealValue == 0)
        ThrowException("Reference to an invalid definition: #" +itostr(DID.Num)+
                       " of type '" + V->getType()->getName() + "'");

      V->replaceAllUsesWith(TheRealValue);
      assert(V->use_empty());
      delete V;
    }
  }

  LateResolvers.clear();
}

// addConstValToConstantPool - This code is used to insert a constant into the
// current constant pool.  This is designed to make maximal (but not more than
// possible) reuse (merging) of constants in the constant pool.  This means that
// multiple references to %4, for example will all get merged.
//
static ConstPoolVal *addConstValToConstantPool(ConstPoolVal *C) {
  vector<ValueList> &ValTab = CurMeth.CurrentMethod ? 
                                  CurMeth.Values : CurModule.Values;
  ConstantPool &CP = CurMeth.CurrentMethod ? 
                          CurMeth.CurrentMethod->getConstantPool() : 
                          CurModule.CurrentModule->getConstantPool();

  if (ConstPoolVal *CPV = CP.find(C)) {
    // Constant already in constant pool. Try to merge the two constants
    if (CPV->hasName() && !C->hasName()) {
      // Merge the two values, we inherit the existing CPV's name.  
      // InsertValue requires that the value have no name to insert correctly
      // (because we want to fill the slot this constant would have filled)
      //
      string Name = CPV->getName();
      CPV->setName("");
      InsertValue(CPV, ValTab);
      CPV->setName(Name);
      delete C;
      return CPV;
    } else if (!CPV->hasName() && C->hasName()) {
      // If we have a name on this value and there isn't one in the const 
      // pool val already, propogate it.
      //
      CPV->setName(C->getName());
      delete C;   // Sorry, you're toast
      return CPV;
    } else if (CPV->hasName() && C->hasName()) {
      // Both values have distinct names.  We cannot merge them.
      CP.insert(C);
      InsertValue(C, ValTab);
      return C;
    } else if (!CPV->hasName() && !C->hasName()) {
      // Neither value has a name, trivially merge them.
      InsertValue(CPV, ValTab);
      delete C;
      return CPV;
    }

    assert(0 && "Not reached!");
    return 0;
  } else {           // No duplication of value.
    CP.insert(C);
    InsertValue(C, ValTab);
    return C;
  } 
}

//===----------------------------------------------------------------------===//
//            RunVMAsmParser - Define an interface to this parser
//===----------------------------------------------------------------------===//
//
Module *RunVMAsmParser(const ToolCommandLine &Opts, FILE *F) {
  llvmAsmin = F;
  CurOptions = &Opts;
  llvmAsmlineno = 1;      // Reset the current line number...

  CurModule.CurrentModule = new Module();  // Allocate a new module to read
  yyparse();       // Parse the file.
  Module *Result = ParserResult;
  CurOptions = 0;
  llvmAsmin = stdin;    // F is about to go away, don't use it anymore...
  ParserResult = 0;

  return Result;
}

%}

%union {
  Module                  *ModuleVal;
  Method                  *MethodVal;
  MethodArgument          *MethArgVal;
  BasicBlock              *BasicBlockVal;
  TerminatorInst          *TermInstVal;
  Instruction             *InstVal;
  ConstPoolVal            *ConstVal;
  const Type              *TypeVal;

  list<MethodArgument*>   *MethodArgList;
  list<Value*>            *ValueList;
  list<const Type*>       *TypeList;
  list<pair<ConstPoolVal*, BasicBlock*> > *JumpTable;
  vector<ConstPoolVal*>   *ConstVector;

  int64_t                  SInt64Val;
  uint64_t                 UInt64Val;
  int                      SIntVal;
  unsigned                 UIntVal;

  char                    *StrVal;   // This memory is allocated by strdup!
  ValID                    ValIDVal; // May contain memory allocated by strdup

  Instruction::UnaryOps    UnaryOpVal;
  Instruction::BinaryOps   BinaryOpVal;
  Instruction::TermOps     TermOpVal;
  Instruction::MemoryOps   MemOpVal;
}

%type <ModuleVal>     Module MethodList
%type <MethodVal>     Method MethodHeader BasicBlockList
%type <BasicBlockVal> BasicBlock InstructionList
%type <TermInstVal>   BBTerminatorInst
%type <InstVal>       Inst InstVal MemoryInst
%type <ConstVal>      ConstVal
%type <ConstVector>   ConstVector
%type <MethodArgList> ArgList ArgListH
%type <MethArgVal>    ArgVal
%type <ValueList>     ValueRefList ValueRefListE
%type <TypeList>      TypeList
%type <JumpTable>     JumpTable

%type <ValIDVal>      ValueRef ConstValueRef // Reference to a definition or BB

// Tokens and types for handling constant integer values
//
// ESINT64VAL - A negative number within long long range
%token <SInt64Val> ESINT64VAL

// EUINT64VAL - A positive number within uns. long long range
%token <UInt64Val> EUINT64VAL
%type  <SInt64Val> EINT64VAL

%token  <SIntVal>   SINTVAL   // Signed 32 bit ints...
%token  <UIntVal>   UINTVAL   // Unsigned 32 bit ints...
%type   <SIntVal>   INTVAL

// Built in types...
%type  <TypeVal> Types TypesV SIntType UIntType IntType
%token <TypeVal> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
%token <TypeVal> FLOAT DOUBLE STRING TYPE LABEL

%token <StrVal>     VAR_ID LABELSTR STRINGCONSTANT
%type  <StrVal>  OptVAR_ID OptAssign


%token IMPLEMENTATION TRUE FALSE BEGINTOK END DECLARE
%token PHI CALL

// Basic Block Terminating Operators 
%token <TermOpVal> RET BR SWITCH

// Unary Operators 
%type  <UnaryOpVal> UnaryOps  // all the unary operators
%token <UnaryOpVal> NEG NOT

// Unary Conversion Operators
%token <UnaryOpVal> TOINT TOUINT

// Binary Operators 
%type  <BinaryOpVal> BinaryOps  // all the binary operators
%token <BinaryOpVal> ADD SUB MUL DIV REM

// Binary Comarators
%token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE 

// Memory Instructions
%token <MemoryOpVal> MALLOC ALLOCA FREE LOAD STORE GETFIELD PUTFIELD

%start Module
%%

// Handle constant integer size restriction and conversion...
//

INTVAL : SINTVAL
INTVAL : UINTVAL {
  if ($1 > (uint32_t)INT32_MAX)     // Outside of my range!
    ThrowException("Value too large for type!");
  $$ = (int32_t)$1;
}


EINT64VAL : ESINT64VAL       // These have same type and can't cause problems...
EINT64VAL : EUINT64VAL {
  if ($1 > (uint64_t)INT64_MAX)     // Outside of my range!
    ThrowException("Value too large for type!");
  $$ = (int64_t)$1;
}

// Types includes all predefined types... except void, because you can't do 
// anything with it except for certain specific things...
//
// User defined types are added latter...
//
Types     : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT 
Types     : LONG | ULONG | FLOAT | DOUBLE | STRING | TYPE | LABEL

// TypesV includes all of 'Types', but it also includes the void type.
TypesV    : Types | VOID

// Operations that are notably excluded from this list include: 
// RET, BR, & SWITCH because they end basic blocks and are treated specially.
//
UnaryOps  : NEG | NOT | TOINT | TOUINT
BinaryOps : ADD | SUB | MUL | DIV | REM
BinaryOps : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE

// Valueine some types that allow classification if we only want a particular 
// thing...
SIntType :  LONG |  INT |  SHORT | SBYTE
UIntType : ULONG | UINT | USHORT | UBYTE
IntType : SIntType | UIntType

OptAssign : VAR_ID '=' {
    $$ = $1;
  }
  | /*empty*/ { 
    $$ = 0; 
  }

ConstVal : SIntType EINT64VAL {     // integral constants
    if (!ConstPoolSInt::isValueValidForType($1, $2))
      ThrowException("Constant value doesn't fit in type!");
    $$ = new ConstPoolSInt($1, $2);
  } 
  | UIntType EUINT64VAL {           // integral constants
    if (!ConstPoolUInt::isValueValidForType($1, $2))
      ThrowException("Constant value doesn't fit in type!");
    $$ = new ConstPoolUInt($1, $2);
  } 
  | BOOL TRUE {                     // Boolean constants
    $$ = new ConstPoolBool(true);
  }
  | BOOL FALSE {                    // Boolean constants
    $$ = new ConstPoolBool(false);
  }
  | STRING STRINGCONSTANT {         // String constants
    cerr << "FIXME: TODO: String constants [sbyte] not implemented yet!\n";
    abort();
    //$$ = new ConstPoolString($2);
    free($2);
  } 
  | TYPE Types {                    // Type constants
    $$ = new ConstPoolType($2);
  }
  | '[' Types ']' '[' ConstVector ']' {      // Nonempty array constant
    // Verify all elements are correct type!
    const ArrayType *AT = ArrayType::getArrayType($2);
    for (unsigned i = 0; i < $5->size(); i++) {
      if ($2 != (*$5)[i]->getType())
	ThrowException("Element #" + utostr(i) + " is not of type '" + 
		       $2->getName() + "' as required!\nIt is of type '" +
		       (*$5)[i]->getType()->getName() + "'.");
    }

    $$ = new ConstPoolArray(AT, *$5);
    delete $5;
  }
  | '[' Types ']' '[' ']' {                  // Empty array constant
    vector<ConstPoolVal*> Empty;
    $$ = new ConstPoolArray(ArrayType::getArrayType($2), Empty);
  }
  | '[' EUINT64VAL 'x' Types ']' '[' ConstVector ']' {
    // Verify all elements are correct type!
    const ArrayType *AT = ArrayType::getArrayType($4, (int)$2);
    if ($2 != $7->size())
      ThrowException("Type mismatch: constant sized array initialized with " +
		     utostr($7->size()) +  " arguments, but has size of " + 
		     itostr((int)$2) + "!");

    for (unsigned i = 0; i < $7->size(); i++) {
      if ($4 != (*$7)[i]->getType())
	ThrowException("Element #" + utostr(i) + " is not of type '" + 
		       $4->getName() + "' as required!\nIt is of type '" +
		       (*$7)[i]->getType()->getName() + "'.");
    }

    $$ = new ConstPoolArray(AT, *$7);
    delete $7;
  }
  | '[' EUINT64VAL 'x' Types ']' '[' ']' {
    if ($2 != 0) 
      ThrowException("Type mismatch: constant sized array initialized with 0"
		     " arguments, but has size of " + itostr((int)$2) + "!");
    vector<ConstPoolVal*> Empty;
    $$ = new ConstPoolArray(ArrayType::getArrayType($4, 0), Empty);
  }
  | '{' TypeList '}' '{' ConstVector '}' {
    StructType::ElementTypes Types($2->begin(), $2->end());
    delete $2;

    const StructType *St = StructType::getStructType(Types);
    $$ = new ConstPoolStruct(St, *$5);
    delete $5;
  }
  | '{' '}' '{' '}' {
    const StructType *St = 
      StructType::getStructType(StructType::ElementTypes());
    vector<ConstPoolVal*> Empty;
    $$ = new ConstPoolStruct(St, Empty);
  }
/*
  | Types '*' ConstVal {
    assert(0);
    $$ = 0;
  }
*/


ConstVector : ConstVector ',' ConstVal {
    ($$ = $1)->push_back(addConstValToConstantPool($3));
  }
  | ConstVal {
    $$ = new vector<ConstPoolVal*>();
    $$->push_back(addConstValToConstantPool($1));
  }


ConstPool : ConstPool OptAssign ConstVal { 
    if ($2) {
      $3->setName($2);
      free($2);
    }

    addConstValToConstantPool($3);
  }
  | /* empty: end of list */ { 
  }


//===----------------------------------------------------------------------===//
//                             Rules to match Modules
//===----------------------------------------------------------------------===//

// Module rule: Capture the result of parsing the whole file into a result
// variable...
//
Module : MethodList {
  $$ = ParserResult = $1;
  CurModule.ModuleDone();
}

MethodList : MethodList Method {
    $1->getMethodList().push_back($2);
    CurMeth.MethodDone();
    $$ = $1;
  } 
  | ConstPool IMPLEMENTATION {
    $$ = CurModule.CurrentModule;
  }


//===----------------------------------------------------------------------===//
//                       Rules to match Method Headers
//===----------------------------------------------------------------------===//

OptVAR_ID : VAR_ID | /*empty*/ { $$ = 0; }

ArgVal : Types OptVAR_ID {
  $$ = new MethodArgument($1);
  if ($2) {      // Was the argument named?
    $$->setName($2); 
    free($2);    // The string was strdup'd, so free it now.
  }
}

ArgListH : ArgVal ',' ArgListH {
    $$ = $3;
    $3->push_front($1);
  }
  | ArgVal {
    $$ = new list<MethodArgument*>();
    $$->push_front($1);
  }

ArgList : ArgListH {
    $$ = $1;
  }
  | /* empty */ {
    $$ = 0;
  }

MethodHeaderH : TypesV STRINGCONSTANT '(' ArgList ')' {
  MethodType::ParamTypes ParamTypeList;
  if ($4)
    for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); I++)
      ParamTypeList.push_back((*I)->getType());

  const MethodType *MT = MethodType::getMethodType($1, ParamTypeList);

  Method *M = new Method(MT, $2);
  free($2);  // Free strdup'd memory!

  InsertValue(M, CurModule.Values);

  CurMeth.MethodStart(M);

  // Add all of the arguments we parsed to the method...
  if ($4) {        // Is null if empty...
    Method::ArgumentListType &ArgList = M->getArgumentList();

    for (list<MethodArgument*>::iterator I = $4->begin(); I != $4->end(); I++) {
      InsertValue(*I);
      ArgList.push_back(*I);
    }
    delete $4;                     // We're now done with the argument list
  }
}

MethodHeader : MethodHeaderH ConstPool BEGINTOK {
  $$ = CurMeth.CurrentMethod;
}

Method : BasicBlockList END {
  $$ = $1;
}


//===----------------------------------------------------------------------===//
//                        Rules to match Basic Blocks
//===----------------------------------------------------------------------===//

ConstValueRef : ESINT64VAL {    // A reference to a direct constant
    $$ = ValID::create($1);
  }
  | EUINT64VAL {
    $$ = ValID::create($1);
  }
  | TRUE {
    $$ = ValID::create((int64_t)1);
  } 
  | FALSE {
    $$ = ValID::create((int64_t)0);
  }
  | STRINGCONSTANT {        // Quoted strings work too... especially for methods
    $$ = ValID::create_conststr($1);
  }

// ValueRef - A reference to a definition... 
ValueRef : INTVAL {           // Is it an integer reference...?
    $$ = ValID::create($1);
  }
  | VAR_ID {                // It must be a named reference then...
    $$ = ValID::create($1);
  }
  | ConstValueRef {
    $$ = $1;
  }

// The user may refer to a user defined type by its typeplane... check for this
// now...
//
Types : ValueRef {
    Value *D = getVal(Type::TypeTy, $1, true);
    if (D == 0) ThrowException("Invalid user defined type: " + $1.getName());
    assert (D->getValueType() == Value::ConstantVal &&
            "Internal error!  User defined type not in const pool!");
    ConstPoolType *CPT = (ConstPoolType*)D;
    $$ = CPT->getValue();
  }
  | TypesV '(' TypeList ')' {               // Method derived type?
    MethodType::ParamTypes Params($3->begin(), $3->end());
    delete $3;
    $$ = MethodType::getMethodType($1, Params);
  }
  | TypesV '(' ')' {               // Method derived type?
    MethodType::ParamTypes Params;     // Empty list
    $$ = MethodType::getMethodType($1, Params);
  }
  | '[' Types ']' {
    $$ = ArrayType::getArrayType($2);
  }
  | '[' EUINT64VAL 'x' Types ']' {
    $$ = ArrayType::getArrayType($4, (int)$2);
  }
  | '{' TypeList '}' {
    StructType::ElementTypes Elements($2->begin(), $2->end());
    delete $2;
    $$ = StructType::getStructType(Elements);
  }
  | '{' '}' {
    $$ = StructType::getStructType(StructType::ElementTypes());
  }
  | Types '*' {
    $$ = PointerType::getPointerType($1);
  }


TypeList : Types {
    $$ = new list<const Type*>();
    $$->push_back($1);
  }
  | TypeList ',' Types {
    ($$=$1)->push_back($3);
  }


BasicBlockList : BasicBlockList BasicBlock {
    $1->getBasicBlocks().push_back($2);
    $$ = $1;
  }
  | MethodHeader BasicBlock { // Do not allow methods with 0 basic blocks   
    $$ = $1;                  // in them...
    $1->getBasicBlocks().push_back($2);
  }


// Basic blocks are terminated by branching instructions: 
// br, br/cc, switch, ret
//
BasicBlock : InstructionList BBTerminatorInst  {
    $1->getInstList().push_back($2);
    InsertValue($1);
    $$ = $1;
  }
  | LABELSTR InstructionList BBTerminatorInst  {
    $2->getInstList().push_back($3);
    $2->setName($1);
    free($1);         // Free the strdup'd memory...

    InsertValue($2);
    $$ = $2;
  }

InstructionList : InstructionList Inst {
    $1->getInstList().push_back($2);
    $$ = $1;
  }
  | /* empty */ {
    $$ = new BasicBlock();
  }

BBTerminatorInst : RET Types ValueRef {              // Return with a result...
    $$ = new ReturnInst(getVal($2, $3));
  }
  | RET VOID {                                       // Return with no result...
    $$ = new ReturnInst();
  }
  | BR LABEL ValueRef {                         // Unconditional Branch...
    $$ = new BranchInst((BasicBlock*)getVal(Type::LabelTy, $3));
  }                                                  // Conditional Branch...
  | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {  
    $$ = new BranchInst((BasicBlock*)getVal(Type::LabelTy, $6), 
			(BasicBlock*)getVal(Type::LabelTy, $9),
			getVal(Type::BoolTy, $3));
  }
  | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
    SwitchInst *S = new SwitchInst(getVal($2, $3), 
                                   (BasicBlock*)getVal(Type::LabelTy, $6));
    $$ = S;

    list<pair<ConstPoolVal*, BasicBlock*> >::iterator I = $8->begin(), 
                                                      end = $8->end();
    for (; I != end; I++)
      S->dest_push_back(I->first, I->second);
  }

JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
    $$ = $1;
    ConstPoolVal *V = (ConstPoolVal*)getVal($2, $3, true);
    if (V == 0)
      ThrowException("May only switch on a constant pool value!");

    $$->push_back(make_pair(V, (BasicBlock*)getVal($5, $6)));
  }
  | IntType ConstValueRef ',' LABEL ValueRef {
    $$ = new list<pair<ConstPoolVal*, BasicBlock*> >();
    ConstPoolVal *V = (ConstPoolVal*)getVal($1, $2, true);

    if (V == 0)
      ThrowException("May only switch on a constant pool value!");

    $$->push_back(make_pair(V, (BasicBlock*)getVal($4, $5)));
  }

Inst : OptAssign InstVal {
  if ($1)              // Is this definition named??
    $2->setName($1);   // if so, assign the name...

  InsertValue($2);
  $$ = $2;
}

ValueRefList : Types ValueRef {    // Used for PHI nodes and call statements...
    $$ = new list<Value*>();
    $$->push_back(getVal($1, $2));
  }
  | ValueRefList ',' ValueRef {
    $$ = $1;
    $1->push_back(getVal($1->front()->getType(), $3));
  }

// ValueRefListE - Just like ValueRefList, except that it may also be empty!
ValueRefListE : ValueRefList | /*empty*/ { $$ = 0; }

InstVal : BinaryOps Types ValueRef ',' ValueRef {
    $$ = Instruction::getBinaryOperator($1, getVal($2, $3), getVal($2, $5));
    if ($$ == 0)
      ThrowException("binary operator returned null!");
  }
  | UnaryOps Types ValueRef {
    $$ = Instruction::getUnaryOperator($1, getVal($2, $3));
    if ($$ == 0)
      ThrowException("unary operator returned null!");
  } 
  | PHI ValueRefList {
    $$ = new PHINode($2->front()->getType());
    while ($2->begin() != $2->end()) {
      // TODO: Ensure all types are the same... 
      ((PHINode*)$$)->addIncoming($2->front());
      $2->pop_front();
    }
    delete $2;  // Free the list...
  } 
  | CALL Types ValueRef '(' ValueRefListE ')' {
    if (!$2->isMethodType())
      ThrowException("Can only call methods: invalid type '" + 
		     $2->getName() + "'!");

    const MethodType *Ty = (const MethodType*)$2;

    Value *V = getVal(Ty, $3);
    if (V->getValueType() != Value::MethodVal || V->getType() != Ty)
      ThrowException("Cannot call: " + $3.getName() + "!");

    // Create or access a new type that corresponds to the function call...
    vector<Value *> Params;

    if ($5) {
      // Pull out just the arguments...
      Params.insert(Params.begin(), $5->begin(), $5->end());
      delete $5;

      // Loop through MethodType's arguments and ensure they are specified
      // correctly!
      //
      MethodType::ParamTypes::const_iterator I = Ty->getParamTypes().begin();
      unsigned i;
      for (i = 0; i < Params.size() && I != Ty->getParamTypes().end(); ++i,++I){
	if (Params[i]->getType() != *I)
	  ThrowException("Parameter " + utostr(i) + " is not of type '" + 
			 (*I)->getName() + "'!");
      }

      if (i != Params.size() || I != Ty->getParamTypes().end())
	ThrowException("Invalid number of parameters detected!");
    }

    // Create the call node...
    $$ = new CallInst((Method*)V, Params);
  }
  | MemoryInst {
    $$ = $1;
  }

MemoryInst : MALLOC Types {
    ConstPoolVal *TyVal = new ConstPoolType(PointerType::getPointerType($2));
    TyVal = addConstValToConstantPool(TyVal);
    $$ = new MallocInst((ConstPoolType*)TyVal);
  }
  | MALLOC Types ',' UINT ValueRef {
    if (!$2->isArrayType() || ((const ArrayType*)$2)->isSized())
      ThrowException("Trying to allocate " + $2->getName() + 
		     " as unsized array!");

    Value *ArrSize = getVal($4, $5);
    ConstPoolVal *TyVal = new ConstPoolType(PointerType::getPointerType($2));
    TyVal = addConstValToConstantPool(TyVal);
    $$ = new MallocInst((ConstPoolType*)TyVal, ArrSize);
  }
  | ALLOCA Types {
    ConstPoolVal *TyVal = new ConstPoolType(PointerType::getPointerType($2));
    TyVal = addConstValToConstantPool(TyVal);
    $$ = new AllocaInst((ConstPoolType*)TyVal);
  }
  | ALLOCA Types ',' UINT ValueRef {
    if (!$2->isArrayType() || ((const ArrayType*)$2)->isSized())
      ThrowException("Trying to allocate " + $2->getName() + 
		     " as unsized array!");

    Value *ArrSize = getVal($4, $5);
    ConstPoolVal *TyVal = new ConstPoolType(PointerType::getPointerType($2));
    TyVal = addConstValToConstantPool(TyVal);
    $$ = new AllocaInst((ConstPoolType*)TyVal, ArrSize);
  }
  | FREE Types ValueRef {
    if (!$2->isPointerType())
      ThrowException("Trying to free nonpointer type " + $2->getName() + "!");
    $$ = new FreeInst(getVal($2, $3));
  }

%%
int yyerror(char *ErrorMsg) {
  ThrowException(string("Parse error: ") + ErrorMsg);
  return 0;
}