This repository has been archived by the owner on Aug 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
CVXBuildSystem.cs
1668 lines (1414 loc) · 58.4 KB
/
CVXBuildSystem.cs
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
/*
* ClangVSx - Compiler Bridge for CLang in MS Visual Studio
* Harry Denholm, ishani.org 2011-2012
*
* https://github.com/ishani/ClangVSx
* http://www.ishani.org/web/articles/code/clangvsx/
*
* Released under LLVM Release License. See LICENSE.TXT for details.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using Microsoft.VisualStudio.VCProjectEngine;
using Process = System.Diagnostics.Process;
using System.Threading;
namespace ClangVSx
{
/// <summary>
/// Collection of build tools
/// </summary>
internal class CVXBuildSystem
{
private readonly String ConsoleDivider = String.Empty;
private readonly bool DoGenerateBatchFiles;
private readonly bool DoShowCommands;
private readonly String LocationClangEXE;
private readonly String LocationLIBExe;
private readonly String LocationLINKExe;
private readonly String LocationLLVM_LINK_EXE;
private readonly String LocationLLVM_LLC_EXE;
private readonly String PathToVSCommonIDE;
private readonly String PathToVSTools;
private StreamWriter BatchFileStream; // if DoGenerateBatchFiles == true, this is set to the output file stream
protected OutputWindowPane OutputPane; // output panel configured by AddIn, passed in to ctor
protected Window VSOutputWindow;
public CVXBuildSystem(Window clangOutputWindow, OutputWindowPane clangOutputPane)
{
VSOutputWindow = clangOutputWindow;
OutputPane = clangOutputPane;
ConsoleDivider = ConsoleDivider.PadLeft(128, '-');
// clear and focus the output window
OutputPane.Clear();
ShowOutputPane();
// write out a version header
{
Assembly assem = Assembly.GetExecutingAssembly();
Version vers = assem.GetName().Version;
DateTime buildDate = new DateTime(2000, 1, 1).AddDays(vers.Build).AddSeconds(vers.Revision * 2);
WriteToOutputPane("ClangVSx " + vers.Major.ToString() + "." + vers.Minor.ToString() +
" | LLVM/Clang C++ Compiler Bridge | www.ishani.org\n\n");
// try to give the message queue time to bring up the output window
Application.DoEvents();
}
// read out current executables' locations
LocationClangEXE = CVXRegistry.PathToClang;
LocationLLVM_LINK_EXE = Path.GetDirectoryName(LocationClangEXE) + @"\llvm-link.exe";
LocationLLVM_LLC_EXE = Path.GetDirectoryName(LocationClangEXE) + @"\llc.exe";
// work out where the MS linker / lib tools are, Clang/LLVM doesn't have a linker presently
// eg "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\"
// VS120COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\
#if CVSX_2013
String pathToVS = Environment.GetEnvironmentVariable("VS120COMNTOOLS");
if (pathToVS == null && !CVXRegistry.VSRootPathOverride.Value) {
throw new Exception(
"Could not find Visual Studio 2013 install directory (via VS120COMNTOOLS environment variable)");
}
#endif
#if CVSX_2012
String pathToVS = Environment.GetEnvironmentVariable("VS110COMNTOOLS");
if (pathToVS == null)
{
throw new Exception(
"Could not find Visual Studio 2012 install directory (via VS110COMNTOOLS environment variable)");
}
#endif
#if CVSX_2010
String pathToVS = Environment.GetEnvironmentVariable("VS100COMNTOOLS");
if (pathToVS == null)
{
throw new Exception(
"Could not find Visual Studio 2010 install directory (via VS100COMNTOOLS environment variable)");
}
#endif
if (CVXRegistry.VSRootPathOverride.Value)
{
WriteToOutputPane("Overriding VS envvar with : " + CVXRegistry.VSRootPath.Value + "\n");
pathToVS = CVXRegistry.VSRootPath.Value;
}
// have to go digging for the location of the MSVC linker/librarian
PathToVSTools = Path.GetFullPath(pathToVS + @"..\..\VC\bin\");
PathToVSCommonIDE = Path.GetFullPath(pathToVS + @"..\IDE\");
LocationLIBExe = PathToVSTools + "lib.exe";
LocationLINKExe = PathToVSTools + "link.exe";
var PathCheck = new[] {
LocationLLVM_LINK_EXE,
LocationLLVM_LLC_EXE,
LocationClangEXE,
LocationLIBExe,
LocationLINKExe
};
foreach (String path in PathCheck)
{
if (!File.Exists(path))
{
throw new Exception(String.Format("Could not find {0}, check ClangVSx Settings - tried:\n\n{1}",
Path.GetFileName(path), path));
}
}
// read more options from the registry
DoShowCommands = CVXRegistry.ShowCommands;
DoGenerateBatchFiles = CVXRegistry.MakeBatchFiles;
}
#region Utils
internal void ShowOutputPane()
{
VSOutputWindow.Activate();
OutputPane.Activate();
Application.DoEvents();
}
internal void WriteToOutputPane(string text)
{
OutputPane.OutputString(text);
}
/// <summary>
/// simple helper that creates a Process instance ready for running the compiler, linker, external tools, etc
/// </summary>
internal Process NewExternalProcess()
{
var result = new Process();
result.StartInfo.UseShellExecute = false;
result.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
result.StartInfo.CreateNoWindow = true;
result.StartInfo.RedirectStandardOutput = true;
result.StartInfo.RedirectStandardError = true;
return result;
}
// http://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
internal int RunProcessAndLogOutputs( Process setProcess )
{
int pCode = -1;
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
using (setProcess)
{
try
{
setProcess.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
};
setProcess.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(e.Data);
}
};
setProcess.Start();
setProcess.BeginOutputReadLine();
setProcess.BeginErrorReadLine();
if (setProcess.WaitForExit(2000))
{
pCode = setProcess.ExitCode;
}
else
{
// Timed out.
}
WriteToOutputPane(output.ToString());
WriteToOutputPane(error.ToString());
}
catch (Exception ex)
{
WriteToOutputPane("Exception when running process: " + ex.Message + "\n");
return -2;
}
finally
{
outputWaitHandle.WaitOne(2000);
errorWaitHandle.WaitOne(2000);
}
}
}
return pCode;
}
private VCFileConfiguration GetFileConfiguration(IVCCollection configs, VCConfiguration cfg)
{
try
{
foreach (VCFileConfiguration vcr in configs)
{
if (vcr.ProjectConfiguration.ConfigurationName == cfg.ConfigurationName &&
vcr.ProjectConfiguration.Platform.Name == cfg.Platform.Name)
{
return vcr;
}
}
}
catch (Exception)
{
WriteToOutputPane("Error: failed to resolve configuration for file - " + cfg.ConfigurationName + " | " +
cfg.Platform.Name + "\n");
return null;
}
return null;
}
#endregion
#region Custom Build Steps
/// <summary>
/// I'm probably showing C# inexperience here; I wanted this function to operate on any
/// object that had an Evaluate method, eg. VCConfiguration, VCFileConfiguration, et al.
/// Reflection and generics is what I came up with!
/// </summary>
internal void ExecuteCustomBuildToolCommandLine<T>(String cmdLine, object evaluator, VCProject vcProject)
{
try
{
MethodInfo evalMethod = typeof(T).GetMethod("Evaluate");
String[] cmdsToRun = cmdLine.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (String singleCmd in cmdsToRun)
{
var evaluatedCmd = evalMethod.Invoke(evaluator, new object[] { singleCmd }) as String;
evaluatedCmd= evaluatedCmd.Replace("/", "\\");
if (DoShowCommands)
{
WriteToOutputPane(" cmd.exe /C " + evaluatedCmd + "\n");
}
if (BatchFileStream != null)
{
BatchFileStream.WriteLine("@REM -- custom build tool --");
BatchFileStream.WriteLine(" cmd.exe /C " + evaluatedCmd);
}
// run the specified tool
Process cbStep = NewExternalProcess();
cbStep.StartInfo.FileName = "cmd.exe";
cbStep.StartInfo.Arguments = "/C " + evaluatedCmd;
cbStep.StartInfo.WorkingDirectory = vcProject.ProjectDirectory;
RunProcessAndLogOutputs(cbStep);
}
}
catch (Exception e)
{
WriteToOutputPane("Exception During Execution : " + cmdLine + "\n" + e.Message + "\n" + e.Source +
"\n\n");
}
}
/// <summary>
/// bootstrap any custom build steps, run via cmd.exe
/// </summary>
internal void RunCustomBuildStep(VCCustomBuildTool customBuildTool, VCFile vcFile, VCProject vcProject,
VCFileConfiguration vcFC, bool ignoreTimeStamp)
{
// check to see if the supplied outputs are older than the file in question
// I assume this is how MSVS does it...
bool outputFilesNeedBuilding = false;
if (ignoreTimeStamp)
{
outputFilesNeedBuilding = true;
}
else
{
if (customBuildTool.Outputs.Length > 0)
{
var vcFileFI = new FileInfo(vcFile.FullPath);
// cut the output files string into individual items
String[] outputFiles = customBuildTool.Outputs.Split(new[] { ' ', ',', ';' },
StringSplitOptions.RemoveEmptyEntries);
foreach (String outputFileName in outputFiles)
{
// find a full pathname for the file, relative or not
String finalOutput = vcFC.Evaluate(outputFileName);
if (!Path.IsPathRooted(outputFileName))
finalOutput = vcProject.ProjectDirectory + outputFileName;
String finalOutputDir = Path.GetDirectoryName(finalOutput);
if (!Directory.Exists(finalOutputDir))
{
Directory.CreateDirectory(finalOutputDir);
}
// if it doesn't exist, safe to assume we should try and build it
if (!File.Exists(finalOutput))
{
outputFilesNeedBuilding = true;
break;
}
// compare timestamps with source file
var outputFileFI = new FileInfo(finalOutput);
TimeSpan timeDiffCodeToObj = outputFileFI.LastWriteTime.Subtract(vcFileFI.LastWriteTime);
if (timeDiffCodeToObj.Seconds < 0)
{
outputFilesNeedBuilding = true;
break;
}
}
}
}
string evaluatedDescription = vcFC.Evaluate(customBuildTool.Description);
// nothing to do?
if (!outputFilesNeedBuilding)
{
WriteToOutputPane("[skipping] " + evaluatedDescription + "\n");
return;
}
WriteToOutputPane("[custom] " + evaluatedDescription + "\n");
ExecuteCustomBuildToolCommandLine<VCFileConfiguration>(customBuildTool.CommandLine, vcFC, vcProject);
}
#endregion
#region VCFile Building
/// <summary>
/// internal function that does the work of compiling a C++ file using Clang
/// </summary>
internal bool InternalBuildVCFile(VCFile vcFile, VCProject vcProject, VCConfiguration vcCfg,
String defaultCompilerString, ref StringBuilder compileString,
HashSet<String> CompilationArtifacts, bool dryRun = false)
{
// get access to the per-file VCCL config data (eg stuff that augments / overwrites the global settings)
// we use this to configure the compiler per file, as it should reflect the final config state of the file
VCFileConfiguration vcFC = GetFileConfiguration((IVCCollection)vcFile.FileConfigurations, vcCfg);
if (vcFC == null)
return false;
var perFileVCC = (VCCLCompilerTool)vcFC.Tool;
// begin forming the command line string to send to Clang
compileString.Append('"' + vcFile.FullPath.Replace("/", "\\") + '"');
compileString.Append(defaultCompilerString);
// sort out an output object file name
String objectFileName = vcFC.Evaluate(perFileVCC.ObjectFile).Replace("/", "\\");
objectFileName = Path.GetFullPath(objectFileName);
String prebuild = Path.GetDirectoryName(objectFileName);
if (!Directory.Exists(prebuild))
{
Directory.CreateDirectory(prebuild);
}
String outputFileExtension = ".obj";
if (perFileVCC.WholeProgramOptimization)
{
outputFileExtension = ".bc";
compileString.Append("-flto ");
}
// check to see if we should emit an obj at all
String compileCmds = compileString.ToString();
if (!compileCmds.Contains("-o\""))
{
// if no obj file specified, make a suitable filename (is this a robust check..??)
if (!Path.HasExtension(objectFileName))
{
objectFileName += Path.ChangeExtension(vcFile.Name, outputFileExtension);
}
else
{
// force our extension?
objectFileName = Path.ChangeExtension(objectFileName, outputFileExtension);
}
// record the .obj target in the cmd line and in the list to pass to the linker
compileString.Append("-o\"");
compileString.Append(objectFileName);
compileString.Append("\" ");
CompilationArtifacts.Add(objectFileName);
}
if (dryRun)
return true;
// stick the per-file defines, includes, etc
compileString.Append(GatherIncludesAndDefines<VCFileConfiguration>(perFileVCC, vcFC));
// figure out a suitable mapping for optimization flags
switch (perFileVCC.Optimization)
{
case optimizeOption.optimizeDisabled:
compileString.Append("-O0 ");
break;
case optimizeOption.optimizeMaxSpeed:
compileString.Append("-O2 ");
break;
case optimizeOption.optimizeFull:
compileString.Append("-O3 ");
break;
case optimizeOption.optimizeMinSpace:
compileString.Append("-Oz "); // opting for the 'smallest size at any cost' option
break;
}
if (perFileVCC.OmitFramePointers || perFileVCC.Optimization == optimizeOption.optimizeFull)
{
compileString.Append("-fomit-frame-pointer ");
}
// arbitrarily turning a 5-point dial into a toggle switch :)
if (perFileVCC.WarningLevel == warningLevelOption.warningLevel_0 ||
perFileVCC.WarningLevel == warningLevelOption.warningLevel_1 ||
perFileVCC.WarningLevel == warningLevelOption.warningLevel_2)
{
compileString.Append("-w "); // no warnings
}
else if (perFileVCC.WarningLevel == warningLevelOption.warningLevel_4)
{
compileString.Append("-Wall --pedantic "); // all warnings
}
if (perFileVCC.WarnAsError)
{
compileString.Append("-Werror ");
}
// stack overflow checking
if (perFileVCC.BufferSecurityCheck)
{
// HDD TODO incompatible with MSVC atm
// compileString.Append("-fstack-protector-all ");
}
else
{
compileString.Append("-fno-stack-protector ");
}
// debug info generation
if (perFileVCC.DebugInformationFormat != debugOption.debugDisabled)
{
// HDD TODO - clang currently can't embed debug info when targeting windows
// compileString.Append("-g ");
}
// no inline function expansion
if (perFileVCC.InlineFunctionExpansion == inlineExpansionOption.expandDisable)
{
// bafflingly, should the option be set to 'Default', we get told it's 'inlineExpansionOption.expandDisable', even
// if it will be set by virtue of the optimisation configuration...
// we have to guess that this choice is only valid when the user hasn't chosen optimisation mode max/size/full
if (perFileVCC.Optimization == optimizeOption.optimizeDisabled ||
perFileVCC.Optimization == optimizeOption.optimizeCustom)
{
compileString.Append("-fno-inline ");
}
}
// asm listing or preprocessor output both turn on the same flag, as the flag produces them both
if (perFileVCC.AssemblerOutput != asmListingOption.asmListingNone ||
perFileVCC.GeneratePreprocessedFile != preprocessOption.preprocessNo)
{
// -S ensures we just preprocess
// -CC leaves comments in the output
compileString.Append("-save-temps -S -Xpreprocessor -CC ");
}
if (perFileVCC.CompileAs == CompileAsOptions.compileAsCPlusPlus)
{
compileString.Append("-x c++ ");
// compiler options from the settings page
if (CVXRegistry.COptCPP14)
{
compileString.Append("-std=c++14 ");
}
else if (CVXRegistry.COptStdSpec)
{
compileString.Append("-std=c++11 ");
}
// RTTI disable?
if (!perFileVCC.RuntimeTypeInfo)
{
compileString.Append("-fno-rtti ");
}
else
{
compileString.Append("-frtti ");
}
// EH
try
{
// this explodes if it's set to 'off', MSBuild conversion layer problems :|
if (perFileVCC.ExceptionHandling != cppExceptionHandling.cppExceptionHandlingNo)
{
compileString.Append("-fexceptions -fcxx-exceptions ");
}
}
catch
{
compileString.Append("-fno-exceptions ");
}
}
else if (perFileVCC.CompileAs == CompileAsOptions.compileAsC)
{
compileString.Append("-x c ");
if (CVXRegistry.COptStdSpec)
{
compileString.Append("-std=c99 ");
}
}
// add the 'additional options' verbatim
if (perFileVCC.AdditionalOptions != null)
{
// add the 'additional options' verbatim
// only pull across opts that begin with "-", ignoring VS "/" ones
string[] opts = vcFC.Evaluate(perFileVCC.AdditionalOptions).Split(' ');
foreach (string opt in opts)
{
if (opt.StartsWith("-"))
compileString.Append(opt + " ");
}
}
// ask for warnings/errors in MSVC format
compileString.Append("-fdiagnostics-format=msvc ");
String fullObjectPath = objectFileName;
if (!Path.IsPathRooted(fullObjectPath))
fullObjectPath = vcProject.ProjectDirectory + objectFileName;
WriteToOutputPane(" - " + vcFile.UnexpandedRelativePath);
if (DoShowCommands)
WriteToOutputPane("\n " + compileString + "\n");
// crank the message pump; means our Output Window stuff should update properly
Application.DoEvents();
// execute the compiler
Process compileProcess = NewExternalProcess();
compileProcess.StartInfo.FileName = LocationClangEXE;
compileProcess.StartInfo.Arguments = compileString.ToString();
compileProcess.StartInfo.WorkingDirectory = vcProject.ProjectDirectory;
compileProcess.Start();
// read any output from the compiler, indicative of some problem...
String outputStr = compileProcess.StandardError.ReadToEnd();
compileProcess.WaitForExit();
if (outputStr.Length > 0)
{
WriteToOutputPane("\n" + outputStr);
WriteToOutputPane(ConsoleDivider + "\n\n");
if (outputStr.Contains("error:"))
return false;
}
else
{
if (!DoShowCommands)
{
if (vcFile.UnexpandedRelativePath.Length < 80)
{
String tabPad = "";
tabPad = tabPad.PadLeft(80 - vcFile.UnexpandedRelativePath.Length, ' ');
WriteToOutputPane(tabPad);
}
WriteToOutputPane(" [ok]\n");
}
}
return true;
}
#endregion
#region Data Gathering
/// <summary>
///
/// </summary>
internal string GatherIncludesAndDefines<T>(VCCLCompilerTool vcCTool, object evaluator)
{
MethodInfo evalMethod = typeof(T).GetMethod("Evaluate");
var result = new StringBuilder();
// push additional includes into the default compiler string
if (vcCTool.AdditionalIncludeDirectories != null)
{
String cIncDir = vcCTool.AdditionalIncludeDirectories.Replace(",", ";");
String[] cIncDirs = cIncDir.Split(';');
foreach (string inc in cIncDirs)
{
if (inc.Length > 0)
{
var parsedInc = (evalMethod.Invoke(evaluator, new object[] { inc }) as String);
if (parsedInc != null && parsedInc.Length > 0)
{
result.Append("-I");
String incCheck = parsedInc.Replace("\\", "/");
// Clang doesn't like the trailing / on these
if (incCheck == "./") incCheck = ".";
if (incCheck == "../") incCheck = "..";
// resolve any relative paths
incCheck = Path.GetFullPath(incCheck);
result.Append("\"");
result.Append(incCheck);
result.Append("\" ");
}
}
}
}
// same for force-includes, route to -include
if (vcCTool.ForcedIncludeFiles != null)
{
String cForceInc = vcCTool.ForcedIncludeFiles.Replace(",", ";");
String[] cForceIncs = cForceInc.Split(';');
foreach (string inc in cForceIncs)
{
if (inc.Length > 0)
{
var parsedInc = (evalMethod.Invoke(evaluator, new object[] { inc }) as String);
if (parsedInc != null && parsedInc.Length > 0)
{
String incCheck = parsedInc.Replace("\\", "/");
// resolve any relative paths
incCheck = Path.GetFullPath(incCheck);
result.Append("-include \"");
result.Append(incCheck);
result.Append("\" ");
}
}
}
}
// get default preprocessor directives
if (vcCTool.PreprocessorDefinitions != null)
{
String cPDefine = vcCTool.PreprocessorDefinitions.Replace(",", ";");
String[] cPDefines = cPDefine.Split(';');
foreach (string pd in cPDefines)
{
if (pd.Length > 0)
{
var parsedPd = (evalMethod.Invoke(evaluator, new object[] { pd }) as String);
if (parsedPd != null && parsedPd.Length > 0)
{
result.Append("-D");
result.Append(parsedPd);
result.Append(" ");
}
}
}
}
return result.ToString();
}
/// <summary>
/// common code to generate compiler settings for non-file-specific stuff
/// </summary>
internal String GenerateDefaultCompilerString(VCProject vcProject, VCConfiguration vcCfg)
{
// per cpp-file compiler setting default:
//
// -c for individual compilation without auto-linking
//
// -nostdinc to stop the compiler adding VS include directories itself; we want to control that
//
// define '__CLANG_VSX__'
//
var defaultCompilerString = new StringBuilder(" -c -nostdinc -D__CLANG_VSX__ ");
String targetCmdOpt = "target";
if (vcCfg.Platform.Name == "Win32")
defaultCompilerString.AppendFormat("-{0} {1} ", targetCmdOpt, CVXRegistry.TripleWin32.Value);
else if (vcCfg.Platform.Name == "x64")
defaultCompilerString.AppendFormat("-{0} {1} ", targetCmdOpt, CVXRegistry.TripleX64.Value);
else if (vcCfg.Platform.Name == "ARM")
defaultCompilerString.AppendFormat("-{0} {1} ", targetCmdOpt, CVXRegistry.TripleARM.Value);
if (CVXRegistry.ShowPhases)
{
defaultCompilerString.Append("-ccc-print-phases ");
}
if (CVXRegistry.COptSLPAgg)
{
defaultCompilerString.Append("-fslp-vectorize-aggressive ");
}
if (CVXRegistry.VerboseVectorize)
{
defaultCompilerString.Append("-Rpass=loop-vectorize -Rpass-missed=loop-vectorize -Rpass-analysis=loop-vectorize ");
}
// add the UNICODE defines?
if (vcCfg.CharacterSet == charSet.charSetUnicode)
{
defaultCompilerString.Append("-DUNICODE -D_UNICODE ");
}
else if (vcCfg.CharacterSet == charSet.charSetMBCS)
{
defaultCompilerString.Append("-D_MBCS ");
}
// get the various VC tools to read out setup
var fTools = (IVCCollection)vcCfg.Tools;
var vcCTool = (VCCLCompilerTool)fTools.Item("VCCLCompilerTool");
var vcLinkerTool = (VCLinkerTool)fTools.Item("VCLinkerTool");
var vcLibTool = (VCLibrarianTool)fTools.Item("VCLibrarianTool");
// convert the project-wide includes, prepro defines, force includes
defaultCompilerString.Append(GatherIncludesAndDefines<VCConfiguration>(vcCTool, vcCfg));
String plt = vcCfg.Platform.Name;
// sort out prolog/epilog settings based on cfg/subsystem
if (vcCfg.ConfigurationType == ConfigurationTypes.typeApplication)
{
}
else if (vcCfg.ConfigurationType ==
ConfigurationTypes.typeDynamicLibrary)
{
defaultCompilerString.Append("-D_WINDLL ");
}
// sort out defines for the runtime library choice
{
// Static MultiThread /MT LIBCMT _MT
// Debug Static MultiThread /MTd LIBCMTD _DEBUG and _MT
//
// Dynamic Link (DLL) /MD MSVCRT _MT and _DLL
// Debug Dynamic Link (DLL) /MDd MSVCRTD _DEBUG, _MT, and _DLL
//
switch (vcCTool.RuntimeLibrary)
{
case runtimeLibraryOption.rtMultiThreaded:
defaultCompilerString.Append("-D_MT ");
break;
case runtimeLibraryOption.rtMultiThreadedDebug:
defaultCompilerString.Append("-D_MT -D_DEBUG ");
break;
case runtimeLibraryOption.rtMultiThreadedDLL:
defaultCompilerString.Append("-D_MT -D_DLL ");
break;
case runtimeLibraryOption.rtMultiThreadedDebugDLL:
defaultCompilerString.Append("-D_MT -D_DLL -D_DEBUG ");
break;
}
}
// allow Clang args to be stuck in the 'additional options' textbox in C/C++ properties page
if (vcCTool.AdditionalOptions != null)
{
// only pull across opts that begin with "++"; we have to be specific here because VS has both / and -
// prefixed arguments, so ++<arg> means we flag up clang-specific args we want to pass in ..
// sadly that also means we can't interop smoothly with VS as it will reject "++", but this is an edge case anyway
string[] opts = vcCfg.Evaluate(vcCTool.AdditionalOptions).Split(' ');
foreach (string opt in opts)
{
if (opt.StartsWith("++"))
defaultCompilerString.Append(opt.Substring(2) + " ");
}
}
// bolt on any arguments from the settings dialog
defaultCompilerString.Append(" ");
defaultCompilerString.Append(CVXRegistry.CommonArgs);
defaultCompilerString.Append(" ");
// gather up default include paths (eg Windows SDK)
if (vcCTool.FullIncludePath != null)
{
String cIncDir = vcCTool.FullIncludePath.Replace(",", ";");
String[] cIncDirs = cIncDir.Split(';');
// add the fully resolved directories into a string set, to weed out any duplicates
var uniqueDirs = new HashSet<String>();
foreach (string inc in cIncDirs)
{
if (inc.Length > 0)
{
uniqueDirs.Add(Path.GetFullPath(inc.Replace("\\", "/")));
}
}
foreach (String inc in uniqueDirs)
{
defaultCompilerString.Append("-isystem \"");
defaultCompilerString.Append(inc);
defaultCompilerString.Replace("\\", "", defaultCompilerString.Length - 1, 1);
defaultCompilerString.Append("\" ");
}
}
defaultCompilerString.Append(" -fms-compatibility ");
defaultCompilerString.Append(" -fms-extensions ");
defaultCompilerString.Append(" -fmsc-version=1800 ");
return defaultCompilerString.ToString();
}
#endregion
public bool CompileSingleFile(VCFile vcFile, VCProject vcProject, VCConfiguration vcCfg,
String additionalCmds = "")
{
var defaultCompilerString = new StringBuilder(GenerateDefaultCompilerString(vcProject, vcCfg));
defaultCompilerString.Append(" ");
defaultCompilerString.Append(additionalCmds);
defaultCompilerString.Append(" ");
var compileString = new StringBuilder(1024);
var Artifacts = new HashSet<String>();
if (InternalBuildVCFile(vcFile, vcProject, vcCfg, defaultCompilerString.ToString(), ref compileString,
Artifacts))
{
WriteToOutputPane("\nCompile Successful\n");
return true;
}
return false;
}
/// <summary>
/// main worker function to build a project, swapping in our own tools as desired
/// </summary>
public bool BuildProject(VCProject vcProject, VCConfiguration vcCfg, bool justLink, IBuildCancellation buildCancellation)
{
String defaultCompilerString = GenerateDefaultCompilerString(vcProject, vcCfg);
// get the various VC tools to read out setup
var fTools = (IVCCollection)vcCfg.Tools;
var vcLinkerTool = (VCLinkerTool)fTools.Item("VCLinkerTool");
var vcLibTool = (VCLibrarianTool)fTools.Item("VCLibrarianTool");
if (vcLinkerTool != null)
{
if (vcLinkerTool.SubSystem != subSystemOption.subSystemWindows &&
vcLinkerTool.SubSystem != subSystemOption.subSystemConsole)
{
WriteToOutputPane("Unsupported subsystem type - " + vcLinkerTool.SubSystem.ToString() +
" - (Windows/Console only)\n");
return false;
}
}
// work out the path to the final linking result, report it
String outLink = "";
switch (vcCfg.ConfigurationType)
{
case ConfigurationTypes.typeApplication:
outLink = vcCfg.Evaluate(vcLinkerTool.OutputFile);
break;
case ConfigurationTypes.typeDynamicLibrary:
outLink = vcCfg.Evaluate(vcLinkerTool.OutputFile);
break;
case ConfigurationTypes.typeStaticLibrary:
outLink = vcCfg.Evaluate(vcLibTool.OutputFile);
break;
}
outLink.Replace("/", "\\");
// resolve path to be local to the location of the project file, if required
outLink = Path.GetFullPath(outLink);
WriteToOutputPane("Linker Output : " + outLink + "\n");
String outLinkDirectory = Path.GetDirectoryName(outLink);
if (!Directory.Exists(outLinkDirectory))
{
Directory.CreateDirectory(outLinkDirectory);
}
// ------------------ log out a batch file of build commands ------------------
if (DoGenerateBatchFiles)
{
String batchFileName = "clang_build_" + vcProject.Name.Replace(" ", "_") + "_" +
vcCfg.Name.Replace("|", "-").Replace(" ", "_") + ".bat";
String buildCommandFileName = Path.GetFullPath(vcProject.ProjectDirectory + "\\" + batchFileName);
BatchFileStream = new StreamWriter(buildCommandFileName);
WriteToOutputPane("Emitting Batch : " + batchFileName + "\n");
}
// ---------------------------- build prep ------------------------------------
// go and look up all the files that will be taking part in this build in some way
var ProjectFiles = new List<ProjectFile>(32);
var vcFileCollection = (IVCCollection)vcProject.Files;
foreach (VCFile vcFile in vcFileCollection)
{
VCFileConfiguration vcFC = GetFileConfiguration((IVCCollection)vcFile.FileConfigurations, vcCfg);
if (vcFC == null)
return false;
try
{
if (vcFC.ExcludedFromBuild)
continue;
ProjectFiles.Add(new ProjectFile(vcFile, vcFC));
}
catch (Exception)
{
// in 2012 RC we get the .filters file in here which throws an exception when ExcludedFromBuild is accessed
// not sure yet how best else to check for this...
WriteToOutputPane("Skipping : " + vcFile.ItemName + "\n");
}
}
var CompilationArtifacts = new HashSet<String>();
// ----------------------------------------------------------------------------
// the MSVC build order we will be attempting to emulate:
// ----------------------------------------------------------------------------
// Pre-Build event
// Custom build tools on individual files
// MIDL
// Resource compiler
// The C/C++ compiler
// Pre-Link event
// Linker or Librarian (as appropriate)