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
|
//===- LLVMCConfigurationEmitter.cpp - Generate LLVMC config ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open
// Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting LLVMC configuration code.
//
//===----------------------------------------------------------------------===//
#include "LLVMCConfigurationEmitter.h"
#include "Record.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSet.h"
#include <algorithm>
#include <cassert>
#include <functional>
#include <stdexcept>
#include <string>
#include <typeinfo>
using namespace llvm;
//===----------------------------------------------------------------------===//
/// Typedefs
typedef std::vector<Record*> RecordVector;
typedef std::vector<std::string> StrVector;
//===----------------------------------------------------------------------===//
/// Constants
// Indentation.
static const unsigned TabWidth = 4;
static const unsigned Indent1 = TabWidth*1;
static const unsigned Indent2 = TabWidth*2;
static const unsigned Indent3 = TabWidth*3;
// Default help string.
static const char * const DefaultHelpString = "NO HELP MESSAGE PROVIDED";
// Name for the "sink" option.
static const char * const SinkOptionName = "AutoGeneratedSinkOption";
namespace {
//===----------------------------------------------------------------------===//
/// Helper functions
/// Id - An 'identity' function object.
struct Id {
template<typename T0>
void operator()(const T0&) const {
}
template<typename T0, typename T1>
void operator()(const T0&, const T1&) const {
}
template<typename T0, typename T1, typename T2>
void operator()(const T0&, const T1&, const T2&) const {
}
};
int InitPtrToInt(const Init* ptr) {
const IntInit& val = dynamic_cast<const IntInit&>(*ptr);
return val.getValue();
}
const std::string& InitPtrToString(const Init* ptr) {
const StringInit& val = dynamic_cast<const StringInit&>(*ptr);
return val.getValue();
}
const ListInit& InitPtrToList(const Init* ptr) {
const ListInit& val = dynamic_cast<const ListInit&>(*ptr);
return val;
}
const DagInit& InitPtrToDag(const Init* ptr) {
const DagInit& val = dynamic_cast<const DagInit&>(*ptr);
return val;
}
const std::string GetOperatorName(const DagInit* D) {
return D->getOperator()->getAsString();
}
const std::string GetOperatorName(const DagInit& D) {
return GetOperatorName(&D);
}
// checkNumberOfArguments - Ensure that the number of args in d is
// greater than or equal to min_arguments, otherwise throw an exception.
void checkNumberOfArguments (const DagInit* d, unsigned min_arguments) {
if (!d || d->getNumArgs() < min_arguments)
throw GetOperatorName(d) + ": too few arguments!";
}
// isDagEmpty - is this DAG marked with an empty marker?
bool isDagEmpty (const DagInit* d) {
return GetOperatorName(d) == "empty_dag_marker";
}
// EscapeVariableName - Escape commas and other symbols not allowed
// in the C++ variable names. Makes it possible to use options named
// like "Wa," (useful for prefix options).
std::string EscapeVariableName(const std::string& Var) {
std::string ret;
for (unsigned i = 0; i != Var.size(); ++i) {
char cur_char = Var[i];
if (cur_char == ',') {
ret += "_comma_";
}
else if (cur_char == '+') {
ret += "_plus_";
}
else if (cur_char == '-') {
ret += "_dash_";
}
else {
ret.push_back(cur_char);
}
}
return ret;
}
/// oneOf - Does the input string contain this character?
bool oneOf(const char* lst, char c) {
while (*lst) {
if (*lst++ == c)
return true;
}
return false;
}
template <class I, class S>
void checkedIncrement(I& P, I E, S ErrorString) {
++P;
if (P == E)
throw ErrorString;
}
// apply is needed because C++'s syntax doesn't let us construct a function
// object and call it in the same statement.
template<typename F, typename T0>
void apply(F Fun, T0& Arg0) {
return Fun(Arg0);
}
template<typename F, typename T0, typename T1>
void apply(F Fun, T0& Arg0, T1& Arg1) {
return Fun(Arg0, Arg1);
}
//===----------------------------------------------------------------------===//
/// Back-end specific code
/// OptionType - One of six different option types. See the
/// documentation for detailed description of differences.
namespace OptionType {
enum OptionType { Alias, Switch, Parameter, ParameterList,
Prefix, PrefixList};
bool IsAlias(OptionType t) {
return (t == Alias);
}
bool IsList (OptionType t) {
return (t == ParameterList || t == PrefixList);
}
bool IsSwitch (OptionType t) {
return (t == Switch);
}
bool IsParameter (OptionType t) {
return (t == Parameter || t == Prefix);
}
}
OptionType::OptionType stringToOptionType(const std::string& T) {
if (T == "alias_option")
return OptionType::Alias;
else if (T == "switch_option")
return OptionType::Switch;
else if (T == "parameter_option")
return OptionType::Parameter;
else if (T == "parameter_list_option")
return OptionType::ParameterList;
else if (T == "prefix_option")
return OptionType::Prefix;
else if (T == "prefix_list_option")
return OptionType::PrefixList;
else
throw "Unknown option type: " + T + '!';
}
namespace OptionDescriptionFlags {
enum OptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
ReallyHidden = 0x4, Extern = 0x8,
OneOrMore = 0x10, ZeroOrOne = 0x20 };
}
/// OptionDescription - Represents data contained in a single
/// OptionList entry.
struct OptionDescription {
OptionType::OptionType Type;
std::string Name;
unsigned Flags;
std::string Help;
unsigned MultiVal;
Init* InitVal;
OptionDescription(OptionType::OptionType t = OptionType::Switch,
const std::string& n = "",
const std::string& h = DefaultHelpString)
: Type(t), Name(n), Flags(0x0), Help(h), MultiVal(1), InitVal(0)
{}
/// GenTypeDeclaration - Returns the C++ variable type of this
/// option.
const char* GenTypeDeclaration() const;
/// GenVariableName - Returns the variable name used in the
/// generated C++ code.
std::string GenVariableName() const;
/// Merge - Merge two option descriptions.
void Merge (const OptionDescription& other);
// Misc convenient getters/setters.
bool isAlias() const;
bool isMultiVal() const;
bool isExtern() const;
void setExtern();
bool isRequired() const;
void setRequired();
bool isOneOrMore() const;
void setOneOrMore();
bool isZeroOrOne() const;
void setZeroOrOne();
bool isHidden() const;
void setHidden();
bool isReallyHidden() const;
void setReallyHidden();
bool isSwitch() const
{ return OptionType::IsSwitch(this->Type); }
bool isParameter() const
{ return OptionType::IsParameter(this->Type); }
bool isList() const
{ return OptionType::IsList(this->Type); }
};
void OptionDescription::Merge (const OptionDescription& other)
{
if (other.Type != Type)
throw "Conflicting definitions for the option " + Name + "!";
if (Help == other.Help || Help == DefaultHelpString)
Help = other.Help;
else if (other.Help != DefaultHelpString) {
llvm::errs() << "Warning: several different help strings"
" defined for option " + Name + "\n";
}
Flags |= other.Flags;
}
bool OptionDescription::isAlias() const {
return OptionType::IsAlias(this->Type);
}
bool OptionDescription::isMultiVal() const {
return MultiVal > 1;
}
bool OptionDescription::isExtern() const {
return Flags & OptionDescriptionFlags::Extern;
}
void OptionDescription::setExtern() {
Flags |= OptionDescriptionFlags::Extern;
}
bool OptionDescription::isRequired() const {
return Flags & OptionDescriptionFlags::Required;
}
void OptionDescription::setRequired() {
Flags |= OptionDescriptionFlags::Required;
}
bool OptionDescription::isOneOrMore() const {
return Flags & OptionDescriptionFlags::OneOrMore;
}
void OptionDescription::setOneOrMore() {
Flags |= OptionDescriptionFlags::OneOrMore;
}
bool OptionDescription::isZeroOrOne() const {
return Flags & OptionDescriptionFlags::ZeroOrOne;
}
void OptionDescription::setZeroOrOne() {
Flags |= OptionDescriptionFlags::ZeroOrOne;
}
bool OptionDescription::isHidden() const {
return Flags & OptionDescriptionFlags::Hidden;
}
void OptionDescription::setHidden() {
Flags |= OptionDescriptionFlags::Hidden;
}
bool OptionDescription::isReallyHidden() const {
return Flags & OptionDescriptionFlags::ReallyHidden;
}
void OptionDescription::setReallyHidden() {
Flags |= OptionDescriptionFlags::ReallyHidden;
}
const char* OptionDescription::GenTypeDeclaration() const {
switch (Type) {
case OptionType::Alias:
return "cl::alias";
case OptionType::PrefixList:
case OptionType::ParameterList:
return "cl::list<std::string>";
case OptionType::Switch:
return "cl::opt<bool>";
case OptionType::Parameter:
case OptionType::Prefix:
default:
return "cl::opt<std::string>";
}
}
std::string OptionDescription::GenVariableName() const {
const std::string& EscapedName = EscapeVariableName(Name);
switch (Type) {
case OptionType::Alias:
return "AutoGeneratedAlias_" + EscapedName;
case OptionType::PrefixList:
case OptionType::ParameterList:
return "AutoGeneratedList_" + EscapedName;
case OptionType::Switch:
return "AutoGeneratedSwitch_" + EscapedName;
case OptionType::Prefix:
case OptionType::Parameter:
default:
return "AutoGeneratedParameter_" + EscapedName;
}
}
/// OptionDescriptions - An OptionDescription array plus some helper
/// functions.
class OptionDescriptions {
typedef StringMap<OptionDescription> container_type;
/// Descriptions - A list of OptionDescriptions.
container_type Descriptions;
public:
/// FindOption - exception-throwing wrapper for find().
const OptionDescription& FindOption(const std::string& OptName) const;
// Wrappers for FindOption that throw an exception in case the option has a
// wrong type.
const OptionDescription& FindSwitch(const std::string& OptName) const;
const OptionDescription& FindParameter(const std::string& OptName) const;
const OptionDescription& FindList(const std::string& OptName) const;
const OptionDescription&
FindListOrParameter(const std::string& OptName) const;
/// insertDescription - Insert new OptionDescription into
/// OptionDescriptions list
void InsertDescription (const OptionDescription& o);
// Support for STL-style iteration
typedef container_type::const_iterator const_iterator;
const_iterator begin() const { return Descriptions.begin(); }
const_iterator end() const { return Descriptions.end(); }
};
const OptionDescription&
OptionDescriptions::FindOption(const std::string& OptName) const {
const_iterator I = Descriptions.find(OptName);
if (I != Descriptions.end())
return I->second;
else
throw OptName + ": no such option!";
}
const OptionDescription&
OptionDescriptions::FindSwitch(const std::string& OptName) const {
const OptionDescription& OptDesc = this->FindOption(OptName);
if (!OptDesc.isSwitch())
throw OptName + ": incorrect option type - should be a switch!";
return OptDesc;
}
const OptionDescription&
OptionDescriptions::FindList(const std::string& OptName) const {
const OptionDescription& OptDesc = this->FindOption(OptName);
if (!OptDesc.isList())
throw OptName + ": incorrect option type - should be a list!";
return OptDesc;
}
const OptionDescription&
OptionDescriptions::FindParameter(const std::string& OptName) const {
const OptionDescription& OptDesc = this->FindOption(OptName);
if (!OptDesc.isParameter())
throw OptName + ": incorrect option type - should be a parameter!";
return OptDesc;
}
const OptionDescription&
OptionDescriptions::FindListOrParameter(const std::string& OptName) const {
const OptionDescription& OptDesc = this->FindOption(OptName);
if (!OptDesc.isList() && !OptDesc.isParameter())
throw OptName
+ ": incorrect option type - should be a list or parameter!";
return OptDesc;
}
void OptionDescriptions::InsertDescription (const OptionDescription& o) {
container_type::iterator I = Descriptions.find(o.Name);
if (I != Descriptions.end()) {
OptionDescription& D = I->second;
D.Merge(o);
}
else {
Descriptions[o.Name] = o;
}
}
/// HandlerTable - A base class for function objects implemented as
/// 'tables of handlers'.
template <class T>
class HandlerTable {
protected:
// Implementation details.
/// Handler -
typedef void (T::* Handler) (const DagInit*);
/// HandlerMap - A map from property names to property handlers
typedef StringMap<Handler> HandlerMap;
static HandlerMap Handlers_;
static bool staticMembersInitialized_;
T* childPtr;
public:
HandlerTable(T* cp) : childPtr(cp)
{}
/// operator() - Just forwards to the corresponding property
/// handler.
void operator() (Init* i) {
const DagInit& property = InitPtrToDag(i);
const std::string& property_name = GetOperatorName(property);
typename HandlerMap::iterator method = Handlers_.find(property_name);
if (method != Handlers_.end()) {
Handler h = method->second;
(childPtr->*h)(&property);
}
else {
throw "No handler found for property " + property_name + "!";
}
}
void AddHandler(const char* Property, Handler Handl) {
Handlers_[Property] = Handl;
}
};
template <class T> typename HandlerTable<T>::HandlerMap
HandlerTable<T>::Handlers_;
template <class T> bool HandlerTable<T>::staticMembersInitialized_ = false;
/// CollectOptionProperties - Function object for iterating over an
/// option property list.
class CollectOptionProperties : public HandlerTable<CollectOptionProperties> {
private:
/// optDescs_ - OptionDescriptions table. This is where the
/// information is stored.
OptionDescription& optDesc_;
public:
explicit CollectOptionProperties(OptionDescription& OD)
: HandlerTable<CollectOptionProperties>(this), optDesc_(OD)
{
if (!staticMembersInitialized_) {
AddHandler("extern", &CollectOptionProperties::onExtern);
AddHandler("help", &CollectOptionProperties::onHelp);
AddHandler("hidden", &CollectOptionProperties::onHidden);
AddHandler("init", &CollectOptionProperties::onInit);
AddHandler("multi_val", &CollectOptionProperties::onMultiVal);
AddHandler("one_or_more", &CollectOptionProperties::onOneOrMore);
AddHandler("really_hidden", &CollectOptionProperties::onReallyHidden);
AddHandler("required", &CollectOptionProperties::onRequired);
AddHandler("zero_or_one", &CollectOptionProperties::onZeroOrOne);
staticMembersInitialized_ = true;
}
}
private:
/// Option property handlers --
/// Methods that handle option properties such as (help) or (hidden).
void onExtern (const DagInit* d) {
checkNumberOfArguments(d, 0);
optDesc_.setExtern();
}
void onHelp (const DagInit* d) {
checkNumberOfArguments(d, 1);
optDesc_.Help = InitPtrToString(d->getArg(0));
}
void onHidden (const DagInit* d) {
checkNumberOfArguments(d, 0);
optDesc_.setHidden();
}
void onReallyHidden (const DagInit* d) {
checkNumberOfArguments(d, 0);
optDesc_.setReallyHidden();
}
void onRequired (const DagInit* d) {
checkNumberOfArguments(d, 0);
if (optDesc_.isOneOrMore())
throw std::string("An option can't have both (required) "
"and (one_or_more) properties!");
optDesc_.setRequired();
}
void onInit (const DagInit* d) {
checkNumberOfArguments(d, 1);
Init* i = d->getArg(0);
const std::string& str = i->getAsString();
bool correct = optDesc_.isParameter() && dynamic_cast<StringInit*>(i);
correct |= (optDesc_.isSwitch() && (str == "true" || str == "false"));
if (!correct)
throw std::string("Incorrect usage of the 'init' option property!");
optDesc_.InitVal = i;
}
void onOneOrMore (const DagInit* d) {
checkNumberOfArguments(d, 0);
if (optDesc_.isRequired() || optDesc_.isZeroOrOne())
throw std::string("Only one of (required), (zero_or_one) or "
"(one_or_more) properties is allowed!");
if (!OptionType::IsList(optDesc_.Type))
llvm::errs() << "Warning: specifying the 'one_or_more' property "
"on a non-list option will have no effect.\n";
optDesc_.setOneOrMore();
}
void onZeroOrOne (const DagInit* d) {
checkNumberOfArguments(d, 0);
if (optDesc_.isRequired() || optDesc_.isOneOrMore())
throw std::string("Only one of (required), (zero_or_one) or "
"(one_or_more) properties is allowed!");
if (!OptionType::IsList(optDesc_.Type))
llvm::errs() << "Warning: specifying the 'zero_or_one' property"
"on a non-list option will have no effect.\n";
optDesc_.setZeroOrOne();
}
void onMultiVal (const DagInit* d) {
checkNumberOfArguments(d, 1);
int val = InitPtrToInt(d->getArg(0));
if (val < 2)
throw std::string("Error in the 'multi_val' property: "
"the value must be greater than 1!");
if (!OptionType::IsList(optDesc_.Type))
throw std::string("The multi_val property is valid only "
"on list options!");
optDesc_.MultiVal = val;
}
};
/// AddOption - A function object that is applied to every option
/// description. Used by CollectOptionDescriptions.
class AddOption {
private:
OptionDescriptions& OptDescs_;
public:
explicit AddOption(OptionDescriptions& OD) : OptDescs_(OD)
{}
void operator()(const Init* i) {
const DagInit& d = InitPtrToDag(i);
checkNumberOfArguments(&d, 1);
const OptionType::OptionType Type =
stringToOptionType(GetOperatorName(d));
const std::string& Name = InitPtrToString(d.getArg(0));
OptionDescription OD(Type, Name);
if (!OD.isExtern())
checkNumberOfArguments(&d, 2);
if (OD.isAlias()) {
// Aliases store the aliased option name in the 'Help' field.
OD.Help = InitPtrToString(d.getArg(1));
}
else if (!OD.isExtern()) {
processOptionProperties(&d, OD);
}
OptDescs_.InsertDescription(OD);
}
private:
/// processOptionProperties - Go through the list of option
/// properties and call a corresponding handler for each.
static void processOptionProperties (const DagInit* d, OptionDescription& o) {
checkNumberOfArguments(d, 2);
DagInit::const_arg_iterator B = d->arg_begin();
// Skip the first argument: it's always the option name.
++B;
std::for_each(B, d->arg_end(), CollectOptionProperties(o));
}
};
/// CollectOptionDescriptions - Collects option properties from all
/// OptionLists.
void CollectOptionDescriptions (RecordVector::const_iterator B,
RecordVector::const_iterator E,
OptionDescriptions& OptDescs)
{
// For every OptionList:
for (; B!=E; ++B) {
RecordVector::value_type T = *B;
// Throws an exception if the value does not exist.
ListInit* PropList = T->getValueAsListInit("options");
// For every option description in this list:
// collect the information and
std::for_each(PropList->begin(), PropList->end(), AddOption(OptDescs));
}
}
// Tool information record
namespace ToolFlags {
enum ToolFlags { Join = 0x1, Sink = 0x2 };
}
struct ToolDescription : public RefCountedBase<ToolDescription> {
std::string Name;
Init* CmdLine;
Init* Actions;
StrVector InLanguage;
std::string OutLanguage;
std::string OutputSuffix;
unsigned Flags;
// Various boolean properties
void setSink() { Flags |= ToolFlags::Sink; }
bool isSink() const { return Flags & ToolFlags::Sink; }
void setJoin() { Flags |= ToolFlags::Join; }
bool isJoin() const { return Flags & ToolFlags::Join; }
// Default ctor here is needed because StringMap can only store
// DefaultConstructible objects
ToolDescription() : CmdLine(0), Actions(0), Flags(0) {}
ToolDescription (const std::string& n)
: Name(n), CmdLine(0), Actions(0), Flags(0)
{}
};
/// ToolDescriptions - A list of Tool information records.
typedef std::vector<IntrusiveRefCntPtr<ToolDescription> > ToolDescriptions;
/// CollectToolProperties - Function object for iterating over a list of
/// tool property records.
class CollectToolProperties : public HandlerTable<CollectToolProperties> {
private:
/// toolDesc_ - Properties of the current Tool. This is where the
/// information is stored.
ToolDescription& toolDesc_;
public:
explicit CollectToolProperties (ToolDescription& d)
: HandlerTable<CollectToolProperties>(this) , toolDesc_(d)
{
if (!staticMembersInitialized_) {
AddHandler("actions", &CollectToolProperties::onActions);
AddHandler("cmd_line", &CollectToolProperties::onCmdLine);
AddHandler("in_language", &CollectToolProperties::onInLanguage);
AddHandler("join", &CollectToolProperties::onJoin);
AddHandler("out_language", &CollectToolProperties::onOutLanguage);
AddHandler("output_suffix", &CollectToolProperties::onOutputSuffix);
AddHandler("sink", &CollectToolProperties::onSink);
staticMembersInitialized_ = true;
}
}
private:
/// Property handlers --
/// Functions that extract information about tool properties from
/// DAG representation.
void onActions (const DagInit* d) {
checkNumberOfArguments(d, 1);
Init* Case = d->getArg(0);
if (typeid(*Case) != typeid(DagInit) ||
GetOperatorName(static_cast<DagInit*>(Case)) != "case")
throw
std::string("The argument to (actions) should be a 'case' construct!");
toolDesc_.Actions = Case;
}
void onCmdLine (const DagInit* d) {
checkNumberOfArguments(d, 1);
toolDesc_.CmdLine = d->getArg(0);
}
void onInLanguage (const DagInit* d) {
checkNumberOfArguments(d, 1);
Init* arg = d->getArg(0);
// Find out the argument's type.
if (typeid(*arg) == typeid(StringInit)) {
// It's a string.
toolDesc_.InLanguage.push_back(InitPtrToString(arg));
}
else {
// It's a list.
const ListInit& lst = InitPtrToList(arg);
StrVector& out = toolDesc_.InLanguage;
// Copy strings to the output vector.
for (ListInit::const_iterator B = lst.begin(), E = lst.end();
B != E; ++B) {
out.push_back(InitPtrToString(*B));
}
// Remove duplicates.
std::sort(out.begin(), out.end());
StrVector::iterator newE = std::unique(out.begin(), out.end());
out.erase(newE, out.end());
}
}
void onJoin (const DagInit* d) {
checkNumberOfArguments(d, 0);
toolDesc_.setJoin();
}
void onOutLanguage (const DagInit* d) {
checkNumberOfArguments(d, 1);
toolDesc_.OutLanguage = InitPtrToString(d->getArg(0));
}
void onOutputSuffix (const DagInit* d) {
checkNumberOfArguments(d, 1);
toolDesc_.OutputSuffix = InitPtrToString(d->getArg(0));
}
void onSink (const DagInit* d) {
checkNumberOfArguments(d, 0);
toolDesc_.setSink();
}
};
/// CollectToolDescriptions - Gather information about tool properties
/// from the parsed TableGen data (basically a wrapper for the
/// CollectToolProperties function object).
void CollectToolDescriptions (RecordVector::const_iterator B,
RecordVector::const_iterator E,
ToolDescriptions& ToolDescs)
{
// Iterate over a properties list of every Tool definition
for (;B!=E;++B) {
const Record* T = *B;
// Throws an exception if the value does not exist.
ListInit* PropList = T->getValueAsListInit("properties");
IntrusiveRefCntPtr<ToolDescription>
ToolDesc(new ToolDescription(T->getName()));
std::for_each(PropList->begin(), PropList->end(),
CollectToolProperties(*ToolDesc));
ToolDescs.push_back(ToolDesc);
}
}
/// FillInEdgeVector - Merge all compilation graph definitions into
/// one single edge list.
void FillInEdgeVector(RecordVector::const_iterator B,
RecordVector::const_iterator E, RecordVector& Out) {
for (; B != E; ++B) {
const ListInit* edges = (*B)->getValueAsListInit("edges");
for (unsigned i = 0; i < edges->size(); ++i)
Out.push_back(edges->getElementAsRecord(i));
}
}
/// CalculatePriority - Calculate the priority of this plugin.
int CalculatePriority(RecordVector::const_iterator B,
RecordVector::const_iterator E) {
int priority = 0;
if (B != E) {
priority = static_cast<int>((*B)->getValueAsInt("priority"));
if (++B != E)
throw std::string("More than one 'PluginPriority' instance found: "
"most probably an error!");
}
return priority;
}
/// NotInGraph - Helper function object for FilterNotInGraph.
struct NotInGraph {
private:
const llvm::StringSet<>& ToolsInGraph_;
public:
NotInGraph(const llvm::StringSet<>& ToolsInGraph)
: ToolsInGraph_(ToolsInGraph)
{}
bool operator()(const IntrusiveRefCntPtr<ToolDescription>& x) {
return (ToolsInGraph_.count(x->Name) == 0);
}
};
/// FilterNotInGraph - Filter out from ToolDescs all Tools not
/// mentioned in the compilation graph definition.
void FilterNotInGraph (const RecordVector& EdgeVector,
ToolDescriptions& ToolDescs) {
// List all tools mentioned in the graph.
llvm::StringSet<> ToolsInGraph;
for (RecordVector::const_iterator B = EdgeVector.begin(),
E = EdgeVector.end(); B != E; ++B) {
const Record* Edge = *B;
const std::string& NodeA = Edge->getValueAsString("a");
const std::string& NodeB = Edge->getValueAsString("b");
if (NodeA != "root")
ToolsInGraph.insert(NodeA);
ToolsInGraph.insert(NodeB);
}
// Filter ToolPropertiesList.
ToolDescriptions::iterator new_end =
std::remove_if(ToolDescs.begin(), ToolDescs.end(),
NotInGraph(ToolsInGraph));
ToolDescs.erase(new_end, ToolDescs.end());
}
/// FillInToolToLang - Fills in two tables that map tool names to
/// (input, output) languages. Helper function used by TypecheckGraph().
void FillInToolToLang (const ToolDescriptions& ToolDescs,
StringMap<StringSet<> >& ToolToInLang,
StringMap<std::string>& ToolToOutLang) {
for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
E = ToolDescs.end(); B != E; ++B) {
const ToolDescription& D = *(*B);
for (StrVector::const_iterator B = D.InLanguage.begin(),
E = D.InLanguage.end(); B != E; ++B)
ToolToInLang[D.Name].insert(*B);
ToolToOutLang[D.Name] = D.OutLanguage;
}
}
/// TypecheckGraph - Check that names for output and input languages
/// on all edges do match. This doesn't do much when the information
/// about the whole graph is not available (i.e. when compiling most
/// plugins).
void TypecheckGraph (const RecordVector& EdgeVector,
const ToolDescriptions& ToolDescs) {
StringMap<StringSet<> > ToolToInLang;
StringMap<std::string> ToolToOutLang;
FillInToolToLang(ToolDescs, ToolToInLang, ToolToOutLang);
StringMap<std::string>::iterator IAE = ToolToOutLang.end();
StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
for (RecordVector::const_iterator B = EdgeVector.begin(),
E = EdgeVector.end(); B != E; ++B) {
const Record* Edge = *B;
const std::string& NodeA = Edge->getValueAsString("a");
const std::string& NodeB = Edge->getValueAsString("b");
StringMap<std::string>::iterator IA = ToolToOutLang.find(NodeA);
StringMap<StringSet<> >::iterator IB = ToolToInLang.find(NodeB);
if (NodeA != "root") {
if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
throw "Edge " + NodeA + "->" + NodeB
+ ": output->input language mismatch";
}
if (NodeB == "root")
throw std::string("Edges back to the root are not allowed!");
}
}
/// WalkCase - Walks the 'case' expression DAG and invokes
/// TestCallback on every test, and StatementCallback on every
/// statement. Handles 'case' nesting, but not the 'and' and 'or'
/// combinators (that is, they are passed directly to TestCallback).
/// TestCallback must have type 'void TestCallback(const DagInit*, unsigned
/// IndentLevel, bool FirstTest)'.
/// StatementCallback must have type 'void StatementCallback(const Init*,
/// unsigned IndentLevel)'.
template <typename F1, typename F2>
void WalkCase(const Init* Case, F1 TestCallback, F2 StatementCallback,
unsigned IndentLevel = 0)
{
const DagInit& d = InitPtrToDag(Case);
// Error checks.
if (GetOperatorName(d) != "case")
throw std::string("WalkCase should be invoked only on 'case' expressions!");
if (d.getNumArgs() < 2)
throw "There should be at least one clause in the 'case' expression:\n"
+ d.getAsString();
// Main loop.
bool even = false;
const unsigned numArgs = d.getNumArgs();
unsigned i = 1;
for (DagInit::const_arg_iterator B = d.arg_begin(), E = d.arg_end();
B != E; ++B) {
Init* arg = *B;
if (!even)
{
// Handle test.
const DagInit& Test = InitPtrToDag(arg);
if (GetOperatorName(Test) == "default" && (i+1 != numArgs))
throw std::string("The 'default' clause should be the last in the"
"'case' construct!");
if (i == numArgs)
throw "Case construct handler: no corresponding action "
"found for the test " + Test.getAsString() + '!';
TestCallback(&Test, IndentLevel, (i == 1));
}
else
{
if (dynamic_cast<DagInit*>(arg)
&& GetOperatorName(static_cast<DagInit*>(arg)) == "case") {
// Nested 'case'.
WalkCase(arg, TestCallback, StatementCallback, IndentLevel + Indent1);
}
// Handle statement.
StatementCallback(arg, IndentLevel);
}
++i;
even = !even;
}
}
/// ExtractOptionNames - A helper function object used by
/// CheckForSuperfluousOptions() to walk the 'case' DAG.
class ExtractOptionNames {
llvm::StringSet<>& OptionNames_;
void processDag(const Init* Statement) {
const DagInit& Stmt = InitPtrToDag(Statement);
const std::string& ActionName = GetOperatorName(Stmt);
if (ActionName == "forward" || ActionName == "forward_as" ||
ActionName == "unpack_values" || ActionName == "switch_on" ||
ActionName == "parameter_equals" || ActionName == "element_in_list" ||
ActionName == "not_empty" || ActionName == "empty") {
checkNumberOfArguments(&Stmt, 1);
const std::string& Name = InitPtrToString(Stmt.getArg(0));
OptionNames_.insert(Name);
}
else if (ActionName == "and" || ActionName == "or") {
for (unsigned i = 0, NumArgs = Stmt.getNumArgs(); i < NumArgs; ++i) {
this->processDag(Stmt.getArg(i));
}
}
}
public:
ExtractOptionNames(llvm::StringSet<>& OptionNames) : OptionNames_(OptionNames)
{}
void operator()(const Init* Statement) {
if (typeid(*Statement) == typeid(ListInit)) {
const ListInit& DagList = *static_cast<const ListInit*>(Statement);
for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
B != E; ++B)
this->processDag(*B);
}
else {
this->processDag(Statement);
}
}
void operator()(const DagInit* Test, unsigned, bool) {
this->operator()(Test);
}
void operator()(const Init* Statement, unsigned) {
this->operator()(Statement);
}
};
/// CheckForSuperfluousOptions - Check that there are no side
/// effect-free options (specified only in the OptionList). Otherwise,
/// output a warning.
void CheckForSuperfluousOptions (const RecordVector& Edges,
const ToolDescriptions& ToolDescs,
const OptionDescriptions& OptDescs) {
llvm::StringSet<> nonSuperfluousOptions;
// Add all options mentioned in the ToolDesc.Actions to the set of
// non-superfluous options.
for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
E = ToolDescs.end(); B != E; ++B) {
const ToolDescription& TD = *(*B);
ExtractOptionNames Callback(nonSuperfluousOptions);
if (TD.Actions)
WalkCase(TD.Actions, Callback, Callback);
}
// Add all options mentioned in the 'case' clauses of the
// OptionalEdges of the compilation graph to the set of
// non-superfluous options.
for (RecordVector::const_iterator B = Edges.begin(), E = Edges.end();
B != E; ++B) {
const Record* Edge = *B;
DagInit* Weight = Edge->getValueAsDag("weight");
if (!isDagEmpty(Weight))
WalkCase(Weight, ExtractOptionNames(nonSuperfluousOptions), Id());
}
// Check that all options in OptDescs belong to the set of
// non-superfluous options.
for (OptionDescriptions::const_iterator B = OptDescs.begin(),
E = OptDescs.end(); B != E; ++B) {
const OptionDescription& Val = B->second;
if (!nonSuperfluousOptions.count(Val.Name)
&& Val.Type != OptionType::Alias)
llvm::errs() << "Warning: option '-" << Val.Name << "' has no effect! "
"Probable cause: this option is specified only in the OptionList.\n";
}
}
/// EmitCaseTest0Args - Helper function used by EmitCaseConstructHandler().
bool EmitCaseTest0Args(const std::string& TestName, raw_ostream& O) {
if (TestName == "single_input_file") {
O << "InputFilenames.size() == 1";
return true;
}
else if (TestName == "multiple_input_files") {
O << "InputFilenames.size() > 1";
return true;
}
return false;
}
/// EmitListTest - Helper function used by EmitCaseTest1ArgList().
template <typename F>
void EmitListTest(const ListInit& L, const char* LogicOp,
F Callback, raw_ostream& O)
{
// This is a lot like EmitLogicalOperationTest, but works on ListInits instead
// of Dags...
bool isFirst = true;
for (ListInit::const_iterator B = L.begin(), E = L.end(); B != E; ++B) {
if (isFirst)
isFirst = false;
else
O << " || ";
Callback(InitPtrToString(*B), O);
}
}
// Callbacks for use with EmitListTest.
class EmitSwitchOn {
const OptionDescriptions& OptDescs_;
public:
EmitSwitchOn(const OptionDescriptions& OptDescs) : OptDescs_(OptDescs)
{}
void operator()(const std::string& OptName, raw_ostream& O) const {
const OptionDescription& OptDesc = OptDescs_.FindSwitch(OptName);
O << OptDesc.GenVariableName();
}
};
class EmitEmptyTest {
bool EmitNegate_;
const OptionDescriptions& OptDescs_;
public:
EmitEmptyTest(bool EmitNegate, const OptionDescriptions& OptDescs)
: EmitNegate_(EmitNegate), OptDescs_(OptDescs)
{}
void operator()(const std::string& OptName, raw_ostream& O) const {
const char* Neg = (EmitNegate_ ? "!" : "");
if (OptName == "o") {
O << Neg << "OutputFilename.empty()";
}
else {
const OptionDescription& OptDesc = OptDescs_.FindListOrParameter(OptName);
O << Neg << OptDesc.GenVariableName() << ".empty()";
}
}
};
/// EmitCaseTest1ArgList - Helper function used by EmitCaseTest1Arg();
bool EmitCaseTest1ArgList(const std::string& TestName,
const DagInit& d,
const OptionDescriptions& OptDescs,
raw_ostream& O) {
const ListInit& L = *static_cast<ListInit*>(d.getArg(0));
if (TestName == "any_switch_on") {
EmitListTest(L, "||", EmitSwitchOn(OptDescs), O);
return true;
}
else if (TestName == "switch_on") {
EmitListTest(L, "&&", EmitSwitchOn(OptDescs), O);
return true;
}
else if (TestName == "any_not_empty") {
EmitListTest(L, "||", EmitEmptyTest(true, OptDescs), O);
return true;
}
else if (TestName == "any_empty") {
EmitListTest(L, "||", EmitEmptyTest(false, OptDescs), O);
return true;
}
else if (TestName == "not_empty") {
EmitListTest(L, "&&", EmitEmptyTest(true, OptDescs), O);
return true;
}
else if (TestName == "empty") {
EmitListTest(L, "&&", EmitEmptyTest(false, OptDescs), O);
return true;
}
return false;
}
/// EmitCaseTest1ArgStr - Helper function used by EmitCaseTest1Arg();
bool EmitCaseTest1ArgStr(const std::string& TestName,
const DagInit& d,
const OptionDescriptions& OptDescs,
raw_ostream& O) {
const std::string& OptName = InitPtrToString(d.getArg(0));
if (TestName == "switch_on") {
apply(EmitSwitchOn(OptDescs), OptName, O);
return true;
}
else if (TestName == "input_languages_contain") {
O << "InLangs.count(\"" << OptName << "\") != 0";
return true;
}
else if (TestName == "in_language") {
// This works only for single-argument Tool::GenerateAction. Join
// tools can process several files in different languages simultaneously.
// TODO: make this work with Edge::Weight (if possible).
O << "LangMap.GetLanguage(inFile) == \"" << OptName << '\"';
return true;
}
else if (TestName == "not_empty" || TestName == "empty") {
bool EmitNegate = (TestName == "not_empty");
apply(EmitEmptyTest(EmitNegate, OptDescs), OptName, O);
return true;
}
return false;
}
/// EmitCaseTest1Arg - Helper function used by EmitCaseConstructHandler();
bool EmitCaseTest1Arg(const std::string& TestName,
const DagInit& d,
const OptionDescriptions& OptDescs,
raw_ostream& O) {
checkNumberOfArguments(&d, 1);
if (typeid(*d.getArg(0)) == typeid(ListInit))
return EmitCaseTest1ArgList(TestName, d, OptDescs, O);
else
return EmitCaseTest1ArgStr(TestName, d, OptDescs, O);
}
/// EmitCaseTest2Args - Helper function used by EmitCaseConstructHandler().
bool EmitCaseTest2Args(const std::string& TestName,
const DagInit& d,
unsigned IndentLevel,
const OptionDescriptions& OptDescs,
raw_ostream& O) {
checkNumberOfArguments(&d, 2);
const std::string& OptName = InitPtrToString(d.getArg(0));
const std::string& OptArg = InitPtrToString(d.getArg(1));
if (TestName == "parameter_equals") {
const OptionDescription& OptDesc = OptDescs.FindParameter(OptName);
O << OptDesc.GenVariableName() << " == \"" << OptArg << "\"";
return true;
}
else if (TestName == "element_in_list") {
const OptionDescription& OptDesc = OptDescs.FindList(OptName);
const std::string& VarName = OptDesc.GenVariableName();
O << "std::find(" << VarName << ".begin(),\n";
O.indent(IndentLevel + Indent1)
<< VarName << ".end(), \""
<< OptArg << "\") != " << VarName << ".end()";
return true;
}
return false;
}
// Forward declaration.
// EmitLogicalOperationTest and EmitCaseTest are mutually recursive.
void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
const OptionDescriptions& OptDescs,
raw_ostream& O);
/// EmitLogicalOperationTest - Helper function used by
/// EmitCaseConstructHandler.
void EmitLogicalOperationTest(const DagInit& d, const char* LogicOp,
unsigned IndentLevel,
const OptionDescriptions& OptDescs,
raw_ostream& O) {
O << '(';
for (unsigned j = 0, NumArgs = d.getNumArgs(); j < NumArgs; ++j) {
const DagInit& InnerTest = InitPtrToDag(d.getArg(j));
EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
if (j != NumArgs - 1) {
O << ")\n";
O.indent(IndentLevel + Indent1) << ' ' << LogicOp << " (";
}
else {
O << ')';
}
}
}
void EmitLogicalNot(const DagInit& d, unsigned IndentLevel,
const OptionDescriptions& OptDescs, raw_ostream& O)
{
checkNumberOfArguments(&d, 1);
const DagInit& InnerTest = InitPtrToDag(d.getArg(0));
O << "! (";
EmitCaseTest(InnerTest, IndentLevel, OptDescs, O);
O << ")";
}
/// EmitCaseTest - Helper function used by EmitCaseConstructHandler.
void EmitCaseTest(const DagInit& d, unsigned IndentLevel,
const OptionDescriptions& OptDescs,
raw_ostream& O) {
const std::string& TestName = GetOperatorName(d);
if (TestName == "and")
EmitLogicalOperationTest(d, "&&", IndentLevel, OptDescs, O);
else if (TestName == "or")
EmitLogicalOperationTest(d, "||", IndentLevel, OptDescs, O);
else if (TestName == "not")
EmitLogicalNot(d, IndentLevel, OptDescs, O);
else if (EmitCaseTest0Args(TestName, O))
return;
else if (EmitCaseTest1Arg(TestName, d, OptDescs, O))
return;
else if (EmitCaseTest2Args(TestName, d, IndentLevel, OptDescs, O))
return;
else
throw TestName + ": unknown edge property!";
}
/// EmitCaseTestCallback - Callback used by EmitCaseConstructHandler.
class EmitCaseTestCallback {
bool EmitElseIf_;
const OptionDescriptions& OptDescs_;
raw_ostream& O_;
public:
EmitCaseTestCallback(bool EmitElseIf,
const OptionDescriptions& OptDescs, raw_ostream& O)
: EmitElseIf_(EmitElseIf), OptDescs_(OptDescs), O_(O)
{}
void operator()(const DagInit* Test, unsigned IndentLevel, bool FirstTest)
{
if (GetOperatorName(Test) == "default") {
O_.indent(IndentLevel) << "else {\n";
}
else {
O_.indent(IndentLevel)
<< ((!FirstTest && EmitElseIf_) ? "else if (" : "if (");
EmitCaseTest(*Test, IndentLevel, OptDescs_, O_);
O_ << ") {\n";
}
}
};
/// EmitCaseStatementCallback - Callback used by EmitCaseConstructHandler.
template <typename F>
class EmitCaseStatementCallback {
F Callback_;
raw_ostream& O_;
public:
EmitCaseStatementCallback(F Callback, raw_ostream& O)
: Callback_(Callback), O_(O)
{}
void operator() (const Init* Statement, unsigned IndentLevel) {
// Ignore nested 'case' DAG.
if (!(dynamic_cast<const DagInit*>(Statement) &&
GetOperatorName(static_cast<const DagInit*>(Statement)) == "case")) {
if (typeid(*Statement) == typeid(ListInit)) {
const ListInit& DagList = *static_cast<const ListInit*>(Statement);
for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
B != E; ++B)
Callback_(*B, (IndentLevel + Indent1), O_);
}
else {
Callback_(Statement, (IndentLevel + Indent1), O_);
}
}
O_.indent(IndentLevel) << "}\n";
}
};
/// EmitCaseConstructHandler - Emit code that handles the 'case'
/// construct. Takes a function object that should emit code for every case
/// clause. Implemented on top of WalkCase.
/// Callback's type is void F(Init* Statement, unsigned IndentLevel,
/// raw_ostream& O).
/// EmitElseIf parameter controls the type of condition that is emitted ('if
/// (..) {..} else if (..) {} .. else {..}' vs. 'if (..) {..} if(..) {..}
/// .. else {..}').
template <typename F>
void EmitCaseConstructHandler(const Init* Case, unsigned IndentLevel,
F Callback, bool EmitElseIf,
const OptionDescriptions& OptDescs,
raw_ostream& O) {
WalkCase(Case, EmitCaseTestCallback(EmitElseIf, OptDescs, O),
EmitCaseStatementCallback<F>(Callback, O), IndentLevel);
}
/// TokenizeCmdline - converts from "$CALL(HookName, 'Arg1', 'Arg2')/path" to
/// ["$CALL(", "HookName", "Arg1", "Arg2", ")/path"] .
/// Helper function used by EmitCmdLineVecFill and.
void TokenizeCmdline(const std::string& CmdLine, StrVector& Out) {
const char* Delimiters = " \t\n\v\f\r";
enum TokenizerState
{ Normal, SpecialCommand, InsideSpecialCommand, InsideQuotationMarks }
cur_st = Normal;
if (CmdLine.empty())
return;
Out.push_back("");
std::string::size_type B = CmdLine.find_first_not_of(Delimiters),
E = CmdLine.size();
for (; B != E; ++B) {
char cur_ch = CmdLine[B];
switch (cur_st) {
case Normal:
if (cur_ch == '$') {
cur_st = SpecialCommand;
break;
}
if (oneOf(Delimiters, cur_ch)) {
// Skip whitespace
B = CmdLine.find_first_not_of(Delimiters, B);
if (B == std::string::npos) {
B = E-1;
continue;
}
--B;
Out.push_back("");
continue;
}
break;
case SpecialCommand:
if (oneOf(Delimiters, cur_ch)) {
cur_st = Normal;
Out.push_back("");
continue;
}
if (cur_ch == '(') {
Out.push_back("");
cur_st = InsideSpecialCommand;
continue;
}
break;
case InsideSpecialCommand:
if (oneOf(Delimiters, cur_ch)) {
continue;
}
if (cur_ch == '\'') {
cur_st = InsideQuotationMarks;
Out.push_back("");
continue;
}
if (cur_ch == ')') {
cur_st = Normal;
Out.push_back("");
}
if (cur_ch == ',') {
continue;
}
break;
case InsideQuotationMarks:
if (cur_ch == '\'') {
cur_st = InsideSpecialCommand;
continue;
}
break;
}
Out.back().push_back(cur_ch);
}
}
/// SubstituteSpecialCommands - Perform string substitution for $CALL
/// and $ENV. Helper function used by EmitCmdLineVecFill().
StrVector::const_iterator SubstituteSpecialCommands
(StrVector::const_iterator Pos, StrVector::const_iterator End, raw_ostream& O)
{
const std::string& cmd = *Pos;
if (cmd == "$CALL") {
checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
const std::string& CmdName = *Pos;
if (CmdName == ")")
throw std::string("$CALL invocation: empty argument list!");
O << "hooks::";
O << CmdName << "(";
bool firstIteration = true;
while (true) {
checkedIncrement(Pos, End, "Syntax error in $CALL invocation!");
const std::string& Arg = *Pos;
assert(Arg.size() != 0);
if (Arg[0] == ')')
break;
if (firstIteration)
firstIteration = false;
else
O << ", ";
O << '"' << Arg << '"';
}
O << ')';
}
else if (cmd == "$ENV") {
checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
const std::string& EnvName = *Pos;
if (EnvName == ")")
throw "$ENV invocation: empty argument list!";
O << "checkCString(std::getenv(\"";
O << EnvName;
O << "\"))";
checkedIncrement(Pos, End, "Syntax error in $ENV invocation!");
}
else {
throw "Unknown special command: " + cmd;
}
const std::string& Leftover = *Pos;
assert(Leftover.at(0) == ')');
if (Leftover.size() != 1)
O << " + std::string(\"" << (Leftover.c_str() + 1) << "\")";
return Pos;
}
/// EmitCmdLineVecFill - Emit code that fills in the command line
/// vector. Helper function used by EmitGenerateActionMethod().
void EmitCmdLineVecFill(const Init* CmdLine, const std::string& ToolName,
bool IsJoin, unsigned IndentLevel,
raw_ostream& O) {
StrVector StrVec;
TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
if (StrVec.empty())
throw "Tool '" + ToolName + "' has empty command line!";
StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
// If there is a hook invocation on the place of the first command, skip it.
assert(!StrVec[0].empty());
if (StrVec[0][0] == '$') {
while (I != E && (*I)[0] != ')' )
++I;
// Skip the ')' symbol.
++I;
}
else {
++I;
}
bool hasINFILE = false;
for (; I != E; ++I) {
const std::string& cmd = *I;
assert(!cmd.empty());
O.indent(IndentLevel);
if (cmd.at(0) == '$') {
if (cmd == "$INFILE") {
hasINFILE = true;
if (IsJoin) {
O << "for (PathVector::const_iterator B = inFiles.begin()"
<< ", E = inFiles.end();\n";
O.indent(IndentLevel) << "B != E; ++B)\n";
O.indent(IndentLevel + Indent1) << "vec.push_back(B->str());\n";
}
else {
O << "vec.push_back(inFile.str());\n";
}
}
else if (cmd == "$OUTFILE") {
O << "vec.push_back(\"\");\n";
O.indent(IndentLevel) << "out_file_index = vec.size()-1;\n";
}
else {
O << "vec.push_back(";
I = SubstituteSpecialCommands(I, E, O);
O << ");\n";
}
}
else {
O << "vec.push_back(\"" << cmd << "\");\n";
}
}
if (!hasINFILE)
throw "Tool '" + ToolName + "' doesn't take any input!";
O.indent(IndentLevel) << "cmd = ";
if (StrVec[0][0] == '$')
SubstituteSpecialCommands(StrVec.begin(), StrVec.end(), O);
else
O << '"' << StrVec[0] << '"';
O << ";\n";
}
/// EmitCmdLineVecFillCallback - A function object wrapper around
/// EmitCmdLineVecFill(). Used by EmitGenerateActionMethod() as an
/// argument to EmitCaseConstructHandler().
class EmitCmdLineVecFillCallback {
bool IsJoin;
const std::string& ToolName;
public:
EmitCmdLineVecFillCallback(bool J, const std::string& TN)
: IsJoin(J), ToolName(TN) {}
void operator()(const Init* Statement, unsigned IndentLevel,
raw_ostream& O) const
{
EmitCmdLineVecFill(Statement, ToolName, IsJoin, IndentLevel, O);
}
};
/// EmitForwardOptionPropertyHandlingCode - Helper function used to
/// implement EmitActionHandler. Emits code for
/// handling the (forward) and (forward_as) option properties.
void EmitForwardOptionPropertyHandlingCode (const OptionDescription& D,
unsigned IndentLevel,
const std::string& NewName,
raw_ostream& O) {
const std::string& Name = NewName.empty()
? ("-" + D.Name)
: NewName;
unsigned IndentLevel1 = IndentLevel + Indent1;
switch (D.Type) {
case OptionType::Switch:
O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
break;
case OptionType::Parameter:
O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\");\n";
O.indent(IndentLevel) << "vec.push_back(" << D.GenVariableName() << ");\n";
break;
case OptionType::Prefix:
O.indent(IndentLevel) << "vec.push_back(\"" << Name << "\" + "
<< D.GenVariableName() << ");\n";
break;
case OptionType::PrefixList:
O.indent(IndentLevel)
<< "for (" << D.GenTypeDeclaration()
<< "::iterator B = " << D.GenVariableName() << ".begin(),\n";
O.indent(IndentLevel)
<< "E = " << D.GenVariableName() << ".end(); B != E;) {\n";
O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\" + " << "*B);\n";
O.indent(IndentLevel1) << "++B;\n";
for (int i = 1, j = D.MultiVal; i < j; ++i) {
O.indent(IndentLevel1) << "vec.push_back(*B);\n";
O.indent(IndentLevel1) << "++B;\n";
}
O.indent(IndentLevel) << "}\n";
break;
case OptionType::ParameterList:
O.indent(IndentLevel)
<< "for (" << D.GenTypeDeclaration() << "::iterator B = "
<< D.GenVariableName() << ".begin(),\n";
O.indent(IndentLevel) << "E = " << D.GenVariableName()
<< ".end() ; B != E;) {\n";
O.indent(IndentLevel1) << "vec.push_back(\"" << Name << "\");\n";
for (int i = 0, j = D.MultiVal; i < j; ++i) {
O.indent(IndentLevel1) << "vec.push_back(*B);\n";
O.indent(IndentLevel1) << "++B;\n";
}
O.indent(IndentLevel) << "}\n";
break;
case OptionType::Alias:
default:
throw std::string("Aliases are not allowed in tool option descriptions!");
}
}
/// ActionHandlingCallbackBase - Base class of EmitActionHandlersCallback and
/// EmitPreprocessOptionsCallback.
struct ActionHandlingCallbackBase {
void onErrorDag(const DagInit& d,
unsigned IndentLevel, raw_ostream& O) const
{
O.indent(IndentLevel)
<< "throw std::runtime_error(\"" <<
(d.getNumArgs() >= 1 ? InitPtrToString(d.getArg(0))
: "Unknown error!")
<< "\");\n";
}
void onWarningDag(const DagInit& d,
unsigned IndentLevel, raw_ostream& O) const
{
checkNumberOfArguments(&d, 1);
O.indent(IndentLevel) << "llvm::errs() << \""
<< InitPtrToString(d.getArg(0)) << "\";\n";
}
};
/// EmitActionHandlersCallback - Emit code that handles actions. Used by
/// EmitGenerateActionMethod() as an argument to EmitCaseConstructHandler().
class EmitActionHandlersCallback : ActionHandlingCallbackBase {
const OptionDescriptions& OptDescs;
void processActionDag(const Init* Statement, unsigned IndentLevel,
raw_ostream& O) const
{
const DagInit& Dag = InitPtrToDag(Statement);
const std::string& ActionName = GetOperatorName(Dag);
if (ActionName == "append_cmd") {
checkNumberOfArguments(&Dag, 1);
const std::string& Cmd = InitPtrToString(Dag.getArg(0));
StrVector Out;
llvm::SplitString(Cmd, Out);
for (StrVector::const_iterator B = Out.begin(), E = Out.end();
B != E; ++B)
O.indent(IndentLevel) << "vec.push_back(\"" << *B << "\");\n";
}
else if (ActionName == "error") {
this->onErrorDag(Dag, IndentLevel, O);
}
else if (ActionName == "warning") {
this->onWarningDag(Dag, IndentLevel, O);
}
else if (ActionName == "forward") {
checkNumberOfArguments(&Dag, 1);
const std::string& Name = InitPtrToString(Dag.getArg(0));
EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
IndentLevel, "", O);
}
else if (ActionName == "forward_as") {
checkNumberOfArguments(&Dag, 2);
const std::string& Name = InitPtrToString(Dag.getArg(0));
const std::string& NewName = InitPtrToString(Dag.getArg(1));
EmitForwardOptionPropertyHandlingCode(OptDescs.FindOption(Name),
IndentLevel, NewName, O);
}
else if (ActionName == "output_suffix") {
checkNumberOfArguments(&Dag, 1);
const std::string& OutSuf = InitPtrToString(Dag.getArg(0));
O.indent(IndentLevel) << "output_suffix = \"" << OutSuf << "\";\n";
}
else if (ActionName == "stop_compilation") {
O.indent(IndentLevel) << "stop_compilation = true;\n";
}
else if (ActionName == "unpack_values") {
checkNumberOfArguments(&Dag, 1);
const std::string& Name = InitPtrToString(Dag.getArg(0));
const OptionDescription& D = OptDescs.FindOption(Name);
if (D.isMultiVal())
throw std::string("Can't use unpack_values with multi-valued options!");
if (D.isList()) {
O.indent(IndentLevel)
<< "for (" << D.GenTypeDeclaration()
<< "::iterator B = " << D.GenVariableName() << ".begin(),\n";
O.indent(IndentLevel)
<< "E = " << D.GenVariableName() << ".end(); B != E; ++B)\n";
O.indent(IndentLevel + Indent1)
<< "llvm::SplitString(*B, vec, \",\");\n";
}
else if (D.isParameter()){
O.indent(IndentLevel) << "llvm::SplitString("
<< D.GenVariableName() << ", vec, \",\");\n";
}
else {
throw "Option '" + D.Name +
"': switches can't have the 'unpack_values' property!";
}
}
else {
throw "Unknown action name: " + ActionName + "!";
}
}
public:
EmitActionHandlersCallback(const OptionDescriptions& OD)
: OptDescs(OD) {}
void operator()(const Init* Statement,
unsigned IndentLevel, raw_ostream& O) const
{
this->processActionDag(Statement, IndentLevel, O);
}
};
bool IsOutFileIndexCheckRequiredStr (const Init* CmdLine) {
StrVector StrVec;
TokenizeCmdline(InitPtrToString(CmdLine), StrVec);
for (StrVector::const_iterator I = StrVec.begin(), E = StrVec.end();
I != E; ++I) {
if (*I == "$OUTFILE")
return false;
}
return true;
}
class IsOutFileIndexCheckRequiredStrCallback {
bool* ret_;
public:
IsOutFileIndexCheckRequiredStrCallback(bool* ret) : ret_(ret)
{}
void operator()(const Init* CmdLine) {
// Ignore nested 'case' DAG.
if (typeid(*CmdLine) == typeid(DagInit))
return;
if (IsOutFileIndexCheckRequiredStr(CmdLine))
*ret_ = true;
}
void operator()(const DagInit* Test, unsigned, bool) {
this->operator()(Test);
}
void operator()(const Init* Statement, unsigned) {
this->operator()(Statement);
}
};
bool IsOutFileIndexCheckRequiredCase (Init* CmdLine) {
bool ret = false;
WalkCase(CmdLine, Id(), IsOutFileIndexCheckRequiredStrCallback(&ret));
return ret;
}
/// IsOutFileIndexCheckRequired - Should we emit an "out_file_index != -1" check
/// in EmitGenerateActionMethod() ?
bool IsOutFileIndexCheckRequired (Init* CmdLine) {
if (typeid(*CmdLine) == typeid(StringInit))
return IsOutFileIndexCheckRequiredStr(CmdLine);
else
return IsOutFileIndexCheckRequiredCase(CmdLine);
}
// EmitGenerateActionMethod - Emit either a normal or a "join" version of the
// Tool::GenerateAction() method.
void EmitGenerateActionMethod (const ToolDescription& D,
const OptionDescriptions& OptDescs,
bool IsJoin, raw_ostream& O) {
if (IsJoin)
O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
else
O.indent(Indent1) << "Action GenerateAction(const sys::Path& inFile,\n";
O.indent(Indent2) << "bool HasChildren,\n";
O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
O.indent(Indent1) << "{\n";
O.indent(Indent2) << "std::string cmd;\n";
O.indent(Indent2) << "std::vector<std::string> vec;\n";
O.indent(Indent2) << "bool stop_compilation = !HasChildren;\n";
O.indent(Indent2) << "const char* output_suffix = \""
<< D.OutputSuffix << "\";\n";
if (!D.CmdLine)
throw "Tool " + D.Name + " has no cmd_line property!";
bool IndexCheckRequired = IsOutFileIndexCheckRequired(D.CmdLine);
O.indent(Indent2) << "int out_file_index"
<< (IndexCheckRequired ? " = -1" : "")
<< ";\n\n";
// Process the cmd_line property.
if (typeid(*D.CmdLine) == typeid(StringInit))
EmitCmdLineVecFill(D.CmdLine, D.Name, IsJoin, Indent2, O);
else
EmitCaseConstructHandler(D.CmdLine, Indent2,
EmitCmdLineVecFillCallback(IsJoin, D.Name),
true, OptDescs, O);
// For every understood option, emit handling code.
if (D.Actions)
EmitCaseConstructHandler(D.Actions, Indent2,
EmitActionHandlersCallback(OptDescs),
false, OptDescs, O);
O << '\n';
O.indent(Indent2)
<< "std::string out_file = OutFilename("
<< (IsJoin ? "sys::Path(),\n" : "inFile,\n");
O.indent(Indent3) << "TempDir, stop_compilation, output_suffix).str();\n\n";
if (IndexCheckRequired)
O.indent(Indent2) << "if (out_file_index != -1)\n";
O.indent(IndexCheckRequired ? Indent3 : Indent2)
<< "vec[out_file_index] = out_file;\n";
// Handle the Sink property.
if (D.isSink()) {
O.indent(Indent2) << "if (!" << SinkOptionName << ".empty()) {\n";
O.indent(Indent3) << "vec.insert(vec.end(), "
<< SinkOptionName << ".begin(), " << SinkOptionName
<< ".end());\n";
O.indent(Indent2) << "}\n";
}
O.indent(Indent2) << "return Action(cmd, vec, stop_compilation, out_file);\n";
O.indent(Indent1) << "}\n\n";
}
/// EmitGenerateActionMethods - Emit two GenerateAction() methods for
/// a given Tool class.
void EmitGenerateActionMethods (const ToolDescription& ToolDesc,
const OptionDescriptions& OptDescs,
raw_ostream& O) {
if (!ToolDesc.isJoin()) {
O.indent(Indent1) << "Action GenerateAction(const PathVector& inFiles,\n";
O.indent(Indent2) << "bool HasChildren,\n";
O.indent(Indent2) << "const llvm::sys::Path& TempDir,\n";
O.indent(Indent2) << "const InputLanguagesSet& InLangs,\n";
O.indent(Indent2) << "const LanguageMap& LangMap) const\n";
O.indent(Indent1) << "{\n";
O.indent(Indent2) << "throw std::runtime_error(\"" << ToolDesc.Name
<< " is not a Join tool!\");\n";
O.indent(Indent1) << "}\n\n";
}
else {
EmitGenerateActionMethod(ToolDesc, OptDescs, true, O);
}
EmitGenerateActionMethod(ToolDesc, OptDescs, false, O);
}
/// EmitInOutLanguageMethods - Emit the [Input,Output]Language()
/// methods for a given Tool class.
void EmitInOutLanguageMethods (const ToolDescription& D, raw_ostream& O) {
O.indent(Indent1) << "const char** InputLanguages() const {\n";
O.indent(Indent2) << "return InputLanguages_;\n";
O.indent(Indent1) << "}\n\n";
if (D.OutLanguage.empty())
throw "Tool " + D.Name + " has no 'out_language' property!";
O.indent(Indent1) << "const char* OutputLanguage() const {\n";
O.indent(Indent2) << "return \"" << D.OutLanguage << "\";\n";
O.indent(Indent1) << "}\n\n";
}
/// EmitNameMethod - Emit the Name() method for a given Tool class.
void EmitNameMethod (const ToolDescription& D, raw_ostream& O) {
O.indent(Indent1) << "const char* Name() const {\n";
O.indent(Indent2) << "return \"" << D.Name << "\";\n";
O.indent(Indent1) << "}\n\n";
}
/// EmitIsJoinMethod - Emit the IsJoin() method for a given Tool
/// class.
void EmitIsJoinMethod (const ToolDescription& D, raw_ostream& O) {
O.indent(Indent1) << "bool IsJoin() const {\n";
if (D.isJoin())
O.indent(Indent2) << "return true;\n";
else
O.indent(Indent2) << "return false;\n";
O.indent(Indent1) << "}\n\n";
}
/// EmitStaticMemberDefinitions - Emit static member definitions for a
/// given Tool class.
void EmitStaticMemberDefinitions(const ToolDescription& D, raw_ostream& O) {
if (D.InLanguage.empty())
throw "Tool " + D.Name + " has no 'in_language' property!";
O << "const char* " << D.Name << "::InputLanguages_[] = {";
for (StrVector::const_iterator B = D.InLanguage.begin(),
E = D.InLanguage.end(); B != E; ++B)
O << '\"' << *B << "\", ";
O << "0};\n\n";
}
/// EmitToolClassDefinition - Emit a Tool class definition.
void EmitToolClassDefinition (const ToolDescription& D,
const OptionDescriptions& OptDescs,
raw_ostream& O) {
if (D.Name == "root")
return;
// Header
O << "class " << D.Name << " : public ";
if (D.isJoin())
O << "JoinTool";
else
O << "Tool";
O << "{\nprivate:\n";
O.indent(Indent1) << "static const char* InputLanguages_[];\n\n";
O << "public:\n";
EmitNameMethod(D, O);
EmitInOutLanguageMethods(D, O);
EmitIsJoinMethod(D, O);
EmitGenerateActionMethods(D, OptDescs, O);
// Close class definition
O << "};\n";
EmitStaticMemberDefinitions(D, O);
}
/// EmitOptionDefinitions - Iterate over a list of option descriptions
/// and emit registration code.
void EmitOptionDefinitions (const OptionDescriptions& descs,
bool HasSink, bool HasExterns,
raw_ostream& O)
{
std::vector<OptionDescription> Aliases;
// Emit static cl::Option variables.
for (OptionDescriptions::const_iterator B = descs.begin(),
E = descs.end(); B!=E; ++B) {
const OptionDescription& val = B->second;
if (val.Type == OptionType::Alias) {
Aliases.push_back(val);
continue;
}
if (val.isExtern())
O << "extern ";
O << val.GenTypeDeclaration() << ' '
<< val.GenVariableName();
if (val.isExtern()) {
O << ";\n";
continue;
}
O << "(\"" << val.Name << "\"\n";
if (val.Type == OptionType::Prefix || val.Type == OptionType::PrefixList)
O << ", cl::Prefix";
if (val.isRequired()) {
if (val.isList() && !val.isMultiVal())
O << ", cl::OneOrMore";
else
O << ", cl::Required";
}
else if (val.isOneOrMore() && val.isList()) {
O << ", cl::OneOrMore";
}
else if (val.isZeroOrOne() && val.isList()) {
O << ", cl::ZeroOrOne";
}
if (val.isReallyHidden()) {
O << ", cl::ReallyHidden";
}
else if (val.isHidden()) {
O << ", cl::Hidden";
}
if (val.MultiVal > 1)
O << ", cl::multi_val(" << val.MultiVal << ')';
if (val.InitVal) {
const std::string& str = val.InitVal->getAsString();
O << ", cl::init(" << str << ')';
}
if (!val.Help.empty())
O << ", cl::desc(\"" << val.Help << "\")";
O << ");\n\n";
}
// Emit the aliases (they should go after all the 'proper' options).
for (std::vector<OptionDescription>::const_iterator
B = Aliases.begin(), E = Aliases.end(); B != E; ++B) {
const OptionDescription& val = *B;
O << val.GenTypeDeclaration() << ' '
<< val.GenVariableName()
<< "(\"" << val.Name << '\"';
const OptionDescription& D = descs.FindOption(val.Help);
O << ", cl::aliasopt(" << D.GenVariableName() << ")";
O << ", cl::desc(\"" << "An alias for -" + val.Help << "\"));\n";
}
// Emit the sink option.
if (HasSink)
O << (HasExterns ? "extern cl" : "cl")
<< "::list<std::string> " << SinkOptionName
<< (HasExterns ? ";\n" : "(cl::Sink);\n");
O << '\n';
}
/// EmitPreprocessOptionsCallback - Helper function passed to
/// EmitCaseConstructHandler() by EmitPreprocessOptions().
class EmitPreprocessOptionsCallback : ActionHandlingCallbackBase {
const OptionDescriptions& OptDescs_;
void onUnsetOption(Init* i, unsigned IndentLevel, raw_ostream& O) {
const std::string& OptName = InitPtrToString(i);
const OptionDescription& OptDesc = OptDescs_.FindOption(OptName);
if (OptDesc.isSwitch()) {
O.indent(IndentLevel) << OptDesc.GenVariableName() << " = false;\n";
}
else if (OptDesc.isParameter()) {
O.indent(IndentLevel) << OptDesc.GenVariableName() << " = \"\";\n";
}
else if (OptDesc.isList()) {
O.indent(IndentLevel) << OptDesc.GenVariableName() << ".clear();\n";
}
else {
throw "Can't apply 'unset_option' to alias option '" + OptName + "'";
}
}
void processDag(const Init* I, unsigned IndentLevel, raw_ostream& O)
{
const DagInit& d = InitPtrToDag(I);
const std::string& OpName = GetOperatorName(d);
if (OpName == "warning") {
this->onWarningDag(d, IndentLevel, O);
}
else if (OpName == "error") {
this->onWarningDag(d, IndentLevel, O);
}
else if (OpName == "unset_option") {
checkNumberOfArguments(&d, 1);
Init* I = d.getArg(0);
if (typeid(*I) == typeid(ListInit)) {
const ListInit& DagList = *static_cast<const ListInit*>(I);
for (ListInit::const_iterator B = DagList.begin(), E = DagList.end();
B != E; ++B)
this->onUnsetOption(*B, IndentLevel, O);
}
else {
this->onUnsetOption(I, IndentLevel, O);
}
}
else {
throw "Unknown operator in the option preprocessor: '" + OpName + "'!"
"\nOnly 'warning', 'error' and 'unset_option' are allowed.";
}
}
public:
void operator()(const Init* I, unsigned IndentLevel, raw_ostream& O) {
this->processDag(I, IndentLevel, O);
}
EmitPreprocessOptionsCallback(const OptionDescriptions& OptDescs)
: OptDescs_(OptDescs)
{}
};
/// EmitPreprocessOptions - Emit the PreprocessOptionsLocal() function.
void EmitPreprocessOptions (const RecordKeeper& Records,
const OptionDescriptions& OptDecs, raw_ostream& O)
{
O << "void PreprocessOptionsLocal() {\n";
const RecordVector& OptionPreprocessors =
Records.getAllDerivedDefinitions("OptionPreprocessor");
for (RecordVector::const_iterator B = OptionPreprocessors.begin(),
E = OptionPreprocessors.end(); B!=E; ++B) {
DagInit* Case = (*B)->getValueAsDag("preprocessor");
EmitCaseConstructHandler(Case, Indent1,
EmitPreprocessOptionsCallback(OptDecs),
false, OptDecs, O);
}
O << "}\n\n";
}
/// EmitPopulateLanguageMap - Emit the PopulateLanguageMapLocal() function.
void EmitPopulateLanguageMap (const RecordKeeper& Records, raw_ostream& O)
{
O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
// Get the relevant field out of RecordKeeper
const Record* LangMapRecord = Records.getDef("LanguageMap");
// It is allowed for a plugin to have no language map.
if (LangMapRecord) {
ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
if (!LangsToSuffixesList)
throw std::string("Error in the language map definition!");
for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
const std::string& Lang = LangToSuffixes->getValueAsString("lang");
const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
for (unsigned i = 0; i < Suffixes->size(); ++i)
O.indent(Indent1) << "langMap[\""
<< InitPtrToString(Suffixes->getElement(i))
<< "\"] = \"" << Lang << "\";\n";
}
}
O << "}\n\n";
}
/// IncDecWeight - Helper function passed to EmitCaseConstructHandler()
/// by EmitEdgeClass().
void IncDecWeight (const Init* i, unsigned IndentLevel,
raw_ostream& O) {
const DagInit& d = InitPtrToDag(i);
const std::string& OpName = GetOperatorName(d);
if (OpName == "inc_weight") {
O.indent(IndentLevel) << "ret += ";
}
else if (OpName == "dec_weight") {
O.indent(IndentLevel) << "ret -= ";
}
else if (OpName == "error") {
checkNumberOfArguments(&d, 1);
O.indent(IndentLevel) << "throw std::runtime_error(\""
<< InitPtrToString(d.getArg(0))
<< "\");\n";
return;
}
else {
throw "Unknown operator in edge properties list: '" + OpName + "'!"
"\nOnly 'inc_weight', 'dec_weight' and 'error' are allowed.";
}
if (d.getNumArgs() > 0)
O << InitPtrToInt(d.getArg(0)) << ";\n";
else
O << "2;\n";
}
/// EmitEdgeClass - Emit a single Edge# class.
void EmitEdgeClass (unsigned N, const std::string& Target,
DagInit* Case, const OptionDescriptions& OptDescs,
raw_ostream& O) {
// Class constructor.
O << "class Edge" << N << ": public Edge {\n"
<< "public:\n";
O.indent(Indent1) << "Edge" << N << "() : Edge(\"" << Target
<< "\") {}\n\n";
// Function Weight().
O.indent(Indent1)
<< "unsigned Weight(const InputLanguagesSet& InLangs) const {\n";
O.indent(Indent2) << "unsigned ret = 0;\n";
// Handle the 'case' construct.
EmitCaseConstructHandler(Case, Indent2, IncDecWeight, false, OptDescs, O);
O.indent(Indent2) << "return ret;\n";
O.indent(Indent1) << "};\n\n};\n\n";
}
/// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
void EmitEdgeClasses (const RecordVector& EdgeVector,
const OptionDescriptions& OptDescs,
raw_ostream& O) {
int i = 0;
for (RecordVector::const_iterator B = EdgeVector.begin(),
E = EdgeVector.end(); B != E; ++B) {
const Record* Edge = *B;
const std::string& NodeB = Edge->getValueAsString("b");
DagInit* Weight = Edge->getValueAsDag("weight");
if (!isDagEmpty(Weight))
EmitEdgeClass(i, NodeB, Weight, OptDescs, O);
++i;
}
}
/// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraphLocal()
/// function.
void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
const ToolDescriptions& ToolDescs,
raw_ostream& O)
{
O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
E = ToolDescs.end(); B != E; ++B)
O.indent(Indent1) << "G.insertNode(new " << (*B)->Name << "());\n";
O << '\n';
// Insert edges.
int i = 0;
for (RecordVector::const_iterator B = EdgeVector.begin(),
E = EdgeVector.end(); B != E; ++B) {
const Record* Edge = *B;
const std::string& NodeA = Edge->getValueAsString("a");
const std::string& NodeB = Edge->getValueAsString("b");
DagInit* Weight = Edge->getValueAsDag("weight");
O.indent(Indent1) << "G.insertEdge(\"" << NodeA << "\", ";
if (isDagEmpty(Weight))
O << "new SimpleEdge(\"" << NodeB << "\")";
else
O << "new Edge" << i << "()";
O << ");\n";
++i;
}
O << "}\n\n";
}
/// ExtractHookNames - Extract the hook names from all instances of
/// $CALL(HookName) in the provided command line string. Helper
/// function used by FillInHookNames().
class ExtractHookNames {
llvm::StringMap<unsigned>& HookNames_;
public:
ExtractHookNames(llvm::StringMap<unsigned>& HookNames)
: HookNames_(HookNames) {}
void operator()(const Init* CmdLine) {
StrVector cmds;
// Ignore nested 'case' DAG.
if (typeid(*CmdLine) == typeid(DagInit))
return;
TokenizeCmdline(InitPtrToString(CmdLine), cmds);
for (StrVector::const_iterator B = cmds.begin(), E = cmds.end();
B != E; ++B) {
const std::string& cmd = *B;
if (cmd == "$CALL") {
unsigned NumArgs = 0;
checkedIncrement(B, E, "Syntax error in $CALL invocation!");
const std::string& HookName = *B;
if (HookName.at(0) == ')')
throw "$CALL invoked with no arguments!";
while (++B != E && B->at(0) != ')') {
++NumArgs;
}
StringMap<unsigned>::const_iterator H = HookNames_.find(HookName);
if (H != HookNames_.end() && H->second != NumArgs)
throw "Overloading of hooks is not allowed. Overloaded hook: "
+ HookName;
else
HookNames_[HookName] = NumArgs;
}
}
}
void operator()(const DagInit* Test, unsigned, bool) {
this->operator()(Test);
}
void operator()(const Init* Statement, unsigned) {
this->operator()(Statement);
}
};
/// FillInHookNames - Actually extract the hook names from all command
/// line strings. Helper function used by EmitHookDeclarations().
void FillInHookNames(const ToolDescriptions& ToolDescs,
llvm::StringMap<unsigned>& HookNames)
{
// For all command lines:
for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
E = ToolDescs.end(); B != E; ++B) {
const ToolDescription& D = *(*B);
if (!D.CmdLine)
continue;
if (dynamic_cast<StringInit*>(D.CmdLine))
// This is a string.
ExtractHookNames(HookNames).operator()(D.CmdLine);
else
// This is a 'case' construct.
WalkCase(D.CmdLine, Id(), ExtractHookNames(HookNames));
}
}
/// EmitHookDeclarations - Parse CmdLine fields of all the tool
/// property records and emit hook function declaration for each
/// instance of $CALL(HookName).
void EmitHookDeclarations(const ToolDescriptions& ToolDescs, raw_ostream& O) {
llvm::StringMap<unsigned> HookNames;
FillInHookNames(ToolDescs, HookNames);
if (HookNames.empty())
return;
O << "namespace hooks {\n";
for (StringMap<unsigned>::const_iterator B = HookNames.begin(),
E = HookNames.end(); B != E; ++B) {
O.indent(Indent1) << "std::string " << B->first() << "(";
for (unsigned i = 0, j = B->second; i < j; ++i) {
O << "const char* Arg" << i << (i+1 == j ? "" : ", ");
}
O <<");\n";
}
O << "}\n\n";
}
/// EmitRegisterPlugin - Emit code to register this plugin.
void EmitRegisterPlugin(int Priority, raw_ostream& O) {
O << "struct Plugin : public llvmc::BasePlugin {\n\n";
O.indent(Indent1) << "int Priority() const { return "
<< Priority << "; }\n\n";
O.indent(Indent1) << "void PreprocessOptions() const\n";
O.indent(Indent1) << "{ PreprocessOptionsLocal(); }\n\n";
O.indent(Indent1) << "void PopulateLanguageMap(LanguageMap& langMap) const\n";
O.indent(Indent1) << "{ PopulateLanguageMapLocal(langMap); }\n\n";
O.indent(Indent1)
<< "void PopulateCompilationGraph(CompilationGraph& graph) const\n";
O.indent(Indent1) << "{ PopulateCompilationGraphLocal(graph); }\n"
<< "};\n\n"
<< "static llvmc::RegisterPlugin<Plugin> RP;\n\n";
}
/// EmitIncludes - Emit necessary #include directives and some
/// additional declarations.
void EmitIncludes(raw_ostream& O) {
O << "#include \"llvm/CompilerDriver/BuiltinOptions.h\"\n"
<< "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
<< "#include \"llvm/CompilerDriver/ForceLinkageMacros.h\"\n"
<< "#include \"llvm/CompilerDriver/Plugin.h\"\n"
<< "#include \"llvm/CompilerDriver/Tool.h\"\n\n"
<< "#include \"llvm/ADT/StringExtras.h\"\n"
<< "#include \"llvm/Support/CommandLine.h\"\n"
<< "#include \"llvm/Support/raw_ostream.h\"\n\n"
<< "#include <cstdlib>\n"
<< "#include <stdexcept>\n\n"
<< "using namespace llvm;\n"
<< "using namespace llvmc;\n\n"
<< "extern cl::opt<std::string> OutputFilename;\n\n"
<< "inline const char* checkCString(const char* s)\n"
<< "{ return s == NULL ? \"\" : s; }\n\n";
}
/// PluginData - Holds all information about a plugin.
struct PluginData {
OptionDescriptions OptDescs;
bool HasSink;
bool HasExterns;
ToolDescriptions ToolDescs;
RecordVector Edges;
int Priority;
};
/// HasSink - Go through the list of tool descriptions and check if
/// there are any with the 'sink' property set.
bool HasSink(const ToolDescriptions& ToolDescs) {
for (ToolDescriptions::const_iterator B = ToolDescs.begin(),
E = ToolDescs.end(); B != E; ++B)
if ((*B)->isSink())
return true;
return false;
}
/// HasExterns - Go through the list of option descriptions and check
/// if there are any external options.
bool HasExterns(const OptionDescriptions& OptDescs) {
for (OptionDescriptions::const_iterator B = OptDescs.begin(),
E = OptDescs.end(); B != E; ++B)
if (B->second.isExtern())
return true;
return false;
}
/// CollectPluginData - Collect tool and option properties,
/// compilation graph edges and plugin priority from the parse tree.
void CollectPluginData (const RecordKeeper& Records, PluginData& Data) {
// Collect option properties.
const RecordVector& OptionLists =
Records.getAllDerivedDefinitions("OptionList");
CollectOptionDescriptions(OptionLists.begin(), OptionLists.end(),
Data.OptDescs);
// Collect tool properties.
const RecordVector& Tools = Records.getAllDerivedDefinitions("Tool");
CollectToolDescriptions(Tools.begin(), Tools.end(), Data.ToolDescs);
Data.HasSink = HasSink(Data.ToolDescs);
Data.HasExterns = HasExterns(Data.OptDescs);
// Collect compilation graph edges.
const RecordVector& CompilationGraphs =
Records.getAllDerivedDefinitions("CompilationGraph");
FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
Data.Edges);
// Calculate the priority of this plugin.
const RecordVector& Priorities =
Records.getAllDerivedDefinitions("PluginPriority");
Data.Priority = CalculatePriority(Priorities.begin(), Priorities.end());
}
/// CheckPluginData - Perform some sanity checks on the collected data.
void CheckPluginData(PluginData& Data) {
// Filter out all tools not mentioned in the compilation graph.
FilterNotInGraph(Data.Edges, Data.ToolDescs);
// Typecheck the compilation graph.
TypecheckGraph(Data.Edges, Data.ToolDescs);
// Check that there are no options without side effects (specified
// only in the OptionList).
CheckForSuperfluousOptions(Data.Edges, Data.ToolDescs, Data.OptDescs);
}
void EmitPluginCode(const PluginData& Data, raw_ostream& O) {
// Emit file header.
EmitIncludes(O);
// Emit global option registration code.
EmitOptionDefinitions(Data.OptDescs, Data.HasSink, Data.HasExterns, O);
// Emit hook declarations.
EmitHookDeclarations(Data.ToolDescs, O);
O << "namespace {\n\n";
// Emit PreprocessOptionsLocal() function.
EmitPreprocessOptions(Records, Data.OptDescs, O);
// Emit PopulateLanguageMapLocal() function
// (language map maps from file extensions to language names).
EmitPopulateLanguageMap(Records, O);
// Emit Tool classes.
for (ToolDescriptions::const_iterator B = Data.ToolDescs.begin(),
E = Data.ToolDescs.end(); B!=E; ++B)
EmitToolClassDefinition(*(*B), Data.OptDescs, O);
// Emit Edge# classes.
EmitEdgeClasses(Data.Edges, Data.OptDescs, O);
// Emit PopulateCompilationGraphLocal() function.
EmitPopulateCompilationGraph(Data.Edges, Data.ToolDescs, O);
// Emit code for plugin registration.
EmitRegisterPlugin(Data.Priority, O);
O << "} // End anonymous namespace.\n\n";
// Force linkage magic.
O << "namespace llvmc {\n";
O << "LLVMC_FORCE_LINKAGE_DECL(LLVMC_PLUGIN_NAME) {}\n";
O << "}\n";
// EOF
}
// End of anonymous namespace
}
/// run - The back-end entry point.
void LLVMCConfigurationEmitter::run (raw_ostream &O) {
try {
PluginData Data;
CollectPluginData(Records, Data);
CheckPluginData(Data);
EmitSourceFileHeader("LLVMC Configuration Library", O);
EmitPluginCode(Data, O);
} catch (std::exception& Error) {
throw Error.what() + std::string(" - usually this means a syntax error.");
}
}
|