summaryrefslogtreecommitdiff
path: root/src/plugins/projectexplorer/msvctoolchain.cpp
blob: 4e5bb1cb18a55c43247af826cb648a243e34db4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "msvctoolchain.h"

#include "gcctoolchain.h"
#include "msvcparser.h"
#include "projectexplorer.h"
#include "projectexplorerconstants.h"
#include "projectexplorersettings.h"
#include "taskhub.h"
#include "toolchainmanager.h"

#include <coreplugin/icore.h>

#include <utils/algorithm.h>
#include <utils/hostosinfo.h>
#include <utils/optional.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <utils/synchronousprocess.h>
#include <utils/runextensions.h>
#include <utils/temporarydirectory.h>
#include <utils/pathchooser.h>
#include <utils/winutils.h>

#include <QDir>
#include <QFileInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QProcess>
#include <QRegularExpression>
#include <QSettings>
#include <QVector>
#include <QVersionNumber>

#include <QLabel>
#include <QComboBox>
#include <QFormLayout>

using namespace Utils;

#define KEY_ROOT "ProjectExplorer.MsvcToolChain."
static const char varsBatKeyC[] = KEY_ROOT "VarsBat";
static const char varsBatArgKeyC[] = KEY_ROOT "VarsBatArg";
static const char supportedAbiKeyC[] = KEY_ROOT "SupportedAbi";
static const char supportedAbisKeyC[] = KEY_ROOT "SupportedAbis";
static const char environModsKeyC[] = KEY_ROOT "environmentModifications";

enum { debug = 0 };

namespace ProjectExplorer {
namespace Internal {

// --------------------------------------------------------------------------
// Helpers:
// --------------------------------------------------------------------------

static QThreadPool *envModThreadPool()
{
    static QThreadPool *pool = nullptr;
    if (!pool) {
        pool = new QThreadPool(ProjectExplorerPlugin::instance());
        pool->setMaxThreadCount(1);
    }
    return pool;
}

struct MsvcPlatform
{
    MsvcToolChain::Platform platform;
    const char *name;
    const char *prefix; // VS up until 14.0 (MSVC2015)
    const char *bat;
};

const MsvcPlatform platforms[]
    = {{MsvcToolChain::x86, "x86", "/bin", "vcvars32.bat"},
       {MsvcToolChain::amd64, "amd64", "/bin/amd64", "vcvars64.bat"},
       {MsvcToolChain::x86_amd64, "x86_amd64", "/bin/x86_amd64", "vcvarsx86_amd64.bat"},
       {MsvcToolChain::ia64, "ia64", "/bin/ia64", "vcvars64.bat"},
       {MsvcToolChain::x86_ia64, "x86_ia64", "/bin/x86_ia64", "vcvarsx86_ia64.bat"},
       {MsvcToolChain::arm, "arm", "/bin/arm", "vcvarsarm.bat"},
       {MsvcToolChain::x86_arm, "x86_arm", "/bin/x86_arm", "vcvarsx86_arm.bat"},
       {MsvcToolChain::amd64_arm, "amd64_arm", "/bin/amd64_arm", "vcvarsamd64_arm.bat"},
       {MsvcToolChain::amd64_x86, "amd64_x86", "/bin/amd64_x86", "vcvarsamd64_x86.bat"}};

static QList<const MsvcToolChain *> g_availableMsvcToolchains;

static const MsvcPlatform *platformEntry(MsvcToolChain::Platform t)
{
    for (const MsvcPlatform &p : platforms) {
        if (p.platform == t)
            return &p;
    }
    return nullptr;
}

static QString platformName(MsvcToolChain::Platform t)
{
    if (const MsvcPlatform *p = platformEntry(t))
        return QLatin1String(p->name);
    return QString();
}

static bool hostSupportsPlatform(MsvcToolChain::Platform platform)
{
    switch (Utils::HostOsInfo::hostArchitecture()) {
    case Utils::HostOsInfo::HostArchitectureAMD64:
        if (platform == MsvcToolChain::amd64 || platform == MsvcToolChain::amd64_arm
            || platform == MsvcToolChain::amd64_x86)
            return true;
        Q_FALLTHROUGH(); // all x86 toolchains are also working on an amd64 host
    case Utils::HostOsInfo::HostArchitectureX86:
        return platform == MsvcToolChain::x86 || platform == MsvcToolChain::x86_amd64
               || platform == MsvcToolChain::x86_ia64 || platform == MsvcToolChain::x86_arm;
    case Utils::HostOsInfo::HostArchitectureArm:
        return platform == MsvcToolChain::arm;
    case Utils::HostOsInfo::HostArchitectureItanium:
        return platform == MsvcToolChain::ia64;
    default:
        return false;
    }
}

static QString fixRegistryPath(const QString &path)
{
    QString result = QDir::fromNativeSeparators(path);
    if (result.endsWith(QLatin1Char('/')))
        result.chop(1);
    return result;
}

struct VisualStudioInstallation
{
    QString vsName;
    QVersionNumber version;
    QString path;       // Main installation path
    QString vcVarsPath; // Path under which the various vc..bat are to be found
    QString vcVarsAll;
};

QDebug operator<<(QDebug d, const VisualStudioInstallation &i)
{
    QDebugStateSaver saver(d);
    d.noquote();
    d.nospace();
    d << "VisualStudioInstallation(\"" << i.vsName << "\", v=" << i.version << ", path=\""
      << QDir::toNativeSeparators(i.path) << "\", vcVarsPath=\""
      << QDir::toNativeSeparators(i.vcVarsPath) << "\", vcVarsAll=\""
      << QDir::toNativeSeparators(i.vcVarsAll) << "\")";
    return d;
}

static QString windowsProgramFilesDir()
{
#ifdef Q_OS_WIN64
    const char programFilesC[] = "ProgramFiles(x86)";
#else
    const char programFilesC[] = "ProgramFiles";
#endif
    return QDir::fromNativeSeparators(QFile::decodeName(qgetenv(programFilesC)));
}

static Utils::optional<VisualStudioInstallation> installationFromPathAndVersion(
    const QString &installationPath, const QVersionNumber &version)
{
    QString vcVarsPath = QDir::fromNativeSeparators(installationPath);
    if (!vcVarsPath.endsWith('/'))
        vcVarsPath += '/';
    if (version.majorVersion() > 14)
        vcVarsPath += QStringLiteral("VC/Auxiliary/Build");
    else
        vcVarsPath += QStringLiteral("VC");

    const QString vcVarsAllPath = vcVarsPath + QStringLiteral("/vcvarsall.bat");
    if (!QFileInfo(vcVarsAllPath).isFile()) {
        qWarning().noquote() << "Unable to find MSVC setup script "
                             << QDir::toNativeSeparators(vcVarsPath) << " in version " << version;
        return Utils::nullopt;
    }

    const QString versionString = version.toString();
    VisualStudioInstallation installation;
    installation.path = installationPath;
    installation.version = version;
    installation.vsName = versionString;
    installation.vcVarsPath = vcVarsPath;
    installation.vcVarsAll = vcVarsAllPath;
    return installation;
}

// Detect build tools introduced with MSVC2017
static Utils::optional<VisualStudioInstallation> detectCppBuildTools2017()
{
    const QString installPath = windowsProgramFilesDir()
                                + "/Microsoft Visual Studio/2017/BuildTools";
    const QString vcVarsPath = installPath + "/VC/Auxiliary/Build";
    const QString vcVarsAllPath = vcVarsPath + "/vcvarsall.bat";

    if (!QFileInfo::exists(vcVarsAllPath))
        return Utils::nullopt;

    VisualStudioInstallation installation;
    installation.path = installPath;
    installation.vcVarsAll = vcVarsAllPath;
    installation.vcVarsPath = vcVarsPath;
    installation.version = QVersionNumber(15);
    installation.vsName = "15.0";

    return installation;
}

static QVector<VisualStudioInstallation> detectVisualStudioFromVsWhere(const QString &vswhere)
{
    QVector<VisualStudioInstallation> installations;
    Utils::SynchronousProcess vsWhereProcess;
    const int timeoutS = 5;
    vsWhereProcess.setTimeoutS(timeoutS);
    const QStringList
        arguments{"-products", "*", "-prerelease", "-legacy", "-format", "json", "-utf8"};
    Utils::SynchronousProcessResponse response = vsWhereProcess.runBlocking(vswhere, arguments);
    switch (response.result) {
    case Utils::SynchronousProcessResponse::Finished:
        break;
    case Utils::SynchronousProcessResponse::StartFailed:
        qWarning().noquote() << QDir::toNativeSeparators(vswhere) << "could not be started.";
        return installations;
    case Utils::SynchronousProcessResponse::FinishedError:
        qWarning().noquote().nospace() << QDir::toNativeSeparators(vswhere)
                                       << " finished with exit code "
                                       << response.exitCode << ".";
        return installations;
    case Utils::SynchronousProcessResponse::TerminatedAbnormally:
        qWarning().noquote().nospace()
            << QDir::toNativeSeparators(vswhere) << " crashed. Exit code: " << response.exitCode;
        return installations;
    case Utils::SynchronousProcessResponse::Hang:
        qWarning().noquote() << QDir::toNativeSeparators(vswhere) << "did not finish in" << timeoutS
                             << "seconds.";
        return installations;
    }

    QByteArray output = response.stdOut().toUtf8();
    QJsonParseError error;
    const QJsonDocument doc = QJsonDocument::fromJson(output, &error);
    if (error.error != QJsonParseError::NoError || doc.isNull()) {
        qWarning() << "Could not parse json document from vswhere output.";
        return installations;
    }

    const QJsonArray versions = doc.array();
    if (versions.isEmpty()) {
        qWarning() << "Could not detect any versions from vswhere output.";
        return installations;
    }

    for (const QJsonValue &vsVersion : versions) {
        const QJsonObject vsVersionObj = vsVersion.toObject();
        if (vsVersionObj.isEmpty()) {
            qWarning() << "Could not obtain object from vswhere version";
            continue;
        }

        QJsonValue value = vsVersionObj.value("installationVersion");
        if (value.isUndefined()) {
            qWarning() << "Could not obtain VS version from json output";
            continue;
        }
        const QString versionString = value.toString();
        QVersionNumber version = QVersionNumber::fromString(versionString);
        value = vsVersionObj.value("installationPath");
        if (value.isUndefined()) {
            qWarning() << "Could not obtain VS installation path from json output";
            continue;
        }
        const QString installationPath = value.toString();
        Utils::optional<VisualStudioInstallation> installation
            = installationFromPathAndVersion(installationPath, version);

        if (installation)
            installations.append(*installation);
    }
    return installations;
}

static QVector<VisualStudioInstallation> detectVisualStudioFromRegistry()
{
    QVector<VisualStudioInstallation> result;
#ifdef Q_OS_WIN64
    const QString keyRoot = QStringLiteral(
        "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\");
#else
    const QString keyRoot = QStringLiteral(
        "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\");
#endif
    QSettings vsRegistry(keyRoot + QStringLiteral("VS7"), QSettings::NativeFormat);
    QScopedPointer<QSettings> vcRegistry;
    foreach (const QString &vsName, vsRegistry.allKeys()) {
        const QVersionNumber version = QVersionNumber::fromString(vsName);
        if (!version.isNull()) {
            const QString installationPath = fixRegistryPath(vsRegistry.value(vsName).toString());

            Utils::optional<VisualStudioInstallation> installation
                = installationFromPathAndVersion(installationPath, version);
            if (installation)
                result.append(*installation);
        }
    }

    // Detect VS 2017 Build Tools
    auto installation = detectCppBuildTools2017();
    if (installation)
        result.append(*installation);

    return result;
}

static QVector<VisualStudioInstallation> detectVisualStudio()
{
    const QString vswhere = windowsProgramFilesDir()
                            + "/Microsoft Visual Studio/Installer/vswhere.exe";
    if (QFileInfo::exists(vswhere)) {
        const QVector<VisualStudioInstallation> installations = detectVisualStudioFromVsWhere(
            vswhere);
        if (!installations.isEmpty())
            return installations;
    }

    return detectVisualStudioFromRegistry();
}

static unsigned char wordWidthForPlatform(MsvcToolChain::Platform platform)
{
    switch (platform) {
    case ProjectExplorer::Internal::MsvcToolChain::x86:
    case ProjectExplorer::Internal::MsvcToolChain::arm:
    case ProjectExplorer::Internal::MsvcToolChain::x86_arm:
    case ProjectExplorer::Internal::MsvcToolChain::amd64_arm:
    case ProjectExplorer::Internal::MsvcToolChain::amd64_x86:
        return 32;
    case ProjectExplorer::Internal::MsvcToolChain::amd64:
    case ProjectExplorer::Internal::MsvcToolChain::x86_amd64:
    case ProjectExplorer::Internal::MsvcToolChain::ia64:
    case ProjectExplorer::Internal::MsvcToolChain::x86_ia64:
        return 64;
    }

    return 0;
}

static Abi::Architecture archForPlatform(MsvcToolChain::Platform platform)
{
    switch (platform) {
    case ProjectExplorer::Internal::MsvcToolChain::x86:
    case ProjectExplorer::Internal::MsvcToolChain::amd64:
    case ProjectExplorer::Internal::MsvcToolChain::x86_amd64:
    case ProjectExplorer::Internal::MsvcToolChain::amd64_x86:
        return Abi::X86Architecture;
    case ProjectExplorer::Internal::MsvcToolChain::arm:
    case ProjectExplorer::Internal::MsvcToolChain::x86_arm:
    case ProjectExplorer::Internal::MsvcToolChain::amd64_arm:
        return Abi::ArmArchitecture;
    case ProjectExplorer::Internal::MsvcToolChain::ia64:
    case ProjectExplorer::Internal::MsvcToolChain::x86_ia64:
        return Abi::ItaniumArchitecture;
    }

    return Abi::UnknownArchitecture;
}

static Abi findAbiOfMsvc(MsvcToolChain::Type type,
                         MsvcToolChain::Platform platform,
                         const QString &version)
{
    Abi::OSFlavor flavor = Abi::UnknownFlavor;

    QString msvcVersionString = version;
    if (type == MsvcToolChain::WindowsSDK) {
        if (version == QLatin1String("v7.0") || version.startsWith(QLatin1String("6.")))
            msvcVersionString = QLatin1String("9.0");
        else if (version == QLatin1String("v7.0A") || version == QLatin1String("v7.1"))
            msvcVersionString = QLatin1String("10.0");
    }
    if (msvcVersionString.startsWith(QLatin1String("16.")))
        flavor = Abi::WindowsMsvc2019Flavor;
    else if (msvcVersionString.startsWith(QLatin1String("15.")))
        flavor = Abi::WindowsMsvc2017Flavor;
    else if (msvcVersionString.startsWith(QLatin1String("14.")))
        flavor = Abi::WindowsMsvc2015Flavor;
    else if (msvcVersionString.startsWith(QLatin1String("12.")))
        flavor = Abi::WindowsMsvc2013Flavor;
    else if (msvcVersionString.startsWith(QLatin1String("11.")))
        flavor = Abi::WindowsMsvc2012Flavor;
    else if (msvcVersionString.startsWith(QLatin1String("10.")))
        flavor = Abi::WindowsMsvc2010Flavor;
    else if (msvcVersionString.startsWith(QLatin1String("9.")))
        flavor = Abi::WindowsMsvc2008Flavor;
    else
        flavor = Abi::WindowsMsvc2005Flavor;
    const Abi result = Abi(archForPlatform(platform), Abi::WindowsOS, flavor, Abi::PEFormat,
                           wordWidthForPlatform(platform));
    if (!result.isValid())
        qWarning("Unable to completely determine the ABI of MSVC version %s (%s).",
                 qPrintable(version),
                 qPrintable(result.toString()));
    return result;
}

static QString generateDisplayName(const QString &name,
                                   MsvcToolChain::Type t,
                                   MsvcToolChain::Platform p)
{
    if (t == MsvcToolChain::WindowsSDK) {
        QString sdkName = name;
        sdkName += QString::fromLatin1(" (%1)").arg(platformName(p));
        return sdkName;
    }
    // Comes as "9.0" from the registry
    QString vcName = QLatin1String("Microsoft Visual C++ Compiler ");
    vcName += name;
    vcName += QString::fromLatin1(" (%1)").arg(platformName(p));
    return vcName;
}

static QByteArray msvcCompilationDefine(const char *def)
{
    const QByteArray macro(def);
    return "#if defined(" + macro + ")\n__PPOUT__(" + macro + ")\n#endif\n";
}

static QByteArray msvcCompilationFile()
{
    static const char *macros[] = {"_ATL_VER",
                                   "__ATOM__",
                                   "__AVX__",
                                   "__AVX2__",
                                   "_CHAR_UNSIGNED",
                                   "__CLR_VER",
                                   "_CMMN_INTRIN_FUNC",
                                   "_CONTROL_FLOW_GUARD",
                                   "__cplusplus",
                                   "__cplusplus_cli",
                                   "__cplusplus_winrt",
                                   "_CPPLIB_VER",
                                   "_CPPRTTI",
                                   "_CPPUNWIND",
                                   "_DEBUG",
                                   "_DLL",
                                   "_INTEGRAL_MAX_BITS",
                                   "__INTELLISENSE__",
                                   "_ISO_VOLATILE",
                                   "_KERNEL_MODE",
                                   "_M_AAMD64",
                                   "_M_ALPHA",
                                   "_M_AMD64",
                                   "_MANAGED",
                                   "_M_ARM",
                                   "_M_ARM64",
                                   "_M_ARM_ARMV7VE",
                                   "_M_ARM_FP",
                                   "_M_ARM_NT",
                                   "_M_ARMT",
                                   "_M_CEE",
                                   "_M_CEE_PURE",
                                   "_M_CEE_SAFE",
                                   "_MFC_VER",
                                   "_M_FP_EXCEPT",
                                   "_M_FP_FAST",
                                   "_M_FP_PRECISE",
                                   "_M_FP_STRICT",
                                   "_M_IA64",
                                   "_M_IX86",
                                   "_M_IX86_FP",
                                   "_M_MPPC",
                                   "_M_MRX000",
                                   "_M_PPC",
                                   "_MSC_BUILD",
                                   "_MSC_EXTENSIONS",
                                   "_MSC_FULL_VER",
                                   "_MSC_VER",
                                   "_MSVC_LANG",
                                   "__MSVC_RUNTIME_CHECKS",
                                   "_MT",
                                   "_M_THUMB",
                                   "_M_X64",
                                   "_NATIVE_WCHAR_T_DEFINED",
                                   "_OPENMP",
                                   "_PREFAST_",
                                   "__STDC__",
                                   "__STDC_HOSTED__",
                                   "__STDCPP_THREADS__",
                                   "_VC_NODEFAULTLIB",
                                   "_WCHAR_T_DEFINED",
                                   "_WIN32",
                                   "_WIN32_WCE",
                                   "_WIN64",
                                   "_WINRT_DLL",
                                   "_Wp64",
                                   nullptr};
    QByteArray file = "#define __PPOUT__(x) V##x=x\n\n";
    for (int i = 0; macros[i] != nullptr; ++i)
        file += msvcCompilationDefine(macros[i]);
    file += "\nvoid main(){}\n\n";
    return file;
}

// Run MSVC 'cl' compiler to obtain #defines.
// This function must be thread-safe!
//
// Some notes regarding the used approach:
//
// It seems that there is no reliable way to get all the
// predefined macros for a cl invocation. The following two
// approaches are unfortunately limited since both lead to an
// incomplete list of actually predefined macros and come with
// other problems, too.
//
// 1) Maintain a list of predefined macros from the official
//    documentation (for MSVC2015, e.g. [1]). Feed cl with a
//    temporary file that queries the values of those macros.
//
//    Problems:
//     * Maintaining that list.
//     * The documentation is incomplete, we do not get all
//       predefined macros. E.g. the cl from MSVC2015, set up
//       with "vcvars.bat x86_arm", predefines among others
//       _M_ARMT, but that's not reflected in the
//       documentation.
//
// 2) Run cl with the undocumented options /B1 and /Bx, as
//    described in [2].
//
//    Note: With qmake from Qt >= 5.8 it's possible to print
//    the macros formatted as preprocessor code in an easy to
//    read/compare/diff way:
//
//      > cl /nologo /c /TC /B1 qmake NUL
//      > cl /nologo /c /TP /Bx qmake NUL
//
//    Problems:
//     * Using undocumented options.
//     * Resulting macros are incomplete.
//       For example, the nowadays default option /Zc:wchar_t
//       predefines _WCHAR_T_DEFINED, but this is not reflected
//       with this approach.
//
//       To work around this we would need extra cl invocations
//       to get the actual values of the missing macros
//       (approach 1).
//
// Currently we combine both approaches in this way:
//  * As base, maintain the list from the documentation and
//    update it once a new MSVC version is released.
//  * Enrich it with macros that we discover with approach 2
//    once a new MSVC version is released.
//  * Enrich it further with macros that are not covered with
//    the above points.
//
// TODO: Update the predefined macros for MSVC 2017 once the
//       page exists.
//
// [1] https://msdn.microsoft.com/en-us/library/b0084kay.aspx
// [2] http://stackoverflow.com/questions/3665537/how-to-find-out-cl-exes-built-in-macros
Macros MsvcToolChain::msvcPredefinedMacros(const QStringList &cxxflags,
                                           const Utils::Environment &env) const
{
    Macros predefinedMacros;

    QStringList toProcess;
    for (const QString &arg : cxxflags) {
        if (arg.startsWith(QLatin1String("/D"))) {
            const QString define = arg.mid(2);
            predefinedMacros.append(Macro::fromKeyValue(define));
        } else if (arg.startsWith(QLatin1String("/U"))) {
            predefinedMacros.append(
                {arg.mid(2).toLocal8Bit(), ProjectExplorer::MacroType::Undefine});
        } else {
            toProcess.append(arg);
        }
    }

    Utils::TempFileSaver saver(Utils::TemporaryDirectory::masterDirectoryPath()
                               + "/envtestXXXXXX.cpp");
    saver.write(msvcCompilationFile());
    if (!saver.finalize()) {
        qWarning("%s: %s", Q_FUNC_INFO, qPrintable(saver.errorString()));
        return predefinedMacros;
    }
    Utils::SynchronousProcess cpp;
    cpp.setEnvironment(env.toStringList());
    cpp.setWorkingDirectory(Utils::TemporaryDirectory::masterDirectoryPath());
    QStringList arguments;
    const Utils::FileName binary = env.searchInPath(QLatin1String("cl.exe"));
    if (binary.isEmpty()) {
        qWarning("%s: The compiler binary cl.exe could not be found in the path.", Q_FUNC_INFO);
        return predefinedMacros;
    }

    if (language() == ProjectExplorer::Constants::C_LANGUAGE_ID)
        arguments << QLatin1String("/TC");
    arguments << toProcess << QLatin1String("/EP") << QDir::toNativeSeparators(saver.fileName());
    Utils::SynchronousProcessResponse response = cpp.runBlocking(binary.toString(), arguments);
    if (response.result != Utils::SynchronousProcessResponse::Finished || response.exitCode != 0)
        return predefinedMacros;

    const QStringList output = Utils::filtered(response.stdOut().split('\n'),
                                               [](const QString &s) { return s.startsWith('V'); });
    for (const QString &line : output)
        predefinedMacros.append(Macro::fromKeyValue(line.mid(1)));
    return predefinedMacros;
}

//
// We want to detect the language version based on the predefined macros.
// Unfortunately MSVC does not conform to standard when it comes to the predefined
// __cplusplus macro - it reports "199711L", even for newer language versions.
//
// However:
//   * For >= Visual Studio 2015 Update 3 predefines _MSVC_LANG which has the proper value
//     of __cplusplus.
//     See https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=vs-2017
//   * For >= Visual Studio 2017 Version 15.7 __cplusplus is correct once /Zc:__cplusplus
//     is provided on the command line. Then __cplusplus == _MSVC_LANG.
//     See https://blogs.msdn.microsoft.com/vcblog/2018/04/09/msvc-now-correctly-reports-__cplusplus
//
// We rely on _MSVC_LANG if possible, otherwise on some hard coded language versions
// depending on _MSC_VER.
//
// For _MSV_VER values, see https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=vs-2017.
//
Utils::LanguageVersion MsvcToolChain::msvcLanguageVersion(const QStringList & /*cxxflags*/,
                                                          const Core::Id &language,
                                                          const Macros &macros) const
{
    using Utils::LanguageVersion;

    int mscVer = -1;
    QByteArray msvcLang;
    for (const ProjectExplorer::Macro &macro : macros) {
        if (macro.key == "_MSVC_LANG")
            msvcLang = macro.value;
        if (macro.key == "_MSC_VER")
            mscVer = macro.value.toInt(nullptr);
    }
    QTC_CHECK(mscVer > 0);

    if (language == Constants::CXX_LANGUAGE_ID) {
        if (!msvcLang.isEmpty()) // >= Visual Studio 2015 Update 3
            return ToolChain::cxxLanguageVersion(msvcLang);
        if (mscVer >= 1800) // >= Visual Studio 2013 (12.0)
            return LanguageVersion::CXX14;
        if (mscVer >= 1600) // >= Visual Studio 2010 (10.0)
            return LanguageVersion::CXX11;
        return LanguageVersion::CXX98;
    } else if (language == Constants::C_LANGUAGE_ID) {
        if (mscVer >= 1910) // >= Visual Studio 2017 RTW (15.0)
            return LanguageVersion::C11;
        return LanguageVersion::C99;
    } else {
        QTC_CHECK(false && "Unexpected toolchain language, assuming latest C++ we support.");
        return LanguageVersion::LatestCxx;
    }
}

// Windows: Expand the delayed evaluation references returned by the
// SDK setup scripts: "PATH=!Path!;foo". Some values might expand
// to empty and should not be added
static QString winExpandDelayedEnvReferences(QString in, const Utils::Environment &env)
{
    const QChar exclamationMark = QLatin1Char('!');
    for (int pos = 0; pos < in.size();) {
        // Replace "!REF!" by its value in process environment
        pos = in.indexOf(exclamationMark, pos);
        if (pos == -1)
            break;
        const int nextPos = in.indexOf(exclamationMark, pos + 1);
        if (nextPos == -1)
            break;
        const QString var = in.mid(pos + 1, nextPos - pos - 1);
        const QString replacement = env.value(var.toUpper());
        in.replace(pos, nextPos + 1 - pos, replacement);
        pos += replacement.size();
    }
    return in;
}

void MsvcToolChain::environmentModifications(
    QFutureInterface<MsvcToolChain::GenerateEnvResult> &future,
    QString vcvarsBat,
    QString varsBatArg)
{
    const Utils::Environment inEnv = Utils::Environment::systemEnvironment();
    Utils::Environment outEnv;
    QMap<QString, QString> envPairs;
    QList<Utils::EnvironmentItem> diff;
    Utils::optional<QString> error = generateEnvironmentSettings(inEnv,
                                                                 vcvarsBat,
                                                                 varsBatArg,
                                                                 envPairs);
    if (!error) {
        // Now loop through and process them
        for (auto envIter = envPairs.cbegin(), end = envPairs.cend(); envIter != end; ++envIter) {
            const QString expandedValue = winExpandDelayedEnvReferences(envIter.value(), inEnv);
            if (!expandedValue.isEmpty())
                outEnv.set(envIter.key(), expandedValue);
        }

        if (debug) {
            const QStringList newVars = outEnv.toStringList();
            const QStringList oldVars = inEnv.toStringList();
            QDebug nsp = qDebug().nospace();
            foreach (const QString &n, newVars) {
                if (!oldVars.contains(n))
                    nsp << n << '\n';
            }
        }

        diff = inEnv.diff(outEnv, true);
        for (int i = diff.size() - 1; i >= 0; --i) {
            if (diff.at(i).name.startsWith(QLatin1Char('='))) { // Exclude "=C:", "=EXITCODE"
                diff.removeAt(i);
            }
        }
    }

    future.reportResult({error, diff});
}

void MsvcToolChain::initEnvModWatcher(const QFuture<GenerateEnvResult> &future)
{
    QObject::connect(&m_envModWatcher, &QFutureWatcher<GenerateEnvResult>::resultReadyAt, [&]() {
        const GenerateEnvResult &result = m_envModWatcher.result();
        if (result.error) {
            const QString &errorMessage = *result.error;
            if (!errorMessage.isEmpty())
                TaskHub::addTask(Task::Error, errorMessage, Constants::TASK_CATEGORY_COMPILE);
        } else {
            updateEnvironmentModifications(result.environmentItems);
        }
    });
    m_envModWatcher.setFuture(future);
}

void MsvcToolChain::updateEnvironmentModifications(QList<Utils::EnvironmentItem> modifications)
{
    Utils::EnvironmentItem::sort(&modifications);
    if (modifications != m_environmentModifications) {
        m_environmentModifications = modifications;
        rescanForCompiler();
        toolChainUpdated();
    }
}

void MsvcToolChain::detectInstalledAbis()
{
    static QMap<QString, QList<Abi>> abiCache;
    const QString vcVarsBase
            = QDir::fromNativeSeparators(m_vcvarsBat).left(m_vcvarsBat.lastIndexOf('/'));
    if (abiCache.contains(vcVarsBase)) {
        m_supportedAbis = abiCache.value(vcVarsBase);
        return;
    }

    QTC_ASSERT(m_supportedAbis.isEmpty(), return);
    const Abi baseAbi = targetAbi();
    for (MsvcPlatform platform : platforms) {
        bool toolchainInstalled = false;
        QString perhapsVcVarsPath = vcVarsBase + QLatin1Char('/') + QLatin1String(platform.bat);
        const Platform p = platform.platform;
        if (QFileInfo(perhapsVcVarsPath).isFile()) {
            toolchainInstalled = true;
        } else {
            // MSVC 2015 and below had various versions of vcvars scripts in subfolders. Try these
            // as fallbacks.
            perhapsVcVarsPath = vcVarsBase + platform.prefix + QLatin1Char('/')
                    + QLatin1String(platform.bat);
            toolchainInstalled = QFileInfo(perhapsVcVarsPath).isFile();
        }
        if (hostSupportsPlatform(platform.platform) && toolchainInstalled) {
            Abi newAbi(archForPlatform(p), baseAbi.os(), baseAbi.osFlavor(), baseAbi.binaryFormat(),
                       wordWidthForPlatform(p));
            if (!m_supportedAbis.contains(newAbi))
                m_supportedAbis.append(newAbi);
        }
    }
    abiCache.insert(vcVarsBase, m_supportedAbis);
}

Utils::Environment MsvcToolChain::readEnvironmentSetting(const Utils::Environment &env) const
{
    Utils::Environment resultEnv = env;
    if (m_environmentModifications.isEmpty()) {
        m_envModWatcher.waitForFinished();
        if (m_envModWatcher.future().isFinished() && !m_envModWatcher.future().isCanceled()) {
            const GenerateEnvResult &result = m_envModWatcher.result();
            if (result.error) {
                const QString &errorMessage = *result.error;
                if (!errorMessage.isEmpty())
                    TaskHub::addTask(Task::Error, errorMessage, Constants::TASK_CATEGORY_COMPILE);
            } else {
                resultEnv.modify(result.environmentItems);
            }
        }
    } else {
        resultEnv.modify(m_environmentModifications);
    }
    return resultEnv;
}

// --------------------------------------------------------------------------
// MsvcToolChain
// --------------------------------------------------------------------------

MsvcToolChain::MsvcToolChain(const QString &name,
                             const Abi &abi,
                             const QString &varsBat,
                             const QString &varsBatArg)
    : MsvcToolChain(Constants::MSVC_TOOLCHAIN_TYPEID, name, abi, varsBat, varsBatArg)
{}

static void addToAvailableMsvcToolchains(const MsvcToolChain *toolchain)
{
    if (toolchain->typeId() != Constants::MSVC_TOOLCHAIN_TYPEID)
        return;

    if (!g_availableMsvcToolchains.contains(toolchain))
        g_availableMsvcToolchains.push_back(toolchain);
}

MsvcToolChain::MsvcToolChain(Core::Id typeId,
                             const QString &name,
                             const Abi &abi,
                             const QString &varsBat,
                             const QString &varsBatArg)
    : ToolChain(typeId)
    , m_headerPathsMutex(new QMutex)
    , m_lastEnvironment(Utils::Environment::systemEnvironment())
    , m_abi(abi)
    , m_vcvarsBat(varsBat)
    , m_varsBatArg(varsBatArg)
{
    detectInstalledAbis();
    addToAvailableMsvcToolchains(this);

    initEnvModWatcher(Utils::runAsync(envModThreadPool(),
                                      &MsvcToolChain::environmentModifications,
                                      varsBat,
                                      varsBatArg));

    Q_ASSERT(!name.isEmpty());

    setDisplayName(name);
}

MsvcToolChain::MsvcToolChain(Core::Id typeId)
    : ToolChain(typeId)
{}

void MsvcToolChain::inferWarningsForLevel(int warningLevel, WarningFlags &flags)
{
    // reset all except unrelated flag
    flags = flags & WarningFlags::AsErrors;

    if (warningLevel >= 1)
        flags |= WarningFlags(WarningFlags::Default | WarningFlags::IgnoredQualfiers
                              | WarningFlags::HiddenLocals | WarningFlags::UnknownPragma);
    if (warningLevel >= 2)
        flags |= WarningFlags::All;
    if (warningLevel >= 3) {
        flags |= WarningFlags(WarningFlags::Extra | WarningFlags::NonVirtualDestructor
                              | WarningFlags::SignedComparison | WarningFlags::UnusedLocals
                              | WarningFlags::Deprecated);
    }
    if (warningLevel >= 4)
        flags |= WarningFlags::UnusedParams;
}

MsvcToolChain::MsvcToolChain()
    : MsvcToolChain(Constants::MSVC_TOOLCHAIN_TYPEID)
{}

MsvcToolChain::~MsvcToolChain()
{
    g_availableMsvcToolchains.removeOne(this);
    delete m_headerPathsMutex;
}

Abi MsvcToolChain::targetAbi() const
{
    return m_abi;
}

QList<Abi> MsvcToolChain::supportedAbis() const
{
    return m_supportedAbis;
}

void MsvcToolChain::setTargetAbi(const Abi &abi)
{
    if (m_abi == abi)
        return;

    m_abi = abi;
}

bool MsvcToolChain::isValid() const
{
    if (m_vcvarsBat.isEmpty())
        return false;
    QFileInfo fi(m_vcvarsBat);
    return fi.isFile() && fi.isExecutable();
}

QString MsvcToolChain::originalTargetTriple() const
{
    return m_abi.wordWidth() == 64 ? QLatin1String("x86_64-pc-windows-msvc")
                                   : QLatin1String("i686-pc-windows-msvc");
}

QString MsvcToolChain::typeDisplayName() const
{
    return MsvcToolChainFactory::tr("MSVC");
}

Utils::FileNameList MsvcToolChain::suggestedMkspecList() const
{
    Utils::FileNameList result;
    result << Utils::FileName::fromLatin1("win32-msvc"); // Common MSVC mkspec introduced in 5.8.1
    switch (m_abi.osFlavor()) {
    case Abi::WindowsMsvc2005Flavor:
        result << Utils::FileName::fromLatin1("win32-msvc2005");
        break;
    case Abi::WindowsMsvc2008Flavor:
        result << Utils::FileName::fromLatin1("win32-msvc2008");
        break;
    case Abi::WindowsMsvc2010Flavor:
        result << Utils::FileName::fromLatin1("win32-msvc2010");
        break;
    case Abi::WindowsMsvc2012Flavor:
        result << Utils::FileName::fromLatin1("win32-msvc2012")
               << Utils::FileName::fromLatin1("win32-msvc2010");
        break;
    case Abi::WindowsMsvc2013Flavor:
        result << Utils::FileName::fromLatin1("win32-msvc2013")
               << Utils::FileName::fromLatin1("winphone-arm-msvc2013")
               << Utils::FileName::fromLatin1("winphone-x86-msvc2013")
               << Utils::FileName::fromLatin1("winrt-arm-msvc2013")
               << Utils::FileName::fromLatin1("winrt-x86-msvc2013")
               << Utils::FileName::fromLatin1("winrt-x64-msvc2013")
               << Utils::FileName::fromLatin1("win32-msvc2012")
               << Utils::FileName::fromLatin1("win32-msvc2010");
        break;
    case Abi::WindowsMsvc2015Flavor:
        result << Utils::FileName::fromLatin1("win32-msvc2015")
               << Utils::FileName::fromLatin1("winphone-arm-msvc2015")
               << Utils::FileName::fromLatin1("winphone-x86-msvc2015")
               << Utils::FileName::fromLatin1("winrt-arm-msvc2015")
               << Utils::FileName::fromLatin1("winrt-x86-msvc2015")
               << Utils::FileName::fromLatin1("winrt-x64-msvc2015");
        break;
    case Abi::WindowsMsvc2017Flavor:
        result << Utils::FileName::fromLatin1("win32-msvc2017")
               << Utils::FileName::fromLatin1("winrt-arm-msvc2017")
               << Utils::FileName::fromLatin1("winrt-x86-msvc2017")
               << Utils::FileName::fromLatin1("winrt-x64-msvc2017");
        break;
    case Abi::WindowsMsvc2019Flavor:
        result << Utils::FileName::fromLatin1("win32-msvc2019")
               << Utils::FileName::fromLatin1("winrt-arm-msvc2019")
               << Utils::FileName::fromLatin1("winrt-x86-msvc2019")
               << Utils::FileName::fromLatin1("winrt-x64-msvc2019");
        break;
    default:
        result.clear();
        break;
    }
    return result;
}

QVariantMap MsvcToolChain::toMap() const
{
    QVariantMap data = ToolChain::toMap();
    data.insert(QLatin1String(varsBatKeyC), m_vcvarsBat);
    if (!m_varsBatArg.isEmpty())
        data.insert(QLatin1String(varsBatArgKeyC), m_varsBatArg);
    data.insert(QLatin1String(supportedAbiKeyC), m_abi.toString());
    const QStringList abiList = Utils::transform(m_supportedAbis, &Abi::toString);
    data.insert(supportedAbisKeyC, abiList);
    Utils::EnvironmentItem::sort(&m_environmentModifications);
    data.insert(QLatin1String(environModsKeyC),
                Utils::EnvironmentItem::toVariantList(m_environmentModifications));
    return data;
}

bool MsvcToolChain::fromMap(const QVariantMap &data)
{
    if (!ToolChain::fromMap(data))
        return false;
    m_vcvarsBat = QDir::fromNativeSeparators(data.value(QLatin1String(varsBatKeyC)).toString());
    m_varsBatArg = data.value(QLatin1String(varsBatArgKeyC)).toString();
    detectInstalledAbis();
    addToAvailableMsvcToolchains(this);

    const QString abiString = data.value(QLatin1String(supportedAbiKeyC)).toString();
    m_abi = Abi::fromString(abiString);
    const QStringList abiList = data.value(supportedAbisKeyC).toStringList();
    m_supportedAbis.clear();
    for (const QString &a : abiList) {
        Abi abi = Abi::fromString(a);
        if (!abi.isValid())
            continue;
        m_supportedAbis.append(abi);
    }
    m_environmentModifications = Utils::EnvironmentItem::itemsFromVariantList(
        data.value(QLatin1String(environModsKeyC)).toList());
    rescanForCompiler();

    initEnvModWatcher(Utils::runAsync(envModThreadPool(),
                                      &MsvcToolChain::environmentModifications,
                                      m_vcvarsBat,
                                      m_varsBatArg));

    return !m_vcvarsBat.isEmpty() && m_abi.isValid();
}

std::unique_ptr<ToolChainConfigWidget> MsvcToolChain::createConfigurationWidget()
{
    return std::make_unique<MsvcToolChainConfigWidget>(this);
}

bool static hasFlagEffectOnMacros(const QString &flag)
{
    if (flag.startsWith("-") || flag.startsWith("/")) {
        const QString f = flag.mid(1);
        if (f.startsWith("I"))
            return false; // Skip include paths
        if (f.startsWith("w", Qt::CaseInsensitive))
            return false; // Skip warning options
        if (f.startsWith("Y") || (f.startsWith("F") && f != "F"))
            return false; // Skip pch-related flags
    }
    return true;
}

ToolChain::MacroInspectionRunner MsvcToolChain::createMacroInspectionRunner() const
{
    Utils::Environment env(m_lastEnvironment);
    addToEnvironment(env);
    MacrosCache macroCache = predefinedMacrosCache();
    const Core::Id lang = language();

    // This runner must be thread-safe!
    return [this, env, macroCache, lang](const QStringList &cxxflags) {
        const QStringList filteredFlags = Utils::filtered(cxxflags, [](const QString &arg) {
            return hasFlagEffectOnMacros(arg);
        });

        const Utils::optional<MacroInspectionReport> cachedMacros = macroCache->check(filteredFlags);
        if (cachedMacros)
            return cachedMacros.value();

        const Macros macros = msvcPredefinedMacros(filteredFlags, env);

        const auto report = MacroInspectionReport{macros,
                                                  msvcLanguageVersion(filteredFlags, lang, macros)};
        macroCache->insert(filteredFlags, report);

        return report;
    };
}

Macros MsvcToolChain::predefinedMacros(const QStringList &cxxflags) const
{
    return createMacroInspectionRunner()(cxxflags).macros;
}

Utils::LanguageExtensions MsvcToolChain::languageExtensions(const QStringList &cxxflags) const
{
    using Utils::LanguageExtension;
    Utils::LanguageExtensions extensions(LanguageExtension::Microsoft);
    if (cxxflags.contains(QLatin1String("/openmp")))
        extensions |= LanguageExtension::OpenMP;

    // see http://msdn.microsoft.com/en-us/library/0k0w269d%28v=vs.71%29.aspx
    if (cxxflags.contains(QLatin1String("/Za")))
        extensions &= ~Utils::LanguageExtensions(LanguageExtension::Microsoft);

    return extensions;
}

WarningFlags MsvcToolChain::warningFlags(const QStringList &cflags) const
{
    WarningFlags flags = WarningFlags::NoWarnings;
    foreach (QString flag, cflags) {
        if (!flag.isEmpty() && flag[0] == QLatin1Char('-'))
            flag[0] = QLatin1Char('/');

        if (flag == QLatin1String("/WX")) {
            flags |= WarningFlags::AsErrors;
        } else if (flag == QLatin1String("/W0") || flag == QLatin1String("/w")) {
            inferWarningsForLevel(0, flags);
        } else if (flag == QLatin1String("/W1")) {
            inferWarningsForLevel(1, flags);
        } else if (flag == QLatin1String("/W2")) {
            inferWarningsForLevel(2, flags);
        } else if (flag == QLatin1String("/W3") || flag == QLatin1String("/W4")
                   || flag == QLatin1String("/Wall")) {
            inferWarningsForLevel(3, flags);
        }

        WarningFlagAdder add(flag, flags);
        if (add.triggered())
            continue;
        // http://msdn.microsoft.com/en-us/library/ay4h0tc9.aspx
        add(4263, WarningFlags::OverloadedVirtual);
        // http://msdn.microsoft.com/en-us/library/ytxde1x7.aspx
        add(4230, WarningFlags::IgnoredQualfiers);
        // not exact match, http://msdn.microsoft.com/en-us/library/0hx5ckb0.aspx
        add(4258, WarningFlags::HiddenLocals);
        // http://msdn.microsoft.com/en-us/library/wzxffy8c.aspx
        add(4265, WarningFlags::NonVirtualDestructor);
        // http://msdn.microsoft.com/en-us/library/y92ktdf2%28v=vs.90%29.aspx
        add(4018, WarningFlags::SignedComparison);
        // http://msdn.microsoft.com/en-us/library/w099eeey%28v=vs.90%29.aspx
        add(4068, WarningFlags::UnknownPragma);
        // http://msdn.microsoft.com/en-us/library/26kb9fy0%28v=vs.80%29.aspx
        add(4100, WarningFlags::UnusedParams);
        // http://msdn.microsoft.com/en-us/library/c733d5h9%28v=vs.90%29.aspx
        add(4101, WarningFlags::UnusedLocals);
        // http://msdn.microsoft.com/en-us/library/xb1db44s%28v=vs.90%29.aspx
        add(4189, WarningFlags::UnusedLocals);
        // http://msdn.microsoft.com/en-us/library/ttcz0bys%28v=vs.90%29.aspx
        add(4996, WarningFlags::Deprecated);
    }
    return flags;
}

ToolChain::BuiltInHeaderPathsRunner MsvcToolChain::createBuiltInHeaderPathsRunner() const
{
    Utils::Environment env(m_lastEnvironment);
    addToEnvironment(env);

    return [this, env](const QStringList &, const QString &, const QString &) {
        QMutexLocker locker(m_headerPathsMutex);
        if (m_headerPaths.isEmpty()) {
            foreach (const QString &path,
                     env.value(QLatin1String("INCLUDE")).split(QLatin1Char(';'))) {
                m_headerPaths.append({path, HeaderPathType::BuiltIn});
            }
        }
        return m_headerPaths;
    };
}

HeaderPaths MsvcToolChain::builtInHeaderPaths(const QStringList &cxxflags,
                                              const Utils::FileName &sysRoot) const
{
    return createBuiltInHeaderPathsRunner()(cxxflags, sysRoot.toString(), "");
}

void MsvcToolChain::addToEnvironment(Utils::Environment &env) const
{
    // We cache the full environment (incoming + modifications by setup script).
    if (!m_resultEnvironment.size() || env != m_lastEnvironment) {
        if (debug)
            qDebug() << "addToEnvironment: " << displayName();
        m_lastEnvironment = env;
        m_resultEnvironment = readEnvironmentSetting(env);
    }
    env = m_resultEnvironment;
}

static QString wrappedMakeCommand(const QString &command)
{
    const QString wrapperPath = QDir::currentPath() + "/msvc_make.bat";
    QFile wrapper(wrapperPath);
    if (!wrapper.open(QIODevice::WriteOnly))
        return command;
    QTextStream stream(&wrapper);
    stream << "chcp 65001\n";
    stream << command << " %*";

    return wrapperPath;
}

FileName MsvcToolChain::makeCommand(const Environment &environment) const
{
    bool useJom = ProjectExplorerPlugin::projectExplorerSettings().useJom;
    const QString jom("jom.exe");
    const QString nmake("nmake.exe");
    Utils::FileName tmp;

    FileName command;
    if (useJom) {
        tmp = environment.searchInPath(jom,
                                       {Utils::FileName::fromString(
                                           QCoreApplication::applicationDirPath())});
        if (!tmp.isEmpty())
            command = tmp;
    }

    if (command.isEmpty()) {
        tmp = environment.searchInPath(nmake);
        if (!tmp.isEmpty())
            command = tmp;
    }

    if (command.isEmpty())
        command = FileName::fromString(useJom ? jom : nmake);

    if (environment.hasKey("VSLANG"))
        return FileName::fromString(wrappedMakeCommand(command.toString()));

    return command;
}

Utils::FileName MsvcToolChain::compilerCommand() const
{
    return m_compilerCommand;
}

void MsvcToolChain::rescanForCompiler()
{
    Utils::Environment env = Utils::Environment::systemEnvironment();
    addToEnvironment(env);

    m_compilerCommand
        = env.searchInPath(QLatin1String("cl.exe"), {}, [](const Utils::FileName &name) {
              QDir dir(QDir::cleanPath(name.toFileInfo().absolutePath() + QStringLiteral("/..")));
              do {
                  if (QFile::exists(dir.absoluteFilePath(QStringLiteral("vcvarsall.bat")))
                      || QFile::exists(dir.absolutePath() + "/Auxiliary/Build/vcvarsall.bat"))
                      return true;
              } while (dir.cdUp() && !dir.isRoot());
              return false;
          });
}

IOutputParser *MsvcToolChain::outputParser() const
{
    return new MsvcParser;
}

void MsvcToolChain::changeVcVarsCall(const QString &varsBat, const QString &varsBatArg)
{
    m_vcvarsBat = varsBat;
    m_varsBatArg = varsBatArg;

    if (!varsBat.isEmpty()) {
        detectInstalledAbis();
        initEnvModWatcher(Utils::runAsync(envModThreadPool(),
                                          &ClangClToolChain::environmentModifications,
                                          m_vcvarsBat,
                                          m_varsBatArg));
    }
}

// --------------------------------------------------------------------------
// MsvcBasedToolChainConfigWidget: Creates a simple GUI without error label
// to display name and varsBat. Derived classes should add the error label and
// call setFromMsvcToolChain().
// --------------------------------------------------------------------------

MsvcBasedToolChainConfigWidget::MsvcBasedToolChainConfigWidget(ToolChain *tc)
    : ToolChainConfigWidget(tc)
    , m_nameDisplayLabel(new QLabel(this))
    , m_varsBatDisplayLabel(new QLabel(this))
{
    m_nameDisplayLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
    m_mainLayout->addRow(m_nameDisplayLabel);
    m_varsBatDisplayLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
    m_mainLayout->addRow(tr("Initialization:"), m_varsBatDisplayLabel);
}

static QString msvcVarsToDisplay(const MsvcToolChain &tc)
{
    QString varsBatDisplay = QDir::toNativeSeparators(tc.varsBat());
    if (!tc.varsBatArg().isEmpty()) {
        varsBatDisplay += QLatin1Char(' ');
        varsBatDisplay += tc.varsBatArg();
    }
    return varsBatDisplay;
}

void MsvcBasedToolChainConfigWidget::setFromMsvcToolChain()
{
    const auto *tc = static_cast<const MsvcToolChain *>(toolChain());
    QTC_ASSERT(tc, return );
    m_nameDisplayLabel->setText(tc->displayName());
    m_varsBatDisplayLabel->setText(msvcVarsToDisplay(*tc));
}

// --------------------------------------------------------------------------
// MsvcToolChainConfigWidget
// --------------------------------------------------------------------------

MsvcToolChainConfigWidget::MsvcToolChainConfigWidget(ToolChain *tc)
    : MsvcBasedToolChainConfigWidget(tc)
    , m_varsBatPathCombo(new QComboBox(this))
    , m_varsBatArchCombo(new QComboBox(this))
    , m_varsBatArgumentsEdit(new QLineEdit(this))
    , m_abiWidget(new AbiWidget)
{
    m_mainLayout->removeRow(m_mainLayout->rowCount() - 1);

    QHBoxLayout *hLayout = new QHBoxLayout();
    m_varsBatPathCombo->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
    m_varsBatPathCombo->setEditable(true);
    for (const MsvcToolChain *tmpTc : g_availableMsvcToolchains) {
        const QString nativeVcVars = QDir::toNativeSeparators(tmpTc->varsBat());
        if (!tmpTc->varsBat().isEmpty()
                && m_varsBatPathCombo->findText(nativeVcVars) == -1) {
            m_varsBatPathCombo->addItem(nativeVcVars);
        }
    }
    const bool isAmd64
            = Utils::HostOsInfo::hostArchitecture() == Utils::HostOsInfo::HostArchitectureAMD64;
     // TODO: Add missing values to MsvcToolChain::Platform
    m_varsBatArchCombo->addItem(tr("<empty>"), isAmd64 ? MsvcToolChain::amd64 : MsvcToolChain::x86);
    m_varsBatArchCombo->addItem("x86", MsvcToolChain::x86);
    m_varsBatArchCombo->addItem("amd64", MsvcToolChain::amd64);
    m_varsBatArchCombo->addItem("arm", MsvcToolChain::arm);
    m_varsBatArchCombo->addItem("x86_amd64", MsvcToolChain::x86_amd64);
    m_varsBatArchCombo->addItem("x86_arm", MsvcToolChain::x86_arm);
//    m_varsBatArchCombo->addItem("x86_arm64", MsvcToolChain::x86_arm64);
    m_varsBatArchCombo->addItem("amd64_x86", MsvcToolChain::amd64_x86);
    m_varsBatArchCombo->addItem("amd64_arm", MsvcToolChain::amd64_arm);
//    m_varsBatArchCombo->addItem("amd64_arm64", MsvcToolChain::amd64_arm64);
    m_varsBatArchCombo->addItem("ia64", MsvcToolChain::ia64);
    m_varsBatArchCombo->addItem("x86_ia64", MsvcToolChain::x86_ia64);
    m_varsBatArgumentsEdit->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
    m_varsBatArgumentsEdit->setToolTip(tr("Additional arguments for the vcvarsall.bat call"));
    hLayout->addWidget(m_varsBatPathCombo);
    hLayout->addWidget(m_varsBatArchCombo);
    hLayout->addWidget(m_varsBatArgumentsEdit);
    m_mainLayout->addRow(tr("Initialization:"), hLayout);
    m_mainLayout->addRow(tr("&ABI:"), m_abiWidget);
    addErrorLabel();
    setFromMsvcToolChain();

    connect(m_varsBatPathCombo, &QComboBox::currentTextChanged,
            this, &MsvcToolChainConfigWidget::handleVcVarsChange);
    connect(m_varsBatArchCombo, &QComboBox::currentTextChanged,
            this, &MsvcToolChainConfigWidget::handleVcVarsArchChange);
    connect(m_varsBatArgumentsEdit, &QLineEdit::textChanged,
            this, &ToolChainConfigWidget::dirty);
    connect(m_abiWidget, &AbiWidget::abiChanged, this, &ToolChainConfigWidget::dirty);
}

void MsvcToolChainConfigWidget::applyImpl()
{
    auto *tc = static_cast<MsvcToolChain *>(toolChain());
    QTC_ASSERT(tc, return );
    tc->setTargetAbi(m_abiWidget->currentAbi());
    const QString vcVars = QDir::fromNativeSeparators(m_varsBatPathCombo->currentText());
    tc->changeVcVarsCall(vcVars, vcVarsArguments());
    setFromMsvcToolChain();
}

void MsvcToolChainConfigWidget::discardImpl()
{
    setFromMsvcToolChain();
}

bool MsvcToolChainConfigWidget::isDirtyImpl() const
{
    auto msvcToolChain = static_cast<MsvcToolChain *>(toolChain());

    return msvcToolChain->varsBat() != QDir::fromNativeSeparators(m_varsBatPathCombo->currentText())
            || msvcToolChain->varsBatArg() != vcVarsArguments()
            || msvcToolChain->targetAbi() != m_abiWidget->currentAbi();
}

void MsvcToolChainConfigWidget::makeReadOnlyImpl()
{
    m_varsBatPathCombo->setEnabled(false);
    m_varsBatArchCombo->setEnabled(false);
    m_varsBatArgumentsEdit->setEnabled(false);
    m_abiWidget->setEnabled(false);
}

void MsvcToolChainConfigWidget::setFromMsvcToolChain()
{
    const auto *tc = static_cast<const MsvcToolChain *>(toolChain());
    QTC_ASSERT(tc, return );
    m_nameDisplayLabel->setText(tc->displayName());
    QString args = tc->varsBatArg();
    QStringList argList = args.split(' ');
    for (int i = 0; i < argList.count(); ++i) {
        if (m_varsBatArchCombo->findText(argList.at(i).trimmed()) != -1) {
            const QString arch = argList.takeAt(i);
            m_varsBatArchCombo->setCurrentText(arch);
            args = argList.join(QLatin1Char(' '));
            break;
        }
    }
    m_varsBatPathCombo->setCurrentText(QDir::toNativeSeparators(tc->varsBat()));
    m_varsBatArgumentsEdit->setText(args);
    m_abiWidget->setAbis(tc->supportedAbis(), tc->targetAbi());
}

void MsvcToolChainConfigWidget::handleVcVarsChange(const QString &vcVars)
{
    const QString normalizedVcVars = QDir::fromNativeSeparators(vcVars);
    const auto *currentTc = static_cast<const MsvcToolChain *>(toolChain());
    QTC_ASSERT(currentTc, return );
    const MsvcToolChain::Platform platform = m_varsBatArchCombo->currentData().value<MsvcToolChain::Platform>();
    const Abi::Architecture arch = archForPlatform(platform);
    const unsigned char wordWidth = wordWidthForPlatform(platform);

    for (const MsvcToolChain *tc : g_availableMsvcToolchains) {
        if (tc->varsBat() == normalizedVcVars && tc->targetAbi().wordWidth() == wordWidth
                && tc->targetAbi().architecture() == arch) {
            m_abiWidget->setAbis(tc->supportedAbis(), tc->targetAbi());
            break;
        }
    }
    emit dirty();
}

void MsvcToolChainConfigWidget::handleVcVarsArchChange(const QString &)
{
    Abi currentAbi = m_abiWidget->currentAbi();
    const MsvcToolChain::Platform platform = m_varsBatArchCombo->currentData().value<MsvcToolChain::Platform>();
    Abi newAbi(archForPlatform(platform), currentAbi.os(), currentAbi.osFlavor(),
               currentAbi.binaryFormat(), wordWidthForPlatform(platform));
    if (currentAbi != newAbi)
        m_abiWidget->setAbis(m_abiWidget->supportedAbis(), newAbi);
    emit dirty();
}

QString MsvcToolChainConfigWidget::vcVarsArguments() const
{
    QString varsBatArg
            = m_varsBatArchCombo->currentText() == tr("<empty>")
            ? "" : m_varsBatArchCombo->currentText();
    if (!m_varsBatArgumentsEdit->text().isEmpty())
        varsBatArg += QLatin1Char(' ') + m_varsBatArgumentsEdit->text();
    return varsBatArg;
}

// --------------------------------------------------------------------------
// ClangClToolChainConfigWidget
// --------------------------------------------------------------------------

ClangClToolChainConfigWidget::ClangClToolChainConfigWidget(ToolChain *tc) :
    MsvcBasedToolChainConfigWidget(tc),
    m_varsBatDisplayCombo(new QComboBox(this))
{
    m_mainLayout->removeRow(m_mainLayout->rowCount() - 1);

    m_varsBatDisplayCombo->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    m_mainLayout->addRow(tr("Initialization:"), m_varsBatDisplayCombo);

    if (tc->isAutoDetected()) {
        m_llvmDirLabel = new QLabel(this);
        m_llvmDirLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
        m_mainLayout->addRow(tr("&Compiler path:"), m_llvmDirLabel);
    } else {
        const QStringList gnuVersionArgs = QStringList("--version");
        m_compilerCommand = new Utils::PathChooser(this);
        m_compilerCommand->setExpectedKind(Utils::PathChooser::ExistingCommand);
        m_compilerCommand->setCommandVersionArguments(gnuVersionArgs);
        m_compilerCommand->setHistoryCompleter("PE.Clang.Command.History");
        m_mainLayout->addRow(tr("&Compiler path:"), m_compilerCommand);
    }
    addErrorLabel();
    setFromClangClToolChain();

    if (m_compilerCommand) {
        connect(m_compilerCommand,
                &Utils::PathChooser::rawPathChanged,
                this,
                &ClangClToolChainConfigWidget::dirty);
    }
}

void ClangClToolChainConfigWidget::setFromClangClToolChain()
{
    const auto *currentTC = static_cast<const MsvcToolChain *>(toolChain());
    m_nameDisplayLabel->setText(currentTC->displayName());
    m_varsBatDisplayCombo->clear();
    m_varsBatDisplayCombo->addItem(msvcVarsToDisplay(*currentTC));
    for (const MsvcToolChain *tc : g_availableMsvcToolchains) {
        const QString varsToDisplay = msvcVarsToDisplay(*tc);
        if (m_varsBatDisplayCombo->findText(varsToDisplay) == -1)
            m_varsBatDisplayCombo->addItem(varsToDisplay);
    }

    const auto *clangClToolChain = static_cast<const ClangClToolChain *>(toolChain());
    if (clangClToolChain->isAutoDetected())
        m_llvmDirLabel->setText(QDir::toNativeSeparators(clangClToolChain->clangPath()));
    else
        m_compilerCommand->setFileName(Utils::FileName::fromString(clangClToolChain->clangPath()));
}

static const MsvcToolChain *findMsvcToolChain(unsigned char wordWidth, Abi::OSFlavor flavor)
{
    return Utils::findOrDefault(g_availableMsvcToolchains,
                                [wordWidth, flavor](const MsvcToolChain *tc) {
                                    const Abi abi = tc->targetAbi();
                                    return abi.osFlavor() == flavor && wordWidth == abi.wordWidth();
                                });
}

static const MsvcToolChain *findMsvcToolChain(const QString &displayedVarsBat)
{
    return Utils::findOrDefault(g_availableMsvcToolchains,
                                [&displayedVarsBat] (const MsvcToolChain *tc) {
                                    return msvcVarsToDisplay(*tc) == displayedVarsBat;
                                });
}

static QVersionNumber clangClVersion(const QString &clangClPath)
{
    Utils::SynchronousProcess clangClProcess;
    const Utils::SynchronousProcessResponse response
        = clangClProcess.runBlocking(clangClPath, {QStringLiteral("--version")});
    if (response.result != Utils::SynchronousProcessResponse::Finished || response.exitCode != 0)
        return {};
    const QRegularExpressionMatch match = QRegularExpression(
                                              QStringLiteral("clang version (\\d+(\\.\\d+)+)"))
                                              .match(response.stdOut());
    if (!match.hasMatch())
        return {};
    return QVersionNumber::fromString(match.captured(1));
}

static const MsvcToolChain *selectMsvcToolChain(const QString &displayedVarsBat,
                                                const QString &clangClPath,
                                                unsigned char wordWidth)
{
    const MsvcToolChain *toolChain = nullptr;
    if (!displayedVarsBat.isEmpty()) {
        toolChain = findMsvcToolChain(displayedVarsBat);
        if (toolChain)
            return toolChain;
    }

    QTC_CHECK(displayedVarsBat.isEmpty());
    const QVersionNumber version = clangClVersion(clangClPath);
    if (version.majorVersion() >= 6)
        toolChain = findMsvcToolChain(wordWidth, Abi::WindowsMsvc2017Flavor);
    if (!toolChain) {
        toolChain = findMsvcToolChain(wordWidth, Abi::WindowsMsvc2015Flavor);
        if (!toolChain)
            toolChain = findMsvcToolChain(wordWidth, Abi::WindowsMsvc2013Flavor);
    }
    return toolChain;
}

static QList<ToolChain *> detectClangClToolChainInPath(const QString &clangClPath,
                                                       const QList<ToolChain *> &alreadyKnown,
                                                       const QString &displayedVarsBat,
                                                       bool isDefault = false)
{
    QList<ToolChain *> res;
    const unsigned char wordWidth = Utils::is64BitWindowsBinary(clangClPath) ? 64 : 32;
    const MsvcToolChain *toolChain = selectMsvcToolChain(displayedVarsBat, clangClPath, wordWidth);

    if (!toolChain) {
        qWarning("Unable to find a suitable MSVC version for \"%s\".",
                 qPrintable(QDir::toNativeSeparators(clangClPath)));
        return res;
    }

    Utils::Environment systemEnvironment = Utils::Environment::systemEnvironment();
    const Abi targetAbi = toolChain->targetAbi();
    const QString name = QString("%1LLVM %2 bit based on %3")
                             .arg(QLatin1String(isDefault ? "Default " : ""))
                             .arg(wordWidth)
                             .arg(Abi::toString(targetAbi.osFlavor()).toUpper());
    for (auto language : {Constants::C_LANGUAGE_ID, Constants::CXX_LANGUAGE_ID}) {
        ClangClToolChain *tc = static_cast<ClangClToolChain *>(
            Utils::findOrDefault(alreadyKnown, [&](ToolChain *tc) -> bool {
                if (tc->typeId() != Constants::CLANG_CL_TOOLCHAIN_TYPEID)
                    return false;
                if (tc->targetAbi() != targetAbi)
                    return false;
                if (tc->language() != language)
                    return false;
                return systemEnvironment.isSameExecutable(tc->compilerCommand().toString(),
                                                          clangClPath);
            }));
        if (!tc) {
            tc = new ClangClToolChain(name, clangClPath);
            tc->setDetection(ToolChain::AutoDetection);
            tc->setLanguage(language);
            tc->resetMsvcToolChain(toolChain);
        }
        res << tc;
    }
    return res;
}

static QString compilerFromPath(const QString &path)
{
    return path + "/bin/clang-cl.exe";
}

void ClangClToolChainConfigWidget::applyImpl()
{
    Utils::FileName clangClPath = m_compilerCommand->fileName();
    auto clangClToolChain = static_cast<ClangClToolChain *>(toolChain());
    clangClToolChain->setClangPath(clangClPath.toString());

    if (clangClPath.fileName() != "clang-cl.exe") {
        clangClToolChain->resetMsvcToolChain();
        setFromClangClToolChain();
        return;
    }

    const QString displayedVarsBat = m_varsBatDisplayCombo->currentText();
    QList<ToolChain *> results = detectClangClToolChainInPath(clangClPath.toString(),
                                                              {},
                                                              displayedVarsBat);

    if (results.isEmpty()) {
        clangClToolChain->resetMsvcToolChain();
    } else {
        for (const ToolChain *toolchain : results) {
            if (toolchain->language() == clangClToolChain->language()) {
                clangClToolChain->resetMsvcToolChain(static_cast<const MsvcToolChain *>(toolchain));
                break;
            }
        }

        qDeleteAll(results);
    }
    setFromClangClToolChain();
}

void ClangClToolChainConfigWidget::discardImpl()
{
    setFromClangClToolChain();
}

void ClangClToolChainConfigWidget::makeReadOnlyImpl()
{
    m_varsBatDisplayCombo->setEnabled(false);
}

// --------------------------------------------------------------------------
// ClangClToolChain, piggy-backing on MSVC2015 and providing the compiler
// clang-cl.exe as a [to some extent] compatible drop-in replacement for cl.
// --------------------------------------------------------------------------

ClangClToolChain::ClangClToolChain(const QString &name,
                                   const QString &clangPath)
    : MsvcToolChain(Constants::CLANG_CL_TOOLCHAIN_TYPEID, name, Abi(), "", "")
    , m_clangPath(clangPath)
{}

ClangClToolChain::ClangClToolChain()
    : MsvcToolChain(Constants::CLANG_CL_TOOLCHAIN_TYPEID)
{}

bool ClangClToolChain::isValid() const
{
    return MsvcToolChain::isValid() && compilerCommand().exists()
           && compilerCommand().fileName() == "clang-cl.exe";
}

void ClangClToolChain::addToEnvironment(Utils::Environment &env) const
{
    MsvcToolChain::addToEnvironment(env);
    QDir path = QFileInfo(m_clangPath).absoluteDir(); // bin folder
    env.prependOrSetPath(path.canonicalPath());
}

Utils::FileName ClangClToolChain::compilerCommand() const
{
    return Utils::FileName::fromString(m_clangPath);
}

QString ClangClToolChain::typeDisplayName() const
{
    return QCoreApplication::translate("ProjectExplorer::ClangToolChainFactory", "Clang");
}

QList<Utils::FileName> ClangClToolChain::suggestedMkspecList() const
{
    const QString mkspec = QLatin1String("win32-clang-") + Abi::toString(targetAbi().osFlavor());
    return QList<Utils::FileName>{Utils::FileName::fromString(mkspec),
                                  Utils::FileName::fromString("win32-clang-msvc")};
}

IOutputParser *ClangClToolChain::outputParser() const
{
    return new ClangClParser;
}

static inline QString llvmDirKey()
{
    return QStringLiteral("ProjectExplorer.ClangClToolChain.LlvmDir");
}

QVariantMap ClangClToolChain::toMap() const
{
    QVariantMap result = MsvcToolChain::toMap();
    result.insert(llvmDirKey(), m_clangPath);
    return result;
}

bool ClangClToolChain::fromMap(const QVariantMap &data)
{
    if (!MsvcToolChain::fromMap(data))
        return false;
    const QString clangPath = data.value(llvmDirKey()).toString();
    if (clangPath.isEmpty())
        return false;
    m_clangPath = clangPath;

    return true;
}

std::unique_ptr<ToolChainConfigWidget> ClangClToolChain::createConfigurationWidget()
{
    return std::make_unique<ClangClToolChainConfigWidget>(this);
}

void ClangClToolChain::resetMsvcToolChain(const MsvcToolChain *base)
{
    if (!base) {
        m_abi = Abi();
        changeVcVarsCall("");
        return;
    }

    m_abi = base->targetAbi();
    changeVcVarsCall(base->varsBat(), base->varsBatArg());
}

bool ClangClToolChain::operator==(const ToolChain &other) const
{
    if (!MsvcToolChain::operator==(other))
        return false;

    const auto *clangClTc = static_cast<const ClangClToolChain *>(&other);
    return m_clangPath == clangClTc->m_clangPath;
}

Macros ClangClToolChain::msvcPredefinedMacros(const QStringList &cxxflags,
                                              const Utils::Environment &env) const
{
    if (!cxxflags.contains("--driver-mode=g++"))
        return MsvcToolChain::msvcPredefinedMacros(cxxflags, env);

    Utils::SynchronousProcess cpp;
    cpp.setEnvironment(env.toStringList());
    cpp.setWorkingDirectory(Utils::TemporaryDirectory::masterDirectoryPath());

    QStringList arguments = cxxflags;
    arguments.append(gccPredefinedMacrosOptions(language()));
    arguments.append("-");
    Utils::SynchronousProcessResponse response = cpp.runBlocking(compilerCommand().toString(),
                                                                 arguments);
    if (response.result != Utils::SynchronousProcessResponse::Finished || response.exitCode != 0) {
        // Show the warning but still parse the output.
        QTC_CHECK(false && "clang-cl exited with non-zero code.");
    }

    return Macro::toMacros(response.allRawOutput());
}

Utils::LanguageVersion ClangClToolChain::msvcLanguageVersion(const QStringList &cxxflags,
                                                             const Core::Id &language,
                                                             const Macros &macros) const
{
    if (cxxflags.contains("--driver-mode=g++"))
        return ToolChain::languageVersion(language, macros);
    return MsvcToolChain::msvcLanguageVersion(cxxflags, language, macros);
}

ClangClToolChain::BuiltInHeaderPathsRunner ClangClToolChain::createBuiltInHeaderPathsRunner() const
{
    {
        QMutexLocker locker(m_headerPathsMutex);
        m_headerPaths.clear();
    }

    return MsvcToolChain::createBuiltInHeaderPathsRunner();
}

// --------------------------------------------------------------------------
// MsvcToolChainFactory
// --------------------------------------------------------------------------

MsvcToolChainFactory::MsvcToolChainFactory()
{
    setDisplayName(tr("MSVC"));
    setSupportedToolChainType(Constants::MSVC_TOOLCHAIN_TYPEID);
    setSupportedLanguages({Constants::C_LANGUAGE_ID, Constants::CXX_LANGUAGE_ID});
    setToolchainConstructor([] { return new MsvcToolChain; });
}

QString MsvcToolChainFactory::vcVarsBatFor(const QString &basePath,
                                           MsvcToolChain::Platform platform,
                                           const QVersionNumber &v)
{
    QString result;
    if (const MsvcPlatform *p = platformEntry(platform)) {
        result += basePath;
        // Starting with 15.0 (MSVC2017), the .bat are in one folder.
        if (v.majorVersion() <= 14)
            result += QLatin1String(p->prefix);
        result += QLatin1Char('/');
        result += QLatin1String(p->bat);
    }
    return result;
}

static QList<ToolChain *> findOrCreateToolChain(const QList<ToolChain *> &alreadyKnown,
                                                const QString &name,
                                                const Abi &abi,
                                                const QString &varsBat,
                                                const QString &varsBatArg)
{
    QList<ToolChain *> res;
    for (auto language : {Constants::C_LANGUAGE_ID, Constants::CXX_LANGUAGE_ID}) {
        ToolChain *tc = Utils::findOrDefault(alreadyKnown, [&](ToolChain *tc) -> bool {
            if (tc->typeId() != Constants::MSVC_TOOLCHAIN_TYPEID)
                return false;
            if (tc->targetAbi() != abi)
                return false;
            if (tc->language() != language)
                return false;
            auto mtc = static_cast<MsvcToolChain *>(tc);
            return mtc->varsBat() == varsBat && mtc->varsBatArg() == varsBatArg;
        });
        if (!tc) {
            tc = new MsvcToolChain(name, abi, varsBat, varsBatArg);
            tc->setLanguage(language);
        }
        res << tc;
    }
    return res;
}

// Detect build tools introduced with MSVC2015
static void detectCppBuildTools2015(QList<ToolChain *> *list)
{
    struct Entry
    {
        const char *postFix;
        const char *varsBatArg;
        Abi::Architecture architecture;
        Abi::BinaryFormat format;
        unsigned char wordSize;
    };

    const Entry entries[] = {{" (x86)", "x86", Abi::X86Architecture, Abi::PEFormat, 32},
                             {" (x64)", "amd64", Abi::X86Architecture, Abi::PEFormat, 64},
                             {" (x86_arm)", "x86_arm", Abi::ArmArchitecture, Abi::PEFormat, 32},
                             {" (x64_arm)", "amd64_arm", Abi::ArmArchitecture, Abi::PEFormat, 64}};

    const QString name = QStringLiteral("Microsoft Visual C++ Build Tools");
    const QString vcVarsBat = windowsProgramFilesDir() + QLatin1Char('/') + name
                              + QStringLiteral("/vcbuildtools.bat");
    if (!QFileInfo(vcVarsBat).isFile())
        return;
    for (const Entry &e : entries) {
        const Abi abi(e.architecture,
                      Abi::WindowsOS,
                      Abi::WindowsMsvc2015Flavor,
                      e.format,
                      e.wordSize);
        for (auto language : {Constants::C_LANGUAGE_ID, Constants::CXX_LANGUAGE_ID}) {
            auto tc = new MsvcToolChain(name + QLatin1String(e.postFix),
                                        abi,
                                        vcVarsBat,
                                        QLatin1String(e.varsBatArg));
            tc->setDetection(ToolChain::AutoDetection);
            tc->setLanguage(language);
            list->append(tc);
        }
    }
}

QList<ToolChain *> MsvcToolChainFactory::autoDetect(const QList<ToolChain *> &alreadyKnown)
{
    QList<ToolChain *> results;

    // 1) Installed SDKs preferred over standalone Visual studio
    const QSettings
        sdkRegistry(QLatin1String(
                        "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows"),
                    QSettings::NativeFormat);
    const QString defaultSdkPath = sdkRegistry.value(QLatin1String("CurrentInstallFolder"))
                                       .toString();
    if (!defaultSdkPath.isEmpty()) {
        foreach (const QString &sdkKey, sdkRegistry.childGroups()) {
            const QString name = sdkRegistry.value(sdkKey + QLatin1String("/ProductName")).toString();
            const QString folder = sdkRegistry.value(sdkKey + QLatin1String("/InstallationFolder"))
                                       .toString();
            if (folder.isEmpty())
                continue;

            QDir dir(folder);
            if (!dir.cd(QLatin1String("bin")))
                continue;
            QFileInfo fi(dir, QLatin1String("SetEnv.cmd"));
            if (!fi.exists())
                continue;

            QList<ToolChain *> tmp;
            const QVector<QPair<MsvcToolChain::Platform, QString>> platforms = {
                {MsvcToolChain::x86, "x86"},
                {MsvcToolChain::amd64, "x64"},
                {MsvcToolChain::ia64, "ia64"},
            };
            for (const auto &platform : platforms) {
                tmp.append(findOrCreateToolChain(alreadyKnown,
                                                 generateDisplayName(name,
                                                                     MsvcToolChain::WindowsSDK,
                                                                     platform.first),
                                                 findAbiOfMsvc(MsvcToolChain::WindowsSDK,
                                                               platform.first,
                                                               sdkKey),
                                                 fi.absoluteFilePath(),
                                                 "/" + platform.second));
            }
            // Make sure the default is front.
            if (folder == defaultSdkPath)
                results = tmp + results;
            else
                results += tmp;
        } // foreach
    }

    // 2) Installed MSVCs
    // prioritized list.
    // x86_arm was put before amd64_arm as a workaround for auto detected windows phone
    // toolchains. As soon as windows phone builds support x64 cross builds, this change
    // can be reverted.
    const MsvcToolChain::Platform platforms[] = {MsvcToolChain::x86,
                                                 MsvcToolChain::amd64_x86,
                                                 MsvcToolChain::amd64,
                                                 MsvcToolChain::x86_amd64,
                                                 MsvcToolChain::arm,
                                                 MsvcToolChain::x86_arm,
                                                 MsvcToolChain::amd64_arm,
                                                 MsvcToolChain::ia64,
                                                 MsvcToolChain::x86_ia64};

    foreach (const VisualStudioInstallation &i, detectVisualStudio()) {
        for (MsvcToolChain::Platform platform : platforms) {
            const bool toolchainInstalled
                = QFileInfo(vcVarsBatFor(i.vcVarsPath, platform, i.version)).isFile();
            if (hostSupportsPlatform(platform) && toolchainInstalled) {
                results.append(
                    findOrCreateToolChain(alreadyKnown,
                                          generateDisplayName(i.vsName, MsvcToolChain::VS, platform),
                                          findAbiOfMsvc(MsvcToolChain::VS, platform, i.vsName),
                                          i.vcVarsAll,
                                          platformName(platform)));
            }
        }
    }

    detectCppBuildTools2015(&results);

    for (ToolChain *tc : results)
        tc->setDetection(ToolChain::AutoDetection);

    return results;
}

ClangClToolChainFactory::ClangClToolChainFactory()
{
    setDisplayName(tr("clang-cl"));
    setSupportedLanguages({Constants::C_LANGUAGE_ID, Constants::CXX_LANGUAGE_ID});
    setSupportedToolChainType(Constants::CLANG_CL_TOOLCHAIN_TYPEID);
    setToolchainConstructor([] { return new ClangClToolChain; });
}

bool ClangClToolChainFactory::canCreate() const
{
    return !g_availableMsvcToolchains.isEmpty();
}

QList<ToolChain *> ClangClToolChainFactory::autoDetect(const QList<ToolChain *> &alreadyKnown)
{
    Q_UNUSED(alreadyKnown)

#ifdef Q_OS_WIN64
    const char registryNode[] = "HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\LLVM\\LLVM";
#else
    const char registryNode[] = "HKEY_LOCAL_MACHINE\\SOFTWARE\\LLVM\\LLVM";
#endif

    QList<ToolChain *> results;
    QList<ToolChain *> known = alreadyKnown;

    QString qtCreatorsClang = Core::ICore::clangExecutable(CLANG_BINDIR);
    if (!qtCreatorsClang.isEmpty()) {
        qtCreatorsClang = Utils::FileName::fromString(qtCreatorsClang)
                              .parentDir()
                              .pathAppended("clang-cl.exe")
                              .toString();
        results.append(detectClangClToolChainInPath(qtCreatorsClang, alreadyKnown, "", true));
        known.append(results);
    }

    const QSettings registry(QLatin1String(registryNode), QSettings::NativeFormat);
    if (registry.status() == QSettings::NoError) {
        const QString path = QDir::cleanPath(registry.value(QStringLiteral(".")).toString());
        const QString clangClPath = compilerFromPath(path);
        if (!path.isEmpty()) {
            results.append(detectClangClToolChainInPath(clangClPath, known, ""));
            known.append(results);
        }
    }

    const Utils::Environment systemEnvironment = Utils::Environment::systemEnvironment();
    const Utils::FileName clangClPath = systemEnvironment.searchInPath("clang-cl");
    if (!clangClPath.isEmpty())
        results.append(detectClangClToolChainInPath(clangClPath.toString(), known, ""));

    return results;
}

ToolChain *ClangClToolChainFactory::create()
{
    return new ClangClToolChain("clang-cl", "");
}

bool MsvcToolChain::operator==(const ToolChain &other) const
{
    if (!ToolChain::operator==(other))
        return false;

    const auto *msvcTc = dynamic_cast<const MsvcToolChain *>(&other);
    return targetAbi() == msvcTc->targetAbi() && m_vcvarsBat == msvcTc->m_vcvarsBat
           && m_varsBatArg == msvcTc->m_varsBatArg;
}

void MsvcToolChain::cancelMsvcToolChainDetection()
{
    envModThreadPool()->clear();
}

Utils::optional<QString> MsvcToolChain::generateEnvironmentSettings(const Utils::Environment &env,
                                                                    const QString &batchFile,
                                                                    const QString &batchArgs,
                                                                    QMap<QString, QString> &envPairs)
{
    const QString marker = "####################";
    // Create a temporary file name for the output. Use a temporary file here
    // as I don't know another way to do this in Qt...

    // Create a batch file to create and save the env settings
    Utils::TempFileSaver saver(Utils::TemporaryDirectory::masterDirectoryPath() + "/XXXXXX.bat");

    QByteArray call = "call ";
    call += Utils::QtcProcess::quoteArg(batchFile).toLocal8Bit();
    if (!batchArgs.isEmpty()) {
        call += ' ';
        call += batchArgs.toLocal8Bit();
    }
    if (Utils::HostOsInfo::isWindowsHost())
        saver.write("chcp 65001\r\n");
    saver.write(call + "\r\n");
    saver.write("@echo " + marker.toLocal8Bit() + "\r\n");
    saver.write("set\r\n");
    saver.write("@echo " + marker.toLocal8Bit() + "\r\n");
    if (!saver.finalize()) {
        qWarning("%s: %s", Q_FUNC_INFO, qPrintable(saver.errorString()));
        return QString();
    }

    Utils::SynchronousProcess run;

    // As of WinSDK 7.1, there is logic preventing the path from being set
    // correctly if "ORIGINALPATH" is already set. That can cause problems
    // if Creator is launched within a session set up by setenv.cmd.
    Utils::Environment runEnv = env;
    runEnv.unset(QLatin1String("ORIGINALPATH"));
    run.setEnvironment(runEnv.toStringList());
    run.setTimeoutS(30);
    Utils::FileName cmdPath = Utils::FileName::fromUserInput(
        QString::fromLocal8Bit(qgetenv("COMSPEC")));
    if (cmdPath.isEmpty())
        cmdPath = env.searchInPath(QLatin1String("cmd.exe"));
    // Windows SDK setup scripts require command line switches for environment expansion.
    QStringList cmdArguments({QLatin1String("/E:ON"), QLatin1String("/V:ON"), QLatin1String("/c")});
    cmdArguments << QDir::toNativeSeparators(saver.fileName());
    if (debug)
        qDebug() << "readEnvironmentSetting: " << call << cmdPath << cmdArguments.join(' ')
                 << " Env: " << runEnv.size();
    run.setCodec(QTextCodec::codecForName("UTF-8"));
    Utils::SynchronousProcessResponse response = run.runBlocking(cmdPath.toString(), cmdArguments);

    if (response.result != Utils::SynchronousProcessResponse::Finished) {
        const QString message = !response.stdErr().isEmpty()
                                    ? response.stdErr()
                                    : response.exitMessage(cmdPath.toString(), 10);
        qWarning().noquote() << message;
        QString command = QDir::toNativeSeparators(batchFile);
        if (!batchArgs.isEmpty())
            command += ' ' + batchArgs;
        return QCoreApplication::translate("ProjectExplorer::Internal::MsvcToolChain",
                                           "Failed to retrieve MSVC Environment from \"%1\":\n"
                                           "%2")
            .arg(command, message);
    }

    // The SDK/MSVC scripts do not return exit codes != 0. Check on stdout.
    const QString stdOut = response.stdOut();

    //
    // Now parse the file to get the environment settings
    const int start = stdOut.indexOf(marker);
    if (start == -1) {
        qWarning("Could not find start marker in stdout output.");
        return QString();
    }

    const int end = stdOut.indexOf(marker, start + 1);
    if (end == -1) {
        qWarning("Could not find end marker in stdout output.");
        return QString();
    }

    const QString output = stdOut.mid(start, end - start);

    foreach (const QString &line, output.split(QLatin1String("\n"))) {
        const int pos = line.indexOf('=');
        if (pos > 0) {
            const QString varName = line.mid(0, pos);
            const QString varValue = line.mid(pos + 1);
            envPairs.insert(varName, varValue);
        }
    }

    return Utils::nullopt;
}

bool MsvcToolChainFactory::canCreate() const
{
    return !g_availableMsvcToolchains.isEmpty();
}

ToolChain *MsvcToolChainFactory::create()
{
    return new MsvcToolChain("Microsoft Visual C++ Compiler",
                             Abi::hostAbi(), g_availableMsvcToolchains.first()->varsBat(), "");
}

MsvcToolChain::WarningFlagAdder::WarningFlagAdder(const QString &flag, WarningFlags &flags)
    : m_flags(flags)
{
    if (flag.startsWith(QLatin1String("-wd"))) {
        m_doesEnable = false;
    } else if (flag.startsWith(QLatin1String("-w"))) {
        m_doesEnable = true;
    } else {
        m_triggered = true;
        return;
    }
    bool ok = false;
    if (m_doesEnable)
        m_warningCode = flag.midRef(2).toInt(&ok);
    else
        m_warningCode = flag.midRef(3).toInt(&ok);
    if (!ok)
        m_triggered = true;
}

void MsvcToolChain::WarningFlagAdder::operator()(int warningCode, WarningFlags flagsSet)
{
    if (m_triggered)
        return;
    if (warningCode == m_warningCode) {
        m_triggered = true;
        if (m_doesEnable)
            m_flags |= flagsSet;
        else
            m_flags &= ~flagsSet;
    }
}

bool MsvcToolChain::WarningFlagAdder::triggered() const
{
    return m_triggered;
}

} // namespace Internal
} // namespace ProjectExplorer

Q_DECLARE_METATYPE(ProjectExplorer::Internal::MsvcToolChain::Platform)