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
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
|
// translation pass
// Copyright (C) 2005-2008 Red Hat Inc.
// Copyright (C) 2005-2008 Intel Corporation.
//
// This file is part of systemtap, and is free software. You can
// redistribute it and/or modify it under the terms of the GNU General
// Public License (GPL); either version 2, or (at your option) any
// later version.
#include "config.h"
#include "staptree.h"
#include "elaborate.h"
#include "translate.h"
#include "session.h"
#include "tapsets.h"
#include "util.h"
#include "dwarf_wrappers.h"
#include <cstdlib>
#include <iostream>
#include <set>
#include <sstream>
#include <string>
#include <cassert>
#include <cstring>
extern "C" {
#include <elfutils/libdwfl.h>
}
using namespace std;
struct var;
struct tmpvar;
struct aggvar;
struct mapvar;
struct itervar;
struct c_unparser: public unparser, public visitor
{
systemtap_session* session;
translator_output* o;
derived_probe* current_probe;
functiondecl* current_function;
unsigned tmpvar_counter;
unsigned label_counter;
unsigned action_counter;
bool probe_or_function_needs_deref_fault_handler;
varuse_collecting_visitor vcv_needs_global_locks;
map<string, string> probe_contents;
c_unparser (systemtap_session* ss):
session (ss), o (ss->op), current_probe(0), current_function (0),
tmpvar_counter (0), label_counter (0) {}
~c_unparser () {}
void emit_map_type_instantiations ();
void emit_common_header ();
void emit_global (vardecl* v);
void emit_global_init (vardecl* v);
void emit_global_param (vardecl* v);
void emit_functionsig (functiondecl* v);
void emit_module_init ();
void emit_module_exit ();
void emit_function (functiondecl* v);
void emit_locks (const varuse_collecting_visitor& v);
void emit_probe (derived_probe* v);
void emit_unlocks (const varuse_collecting_visitor& v);
// for use by stats (pmap) foreach
set<string> aggregations_active;
// for use by looping constructs
vector<string> loop_break_labels;
vector<string> loop_continue_labels;
string c_typename (exp_type e);
string c_varname (const string& e);
string c_expression (expression* e);
void c_assign (var& lvalue, const string& rvalue, const token* tok);
void c_assign (const string& lvalue, expression* rvalue, const string& msg);
void c_assign (const string& lvalue, const string& rvalue, exp_type type,
const string& msg, const token* tok);
void c_declare(exp_type ty, const string &name);
void c_declare_static(exp_type ty, const string &name);
void c_strcat (const string& lvalue, const string& rvalue);
void c_strcat (const string& lvalue, expression* rvalue);
void c_strcpy (const string& lvalue, const string& rvalue);
void c_strcpy (const string& lvalue, expression* rvalue);
bool is_local (vardecl const* r, token const* tok);
tmpvar gensym(exp_type ty);
aggvar gensym_aggregate();
var getvar(vardecl* v, token const* tok = NULL);
itervar getiter(symbol* s);
mapvar getmap(vardecl* v, token const* tok = NULL);
void load_map_indices(arrayindex* e,
vector<tmpvar> & idx);
void load_aggregate (expression *e, aggvar & agg, bool pre_agg=false);
string histogram_index_check(var & vase, tmpvar & idx) const;
void collect_map_index_types(vector<vardecl* > const & vars,
set< pair<vector<exp_type>, exp_type> > & types);
void record_actions (unsigned actions, bool update=false);
void visit_block (block* s);
void visit_embeddedcode (embeddedcode* s);
void visit_null_statement (null_statement* s);
void visit_expr_statement (expr_statement* s);
void visit_if_statement (if_statement* s);
void visit_for_loop (for_loop* s);
void visit_foreach_loop (foreach_loop* s);
void visit_return_statement (return_statement* s);
void visit_delete_statement (delete_statement* s);
void visit_next_statement (next_statement* s);
void visit_break_statement (break_statement* s);
void visit_continue_statement (continue_statement* s);
void visit_literal_string (literal_string* e);
void visit_literal_number (literal_number* e);
void visit_binary_expression (binary_expression* e);
void visit_unary_expression (unary_expression* e);
void visit_pre_crement (pre_crement* e);
void visit_post_crement (post_crement* e);
void visit_logical_or_expr (logical_or_expr* e);
void visit_logical_and_expr (logical_and_expr* e);
void visit_array_in (array_in* e);
void visit_comparison (comparison* e);
void visit_concatenation (concatenation* e);
void visit_ternary_expression (ternary_expression* e);
void visit_assignment (assignment* e);
void visit_symbol (symbol* e);
void visit_target_symbol (target_symbol* e);
void visit_arrayindex (arrayindex* e);
void visit_functioncall (functioncall* e);
void visit_print_format (print_format* e);
void visit_stat_op (stat_op* e);
void visit_hist_op (hist_op* e);
};
// A shadow visitor, meant to generate temporary variable declarations
// for function or probe bodies. Member functions should exactly match
// the corresponding c_unparser logic and traversal sequence,
// to ensure interlocking naming and declaration of temp variables.
struct c_tmpcounter:
public traversing_visitor
{
c_unparser* parent;
c_tmpcounter (c_unparser* p):
parent (p)
{
parent->tmpvar_counter = 0;
}
void load_map_indices(arrayindex* e);
void visit_block (block *s);
void visit_for_loop (for_loop* s);
void visit_foreach_loop (foreach_loop* s);
// void visit_return_statement (return_statement* s);
void visit_delete_statement (delete_statement* s);
void visit_binary_expression (binary_expression* e);
// void visit_unary_expression (unary_expression* e);
void visit_pre_crement (pre_crement* e);
void visit_post_crement (post_crement* e);
// void visit_logical_or_expr (logical_or_expr* e);
// void visit_logical_and_expr (logical_and_expr* e);
void visit_array_in (array_in* e);
// void visit_comparison (comparison* e);
void visit_concatenation (concatenation* e);
// void visit_ternary_expression (ternary_expression* e);
void visit_assignment (assignment* e);
void visit_arrayindex (arrayindex* e);
void visit_functioncall (functioncall* e);
void visit_print_format (print_format* e);
void visit_stat_op (stat_op* e);
};
struct c_unparser_assignment:
public throwing_visitor
{
c_unparser* parent;
string op;
expression* rvalue;
bool post; // true == value saved before modify operator
c_unparser_assignment (c_unparser* p, const string& o, expression* e):
throwing_visitor ("invalid lvalue type"),
parent (p), op (o), rvalue (e), post (false) {}
c_unparser_assignment (c_unparser* p, const string& o, bool pp):
throwing_visitor ("invalid lvalue type"),
parent (p), op (o), rvalue (0), post (pp) {}
void prepare_rvalue (string const & op,
tmpvar & rval,
token const* tok);
void c_assignop(tmpvar & res,
var const & lvar,
tmpvar const & tmp,
token const* tok);
// only symbols and arrayindex nodes are possible lvalues
void visit_symbol (symbol* e);
void visit_arrayindex (arrayindex* e);
};
struct c_tmpcounter_assignment:
public traversing_visitor
// leave throwing for illegal lvalues to the c_unparser_assignment instance
{
c_tmpcounter* parent;
const string& op;
expression* rvalue;
bool post; // true == value saved before modify operator
c_tmpcounter_assignment (c_tmpcounter* p, const string& o, expression* e, bool pp = false):
parent (p), op (o), rvalue (e), post (pp) {}
void prepare_rvalue (tmpvar & rval);
void c_assignop(tmpvar & res);
// only symbols and arrayindex nodes are possible lvalues
void visit_symbol (symbol* e);
void visit_arrayindex (arrayindex* e);
};
ostream & operator<<(ostream & o, var const & v);
/*
Some clarification on the runtime structures involved in statistics:
The basic type for collecting statistics in the runtime is struct
stat_data. This contains the count, min, max, sum, and possibly
histogram fields.
There are two places struct stat_data shows up.
1. If you declare a statistic variable of any sort, you want to make
a struct _Stat. A struct _Stat* is also called a Stat. Struct _Stat
contains a per-CPU array of struct stat_data values, as well as a
struct stat_data which it aggregates into. Writes into a Struct
_Stat go into the per-CPU struct stat. Reads involve write-locking
the struct _Stat, aggregating into its aggregate struct stat_data,
unlocking, read-locking the struct _Stat, then reading values out of
the aggregate and unlocking.
2. If you declare a statistic-valued map, you want to make a
pmap. This is a per-CPU array of maps, each of which holds struct
stat_data values, as well as an aggregate *map*. Writes into a pmap
go into the per-CPU map. Reads involve write-locking the pmap,
aggregating into its aggregate map, unlocking, read-locking the
pmap, then reading values out of its aggregate (which is a normal
map) and unlocking.
Because, at the moment, the runtime does not support the concept of
a statistic which collects multiple histogram types, we may need to
instantiate one pmap or struct _Stat for each histogram variation
the user wants to track.
*/
class var
{
protected:
bool local;
exp_type ty;
statistic_decl sd;
string name;
public:
var(bool local, exp_type ty, statistic_decl const & sd, string const & name)
: local(local), ty(ty), sd(sd), name(name)
{}
var(bool local, exp_type ty, string const & name)
: local(local), ty(ty), name(name)
{}
virtual ~var() {}
bool is_local() const
{
return local;
}
statistic_decl const & sdecl() const
{
return sd;
}
void assert_hist_compatible(hist_op const & hop)
{
// Semantic checks in elaborate should have caught this if it was
// false. This is just a double-check.
switch (sd.type)
{
case statistic_decl::linear:
assert(hop.htype == hist_linear);
assert(hop.params.size() == 3);
assert(hop.params[0] == sd.linear_low);
assert(hop.params[1] == sd.linear_high);
assert(hop.params[2] == sd.linear_step);
break;
case statistic_decl::logarithmic:
assert(hop.htype == hist_log);
assert(hop.params.size() == 0);
break;
case statistic_decl::none:
assert(false);
}
}
exp_type type() const
{
return ty;
}
string value() const
{
if (local)
return "l->" + name;
else
return "global.s_" + name;
}
virtual string hist() const
{
assert (ty == pe_stats);
assert (sd.type != statistic_decl::none);
return "(&(" + value() + "->hist))";
}
virtual string buckets() const
{
assert (ty == pe_stats);
assert (sd.type != statistic_decl::none);
return "(" + value() + "->hist.buckets)";
}
string init() const
{
switch (type())
{
case pe_string:
if (! local)
return ""; // module_param
else
return value() + "[0] = '\\0';";
case pe_long:
if (! local)
return ""; // module_param
else
return value() + " = 0;";
case pe_stats:
{
// See also mapvar::init().
string prefix = value() + " = _stp_stat_init (";
// Check for errors during allocation.
string suffix = "if (" + value () + " == NULL) rc = -ENOMEM;";
switch (sd.type)
{
case statistic_decl::none:
prefix += "HIST_NONE";
break;
case statistic_decl::linear:
prefix += string("HIST_LINEAR")
+ ", " + stringify(sd.linear_low)
+ ", " + stringify(sd.linear_high)
+ ", " + stringify(sd.linear_step);
break;
case statistic_decl::logarithmic:
prefix += string("HIST_LOG");
break;
default:
throw semantic_error("unsupported stats type for " + value());
}
prefix = prefix + "); ";
return string (prefix + suffix);
}
default:
throw semantic_error("unsupported initializer for " + value());
}
}
string fini () const
{
switch (type())
{
case pe_string:
case pe_long:
return ""; // no action required
case pe_stats:
return "_stp_stat_del (" + value () + ");";
default:
throw semantic_error("unsupported deallocator for " + value());
}
}
void declare(c_unparser &c) const
{
c.c_declare(ty, name);
}
};
ostream & operator<<(ostream & o, var const & v)
{
return o << v.value();
}
struct stmt_expr
{
c_unparser & c;
stmt_expr(c_unparser & c) : c(c)
{
c.o->newline() << "({";
c.o->indent(1);
}
~stmt_expr()
{
c.o->newline(-1) << "})";
}
};
struct tmpvar
: public var
{
protected:
bool overridden;
string override_value;
public:
tmpvar(exp_type ty,
unsigned & counter)
: var(true, ty, ("__tmp" + stringify(counter++))), overridden(false)
{}
tmpvar(const var& source)
: var(source), overridden(false)
{}
void override(const string &value)
{
overridden = true;
override_value = value;
}
string value() const
{
if (overridden)
return override_value;
else
return var::value();
}
};
ostream & operator<<(ostream & o, tmpvar const & v)
{
return o << v.value();
}
struct aggvar
: public var
{
aggvar(unsigned & counter)
: var(true, pe_stats, ("__tmp" + stringify(counter++)))
{}
string init() const
{
assert (type() == pe_stats);
return value() + " = NULL;";
}
void declare(c_unparser &c) const
{
assert (type() == pe_stats);
c.o->newline() << "struct stat_data *" << name << ";";
}
};
struct mapvar
: public var
{
vector<exp_type> index_types;
int maxsize;
mapvar (bool local, exp_type ty,
statistic_decl const & sd,
string const & name,
vector<exp_type> const & index_types,
int maxsize)
: var (local, ty, sd, name),
index_types (index_types),
maxsize (maxsize)
{}
static string shortname(exp_type e);
static string key_typename(exp_type e);
static string value_typename(exp_type e);
string keysym () const
{
string result;
vector<exp_type> tmp = index_types;
tmp.push_back (type ());
for (unsigned i = 0; i < tmp.size(); ++i)
{
switch (tmp[i])
{
case pe_long:
result += 'i';
break;
case pe_string:
result += 's';
break;
case pe_stats:
result += 'x';
break;
default:
throw semantic_error("unknown type of map");
break;
}
}
return result;
}
string call_prefix (string const & fname, vector<tmpvar> const & indices, bool pre_agg=false) const
{
string mtype = (is_parallel() && !pre_agg) ? "pmap" : "map";
string result = "_stp_" + mtype + "_" + fname + "_" + keysym() + " (";
result += pre_agg? fetch_existing_aggregate() : value();
for (unsigned i = 0; i < indices.size(); ++i)
{
if (indices[i].type() != index_types[i])
throw semantic_error("index type mismatch");
result += ", ";
result += indices[i].value();
}
return result;
}
bool is_parallel() const
{
return type() == pe_stats;
}
string calculate_aggregate() const
{
if (!is_parallel())
throw semantic_error("aggregating non-parallel map type");
return "_stp_pmap_agg (" + value() + ")";
}
string fetch_existing_aggregate() const
{
if (!is_parallel())
throw semantic_error("fetching aggregate of non-parallel map type");
return "_stp_pmap_get_agg(" + value() + ")";
}
string del (vector<tmpvar> const & indices) const
{
return (call_prefix("del", indices) + ")");
}
string exists (vector<tmpvar> const & indices) const
{
if (type() == pe_long || type() == pe_string)
return (call_prefix("exists", indices) + ")");
else if (type() == pe_stats)
return ("((uintptr_t)" + call_prefix("get", indices)
+ ") != (uintptr_t) 0)");
else
throw semantic_error("checking existence of an unsupported map type");
}
string get (vector<tmpvar> const & indices, bool pre_agg=false) const
{
// see also itervar::get_key
if (type() == pe_string)
// impedance matching: NULL -> empty strings
return ("({ char *v = " + call_prefix("get", indices, pre_agg) + ");"
+ "if (!v) v = \"\"; v; })");
else if (type() == pe_long || type() == pe_stats)
return call_prefix("get", indices, pre_agg) + ")";
else
throw semantic_error("getting a value from an unsupported map type");
}
string add (vector<tmpvar> const & indices, tmpvar const & val) const
{
string res = "{ int rc = ";
// impedance matching: empty strings -> NULL
if (type() == pe_stats)
res += (call_prefix("add", indices) + ", " + val.value() + ")");
else
throw semantic_error("adding a value of an unsupported map type");
res += "; if (unlikely(rc)) { c->last_error = \"Array overflow, check " +
stringify(maxsize > 0 ?
"size limit (" + stringify(maxsize) + ")" : "MAXMAPENTRIES")
+ "\"; goto out; }}";
return res;
}
string set (vector<tmpvar> const & indices, tmpvar const & val) const
{
string res = "{ int rc = ";
// impedance matching: empty strings -> NULL
if (type() == pe_string)
res += (call_prefix("set", indices)
+ ", (" + val.value() + "[0] ? " + val.value() + " : NULL))");
else if (type() == pe_long)
res += (call_prefix("set", indices) + ", " + val.value() + ")");
else
throw semantic_error("setting a value of an unsupported map type");
res += "; if (unlikely(rc)) { c->last_error = \"Array overflow, check " +
stringify(maxsize > 0 ?
"size limit (" + stringify(maxsize) + ")" : "MAXMAPENTRIES")
+ "\"; goto out; }}";
return res;
}
string hist() const
{
assert (ty == pe_stats);
assert (sd.type != statistic_decl::none);
return "(&(" + fetch_existing_aggregate() + "->hist))";
}
string buckets() const
{
assert (ty == pe_stats);
assert (sd.type != statistic_decl::none);
return "(" + fetch_existing_aggregate() + "->hist.buckets)";
}
string init () const
{
string mtype = is_parallel() ? "pmap" : "map";
string prefix = value() + " = _stp_" + mtype + "_new_" + keysym() + " (" +
(maxsize > 0 ? stringify(maxsize) : "MAXMAPENTRIES") ;
// See also var::init().
// Check for errors during allocation.
string suffix = "if (" + value () + " == NULL) rc = -ENOMEM;";
if (type() == pe_stats)
{
switch (sdecl().type)
{
case statistic_decl::none:
prefix = prefix + ", HIST_NONE";
break;
case statistic_decl::linear:
// FIXME: check for "reasonable" values in linear stats
prefix = prefix + ", HIST_LINEAR"
+ ", " + stringify(sdecl().linear_low)
+ ", " + stringify(sdecl().linear_high)
+ ", " + stringify(sdecl().linear_step);
break;
case statistic_decl::logarithmic:
prefix = prefix + ", HIST_LOG";
break;
}
}
prefix = prefix + "); ";
return (prefix + suffix);
}
string fini () const
{
// NB: fini() is safe to call even for globals that have not
// successfully initialized (that is to say, on NULL pointers),
// because the runtime specifically tolerates that in its _del
// functions.
if (is_parallel())
return "_stp_pmap_del (" + value() + ");";
else
return "_stp_map_del (" + value() + ");";
}
};
class itervar
{
exp_type referent_ty;
string name;
public:
itervar (symbol* e, unsigned & counter)
: referent_ty(e->referent->type),
name("__tmp" + stringify(counter++))
{
if (referent_ty == pe_unknown)
throw semantic_error("iterating over unknown reference type", e->tok);
}
string declare () const
{
return "struct map_node *" + name + ";";
}
string start (mapvar const & mv) const
{
string res;
if (mv.type() != referent_ty)
throw semantic_error("inconsistent iterator type in itervar::start()");
if (mv.is_parallel())
return "_stp_map_start (" + mv.fetch_existing_aggregate() + ")";
else
return "_stp_map_start (" + mv.value() + ")";
}
string next (mapvar const & mv) const
{
if (mv.type() != referent_ty)
throw semantic_error("inconsistent iterator type in itervar::next()");
if (mv.is_parallel())
return "_stp_map_iter (" + mv.fetch_existing_aggregate() + ", " + value() + ")";
else
return "_stp_map_iter (" + mv.value() + ", " + value() + ")";
}
string value () const
{
return "l->" + name;
}
string get_key (exp_type ty, unsigned i) const
{
// bug translator/1175: runtime uses base index 1 for the first dimension
// see also mapval::get
switch (ty)
{
case pe_long:
return "_stp_key_get_int64 ("+ value() + ", " + stringify(i+1) + ")";
case pe_string:
// impedance matching: NULL -> empty strings
return "({ char *v = "
"_stp_key_get_str ("+ value() + ", " + stringify(i+1) + "); "
"if (! v) v = \"\"; "
"v; })";
default:
throw semantic_error("illegal key type");
}
}
};
ostream & operator<<(ostream & o, itervar const & v)
{
return o << v.value();
}
// ------------------------------------------------------------------------
translator_output::translator_output (ostream& f):
buf(0), o2 (0), o (f), tablevel (0)
{
}
translator_output::translator_output (const string& filename, size_t bufsize):
buf (new char[bufsize]),
o2 (new ofstream (filename.c_str ())),
o (*o2),
tablevel (0)
{
o2->rdbuf()->pubsetbuf(buf, bufsize);
}
translator_output::~translator_output ()
{
delete o2;
delete [] buf;
}
ostream&
translator_output::newline (int indent)
{
if (! (indent > 0 || tablevel >= (unsigned)-indent)) o.flush ();
assert (indent > 0 || tablevel >= (unsigned)-indent);
tablevel += indent;
o << "\n";
for (unsigned i=0; i<tablevel; i++)
o << " ";
return o;
}
void
translator_output::indent (int indent)
{
if (! (indent > 0 || tablevel >= (unsigned)-indent)) o.flush ();
assert (indent > 0 || tablevel >= (unsigned)-indent);
tablevel += indent;
}
ostream&
translator_output::line ()
{
return o;
}
// ------------------------------------------------------------------------
void
c_unparser::emit_common_header ()
{
o->newline();
o->newline() << "typedef char string_t[MAXSTRINGLEN];";
o->newline();
o->newline() << "#define STAP_SESSION_STARTING 0";
o->newline() << "#define STAP_SESSION_RUNNING 1";
o->newline() << "#define STAP_SESSION_ERROR 2";
o->newline() << "#define STAP_SESSION_STOPPING 3";
o->newline() << "#define STAP_SESSION_STOPPED 4";
o->newline() << "atomic_t session_state = ATOMIC_INIT (STAP_SESSION_STARTING);";
o->newline() << "atomic_t error_count = ATOMIC_INIT (0);";
o->newline() << "atomic_t skipped_count = ATOMIC_INIT (0);";
o->newline();
o->newline() << "struct context {";
o->newline(1) << "atomic_t busy;";
o->newline() << "const char *probe_point;";
o->newline() << "int actionremaining;";
o->newline() << "unsigned nesting;";
o->newline() << "string_t error_buffer;";
o->newline() << "const char *last_error;";
// NB: last_error is used as a health flag within a probe.
// While it's 0, execution continues
// When it's "something", probe code unwinds, _stp_error's, sets error state
o->newline() << "const char *last_stmt;";
o->newline() << "struct pt_regs *regs;";
o->newline() << "unsigned long *unwaddr;";
// unwaddr is caching unwound address in each probe handler on ia64.
o->newline() << "struct kretprobe_instance *pi;";
o->newline() << "int regparm;";
o->newline() << "va_list *mark_va_list;";
o->newline() << "void *data;";
o->newline() << "#ifdef STP_TIMING";
o->newline() << "Stat *statp;";
o->newline() << "#endif";
o->newline() << "#ifdef STP_OVERLOAD";
o->newline() << "cycles_t cycles_base;";
o->newline() << "cycles_t cycles_sum;";
o->newline() << "#endif";
o->newline() << "union {";
o->indent(1);
// To elide context variables for probe handler functions that
// themselves are about to get duplicate-eliminated, we XXX
// duplicate the parse-tree-hash method from ::emit_probe().
map<string, string> tmp_probe_contents;
// The reason we don't use c_unparser::probe_contents itself
// for this is that we don't want to muck up the data for
// that later routine.
for (unsigned i=0; i<session->probes.size(); i++)
{
derived_probe* dp = session->probes[i];
// NB: see c_unparser::emit_probe() for original copy of duplicate-hashing logic.
ostringstream oss;
oss << "c->statp = & time_" << dp->basest()->name << ";" << endl; // -t anti-dupe
oss << "# needs_global_locks: " << dp->needs_global_locks () << endl;
dp->body->print(oss);
// NB: dependent probe conditions *could* be listed here, but don't need to be.
// That's because they're only dependent on the probe body, which is already
// "hashed" in above.
if (tmp_probe_contents.count(oss.str()) == 0) // unique
{
tmp_probe_contents[oss.str()] = dp->name; // save it
// XXX: probe locals need not be recursion-nested, only function locals
o->newline() << "struct " << dp->name << "_locals {";
o->indent(1);
for (unsigned j=0; j<dp->locals.size(); j++)
{
vardecl* v = dp->locals[j];
try
{
o->newline() << c_typename (v->type) << " "
<< c_varname (v->name) << ";";
} catch (const semantic_error& e) {
semantic_error e2 (e);
if (e2.tok1 == 0) e2.tok1 = v->tok;
throw e2;
}
}
// NB: This part is finicky. The logic here must
// match up with
c_tmpcounter ct (this);
dp->emit_probe_context_vars (o);
dp->body->visit (& ct);
o->newline(-1) << "} " << dp->name << ";";
}
}
for (unsigned i=0; i<session->functions.size(); i++)
{
functiondecl* fd = session->functions[i];
o->newline()
<< "struct function_" << c_varname (fd->name) << "_locals {";
o->indent(1);
for (unsigned j=0; j<fd->locals.size(); j++)
{
vardecl* v = fd->locals[j];
try
{
o->newline() << c_typename (v->type) << " "
<< c_varname (v->name) << ";";
} catch (const semantic_error& e) {
semantic_error e2 (e);
if (e2.tok1 == 0) e2.tok1 = v->tok;
throw e2;
}
}
for (unsigned j=0; j<fd->formal_args.size(); j++)
{
vardecl* v = fd->formal_args[j];
try
{
o->newline() << c_typename (v->type) << " "
<< c_varname (v->name) << ";";
} catch (const semantic_error& e) {
semantic_error e2 (e);
if (e2.tok1 == 0) e2.tok1 = v->tok;
throw e2;
}
}
c_tmpcounter ct (this);
fd->body->visit (& ct);
if (fd->type == pe_unknown)
o->newline() << "/* no return value */";
else
{
o->newline() << c_typename (fd->type) << " __retvalue;";
}
o->newline(-1) << "} function_" << c_varname (fd->name) << ";";
}
o->newline(-1) << "} locals [MAXNESTING];";
o->newline(-1) << "};\n";
o->newline() << "void *contexts = NULL; /* alloc_percpu */\n";
emit_map_type_instantiations ();
if (!session->stat_decls.empty())
o->newline() << "#include \"stat.c\"\n";
o->newline();
}
void
c_unparser::emit_global_param (vardecl *v)
{
string vn = c_varname (v->name);
// NB: systemtap globals can collide with linux macros,
// e.g. VM_FAULT_MAJOR. We want the parameter name anyway. This
// #undef is spit out at the end of the C file, so that removing the
// definition won't affect any other embedded-C or generated code.
// XXX: better not have a global variable named module_param_named etc.!
o->newline() << "#undef " << vn;
// Emit module_params for this global, if its type is convenient.
if (v->arity == 0 && v->type == pe_long)
{
o->newline() << "module_param_named (" << vn << ", "
<< "global.s_" << vn << ", int64_t, 0);";
}
else if (v->arity == 0 && v->type == pe_string)
{
// NB: no special copying is needed.
o->newline() << "module_param_string (" << vn << ", "
<< "global.s_" << vn
<< ", MAXSTRINGLEN, 0);";
}
}
void
c_unparser::emit_global (vardecl *v)
{
string vn = c_varname (v->name);
if (v->arity == 0)
o->newline() << c_typename (v->type) << " s_" << vn << ";";
else if (v->type == pe_stats)
o->newline() << "PMAP s_" << vn << ";";
else
o->newline() << "MAP s_" << vn << ";";
o->newline() << "rwlock_t s_" << vn << "_lock;";
}
void
c_unparser::emit_global_init (vardecl *v)
{
string vn = c_varname (v->name);
if (v->arity == 0) // can only statically initialize some scalars
{
if (v->init)
{
o->line() << ".s_" << vn << " = ";
v->init->visit(this);
o->line() << ",";
}
}
}
void
c_unparser::emit_functionsig (functiondecl* v)
{
o->newline() << "static void function_" << v->name
<< " (struct context * __restrict__ c);";
}
void
c_unparser::emit_module_init ()
{
vector<derived_probe_group*> g = all_session_groups (*session);
for (unsigned i=0; i<g.size(); i++)
g[i]->emit_module_decls (*session);
o->newline();
o->newline() << "int systemtap_module_init (void) {";
o->newline(1) << "int rc = 0;";
o->newline() << "int i=0, j=0;"; // for derived_probe_group use
o->newline() << "const char *probe_point = \"\";";
// Compare actual and targeted kernel releases/machines. Sometimes
// one may install the incorrect debuginfo or -devel RPM, and try to
// run a probe compiled for a different version. Catch this early,
// just in case modversions didn't.
o->newline() << "{";
o->newline(1) << "const char* release = UTS_RELEASE;";
// NB: This UTS_RELEASE compile-time macro directly checks only that
// the compile-time kbuild tree matches the compile-time debuginfo/etc.
// It does not check the run time kernel value. However, this is
// probably OK since the kbuild modversions system aims to prevent
// mismatches between kbuild and runtime versions at module-loading time.
// o->newline() << "const char* machine = UTS_MACHINE;";
// NB: We could compare UTS_MACHINE too, but on x86 it lies
// (UTS_MACHINE=i386, but uname -m is i686). Sheesh.
o->newline() << "if (strcmp (release, "
<< lex_cast_qstring (session->kernel_release) << ")) {";
o->newline(1) << "_stp_error (\"module release mismatch (%s vs %s)\", "
<< "release, "
<< lex_cast_qstring (session->kernel_release)
<< ");";
o->newline() << "rc = -EINVAL;";
o->newline(-1) << "}";
// XXX: perform buildid-based checking if able
o->newline(-1) << "}";
o->newline() << "if (rc) goto out;";
o->newline() << "(void) probe_point;";
o->newline() << "(void) i;";
o->newline() << "(void) j;";
o->newline() << "atomic_set (&session_state, STAP_SESSION_STARTING);";
// This signals any other probes that may be invoked in the next little
// while to abort right away. Currently running probes are allowed to
// terminate. These may set STAP_SESSION_ERROR!
// per-cpu context
o->newline() << "if (sizeof (struct context) <= 131072)";
o->newline(1) << "contexts = alloc_percpu (struct context);";
o->newline(-1) << "if (contexts == NULL) {";
o->newline(1) << "_stp_error (\"percpu context (size %lu) allocation failed\", sizeof (struct context));";
o->newline() << "rc = -ENOMEM;";
o->newline() << "goto out;";
o->newline(-1) << "}";
for (unsigned i=0; i<session->globals.size(); i++)
{
vardecl* v = session->globals[i];
if (v->index_types.size() > 0)
o->newline() << getmap (v).init();
else
o->newline() << getvar (v).init();
// NB: in case of failure of allocation, "rc" will be set to non-zero.
// Allocation can in general continue.
o->newline() << "if (rc) {";
o->newline(1) << "_stp_error (\"global variable " << v->name << " allocation failed\");";
o->newline() << "goto out;";
o->newline(-1) << "}";
o->newline() << "rwlock_init (& global.s_" << c_varname (v->name) << "_lock);";
}
// initialize each Stat used for timing information
o->newline() << "#ifdef STP_TIMING";
set<string> basest_names;
for (unsigned i=0; i<session->probes.size(); i++)
{
string nm = session->probes[i]->basest()->name;
if (basest_names.find(nm) == basest_names.end())
{
o->newline() << "time_" << nm << " = _stp_stat_init (HIST_NONE);";
// NB: we don't check for null return here, but instead at
// passage to probe handlers and at final printing.
basest_names.insert (nm);
}
}
o->newline() << "#endif";
// Print a message to the kernel log about this module. This is
// intended to help debug problems with systemtap modules.
o->newline() << "_stp_print_kernel_info("
<< "\"" << VERSION
<< "/" << dwfl_version (NULL) << "\""
<< ", (num_online_cpus() * sizeof(struct context))"
<< ", " << session->probes.size()
<< ");";
// Run all probe registrations. This actually runs begin probes.
for (unsigned i=0; i<g.size(); i++)
{
g[i]->emit_module_init (*session);
// NB: this gives O(N**2) amount of code, but luckily there
// are only seven or eight derived_probe_groups, so it's ok.
o->newline() << "if (rc) {";
o->newline(1) << "_stp_error (\"probe %s registration error (rc %d)\", probe_point, rc);";
// NB: we need to be in the error state so timers can shutdown cleanly,
// and so end probes don't run. OTOH, error probes can run.
o->newline() << "atomic_set (&session_state, STAP_SESSION_ERROR);";
if (i>0)
for (int j=i-1; j>=0; j--)
g[j]->emit_module_exit (*session);
o->newline() << "goto out;";
o->newline(-1) << "}";
}
// All registrations were successful. Consider the system started.
o->newline() << "if (atomic_read (&session_state) == STAP_SESSION_STARTING)";
// NB: only other valid state value is ERROR, in which case we don't
o->newline(1) << "atomic_set (&session_state, STAP_SESSION_RUNNING);";
o->newline(-1) << "return 0;";
// Error handling path; by now all partially registered probe groups
// have been unregistered.
o->newline(-1) << "out:";
o->indent(1);
// If any registrations failed, we will need to deregister the globals,
// as this is our only chance.
for (unsigned i=0; i<session->globals.size(); i++)
{
vardecl* v = session->globals[i];
if (v->index_types.size() > 0)
o->newline() << getmap (v).fini();
else
o->newline() << getvar (v).fini();
}
o->newline() << "return rc;";
o->newline(-1) << "}\n";
}
void
c_unparser::emit_module_exit ()
{
o->newline() << "void systemtap_module_exit (void) {";
// rc?
o->newline(1) << "int holdon;";
o->newline() << "int i=0, j=0;"; // for derived_probe_group use
o->newline() << "(void) i;";
o->newline() << "(void) j;";
// If we aborted startup, then everything has been cleaned up already, and
// module_exit shouldn't even have been called. But since it might be, let's
// beat a hasty retreat to avoid double uninitialization.
o->newline() << "if (atomic_read (&session_state) == STAP_SESSION_STARTING)";
o->newline(1) << "return;";
o->indent(-1);
o->newline() << "if (atomic_read (&session_state) == STAP_SESSION_RUNNING)";
// NB: only other valid state value is ERROR, in which case we don't
o->newline(1) << "atomic_set (&session_state, STAP_SESSION_STOPPING);";
o->indent(-1);
// This signals any other probes that may be invoked in the next little
// while to abort right away. Currently running probes are allowed to
// terminate. These may set STAP_SESSION_ERROR!
// NB: systemtap_module_exit is assumed to be called from ordinary
// user context, say during module unload. Among other things, this
// means we can sleep a while.
o->newline() << "do {";
o->newline(1) << "int i;";
o->newline() << "holdon = 0;";
o->newline() << "for (i=0; i < NR_CPUS; i++)";
o->newline(1) << "if (cpu_possible (i) && "
<< "atomic_read (& ((struct context *)per_cpu_ptr(contexts, i))->busy)) "
<< "holdon = 1;";
o->newline () << "schedule ();";
o->newline(-2) << "} while (holdon);";
// XXX: might like to have an escape hatch, in case some probe is
// genuinely stuck somehow
// Notice we're processing the derived_probe_group list in reverse
// order. This ensures that probes get unregistered in reverse
// order of the way they were registered.
vector<derived_probe_group*> g = all_session_groups (*session);
for (vector<derived_probe_group*>::reverse_iterator i = g.rbegin();
i != g.rend(); i++)
(*i)->emit_module_exit (*session); // NB: runs "end" probes
for (unsigned i=0; i<session->globals.size(); i++)
{
vardecl* v = session->globals[i];
if (v->index_types.size() > 0)
o->newline() << getmap (v).fini();
else
o->newline() << getvar (v).fini();
}
o->newline() << "free_percpu (contexts);";
// print probe timing statistics
{
o->newline() << "#ifdef STP_TIMING";
o->newline() << "{";
o->indent(1);
set<string> basest_names;
for (unsigned i=0; i<session->probes.size(); i++)
{
probe* p = session->probes[i]->basest();
string nm = p->name;
if (basest_names.find(nm) == basest_names.end())
{
basest_names.insert (nm);
// NB: check for null stat object
o->newline() << "if (likely (time_" << p->name << ")) {";
o->newline(1) << "const char *probe_point = "
<< lex_cast_qstring (* p->locations[0])
<< (p->locations.size() > 1 ? "\"+\"" : "")
<< (p->locations.size() > 1 ? lex_cast_qstring(p->locations.size()-1) : "")
<< ";";
o->newline() << "const char *decl_location = "
<< lex_cast_qstring (p->tok->location)
<< ";";
o->newline() << "struct stat_data *stats = _stp_stat_get (time_"
<< p->name
<< ", 0);";
o->newline() << "if (stats->count) {";
o->newline(1) << "int64_t avg = _stp_div64 (NULL, stats->sum, stats->count);";
o->newline() << "_stp_printf (\"probe %s (%s), hits: %lld, cycles: %lldmin/%lldavg/%lldmax\\n\",";
o->newline() << "probe_point, decl_location, (long long) stats->count, (long long) stats->min, (long long) avg, (long long) stats->max);";
o->newline(-1) << "}";
o->newline() << "_stp_stat_del (time_" << p->name << ");";
o->newline(-1) << "}";
}
}
o->newline() << "_stp_print_flush();";
o->newline(-1) << "}";
o->newline() << "#endif";
}
// print final error/reentrancy counts if non-zero
o->newline() << "if (atomic_read (& skipped_count) || "
<< "atomic_read (& error_count)) {";
o->newline(1) << "_stp_warn (\"Number of errors: %d, "
<< "skipped probes: %d\\n\", "
<< "(int) atomic_read (& error_count), "
<< "(int) atomic_read (& skipped_count));";
o->newline() << "_stp_print_flush();";
o->newline(-1) << "}";
o->newline(-1) << "}\n";
}
void
c_unparser::emit_function (functiondecl* v)
{
o->newline() << "void function_" << c_varname (v->name)
<< " (struct context* __restrict__ c) {";
o->indent(1);
this->current_probe = 0;
this->current_function = v;
this->tmpvar_counter = 0;
this->action_counter = 0;
o->newline()
<< "struct function_" << c_varname (v->name) << "_locals * "
<< " __restrict__ l =";
o->newline(1)
<< "& c->locals[c->nesting+1].function_" << c_varname (v->name) // NB: nesting+1
<< ";";
o->newline(-1) << "(void) l;"; // make sure "l" is marked used
o->newline() << "#define CONTEXT c";
o->newline() << "#define THIS l";
o->newline() << "if (0) goto out;"; // make sure out: is marked used
// set this, in case embedded-c code sets last_error but doesn't otherwise identify itself
o->newline() << "c->last_stmt = " << lex_cast_qstring(*v->tok) << ";";
// check/increment nesting level
o->newline() << "if (unlikely (c->nesting+2 >= MAXNESTING)) {";
o->newline(1) << "c->last_error = \"MAXNESTING exceeded\";";
o->newline() << "return;";
o->newline(-1) << "} else {";
o->newline(1) << "c->nesting ++;";
o->newline(-1) << "}";
// initialize locals
// XXX: optimization: use memset instead
for (unsigned i=0; i<v->locals.size(); i++)
{
if (v->locals[i]->index_types.size() > 0) // array?
throw semantic_error ("array locals not supported, missing global declaration?",
v->locals[i]->tok);
o->newline() << getvar (v->locals[i]).init();
}
// initialize return value, if any
if (v->type != pe_unknown)
{
var retvalue = var(true, v->type, "__retvalue");
o->newline() << retvalue.init();
}
o->newline() << "#define return goto out"; // redirect embedded-C return
this->probe_or_function_needs_deref_fault_handler = false;
v->body->visit (this);
o->newline() << "#undef return";
this->current_function = 0;
record_actions(0, true);
if (this->probe_or_function_needs_deref_fault_handler) {
// Emit this handler only if the body included a
// print/printf/etc. using a string or memory buffer!
o->newline() << "CATCH_DEREF_FAULT ();";
}
o->newline(-1) << "out:";
o->newline(1) << ";";
// Function prologue: this is why we redirect the "return" above.
// Decrement nesting level.
o->newline() << "c->nesting --;";
o->newline() << "#undef CONTEXT";
o->newline() << "#undef THIS";
o->newline(-1) << "}\n";
}
#define DUPMETHOD_CALL 0
#define DUPMETHOD_ALIAS 0
#define DUPMETHOD_RENAME 1
void
c_unparser::emit_probe (derived_probe* v)
{
this->current_function = 0;
this->current_probe = v;
this->tmpvar_counter = 0;
this->action_counter = 0;
// If we about to emit a probe that is exactly the same as another
// probe previously emitted, make the second probe just call the
// first one.
//
// Notice we're using the probe body itself instead of the emitted C
// probe body to compare probes. We need to do this because the
// emitted C probe body has stuff in it like:
// c->last_stmt = "identifier 'printf' at foo.stp:<line>:<column>";
//
// which would make comparisons impossible.
//
// --------------------------------------------------------------------------
// NB: see also c_unparser:emit_common_header(), which deliberately but sadly
// duplicates this calculation.
// --------------------------------------------------------------------------
//
ostringstream oss;
// NB: statp is just for avoiding designation as duplicate. It need not be C.
// NB: This code *could* be enclosed in an "if (session->timing)". That would
// recognize more duplicate probe handlers, but then the generated code could
// be very different with or without -t.
oss << "c->statp = & time_" << v->basest()->name << ";" << endl;
v->body->print(oss);
// Since the generated C changes based on whether or not the probe
// needs locks around global variables, this needs to be reflected
// here. We don't want to treat as duplicate the handlers of
// begin/end and normal probes that differ only in need_global_locks.
oss << "# needs_global_locks: " << v->needs_global_locks () << endl;
// If an identical probe has already been emitted, just call that
// one.
if (probe_contents.count(oss.str()) != 0)
{
string dupe = probe_contents[oss.str()];
// NB: Elision of context variable structs is a separate
// operation which has already taken place by now.
if (session->verbose > 1)
clog << v->name << " elided, duplicates " << dupe << endl;
#if DUPMETHOD_CALL
// This one emits a direct call to the first copy.
o->newline();
o->newline() << "static void " << v->name << " (struct context * __restrict__ c) ";
o->newline() << "{ " << dupe << " (c); }";
#elif DUPMETHOD_ALIAS
// This one defines a function alias, arranging gcc to emit
// several equivalent symbols for the same function body.
// For some reason, on gcc 4.1, this is twice as slow as
// the CALL option.
o->newline();
o->newline() << "static void " << v->name << " (struct context * __restrict__ c) ";
o->line() << "__attribute__ ((alias (\"" << dupe << "\")));";
#elif DUPMETHOD_RENAME
// This one is sneaky. It emits nothing for duplicate probe
// handlers. It instead redirects subsequent references to the
// probe handler function to the first copy, *by name*.
v->name = dupe;
#else
#error "Unknown duplicate elimination method"
#endif
}
else // This probe is unique. Remember it and output it.
{
this->probe_or_function_needs_deref_fault_handler = false;
o->newline();
o->newline() << "#ifdef STP_TIMING";
o->newline() << "static __cacheline_aligned Stat " << "time_" << v->basest()->name << ";";
o->newline() << "#endif";
o->newline();
o->newline() << "static void " << v->name << " (struct context * __restrict__ c) ";
o->line () << "{";
o->indent (1);
probe_contents[oss.str()] = v->name;
// initialize frame pointer
o->newline() << "struct " << v->name << "_locals * __restrict__ l =";
o->newline(1) << "& c->locals[0]." << v->name << ";";
o->newline(-1) << "(void) l;"; // make sure "l" is marked used
o->newline() << "#ifdef STP_TIMING";
o->newline() << "c->statp = & time_" << v->basest()->name << ";";
o->newline() << "#endif";
// emit probe local initialization block
v->emit_probe_local_init(o);
// emit all read/write locks for global variables
varuse_collecting_visitor vut;
if (v->needs_global_locks ())
{
v->body->visit (& vut);
emit_locks (vut);
}
// initialize locals
for (unsigned j=0; j<v->locals.size(); j++)
{
if (v->locals[j]->index_types.size() > 0) // array?
throw semantic_error ("array locals not supported, missing global declaration?",
v->locals[j]->tok);
else if (v->locals[j]->type == pe_long)
o->newline() << "l->" << c_varname (v->locals[j]->name)
<< " = 0;";
else if (v->locals[j]->type == pe_string)
o->newline() << "l->" << c_varname (v->locals[j]->name)
<< "[0] = '\\0';";
else
throw semantic_error ("unsupported local variable type",
v->locals[j]->tok);
}
v->initialize_probe_context_vars (o);
v->body->visit (this);
record_actions(0, true);
if (this->probe_or_function_needs_deref_fault_handler) {
// Emit this handler only if the body included a
// print/printf/etc. using a string or memory buffer!
o->newline() << "CATCH_DEREF_FAULT ();";
}
o->newline(-1) << "out:";
// NB: no need to uninitialize locals, except if arrays/stats can
// someday be local
// XXX: do this flush only if the body included a
// print/printf/etc. routine!
o->newline(1) << "_stp_print_flush();";
if (v->needs_global_locks ())
emit_unlocks (vut);
o->newline(-1) << "}\n";
}
this->current_probe = 0;
}
void
c_unparser::emit_locks(const varuse_collecting_visitor& vut)
{
o->newline() << "{";
o->newline(1) << "unsigned numtrylock = 0;";
o->newline() << "(void) numtrylock;";
string last_locked_var;
for (unsigned i = 0; i < session->globals.size(); i++)
{
vardecl* v = session->globals[i];
bool read_p = vut.read.find(v) != vut.read.end();
bool write_p = vut.written.find(v) != vut.written.end();
if (!read_p && !write_p) continue;
if (v->type == pe_stats) // read and write locks are flipped
// Specifically, a "<<<" to a stats object is considered a
// "shared-lock" operation, since it's implicitly done
// per-cpu. But a "@op(x)" extraction is an "exclusive-lock"
// one, as is a (sorted or unsorted) foreach, so those cases
// are excluded by the w & !r condition below.
{
if (write_p && !read_p) { read_p = true; write_p = false; }
else if (read_p && !write_p) { read_p = false; write_p = true; }
}
// We don't need to read lock "read-mostly" global variables. A
// "read-mostly" global variable is only written to within
// probes that don't need global variable locking (such as
// begin/end probes). If vcv_needs_global_locks doesn't mark
// the global as written to, then we don't have to lock it
// here to read it safely.
if (read_p && !write_p)
{
if (vcv_needs_global_locks.written.find(v)
== vcv_needs_global_locks.written.end())
continue;
}
string lockcall =
string (write_p ? "write" : "read") +
"_trylock (& global.s_" + v->name + "_lock)";
o->newline() << "while (! " << lockcall
<< "&& (++numtrylock < MAXTRYLOCK))";
o->newline(1) << "ndelay (TRYLOCKDELAY);";
o->newline(-1) << "if (unlikely (numtrylock >= MAXTRYLOCK)) {";
o->newline(1) << "atomic_inc (& skipped_count);";
// The following works even if i==0. Note that using
// globals[i-1]->name is wrong since that global may not have
// been lockworthy by this probe.
o->newline() << "goto unlock_" << last_locked_var << ";";
o->newline(-1) << "}";
last_locked_var = v->name;
}
o->newline() << "if (0) goto unlock_;";
o->newline(-1) << "}";
}
void
c_unparser::emit_unlocks(const varuse_collecting_visitor& vut)
{
unsigned numvars = 0;
if (session->verbose>1)
clog << current_probe->name << " locks ";
for (int i = session->globals.size()-1; i>=0; i--) // in reverse order!
{
vardecl* v = session->globals[i];
bool read_p = vut.read.find(v) != vut.read.end();
bool write_p = vut.written.find(v) != vut.written.end();
if (!read_p && !write_p) continue;
// Duplicate lock flipping logic from above
if (v->type == pe_stats)
{
if (write_p && !read_p) { read_p = true; write_p = false; }
else if (read_p && !write_p) { read_p = false; write_p = true; }
}
// Duplicate "read-mostly" global variable logic from above.
if (read_p && !write_p)
{
if (vcv_needs_global_locks.written.find(v)
== vcv_needs_global_locks.written.end())
continue;
}
numvars ++;
o->newline(-1) << "unlock_" << v->name << ":";
o->indent(1);
if (session->verbose>1)
clog << v->name << "[" << (read_p ? "r" : "")
<< (write_p ? "w" : "") << "] ";
if (write_p) // emit write lock
o->newline() << "write_unlock (& global.s_" << v->name << "_lock);";
else // (read_p && !write_p) : emit read lock
o->newline() << "read_unlock (& global.s_" << v->name << "_lock);";
// fall through to next variable; thus the reverse ordering
}
// emit plain "unlock" label, used if the very first lock failed.
o->newline(-1) << "unlock_: ;";
o->indent(1);
if (numvars) // is there a chance that any lock attempt failed?
{
o->newline() << "if (atomic_read (& skipped_count) > MAXSKIPPED) {";
// XXX: In this known non-reentrant context, we could print a more
// informative error.
o->newline(1) << "atomic_set (& session_state, STAP_SESSION_ERROR);";
o->newline() << "_stp_exit();";
o->newline(-1) << "}";
if (session->verbose>1)
clog << endl;
}
else if (session->verbose>1)
clog << "nothing" << endl;
}
void
c_unparser::collect_map_index_types(vector<vardecl *> const & vars,
set< pair<vector<exp_type>, exp_type> > & types)
{
for (unsigned i = 0; i < vars.size(); ++i)
{
vardecl *v = vars[i];
if (v->arity > 0)
{
types.insert(make_pair(v->index_types, v->type));
}
}
}
string
mapvar::value_typename(exp_type e)
{
switch (e)
{
case pe_long:
return "INT64";
case pe_string:
return "STRING";
case pe_stats:
return "STAT";
default:
throw semantic_error("array type is neither string nor long");
}
return "";
}
string
mapvar::key_typename(exp_type e)
{
switch (e)
{
case pe_long:
return "INT64";
case pe_string:
return "STRING";
default:
throw semantic_error("array key is neither string nor long");
}
return "";
}
string
mapvar::shortname(exp_type e)
{
switch (e)
{
case pe_long:
return "i";
case pe_string:
return "s";
default:
throw semantic_error("array type is neither string nor long");
}
return "";
}
void
c_unparser::emit_map_type_instantiations ()
{
set< pair<vector<exp_type>, exp_type> > types;
collect_map_index_types(session->globals, types);
for (unsigned i = 0; i < session->probes.size(); ++i)
collect_map_index_types(session->probes[i]->locals, types);
for (unsigned i = 0; i < session->functions.size(); ++i)
collect_map_index_types(session->functions[i]->locals, types);
if (!types.empty())
o->newline() << "#include \"alloc.c\"";
for (set< pair<vector<exp_type>, exp_type> >::const_iterator i = types.begin();
i != types.end(); ++i)
{
o->newline() << "#define VALUE_TYPE " << mapvar::value_typename(i->second);
for (unsigned j = 0; j < i->first.size(); ++j)
{
string ktype = mapvar::key_typename(i->first.at(j));
o->newline() << "#define KEY" << (j+1) << "_TYPE " << ktype;
}
if (i->second == pe_stats)
o->newline() << "#include \"pmap-gen.c\"";
else
o->newline() << "#include \"map-gen.c\"";
o->newline() << "#undef VALUE_TYPE";
for (unsigned j = 0; j < i->first.size(); ++j)
{
o->newline() << "#undef KEY" << (j+1) << "_TYPE";
}
/* FIXME
* For pmaps, we also need to include map-gen.c, because we might be accessing
* the aggregated map. The better way to handle this is for pmap-gen.c to make
* this include, but that's impossible with the way they are set up now.
*/
if (i->second == pe_stats)
{
o->newline() << "#define VALUE_TYPE " << mapvar::value_typename(i->second);
for (unsigned j = 0; j < i->first.size(); ++j)
{
string ktype = mapvar::key_typename(i->first.at(j));
o->newline() << "#define KEY" << (j+1) << "_TYPE " << ktype;
}
o->newline() << "#include \"map-gen.c\"";
o->newline() << "#undef VALUE_TYPE";
for (unsigned j = 0; j < i->first.size(); ++j)
{
o->newline() << "#undef KEY" << (j+1) << "_TYPE";
}
}
}
if (!types.empty())
o->newline() << "#include \"map.c\"";
};
string
c_unparser::c_typename (exp_type e)
{
switch (e)
{
case pe_long: return string("int64_t");
case pe_string: return string("string_t");
case pe_stats: return string("Stat");
case pe_unknown:
default:
throw semantic_error ("cannot expand unknown type");
}
}
string
c_unparser::c_varname (const string& e)
{
// XXX: safeify, uniquefy, given name
return e;
}
string
c_unparser::c_expression (expression *e)
{
// We want to evaluate expression 'e' and return its value as a
// string. In the case of expressions that are just numeric
// constants, if we just print the value into a string, it won't
// have the same value as being visited by c_unparser. For
// instance, a numeric constant evaluated using print() would return
// "5", while c_unparser::visit_literal_number() would
// return "((int64_t)5LL)". String constants evaluated using
// print() would just return the string, while
// c_unparser::visit_literal_string() would return the string with
// escaped double quote characters. So, we need to "visit" the
// expression.
// However, we have to be careful of side effects. Currently this
// code is only being used for evaluating literal numbers and
// strings, which currently have no side effects. Until needed
// otherwise, limit the use of this function to literal numbers and
// strings.
if (e->tok->type != tok_number && e->tok->type != tok_string)
throw semantic_error("unsupported c_expression token type");
// Create a fake output stream so we can grab the string output.
ostringstream oss;
translator_output tmp_o(oss);
// Temporarily swap out the real translator_output stream with our
// fake one.
translator_output *saved_o = o;
o = &tmp_o;
// Visit the expression then restore the original output stream
e->visit (this);
o = saved_o;
return (oss.str());
}
void
c_unparser::c_assign (var& lvalue, const string& rvalue, const token *tok)
{
switch (lvalue.type())
{
case pe_string:
c_strcpy(lvalue.value(), rvalue);
break;
case pe_long:
o->newline() << lvalue << " = " << rvalue << ";";
break;
default:
throw semantic_error ("unknown lvalue type in assignment", tok);
}
}
void
c_unparser::c_assign (const string& lvalue, expression* rvalue,
const string& msg)
{
if (rvalue->type == pe_long)
{
o->newline() << lvalue << " = ";
rvalue->visit (this);
o->line() << ";";
}
else if (rvalue->type == pe_string)
{
c_strcpy (lvalue, rvalue);
}
else
{
string fullmsg = msg + " type unsupported";
throw semantic_error (fullmsg, rvalue->tok);
}
}
void
c_unparser::c_assign (const string& lvalue, const string& rvalue,
exp_type type, const string& msg, const token* tok)
{
if (type == pe_long)
{
o->newline() << lvalue << " = " << rvalue << ";";
}
else if (type == pe_string)
{
c_strcpy (lvalue, rvalue);
}
else
{
string fullmsg = msg + " type unsupported";
throw semantic_error (fullmsg, tok);
}
}
void
c_unparser_assignment::c_assignop(tmpvar & res,
var const & lval,
tmpvar const & rval,
token const * tok)
{
// This is common code used by scalar and array-element assignments.
// It assumes an operator-and-assignment (defined by the 'pre' and
// 'op' fields of c_unparser_assignment) is taking place between the
// following set of variables:
//
// res: the result of evaluating the expression, a temporary
// lval: the lvalue of the expression, which may be damaged
// rval: the rvalue of the expression, which is a temporary or constant
// we'd like to work with a local tmpvar so we can overwrite it in
// some optimized cases
translator_output* o = parent->o;
if (res.type() == pe_string)
{
if (post)
throw semantic_error ("post assignment on strings not supported",
tok);
if (op == "=")
{
parent->c_strcpy (lval.value(), rval.value());
// no need for second copy
res = rval;
}
else if (op == ".=")
{
parent->c_strcat (lval.value(), rval.value());
res = lval;
}
else
throw semantic_error ("string assignment operator " +
op + " unsupported", tok);
}
else if (op == "<<<")
{
assert(lval.type() == pe_stats);
assert(rval.type() == pe_long);
assert(res.type() == pe_long);
o->newline() << res << " = " << rval << ";";
o->newline() << "_stp_stat_add (" << lval << ", " << res << ");";
}
else if (res.type() == pe_long)
{
// a lot of operators come through this "gate":
// - vanilla assignment "="
// - stats aggregation "<<<"
// - modify-accumulate "+=" and many friends
// - pre/post-crement "++"/"--"
// - "/" and "%" operators, but these need special handling in kernel
// compute the modify portion of a modify-accumulate
string macop;
unsigned oplen = op.size();
if (op == "=")
macop = "*error*"; // special shortcuts below
else if (op == "++" || op == "+=")
macop = "+=";
else if (op == "--" || op == "-=")
macop = "-=";
else if (oplen > 1 && op[oplen-1] == '=') // for *=, <<=, etc...
macop = op;
else
// internal error
throw semantic_error ("unknown macop for assignment", tok);
if (post)
{
if (macop == "/" || macop == "%" || op == "=")
throw semantic_error ("invalid post-mode operator", tok);
o->newline() << res << " = " << lval << ";";
if (macop == "+=" || macop == "-=")
o->newline() << lval << " " << macop << " " << rval << ";";
else
o->newline() << lval << " = " << res << " " << macop << " " << rval << ";";
}
else
{
if (op == "=") // shortcut simple assignment
{
o->newline() << lval << " = " << rval << ";";
res = rval;
}
else
{
if (macop == "/=" || macop == "%=")
{
o->newline() << "if (unlikely(!" << rval << ")) {";
o->newline(1) << "c->last_error = \"division by 0\";";
o->newline() << "goto out;";
o->newline(-1) << "}";
o->newline() << lval << " = "
<< ((macop == "/=") ? "_stp_div64" : "_stp_mod64")
<< " (NULL, " << lval << ", " << rval << ");";
}
else
o->newline() << lval << " " << macop << " " << rval << ";";
res = lval;
}
}
}
else
throw semantic_error ("assignment type not yet implemented", tok);
}
void
c_unparser::c_declare(exp_type ty, const string &name)
{
o->newline() << c_typename (ty) << " " << c_varname (name) << ";";
}
void
c_unparser::c_declare_static(exp_type ty, const string &name)
{
o->newline() << "static " << c_typename (ty) << " " << c_varname (name) << ";";
}
void
c_unparser::c_strcpy (const string& lvalue, const string& rvalue)
{
o->newline() << "strlcpy ("
<< lvalue << ", "
<< rvalue << ", MAXSTRINGLEN);";
}
void
c_unparser::c_strcpy (const string& lvalue, expression* rvalue)
{
o->newline() << "strlcpy (" << lvalue << ", ";
rvalue->visit (this);
o->line() << ", MAXSTRINGLEN);";
}
void
c_unparser::c_strcat (const string& lvalue, const string& rvalue)
{
o->newline() << "strlcat ("
<< lvalue << ", "
<< rvalue << ", MAXSTRINGLEN);";
}
void
c_unparser::c_strcat (const string& lvalue, expression* rvalue)
{
o->newline() << "strlcat (" << lvalue << ", ";
rvalue->visit (this);
o->line() << ", MAXSTRINGLEN);";
}
bool
c_unparser::is_local(vardecl const *r, token const *tok)
{
if (current_probe)
{
for (unsigned i=0; i<current_probe->locals.size(); i++)
{
if (current_probe->locals[i] == r)
return true;
}
}
else if (current_function)
{
for (unsigned i=0; i<current_function->locals.size(); i++)
{
if (current_function->locals[i] == r)
return true;
}
for (unsigned i=0; i<current_function->formal_args.size(); i++)
{
if (current_function->formal_args[i] == r)
return true;
}
}
for (unsigned i=0; i<session->globals.size(); i++)
{
if (session->globals[i] == r)
return false;
}
if (tok)
throw semantic_error ("unresolved symbol", tok);
else
throw semantic_error ("unresolved symbol: " + r->name);
}
tmpvar
c_unparser::gensym(exp_type ty)
{
return tmpvar (ty, tmpvar_counter);
}
aggvar
c_unparser::gensym_aggregate()
{
return aggvar (tmpvar_counter);
}
var
c_unparser::getvar(vardecl *v, token const *tok)
{
bool loc = is_local (v, tok);
if (loc)
return var (loc, v->type, v->name);
else
{
statistic_decl sd;
std::map<std::string, statistic_decl>::const_iterator i;
i = session->stat_decls.find(v->name);
if (i != session->stat_decls.end())
sd = i->second;
return var (loc, v->type, sd, v->name);
}
}
mapvar
c_unparser::getmap(vardecl *v, token const *tok)
{
if (v->arity < 1)
throw semantic_error("attempt to use scalar where map expected", tok);
statistic_decl sd;
std::map<std::string, statistic_decl>::const_iterator i;
i = session->stat_decls.find(v->name);
if (i != session->stat_decls.end())
sd = i->second;
return mapvar (is_local (v, tok), v->type, sd,
v->name, v->index_types, v->maxsize);
}
itervar
c_unparser::getiter(symbol *s)
{
return itervar (s, tmpvar_counter);
}
// Queue up some actions to remove from actionremaining. Set update=true at
// the end of basic blocks to actually update actionremaining and check it
// against MAXACTION.
void
c_unparser::record_actions (unsigned actions, bool update)
{
action_counter += actions;
// Update if needed, or after queueing up a few actions, in case of very
// large code sequences.
if ((update && action_counter > 0) || action_counter >= 10/*<-arbitrary*/)
{
o->newline() << "c->actionremaining -= " << action_counter << ";";
o->newline() << "if (unlikely (c->actionremaining <= 0)) {";
o->newline(1) << "c->last_error = \"MAXACTION exceeded\";";
o->newline() << "goto out;";
o->newline(-1) << "}";
action_counter = 0;
}
}
void
c_unparser::visit_block (block *s)
{
o->newline() << "{";
o->indent (1);
for (unsigned i=0; i<s->statements.size(); i++)
{
try
{
s->statements[i]->visit (this);
o->newline();
}
catch (const semantic_error& e)
{
session->print_error (e);
}
}
o->newline(-1) << "}";
}
void
c_unparser::visit_embeddedcode (embeddedcode *s)
{
o->newline() << "{";
o->newline(1) << s->code;
o->newline(-1) << "}";
}
void
c_unparser::visit_null_statement (null_statement *)
{
o->newline() << "/* null */;";
}
void
c_unparser::visit_expr_statement (expr_statement *s)
{
o->newline() << "(void) ";
s->value->visit (this);
o->line() << ";";
record_actions(1);
}
void
c_unparser::visit_if_statement (if_statement *s)
{
record_actions(1, true);
o->newline() << "if (";
o->indent (1);
s->condition->visit (this);
o->indent (-1);
o->line() << ") {";
o->indent (1);
s->thenblock->visit (this);
record_actions(0, true);
o->newline(-1) << "}";
if (s->elseblock)
{
o->newline() << "else {";
o->indent (1);
s->elseblock->visit (this);
record_actions(0, true);
o->newline(-1) << "}";
}
}
void
c_tmpcounter::visit_block (block *s)
{
// Key insight: individual statements of a block can reuse
// temporary variable slots, since temporaries don't survive
// statement boundaries. So we use gcc's anonymous union/struct
// facility to explicitly overlay the temporaries.
parent->o->newline() << "union {";
parent->o->indent(1);
for (unsigned i=0; i<s->statements.size(); i++)
{
// To avoid lots of empty structs inside the union, remember
// where we are now. Then, output the struct start and remember
// that positon. If when we get done with the statement we
// haven't moved, then we don't really need the struct. To get
// rid of the struct start we output, we'll seek back to where
// we were before we output the struct.
std::ostream::pos_type before_struct_pos = parent->o->tellp();
parent->o->newline() << "struct {";
parent->o->indent(1);
std::ostream::pos_type after_struct_pos = parent->o->tellp();
s->statements[i]->visit (this);
parent->o->indent(-1);
if (after_struct_pos == parent->o->tellp())
parent->o->seekp(before_struct_pos);
else
parent->o->newline() << "};";
}
parent->o->newline(-1) << "};";
}
void
c_tmpcounter::visit_for_loop (for_loop *s)
{
if (s->init) s->init->visit (this);
s->cond->visit (this);
s->block->visit (this);
if (s->incr) s->incr->visit (this);
}
void
c_unparser::visit_for_loop (for_loop *s)
{
string ctr = stringify (label_counter++);
string toplabel = "top_" + ctr;
string contlabel = "continue_" + ctr;
string breaklabel = "break_" + ctr;
// initialization
if (s->init) s->init->visit (this);
record_actions(1, true);
// condition
o->newline(-1) << toplabel << ":";
// Emit an explicit action here to cover the act of iteration.
// Equivalently, it can stand for the evaluation of the condition
// expression.
o->indent(1);
record_actions(1);
o->newline() << "if (! (";
if (s->cond->type != pe_long)
throw semantic_error ("expected numeric type", s->cond->tok);
s->cond->visit (this);
o->line() << ")) goto " << breaklabel << ";";
// body
loop_break_labels.push_back (breaklabel);
loop_continue_labels.push_back (contlabel);
s->block->visit (this);
record_actions(0, true);
loop_break_labels.pop_back ();
loop_continue_labels.pop_back ();
// iteration
o->newline(-1) << contlabel << ":";
o->indent(1);
if (s->incr) s->incr->visit (this);
o->newline() << "goto " << toplabel << ";";
// exit
o->newline(-1) << breaklabel << ":";
o->newline(1) << "; /* dummy statement */";
}
struct arrayindex_downcaster
: public traversing_visitor
{
arrayindex *& arr;
arrayindex_downcaster (arrayindex *& arr)
: arr(arr)
{}
void visit_arrayindex (arrayindex* e)
{
arr = e;
}
};
static bool
expression_is_arrayindex (expression *e,
arrayindex *& hist)
{
arrayindex *h = NULL;
arrayindex_downcaster d(h);
e->visit (&d);
if (static_cast<void*>(h) == static_cast<void*>(e))
{
hist = h;
return true;
}
return false;
}
void
c_tmpcounter::visit_foreach_loop (foreach_loop *s)
{
symbol *array;
hist_op *hist;
classify_indexable (s->base, array, hist);
if (array)
{
itervar iv = parent->getiter (array);
parent->o->newline() << iv.declare();
}
else
{
// See commentary in c_tmpcounter::visit_arrayindex for
// discussion of tmpvars required to look into @hist_op(...)
// expressions.
// First make sure we have exactly one pe_long variable to use as
// our bucket index.
if (s->indexes.size() != 1 || s->indexes[0]->referent->type != pe_long)
throw semantic_error("Invalid indexing of histogram", s->tok);
// Then declare what we need to form the aggregate we're
// iterating over, and all the tmpvars needed by our call to
// load_aggregate().
aggvar agg = parent->gensym_aggregate ();
agg.declare(*(this->parent));
symbol *sym = get_symbol_within_expression (hist->stat);
var v = parent->getvar(sym->referent, sym->tok);
if (sym->referent->arity != 0)
{
arrayindex *arr = NULL;
if (!expression_is_arrayindex (hist->stat, arr))
throw semantic_error("expected arrayindex expression in iterated hist_op", s->tok);
for (unsigned i=0; i<sym->referent->index_types.size(); i++)
{
tmpvar ix = parent->gensym (sym->referent->index_types[i]);
ix.declare (*parent);
arr->indexes[i]->visit(this);
}
}
}
// Create a temporary for the loop limit counter and the limit
// expression result.
if (s->limit)
{
tmpvar res_limit = parent->gensym (pe_long);
res_limit.declare(*parent);
s->limit->visit (this);
tmpvar limitv = parent->gensym (pe_long);
limitv.declare(*parent);
}
s->block->visit (this);
}
void
c_unparser::visit_foreach_loop (foreach_loop *s)
{
symbol *array;
hist_op *hist;
classify_indexable (s->base, array, hist);
if (array)
{
mapvar mv = getmap (array->referent, s->tok);
itervar iv = getiter (array);
vector<var> keys;
string ctr = stringify (label_counter++);
string toplabel = "top_" + ctr;
string contlabel = "continue_" + ctr;
string breaklabel = "break_" + ctr;
// NB: structure parallels for_loop
// initialization
tmpvar *res_limit = NULL;
if (s->limit)
{
// Evaluate the limit expression once.
res_limit = new tmpvar(gensym(pe_long));
c_assign (res_limit->value(), s->limit, "foreach limit");
}
// aggregate array if required
if (mv.is_parallel())
{
o->newline() << "if (unlikely(NULL == " << mv.calculate_aggregate() << ")) {";
o->newline(1) << "c->last_error = \"aggregation overflow in " << mv << "\";";
o->newline() << "goto out;";
o->newline(-1) << "}";
// sort array if desired
if (s->sort_direction)
{
int sort_column;
// If the user wanted us to sort by value, we'll sort by
// @count instead for aggregates. '-5' tells the
// runtime to sort by count.
if (s->sort_column == 0)
sort_column = -5;
else
sort_column = s->sort_column;
o->newline() << "else"; // only sort if aggregation was ok
if (s->limit)
{
o->newline(1) << "_stp_map_sortn ("
<< mv.fetch_existing_aggregate() << ", "
<< *res_limit << ", " << sort_column << ", "
<< - s->sort_direction << ");";
}
else
{
o->newline(1) << "_stp_map_sort ("
<< mv.fetch_existing_aggregate() << ", "
<< sort_column << ", "
<< - s->sort_direction << ");";
}
o->indent(-1);
}
}
else
{
// sort array if desired
if (s->sort_direction)
{
if (s->limit)
{
o->newline() << "_stp_map_sortn (" << mv.value() << ", "
<< *res_limit << ", " << s->sort_column << ", "
<< - s->sort_direction << ");";
}
else
{
o->newline() << "_stp_map_sort (" << mv.value() << ", "
<< s->sort_column << ", "
<< - s->sort_direction << ");";
}
}
}
// NB: sort direction sense is opposite in runtime, thus the negation
if (mv.is_parallel())
aggregations_active.insert(mv.value());
o->newline() << iv << " = " << iv.start (mv) << ";";
tmpvar *limitv = NULL;
if (s->limit)
{
// Create the loop limit variable here and initialize it.
limitv = new tmpvar(gensym (pe_long));
o->newline() << *limitv << " = 0LL;";
}
record_actions(1, true);
// condition
o->newline(-1) << toplabel << ":";
// Emit an explicit action here to cover the act of iteration.
// Equivalently, it can stand for the evaluation of the
// condition expression.
o->indent(1);
record_actions(1);
o->newline() << "if (! (" << iv << ")) goto " << breaklabel << ";";
// body
loop_break_labels.push_back (breaklabel);
loop_continue_labels.push_back (contlabel);
o->newline() << "{";
o->indent (1);
if (s->limit)
{
// If we've been through LIMIT loop iterations, quit.
o->newline() << "if (" << *limitv << "++ >= " << *res_limit
<< ") goto " << breaklabel << ";";
// We're done with limitv and res_limit.
delete limitv;
delete res_limit;
}
for (unsigned i = 0; i < s->indexes.size(); ++i)
{
// copy the iter values into the specified locals
var v = getvar (s->indexes[i]->referent);
c_assign (v, iv.get_key (v.type(), i), s->tok);
}
s->block->visit (this);
record_actions(0, true);
o->newline(-1) << "}";
loop_break_labels.pop_back ();
loop_continue_labels.pop_back ();
// iteration
o->newline(-1) << contlabel << ":";
o->newline(1) << iv << " = " << iv.next (mv) << ";";
o->newline() << "goto " << toplabel << ";";
// exit
o->newline(-1) << breaklabel << ":";
o->newline(1) << "; /* dummy statement */";
if (mv.is_parallel())
aggregations_active.erase(mv.value());
}
else
{
// Iterating over buckets in a histogram.
assert(s->indexes.size() == 1);
assert(s->indexes[0]->referent->type == pe_long);
var bucketvar = getvar (s->indexes[0]->referent);
aggvar agg = gensym_aggregate ();
load_aggregate(hist->stat, agg);
symbol *sym = get_symbol_within_expression (hist->stat);
var v = getvar(sym->referent, sym->tok);
v.assert_hist_compatible(*hist);
tmpvar *res_limit = NULL;
tmpvar *limitv = NULL;
if (s->limit)
{
// Evaluate the limit expression once.
res_limit = new tmpvar(gensym(pe_long));
c_assign (res_limit->value(), s->limit, "foreach limit");
// Create the loop limit variable here and initialize it.
limitv = new tmpvar(gensym (pe_long));
o->newline() << *limitv << " = 0LL;";
}
// XXX: break / continue don't work here yet
record_actions(1, true);
o->newline() << "for (" << bucketvar << " = 0; "
<< bucketvar << " < " << v.buckets() << "; "
<< bucketvar << "++) { ";
o->newline(1);
if (s->limit)
{
// If we've been through LIMIT loop iterations, quit.
o->newline() << "if (" << *limitv << "++ >= " << *res_limit
<< ") break;";
// We're done with limitv and res_limit.
delete limitv;
delete res_limit;
}
s->block->visit (this);
record_actions(1, true);
o->newline(-1) << "}";
}
}
void
c_unparser::visit_return_statement (return_statement* s)
{
if (current_function == 0)
throw semantic_error ("cannot 'return' from probe", s->tok);
if (s->value->type != current_function->type)
throw semantic_error ("return type mismatch", current_function->tok,
"vs", s->tok);
c_assign ("l->__retvalue", s->value, "return value");
record_actions(1, true);
o->newline() << "goto out;";
}
void
c_unparser::visit_next_statement (next_statement* s)
{
if (current_probe == 0)
throw semantic_error ("cannot 'next' from function", s->tok);
record_actions(1, true);
o->newline() << "goto out;";
}
struct delete_statement_operand_tmp_visitor:
public traversing_visitor
{
c_tmpcounter *parent;
delete_statement_operand_tmp_visitor (c_tmpcounter *p):
parent (p)
{}
//void visit_symbol (symbol* e);
void visit_arrayindex (arrayindex* e);
};
struct delete_statement_operand_visitor:
public throwing_visitor
{
c_unparser *parent;
delete_statement_operand_visitor (c_unparser *p):
throwing_visitor ("invalid operand of delete expression"),
parent (p)
{}
void visit_symbol (symbol* e);
void visit_arrayindex (arrayindex* e);
};
void
delete_statement_operand_visitor::visit_symbol (symbol* e)
{
assert (e->referent != 0);
if (e->referent->arity > 0)
{
mapvar mvar = parent->getmap(e->referent, e->tok);
/* NB: Memory deallocation/allocation operations
are not generally safe.
parent->o->newline() << mvar.fini ();
parent->o->newline() << mvar.init ();
*/
if (mvar.is_parallel())
parent->o->newline() << "_stp_pmap_clear (" << mvar.value() << ");";
else
parent->o->newline() << "_stp_map_clear (" << mvar.value() << ");";
}
else
{
var v = parent->getvar(e->referent, e->tok);
switch (e->type)
{
case pe_stats:
parent->o->newline() << "_stp_stat_clear (" << v.value() << ");";
break;
case pe_long:
parent->o->newline() << v.value() << " = 0;";
break;
case pe_string:
parent->o->newline() << v.value() << "[0] = '\\0';";
break;
case pe_unknown:
default:
throw semantic_error("Cannot delete unknown expression type", e->tok);
}
}
}
void
delete_statement_operand_tmp_visitor::visit_arrayindex (arrayindex* e)
{
symbol *array;
hist_op *hist;
classify_indexable (e->base, array, hist);
if (array)
{
assert (array->referent != 0);
vardecl* r = array->referent;
// One temporary per index dimension.
for (unsigned i=0; i<r->index_types.size(); i++)
{
tmpvar ix = parent->parent->gensym (r->index_types[i]);
ix.declare (*(parent->parent));
e->indexes[i]->visit(parent);
}
}
else
{
throw semantic_error("cannot delete histogram bucket entries\n", e->tok);
}
}
void
delete_statement_operand_visitor::visit_arrayindex (arrayindex* e)
{
symbol *array;
hist_op *hist;
classify_indexable (e->base, array, hist);
if (array)
{
vector<tmpvar> idx;
parent->load_map_indices (e, idx);
{
mapvar mvar = parent->getmap (array->referent, e->tok);
parent->o->newline() << mvar.del (idx) << ";";
}
}
else
{
throw semantic_error("cannot delete histogram bucket entries\n", e->tok);
}
}
void
c_tmpcounter::visit_delete_statement (delete_statement* s)
{
delete_statement_operand_tmp_visitor dv (this);
s->value->visit (&dv);
}
void
c_unparser::visit_delete_statement (delete_statement* s)
{
delete_statement_operand_visitor dv (this);
s->value->visit (&dv);
record_actions(1);
}
void
c_unparser::visit_break_statement (break_statement* s)
{
if (loop_break_labels.size() == 0)
throw semantic_error ("cannot 'break' outside loop", s->tok);
record_actions(1, true);
string label = loop_break_labels[loop_break_labels.size()-1];
o->newline() << "goto " << label << ";";
}
void
c_unparser::visit_continue_statement (continue_statement* s)
{
if (loop_continue_labels.size() == 0)
throw semantic_error ("cannot 'continue' outside loop", s->tok);
record_actions(1, true);
string label = loop_continue_labels[loop_continue_labels.size()-1];
o->newline() << "goto " << label << ";";
}
void
c_unparser::visit_literal_string (literal_string* e)
{
const string& v = e->value;
o->line() << '"';
for (unsigned i=0; i<v.size(); i++)
// NB: The backslash character is specifically passed through as is.
// This is because our parser treats "\" as an ordinary character, not
// an escape sequence, leaving it to the C compiler (and this function)
// to treat it as such. If we were to escape it, there would be no way
// of generating C-level escapes from script code.
// See also print_format::components_to_string and lex_cast_qstring
if (v[i] == '"') // or other escapeworthy characters?
o->line() << '\\' << '"';
else
o->line() << v[i];
o->line() << '"';
}
void
c_unparser::visit_literal_number (literal_number* e)
{
// This looks ugly, but tries to be warning-free on 32- and 64-bit
// hosts.
// NB: this needs to be signed!
if (e->value == -9223372036854775807LL-1) // PR 5023
o->line() << "((int64_t)" << (unsigned long long) e->value << "ULL)";
else
o->line() << "((int64_t)" << e->value << "LL)";
}
void
c_tmpcounter::visit_binary_expression (binary_expression* e)
{
if (e->op == "/" || e->op == "%")
{
tmpvar left = parent->gensym (pe_long);
tmpvar right = parent->gensym (pe_long);
if (e->left->tok->type != tok_number)
left.declare (*parent);
if (e->right->tok->type != tok_number)
right.declare (*parent);
}
e->left->visit (this);
e->right->visit (this);
}
void
c_unparser::visit_binary_expression (binary_expression* e)
{
if (e->type != pe_long ||
e->left->type != pe_long ||
e->right->type != pe_long)
throw semantic_error ("expected numeric types", e->tok);
if (e->op == "+" ||
e->op == "-" ||
e->op == "*" ||
e->op == "&" ||
e->op == "|" ||
e->op == "^")
{
o->line() << "((";
e->left->visit (this);
o->line() << ") " << e->op << " (";
e->right->visit (this);
o->line() << "))";
}
else if (e->op == ">>" ||
e->op == "<<")
{
o->line() << "((";
e->left->visit (this);
o->line() << ") " << e->op << "max(min(";
e->right->visit (this);
o->line() << ", (int64_t)64LL), (int64_t)0LL))"; // between 0 and 64
}
else if (e->op == "/" ||
e->op == "%")
{
// % and / need a division-by-zero check; and thus two temporaries
// for proper evaluation order
tmpvar left = gensym (pe_long);
tmpvar right = gensym (pe_long);
o->line() << "({";
o->indent(1);
if (e->left->tok->type == tok_number)
left.override(c_expression(e->left));
else
{
o->newline() << left << " = ";
e->left->visit (this);
o->line() << ";";
}
if (e->right->tok->type == tok_number)
right.override(c_expression(e->right));
else
{
o->newline() << right << " = ";
e->right->visit (this);
o->line() << ";";
}
o->newline() << "if (unlikely(!" << right << ")) {";
o->newline(1) << "c->last_error = \"division by 0\";";
o->newline() << "c->last_stmt = " << lex_cast_qstring(*e->tok) << ";";
o->newline() << "goto out;";
o->newline(-1) << "}";
o->newline() << ((e->op == "/") ? "_stp_div64" : "_stp_mod64")
<< " (NULL, " << left << ", " << right << ");";
o->newline(-1) << "})";
}
else
throw semantic_error ("operator not yet implemented", e->tok);
}
void
c_unparser::visit_unary_expression (unary_expression* e)
{
if (e->type != pe_long ||
e->operand->type != pe_long)
throw semantic_error ("expected numeric types", e->tok);
if (e->op == "-")
{
// NB: Subtraction is special, since negative literals in the
// script language show up as unary negations over positive
// literals here. This makes it "exciting" for emitting pure
// C since: - 0x8000_0000_0000_0000 ==> - (- 9223372036854775808)
// This would constitute a signed overflow, which gcc warns on
// unless -ftrapv/-J are in CFLAGS - which they're not.
o->line() << "(int64_t)(0 " << e->op << " (uint64_t)(";
e->operand->visit (this);
o->line() << "))";
}
else
{
o->line() << "(" << e->op << " (";
e->operand->visit (this);
o->line() << "))";
}
}
void
c_unparser::visit_logical_or_expr (logical_or_expr* e)
{
if (e->type != pe_long ||
e->left->type != pe_long ||
e->right->type != pe_long)
throw semantic_error ("expected numeric types", e->tok);
o->line() << "((";
e->left->visit (this);
o->line() << ") " << e->op << " (";
e->right->visit (this);
o->line() << "))";
}
void
c_unparser::visit_logical_and_expr (logical_and_expr* e)
{
if (e->type != pe_long ||
e->left->type != pe_long ||
e->right->type != pe_long)
throw semantic_error ("expected numeric types", e->tok);
o->line() << "((";
e->left->visit (this);
o->line() << ") " << e->op << " (";
e->right->visit (this);
o->line() << "))";
}
void
c_tmpcounter::visit_array_in (array_in* e)
{
symbol *array;
hist_op *hist;
classify_indexable (e->operand->base, array, hist);
if (array)
{
assert (array->referent != 0);
vardecl* r = array->referent;
// One temporary per index dimension.
for (unsigned i=0; i<r->index_types.size(); i++)
{
tmpvar ix = parent->gensym (r->index_types[i]);
ix.declare (*parent);
e->operand->indexes[i]->visit(this);
}
// A boolean result.
tmpvar res = parent->gensym (e->type);
res.declare (*parent);
}
else
{
// By definition:
//
// 'foo in @hist_op(...)' is true iff
// '@hist_op(...)[foo]' is nonzero
//
// so we just delegate to the latter call, since int64_t is also
// our boolean type.
e->operand->visit(this);
}
}
void
c_unparser::visit_array_in (array_in* e)
{
symbol *array;
hist_op *hist;
classify_indexable (e->operand->base, array, hist);
if (array)
{
stmt_expr block(*this);
vector<tmpvar> idx;
load_map_indices (e->operand, idx);
// o->newline() << "c->last_stmt = " << lex_cast_qstring(*e->tok) << ";";
tmpvar res = gensym (pe_long);
mapvar mvar = getmap (array->referent, e->tok);
c_assign (res, mvar.exists(idx), e->tok);
o->newline() << res << ";";
}
else
{
// By definition:
//
// 'foo in @hist_op(...)' is true iff
// '@hist_op(...)[foo]' is nonzero
//
// so we just delegate to the latter call, since int64_t is also
// our boolean type.
e->operand->visit(this);
}
}
void
c_unparser::visit_comparison (comparison* e)
{
o->line() << "(";
if (e->left->type == pe_string)
{
if (e->right->type != pe_string)
throw semantic_error ("expected string types", e->tok);
o->line() << "strncmp (";
e->left->visit (this);
o->line() << ", ";
e->right->visit (this);
o->line() << ", MAXSTRINGLEN";
o->line() << ") " << e->op << " 0";
}
else if (e->left->type == pe_long)
{
if (e->right->type != pe_long)
throw semantic_error ("expected numeric types", e->tok);
o->line() << "((";
e->left->visit (this);
o->line() << ") " << e->op << " (";
e->right->visit (this);
o->line() << "))";
}
else
throw semantic_error ("unexpected type", e->left->tok);
o->line() << ")";
}
void
c_tmpcounter::visit_concatenation (concatenation* e)
{
tmpvar t = parent->gensym (e->type);
t.declare (*parent);
e->left->visit (this);
e->right->visit (this);
}
void
c_unparser::visit_concatenation (concatenation* e)
{
if (e->op != ".")
throw semantic_error ("unexpected concatenation operator", e->tok);
if (e->type != pe_string ||
e->left->type != pe_string ||
e->right->type != pe_string)
throw semantic_error ("expected string types", e->tok);
tmpvar t = gensym (e->type);
o->line() << "({ ";
o->indent(1);
// o->newline() << "c->last_stmt = " << lex_cast_qstring(*e->tok) << ";";
c_assign (t.value(), e->left, "assignment");
c_strcat (t.value(), e->right);
o->newline() << t << ";";
o->newline(-1) << "})";
}
void
c_unparser::visit_ternary_expression (ternary_expression* e)
{
if (e->cond->type != pe_long)
throw semantic_error ("expected numeric condition", e->cond->tok);
if (e->truevalue->type != e->falsevalue->type ||
e->type != e->truevalue->type ||
(e->truevalue->type != pe_long && e->truevalue->type != pe_string))
throw semantic_error ("expected matching types", e->tok);
o->line() << "((";
e->cond->visit (this);
o->line() << ") ? (";
e->truevalue->visit (this);
o->line() << ") : (";
e->falsevalue->visit (this);
o->line() << "))";
}
void
c_tmpcounter::visit_assignment (assignment *e)
{
c_tmpcounter_assignment tav (this, e->op, e->right);
e->left->visit (& tav);
}
void
c_unparser::visit_assignment (assignment* e)
{
if (e->op == "<<<")
{
if (e->type != pe_long)
throw semantic_error ("non-number <<< expression", e->tok);
if (e->left->type != pe_stats)
throw semantic_error ("non-stats left operand to <<< expression", e->left->tok);
if (e->right->type != pe_long)
throw semantic_error ("non-number right operand to <<< expression", e->right->tok);
}
else
{
if (e->type != e->left->type)
throw semantic_error ("type mismatch", e->tok,
"vs", e->left->tok);
if (e->right->type != e->left->type)
throw semantic_error ("type mismatch", e->right->tok,
"vs", e->left->tok);
}
c_unparser_assignment tav (this, e->op, e->right);
e->left->visit (& tav);
}
void
c_tmpcounter::visit_pre_crement (pre_crement* e)
{
c_tmpcounter_assignment tav (this, e->op, 0);
e->operand->visit (& tav);
}
void
c_unparser::visit_pre_crement (pre_crement* e)
{
if (e->type != pe_long ||
e->type != e->operand->type)
throw semantic_error ("expected numeric type", e->tok);
c_unparser_assignment tav (this, e->op, false);
e->operand->visit (& tav);
}
void
c_tmpcounter::visit_post_crement (post_crement* e)
{
c_tmpcounter_assignment tav (this, e->op, 0, true);
e->operand->visit (& tav);
}
void
c_unparser::visit_post_crement (post_crement* e)
{
if (e->type != pe_long ||
e->type != e->operand->type)
throw semantic_error ("expected numeric type", e->tok);
c_unparser_assignment tav (this, e->op, true);
e->operand->visit (& tav);
}
void
c_unparser::visit_symbol (symbol* e)
{
assert (e->referent != 0);
vardecl* r = e->referent;
if (r->index_types.size() != 0)
throw semantic_error ("invalid reference to array", e->tok);
var v = getvar(r, e->tok);
o->line() << v;
}
void
c_tmpcounter_assignment::prepare_rvalue (tmpvar & rval)
{
if (rvalue)
{
// literal number and strings don't need any temporaries declared
if (rvalue->tok->type != tok_number && rvalue->tok->type != tok_string)
rval.declare (*(parent->parent));
rvalue->visit (parent);
}
}
void
c_tmpcounter_assignment::c_assignop(tmpvar & res)
{
if (res.type() == pe_string)
{
// string assignment doesn't need any temporaries declared
}
else if (op == "<<<")
res.declare (*(parent->parent));
else if (res.type() == pe_long)
{
// Only the 'post' operators ('x++') need a temporary declared.
if (post)
res.declare (*(parent->parent));
}
}
// Assignment expansion is tricky.
//
// Because assignments are nestable expressions, we have
// to emit C constructs that are nestable expressions too.
// We have to evaluate the given expressions the proper number of times,
// including array indices.
// We have to lock the lvalue (if global) against concurrent modification,
// especially with modify-assignment operations (+=, ++).
// We have to check the rvalue (for division-by-zero checks).
// In the normal "pre=false" case, for (A op B) emit:
// ({ tmp = B; check(B); lock(A); res = A op tmp; A = res; unlock(A); res; })
// In the "pre=true" case, emit instead:
// ({ tmp = B; check(B); lock(A); res = A; A = res op tmp; unlock(A); res; })
//
// (op is the plain operator portion of a combined calculate/assignment:
// "+" for "+=", and so on. It is in the "macop" variable below.)
//
// For array assignments, additional temporaries are used for each
// index, which are expanded before the "tmp=B" expression, in order
// to consistently order evaluation of lhs before rhs.
//
void
c_tmpcounter_assignment::visit_symbol (symbol *e)
{
exp_type ty = rvalue ? rvalue->type : e->type;
tmpvar rval = parent->parent->gensym (ty);
tmpvar res = parent->parent->gensym (ty);
prepare_rvalue(rval);
c_assignop (res);
}
void
c_unparser_assignment::prepare_rvalue (string const & op,
tmpvar & rval,
token const * tok)
{
if (rvalue)
{
if (rvalue->tok->type == tok_number || rvalue->tok->type == tok_string)
// Instead of assigning the numeric or string constant to a
// temporary, then assigning the temporary to the final, let's
// just override the temporary with the constant.
rval.override(parent->c_expression(rvalue));
else
parent->c_assign (rval.value(), rvalue, "assignment");
}
else
{
if (op == "++" || op == "--")
// Here is part of the conversion proccess of turning "x++" to
// "x += 1".
rval.override("1");
else
throw semantic_error ("need rvalue for assignment", tok);
}
}
void
c_unparser_assignment::visit_symbol (symbol *e)
{
stmt_expr block(*parent);
assert (e->referent != 0);
if (e->referent->index_types.size() != 0)
throw semantic_error ("unexpected reference to array", e->tok);
// parent->o->newline() << "c->last_stmt = " << lex_cast_qstring(*e->tok) << ";";
exp_type ty = rvalue ? rvalue->type : e->type;
tmpvar rval = parent->gensym (ty);
tmpvar res = parent->gensym (ty);
prepare_rvalue (op, rval, e->tok);
var lvar = parent->getvar (e->referent, e->tok);
c_assignop (res, lvar, rval, e->tok);
parent->o->newline() << res << ";";
}
void
c_unparser::visit_target_symbol (target_symbol* e)
{
throw semantic_error("cannot translate general target-symbol expression", e->tok);
}
void
c_tmpcounter::load_map_indices(arrayindex *e)
{
symbol *array;
hist_op *hist;
classify_indexable (e->base, array, hist);
if (array)
{
assert (array->referent != 0);
vardecl* r = array->referent;
// One temporary per index dimension, except in the case of
// number or string constants.
for (unsigned i=0; i<r->index_types.size(); i++)
{
tmpvar ix = parent->gensym (r->index_types[i]);
if (e->indexes[i]->tok->type == tok_number
|| e->indexes[i]->tok->type == tok_string)
{
// Do nothing
}
else
ix.declare (*parent);
e->indexes[i]->visit(this);
}
}
}
void
c_unparser::load_map_indices(arrayindex *e,
vector<tmpvar> & idx)
{
symbol *array;
hist_op *hist;
classify_indexable (e->base, array, hist);
if (array)
{
idx.clear();
assert (array->referent != 0);
vardecl* r = array->referent;
if (r->index_types.size() == 0 ||
r->index_types.size() != e->indexes.size())
throw semantic_error ("invalid array reference", e->tok);
for (unsigned i=0; i<r->index_types.size(); i++)
{
if (r->index_types[i] != e->indexes[i]->type)
throw semantic_error ("array index type mismatch", e->indexes[i]->tok);
tmpvar ix = gensym (r->index_types[i]);
if (e->indexes[i]->tok->type == tok_number
|| e->indexes[i]->tok->type == tok_string)
// Instead of assigning the numeric or string constant to a
// temporary, then using the temporary, let's just
// override the temporary with the constant.
ix.override(c_expression(e->indexes[i]));
else
{
// o->newline() << "c->last_stmt = "
// << lex_cast_qstring(*e->indexes[i]->tok) << ";";
c_assign (ix.value(), e->indexes[i], "array index copy");
}
idx.push_back (ix);
}
}
else
{
assert (e->indexes.size() == 1);
assert (e->indexes[0]->type == pe_long);
tmpvar ix = gensym (pe_long);
// o->newline() << "c->last_stmt = "
// << lex_cast_qstring(*e->indexes[0]->tok) << ";";
c_assign (ix.value(), e->indexes[0], "array index copy");
idx.push_back(ix);
}
}
void
c_unparser::load_aggregate (expression *e, aggvar & agg, bool pre_agg)
{
symbol *sym = get_symbol_within_expression (e);
if (sym->referent->type != pe_stats)
throw semantic_error ("unexpected aggregate of non-statistic", sym->tok);
var v = getvar(sym->referent, e->tok);
if (sym->referent->arity == 0)
{
// o->newline() << "c->last_stmt = " << lex_cast_qstring(*sym->tok) << ";";
o->newline() << agg << " = _stp_stat_get (" << v << ", 0);";
}
else
{
arrayindex *arr = NULL;
if (!expression_is_arrayindex (e, arr))
throw semantic_error("unexpected aggregate of non-arrayindex", e->tok);
vector<tmpvar> idx;
load_map_indices (arr, idx);
mapvar mvar = getmap (sym->referent, sym->tok);
// o->newline() << "c->last_stmt = " << lex_cast_qstring(*sym->tok) << ";";
o->newline() << agg << " = " << mvar.get(idx, pre_agg) << ";";
}
}
string
c_unparser::histogram_index_check(var & base, tmpvar & idx) const
{
return "((" + idx.value() + " >= 0)"
+ " && (" + idx.value() + " < " + base.buckets() + "))";
}
void
c_tmpcounter::visit_arrayindex (arrayindex *e)
{
symbol *array;
hist_op *hist;
classify_indexable (e->base, array, hist);
if (array)
{
load_map_indices(e);
// The index-expression result.
tmpvar res = parent->gensym (e->type);
res.declare (*parent);
}
else
{
assert(hist);
// Note: this is a slightly tricker-than-it-looks allocation of
// temporaries. The reason is that we're in the branch handling
// histogram-indexing, and the histogram might be build over an
// indexable entity itself. For example if we have:
//
// global foo
// ...
// foo[getpid(), geteuid()] <<< 1
// ...
// print @log_hist(foo[pid, euid])[bucket]
//
// We are looking at the @log_hist(...)[bucket] expression, so
// allocating one tmpvar for calculating bucket (the "index" of
// this arrayindex expression), and one tmpvar for storing the
// result in, just as normal.
//
// But we are *also* going to call load_aggregate on foo, which
// will itself require tmpvars for each of its indices. Since
// this is not handled by delving into the subexpression (it
// would be if hist were first-class in the type system, but
// it's not) we we allocate all the tmpvars used in such a
// subexpression up here: first our own aggvar, then our index
// (bucket) tmpvar, then all the index tmpvars of our
// pe_stat-valued subexpression, then our result.
// First all the stuff related to indexing into the histogram
if (e->indexes.size() != 1)
throw semantic_error("Invalid indexing of histogram", e->tok);
tmpvar ix = parent->gensym (pe_long);
ix.declare (*parent);
e->indexes[0]->visit(this);
tmpvar res = parent->gensym (pe_long);
res.declare (*parent);
// Then the aggregate, and all the tmpvars needed by our call to
// load_aggregate().
aggvar agg = parent->gensym_aggregate ();
agg.declare(*(this->parent));
symbol *sym = get_symbol_within_expression (hist->stat);
var v = parent->getvar(sym->referent, sym->tok);
if (sym->referent->arity != 0)
{
arrayindex *arr = NULL;
if (!expression_is_arrayindex (hist->stat, arr))
throw semantic_error("expected arrayindex expression in indexed hist_op", e->tok);
for (unsigned i=0; i<sym->referent->index_types.size(); i++)
{
tmpvar ix = parent->gensym (sym->referent->index_types[i]);
ix.declare (*parent);
arr->indexes[i]->visit(this);
}
}
}
}
void
c_unparser::visit_arrayindex (arrayindex* e)
{
symbol *array;
hist_op *hist;
classify_indexable (e->base, array, hist);
if (array)
{
// Visiting an statistic-valued array in a non-lvalue context is prohibited.
if (array->referent->type == pe_stats)
throw semantic_error ("statistic-valued array in rvalue context", e->tok);
stmt_expr block(*this);
// NB: Do not adjust the order of the next few lines; the tmpvar
// allocation order must remain the same between
// c_unparser::visit_arrayindex and c_tmpcounter::visit_arrayindex
vector<tmpvar> idx;
load_map_indices (e, idx);
tmpvar res = gensym (e->type);
mapvar mvar = getmap (array->referent, e->tok);
// o->newline() << "c->last_stmt = " << lex_cast_qstring(*e->tok) << ";";
c_assign (res, mvar.get(idx), e->tok);
o->newline() << res << ";";
}
else
{
// See commentary in c_tmpcounter::visit_arrayindex
assert(hist);
stmt_expr block(*this);
// NB: Do not adjust the order of the next few lines; the tmpvar
// allocation order must remain the same between
// c_unparser::visit_arrayindex and c_tmpcounter::visit_arrayindex
vector<tmpvar> idx;
load_map_indices (e, idx);
tmpvar res = gensym (e->type);
aggvar agg = gensym_aggregate ();
// These should have faulted during elaboration if not true.
assert(idx.size() == 1);
assert(idx[0].type() == pe_long);
symbol *sym = get_symbol_within_expression (hist->stat);
var *v;
if (sym->referent->arity < 1)
v = new var(getvar(sym->referent, e->tok));
else
v = new mapvar(getmap(sym->referent, e->tok));
v->assert_hist_compatible(*hist);
if (aggregations_active.count(v->value()))
load_aggregate(hist->stat, agg, true);
else
load_aggregate(hist->stat, agg, false);
o->newline() << "c->last_stmt = " << lex_cast_qstring(*e->tok) << ";";
// PR 2142+2610: empty aggregates
o->newline() << "if (unlikely (" << agg.value() << " == NULL)"
<< " || " << agg.value() << "->count == 0) {";
o->newline(1) << "c->last_error = \"empty aggregate\";";
o->newline() << "goto out;";
o->newline(-1) << "} else {";
o->newline(1) << "if (" << histogram_index_check(*v, idx[0]) << ")";
o->newline(1) << res << " = " << agg << "->histogram[" << idx[0] << "];";
o->newline(-1) << "else {";
o->newline(1) << "c->last_error = \"histogram index out of range\";";
o->newline() << "goto out;";
o->newline(-1) << "}";
o->newline(-1) << "}";
o->newline() << res << ";";
delete v;
}
}
void
c_tmpcounter_assignment::visit_arrayindex (arrayindex *e)
{
symbol *array;
hist_op *hist;
classify_indexable (e->base, array, hist);
if (array)
{
parent->load_map_indices(e);
// The expression rval, lval, and result.
exp_type ty = rvalue ? rvalue->type : e->type;
tmpvar rval = parent->parent->gensym (ty);
tmpvar lval = parent->parent->gensym (ty);
tmpvar res = parent->parent->gensym (ty);
prepare_rvalue(rval);
lval.declare (*(parent->parent));
if (op == "<<<")
res.declare (*(parent->parent));
else
c_assignop(res);
}
else
{
throw semantic_error("cannot assign to histogram buckets", e->tok);
}
}
void
c_unparser_assignment::visit_arrayindex (arrayindex *e)
{
symbol *array;
hist_op *hist;
classify_indexable (e->base, array, hist);
if (array)
{
stmt_expr block(*parent);
translator_output *o = parent->o;
if (array->referent->index_types.size() == 0)
throw semantic_error ("unexpected reference to scalar", e->tok);
// nb: Do not adjust the order of the next few lines; the tmpvar
// allocation order must remain the same between
// c_unparser_assignment::visit_arrayindex and
// c_tmpcounter_assignment::visit_arrayindex
vector<tmpvar> idx;
parent->load_map_indices (e, idx);
exp_type ty = rvalue ? rvalue->type : e->type;
tmpvar rvar = parent->gensym (ty);
tmpvar lvar = parent->gensym (ty);
tmpvar res = parent->gensym (ty);
// NB: because these expressions are nestable, emit this construct
// thusly:
// ({ tmp0=(idx0); ... tmpN=(idxN); rvar=(rhs); lvar; res;
// lock (array);
// lvar = get (array,idx0...N); // if necessary
// assignop (res, lvar, rvar);
// set (array, idx0...N, lvar);
// unlock (array);
// res; })
//
// we store all indices in temporary variables to avoid nasty
// reentrancy issues that pop up with nested expressions:
// e.g. ++a[a[c]=5] could deadlock
//
//
// There is an exception to the above form: if we're doign a <<< assigment to
// a statistic-valued map, there's a special form we follow:
//
// ({ tmp0=(idx0); ... tmpN=(idxN); rvar=(rhs);
// *no need to* lock (array);
// _stp_map_add_stat (array, idx0...N, rvar);
// *no need to* unlock (array);
// rvar; })
//
// To simplify variable-allocation rules, we assign rvar to lvar and
// res in this block as well, even though they are technically
// superfluous.
prepare_rvalue (op, rvar, e->tok);
if (op == "<<<")
{
assert (e->type == pe_stats);
assert (rvalue->type == pe_long);
mapvar mvar = parent->getmap (array->referent, e->tok);
// o->newline() << "c->last_stmt = " << lex_cast_qstring(*e->tok) << ";";
o->newline() << mvar.add (idx, rvar) << ";";
res = rvar;
// no need for these dummy assignments
// o->newline() << lvar << " = " << rvar << ";";
// o->newline() << res << " = " << rvar << ";";
}
else
{
mapvar mvar = parent->getmap (array->referent, e->tok);
// o->newline() << "c->last_stmt = " << lex_cast_qstring(*e->tok) << ";";
if (op != "=") // don't bother fetch slot if we will just overwrite it
parent->c_assign (lvar, mvar.get(idx), e->tok);
c_assignop (res, lvar, rvar, e->tok);
o->newline() << mvar.set (idx, lvar) << ";";
}
o->newline() << res << ";";
}
else
{
throw semantic_error("cannot assign to histogram buckets", e->tok);
}
}
void
c_tmpcounter::visit_functioncall (functioncall *e)
{
assert (e->referent != 0);
functiondecl* r = e->referent;
// one temporary per argument, unless literal numbers or strings
for (unsigned i=0; i<r->formal_args.size(); i++)
{
tmpvar t = parent->gensym (r->formal_args[i]->type);
if (e->args[i]->tok->type != tok_number
&& e->args[i]->tok->type != tok_string)
t.declare (*parent);
e->args[i]->visit (this);
}
}
void
c_unparser::visit_functioncall (functioncall* e)
{
assert (e->referent != 0);
functiondecl* r = e->referent;
if (r->formal_args.size() != e->args.size())
throw semantic_error ("invalid length argument list", e->tok);
stmt_expr block(*this);
// NB: we store all actual arguments in temporary variables,
// to avoid colliding sharing of context variables with
// nested function calls: f(f(f(1)))
// compute actual arguments
vector<tmpvar> tmp;
for (unsigned i=0; i<e->args.size(); i++)
{
tmpvar t = gensym(e->args[i]->type);
if (r->formal_args[i]->type != e->args[i]->type)
throw semantic_error ("function argument type mismatch",
e->args[i]->tok, "vs", r->formal_args[i]->tok);
if (e->args[i]->tok->type == tok_number
|| e->args[i]->tok->type == tok_string)
t.override(c_expression(e->args[i]));
else
{
// o->newline() << "c->last_stmt = "
// << lex_cast_qstring(*e->args[i]->tok) << ";";
c_assign (t.value(), e->args[i],
"function actual argument evaluation");
}
tmp.push_back(t);
}
// copy in actual arguments
for (unsigned i=0; i<e->args.size(); i++)
{
if (r->formal_args[i]->type != e->args[i]->type)
throw semantic_error ("function argument type mismatch",
e->args[i]->tok, "vs", r->formal_args[i]->tok);
c_assign ("c->locals[c->nesting+1].function_" +
c_varname (r->name) + "." +
c_varname (r->formal_args[i]->name),
tmp[i].value(),
e->args[i]->type,
"function actual argument copy",
e->args[i]->tok);
}
// call function
o->newline() << "function_" << c_varname (r->name) << " (c);";
o->newline() << "if (unlikely(c->last_error)) goto out;";
// return result from retvalue slot
if (r->type == pe_unknown)
// If we passed typechecking, then nothing will use this return value
o->newline() << "(void) 0;";
else
o->newline() << "c->locals[c->nesting+1]"
<< ".function_" << c_varname (r->name)
<< ".__retvalue;";
}
void
c_tmpcounter::visit_print_format (print_format* e)
{
if (e->hist)
{
symbol *sym = get_symbol_within_expression (e->hist->stat);
var v = parent->getvar(sym->referent, sym->tok);
aggvar agg = parent->gensym_aggregate ();
agg.declare(*(this->parent));
if (sym->referent->arity != 0)
{
// One temporary per index dimension.
for (unsigned i=0; i<sym->referent->index_types.size(); i++)
{
arrayindex *arr = NULL;
if (!expression_is_arrayindex (e->hist->stat, arr))
throw semantic_error("expected arrayindex expression in printed hist_op", e->tok);
tmpvar ix = parent->gensym (sym->referent->index_types[i]);
ix.declare (*parent);
arr->indexes[i]->visit(this);
}
}
}
else
{
// One temporary per argument
for (unsigned i=0; i < e->args.size(); i++)
{
tmpvar t = parent->gensym (e->args[i]->type);
if (e->args[i]->type == pe_unknown)
{
throw semantic_error("unknown type of arg to print operator",
e->args[i]->tok);
}
if (e->args[i]->tok->type != tok_number
&& e->args[i]->tok->type != tok_string)
t.declare (*parent);
e->args[i]->visit (this);
}
// And the result
exp_type ty = e->print_to_stream ? pe_long : pe_string;
tmpvar res = parent->gensym (ty);
if (ty == pe_string)
res.declare (*parent);
}
}
void
c_unparser::visit_print_format (print_format* e)
{
// Print formats can contain a general argument list *or* a special
// type of argument which gets its own processing: a single,
// non-format-string'ed, histogram-type stat_op expression.
if (e->hist)
{
stmt_expr block(*this);
symbol *sym = get_symbol_within_expression (e->hist->stat);
aggvar agg = gensym_aggregate ();
var *v;
if (sym->referent->arity < 1)
v = new var(getvar(sym->referent, e->tok));
else
v = new mapvar(getmap(sym->referent, e->tok));
v->assert_hist_compatible(*e->hist);
{
if (aggregations_active.count(v->value()))
load_aggregate(e->hist->stat, agg, true);
else
load_aggregate(e->hist->stat, agg, false);
// PR 2142+2610: empty aggregates
o->newline() << "if (unlikely (" << agg.value() << " == NULL)"
<< " || " << agg.value() << "->count == 0) {";
o->newline(1) << "c->last_error = \"empty aggregate\";";
o->newline() << "c->last_stmt = " << lex_cast_qstring(*e->tok) << ";";
o->newline() << "goto out;";
o->newline(-1) << "} else";
o->newline(1) << "_stp_stat_print_histogram (" << v->hist() << ", " << agg.value() << ");";
o->indent(-1);
}
delete v;
}
else
{
stmt_expr block(*this);
// Compute actual arguments
vector<tmpvar> tmp;
for (unsigned i=0; i<e->args.size(); i++)
{
tmpvar t = gensym(e->args[i]->type);
tmp.push_back(t);
// o->newline() << "c->last_stmt = "
// << lex_cast_qstring(*e->args[i]->tok) << ";";
// If we've got a numeric or string constant, instead of
// assigning the numeric or string constant to a temporary,
// then passing the temporary to _stp_printf/_stp_snprintf,
// let's just override the temporary with the constant.
if (e->args[i]->tok->type == tok_number
|| e->args[i]->tok->type == tok_string)
tmp[i].override(c_expression(e->args[i]));
else
c_assign (t.value(), e->args[i],
"print format actual argument evaluation");
}
std::vector<print_format::format_component> components;
if (e->print_with_format)
{
components = e->components;
}
else
{
// Synthesize a print-format string if the user didn't
// provide one; the synthetic string simply contains one
// directive for each argument.
for (unsigned i = 0; i < e->args.size(); ++i)
{
if (i > 0 && e->print_with_delim)
components.push_back (e->delimiter);
print_format::format_component curr;
curr.clear();
switch (e->args[i]->type)
{
case pe_unknown:
throw semantic_error("cannot print unknown expression type", e->args[i]->tok);
case pe_stats:
throw semantic_error("cannot print a raw stats object", e->args[i]->tok);
case pe_long:
curr.type = print_format::conv_signed_decimal;
break;
case pe_string:
curr.type = print_format::conv_string;
break;
}
components.push_back (curr);
}
if (e->print_with_newline)
{
print_format::format_component curr;
curr.clear();
curr.type = print_format::conv_literal;
curr.literal_string = "\\n";
components.push_back (curr);
}
}
// Allocate the result
exp_type ty = e->print_to_stream ? pe_long : pe_string;
tmpvar res = gensym (ty);
int use_print = 0;
string format_string = print_format::components_to_string(components);
if (tmp.size() == 0 || (tmp.size() == 1 && format_string == "%s"))
use_print = 1;
else if (tmp.size() == 1
&& e->args[0]->tok->type == tok_string
&& format_string == "%s\\n")
{
use_print = 1;
tmp[0].override(tmp[0].value() + "\"\\n\"");
components[0].type = print_format::conv_literal;
}
// Make the [s]printf call...
// Generate code to check that any pointer arguments are actually accessible. */
int arg_ix = 0;
for (unsigned i = 0; i < components.size(); ++i) {
if (components[i].type == print_format::conv_literal)
continue;
/* Take note of the width and precision arguments, if any. */
int width_ix = -1, prec_ix= -1;
if (components[i].widthtype == print_format::width_dynamic)
width_ix = arg_ix++;
if (components[i].prectype == print_format::prec_dynamic)
prec_ix = arg_ix++;
/* Generate a noop call to deref_buffer for %m. */
if (components[i].type == print_format::conv_memory) {
this->probe_or_function_needs_deref_fault_handler = true;
o->newline() << "deref_buffer (0, " << tmp[arg_ix].value() << ", ";
if (prec_ix == -1)
if (width_ix != -1)
prec_ix = width_ix;
if (prec_ix != -1)
o->line() << tmp[prec_ix].value();
else
o->line() << "1";
o->line() << ");";
}
++arg_ix;
}
if (e->print_to_stream)
{
if (e->print_char)
{
o->newline() << "_stp_print_char (";
if (tmp.size())
o->line() << tmp[0].value() << ");";
else
o->line() << '"' << format_string << "\");";
return;
}
if (use_print)
{
o->newline() << "_stp_print (";
if (tmp.size())
o->line() << tmp[0].value() << ");";
else
o->line() << '"' << format_string << "\");";
return;
}
// We'll just hardcode the result of 0 instead of using the
// temporary.
res.override("((int64_t)0LL)");
o->newline() << "_stp_printf (";
}
else
o->newline() << "_stp_snprintf (" << res.value() << ", MAXSTRINGLEN, ";
o->line() << '"' << format_string << '"';
/* Generate the actual arguments. Make sure that they match the expected type of the
format specifier. */
arg_ix = 0;
for (unsigned i = 0; i < components.size(); ++i) {
if (components[i].type == print_format::conv_literal)
continue;
/* Cast the width and precision arguments, if any, to 'int'. */
if (components[i].widthtype == print_format::width_dynamic)
o->line() << ", (int)" << tmp[arg_ix++].value();
if (components[i].prectype == print_format::prec_dynamic)
o->line() << ", (int)" << tmp[arg_ix++].value();
/* The type of the %m argument is 'char*'. */
if (components[i].type == print_format::conv_memory)
o->line() << ", (char*)(uintptr_t)" << tmp[arg_ix++].value();
else
o->line() << ", " << tmp[arg_ix++].value();
}
o->line() << ");";
o->newline() << res.value() << ";";
}
}
void
c_tmpcounter::visit_stat_op (stat_op* e)
{
symbol *sym = get_symbol_within_expression (e->stat);
var v = parent->getvar(sym->referent, e->tok);
aggvar agg = parent->gensym_aggregate ();
tmpvar res = parent->gensym (pe_long);
agg.declare(*(this->parent));
res.declare(*(this->parent));
if (sym->referent->arity != 0)
{
// One temporary per index dimension.
for (unsigned i=0; i<sym->referent->index_types.size(); i++)
{
// Sorry about this, but with no dynamic_cast<> and no
// constructor patterns, this is how things work.
arrayindex *arr = NULL;
if (!expression_is_arrayindex (e->stat, arr))
throw semantic_error("expected arrayindex expression in stat_op of array", e->tok);
tmpvar ix = parent->gensym (sym->referent->index_types[i]);
ix.declare (*parent);
arr->indexes[i]->visit(this);
}
}
}
void
c_unparser::visit_stat_op (stat_op* e)
{
// Stat ops can be *applied* to two types of expression:
//
// 1. An arrayindex expression on a pe_stats-valued array.
//
// 2. A symbol of type pe_stats.
// FIXME: classify the expression the stat_op is being applied to,
// call appropriate stp_get_stat() / stp_pmap_get_stat() helper,
// then reach into resultant struct stat_data.
// FIXME: also note that summarizing anything is expensive, and we
// really ought to pass a timeout handler into the summary routine,
// check its response, possibly exit if it ran out of cycles.
{
stmt_expr block(*this);
symbol *sym = get_symbol_within_expression (e->stat);
aggvar agg = gensym_aggregate ();
tmpvar res = gensym (pe_long);
var v = getvar(sym->referent, e->tok);
{
if (aggregations_active.count(v.value()))
load_aggregate(e->stat, agg, true);
else
load_aggregate(e->stat, agg, false);
// PR 2142+2610: empty aggregates
if (e->ctype == sc_count)
{
o->newline() << "if (unlikely (" << agg.value() << " == NULL))";
o->indent(1);
c_assign(res, "0", e->tok);
o->indent(-1);
}
else
{
o->newline() << "if (unlikely (" << agg.value() << " == NULL)"
<< " || " << agg.value() << "->count == 0) {";
o->newline(1) << "c->last_error = \"empty aggregate\";";
o->newline() << "c->last_stmt = " << lex_cast_qstring(*e->tok) << ";";
o->newline() << "goto out;";
o->newline(-1) << "}";
}
o->newline() << "else";
o->indent(1);
switch (e->ctype)
{
case sc_average:
c_assign(res, ("_stp_div64(NULL, " + agg.value() + "->sum, "
+ agg.value() + "->count)"),
e->tok);
break;
case sc_count:
c_assign(res, agg.value() + "->count", e->tok);
break;
case sc_sum:
c_assign(res, agg.value() + "->sum", e->tok);
break;
case sc_min:
c_assign(res, agg.value() + "->min", e->tok);
break;
case sc_max:
c_assign(res, agg.value() + "->max", e->tok);
break;
}
o->indent(-1);
}
o->newline() << res << ";";
}
}
void
c_unparser::visit_hist_op (hist_op*)
{
// Hist ops can only occur in a limited set of circumstances:
//
// 1. Inside an arrayindex expression, as the base referent. See
// c_unparser::visit_arrayindex for handling of this case.
//
// 2. Inside a foreach statement, as the base referent. See
// c_unparser::visit_foreach_loop for handling this case.
//
// 3. Inside a print_format expression, as the sole argument. See
// c_unparser::visit_print_format for handling this case.
//
// Note that none of these cases involves the c_unparser ever
// visiting this node. We should not get here.
assert(false);
}
struct unwindsym_dump_context
{
systemtap_session& session;
ostream& output;
unsigned stp_module_index;
set<string> undone_unwindsym_modules;
};
static int
dump_unwindsyms (Dwfl_Module *m,
void **userdata __attribute__ ((unused)),
const char *name,
Dwarf_Addr base,
void *arg)
{
unwindsym_dump_context* c = (unwindsym_dump_context*) arg;
assert (c);
unsigned stpmod_idx = c->stp_module_index;
string modname = name;
// skip modules/files we're not actually interested in
if (c->session.unwindsym_modules.find(modname) == c->session.unwindsym_modules.end())
return DWARF_CB_OK;
c->stp_module_index ++;
if (c->session.verbose > 1)
clog << "dump_unwindsyms " << name
<< " index=" << stpmod_idx
<< " base=0x" << hex << base << dec << endl;
// We want to extract several bits of information:
//
// - parts of the program-header that map the file's physical offsets to the text section
// - section table: just a list of section (relocation) base addresses
// - symbol table of the text-like sections, with all addresses relativized to each base
// - the contents of .debug_frame section, for unwinding purposes
//
// In the future, we'll also care about data symbols.
int syments = dwfl_module_getsymtab(m);
assert(syments);
// Look up the relocation basis for symbols
int n = dwfl_module_relocations (m);
dwfl_assert ("dwfl_module_relocations", n >= 0);
// XXX: unfortunate duplication with tapsets.cxx:emit_address()
typedef map<Dwarf_Addr,const char*> addrmap_t; // NB: plain map, sorted by address
vector<string> seclist; // encountered relocation bases (section names)
map<unsigned, addrmap_t> addrmap; // per-relocation-base sorted addrmap
Dwarf_Addr extra_offset = 0;
for (int i = 1 /* XXX: why not 0? */ ; i < syments; ++i)
{
GElf_Sym sym;
const char *name = dwfl_module_getsym(m, i, &sym, NULL);
if (name)
{
// NB: Yey, we found the kernel's _stext value.
// Sess.sym_stext may be unset (0) at this point, since
// there may have been no kernel probes set. We could
// use tapsets.cxx:lookup_symbol_address(), but then
// we're already iterating over the same data here...
if (modname == "kernel" && !strcmp(name, "_stext"))
{
extra_offset = sym.st_value;
if (c->session.verbose > 2)
clog << "Found kernel _stext 0x" << hex << extra_offset << dec << endl;
}
if (GELF_ST_TYPE (sym.st_info) == STT_FUNC &&
sym.st_shndx != SHN_UNDEF)
{
Dwarf_Addr sym_addr = sym.st_value;
const char *secname = NULL;
if (n > 0) // only try to relocate if there exist relocation bases
{
int ki = dwfl_module_relocate_address (m, &sym_addr);
dwfl_assert ("dwfl_module_relocate_address", ki >= 0);
secname = dwfl_module_relocation_info (m, ki, NULL);
}
if (n == 1 && modname == "kernel" && secname && secname[0] == '\0')
{
// This is a symbol within a relocatable kernel image.
secname = "_stext";
// NB: don't subtract session.sym_stext, which could be inconveniently NULL.
// Instead, sym_addr will get compensated later via extra_offset.
}
else if (n > 0)
{
assert (secname != NULL);
// secname adequately set
// NB: it may be an empty string for ET_DYN objects
// like shared libraries, as their relocation base
// is implicit.
if (secname[0] == '\0')
secname = ".dynamic";
}
else
{
assert (n == 0);
// sym_addr is absolute, as it must be since there are no relocation bases
secname = ".absolute"; // sentinel
}
// Compute our section number
unsigned secidx;
for (secidx=0; secidx<seclist.size(); secidx++)
if (seclist[secidx]==secname) break;
if (secidx == seclist.size()) // new section name
seclist.push_back (secname);
(addrmap[secidx])[sym_addr] = name;
}
}
}
for (unsigned secidx = 0; secidx < seclist.size(); secidx++)
{
c->output << "struct _stp_symbol "
<< "_stp_module_" << stpmod_idx<< "_symbols_" << secidx << "[] = {" << endl;
// We write out a *sorted* symbol table, so the runtime doesn't have to sort them later.
for (addrmap_t::iterator it = addrmap[secidx].begin(); it != addrmap[secidx].end(); it++)
{
if (it->first < extra_offset)
continue; // skip symbols that occur before our chosen base address
c->output << " { 0x" << hex << it->first-extra_offset << dec
<< ", " << lex_cast_qstring (it->second) << " }," << endl;
}
c->output << "};" << endl;
}
c->output << "struct _stp_section _stp_module_" << stpmod_idx<< "_sections[] = {" << endl;
for (unsigned secidx = 0; secidx < seclist.size(); secidx++)
{
c->output << "{" << endl
<< ".name = " << lex_cast_qstring(seclist[secidx]) << "," << endl
<< ".symbols = _stp_module_" << stpmod_idx << "_symbols_" << secidx << "," << endl
<< ".num_symbols = sizeof(_stp_module_" << stpmod_idx << "_symbols_" << secidx << ")/sizeof(struct _stp_symbol)" << endl
<< "}," << endl;
}
c->output << "};" << endl;
c->output << "struct _stp_module _stp_module_" << stpmod_idx << " = {" << endl;
c->output << ".name = " << lex_cast_qstring (modname) << ", " << endl;
c->output << ".sections = _stp_module_" << stpmod_idx << "_sections" << ", " << endl;
c->output << ".num_sections = sizeof(_stp_module_" << stpmod_idx << "_sections)/"
<< "sizeof(struct _stp_section), " << endl;
c->output << "};" << endl << endl;
c->undone_unwindsym_modules.erase (modname);
return DWARF_CB_OK;
}
// Emit symbol table & unwind data, plus any calls needed to register
// them with the runtime.
void
emit_symbol_data (systemtap_session& s)
{
string symfile = "stap-symbols.h";
s.op->newline() << "#include " << lex_cast_qstring (symfile);
ofstream kallsyms_out ((s.tmpdir + "/" + symfile).c_str());
unwindsym_dump_context ctx = { s, kallsyms_out, 0, s.unwindsym_modules };
// XXX: copied from tapsets.cxx dwflpp::, sadly
static char debuginfo_path_arr[] = "-:.debug:/usr/lib/debug:build";
static char *debuginfo_env_arr = getenv("SYSTEMTAP_DEBUGINFO_PATH");
static char *debuginfo_path = (debuginfo_env_arr ?
debuginfo_env_arr : debuginfo_path_arr);
static const char *debug_path = (debuginfo_env_arr ?
debuginfo_env_arr : s.kernel_release.c_str());
// ---- step 1: process any kernel modules listed
static const Dwfl_Callbacks kernel_callbacks =
{
dwfl_linux_kernel_find_elf,
dwfl_standard_find_debuginfo,
dwfl_offline_section_address,
& debuginfo_path
};
Dwfl *dwfl = dwfl_begin (&kernel_callbacks);
if (!dwfl)
throw semantic_error ("cannot open dwfl");
dwfl_report_begin (dwfl);
int rc = dwfl_linux_kernel_report_offline (dwfl, debug_path, NULL /* XXX: filtering callback */);
dwfl_report_end (dwfl, NULL, NULL);
if (rc == 0) // tolerate missing data; will warn user about it anyway
{
ptrdiff_t off = 0;
do
{
if (pending_interrupts) return;
off = dwfl_getmodules (dwfl, &dump_unwindsyms, (void *) &ctx, 0);
}
while (off > 0);
dwfl_assert("dwfl_getmodules", off == 0);
}
dwfl_end(dwfl);
// ---- step 2: process any user modules (files) listed
// XXX: see dwflpp::setup_user.
static const Dwfl_Callbacks user_callbacks =
{
NULL, /* dwfl_linux_kernel_find_elf, */
dwfl_standard_find_debuginfo,
dwfl_offline_section_address,
& debuginfo_path
};
for (std::set<std::string>::iterator it = s.unwindsym_modules.begin();
it != s.unwindsym_modules.end();
it++)
{
string modname = *it;
assert (modname.length() != 0);
if (modname[0] != '/') continue; // user-space files must be full paths
Dwfl *dwfl = dwfl_begin (&user_callbacks);
if (!dwfl)
throw semantic_error ("cannot create dwfl for " + modname);
dwfl_report_begin (dwfl);
Dwfl_Module* mod = dwfl_report_offline (dwfl, modname.c_str(), modname.c_str(), -1);
dwfl_report_end (dwfl, NULL, NULL);
if (mod != 0) // tolerate missing data; will warn below
{
ptrdiff_t off = 0;
do
{
if (pending_interrupts) return;
off = dwfl_getmodules (dwfl, &dump_unwindsyms, (void *) &ctx, 0);
}
while (off > 0);
dwfl_assert("dwfl_getmodules", off == 0);
}
dwfl_end(dwfl);
}
// Print out a definition of the runtime's _stp_modules[] globals.
kallsyms_out << endl;
kallsyms_out << "struct _stp_module *_stp_modules [] = {" << endl;
for (unsigned i=0; i<ctx.stp_module_index; i++)
{
kallsyms_out << "& _stp_module_" << i << "," << endl;
}
kallsyms_out << "};" << endl;
kallsyms_out << "unsigned _stp_num_modules = " << ctx.stp_module_index << ";" << endl;
// Some nonexistent modules may have been identified with "-d". Note them.
for (set<string>::iterator it = ctx.undone_unwindsym_modules.begin();
it != ctx.undone_unwindsym_modules.end();
it ++)
{
s.print_warning ("missing unwind/symbol data for module `" + (*it) + "'");
}
}
int
translate_pass (systemtap_session& s)
{
int rc = 0;
s.op = new translator_output (s.translated_source);
c_unparser cup (& s);
s.up = & cup;
try
{
// This is at the very top of the file.
s.op->newline() << "#ifndef MAXNESTING";
s.op->newline() << "#define MAXNESTING 10";
s.op->newline() << "#endif";
s.op->newline() << "#ifndef MAXSTRINGLEN";
s.op->newline() << "#define MAXSTRINGLEN 128";
s.op->newline() << "#endif";
s.op->newline() << "#ifndef MAXACTION";
s.op->newline() << "#define MAXACTION 1000";
s.op->newline() << "#endif";
s.op->newline() << "#ifndef MAXACTION_INTERRUPTIBLE";
s.op->newline() << "#define MAXACTION_INTERRUPTIBLE (MAXACTION * 10)";
s.op->newline() << "#endif";
s.op->newline() << "#ifndef MAXTRYLOCK";
s.op->newline() << "#define MAXTRYLOCK MAXACTION";
s.op->newline() << "#endif";
s.op->newline() << "#ifndef TRYLOCKDELAY";
s.op->newline() << "#define TRYLOCKDELAY 100";
s.op->newline() << "#endif";
s.op->newline() << "#ifndef MAXMAPENTRIES";
s.op->newline() << "#define MAXMAPENTRIES 2048";
s.op->newline() << "#endif";
s.op->newline() << "#ifndef MAXERRORS";
s.op->newline() << "#define MAXERRORS 0";
s.op->newline() << "#endif";
s.op->newline() << "#ifndef MAXSKIPPED";
s.op->newline() << "#define MAXSKIPPED 100";
s.op->newline() << "#endif";
s.op->newline() << "#ifndef MINSTACKSPACE";
s.op->newline() << "#define MINSTACKSPACE 1024";
s.op->newline() << "#endif";
// Overload processing
s.op->newline() << "#ifndef STP_OVERLOAD_INTERVAL";
s.op->newline() << "#define STP_OVERLOAD_INTERVAL 1000000000LL";
s.op->newline() << "#endif";
s.op->newline() << "#ifndef STP_OVERLOAD_THRESHOLD";
s.op->newline() << "#define STP_OVERLOAD_THRESHOLD 500000000LL";
s.op->newline() << "#endif";
// We allow the user to completely turn overload processing off
// (as opposed to tuning it by overriding the values above) by
// running: stap -DSTP_NO_OVERLOAD {other options}
s.op->newline() << "#ifndef STP_NO_OVERLOAD";
s.op->newline() << "#define STP_OVERLOAD";
s.op->newline() << "#endif";
if (s.bulk_mode)
s.op->newline() << "#define STP_BULKMODE";
if (s.timing)
s.op->newline() << "#define STP_TIMING";
if (s.perfmon)
s.op->newline() << "#define STP_PERFMON";
s.op->newline() << "#include \"runtime.h\"";
s.op->newline() << "#include \"regs.c\"";
s.op->newline() << "#include \"stack.c\"";
s.op->newline() << "#include \"regs-ia64.c\"";
s.op->newline() << "#include \"stat.c\"";
s.op->newline() << "#include <linux/string.h>";
s.op->newline() << "#include <linux/timer.h>";
s.op->newline() << "#include <linux/delay.h>";
s.op->newline() << "#include <linux/profile.h>";
s.op->newline() << "#include <linux/random.h>";
// s.op->newline() << "#include <linux/utsrelease.h>"; // newer kernels only
s.op->newline() << "#include <linux/vermagic.h>";
s.op->newline() << "#include <linux/utsname.h>";
s.op->newline() << "#include <linux/version.h>";
// s.op->newline() << "#include <linux/compile.h>";
s.op->newline() << "#include \"loc2c-runtime.h\" ";
// XXX: old 2.6 kernel hack
s.op->newline() << "#ifndef read_trylock";
s.op->newline() << "#define read_trylock(x) ({ read_lock(x); 1; })";
s.op->newline() << "#endif";
s.up->emit_common_header (); // context etc.
for (unsigned i=0; i<s.embeds.size(); i++)
{
s.op->newline() << s.embeds[i]->code << "\n";
}
s.op->newline() << "static struct {";
s.op->indent(1);
for (unsigned i=0; i<s.globals.size(); i++)
{
s.up->emit_global (s.globals[i]);
}
s.op->newline(-1) << "} global = {";
s.op->newline(1);
for (unsigned i=0; i<s.globals.size(); i++)
{
if (pending_interrupts) return 1;
s.up->emit_global_init (s.globals[i]);
}
s.op->newline(-1) << "};";
s.op->assert_0_indent();
for (unsigned i=0; i<s.functions.size(); i++)
{
if (pending_interrupts) return 1;
s.op->newline();
s.up->emit_functionsig (s.functions[i]);
}
s.op->assert_0_indent();
for (unsigned i=0; i<s.functions.size(); i++)
{
if (pending_interrupts) return 1;
s.op->newline();
s.up->emit_function (s.functions[i]);
}
s.op->assert_0_indent();
// Run a varuse_collecting_visitor over probes that need global
// variable locks. We'll use this information later in
// emit_locks()/emit_unlocks().
for (unsigned i=0; i<s.probes.size(); i++)
{
if (pending_interrupts) return 1;
if (s.probes[i]->needs_global_locks())
s.probes[i]->body->visit (&cup.vcv_needs_global_locks);
}
s.op->assert_0_indent();
for (unsigned i=0; i<s.probes.size(); i++)
{
if (pending_interrupts) return 1;
s.up->emit_probe (s.probes[i]);
}
s.op->assert_0_indent();
s.op->newline();
s.up->emit_module_init ();
s.op->assert_0_indent();
s.op->newline();
s.up->emit_module_exit ();
s.op->assert_0_indent();
s.op->newline();
// XXX impedance mismatch
s.op->newline() << "int probe_start () {";
s.op->newline(1) << "return systemtap_module_init () ? -1 : 0;";
s.op->newline(-1) << "}";
s.op->newline();
s.op->newline() << "void probe_exit () {";
s.op->newline(1) << "systemtap_module_exit ();";
s.op->newline(-1) << "}";
s.op->assert_0_indent();
for (unsigned i=0; i<s.globals.size(); i++)
{
s.op->newline();
s.up->emit_global_param (s.globals[i]);
}
s.op->assert_0_indent();
emit_symbol_data (s);
s.op->newline() << "MODULE_DESCRIPTION(\"systemtap-generated probe\");";
s.op->newline() << "MODULE_LICENSE(\"GPL\");";
s.op->assert_0_indent();
}
catch (const semantic_error& e)
{
s.print_error (e);
}
s.op->line() << "\n";
delete s.op;
s.op = 0;
s.up = 0;
return rc + s.num_errors();
}
|