Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ObjectModel.cs « profiler-decoder-library « Mono.Profiler - github.com/mono/mono-tools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4d2ef4c3a975327a52131e4dabee5637c567c530 (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
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
// Author:
// Massimiliano Mantione (massi@ximian.com)
//
// (C) 2008 Novell, Inc  http://www.novell.com
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Collections.Generic;

namespace  Mono.Profiler {
	public class LoadedClass : BaseLoadedClass, IHeapItemSetStatisticsSubject {
		uint allocatedBytes;
		public uint AllocatedBytes {
			get {
				return allocatedBytes;
			}
		}
		uint currentlyAllocatedBytes;
		public uint CurrentlyAllocatedBytes {
			get {
				return currentlyAllocatedBytes;
			}
		}
		public static Comparison<LoadedClass> CompareByAllocatedBytes = delegate (LoadedClass a, LoadedClass b) {
			return a.AllocatedBytes.CompareTo (b.AllocatedBytes);
		};
		
		string IHeapItemSetStatisticsSubject.Description {
			get {
				return Name;
			}
		}
		
		internal void InstanceCreated (uint size, LoadedMethod method, bool jitTime, StackTrace stackTrace) {
			allocatedBytes += size;
			currentlyAllocatedBytes += size;
			if (method != null) {
				Dictionary<uint,AllocationsPerMethod> methods;
				if (! jitTime) {
					if (allocationsPerMethod == null) {
						allocationsPerMethod = new Dictionary<uint,AllocationsPerMethod> ();
					}
					methods = allocationsPerMethod;
				} else {
					if (allocationsPerMethodAtJitTime == null) {
						allocationsPerMethodAtJitTime = new Dictionary<uint,AllocationsPerMethod> ();
					}
					methods = allocationsPerMethodAtJitTime;
				}
				
				AllocationsPerMethod callerMethod;
				if (methods.ContainsKey (method.ID)) {
					callerMethod = methods [method.ID];
				} else {
					callerMethod = new AllocationsPerMethod (method);
					methods.Add (method.ID, callerMethod);
				}
				callerMethod.Allocation (size, stackTrace);
			}
		}
		
		internal void InstanceFreed (uint size) {
			currentlyAllocatedBytes -= size;
		}
		
		public abstract class AllocationsPerItem<T> {
			protected T item;
			uint allocatedBytes;
			public uint AllocatedBytes {
				get {
					return allocatedBytes;
				}
			}
			uint allocatedInstances;
			public uint AllocatedInstances {
				get {
					return allocatedInstances;
				}
			}
			protected void InternalAllocation (uint allocatedBytes) {
				this.allocatedBytes += allocatedBytes;
				this.allocatedInstances ++;
			}
			
			public static Comparison<AllocationsPerItem<T>> CompareByAllocatedBytes = delegate (AllocationsPerItem<T> a, AllocationsPerItem<T> b) {
				return a.AllocatedBytes.CompareTo (b.AllocatedBytes);
			};
			public static Comparison<AllocationsPerItem<T>> CompareByAllocatedInstances = delegate (AllocationsPerItem<T> a, AllocationsPerItem<T> b) {
				return a.AllocatedInstances.CompareTo (b.AllocatedInstances);
			};
			
			protected AllocationsPerItem (T item) {
				this.item = item;
				allocatedInstances = 0;
				allocatedBytes = 0;
			}
		}
		public class AllocationsPerMethod : AllocationsPerItem<LoadedMethod> {
			public LoadedMethod Method {
				get {
					return item;
				}
			}
			
			Dictionary<uint,AllocationsPerStackTrace> stackTraces;
			public AllocationsPerStackTrace[] StackTraces {
				get {
					if (stackTraces != null) {
						AllocationsPerStackTrace[] result = new AllocationsPerStackTrace [stackTraces.Count];
						stackTraces.Values.CopyTo (result, 0);
						return result;
					} else {
						return new AllocationsPerStackTrace [0];
					}
				}
			}
			public int StackTracesCount {
				get {
					if (stackTraces != null) {
						return stackTraces.Count;
					} else {
						return 0;
					}
				}
			}
			
			internal void Allocation (uint allocatedBytes, StackTrace stackTrace) {
				InternalAllocation (allocatedBytes);
				if (stackTrace != null) {
					if (stackTraces == null) {
						stackTraces = new Dictionary<uint,AllocationsPerStackTrace> ();
					}
					
					AllocationsPerStackTrace allocationsPerStackTrace;
					if (stackTraces.ContainsKey (stackTrace.ID)) {
						allocationsPerStackTrace = stackTraces [stackTrace.ID];
					} else {
						allocationsPerStackTrace = new AllocationsPerStackTrace (stackTrace);
						stackTraces [stackTrace.ID] = allocationsPerStackTrace;
					}
					allocationsPerStackTrace.Allocation (allocatedBytes);
				}
			}
			
			public AllocationsPerMethod (LoadedMethod method) : base (method) {
			}
		}
		public class AllocationsPerStackTrace : AllocationsPerItem<StackTrace> {
			public StackTrace Trace {
				get {
					return item;
				}
			}
			
			internal void Allocation (uint allocatedBytes) {
				InternalAllocation (allocatedBytes);
			}
			
			public AllocationsPerStackTrace (StackTrace trace) : base (trace) {
			}
		}
		
		Dictionary<uint,AllocationsPerMethod> allocationsPerMethod;
		public AllocationsPerMethod[] Methods {
			get {
				if (allocationsPerMethod != null) {
					AllocationsPerMethod[] result = new AllocationsPerMethod [allocationsPerMethod.Count];
					allocationsPerMethod.Values.CopyTo (result, 0);
					return result;
				} else {
					return new AllocationsPerMethod [0];
				}
			}
		}
		
		Dictionary<uint,AllocationsPerMethod> allocationsPerMethodAtJitTime;
		public AllocationsPerMethod[] MethodsAtJitTime {
			get {
				if (allocationsPerMethodAtJitTime != null) {
					AllocationsPerMethod[] result = new AllocationsPerMethod [allocationsPerMethodAtJitTime.Count];
					allocationsPerMethodAtJitTime.Values.CopyTo (result, 0);
					return result;
				} else {
					return new AllocationsPerMethod [0];
				}
			}
		}
		public int MethodsAtJitTimeCount {
			get {
				if (allocationsPerMethodAtJitTime != null) {
					return allocationsPerMethodAtJitTime.Values.Count;
				} else {
					return 0;
				}
			}
		}
		
		public static readonly LoadedClass LoadedClassUnavailable = new LoadedClass (0, "(CLASS UNAVAILABLE)", 0);
		
		public LoadedClass (uint id, string name, uint size): base (id, name, size) {
			allocatedBytes = 0;
			currentlyAllocatedBytes = 0;
			allocationsPerMethod = null;
		}
	}
	
	public class StackTrace : IHeapItemSetStatisticsSubject {
		LoadedMethod topMethod;
		public LoadedMethod TopMethod {
			get {
				return topMethod;
			}
		}
		StackTrace caller;
		public StackTrace Caller {
			get {
				return caller;
			}
		}
		bool methodIsBeingJitted;
		public bool MethodIsBeingJitted {
			get {
				return methodIsBeingJitted;
			}
		}
		uint level;
		public uint Level {
			get {
				return level;
			}
		}
		uint id;
		public uint ID {
			get {
				return id;
			}
		}
		
		ulong clicks;
		public ulong Clicks {
			get {
				return clicks;
			}
		}
		uint calls;
		public ulong Calls {
			get {
				return calls;
			}
		}
		
		public void ResetCalls () {
			calls = 0;
			clicks = 0;
		}
		public void RegisterCall (ulong clicks) {
			this.clicks += clicks;
			calls ++;
		}
		
		static StackTrace[] EmptyCalledFrames = new StackTrace [0];
		List<StackTrace> calledFrames;
		public StackTrace[] CalledFrames {
			get {
				if (calledFrames != null) {
					StackTrace[] result = calledFrames.ToArray ();
					Array.Sort (result, CompareByClicks);
					Array.Reverse (result);
					return result;
				} else {
					return EmptyCalledFrames;
				}
			}
		}
		void AddCalledFrame (StackTrace calledFrame) {
			if (calledFrames == null) {
				calledFrames = new List<StackTrace> ();
			}
			calledFrames.Add (calledFrame);
		}
		
		public static Comparison<StackTrace> CompareByClicks = delegate (StackTrace a, StackTrace b) {
			return a.Clicks.CompareTo (b.Clicks);
		};
		public static Comparison<StackTrace> CompareByCalls = delegate (StackTrace a, StackTrace b) {
			return a.Calls.CompareTo (b.Calls);
		};
		
		static List<StackTrace> rootFrames;
		public static StackTrace[] RootFrames {
			get {
				StackTrace[] result = rootFrames.ToArray ();
				Array.Sort (result, CompareByClicks);
				Array.Reverse (result);
				return result;
			}
		}
		
		public void Write (TextWriter writer, int depth, string indentationString) {
			writer.Write ("CallStack of id ");
			writer.Write (id);
			writer.Write ('\n');
			
			StackTrace currentFrame = this;
			while (currentFrame != null) {
				StackTrace nextFrame = currentFrame.Caller;
				for (int i = 0; i < depth; i++) {
					writer.Write (indentationString);
				}
				writer.Write (currentFrame.TopMethod.Name);
				if (nextFrame != null) {
					writer.Write ('\n');
				}
				currentFrame = nextFrame;
			}
		}
		
		public string FullDescription {
			get {
				System.Text.StringBuilder sb = new System.Text.StringBuilder ();
				sb.Append ("CallStack of id ");
				sb.Append (id);
				sb.Append ('\n');
				
				StackTrace currentFrame = this;
				while (currentFrame != null) {
					StackTrace nextFrame = currentFrame.Caller;
					sb.Append ("    ");
					sb.Append (currentFrame.TopMethod.Class.Name);
					sb.Append (".");
					sb.Append (currentFrame.TopMethod.Name);
					if (nextFrame != null) {
						sb.Append ('\n');
					}
					currentFrame = nextFrame;
				}
				
				return sb.ToString ();
			}
		}
		string IHeapItemSetStatisticsSubject.Description {
			get {
				return FullDescription;
			}
		}
		
		StackTrace (LoadedMethod topMethod, StackTrace caller, bool methodIsBeingJitted) {
			this.clicks = 0;
			this.calls = 0;
			this.calledFrames = null;
			this.topMethod = topMethod;
			this.caller = caller;
			if (caller != null) {
				caller.AddCalledFrame (this);
			} else {
				rootFrames.Add (this);
			}
			this.methodIsBeingJitted = methodIsBeingJitted;
			this.level = caller != null ? caller.level + 1 : 1;
			this.id = nextFreeId;
			nextFreeId ++;
		}
		
		bool MatchesCallStack (CallStack.StackFrame stack) {
			StackTrace currentTrace = this;
			
			while ((currentTrace != null) && (stack != null)) {
				if (currentTrace.TopMethod != stack.Method) {
					return false;
				}
				if (currentTrace.methodIsBeingJitted != stack.IsBeingJitted) {
					return false;
				}
				currentTrace = currentTrace.Caller;
				stack = stack.Caller;
			}
			
			if ((currentTrace == null) && (stack == null)) {
				return true;
			} else {
				return false;
			}
		}
		
		internal static StackTrace NewStackTrace (CallStack stack) {
			return NewStackTrace (stack.StackTop);
		}
		
		static uint nextFreeId;
		static Dictionary<uint,List<StackTrace>> [] tracesByLevel;
		public static readonly StackTrace StackTraceUnavailable;
		static StackTrace () {
			rootFrames = new List<StackTrace> ();
			nextFreeId = 0;
			tracesByLevel = new Dictionary<uint,List<StackTrace>> [64];
			StackTraceUnavailable = NewStackTrace (CallStack.StackFrame.StackFrameUnavailable);
		}
		
		static StackTrace NewStackTrace (CallStack.StackFrame frame) {
			if (frame == null) {
				return null;
			}
			
			if (frame.Level >= (uint) tracesByLevel.Length) {
				Dictionary<uint,List<StackTrace>> [] newTracesByLevel = new Dictionary<uint,List<StackTrace>> [frame.Level * 2];
				Array.Copy (tracesByLevel, newTracesByLevel, tracesByLevel.Length);
				tracesByLevel = newTracesByLevel;
			}
			
			Dictionary<uint,List<StackTrace>> tracesByMethod = tracesByLevel [frame.Level];
			if (tracesByLevel [frame.Level] == null) {
				tracesByMethod = new Dictionary<uint,List<StackTrace>> ();
				tracesByLevel [frame.Level] = tracesByMethod;
			}
			
			List<StackTrace> traces;
			if (tracesByMethod.ContainsKey (frame.Method.ID)) {
				traces = tracesByMethod [frame.Method.ID];
			} else {
				traces = new List<StackTrace> ();
				tracesByMethod [frame.Method.ID] = traces;
			}
			
			foreach (StackTrace trace in traces) {
				if (trace.MatchesCallStack (frame)) {
					return trace;
				}
			}
			
			StackTrace callerTrace = NewStackTrace (frame.Caller);
			StackTrace result = new StackTrace (frame.Method, callerTrace, frame.IsBeingJitted);
			traces.Add (result);
			return result;
		}
	}
	
	class CallStack {
		public class StackFrame {
			LoadedMethod method;
			public LoadedMethod Method {
				get {
					return method;
				}
				internal set {
					method = value;
				}
			}
			ulong startCounter;
			public ulong StartCounter {
				get {
					return startCounter;
				}
				internal set {
					startCounter = value;
				}
			}
			bool isBeingJitted;
			public bool IsBeingJitted {
				get {
					return isBeingJitted;
				}
				internal set {
					isBeingJitted = value;
				}
			}
			StackFrame caller;
			public StackFrame Caller {
				get {
					return caller;
				}
				internal set {
					caller = value;
				}
			}
			uint level;
			public uint Level {
				get {
					return level;
				}
			}
			
			public void SetLevel () {
				level = (caller != null) ? (caller.Level + 1) : 1;
			}
			
			public static readonly StackFrame StackFrameUnavailable = new StackFrame (LoadedMethod.LoadedMethodForStackTraceUnavailable, 0, false, null);
			
			internal StackFrame (LoadedMethod method, ulong startCounter, bool isBeingJitted, StackFrame caller) {
				this.method = method;
				this.startCounter = startCounter;
				this.isBeingJitted = isBeingJitted;
				this.caller = caller;
				SetLevel ();
			}
			
			static StackFrame freeFrames = null;
			internal static StackFrame FrameFactory (LoadedMethod method, ulong startCounter, bool isBeingJitted, StackFrame caller) {
				if (freeFrames != null) {
					StackFrame result = freeFrames;
					freeFrames = result.Caller;
					result.Method = method;
					result.startCounter = startCounter;
					result.isBeingJitted = isBeingJitted;
					result.Caller = caller;
					result.SetLevel ();
					return result;
				} else {
					return new StackFrame (method, startCounter, isBeingJitted, caller);
				}
			}
			internal static void FreeFrame (StackFrame frame) {
				frame.Caller = freeFrames;
				freeFrames = frame;
			}
		}
		
		ulong threadId;
		public ulong ThreadId {
			get {
				return threadId;
			}
		}
		
		StackFrame stackTop;
		internal StackFrame StackTop {
			get {
				return stackTop;
			}
		}
		
		public uint Depth {
			get {
				return (stackTop != null) ? stackTop.Level : 0;
			}
		}
		
		void PopMethod (LoadedMethod method, ulong counter, bool isBeingJitted) {
			while (stackTop != null) {
				LoadedMethod topMethod = stackTop.Method;
				bool topMethodIsBeingJitted = stackTop.IsBeingJitted;
				StackFrame callerFrame = stackTop.Caller;
				LoadedMethod callerMethod = (callerFrame != null)? callerFrame.Method : null;
				
				if (! topMethodIsBeingJitted) {
					ulong delta = counter - stackTop.StartCounter;
					
					topMethod.MethodCalled (delta, callerMethod);
					StackTrace trace = StackTrace.NewStackTrace (this);
					if (trace != null) {
						trace.RegisterCall (delta);
					}
				}
				
				StackFrame.FreeFrame (stackTop);
				stackTop = callerFrame;
				if ((topMethod == method) && (topMethodIsBeingJitted == isBeingJitted)) {
					return;
				}
			}
		}
		
		internal void MethodEnter (LoadedMethod method, ulong counter) {
			stackTop = StackFrame.FrameFactory (method, counter, false, stackTop);
		}
		internal void MethodExit (LoadedMethod method, ulong counter) {
			StackTrace trace = StackTrace.NewStackTrace (this);
			if (trace != null) {
				trace.RegisterCall (counter);
			}
			PopMethod (method, counter, false);
		}
		internal void TopMethodExit (ulong counter) {
			MethodExit (stackTop.Method, counter);
		}
		
		internal void MethodJitStart (LoadedMethod method, ulong counter) {
			stackTop = StackFrame.FrameFactory (method, counter, true, stackTop);
		}
		internal void MethodJitEnd (LoadedMethod method, ulong counter) {
			PopMethod (method, counter, true);
		}
		
		internal void AdjustStack (uint lastValidFrame, uint topSectionSize, StackSectionElement<LoadedClass,LoadedMethod>[] topSection) {
			if (Depth >= lastValidFrame) {
				while (Depth > lastValidFrame) {
					StackFrame lastTop = stackTop;
					stackTop = stackTop.Caller;
					StackFrame.FreeFrame (lastTop);
				}
				for (int i = (int) topSectionSize - 1; i >= 0; i--) {
					stackTop = StackFrame.FrameFactory (topSection [i].Method, 0, topSection [i].IsBeingJitted, stackTop);
				}
			} else {
				throw new Exception (String.Format ("Depth is {0} but lastValidFrame is {1}", Depth, lastValidFrame));
			}
		}
		
		internal CallStack (ulong threadId) {
			this.threadId = threadId;
			stackTop = null;
		}
	}
	
	
	public class StatisticalHitItemCallInformation {
		IStatisticalHitItem item;
		public IStatisticalHitItem Item {
			get {
				return item;
			}
		}
		uint calls;
		public uint Calls {
			get {
				return calls;
			}
			internal set {
				calls = value;
			}
		}
		internal void AddCall () {
			calls ++;
		}
		public StatisticalHitItemCallInformation (IStatisticalHitItem item) {
			this.item = item;
			this.calls = 0;
		}
	}
	
	public class StatisticalHitItemCallCounts {
		public static Comparison<IStatisticalHitItem> CompareByStatisticalHits = delegate (IStatisticalHitItem a, IStatisticalHitItem b) {
			int result = a.StatisticalHits.CompareTo (b.StatisticalHits);
			if ((result == 0) && a.HasCallCounts && b.HasCallCounts) {
				StatisticalHitItemCallCounts aCounts = a.CallCounts;
				StatisticalHitItemCallCounts bCounts = b.CallCounts;
				result = aCounts.CallersCount.CompareTo (bCounts.CallersCount);
				if (result == 0) {
					result = aCounts.CalleesCount.CompareTo (bCounts.CalleesCount);
				}
			}
			return result;
		};
		
		List<StatisticalHitItemCallInformation> callers;
		List<StatisticalHitItemCallInformation> callees;
		
		static StatisticalHitItemCallInformation[] GetSortedInfo (List<StatisticalHitItemCallInformation> list) {
			StatisticalHitItemCallInformation[] result = list.ToArray ();
			Array.Sort (result, delegate (StatisticalHitItemCallInformation a, StatisticalHitItemCallInformation b) {
				return a.Calls.CompareTo (b.Calls);
			});
			Array.Reverse (result);
			return result;
		}
		
		public StatisticalHitItemCallInformation[] Callers {
			get {
				return GetSortedInfo (callers);
			}
		}
		public StatisticalHitItemCallInformation[] Callees {
			get {
				return GetSortedInfo (callees);
			}
		}
				
		public int CallersCount {
			get {
				return callers.Count;
			}
		}
		public int CalleesCount {
			get {
				return callees.Count;
			}
		}
		
		void AddCall (List<StatisticalHitItemCallInformation> list, IStatisticalHitItem item) {
			foreach (StatisticalHitItemCallInformation info in list) {
				if (info.Item == item) {
					info.AddCall ();
					return;
				}
			}
			StatisticalHitItemCallInformation newInfo = new StatisticalHitItemCallInformation (item);
			newInfo.AddCall ();
			list.Add (newInfo);
		}
		
		internal void AddCaller (IStatisticalHitItem caller) {
			AddCall (callers, caller);
		}
		internal void AddCallee (IStatisticalHitItem callee) {
			AddCall (callees, callee);
		}
		
		public StatisticalHitItemCallCounts () {
			callers = new List<StatisticalHitItemCallInformation> ();
			callees = new List<StatisticalHitItemCallInformation> ();
		}
	}
	
	public interface IStatisticalHitItem {
		string Name {get;}
		uint StatisticalHits {get;}
		bool HasCallCounts {get;}
		StatisticalHitItemCallCounts CallCounts {get;}
	}
	
	public class LoadedMethod : BaseLoadedMethod<LoadedClass>, IStatisticalHitItem, IHeapItemSetStatisticsSubject {
		ulong clicks;
		public ulong Clicks {
			get {
				return clicks;
			}
			internal set {
				clicks = value;
			}
		}
		public static Comparison<LoadedMethod> CompareByTotalClicks = delegate (LoadedMethod a, LoadedMethod b) {
			return a.Clicks.CompareTo (b.Clicks);
		};
		public static Comparison<LoadedMethod> CompareByEffectiveClicks = delegate (LoadedMethod a, LoadedMethod b) {
			return (a.Clicks - a.CalledClicks).CompareTo (b.Clicks - b.CalledClicks);
		};
		
		string IHeapItemSetStatisticsSubject.Description {
			get {
				return Class.Name + "." + Name;
			}
		}
		
		ulong calledClicks;
		public ulong CalledClicks {
			get {
				return calledClicks;
			}
			internal set {
				calledClicks = value;
			}
		}
		
		uint statisticalHits;
		public uint StatisticalHits {
			get {
				return statisticalHits;
			}
			internal set {
				statisticalHits = value;
			}
		}
		string IStatisticalHitItem.Name {
			get {
				return Class.Name + "." + this.Name;
			}
		}
		
		StatisticalHitItemCallCounts callCounts;
		public bool HasCallCounts {
			get {
				return (callCounts != null);
			}
		}
		public StatisticalHitItemCallCounts CallCounts {
			get {
				if (callCounts == null) {
					callCounts = new StatisticalHitItemCallCounts ();
				}
				return callCounts;
			}
		}
		
		ulong startJit;
		public ulong StartJit {
			get {
				return startJit;
			}
			internal set {
				startJit = value;
			}
		}
		ulong jitClicks;
		public ulong JitClicks {
			get {
				return jitClicks;
			}
			internal set {
				jitClicks = value;
			}
		}
		public static Comparison<LoadedMethod> CompareByJitClicks = delegate (LoadedMethod a, LoadedMethod b) {
			return a.JitClicks.CompareTo (b.JitClicks);
		};
		
		public class ClicksPerCalledMethod {
			LoadedMethod method;
			public LoadedMethod Method {
				get {
					return method;
				}
			}
			
			ulong clicks;
			public ulong Clicks {
				get {
					return clicks;
				}
				internal set {
					clicks = value;
				}
			}
			public static Comparison<ClicksPerCalledMethod> CompareByClicks = delegate (ClicksPerCalledMethod a, ClicksPerCalledMethod b) {
				return a.Clicks.CompareTo (b.Clicks);
			};
			
			public ClicksPerCalledMethod (LoadedMethod method) {
				this.method = method;
				clicks = 0;
			}
		}
		
		Dictionary<uint,ClicksPerCalledMethod> clicksPerCalledMethod;
		public ClicksPerCalledMethod[] Methods {
			get {
				if (clicksPerCalledMethod != null) {
					ClicksPerCalledMethod[] result = new ClicksPerCalledMethod [clicksPerCalledMethod.Count];
					clicksPerCalledMethod.Values.CopyTo (result, 0);
					return result;
				} else {
					return new ClicksPerCalledMethod [0];
				}
			}
		}
		
		public class CallsPerCallerMethod {
			LoadedMethod method;
			public LoadedMethod Callees {
				get {
					return method;
				}
			}
			
			uint calls;
			public uint Calls {
				get {
					return calls;
				}
				internal set {
					calls = value;
				}
			}
			public static Comparison<CallsPerCallerMethod> CompareByCalls = delegate (CallsPerCallerMethod a, CallsPerCallerMethod b) {
				return a.Calls.CompareTo (b.Calls);
			};
			
			public CallsPerCallerMethod (LoadedMethod method) {
				this.method = method;
				calls = 0;
			}
		}
		
		Dictionary<uint,CallsPerCallerMethod> callsPerCallerMethod;
		public CallsPerCallerMethod[] Callers {
			get {
				if (callsPerCallerMethod != null) {
					CallsPerCallerMethod[] result = new CallsPerCallerMethod [callsPerCallerMethod.Count];
					callsPerCallerMethod.Values.CopyTo (result, 0);
					return result;
				} else {
					return new CallsPerCallerMethod [0];
				}
			}
		}
		
		internal void MethodCalled (ulong clicks, LoadedMethod caller) {
			this.clicks += clicks;
			
			if (caller != null) {
				caller.CalleeReturns (this, clicks);
				
				if (callsPerCallerMethod == null) {
					callsPerCallerMethod = new Dictionary<uint,CallsPerCallerMethod> ();
				}
				
				CallsPerCallerMethod callerCalls;
				if (callsPerCallerMethod.ContainsKey (caller.ID)) {
					callerCalls = callsPerCallerMethod [caller.ID];
				} else {
					callerCalls = new CallsPerCallerMethod (caller);
					callsPerCallerMethod.Add (caller.ID, callerCalls);
				}
				
				callerCalls.Calls += 1;
			}
		}
		
		internal void CalleeReturns (LoadedMethod callee, ulong clicks) {
			if (clicksPerCalledMethod == null) {
				clicksPerCalledMethod = new Dictionary<uint,ClicksPerCalledMethod> ();
			}
			
			ClicksPerCalledMethod calledMethodClicks;
			if (clicksPerCalledMethod.ContainsKey (callee.ID)) {
				calledMethodClicks = clicksPerCalledMethod [callee.ID];
			} else {
				calledMethodClicks = new ClicksPerCalledMethod (callee);
				clicksPerCalledMethod.Add (callee.ID, calledMethodClicks);
			}
			
			calledMethodClicks.Clicks += clicks;
			calledClicks += clicks;
		}
		
		public static readonly LoadedMethod LoadedMethodUnavailable = new LoadedMethod (0, LoadedClass.LoadedClassUnavailable, "(METHOD UNAVAILABLE)");
		public static readonly LoadedMethod LoadedMethodForStackTraceUnavailable = new LoadedMethod (0, LoadedClass.LoadedClassUnavailable, "(CALL STACK UNAVAILABLE)");
		
		public LoadedMethod (uint id, LoadedClass c, string name): base (id, c, name) {
			clicks = 0;
			calledClicks = 0;
			jitClicks = 0;
			statisticalHits = 0;
		}
	}
	
	public class UnmanagedFunctionFromID : BaseUnmanagedFunctionFromID<ExecutableMemoryRegion,UnmanagedFunctionFromRegion>, IStatisticalHitItem {
		uint statisticalHits;
		public uint StatisticalHits {
			get {
				return statisticalHits;
			}
			internal set {
				statisticalHits = value;
			}
		}
		
		string IStatisticalHitItem.Name {
			get {
				return "[" + Region.Name + "]" + this.Name;
			}
		}
		
		StatisticalHitItemCallCounts callCounts;
		public bool HasCallCounts {
			get {
				return (callCounts != null);
			}
		}
		public StatisticalHitItemCallCounts CallCounts {
			get {
				if (callCounts == null) {
					callCounts = new StatisticalHitItemCallCounts ();
				}
				return callCounts;
			}
		}
		
		public UnmanagedFunctionFromID (uint id, string name, ExecutableMemoryRegion region) : base (id, name, region) {
			statisticalHits = 0;
		}
	}
	
	public class UnmanagedFunctionFromRegion : BaseUnmanagedFunctionFromRegion<UnmanagedFunctionFromRegion>, IStatisticalHitItem {
		uint statisticalHits;
		public uint StatisticalHits {
			get {
				return statisticalHits;
			}
			internal set {
				statisticalHits = value;
			}
		}
		
		public UnmanagedFunctionFromRegion () {
			statisticalHits = 0;
		}
		
		StatisticalHitItemCallCounts callCounts;
		public bool HasCallCounts {
			get {
				return (callCounts != null);
			}
		}
		public StatisticalHitItemCallCounts CallCounts {
			get {
				if (callCounts == null) {
					callCounts = new StatisticalHitItemCallCounts ();
				}
				return callCounts;
			}
		}
		
		string IStatisticalHitItem.Name {
			get {
				IExecutableMemoryRegion<UnmanagedFunctionFromRegion> r = Region;
				return String.Format ("[{0}({1}-{2})]{3}", r != null ? r.Name : "NULL", this.StartOffset, this.EndOffset, this.Name);
			}
		}
	}
	
	public class ExecutableMemoryRegion : BaseExecutableMemoryRegion<UnmanagedFunctionFromRegion>, IStatisticalHitItem {
		uint statisticalHits;
		public uint StatisticalHits {
			get {
				return statisticalHits;
			}
			internal set {
				statisticalHits = value;
			}
		}
		internal void IncrementStatisticalHits () {
			statisticalHits ++;
		}
		
		string IStatisticalHitItem.Name {
			get {
				return String.Format ("[{0}](UNKNOWN)", this.Name);
			}
		}
		
		StatisticalHitItemCallCounts callCounts;
		public bool HasCallCounts {
			get {
				return (callCounts != null);
			}
		}
		public StatisticalHitItemCallCounts CallCounts {
			get {
				if (callCounts == null) {
					callCounts = new StatisticalHitItemCallCounts ();
				}
				return callCounts;
			}
		}
		
		public ExecutableMemoryRegion (uint id, string name, uint fileOffset, ulong startAddress, ulong endAddress) : base (id, name, fileOffset, startAddress, endAddress) {
				statisticalHits = 0;
		}
	}
	
	public interface IHeapItem : IAllocatedObject<LoadedClass> {
		LoadedMethod AllocatorMethod {get;}
		StackTrace AllocationCallStack {get;}
		bool AllocationHappenedAtJitTime {get;}
	}
	
	public class HeapObject : BaseHeapObject<HeapObject,LoadedClass>, IHeapItem {
		AllocatedObject allocation;
		public AllocatedObject Allocation {
			get {
				return allocation;
			}
			set {
				allocation = value;
				if ((allocation.Class != Class) || (allocation.ID != ID)) {
					throw new Exception (String.Format ("Cannot accept allocation of class {0} and ID {1} for object of class {2} and ID {3}", allocation.Class, allocation.ID, Class, ID));
				}
			}
		}
		public void FindAllocation (ProviderOfPreviousAllocationsSets previousSetsProvider) {
			foreach (HeapItemSet<AllocatedObject> allocations in previousSetsProvider.PreviousAllocationsSets ()) {
				allocation = allocations [ID];
				if (allocation != null) {
					return;
				}
			}
		}
		public LoadedMethod AllocatorMethod {
			get {
				return allocation != null ? allocation.AllocatorMethod : null;
			}
		}
		public StackTrace AllocationCallStack {
			get {
				return allocation != null ? allocation.Trace : null;
			}
		}
		public bool AllocationHappenedAtJitTime {
			get {
				return allocation != null ? allocation.AllocationHappenedAtJitTime : false;
			}
		}
		public HeapObject (ulong ID) : base (ID) {}
	}
	
	public class AllocatedObject : IHeapItem {
		ulong id;
		public ulong ID {
			get {
				return id;
			}
		}
		LoadedClass c;
		public LoadedClass Class {
			get {
				return c;
			}
		}
		uint size;
		public uint Size {
			get {
				return size;
			}
		}
		LoadedMethod caller;
		public LoadedMethod Caller {
			get {
				return caller;
			}
		}
		public LoadedMethod AllocatorMethod {
			get {
				return caller;
			}
		}
		bool jitTime;
		public bool JitTime {
			get {
				return jitTime;
			}
		}
		public bool AllocationHappenedAtJitTime {
			get {
				return jitTime;
			}
		}
		StackTrace trace;
		public StackTrace Trace {
			get {
				return trace;
			}
		}
		public StackTrace AllocationCallStack {
			get {
				return trace;
			}
		}
		
		public AllocatedObject (ulong id, LoadedClass c, uint size, LoadedMethod caller, bool jitTime, StackTrace trace) {
			this.id = id;
			this.c = c;
			this.size = size;
			this.caller = caller;
			this.jitTime = jitTime;
			this.trace = trace;
		}
	}
	
	public class HeapSnapshot : BaseHeapSnapshot<HeapObject,LoadedClass> {
		public class AllocationStatisticsPerClass {
			LoadedClass c;
			public LoadedClass Class {
				get {
					return c;
				}
				internal set {
					c = value;
				}
			}
			uint allocatedBytes;
			public uint AllocatedBytes {
				get {
					return allocatedBytes;
				}
			}
			uint freedBytes;
			public uint FreedBytes {
				get {
					return freedBytes;
				}
			}
			
			public static Comparison<AllocationStatisticsPerClass> CompareByAllocatedBytes = delegate (AllocationStatisticsPerClass a, AllocationStatisticsPerClass b) {
				return a.AllocatedBytes.CompareTo (b.AllocatedBytes);
			};
			
			public void BytesFreed (uint bytes) {
				allocatedBytes -= bytes;
				freedBytes += bytes;
			}
			
			public AllocationStatisticsPerClass (LoadedClass c) {
				this.c = c;
				this.allocatedBytes = c.CurrentlyAllocatedBytes;
				this.freedBytes = 0;
			}
		}
		
		AllocationStatisticsPerClass[] allocationStatistics;
		public AllocationStatisticsPerClass[] AllocationStatistics {
			get {
				int count = 0;
				foreach (AllocationStatisticsPerClass aspc in allocationStatistics) {
					if (aspc != null) {
						count ++;
					}
				}
				AllocationStatisticsPerClass[] result = new AllocationStatisticsPerClass [count];
				count = 0;
				foreach (AllocationStatisticsPerClass aspc in allocationStatistics) {
					if (aspc != null) {
						result [count] = aspc;
						count ++;
					}
				}
				return result;
			}
		}
		
		public void HeapObjectUnreachable (LoadedClass c, uint size) {
			AllocationStatisticsPerClass statisticsPerClass = allocationStatistics [c.ID];
			statisticsPerClass.BytesFreed (size);
		}
		
		public HeapSnapshot (uint collection, ulong startCounter, DateTime startTime, ulong endCounter, DateTime endTime, TimeSpan headerStartTime, LoadedClass[] initialAllocations, bool recordSnapshot) : base (delegate (ulong ID) {return new HeapObject (ID);}, collection, startCounter, startTime, endCounter, endTime, headerStartTime, recordSnapshot) {
			uint maxClassId = 0;
			foreach (LoadedClass c in initialAllocations) {
				if (c.ID > maxClassId) {
					maxClassId = c.ID;
				}
			}
			allocationStatistics = new AllocationStatisticsPerClass [maxClassId + 1];
			foreach (LoadedClass c in initialAllocations) {
				AllocationStatisticsPerClass statisticsPerClass = new AllocationStatisticsPerClass (c);
				allocationStatistics [c.ID] = statisticsPerClass;
			}
		}
	}
	
	public interface IHeapItemFilter<HI> where HI : IHeapItem {
		string Description {
			get;
		}
		bool Filter (HI heapItem);
	}
	public interface IAllocatedObjectFilter : IHeapItemFilter<AllocatedObject> {
	}
	public interface IHeapObjectFilter : IHeapItemFilter<HeapObject> {
	}
	
	public abstract class FilterHeapItemByClass<HI> : IHeapItemFilter<HI> where HI : IHeapItem {
		protected LoadedClass c;
		public LoadedClass Class {
			get {
				return c;
			}
		}
		
		public abstract bool Filter (HI heapItem);
		
		string description;
		public string Description {
			get {
				return description;
			}
		}
		
		public FilterHeapItemByClass (LoadedClass c, string description) {
			this.c = c;
			this.description = description;
		}
	}

	public abstract class FilterHeapItemByAllocatorMethod<HI> : IHeapItemFilter<HI> where HI : IHeapItem {
		protected LoadedMethod allocatorMethod;
		public LoadedMethod AllocatorMethod {
			get {
				return allocatorMethod;
			}
		}
		
		public abstract bool Filter (HI heapItem);
		
		string description;
		public string Description {
			get {
				return description;
			}
		}
		
		protected FilterHeapItemByAllocatorMethod (LoadedMethod allocatorMethod, string description) {
			this.allocatorMethod = allocatorMethod;
			this.description = description;
		}
	}
	
	public class HeapItemWasAllocatedByMethod<HI> : FilterHeapItemByAllocatorMethod<HI> where HI : IHeapItem {
		public override bool Filter (HI heapItem) {
			return heapItem.AllocatorMethod == AllocatorMethod;
		}
		
		public HeapItemWasAllocatedByMethod (LoadedMethod allocatorMethod) : base (allocatorMethod, String.Format ("Object was allocated by {0}", allocatorMethod.Name)) {
		}
	}
	
	public class FilterHeapItemByAllocationCallStack<HI> : IHeapItemFilter<HI> where HI : IHeapItem {
		protected StackTrace allocationCallStack;
		public StackTrace AllocationCallStack {
			get {
				return allocationCallStack;
			}
		}
		
		public bool Filter (HI heapItem) {
			return heapItem.AllocationCallStack == allocationCallStack;
		}
		
		string description;
		public string Description {
			get {
				return description;
			}
		}
		
		public FilterHeapItemByAllocationCallStack (StackTrace allocationCallStack) {
			this.allocationCallStack = allocationCallStack;
			this.description = String.Format ("Allocation has call stack:\n{0}", allocationCallStack.FullDescription);
		}
	}
	
	public class HeapItemIsOfClass<HI> : FilterHeapItemByClass<HI> where HI : IHeapItem {
		protected static string BuildDescription (LoadedClass c) {
			return String.Format ("Object has class {0}", c.Name);
		}
		
		public override bool Filter (HI heapItem) {
			return heapItem.Class == c;
		}
		
		public HeapItemIsOfClass (LoadedClass c) : base (c, BuildDescription (c)) {
		}
	}
	
	public class HeapObjectIsOfClass : HeapItemIsOfClass<HeapObject>, IHeapObjectFilter {
		public HeapObjectIsOfClass (LoadedClass c) : base (c) {
		}
	}
	
	public class AllocatedObjectIsOfClass : HeapItemIsOfClass<AllocatedObject>, IAllocatedObjectFilter {
		public AllocatedObjectIsOfClass (LoadedClass c) : base (c) {
		}
	}
	
	public abstract class FilterHeapObjectByClass : FilterHeapItemByClass<HeapObject>, IHeapObjectFilter {
		protected FilterHeapObjectByClass (LoadedClass c, string description) : base (c, description) {
		}
	}
	
	public class HeapObjectReferencesObjectOfClass : FilterHeapObjectByClass {
		static string BuildDescription (LoadedClass c) {
			return String.Format ("Object references object of class {0}", c.Name);
		}
		
		public override bool Filter (HeapObject heapObject) {
			foreach (HeapObject ho in heapObject.References) {
				if (ho.Class == c) {
					return true;
				}
			}
			return false;
		}
		
		public HeapObjectReferencesObjectOfClass (LoadedClass c) : base (c, BuildDescription (c)) {
		}
	}
	
	public class HeapObjectIsReferencedByObjectOfClass : FilterHeapObjectByClass {
		static string BuildDescription (LoadedClass c) {
			return String.Format ("Object is referenced by object of class {0}", c.Name);
		}
		
		public override bool Filter (HeapObject heapObject) {
			foreach (HeapObject ho in heapObject.BackReferences) {
				if (ho.Class == c) {
					return true;
				}
			}
			return false;
		}
		
		public HeapObjectIsReferencedByObjectOfClass (LoadedClass c) : base (c, BuildDescription (c)) {
		}
	}
	
	public interface IHeapItemSetStatisticsSubject {
		string Description {get;}
		uint ID {get;}
	}
	public delegate HISSS GetHeapItemStatisticsSubject<HI,HISSS> (HI item) where HI : IHeapItem where HISSS : IHeapItemSetStatisticsSubject;
	public delegate HISSBS NewHeapItemStatisticsBySubject<HISSBS,HISSS> (HISSS subject) where HISSS : IHeapItemSetStatisticsSubject where HISSBS : HeapItemSetStatisticsBySubject<HISSS>;
	
	public interface IHeapItemSetStatisticsBySubject {
		IHeapItemSetStatisticsSubject Subject {get;}
		uint ItemsCount {get;}
		uint AllocatedBytes {get;}
	}
	
	public abstract class HeapItemSetStatisticsBySubject<HISSS> : IHeapItemSetStatisticsBySubject where HISSS : IHeapItemSetStatisticsSubject {
		HISSS subject;
		protected HISSS Subject {
			get {
				return subject;
			}
		}
		IHeapItemSetStatisticsSubject IHeapItemSetStatisticsBySubject.Subject {
			get {
				return subject;
			}
		}
		
		uint itemsCount;
		public uint ItemsCount {
			get {
				return itemsCount;
			}
		}
		
		uint allocatedBytes;
		public uint AllocatedBytes {
			get {
				return allocatedBytes;
			}
		}
		
		internal void AddItem (IHeapItem item) {
			itemsCount ++;
			allocatedBytes += item.Size;
		}
		
		protected abstract HISSS GetUnavailableSubject ();
		
		public HeapItemSetStatisticsBySubject (HISSS subject) {
			this.subject = subject != null ? subject : GetUnavailableSubject ();
			this.itemsCount = 0;
			this.allocatedBytes = 0;
		}
		
		public static Comparison<HeapItemSetStatisticsBySubject<HISSS>> CompareByAllocatedBytes = delegate (HeapItemSetStatisticsBySubject<HISSS> a, HeapItemSetStatisticsBySubject<HISSS> b) {
			return a.AllocatedBytes.CompareTo (b.AllocatedBytes);
		};
	}
	
	public class HeapItemSetClassStatistics : HeapItemSetStatisticsBySubject<LoadedClass> {
		public LoadedClass Class {
			get {
				return Subject;
			}
		}
		protected override LoadedClass GetUnavailableSubject () {
			return LoadedClass.LoadedClassUnavailable;
		}
		public HeapItemSetClassStatistics (LoadedClass c) : base (c) {
		}
	}
	
	public class HeapItemSetMethodStatistics : HeapItemSetStatisticsBySubject<LoadedMethod> {
		public LoadedMethod Method {
			get {
				return Subject;
			}
		}
		protected override LoadedMethod GetUnavailableSubject () {
			return LoadedMethod.LoadedMethodUnavailable;
		}
		public HeapItemSetMethodStatistics (LoadedMethod method) : base (method) {
		}
	}
	
	public class HeapItemSetCallStackStatistics : HeapItemSetStatisticsBySubject<StackTrace> {
		public StackTrace CallStack {
			get {
				return Subject;
			}
		}
		protected override StackTrace GetUnavailableSubject () {
			return StackTrace.StackTraceUnavailable;
		}
		public HeapItemSetCallStackStatistics (StackTrace callStack) : base (callStack) {
		}
	}
	
	public interface IHeapItemSet {
		bool ContainsItem (ulong id);
		string ShortDescription {get;}
		string LongDescription {get;}
		IHeapItem[] Elements {get;}
		HeapItemSetClassStatistics[] ClassStatistics {get;}
		HeapItemSetMethodStatistics[] AllocatorMethodStatistics {get;}
		HeapItemSetCallStackStatistics[] AllocationCallStackStatistics {get;}
		uint AllocatedBytes {get;}
		bool ObjectAllocationsArePresent {get;}
		void FindObjectAllocations (ProviderOfPreviousAllocationsSets previousSetsProvider);
	}
	
	public interface ProviderOfPreviousAllocationsSets {
		IEnumerable<HeapItemSet<AllocatedObject>> PreviousAllocationsSets ();
	}
	
	public abstract class HeapItemSet<HI> : IHeapItemSet where HI : IHeapItem {
		public static Comparison<HI> CompareHeapItemsByID = delegate (HI a, HI b) {
			return a.ID.CompareTo (b.ID);
		};
		
		string shortDescription;
		public string ShortDescription {
			get {
				return shortDescription;
			}
		}
		string longDescription;
		public string LongDescription {
			get {
				return longDescription;
			}
		}
		HI[] elements;
		public HI[] Elements {
			get {
				return elements;
			}
		}
		IHeapItem[] IHeapItemSet.Elements {
			get {
				IHeapItem[] result = new IHeapItem [elements.Length];
				Array.Copy (elements, result, elements.Length);
				return result;
			}
		}
		HeapItemSetClassStatistics[] classStatistics;
		public HeapItemSetClassStatistics[] ClassStatistics {
			get {
				return classStatistics;
			}
		}
		uint allocatedBytes;
		public uint AllocatedBytes {
			get {
				return allocatedBytes;
			}
		}
		
		protected HISSBS[] BuildStatistics<HISSS,HISSBS> (GetHeapItemStatisticsSubject<HI,HISSS> getSubject, NewHeapItemStatisticsBySubject<HISSBS,HISSS> newStatistics) where HISSS : IHeapItemSetStatisticsSubject where HISSBS : HeapItemSetStatisticsBySubject<HISSS> {
			Dictionary<uint,HISSBS> statistics = new Dictionary<uint,HISSBS> ();
			
			foreach (HI hi in elements) {
				HISSS subject = getSubject (hi);
				HISSBS s;
				uint id;
				if (subject != null) {
					id = subject.ID;
				} else {
					id = 0;;
				}
				if (statistics.ContainsKey (id)) {
					s = statistics [id];
				} else {
					s = newStatistics (subject);
					statistics [id] = s;
				}
				s.AddItem (hi);
			}
			HISSBS[] result = new HISSBS [statistics.Values.Count];
			statistics.Values.CopyTo (result, 0);
			Array.Sort (result, HeapItemSetStatisticsBySubject<HISSS>.CompareByAllocatedBytes);
			Array.Reverse (result);
			
			return result;
		}
		
		HeapItemSetMethodStatistics[] allocatorMethodStatistics;
		public HeapItemSetMethodStatistics[] AllocatorMethodStatistics {
			get {
				if ((allocatorMethodStatistics == null) && ObjectAllocationsArePresent) {
					allocatorMethodStatistics = BuildStatistics<LoadedMethod,HeapItemSetMethodStatistics> (delegate (HI item) {
						return item.AllocatorMethod;
					}, delegate (LoadedMethod m) {
						return new HeapItemSetMethodStatistics (m);
					});
				}
				return allocatorMethodStatistics;
			}
		}
		public bool HasAllocatorMethodStatistics {
			get {
				return allocatorMethodStatistics != null;
			}
		}
		
		HeapItemSetCallStackStatistics[] allocationCallStackStatistics;
		public HeapItemSetCallStackStatistics[] AllocationCallStackStatistics {
			get {
				if ((allocationCallStackStatistics == null) && ObjectAllocationsArePresent) {
					allocationCallStackStatistics = BuildStatistics<StackTrace,HeapItemSetCallStackStatistics> (delegate (HI item) {
						return item.AllocationCallStack;
					}, delegate (StackTrace s) {
						return new HeapItemSetCallStackStatistics (s);
					});
				}
				return allocationCallStackStatistics;
			}
		}
		public bool HasAllocationCallStackStatistics {
			get {
				return allocationCallStackStatistics != null;
			}
		}
		
		
		public void CompareWithSet<OHI> (HeapItemSet<OHI> otherSet, out HeapItemSet<HI> onlyInThisSet, out HeapItemSet<OHI> onlyInOtherSet) where OHI : IHeapItem  {
			HeapItemSetFromComparison<HI,OHI>.PerformComparison<HI,OHI> (this, otherSet, out onlyInThisSet, out onlyInOtherSet);
		}
		
		public HeapItemSet<HI> IntersectWithSet<OHI> (HeapItemSet<OHI> otherSet) where OHI : IHeapItem  {
			return HeapItemSetFromComparison<HI,OHI>.PerformIntersection<HI,OHI> (this, otherSet);
		}
		
		public HI this [ulong id] {
			get {
				int lowIndex = -1;
				int highIndex = elements.Length;
				
				while (true) {
					int span = (highIndex - lowIndex) / 2;
					
					if (span > 0) {
						int middleIndex = lowIndex + span;
						HI middleElement = elements [middleIndex];
						ulong middleID = middleElement.ID;
						if (middleID > id) {
							highIndex = middleIndex;
						} else if (middleID < id) {
							lowIndex = middleIndex;
						} else {
							return middleElement;
						}
					} else {
						return default (HI);
					}
				}
			}
		}
		public HI this [HI item] {
			get {
				return this [item.ID];
			}
		}
		
		public bool ContainsItem (ulong id) {
			return this [id] != null;
		}
		
		public HeapItemSet<HeapObject> ObjectsReferencingItemInSet (HeapItemSet<HeapObject> objectSet) {
			return Mono.Profiler.HeapItemSetFromComparison<HI,HeapObject>.ObjectsReferencingItemInSet (this, objectSet);
		}
		public HeapItemSet<HeapObject> ObjectsReferencedByItemInSet (HeapItemSet<HeapObject> objectSet) {
			return Mono.Profiler.HeapItemSetFromComparison<HI,HeapObject>.ObjectsReferencedByItemInSet (this, objectSet);
		}
		
		static void FindObjectAllocations (HeapItemSet<HeapObject> baseSet, ProviderOfPreviousAllocationsSets previousSetsProvider) {
			foreach (HeapObject heapObject in baseSet.Elements) {
				if (heapObject.Allocation == null) {
					heapObject.FindAllocation (previousSetsProvider);
				}
			}
		}
		
		bool objectAllocationsArePresent;
		public bool ObjectAllocationsArePresent {
			get {
				return objectAllocationsArePresent;
			}
		}
		public void FindObjectAllocations (ProviderOfPreviousAllocationsSets previousSetsProvider) {
			if ((! objectAllocationsArePresent)) {
				HeapItemSet<HeapObject> baseSet = this as HeapItemSet<HeapObject>;
				if (baseSet != null) {
					FindObjectAllocations (baseSet, previousSetsProvider);
					objectAllocationsArePresent = true;
				}
			}
		}
		
		protected HeapItemSet (string shortDescription, string longDescription, HI[] elements, bool objectAllocationsArePresent) {
			this.shortDescription = shortDescription;
			this.longDescription = longDescription;
			this.elements = elements;
			this.objectAllocationsArePresent = objectAllocationsArePresent;
			allocatedBytes = 0;
			
			Array.Sort (this.elements, CompareHeapItemsByID);
			
			classStatistics = BuildStatistics<LoadedClass,HeapItemSetClassStatistics> (delegate (HI item) {
				allocatedBytes += item.Size;
				return item.Class;
			}, delegate (LoadedClass c) {
				return new HeapItemSetClassStatistics (c);
			});
		}
	}
	
	public class HeapObjectSetFromSnapshot : HeapItemSet<HeapObject> {
		HeapSnapshot heapSnapshot;
		public HeapSnapshot HeapSnapshot {
			get {
				return heapSnapshot;
			}
		}
		
		public HeapObjectSetFromSnapshot (HeapSnapshot heapSnapshot):
			base (String.Format ("Heap at {0}.{1:000}s", heapSnapshot.HeaderStartTime.Seconds, heapSnapshot.HeaderStartTime.Milliseconds),
			      String.Format ("Heap snapshot taken at {0}.{1:000}s", heapSnapshot.HeaderStartTime.Seconds, heapSnapshot.HeaderStartTime.Milliseconds),
			      heapSnapshot.HeapObjects, false) {
			this.heapSnapshot = heapSnapshot;
		}
	}
	
	public class AllocatedObjectSetFromEvents : HeapItemSet<AllocatedObject> {
		public AllocatedObjectSetFromEvents (TimeSpan timeFromStart, AllocatedObject[] allocations):
			base (String.Format ("Allocations {0}.{1:000}s", timeFromStart.Seconds, timeFromStart.Milliseconds),
			      String.Format ("Allocations taken from {0}.{1:000}s", timeFromStart.Seconds, timeFromStart.Milliseconds),
			      allocations, true) {
		}
	}
	
	public class HeapItemSetFromFilter<HI> : HeapItemSet<HI> where HI : IHeapItem {
		HeapItemSet<HI> baseSet;
		public HeapItemSet<HI> BaseSet {
			get {
				return baseSet;
			}
		}
		
		IHeapItemFilter<HI> filter;
		public IHeapItemFilter<HI> Filter {
			get {
				return filter;
			}
		}
		
		static HI[] filterSet (HeapItemSet<HI> baseSet, IHeapItemFilter<HI> filter) {
			List<HI> newSet = new List<HI> ();
			foreach (HI hi in baseSet.Elements) {
				if (filter.Filter (hi)) {
					newSet.Add (hi);
				}
			}
			HI[] result = new HI [newSet.Count];
			newSet.CopyTo (result);
			return result;
		}
		
		public HeapItemSetFromFilter (HeapItemSet<HI> baseSet, IHeapItemFilter<HI> filter): base (filter.Description, String.Format ("{0} and {1}", filter.Description, baseSet.LongDescription), filterSet (baseSet, filter), baseSet.ObjectAllocationsArePresent) {
			this.baseSet = baseSet;
			this.filter = filter;
		}
	}
	
	public class HeapItemSetFromComparison<HI,OHI> : HeapItemSet<HI> where HI : IHeapItem where OHI : IHeapItem {
		HeapItemSet<HI> baseSet;
		public HeapItemSet<HI> BaseSet {
			get {
				return baseSet;
			}
		}
		
		HeapItemSet<OHI> otherSet;
		public HeapItemSet<OHI> OtherSet {
			get {
				return otherSet;
			}
		}
		
		static string buildShortDescription (HeapItemSet<OHI> otherSet, string relation) {
			return String.Format("Object {0} in {1}", relation, otherSet.ShortDescription);
		}
		
		static string buildLongDescription (HeapItemSet<OHI> otherSet, string relation) {
			return String.Format("Object {0} in {1}", relation, otherSet.LongDescription);
		}
		
		public static void PerformComparison<HI1,HI2> (HeapItemSet<HI1> firstSet, HeapItemSet<HI2> secondSet, out HeapItemSet<HI1> onlyInFirstSet, out HeapItemSet<HI2> onlyInSecondSet) where HI1 : IHeapItem where HI2 : IHeapItem {
			List<HI1> onlyInFirst = new List<HI1> ();
			List<HI2> onlyInSecond = new List<HI2> ();
			
			int firstIndex = 0;
			int secondIndex = 0;
			HI1[] firstObjects = firstSet.Elements;
			HI2[] secondObjects = secondSet.Elements;
			
			while ((firstIndex < firstObjects.Length) || (secondIndex < secondObjects.Length)) {
				if (firstIndex >= firstObjects.Length) {
					while (secondIndex < secondObjects.Length) {
						onlyInSecond.Add (secondObjects [secondIndex]);
						secondIndex ++;
					}
				} else if (secondIndex >= secondObjects.Length) {
					while (firstIndex < secondObjects.Length) {
						onlyInFirst.Add (firstObjects [firstIndex]);
						firstIndex ++;
					}
				} else {
					HI1 firstObject = firstObjects [firstIndex];
					HI2 secondObject = secondObjects [secondIndex];
					if (firstObject.ID < secondObject.ID) {
						onlyInFirst.Add (firstObject);
						firstIndex ++;
					} else if (secondObject.ID < firstObject.ID) {
						onlyInSecond.Add (secondObject);
						secondIndex ++;
					} else {
						firstIndex ++;
						secondIndex ++;
					}
				}
			}
			
			onlyInFirstSet = new HeapItemSetFromComparison<HI1,HI2>(firstSet, secondSet, onlyInFirst.ToArray (), "not");
			onlyInSecondSet = new HeapItemSetFromComparison<HI2,HI1>(secondSet, firstSet, onlyInSecond.ToArray (), "not");
		}
		
		public static HeapItemSet<HI1> PerformIntersection<HI1,HI2> (HeapItemSet<HI1> firstSet, HeapItemSet<HI2> secondSet) where HI1 : IHeapItem where HI2 : IHeapItem {
			List<HI1> result = new List<HI1> ();
			
			int firstIndex = 0;
			int secondIndex = 0;
			HI1[] firstObjects = firstSet.Elements;
			HI2[] secondObjects = secondSet.Elements;
			
			Console.WriteLine ("Inside PerformIntersection...");
			
			while ((firstIndex < firstObjects.Length) && (secondIndex < secondObjects.Length)) {
				HI1 firstObject = firstObjects [firstIndex];
				HI2 secondObject = secondObjects [secondIndex];
				if (firstObject.ID < secondObject.ID) {
					firstIndex ++;
				} else if (secondObject.ID < firstObject.ID) {
					secondIndex ++;
				} else {
					result.Add (firstObject);
					firstIndex ++;
					secondIndex ++;
				}
			}
			
			return new HeapItemSetFromComparison<HI1,HI2>(firstSet, secondSet, result.ToArray (), "also");
		}
		
		static bool ObjectReferencesItemInSet (HeapItemSet<HI> itemSet, HeapObject o) {
			foreach (HeapObject reference in o.References) {
				if (itemSet.ContainsItem (reference.ID)) {
					return true;
				}
			}
			return false;
		}
		public static HeapItemSet<HeapObject> ObjectsReferencingItemInSet (HeapItemSet<HI> itemSet, HeapItemSet<HeapObject> objectSet) {
			List<HeapObject> result = new List<HeapObject> ();
			HeapObject[] objects = objectSet.Elements;
			
			foreach (HeapObject o in objects) {
				if (ObjectReferencesItemInSet (itemSet, o)) {
					result.Add (o);
				}
			}
			
			return new HeapItemSetFromComparison<HeapObject,HI>(objectSet, itemSet, result.ToArray (), "references item");
		}
		
		static bool ObjectIsReferencedByItemInSet (HeapItemSet<HI> itemSet, HeapObject o) {
			foreach (HeapObject reference in o.BackReferences) {
				if (itemSet.ContainsItem (reference.ID)) {
					return true;
				}
			}
			return false;
		}
		public static HeapItemSet<HeapObject> ObjectsReferencedByItemInSet (HeapItemSet<HI> itemSet, HeapItemSet<HeapObject> objectSet) {
			List<HeapObject> result = new List<HeapObject> ();
			HeapObject[] objects = objectSet.Elements;
			
			foreach (HeapObject o in objects) {
				if (ObjectIsReferencedByItemInSet (itemSet, o)) {
					result.Add (o);
				}
			}
			
			return new HeapItemSetFromComparison<HeapObject,HI>(objectSet, itemSet, result.ToArray (), "is referenced by item");
		}
		
		HeapItemSetFromComparison (HeapItemSet<HI> baseSet, HeapItemSet<OHI> otherSet, HI[] heapItems, string relation): base (buildShortDescription (otherSet, relation), buildLongDescription (otherSet, relation), heapItems, baseSet.ObjectAllocationsArePresent) {
			this.baseSet = baseSet;
			this.otherSet = otherSet;
		}
	}
	
	public class LoadedElementFactory : ILoadedElementFactory<LoadedClass,LoadedMethod,UnmanagedFunctionFromRegion,UnmanagedFunctionFromID,ExecutableMemoryRegion,HeapObject,HeapSnapshot> {
		bool recordHeapSnapshots = true;
		public bool RecordHeapSnapshots {
			get {
				return recordHeapSnapshots;
			}
			set {
				recordHeapSnapshots = value;
			}
		}
		
		public LoadedClass NewClass (uint id, string name, uint size) {
			return new LoadedClass (id, name, size);
		}
		public LoadedMethod NewMethod (uint id, LoadedClass c, string name) {
			return new LoadedMethod (id, c, name);
		}
		public ExecutableMemoryRegion NewExecutableMemoryRegion (uint id, string fileName, uint fileOffset, ulong startAddress, ulong endAddress) {
			return new ExecutableMemoryRegion (id, fileName, fileOffset, startAddress, endAddress);
		}
		public HeapSnapshot NewHeapSnapshot (uint collection, ulong startCounter, DateTime startTime, ulong endCounter, DateTime endTime, TimeSpan headerStartTime, LoadedClass[] initialAllocations, bool recordSnapshots) {
			return new HeapSnapshot (collection, startCounter, startTime, endCounter, endTime, headerStartTime, initialAllocations, recordSnapshots);
		}
		public UnmanagedFunctionFromID NewUnmanagedFunction (uint id, string name, ExecutableMemoryRegion region) {
			return new UnmanagedFunctionFromID (id, name, region);
		}
	}
	
	public class AllocationSummary : BaseAllocationSummary<LoadedClass> {
		public AllocationSummary (uint collection, ulong startCounter, DateTime startTime) : base (collection, startCounter, startTime) {
		}
	}
	
	public interface MonitorAggregatedDataHandler {
		ulong TicksContended {get;}
		void AddTicksContended (ulong increment);
		ulong ContentionCount {get;}
		void IncrementContentionCount ();
		ulong FailCount {get;}
		void IncrementFailCount ();
		void Reset ();
		
		void WriteName (TextWriter writer, int depth);
		void WriteIndividualStatistics (TextWriter writer, MonitorAggregatedDataHandler owner, ProfilerEventHandler processor, int depth);
		void WriteFullStatistics (TextWriter writer, MonitorAggregatedDataHandler owner, ProfilerEventHandler processor, int depth);
	}
	
	public interface MonitorContainerDataHandler : MonitorAggregatedDataHandler {
		MonitorAggregatedDataHandler[] ComponentData {get;}
	}
	
	public struct MonitorAggregatedData {
		ulong ticksContended;
		public ulong TicksContended {
			get {
				return ticksContended;
			}
		}
		public void AddTicksContended (ulong increment) {
			ticksContended += increment;
		}
		
		uint contentionCount;
		public ulong ContentionCount {
			get {
				return contentionCount;
			}
		}
		public void IncrementContentionCount () {
			contentionCount ++;
		}
		
		uint failCount;
		public ulong FailCount {
			get {
				return failCount;
			}
		}
		public void IncrementFailCount () {
			failCount ++;
		}
		
		public void Reset () {
			ticksContended = 0;
			contentionCount = 0;
			failCount = 0;
		}
	}
	
	public abstract class BaseMonitorStatisticsCollector : MonitorAggregatedDataHandler {
		protected MonitorAggregatedData data;
		
		public ulong TicksContended {
			get {
				return data.TicksContended;
			}
		}
		public abstract void AddTicksContended (ulong increment);
		public ulong ContentionCount {
			get {
				return data.ContentionCount;
			}
		}
		public abstract void IncrementContentionCount ();
		public ulong FailCount {
			get {
				return data.FailCount;
			}
		}
		public abstract void IncrementFailCount ();
		public abstract void Reset ();
		
		public abstract void WriteName (TextWriter writer, int depth);
		
		protected static readonly string IndentationString = "        ";
		protected void WriteIndentation (TextWriter writer, int depth) {
			for (int i = 0; i < depth; i++) {
				writer.Write (IndentationString);
			}
		}
		public void WriteIndividualStatistics (TextWriter writer, MonitorAggregatedDataHandler owner, ProfilerEventHandler processor, int depth) {
			if (owner == null) {
				owner = this;
			}
			
			WriteIndentation (writer, depth);
			
			//double secondsContended = processor.ClicksToSeconds (TicksContended);
			//double ownerSecondsContended = processor.ClicksToSeconds (owner.TicksContended);
			writer.Write ("{0,5:F2}% ({1:F6} ticks) contention time ({2} contentions, {3} failures) in ",
			              //(secondsContended / ownerSecondsContended) * 100.0,
			              (((double) TicksContended) / owner.TicksContended) * 100.0,
			              //secondsContended,
			              TicksContended,
			              ContentionCount,
			              FailCount);
			WriteName (writer, depth);
			writer.WriteLine ();
		}
		public abstract void WriteFullStatistics (TextWriter writer, MonitorAggregatedDataHandler owner, ProfilerEventHandler processor, int depth);
		
		protected static void WriteComponentStatistics (TextWriter writer, MonitorAggregatedDataHandler owner, MonitorAggregatedDataHandler[] components, ProfilerEventHandler processor, int depth) {
			foreach (MonitorAggregatedDataHandler component in components) {
				component.WriteFullStatistics (writer, owner, processor, depth + 1);
			}
		}
		protected static void WriteSimpleContainerComponentStatistics (TextWriter writer, MonitorContainerDataHandler container, ProfilerEventHandler processor, int depth) {
			WriteComponentStatistics (writer, container, container.ComponentData, processor, depth);
		}
		protected static void WriteSimpleContainerFullStatistics (TextWriter writer, MonitorAggregatedDataHandler owner, MonitorContainerDataHandler container, ProfilerEventHandler processor, int depth) {
			container.WriteIndividualStatistics (writer, owner, processor, depth);
			WriteComponentStatistics (writer, container, container.ComponentData, processor, depth);
		}
		
		public static Comparison<MonitorAggregatedDataHandler> CompareStatistics = delegate (MonitorAggregatedDataHandler a, MonitorAggregatedDataHandler b) {
			int result = b.TicksContended.CompareTo (a.TicksContended);
			if (result != 0) {
				return result;
			} else {
				return b.ContentionCount.CompareTo (a.ContentionCount);
			}
		};
	}
	
	public abstract class SimpleMonitorStatistics : BaseMonitorStatisticsCollector {
		public override void AddTicksContended (ulong increment) {
			data.AddTicksContended (increment);
		}
		public override void IncrementContentionCount () {
			data.IncrementContentionCount ();
		}
		public override void IncrementFailCount () {
			data.IncrementFailCount ();
		}
		public override void Reset () {
			data.Reset ();
		}
	}
	
	public class GlobalMonitorStatistics : SimpleMonitorStatistics, MonitorContainerDataHandler {
		Dictionary<uint,MonitorStatisticsByClass> statistics;
		public MonitorStatisticsByClass[] Statistics {
			get {
				MonitorStatisticsByClass[] result = new MonitorStatisticsByClass [statistics.Count];
				statistics.Values.CopyTo (result, 0);
				Array.Sort (result, CompareStatistics);
				return result;
			}
		}
		public MonitorAggregatedDataHandler[] ComponentData {
			get {
				return Statistics;
			}
		}
		
		public void HandleEvent (ulong threadId, MonitorEvent eventCode, LoadedClass c, ulong objectId, StackTrace trace, ulong counter) {
			MonitorStatisticsByClass target;
			if (! statistics.ContainsKey (c.ID)) {
				target = new MonitorStatisticsByClass (this, c);
				statistics [c.ID] = target;
			} else {
				target = statistics [c.ID];
			}
			
			target.HandleEvent (threadId, eventCode, objectId, trace, counter);
		}
		
		public string Name {
			get {
				return "Global statistics";
			}
		}
		
		public override void WriteName (TextWriter writer, int depth) {
			writer.Write (Name);
		}
		
		public override void WriteFullStatistics (TextWriter writer, MonitorAggregatedDataHandler owner, ProfilerEventHandler processor, int depth) {
			WriteSimpleContainerFullStatistics (writer, owner, this, processor, depth);
		}
		
		public void WriteStatistics (TextWriter writer, ProfilerEventHandler processor) {
			WriteFullStatistics (writer, this, processor, 0);
		}
		
		public bool ContainsData {
			get {
				return statistics.Count > 0;
			}
		}
		
		public GlobalMonitorStatistics () {
			statistics = new Dictionary<uint,MonitorStatisticsByClass> ();
		}
	}
	
	public abstract class DependentMonitorStatistics<MS> : BaseMonitorStatisticsCollector where MS : MonitorAggregatedDataHandler {
		MS owner;
		public MS Owner {
			get {
				return owner;
			}
		}
		
		public override void AddTicksContended (ulong increment) {
			data.AddTicksContended (increment);
			owner.AddTicksContended (increment);
		}
		public override void IncrementContentionCount () {
			data.IncrementContentionCount ();
			owner.IncrementContentionCount ();
		}
		public override void IncrementFailCount () {
			data.IncrementFailCount ();
			owner.IncrementFailCount ();
		}
		public override void Reset () {
			data.Reset ();
			owner.Reset ();
		}
		
		protected DependentMonitorStatistics (MS owner) {
			this.owner = owner;
		}
	}
	
	public class MonitorStatisticsByCallerPerClass : SimpleMonitorStatistics, MonitorContainerDataHandler {
		LoadedMethod caller;
		public LoadedMethod Caller {
			get {
				return caller;
			}
		}
		
		Dictionary<uint,MonitorStatisticsByCallStack<MonitorStatisticsByCallerPerClass>> statistics;
		public MonitorStatisticsByCallStack<MonitorStatisticsByCallerPerClass>[] Statistics {
			get {
				MonitorStatisticsByCallStack<MonitorStatisticsByCallerPerClass>[] result = new MonitorStatisticsByCallStack<MonitorStatisticsByCallerPerClass> [statistics.Count];
				statistics.Values.CopyTo (result, 0);
				Array.Sort (result, CompareStatistics);
				return result;
			}
		}
		public MonitorAggregatedDataHandler[] ComponentData {
			get {
				return Statistics;
			}
		}
		
		public MonitorStatisticsByCallStack<MonitorStatisticsByCallerPerClass> HandleEvent (MonitorEvent eventCode, StackTrace trace) {
			MonitorStatisticsByCallStack<MonitorStatisticsByCallerPerClass> target;
			if (! statistics.ContainsKey (trace.ID)) {
				target = new MonitorStatisticsByCallStack<MonitorStatisticsByCallerPerClass> (this, trace);
				statistics [trace.ID] = target;
			} else {
				target = statistics [trace.ID];
			}
			
			target.HandleEvent (eventCode);
			
			return target;
		}
		
		public string Name {
			get {
				return caller.Class.Name + "." + caller.Name;
			}
		}
		
		public override void WriteName (TextWriter writer, int depth) {
			writer.Write (Name);
		}
		
		public override void WriteFullStatistics (TextWriter writer, MonitorAggregatedDataHandler owner, ProfilerEventHandler processor, int depth) {
			WriteSimpleContainerFullStatistics (writer, owner, this, processor, depth);
		}
		
		public MonitorStatisticsByCallerPerClass (LoadedMethod caller) {
			this.caller = caller;
			statistics = new Dictionary<uint,MonitorStatisticsByCallStack<MonitorStatisticsByCallerPerClass>> ();
		}
	}
	
	public class MonitorStatisticsByClass : DependentMonitorStatistics<GlobalMonitorStatistics>, MonitorContainerDataHandler {
		LoadedClass c;
		public LoadedClass Class {
			get {
				return c;
			}
		}
		
		Dictionary<ulong,MonitorStatistics> statistics;
		public MonitorStatistics[] Statistics {
			get {
				MonitorStatistics[] result = new MonitorStatistics [statistics.Count];
				statistics.Values.CopyTo (result, 0);
				Array.Sort (result, CompareStatistics);
				return result;
			}
		}
		public MonitorAggregatedDataHandler[] ComponentData {
			get {
				return Statistics;
			}
		}
		
		Dictionary<uint,MonitorStatisticsByCallerPerClass> statisticsByCaller;
		public MonitorStatisticsByCallerPerClass[] StatisticsByCaller {
			get {
				MonitorStatisticsByCallerPerClass[] result = new MonitorStatisticsByCallerPerClass [statisticsByCaller.Count];
				statisticsByCaller.Values.CopyTo (result, 0);
				Array.Sort (result, CompareStatistics);
				return result;
			}
		}
		public MonitorAggregatedDataHandler[] ComponentDataByCaller {
			get {
				return StatisticsByCaller;
			}
		}
		
		public void HandleEvent (ulong threadId, MonitorEvent eventCode, ulong objectId, StackTrace trace, ulong counter) {
			MonitorStatisticsByCallerPerClass callerPerClassTarget;
			if (statisticsByCaller.ContainsKey (trace.TopMethod.ID)) {
				callerPerClassTarget = statisticsByCaller [trace.TopMethod.ID];
			} else {
				callerPerClassTarget = new MonitorStatisticsByCallerPerClass (trace.TopMethod);
				statisticsByCaller [trace.TopMethod.ID] = callerPerClassTarget;
			}
			MonitorStatisticsByCallStack<MonitorStatisticsByCallerPerClass> tracePerClassDestination = callerPerClassTarget.HandleEvent (eventCode, trace);
			
			MonitorStatistics target;
			if (statistics.ContainsKey (objectId)) {
				target = statistics [objectId];
			} else {
				target = new MonitorStatistics (this, objectId);
				statistics [objectId] = target;
			}
			
			target.HandleEvent (threadId, eventCode, trace, counter, tracePerClassDestination);
		}
		
		public string Name {
			get {
				return c.Name;
			}
		}
		
		public override void WriteName (TextWriter writer, int depth) {
			writer.Write (Name);
		}
		
		public override void WriteFullStatistics (TextWriter writer, MonitorAggregatedDataHandler owner, ProfilerEventHandler processor, int depth) {
			WriteIndividualStatistics (writer, owner, processor, depth);
			
			WriteIndentation (writer, depth + 1);
			writer.WriteLine ("Statistics by caller:");
			WriteComponentStatistics (writer, this, ComponentDataByCaller, processor, depth + 1);
			
			WriteIndentation (writer, depth + 1);
			writer.WriteLine ("Statistics by monitor:");
			WriteComponentStatistics (writer, this, ComponentData, processor, depth + 1);
		}
		
		public MonitorStatisticsByClass (GlobalMonitorStatistics gms, LoadedClass c) : base (gms) {
			this.c = c;
			statistics = new Dictionary<ulong,MonitorStatistics> ();
			statisticsByCaller = new Dictionary<uint,MonitorStatisticsByCallerPerClass> ();
		}
	}
	
	public class MonitorStatistics : DependentMonitorStatistics<MonitorStatisticsByClass>, MonitorContainerDataHandler {
		struct ThreadState {
			public ulong lastCounterValue;
			//public bool isPerformingRetry;
		}
		
		ThreadState currentThreadState;
		ulong currentThreadId;
		Dictionary<ulong,ThreadState> threadStates;
		
		void SetCurrentThread (ulong threadId) {
			if (currentThreadId != threadId) {
				threadStates [currentThreadId] = currentThreadState;
				if (! threadStates.ContainsKey (threadId)) {
					threadStates [threadId] = new ThreadState ();
				}
				currentThreadState = threadStates [threadId];
				currentThreadId = threadId;
			}
		}
		
		public void HandleEvent (ulong threadId, MonitorEvent eventCode, StackTrace trace, ulong counter, MonitorStatisticsByCallStack<MonitorStatisticsByCallerPerClass> tracePerClassDestination) {
			uint methodId = trace.TopMethod.ID;
			MonitorStatisticsByCaller target;
			if (! statistics.ContainsKey (methodId)) {
				target = new MonitorStatisticsByCaller (this, trace.TopMethod);
				statistics [methodId] = target;
			} else {
				target = statistics [methodId];
			}
			
			MonitorStatisticsByCallStack<MonitorStatisticsByCaller> destination = target.HandleEvent (eventCode, trace);
			
			SetCurrentThread (threadId);
			
			switch (eventCode) {
			case MonitorEvent.CONTENTION:
				tracePerClassDestination.IncrementContentionCount ();
				destination.IncrementContentionCount ();
				currentThreadState.lastCounterValue = counter;
				break;
			case MonitorEvent.DONE:
				tracePerClassDestination.AddTicksContended (counter - currentThreadState.lastCounterValue);
				destination.AddTicksContended (counter - currentThreadState.lastCounterValue);
				currentThreadState.lastCounterValue = counter;
				break;
			case MonitorEvent.FAIL:
				tracePerClassDestination.AddTicksContended (counter - currentThreadState.lastCounterValue);
				destination.AddTicksContended (counter - currentThreadState.lastCounterValue);
				currentThreadState.lastCounterValue = counter;
				
				tracePerClassDestination.IncrementFailCount ();
				destination.IncrementFailCount ();
				break;
			default:
				throw new Exception (String.Format ("Invalid MonitorEvent code {0}", eventCode));
			}
		}
		
		ulong objectId;
		public ulong ObjectId {
			get {
				return objectId;
			}
		}
		
		Dictionary<uint,MonitorStatisticsByCaller> statistics;
		public MonitorStatisticsByCaller[] Statistics {
			get {
				MonitorStatisticsByCaller[] result = new MonitorStatisticsByCaller [statistics.Count];
				statistics.Values.CopyTo (result, 0);
				Array.Sort (result, CompareStatistics);
				return result;
			}
		}
		public MonitorAggregatedDataHandler[] ComponentData {
			get {
				return Statistics;
			}
		}
		
		public string Name {
			get {
				return "object " + ObjectId;
			}
		}
		
		public override void WriteName (TextWriter writer, int depth) {
			writer.Write (Name);
		}
		
		public override void WriteFullStatistics (TextWriter writer, MonitorAggregatedDataHandler owner, ProfilerEventHandler processor, int depth) {
			WriteSimpleContainerFullStatistics (writer, owner, this, processor, depth);
		}
		
		public MonitorStatistics (MonitorStatisticsByClass msbc, ulong objectId) : base (msbc) {
			this.objectId = objectId;
			currentThreadState.lastCounterValue = 0;
			currentThreadId = 0;
			threadStates = new Dictionary<ulong,ThreadState> ();
			threadStates [0] = new ThreadState ();
			statistics = new Dictionary<uint,MonitorStatisticsByCaller> ();
		}
	}
	
	public class MonitorStatisticsByCaller : DependentMonitorStatistics<MonitorStatistics>, MonitorContainerDataHandler {
		LoadedMethod caller;
		public LoadedMethod Caller {
			get {
				return caller;
			}
		}
		
		Dictionary<uint,MonitorStatisticsByCallStack<MonitorStatisticsByCaller>> statistics;
		public MonitorStatisticsByCallStack<MonitorStatisticsByCaller>[] Statistics {
			get {
				MonitorStatisticsByCallStack<MonitorStatisticsByCaller>[] result = new MonitorStatisticsByCallStack<MonitorStatisticsByCaller> [statistics.Count];
				statistics.Values.CopyTo (result, 0);
				Array.Sort (result, CompareStatistics);
				return result;
			}
		}
		public MonitorAggregatedDataHandler[] ComponentData {
			get {
				return Statistics;
			}
		}
		
		public MonitorStatisticsByCallStack<MonitorStatisticsByCaller> HandleEvent (MonitorEvent eventCode, StackTrace trace) {
			MonitorStatisticsByCallStack<MonitorStatisticsByCaller> target;
			if (! statistics.ContainsKey (trace.ID)) {
				target = new MonitorStatisticsByCallStack<MonitorStatisticsByCaller> (this, trace);
				statistics [trace.ID] = target;
			} else {
				target = statistics [trace.ID];
			}
			
			target.HandleEvent (eventCode);
			
			return target;
		}
		
		public string Name {
			get {
				return caller.Class.Name + "." + caller.Name;
			}
		}
		
		public override void WriteName (TextWriter writer, int depth) {
			writer.Write (Name);
		}
		
		public override void WriteFullStatistics (TextWriter writer, MonitorAggregatedDataHandler owner, ProfilerEventHandler processor, int depth) {
			WriteSimpleContainerFullStatistics (writer, owner, this, processor, depth);
		}
		
		public MonitorStatisticsByCaller (MonitorStatistics ms, LoadedMethod caller) : base (ms) {
			this.caller = caller;
			statistics = new Dictionary<uint,MonitorStatisticsByCallStack<MonitorStatisticsByCaller>> ();
		}
	}
	
	public class MonitorStatisticsByCallStack<C> : DependentMonitorStatistics<C> where C : MonitorContainerDataHandler {
		StackTrace trace;
		public StackTrace Trace {
			get {
				return trace;
			}
		}
		
		public void HandleEvent (MonitorEvent eventCode) {
		}
		
		public string Name {
			get {
				return trace.FullDescription;
			}
		}
		
		public override void WriteName (TextWriter writer, int depth) {
			trace.Write (writer, depth + 2, IndentationString);
		}
		
		public override void WriteFullStatistics (TextWriter writer, MonitorAggregatedDataHandler owner, ProfilerEventHandler processor, int depth) {
			WriteIndividualStatistics (writer, owner, processor, depth);
		}
		
		public MonitorStatisticsByCallStack (C owner, StackTrace trace) : base (owner) {
			this.trace = trace;
		}
	}
}