summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
blob: 15dece9fcb8bce03c4fb1b52503571ebebdb2457 (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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// 

namespace System.Reflection.Emit 
{
    using System;
    using TextWriter = System.IO.TextWriter;
    using System.Diagnostics.SymbolStore;
    using System.Runtime.InteropServices;
    using System.Reflection;
    using System.Security.Permissions;
    using System.Globalization;
    using System.Diagnostics.Contracts;
    
    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(_ILGenerator))]
    [System.Runtime.InteropServices.ComVisible(true)]
    public class ILGenerator : _ILGenerator
    {
        #region Const Members
        private const int defaultSize = 16;
        private const int DefaultFixupArraySize = 8;
        private const int DefaultLabelArraySize = 4;
        private const int DefaultExceptionArraySize = 2;
        #endregion

        #region Internal Statics
        internal static T[] EnlargeArray<T>(T[] incoming)
        {
            return EnlargeArray(incoming, incoming.Length * 2);
        }
        
        internal static T[] EnlargeArray<T>(T[] incoming, int requiredSize)
        {
            Contract.Requires(incoming != null);
            Contract.Ensures(Contract.Result<T[]>() != null);
            Contract.Ensures(Contract.Result<T[]>().Length == requiredSize);
            
            T[] temp = new T[requiredSize];
            Array.Copy(incoming, 0, temp, 0, incoming.Length);
            return temp;
        }
        
        private static byte[] EnlargeArray(byte[] incoming)
        {
            return EnlargeArray(incoming, incoming.Length * 2);
        }

        private static byte[] EnlargeArray(byte[] incoming, int requiredSize)
        {
            Contract.Requires(incoming != null);
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == requiredSize);
            
            byte[] temp = new byte[requiredSize];
            Buffer.BlockCopy(incoming, 0, temp, 0, incoming.Length);
            return temp;
        }
        #endregion

        #region Internal Data Members
        private  int                m_length;
        private  byte[]             m_ILStream;

        private  int[]              m_labelList;
        private  int                m_labelCount;

        private  __FixupData[]      m_fixupData;         
         
        private  int                m_fixupCount;

        private  int[]              m_RelocFixupList;
        private  int                m_RelocFixupCount;

        private  int                m_exceptionCount;
        private  int                m_currExcStackCount;
        private  __ExceptionInfo[]  m_exceptions;           //This is the list of all of the exceptions in this ILStream.
        private  __ExceptionInfo[]  m_currExcStack;         //This is the stack of exceptions which we're currently in.

        internal ScopeTree          m_ScopeTree;            // this variable tracks all debugging scope information
        internal LineNumberInfo     m_LineNumberInfo;       // this variable tracks all line number information

        internal MethodInfo         m_methodBuilder;
        internal int                m_localCount;
        internal SignatureHelper    m_localSignature;

        private  int                m_maxStackSize = 0;     // Maximum stack size not counting the exceptions.

        private  int                m_maxMidStack = 0;      // Maximum stack size for a given basic block.
        private  int                m_maxMidStackCur = 0;   // Running count of the maximum stack size for the current basic block.

        internal int CurrExcStackCount
        {
            get { return m_currExcStackCount; }
        }

        internal __ExceptionInfo[] CurrExcStack
        {
            get { return m_currExcStack; }
        }
        #endregion

        #region Constructor
        // package private constructor. This code path is used when client create
        // ILGenerator through MethodBuilder.
        internal ILGenerator(MethodInfo methodBuilder) : this(methodBuilder, 64)
        {
        }

        internal ILGenerator(MethodInfo methodBuilder, int size)
        {
            Contract.Requires(methodBuilder != null);
            Contract.Requires(methodBuilder is MethodBuilder || methodBuilder is DynamicMethod);

            if (size < defaultSize)
            {
                m_ILStream = new byte[defaultSize];
            }
            else
            {
                m_ILStream = new byte[size];
            }

            m_length = 0;

            m_labelCount = 0;
            m_fixupCount = 0;
            m_labelList = null;

            m_fixupData = null;

            m_exceptions = null; 
            m_exceptionCount = 0;
            m_currExcStack = null; 
            m_currExcStackCount = 0;

            m_RelocFixupList = null;
            m_RelocFixupCount = 0;

            // initialize the scope tree
            m_ScopeTree = new ScopeTree();
            m_LineNumberInfo = new LineNumberInfo();
            m_methodBuilder = methodBuilder;

            // initialize local signature
            m_localCount = 0;
            MethodBuilder mb = m_methodBuilder as MethodBuilder;
            if (mb == null) 
                m_localSignature = SignatureHelper.GetLocalVarSigHelper(null);
            else
                m_localSignature = SignatureHelper.GetLocalVarSigHelper(mb.GetTypeBuilder().Module);
        }

        #endregion

        #region Internal Members
        internal virtual void RecordTokenFixup()
        {
            if (m_RelocFixupList == null)
                m_RelocFixupList = new int[DefaultFixupArraySize];
            else if (m_RelocFixupList.Length <= m_RelocFixupCount)
                m_RelocFixupList = EnlargeArray(m_RelocFixupList);

            m_RelocFixupList[m_RelocFixupCount++] = m_length;
        }

        internal void InternalEmit(OpCode opcode)
        {
            if (opcode.Size != 1)
            {
                m_ILStream[m_length++] = (byte)(opcode.Value >> 8);
            }

            m_ILStream[m_length++] = (byte)opcode.Value;

            UpdateStackSize(opcode, opcode.StackChange());

        }

        internal void UpdateStackSize(OpCode opcode, int stackchange)
        {
            // Updates internal variables for keeping track of the stack size
            // requirements for the function.  stackchange specifies the amount
            // by which the stacksize needs to be updated.

            // Special case for the Return.  Returns pops 1 if there is a
            // non-void return value.

            // Update the running stacksize.  m_maxMidStack specifies the maximum
            // amount of stack required for the current basic block irrespective of
            // where you enter the block.
            m_maxMidStackCur += stackchange;
            if (m_maxMidStackCur > m_maxMidStack)
                m_maxMidStack = m_maxMidStackCur;
            else if (m_maxMidStackCur < 0)
                m_maxMidStackCur = 0;

            // If the current instruction signifies end of a basic, which basically
            // means an unconditional branch, add m_maxMidStack to m_maxStackSize.
            // m_maxStackSize will eventually be the sum of the stack requirements for
            // each basic block.
            if (opcode.EndsUncondJmpBlk())
            {
                m_maxStackSize += m_maxMidStack;
                m_maxMidStack = 0;
                m_maxMidStackCur = 0;
            }
        }

        [System.Security.SecurityCritical]  // auto-generated
        private int GetMethodToken(MethodBase method, Type[] optionalParameterTypes, bool useMethodDef)
        {
            return ((ModuleBuilder)m_methodBuilder.Module).GetMethodTokenInternal(method, optionalParameterTypes, useMethodDef);
        }

        [System.Security.SecurityCritical]  // auto-generated
        internal virtual SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, 
            Type[] parameterTypes, Type[] optionalParameterTypes)
        {
            return GetMemberRefSignature(call, returnType, parameterTypes, optionalParameterTypes, 0);
        }

        [System.Security.SecurityCritical]  // auto-generated
        private SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, 
            Type[] parameterTypes, Type[] optionalParameterTypes, int cGenericParameters)
        {
            return ((ModuleBuilder)m_methodBuilder.Module).GetMemberRefSignature(call, returnType, parameterTypes, optionalParameterTypes, cGenericParameters);
        }

        internal byte[] BakeByteArray()
        {
            // BakeByteArray is an internal function designed to be called by MethodBuilder to do
            // all of the fixups and return a new byte array representing the byte stream with labels resolved, etc.

            int newSize;
            int updateAddr;
            byte[] newBytes;

            if (m_currExcStackCount != 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_UnclosedExceptionBlock"));
            }
            if (m_length == 0)
                return null;

            //Calculate the size of the new array.
            newSize = m_length;

            //Allocate space for the new array.
            newBytes = new byte[newSize];

            //Copy the data from the old array
            Buffer.BlockCopy(m_ILStream, 0, newBytes, 0, newSize);

            //Do the fixups.
            //This involves iterating over all of the labels and
            //replacing them with their proper values.
            for (int i =0; i < m_fixupCount; i++)
            {
                updateAddr = GetLabelPos(m_fixupData[i].m_fixupLabel) - (m_fixupData[i].m_fixupPos + m_fixupData[i].m_fixupInstSize);

                //Handle single byte instructions
                //Throw an exception if they're trying to store a jump in a single byte instruction that doesn't fit.
                if (m_fixupData[i].m_fixupInstSize == 1)
                {

                    //Verify that our one-byte arg will fit into a Signed Byte.
                    if (updateAddr < SByte.MinValue || updateAddr > SByte.MaxValue)
                    {
                        throw new NotSupportedException(Environment.GetResourceString("NotSupported_IllegalOneByteBranch",m_fixupData[i].m_fixupPos, updateAddr));
                    }

                    //Place the one-byte arg
                    if (updateAddr < 0)
                    {
                        newBytes[m_fixupData[i].m_fixupPos] = (byte)(256 + updateAddr);
                    }
                    else
                    {
                        newBytes[m_fixupData[i].m_fixupPos] = (byte)updateAddr;
                    }
                }
                else
                {
                    //Place the four-byte arg
                    PutInteger4InArray(updateAddr, m_fixupData[i].m_fixupPos, newBytes);
                }
            }
            return newBytes;
        }

        internal __ExceptionInfo[] GetExceptions()
        {
            __ExceptionInfo []temp;
            if (m_currExcStackCount != 0)
            {
                throw new NotSupportedException(Environment.GetResourceString(ResId.Argument_UnclosedExceptionBlock));
            }
            
            if (m_exceptionCount == 0)
            {
                return null;
            }
            
            temp = new __ExceptionInfo[m_exceptionCount];
            Array.Copy(m_exceptions, 0, temp, 0, m_exceptionCount);
            SortExceptions(temp);
            return temp;
        }

        internal void EnsureCapacity(int size)
        {
            // Guarantees an array capable of holding at least size elements.
            if (m_length + size >= m_ILStream.Length)
            {
                if (m_length + size >= 2 * m_ILStream.Length)
                {
                    m_ILStream = EnlargeArray(m_ILStream, m_length + size);
                }
                else
                {
                    m_ILStream = EnlargeArray(m_ILStream);
                }
            }
        }

        internal void PutInteger4(int value)
        {
            m_length = PutInteger4InArray(value, m_length, m_ILStream);
        }

        private static int PutInteger4InArray(int value, int startPos, byte []array)
        {
            // Puts an Int32 onto the stream. This is an internal routine, so it does not do any error checking.

            array[startPos++] = (byte)value;
            array[startPos++] = (byte)(value >>8);
            array[startPos++] = (byte)(value >>16);
            array[startPos++] = (byte)(value >>24);
            return startPos;
        }

        private int GetLabelPos(Label lbl)
        {
            // Gets the position in the stream of a particular label.
            // Verifies that the label exists and that it has been given a value.

            int index = lbl.GetLabelValue();
            
            if (index < 0 || index >= m_labelCount)
                throw new ArgumentException(Environment.GetResourceString("Argument_BadLabel"));

            if (m_labelList[index] < 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_BadLabelContent"));

            return m_labelList[index];
        }

        private void AddFixup(Label lbl, int pos, int instSize)
        {
            // Notes the label, position, and instruction size of a new fixup.  Expands
            // all of the fixup arrays as appropriate.

            if (m_fixupData == null)
            {
                m_fixupData = new __FixupData[DefaultFixupArraySize];
            }
            else if (m_fixupData.Length <= m_fixupCount)
            {
                m_fixupData = EnlargeArray(m_fixupData);
            }

            m_fixupData[m_fixupCount].m_fixupPos = pos;
            m_fixupData[m_fixupCount].m_fixupLabel = lbl;
            m_fixupData[m_fixupCount].m_fixupInstSize = instSize;

            m_fixupCount++;
        }

        internal int GetMaxStackSize()
        {
            return m_maxStackSize;
        }

        private static void SortExceptions(__ExceptionInfo []exceptions)
        {
            // In order to call exceptions properly we have to sort them in ascending order by their end position.
            // Just a cheap insertion sort.  We don't expect many exceptions (<10), where InsertionSort beats QuickSort.
            // If we have more exceptions than this in real life, we should consider moving to a QuickSort.

            int least;
            __ExceptionInfo temp;
            int length = exceptions.Length;
            for (int i =0; i < length; i++)
            {
                least = i;
                for (int j =i + 1; j < length; j++)
                {
                    if (exceptions[least].IsInner(exceptions[j]))
                    {
                        least = j;
                    }
                }
                temp = exceptions[i];
                exceptions[i] = exceptions[least];
                exceptions[least] = temp;
            }
        }

        internal int[] GetTokenFixups()
        {
            if (m_RelocFixupCount == 0)
            {
                Contract.Assert(m_RelocFixupList == null);
                return null;
            }

            int[] narrowTokens = new int[m_RelocFixupCount];
            Array.Copy(m_RelocFixupList, 0, narrowTokens, 0, m_RelocFixupCount);
            return narrowTokens;
        }
        #endregion

        #region Public Members

        #region Emit
        public virtual void Emit(OpCode opcode)
        {
            EnsureCapacity(3);
            InternalEmit(opcode);

        }

        public virtual void Emit(OpCode opcode, byte arg) 
        {
            EnsureCapacity(4);
            InternalEmit(opcode);
            m_ILStream[m_length++]=arg;
        }

        [CLSCompliant(false)]
        public void Emit(OpCode opcode, sbyte arg) 
        {
            // Puts opcode onto the stream of instructions followed by arg

            EnsureCapacity(4);
            InternalEmit(opcode);
            if (arg<0) {
                m_ILStream[m_length++]=(byte)(256+arg);
            } else {
                m_ILStream[m_length++]=(byte) arg;
            }
        }

        public virtual void Emit(OpCode opcode, short arg) 
        {
            // Puts opcode onto the stream of instructions followed by arg
            EnsureCapacity(5);
            InternalEmit(opcode);
            m_ILStream[m_length++]=(byte) arg;
            m_ILStream[m_length++]=(byte) (arg>>8);
        }

        public virtual void Emit(OpCode opcode, int arg) 
        {
            // Puts opcode onto the stream of instructions followed by arg
            EnsureCapacity(7);
            InternalEmit(opcode);
            PutInteger4(arg);
        }

        [System.Security.SecuritySafeCritical]  // auto-generated
        public virtual void Emit(OpCode opcode, MethodInfo meth)
        {
            if (meth == null)
                throw new ArgumentNullException("meth");
            Contract.EndContractBlock();

            if (opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))
            {
                EmitCall(opcode, meth, null);
            }
            else
            {
                int stackchange = 0;

                // Reflection doesn't distinguish between these two concepts:
                //   1. A generic method definition: Foo`1
                //   2. A generic method definition instantiated over its own generic arguments: Foo`1<!!0>
                // In RefEmit, we always want 1 for Ld* opcodes and 2 for Call* and Newobj.
                bool useMethodDef = opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn) || opcode.Equals(OpCodes.Ldvirtftn);
                int tk = GetMethodToken(meth, null, useMethodDef);

                EnsureCapacity(7);
                InternalEmit(opcode);

                UpdateStackSize(opcode, stackchange);
                RecordTokenFixup();
                PutInteger4(tk);        
            }
        }


        [System.Security.SecuritySafeCritical]  // auto-generated
        public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention, 
            Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes)
        {
            int stackchange = 0;
            SignatureHelper     sig;
            if (optionalParameterTypes != null)
            {
                if ((callingConvention & CallingConventions.VarArgs) == 0)
                {
                    // Client should not supply optional parameter in default calling convention
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
                }
            }

            ModuleBuilder modBuilder = (ModuleBuilder) m_methodBuilder.Module;
            sig = GetMemberRefSignature(callingConvention,
                                        returnType,
                                        parameterTypes,
                                        optionalParameterTypes);

            EnsureCapacity(7);
            Emit(OpCodes.Calli);

            // If there is a non-void return type, push one.
            if (returnType != typeof(void))
                stackchange++;
            // Pop off arguments if any.
            if (parameterTypes != null)
                stackchange -= parameterTypes.Length;
            // Pop off vararg arguments.
            if (optionalParameterTypes != null)
                stackchange -= optionalParameterTypes.Length;
            // Pop the this parameter if the method has a this parameter.
            if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
                stackchange--;
            // Pop the native function pointer.
            stackchange--;
            UpdateStackSize(OpCodes.Calli, stackchange);

            RecordTokenFixup();
            PutInteger4(modBuilder.GetSignatureToken(sig).Token);
        }

        public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes)
        {
            int             stackchange = 0;
            int             cParams = 0;
            int             i;
            SignatureHelper sig;
            
            ModuleBuilder modBuilder = (ModuleBuilder) m_methodBuilder.Module;

            if (parameterTypes != null)
            {
                cParams = parameterTypes.Length;
            }
            
            sig = SignatureHelper.GetMethodSigHelper(
                modBuilder, 
                unmanagedCallConv, 
                returnType);
                            
            if (parameterTypes != null)
            {
                for (i = 0; i < cParams; i++) 
                {
                    sig.AddArgument(parameterTypes[i]);
                }
            }
                                  
            // If there is a non-void return type, push one.
            if (returnType != typeof(void))
                stackchange++;
                
            // Pop off arguments if any.
            if (parameterTypes != null)
                stackchange -= cParams;
                
            // Pop the native function pointer.
            stackchange--;
            UpdateStackSize(OpCodes.Calli, stackchange);

            EnsureCapacity(7);
            Emit(OpCodes.Calli);
            RecordTokenFixup();
            PutInteger4(modBuilder.GetSignatureToken(sig).Token);
        }

        [System.Security.SecuritySafeCritical]  // auto-generated
        public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
        {
            if (methodInfo == null)
                throw new ArgumentNullException("methodInfo");

            if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
                throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), "opcode");

            Contract.EndContractBlock();

            int stackchange = 0;
            int tk = GetMethodToken(methodInfo, optionalParameterTypes, false);

            EnsureCapacity(7);
            InternalEmit(opcode);

            // Push the return value if there is one.
            if (methodInfo.ReturnType != typeof(void))
                stackchange++;
            // Pop the parameters.
            Type[] parameters = methodInfo.GetParameterTypes();
            if (parameters != null)
                stackchange -= parameters.Length;

            // Pop the this parameter if the method is non-static and the
            // instruction is not newobj.
            if (!(methodInfo is SymbolMethod) && methodInfo.IsStatic == false && !(opcode.Equals(OpCodes.Newobj)))
                stackchange--;
            // Pop the optional parameters off the stack.
            if (optionalParameterTypes != null)
                stackchange -= optionalParameterTypes.Length;
            UpdateStackSize(opcode, stackchange);

            RecordTokenFixup();
            PutInteger4(tk);
        }

        public virtual void Emit(OpCode opcode, SignatureHelper signature)
        {
            if (signature == null)
                throw new ArgumentNullException("signature");
            Contract.EndContractBlock();

            int stackchange = 0;
            ModuleBuilder modBuilder = (ModuleBuilder)m_methodBuilder.Module;
            SignatureToken sig = modBuilder.GetSignatureToken(signature);

            int tempVal = sig.Token;

            EnsureCapacity(7);
            InternalEmit(opcode);

            // The only IL instruction that has VarPop behaviour, that takes a
            // Signature token as a parameter is calli.  Pop the parameters and
            // the native function pointer.  To be conservative, do not pop the
            // this pointer since this information is not easily derived from
            // SignatureHelper.
            if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
            {
                Contract.Assert(opcode.Equals(OpCodes.Calli),
                                "Unexpected opcode encountered for StackBehaviour VarPop.");
                // Pop the arguments..
                stackchange -= signature.ArgumentCount;
                // Pop native function pointer off the stack.
                stackchange--;
                UpdateStackSize(opcode, stackchange);
            }

            RecordTokenFixup();
            PutInteger4(tempVal);
        }

        [System.Security.SecuritySafeCritical]  // auto-generated
        [System.Runtime.InteropServices.ComVisible(true)]
        public virtual void Emit(OpCode opcode, ConstructorInfo con)
        {
            if (con == null)
                throw new ArgumentNullException("con");
            Contract.EndContractBlock();

            int stackchange = 0;

            // Constructors cannot be generic so the value of UseMethodDef doesn't matter.
            int tk = GetMethodToken(con, null, true);

            EnsureCapacity(7);
            InternalEmit(opcode);

            // Make a conservative estimate by assuming a return type and no
            // this parameter.
            if (opcode.StackBehaviourPush == StackBehaviour.Varpush)
            {
                // Instruction must be one of call or callvirt.
                Contract.Assert(opcode.Equals(OpCodes.Call) ||
                                opcode.Equals(OpCodes.Callvirt),
                                "Unexpected opcode encountered for StackBehaviour of VarPush.");
                stackchange++;
            }
            if (opcode.StackBehaviourPop == StackBehaviour.Varpop)
            {
                // Instruction must be one of call, callvirt or newobj.
                Contract.Assert(opcode.Equals(OpCodes.Call) ||
                                opcode.Equals(OpCodes.Callvirt) ||
                                opcode.Equals(OpCodes.Newobj),
                                "Unexpected opcode encountered for StackBehaviour of VarPop.");

                Type[] parameters = con.GetParameterTypes();
                if (parameters != null)
                    stackchange -= parameters.Length;
            }
            UpdateStackSize(opcode, stackchange);

            RecordTokenFixup();
            PutInteger4(tk);
        }

        [System.Security.SecuritySafeCritical]  // auto-generated
        public virtual void Emit(OpCode opcode, Type cls)
        {
            // Puts opcode onto the stream and then the metadata token represented
            // by cls.  The location of cls is recorded so that the token can be
            // patched if necessary when persisting the module to a PE.

            int tempVal = 0;
            ModuleBuilder modBuilder = (ModuleBuilder) m_methodBuilder.Module;
            if (opcode == OpCodes.Ldtoken && cls != null && cls.IsGenericTypeDefinition)
            {
                // This gets the token for the generic type definition if cls is one.
                tempVal = modBuilder.GetTypeToken( cls ).Token;
            }
            else
            {
                // This gets the token for the generic type instantiated on the formal parameters
                // if cls is a generic type definition.
                tempVal = modBuilder.GetTypeTokenInternal(cls).Token;
            }

            EnsureCapacity(7);
            InternalEmit(opcode);
            RecordTokenFixup();
            PutInteger4(tempVal);
        }

        public virtual void Emit(OpCode opcode, long arg) {
            EnsureCapacity(11);
            InternalEmit(opcode);
            m_ILStream[m_length++] = (byte) arg;
            m_ILStream[m_length++] = (byte) (arg>>8);
            m_ILStream[m_length++] = (byte) (arg>>16);
            m_ILStream[m_length++] = (byte) (arg>>24);
            m_ILStream[m_length++] = (byte) (arg>>32);
            m_ILStream[m_length++] = (byte) (arg>>40);
            m_ILStream[m_length++] = (byte) (arg>>48);
            m_ILStream[m_length++] = (byte) (arg>>56);
        }

        [System.Security.SecuritySafeCritical]  // auto-generated
        unsafe public virtual void Emit(OpCode opcode, float arg) {
            EnsureCapacity(7);
            InternalEmit(opcode);
            uint tempVal = *(uint*)&arg;
            m_ILStream[m_length++] = (byte) tempVal;
            m_ILStream[m_length++] = (byte) (tempVal>>8);
            m_ILStream[m_length++] = (byte) (tempVal>>16);
            m_ILStream[m_length++] = (byte) (tempVal>>24);
        }

        [System.Security.SecuritySafeCritical]  // auto-generated
        unsafe public virtual void Emit(OpCode opcode, double arg) {
            EnsureCapacity(11);
            InternalEmit(opcode);
            ulong tempVal = *(ulong*)&arg;           
            m_ILStream[m_length++] = (byte) tempVal;
            m_ILStream[m_length++] = (byte) (tempVal>>8);
            m_ILStream[m_length++] = (byte) (tempVal>>16);
            m_ILStream[m_length++] = (byte) (tempVal>>24);
            m_ILStream[m_length++] = (byte) (tempVal>>32);
            m_ILStream[m_length++] = (byte) (tempVal>>40);
            m_ILStream[m_length++] = (byte) (tempVal>>48);
            m_ILStream[m_length++] = (byte) (tempVal>>56);
        }

        public virtual void Emit(OpCode opcode, Label label) 
        {
            // Puts opcode onto the stream and leaves space to include label
            // when fixups are done.  Labels are created using ILGenerator.DefineLabel and
            // their location within the stream is fixed by using ILGenerator.MarkLabel.
            // If a single-byte instruction (designated by the _S suffix in OpCodes.cs) is used,
            // the label can represent a jump of at most 127 bytes along the stream.
            //
            // opcode must represent a branch instruction (although we don't explicitly
            // verify this).  Since branches are relative instructions, label will be replaced with the
            // correct offset to branch during the fixup process.
            
            int tempVal = label.GetLabelValue();
            EnsureCapacity(7);

             
            InternalEmit(opcode);
            if (OpCodes.TakesSingleByteArgument(opcode)) {
                AddFixup(label, m_length, 1);
                m_length++;
            } else {
                AddFixup(label, m_length, 4);
                m_length+=4;
            }
        }

        public virtual void Emit(OpCode opcode, Label[] labels)
        {
            if (labels == null)
                throw new ArgumentNullException("labels");
            Contract.EndContractBlock();

            // Emitting a switch table

            int i;
            int remaining;                  // number of bytes remaining for this switch instruction to be substracted
            // for computing the offset

            int count = labels.Length;

            EnsureCapacity( count * 4 + 7 );
            InternalEmit(opcode);
            PutInteger4(count);
            for ( remaining = count * 4, i = 0; remaining > 0; remaining -= 4, i++ ) {
                AddFixup( labels[i], m_length, remaining );
                m_length += 4;
            }
        }

        public virtual void Emit(OpCode opcode, FieldInfo field)
        {
            ModuleBuilder modBuilder = (ModuleBuilder) m_methodBuilder.Module;
            int tempVal = modBuilder.GetFieldToken( field ).Token;
            EnsureCapacity(7);
            InternalEmit(opcode);
            RecordTokenFixup();
            PutInteger4(tempVal);
        }

        public virtual void Emit(OpCode opcode, String str) 
        {
            // Puts the opcode onto the IL stream followed by the metadata token
            // represented by str.  The location of str is recorded for future
            // fixups if the module is persisted to a PE.

            ModuleBuilder modBuilder = (ModuleBuilder) m_methodBuilder.Module;
            int tempVal = modBuilder.GetStringConstant(str).Token;
            EnsureCapacity(7);
            InternalEmit(opcode);
            PutInteger4(tempVal);
        }

        public virtual void Emit(OpCode opcode, LocalBuilder local)
        {
            // Puts the opcode onto the IL stream followed by the information for local variable local.

            if (local == null)
            {
                throw new ArgumentNullException("local");
            }
            Contract.EndContractBlock();
            int tempVal = local.GetLocalIndex();
            if (local.GetMethodBuilder() != m_methodBuilder)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_UnmatchedMethodForLocal"), "local");
            }
            // If the instruction is a ldloc, ldloca a stloc, morph it to the optimal form.
            if (opcode.Equals(OpCodes.Ldloc))
            {
                switch(tempVal)
                {
                    case 0:
                        opcode = OpCodes.Ldloc_0;
                        break;
                    case 1:
                        opcode = OpCodes.Ldloc_1;
                        break;
                    case 2:
                        opcode = OpCodes.Ldloc_2;
                        break;
                    case 3:
                        opcode = OpCodes.Ldloc_3;
                        break;
                    default:
                        if (tempVal <= 255)
                            opcode = OpCodes.Ldloc_S;
                        break;
                }
            }
            else if (opcode.Equals(OpCodes.Stloc))
            {
                switch(tempVal)
                {
                    case 0:
                        opcode = OpCodes.Stloc_0;
                        break;
                    case 1:
                        opcode = OpCodes.Stloc_1;
                        break;
                    case 2:
                        opcode = OpCodes.Stloc_2;
                        break;
                    case 3:
                        opcode = OpCodes.Stloc_3;
                        break;
                    default:
                        if (tempVal <= 255)
                            opcode = OpCodes.Stloc_S;
                        break;
                }
            }
            else if (opcode.Equals(OpCodes.Ldloca))
            {
                if (tempVal <= 255)
                    opcode = OpCodes.Ldloca_S;
            }

            EnsureCapacity(7);
            InternalEmit(opcode);
             
            if (opcode.OperandType == OperandType.InlineNone)
                return;
            else if (!OpCodes.TakesSingleByteArgument(opcode))
            {
                m_ILStream[m_length++]=(byte) tempVal;
                m_ILStream[m_length++]=(byte) (tempVal>>8);
            }
            else
            {
                //Handle stloc_1, ldloc_1
                if (tempVal > Byte.MaxValue)
                {
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadInstructionOrIndexOutOfBound"));
                }
                m_ILStream[m_length++]=(byte)tempVal;
            }
        }
        #endregion

        #region Exceptions
        public virtual Label BeginExceptionBlock() 
        {
            // Begin an Exception block.  Creating an Exception block records some information,
            // but does not actually emit any IL onto the stream.  Exceptions should be created and
            // marked in the following form:
            //
            // Emit Some IL
            // BeginExceptionBlock
            // Emit the IL which should appear within the "try" block
            // BeginCatchBlock
            // Emit the IL which should appear within the "catch" block
            // Optional: BeginCatchBlock (this can be repeated an arbitrary number of times
            // EndExceptionBlock

            // Delay init
            if (m_exceptions == null)
            {
                m_exceptions = new __ExceptionInfo[DefaultExceptionArraySize];
            }

            if (m_currExcStack == null)
            {
                m_currExcStack = new __ExceptionInfo[DefaultExceptionArraySize];
            }

            if (m_exceptionCount>=m_exceptions.Length) {
                m_exceptions=EnlargeArray(m_exceptions);
            }

            if (m_currExcStackCount>=m_currExcStack.Length) {
                m_currExcStack = EnlargeArray(m_currExcStack);
            }

            Label endLabel = DefineLabel();
            __ExceptionInfo exceptionInfo = new __ExceptionInfo(m_length, endLabel);

            // add the exception to the tracking list
            m_exceptions[m_exceptionCount++] = exceptionInfo;

            // Make this exception the current active exception
            m_currExcStack[m_currExcStackCount++] = exceptionInfo;
            return endLabel;
        }

        public virtual void EndExceptionBlock() {
            if (m_currExcStackCount==0) {
                throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
            }

           // Pop the current exception block
            __ExceptionInfo current = m_currExcStack[m_currExcStackCount-1];
            m_currExcStack[m_currExcStackCount-1] = null;
            m_currExcStackCount--;

            Label endLabel = current.GetEndLabel();
            int state = current.GetCurrentState();

            if (state == __ExceptionInfo.State_Filter ||
                state == __ExceptionInfo.State_Try)
            {
                 
                 
                throw new InvalidOperationException(Environment.GetResourceString("Argument_BadExceptionCodeGen"));
            }

            if (state == __ExceptionInfo.State_Catch) {
                this.Emit(OpCodes.Leave, endLabel);
            } else if (state == __ExceptionInfo.State_Finally || state == __ExceptionInfo.State_Fault) {
                this.Emit(OpCodes.Endfinally);
            }

            //Check if we've alredy set this label.
            //The only reason why we might have set this is if we have a finally block.
            if (m_labelList[endLabel.GetLabelValue()]==-1) {
                MarkLabel(endLabel);
            } else {
                MarkLabel(current.GetFinallyEndLabel());
            }

            current.Done(m_length);
        }

        public virtual void BeginExceptFilterBlock() 
        {
            // Begins a eception filter block.  Emits a branch instruction to the end of the current exception block.

            if (m_currExcStackCount == 0)
                throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));

            __ExceptionInfo current = m_currExcStack[m_currExcStackCount-1];

            Label endLabel = current.GetEndLabel();
            this.Emit(OpCodes.Leave, endLabel);

            current.MarkFilterAddr(m_length);
        }

        public virtual void BeginCatchBlock(Type exceptionType) 
        {
            // Begins a catch block.  Emits a branch instruction to the end of the current exception block.

            if (m_currExcStackCount==0) {
                throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
            }
            __ExceptionInfo current = m_currExcStack[m_currExcStackCount-1];

            if (current.GetCurrentState() == __ExceptionInfo.State_Filter) {
                if (exceptionType != null) {
                    throw new ArgumentException(Environment.GetResourceString("Argument_ShouldNotSpecifyExceptionType"));
                }

                this.Emit(OpCodes.Endfilter);
            } else {
                // execute this branch if previous clause is Catch or Fault
                if (exceptionType==null) {
                    throw new ArgumentNullException("exceptionType");
                }

                Label endLabel = current.GetEndLabel();
                this.Emit(OpCodes.Leave, endLabel);

            }

            current.MarkCatchAddr(m_length, exceptionType);
        }

        public virtual void BeginFaultBlock()
        {
            if (m_currExcStackCount==0) {
                throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
            }
            __ExceptionInfo current = m_currExcStack[m_currExcStackCount-1];

            // emit the leave for the clause before this one.
            Label endLabel = current.GetEndLabel();
            this.Emit(OpCodes.Leave, endLabel);

            current.MarkFaultAddr(m_length);
        }

        public virtual void BeginFinallyBlock() 
        {
            if (m_currExcStackCount==0) {
                throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
            }
            __ExceptionInfo current = m_currExcStack[m_currExcStackCount-1];
            int         state = current.GetCurrentState();
            Label       endLabel = current.GetEndLabel();
            int         catchEndAddr = 0;
            if (state != __ExceptionInfo.State_Try)
            {
                // generate leave for any preceeding catch clause
                this.Emit(OpCodes.Leave, endLabel);                
                catchEndAddr = m_length;
            }
            
            MarkLabel(endLabel);


            Label finallyEndLabel = this.DefineLabel();
            current.SetFinallyEndLabel(finallyEndLabel);
            
            // generate leave for try clause                                                  
            this.Emit(OpCodes.Leave, finallyEndLabel);
            if (catchEndAddr == 0)
                catchEndAddr = m_length;
            current.MarkFinallyAddr(m_length, catchEndAddr);
        }

        #endregion

        #region Labels
        public virtual Label DefineLabel() 
        {
            // Declares a new Label.  This is just a token and does not yet represent any particular location
            // within the stream.  In order to set the position of the label within the stream, you must call
            // Mark Label.

            // Delay init the lable array in case we dont use it
            if (m_labelList == null){
                m_labelList = new int[DefaultLabelArraySize];
            }

            if (m_labelCount>=m_labelList.Length) {
                m_labelList = EnlargeArray(m_labelList);
            }
            m_labelList[m_labelCount]=-1;
            return new Label(m_labelCount++);
        }

        public virtual void MarkLabel(Label loc) 
        {
            // Defines a label by setting the position where that label is found within the stream.
            // Does not allow a label to be defined more than once.

            int labelIndex = loc.GetLabelValue();

            //This should never happen.
            if (labelIndex<0 || labelIndex>=m_labelList.Length) {
                throw new ArgumentException (Environment.GetResourceString("Argument_InvalidLabel"));
            }

            if (m_labelList[labelIndex]!=-1) {
                throw new ArgumentException (Environment.GetResourceString("Argument_RedefinedLabel"));
            }

            m_labelList[labelIndex]=m_length;
        }

        #endregion

        #region IL Macros
        public virtual void ThrowException(Type excType)
        {
            // Emits the il to throw an exception

            if (excType==null) {
                throw new ArgumentNullException("excType");
            }

            if (!excType.IsSubclassOf(typeof(Exception)) && excType!=typeof(Exception)) {
                throw new ArgumentException(Environment.GetResourceString("Argument_NotExceptionType"));
            }
            Contract.EndContractBlock();
            ConstructorInfo con = excType.GetConstructor(Type.EmptyTypes);
            if (con==null) {
                throw new ArgumentException(Environment.GetResourceString("Argument_MissingDefaultConstructor"));
            }
            this.Emit(OpCodes.Newobj, con);
            this.Emit(OpCodes.Throw);
        }

        private static Type GetConsoleType()
        {
#if FEATURE_LEGACYSURFACE
            return typeof(Console);
#else
            return Type.GetType(
                "System.Console, System.Console, Version=4.0.0.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken, 
                throwOnError: true);
#endif
        }

        public virtual void EmitWriteLine(String value)
        {
            // Emits the IL to call Console.WriteLine with a string.

            Emit(OpCodes.Ldstr, value);
            Type[] parameterTypes = new Type[1];
            parameterTypes[0] = typeof(String);
            MethodInfo mi = GetConsoleType().GetMethod("WriteLine", parameterTypes);
            Emit(OpCodes.Call, mi);
        }

        public virtual void EmitWriteLine(LocalBuilder localBuilder) 
        {
            // Emits the IL necessary to call WriteLine with lcl.  It is
            // an error to call EmitWriteLine with a lcl which is not of
            // one of the types for which Console.WriteLine implements overloads. (e.g.
            // we do *not* call ToString on the locals.

            Object          cls;
            if (m_methodBuilder==null)
            {
                throw new ArgumentException(Environment.GetResourceString("InvalidOperation_BadILGeneratorUsage"));
            }

            MethodInfo prop = GetConsoleType().GetMethod("get_Out");
            Emit(OpCodes.Call, prop);
            Emit(OpCodes.Ldloc, localBuilder);
            Type[] parameterTypes = new Type[1];
            cls = localBuilder.LocalType;
            if (cls is TypeBuilder || cls is EnumBuilder) {
                throw new ArgumentException(Environment.GetResourceString("NotSupported_OutputStreamUsingTypeBuilder"));
            }
            parameterTypes[0] = (Type)cls;
            MethodInfo mi = typeof(TextWriter).GetMethod("WriteLine", parameterTypes);
             if (mi==null) {
                throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), "localBuilder");
            }

            Emit(OpCodes.Callvirt, mi);
        }

        public virtual void EmitWriteLine(FieldInfo fld)
        {
            // Emits the IL necessary to call WriteLine with fld.  It is
            // an error to call EmitWriteLine with a fld which is not of
            // one of the types for which Console.WriteLine implements overloads. (e.g.
            // we do *not* call ToString on the fields.

            Object cls;

            if (fld == null)
            {
                throw new ArgumentNullException("fld");
            }
            Contract.EndContractBlock();
            
            MethodInfo prop = GetConsoleType().GetMethod("get_Out");
            Emit(OpCodes.Call, prop);

            if ((fld.Attributes & FieldAttributes.Static)!=0) {
                Emit(OpCodes.Ldsfld, fld);
            } else {
                Emit(OpCodes.Ldarg, (short)0); //Load the this ref.
                Emit(OpCodes.Ldfld, fld);
            }
            Type[] parameterTypes = new Type[1];
            cls = fld.FieldType;
            if (cls is TypeBuilder || cls is EnumBuilder) {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_OutputStreamUsingTypeBuilder"));
            }
            parameterTypes[0] = (Type)cls;
            MethodInfo mi = typeof(TextWriter).GetMethod("WriteLine", parameterTypes);
            if (mi==null) {
                throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), "fld");
            }
            Emit(OpCodes.Callvirt, mi);
        }

        #endregion

        #region Debug API
        public virtual LocalBuilder DeclareLocal(Type localType)
        {
            return DeclareLocal(localType, false);
        }

        public virtual LocalBuilder DeclareLocal(Type localType, bool pinned)
        {
            // Declare a local of type "local". The current active lexical scope
            // will be the scope that local will live.

            LocalBuilder    localBuilder;

            MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder;
            if (methodBuilder == null) 
                throw new NotSupportedException();

            if (methodBuilder.IsTypeCreated())
            {
                // cannot change method after its containing type has been created
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated"));
            }

            if (localType==null) {
                throw new ArgumentNullException("localType");
            }

            if (methodBuilder.m_bIsBaked) {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked"));
            }

            // add the localType to local signature
            m_localSignature.AddArgument(localType, pinned);

            localBuilder = new LocalBuilder(m_localCount, localType, methodBuilder, pinned);
            m_localCount++;
            return localBuilder;
        }

        public virtual void UsingNamespace(String usingNamespace)
        {
            // Specifying the namespace to be used in evaluating locals and watches
            // for the current active lexical scope.

            if (usingNamespace == null)
                throw new ArgumentNullException("usingNamespace");

            if (usingNamespace.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "usingNamespace");
            Contract.EndContractBlock();

            int index;
            MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder;
            if (methodBuilder == null) 
                throw new NotSupportedException();

            index = methodBuilder.GetILGenerator().m_ScopeTree.GetCurrentActiveScopeIndex();
            if (index == -1)
            {
                methodBuilder.m_localSymInfo.AddUsingNamespace(usingNamespace);
            }
            else
            {
                m_ScopeTree.AddUsingNamespaceToCurrentScope(usingNamespace);
            }
        }

        public virtual void MarkSequencePoint(
            ISymbolDocumentWriter document,
            int startLine,       // line number is 1 based
            int startColumn,     // column is 0 based
            int endLine,         // line number is 1 based
            int endColumn)       // column is 0 based
        {
            if (startLine == 0 || startLine < 0 || endLine == 0 || endLine < 0)
            {
                throw new ArgumentOutOfRangeException("startLine");
            }
            Contract.EndContractBlock();
            m_LineNumberInfo.AddLineNumberInfo(document, m_length, startLine, startColumn, endLine, endColumn);
        }

        public virtual void BeginScope()
        {
            m_ScopeTree.AddScopeInfo(ScopeAction.Open, m_length);
        }

        public virtual void EndScope()
        {
            m_ScopeTree.AddScopeInfo(ScopeAction.Close, m_length);
        }

        public virtual int ILOffset
        {
            get
            {
                return m_length;
            }
        }

        #endregion

        #endregion

#if !FEATURE_CORECLR
        void _ILGenerator.GetTypeInfoCount(out uint pcTInfo)
        {
            throw new NotImplementedException();
        }

        void _ILGenerator.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
        {
            throw new NotImplementedException();
        }

        void _ILGenerator.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
        {
            throw new NotImplementedException();
        }

        void _ILGenerator.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
        {
            throw new NotImplementedException();
        }
#endif
    }

    internal struct __FixupData
    {
        internal Label m_fixupLabel;
        internal int m_fixupPos;
         
        internal int m_fixupInstSize;
    }

    internal sealed class __ExceptionInfo {

        internal const int None             = 0x0000;  //COR_ILEXCEPTION_CLAUSE_NONE
        internal const int Filter           = 0x0001;  //COR_ILEXCEPTION_CLAUSE_FILTER
        internal const int Finally          = 0x0002;  //COR_ILEXCEPTION_CLAUSE_FINALLY
        internal const int Fault            = 0x0004;  //COR_ILEXCEPTION_CLAUSE_FAULT
        internal const int PreserveStack    = 0x0004;  //COR_ILEXCEPTION_CLAUSE_PRESERVESTACK

        internal const int State_Try = 0;
        internal const int State_Filter =1;
        internal const int State_Catch = 2;
        internal const int State_Finally = 3;
        internal const int State_Fault = 4;
        internal const int State_Done = 5;

        internal int m_startAddr;
        internal int []m_filterAddr;
        internal int []m_catchAddr;
        internal int []m_catchEndAddr;
        internal int []m_type;
        internal Type []m_catchClass;
        internal Label m_endLabel;
        internal Label m_finallyEndLabel;
        internal int m_endAddr;
        internal int m_endFinally;
        internal int m_currentCatch;

        int m_currentState;


        //This will never get called.  The values exist merely to keep the
        //compiler happy.
        private __ExceptionInfo() {
            m_startAddr = 0;
            m_filterAddr = null;
            m_catchAddr = null;
            m_catchEndAddr = null;
            m_endAddr = 0;
            m_currentCatch = 0;
            m_type = null;
            m_endFinally = -1;
            m_currentState = State_Try;
        }

        internal __ExceptionInfo(int startAddr, Label endLabel) {
            m_startAddr=startAddr;
            m_endAddr=-1;
            m_filterAddr=new int[4];
            m_catchAddr=new int[4];
            m_catchEndAddr=new int[4];
            m_catchClass=new Type[4];
            m_currentCatch=0;
            m_endLabel=endLabel;
            m_type=new int[4];
            m_endFinally=-1;
            m_currentState = State_Try;
        }

        private void MarkHelper(
            int         catchorfilterAddr,      // the starting address of a clause
            int         catchEndAddr,           // the end address of a previous catch clause. Only use when finally is following a catch
            Type        catchClass,             // catch exception type
            int         type)                   // kind of clause
        {
            if (m_currentCatch>=m_catchAddr.Length) {
                m_filterAddr=ILGenerator.EnlargeArray(m_filterAddr);
                m_catchAddr=ILGenerator.EnlargeArray(m_catchAddr);
                m_catchEndAddr=ILGenerator.EnlargeArray(m_catchEndAddr);
                m_catchClass=ILGenerator.EnlargeArray(m_catchClass);
                m_type = ILGenerator.EnlargeArray(m_type);
            }
            if (type == Filter)
            {
                m_type[m_currentCatch]=type;
                m_filterAddr[m_currentCatch] = catchorfilterAddr;
                m_catchAddr[m_currentCatch] = -1;
                if (m_currentCatch > 0)
                {
                    Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
                    m_catchEndAddr[m_currentCatch-1] = catchorfilterAddr;
                }
            }
            else
            {
                // catch or Fault clause
                m_catchClass[m_currentCatch]=catchClass;
                if (m_type[m_currentCatch] != Filter)
                {
                    m_type[m_currentCatch]=type;
                }
                m_catchAddr[m_currentCatch]=catchorfilterAddr;
                if (m_currentCatch > 0)
                {
                        if (m_type[m_currentCatch] != Filter)
                        {
                            Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
                            m_catchEndAddr[m_currentCatch-1] = catchEndAddr;
                        }
                }
                m_catchEndAddr[m_currentCatch]=-1;  
                m_currentCatch++;
            }

            if (m_endAddr==-1)
            {
                m_endAddr=catchorfilterAddr;
            }
        }

        internal void MarkFilterAddr(int filterAddr)
        {
            m_currentState = State_Filter;
            MarkHelper(filterAddr, filterAddr, null, Filter);
        }

        internal void MarkFaultAddr(int faultAddr)
        {
            m_currentState = State_Fault;
            MarkHelper(faultAddr, faultAddr, null, Fault);
        }

        internal void MarkCatchAddr(int catchAddr, Type catchException) {
            m_currentState = State_Catch;
            MarkHelper(catchAddr, catchAddr, catchException, None);
        }

        internal void MarkFinallyAddr(int finallyAddr, int endCatchAddr) {
            if (m_endFinally!=-1) {
                throw new ArgumentException(Environment.GetResourceString("Argument_TooManyFinallyClause"));
            } else {
                m_currentState = State_Finally;
                m_endFinally=finallyAddr;
            }
            MarkHelper(finallyAddr, endCatchAddr, null, Finally);
        }

        internal void Done(int endAddr) {
            Contract.Assert(m_currentCatch > 0,"m_currentCatch > 0");
            Contract.Assert(m_catchAddr[m_currentCatch-1] > 0,"m_catchAddr[m_currentCatch-1] > 0");
            Contract.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
            m_catchEndAddr[m_currentCatch-1] = endAddr;
            m_currentState = State_Done;
        }

        internal int GetStartAddress() {
            return m_startAddr;
        }

        internal int GetEndAddress() {
            return m_endAddr;
        }

        internal int GetFinallyEndAddress() {
            return m_endFinally;
        }

        internal Label GetEndLabel() {
            return m_endLabel;
        }

        internal int [] GetFilterAddresses() {
            return m_filterAddr;
        }

        internal int [] GetCatchAddresses() {
            return m_catchAddr;
        }

        internal int [] GetCatchEndAddresses() {
            return m_catchEndAddr;
        }

        internal Type [] GetCatchClass() {
            return m_catchClass;
        }

        internal int GetNumberOfCatches() {
            return m_currentCatch;
        }

        internal int[] GetExceptionTypes() {
            return m_type;
        }

        internal void SetFinallyEndLabel(Label lbl) {
            m_finallyEndLabel=lbl;
        }

        internal Label GetFinallyEndLabel() {
            return m_finallyEndLabel;
        }

        // Specifies whether exc is an inner exception for "this".  The way
        // its determined is by comparing the end address for the last catch
        // clause for both exceptions.  If they're the same, the start address
        // for the exception is compared.
        // WARNING: This is not a generic function to determine the innerness
        // of an exception.  This is somewhat of a mis-nomer.  This gives a
        // random result for cases where the two exceptions being compared do
        // not having a nesting relation. 
        internal bool IsInner(__ExceptionInfo exc) {
            Contract.Requires(exc != null);
            Contract.Assert(m_currentCatch > 0,"m_currentCatch > 0");
            Contract.Assert(exc.m_currentCatch > 0,"exc.m_currentCatch > 0");

            int exclast = exc.m_currentCatch - 1;
            int last = m_currentCatch - 1;

            if (exc.m_catchEndAddr[exclast]  < m_catchEndAddr[last])
                return true;
            else if (exc.m_catchEndAddr[exclast] == m_catchEndAddr[last])
            {
                Contract.Assert(exc.GetEndAddress() != GetEndAddress(),
                                "exc.GetEndAddress() != GetEndAddress()");
                if (exc.GetEndAddress() > GetEndAddress())
                    return true;
            }
            return false;
        }

        // 0 indicates in a try block
        // 1 indicates in a filter block
        // 2 indicates in a catch block
        // 3 indicates in a finally block
        // 4 indicates Done
        internal int GetCurrentState() {
            return m_currentState;
        }
    }


    /***************************
    *
    * Scope Tree is a class that track the scope structure within a method body
    * It keeps track two parallel array. m_ScopeAction keeps track the action. It can be
    * OpenScope or CloseScope. m_iOffset records the offset where the action
    * takes place.
    *
    ***************************/
    [Serializable]
    enum ScopeAction
    {
        Open        = 0x0,
        Close       = 0x1,
    }

    internal sealed class ScopeTree
    {
        internal ScopeTree()
        {
            // initialize data variables
            m_iOpenScopeCount = 0;
            m_iCount = 0;
        }

        /***************************
        *
        * Find the current active lexcial scope. For example, if we have
        * "Open Open Open Close",
        * we will return 1 as the second BeginScope is currently active.
        *
        ***************************/
        internal int GetCurrentActiveScopeIndex()
        {
            int         cClose = 0;
            int         i = m_iCount - 1;

            if (m_iCount == 0)
            {
                return -1;
            }
            for (; cClose > 0 || m_ScopeActions[i] == ScopeAction.Close; i--)
            {
                if (m_ScopeActions[i] == ScopeAction.Open)
                {
                    cClose--;
                }
                else
                    cClose++;
            }

            return i;
        }

        internal void AddLocalSymInfoToCurrentScope(
            String          strName,
            byte[]          signature,
            int             slot,
            int             startOffset,
            int             endOffset)
        {
            int         i = GetCurrentActiveScopeIndex();
            if (m_localSymInfos[i] == null)
            {
                m_localSymInfos[i] = new LocalSymInfo();
            }
            m_localSymInfos[i].AddLocalSymInfo(strName, signature, slot, startOffset, endOffset);
        }

        internal void AddUsingNamespaceToCurrentScope(
            String          strNamespace)
        {
            int         i = GetCurrentActiveScopeIndex();
            if (m_localSymInfos[i] == null)
            {
                m_localSymInfos[i] = new LocalSymInfo();
            }
            m_localSymInfos[i].AddUsingNamespace(strNamespace);
        }

        internal void AddScopeInfo(ScopeAction sa, int iOffset)
        {
            if (sa == ScopeAction.Close && m_iOpenScopeCount <=0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_UnmatchingSymScope"));
            }
            Contract.EndContractBlock();

            // make sure that arrays are large enough to hold addition info
            EnsureCapacity();             
             
             
            m_ScopeActions[m_iCount] = sa;
            m_iOffsets[m_iCount] = iOffset;
            m_localSymInfos[m_iCount] = null;
            checked { m_iCount++; }
            if (sa == ScopeAction.Open)
            {
                m_iOpenScopeCount++;
            }
            else
                m_iOpenScopeCount--;

        }

        /**************************
        *
        * Helper to ensure arrays are large enough
        *
        **************************/
        internal void EnsureCapacity()
        {
            if (m_iCount == 0)
            {
                // First time. Allocate the arrays.
                m_iOffsets = new int[InitialSize];
                m_ScopeActions = new ScopeAction[InitialSize];
                m_localSymInfos = new LocalSymInfo[InitialSize];
            }
            else if (m_iCount == m_iOffsets.Length)
            {
                // the arrays are full. Enlarge the arrays
                // It would probably be simpler to just use Lists here.
                int newSize = checked(m_iCount * 2);
                int[] temp = new int[newSize];
                Array.Copy(m_iOffsets, 0, temp, 0, m_iCount);
                m_iOffsets = temp;

                ScopeAction[] tempSA = new ScopeAction[newSize];
                Array.Copy(m_ScopeActions, 0, tempSA, 0, m_iCount);
                m_ScopeActions = tempSA;

                LocalSymInfo[] tempLSI = new LocalSymInfo[newSize];
                Array.Copy(m_localSymInfos, 0, tempLSI, 0, m_iCount);
                m_localSymInfos = tempLSI;
            }
        }

        #if FEATURE_CORECLR
        [System.Security.SecurityCritical] // auto-generated
        #endif
        internal void EmitScopeTree(ISymbolWriter symWriter)
        {
            int         i;
            for (i = 0; i < m_iCount; i++)
            {
                if (m_ScopeActions[i] == ScopeAction.Open)
                {
                    symWriter.OpenScope(m_iOffsets[i]);
                }
                else
                {
                    symWriter.CloseScope(m_iOffsets[i]);
                }
                if (m_localSymInfos[i] != null)
                {
                    m_localSymInfos[i].EmitLocalSymInfo(symWriter);
                }
            }
        }

        internal int[]          m_iOffsets;                 // array of offsets
        internal ScopeAction[]  m_ScopeActions;             // array of scope actions
        internal int            m_iCount;                   // how many entries in the arrays are occupied
        internal int            m_iOpenScopeCount;          // keep track how many scopes are open
        internal const int      InitialSize = 16;
        internal LocalSymInfo[] m_localSymInfos;            // keep track debugging local information
    }


    /***************************
    *
    * This class tracks the line number info
    *
    ***************************/
    internal sealed class LineNumberInfo
    {
        internal LineNumberInfo()
        {
            // initialize data variables
            m_DocumentCount = 0;
            m_iLastFound = 0;
        }

        internal void AddLineNumberInfo(
            ISymbolDocumentWriter document,
            int             iOffset,
            int             iStartLine,
            int             iStartColumn,
            int             iEndLine,
            int             iEndColumn)
        {
            int         i;
            
            // make sure that arrays are large enough to hold addition info
            i = FindDocument(document);
            
            Contract.Assert(i < m_DocumentCount, "Bad document look up!");
            m_Documents[i].AddLineNumberInfo(document, iOffset, iStartLine, iStartColumn, iEndLine, iEndColumn);
        }
        
        // Find a REDocument representing document. If we cannot find one, we will add a new entry into
        // the REDocument array.
        private int FindDocument(ISymbolDocumentWriter document)
        {
            int         i;
            
            // This is an optimization. The chance that the previous line is coming from the same
            // document is very high.
            if (m_iLastFound < m_DocumentCount && m_Documents[m_iLastFound].m_document == document)
                return m_iLastFound;
                
            for (i = 0; i < m_DocumentCount; i++)
            {
                if (m_Documents[i].m_document == document)
                {
                    m_iLastFound = i;
                    return m_iLastFound;
                }
            }
            
            // cannot find an existing document so add one to the array                                       
            EnsureCapacity();
            m_iLastFound = m_DocumentCount;
            m_Documents[m_iLastFound] = new REDocument(document);
            checked { m_DocumentCount++; }
            return m_iLastFound;
        }

        /**************************
        *
        * Helper to ensure arrays are large enough
        *
        **************************/
        private void EnsureCapacity()
        {
            if (m_DocumentCount == 0)
            {
                // First time. Allocate the arrays.
                m_Documents = new REDocument[InitialSize];
            }
            else if (m_DocumentCount == m_Documents.Length)
            {
                // the arrays are full. Enlarge the arrays
                REDocument[] temp = new REDocument [m_DocumentCount * 2];
                Array.Copy(m_Documents, 0, temp, 0, m_DocumentCount);
                m_Documents = temp;
            }
        }

        #if FEATURE_CORECLR
        [System.Security.SecurityCritical] // auto-generated
        #endif
        internal void EmitLineNumberInfo(ISymbolWriter symWriter)
        {
            for (int i = 0; i < m_DocumentCount; i++)
                m_Documents[i].EmitLineNumberInfo(symWriter);
        }

        private int          m_DocumentCount;         // how many documents that we have right now
        private REDocument[] m_Documents;             // array of documents
        private const int    InitialSize = 16;
        private int          m_iLastFound;
    }


    /***************************
    *
    * This class tracks the line number info
    *
    ***************************/
    internal sealed class REDocument
    {
        internal REDocument(ISymbolDocumentWriter document)
        {
            // initialize data variables
            m_iLineNumberCount = 0;
            m_document = document;
        }

        internal void AddLineNumberInfo(
            ISymbolDocumentWriter document,
            int             iOffset,
            int             iStartLine,
            int             iStartColumn,
            int             iEndLine,
            int             iEndColumn)
        {
            Contract.Assert(document == m_document, "Bad document look up!");
            
            // make sure that arrays are large enough to hold addition info
            EnsureCapacity();
            
            m_iOffsets[m_iLineNumberCount] = iOffset;
            m_iLines[m_iLineNumberCount] = iStartLine;
            m_iColumns[m_iLineNumberCount] = iStartColumn;
            m_iEndLines[m_iLineNumberCount] = iEndLine;
            m_iEndColumns[m_iLineNumberCount] = iEndColumn;
            checked { m_iLineNumberCount++; }
        }

        /**************************
        *
        * Helper to ensure arrays are large enough
        *
        **************************/
        private void EnsureCapacity()
        {
            if (m_iLineNumberCount == 0)
            {
                // First time. Allocate the arrays.
                m_iOffsets = new int[InitialSize];
                m_iLines = new int[InitialSize];
                m_iColumns = new int[InitialSize];
                m_iEndLines = new int[InitialSize];
                m_iEndColumns = new int[InitialSize];
            }
            else if (m_iLineNumberCount == m_iOffsets.Length)
            {            
                // the arrays are full. Enlarge the arrays
                // It would probably be simpler to just use Lists here
                int newSize = checked(m_iLineNumberCount * 2);
                int[] temp = new int [newSize];
                Array.Copy(m_iOffsets, 0, temp, 0, m_iLineNumberCount);
                m_iOffsets = temp;

                temp = new int [newSize];
                Array.Copy(m_iLines, 0, temp, 0, m_iLineNumberCount);
                m_iLines = temp;

                temp = new int [newSize];
                Array.Copy(m_iColumns, 0, temp, 0, m_iLineNumberCount);
                m_iColumns = temp;

                temp = new int [newSize];
                Array.Copy(m_iEndLines, 0, temp, 0, m_iLineNumberCount);
                m_iEndLines = temp;

                temp = new int [newSize];
                Array.Copy(m_iEndColumns, 0, temp, 0, m_iLineNumberCount);
                m_iEndColumns = temp;
            }
        }

        #if FEATURE_CORECLR
        [System.Security.SecurityCritical] // auto-generated
        #endif
        internal void EmitLineNumberInfo(ISymbolWriter symWriter)
        {
            int[]       iOffsetsTemp;
            int[]       iLinesTemp;
            int[]       iColumnsTemp;
            int[]       iEndLinesTemp;
            int[]       iEndColumnsTemp;

            if (m_iLineNumberCount == 0)
                return;
            // reduce the array size to be exact
            iOffsetsTemp = new int [m_iLineNumberCount];
            Array.Copy(m_iOffsets, 0, iOffsetsTemp, 0, m_iLineNumberCount);

            iLinesTemp = new int [m_iLineNumberCount];
            Array.Copy(m_iLines, 0, iLinesTemp, 0, m_iLineNumberCount);

            iColumnsTemp = new int [m_iLineNumberCount];
            Array.Copy(m_iColumns, 0, iColumnsTemp, 0, m_iLineNumberCount);

            iEndLinesTemp = new int [m_iLineNumberCount];
            Array.Copy(m_iEndLines, 0, iEndLinesTemp, 0, m_iLineNumberCount);

            iEndColumnsTemp = new int [m_iLineNumberCount];
            Array.Copy(m_iEndColumns, 0, iEndColumnsTemp, 0, m_iLineNumberCount);

            symWriter.DefineSequencePoints(m_document, iOffsetsTemp, iLinesTemp, iColumnsTemp, iEndLinesTemp, iEndColumnsTemp); 
        }

        private  int[]       m_iOffsets;                 // array of offsets
        private  int[]       m_iLines;                   // array of offsets
        private  int[]       m_iColumns;                 // array of offsets
        private  int[]       m_iEndLines;                // array of offsets
        private  int[]       m_iEndColumns;              // array of offsets
        internal ISymbolDocumentWriter m_document;       // The ISymbolDocumentWriter that this REDocument is tracking.
        private  int         m_iLineNumberCount;         // how many entries in the arrays are occupied
        private  const int   InitialSize = 16;
    }       // end of REDocument
}