-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathDPCT.cpp
More file actions
1551 lines (1394 loc) · 59.4 KB
/
DPCT.cpp
File metadata and controls
1551 lines (1394 loc) · 59.4 KB
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
//===--------------- DPCT.cpp ---------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/DPCT/DPCT.h"
#include "ASTTraversal.h"
#include "AnalysisInfo.h"
#include "CommandOption/ValidateArguments.h"
#include "Config.h"
#include "ErrorHandle/CrashRecovery.h"
#include "ErrorHandle/Error.h"
#include "FileGenerator/GenFiles.h"
#include "FileGenerator/GenHelperFunction.h"
#include "IncMigration/ExternalReplacement.h"
#include "IncMigration/IncrementalMigrationUtility.h"
#include "Linux/AutoComplete.h"
#include "MigrateScript/GenMakefile.h"
#include "MigrateScript/MigrateCmakeScript.h"
#include "MigrateScript/MigratePythonBuildScript.h"
#include "MigrationAction.h"
#include "MigrationReport/Statics.h"
#include "QueryAPIMapping/QueryAPIMapping.h"
#include "RuleInfra/CallExprRewriter.h"
#include "RuleInfra/MemberExprRewriter.h"
#include "RuleInfra/TypeLocRewriters.h"
#include "RulesDNN/MapNamesDNN.h"
#include "RulesLang/MapNamesLang.h"
#include "RulesLangLib/MapNamesLangLib.h"
#include "RulesMathLib/MapNamesBlas.h"
#include "RulesMathLib/MapNamesRandom.h"
#include "UserDefinedRules/PatternRewriter.h"
#include "UserDefinedRules/UserDefinedRules.h"
#include "Utility.h"
#include "Windows/VcxprojParser.h"
#include "clang/Format/Format.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Core/UnifiedPath.h"
#include "clang/Tooling/Refactoring.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/TargetParser/Host.h"
#include <string>
#include "ToolChains/Cuda.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Options.h"
#include <algorithm>
#include <cstring>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Version.h"
#include "clang/DPCT/DpctOptions.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Rewrite/Core/Rewriter.h"
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::dpct;
using namespace clang::tooling;
using namespace llvm::cl;
extern bool isDPCT;
extern bool ReMigrationReady;
namespace clang {
namespace tooling {
UnifiedPath getFormatSearchPath();
extern std::string ClangToolOutputMessage;
#ifdef _WIN32
extern UnifiedPath VcxprojFilePath;
#endif
} // namespace tooling
namespace dpct {
llvm::cl::OptionCategory &CtHelpCatAll = llvm::cl::getCtHelpCat();
llvm::cl::OptionCategory &CtHelpCatBasic = llvm::cl::getCtHelpCatBasic();
llvm::cl::OptionCategory &CtHelpCatAdvanced = llvm::cl::getCtHelpCatAdvanced();
llvm::cl::OptionCategory &CtHelpCatCodeGen = llvm::cl::getCtHelpCatCodeGen();
llvm::cl::OptionCategory &CtHelpCatReportGen =
llvm::cl::getCtHelpCatReportGen();
llvm::cl::OptionCategory &CtHelpCatBuildScript =
llvm::cl::getCtHelpCatBuildScript();
llvm::cl::OptionCategory &CtHelpCatQueryAPI = llvm::cl::getCtHelpCatQueryAPI();
llvm::cl::OptionCategory &CtHelpCatWarnings = llvm::cl::getCtHelpCatWarnings();
llvm::cl::OptionCategory &CtHelpCatHelpInfo = llvm::cl::getCtHelpCatHelpInfo();
llvm::cl::OptionCategory &CtHelpCatInterceptBuild =
llvm::cl::getCtHelpCatInterceptBuild();
void initWarningIDs();
} // namespace dpct
} // namespace clang
// clang-format off
const char *const CtHelpMessage = DiagRef;
const char *const CtHelpHint =
" Warning: Please specify file(s) to be migrated.\n"
" To get help on the tool usage, run: dpct --help\n"
"\n";
const char *const CmakeScriptMigrationHelpHint =
"Warning: CMake build script file like CMakeLists.txt is not found, so no CMake build script file will be migrated.";
const char *const PythonBuildScriptMigrationHelpHint =
"Warning: No Python file is found, so no Python build script file will be migrated.";
const char *const BuildScriptMigrationHelpHint =
"Warning: No CMake build script file (e.g., CMakeLists.txt or files with a .cmake suffix) or Python file was found, so no CMake or Python build script file will be migrated.";
static extrahelp CommonHelp(CtHelpMessage);
static std::string SuppressWarningsMessage = "A comma separated list of migration warnings to suppress. Valid "
"warning IDs range\n"
"from " + std::to_string(DiagnosticsMessage::MinID) + " to " +
std::to_string(DiagnosticsMessage::MaxID) +
". Hyphen separated ranges are also allowed. For example:\n"
"--suppress-warnings=1000-1010,1011.";
#define DPCT_OPTIONS_VAR 1
#define DPCT_OPTIONS_IN_CLANG_DPCT 1
#include "clang/DPCT/DPCTOptions.inc"
#ifdef __linux__
static AutoCompletePrinter AutoCompletePrinterInstance;
static llvm::cl::opt<AutoCompletePrinter, true, llvm::cl::parser<std::string>> AutoComplete(
"autocomplete", llvm::cl::desc("List all options or enums which have the specified prefix.\n"),
llvm::cl::cat(CtHelpCatAll), llvm::cl::ReallyHidden, llvm::cl::location(AutoCompletePrinterInstance));
#endif
// clang-format on
// TODO: implement one of this for each source language.
UnifiedPath CudaPath;
UnifiedPath DpctInstallPath;
std::unordered_map<std::string, bool> ChildOrSameCache;
std::unordered_map<std::string, bool> ChildPathCache;
std::unordered_map<std::string, bool> IsDirectoryCache;
extern bool StopOnParseErrTooling;
extern UnifiedPath InRootTooling;
clang::tooling::UnifiedPath InRootPath;
clang::tooling::UnifiedPath OutRootPath;
clang::tooling::UnifiedPath CudaIncludePath;
clang::tooling::UnifiedPath SDKPath;
std::vector<clang::tooling::UnifiedPath> RuleFilePath;
std::vector<clang::tooling::UnifiedPath> AnalysisScope;
UnifiedPath getCudaInstallPath(int argc, const char **argv) {
std::vector<const char *> Argv;
Argv.reserve(argc);
// do not copy "--" so the driver sees a possible SDK include path option
std::copy_if(argv, argv + argc, back_inserter(Argv),
[](const char *s) { return std::strcmp(s, "--"); });
// Remove the redundant prefix "--extra-arg=" so that
// SDK detector can find correct path.
for (unsigned int i = 0; i < Argv.size(); i++) {
if (strncmp(argv[i], "--extra-arg=--cuda-path", 23) == 0) {
Argv[i] = argv[i] + 12;
}
}
// Output parameters to indicate errors in parsing. Not checked here,
// OptParser will handle errors.
unsigned MissingArgIndex, MissingArgCount;
MissingArgIndex = MissingArgCount = 0;
auto &Opts = driver::getDriverOptTable();
llvm::opt::InputArgList ParsedArgs =
Opts.ParseArgs(Argv, MissingArgIndex, MissingArgCount);
// Create minimalist CudaInstallationDetector and return the InstallPath.
DiagnosticsEngine E(nullptr, nullptr, nullptr, false);
driver::Driver Driver("", llvm::sys::getDefaultTargetTriple(), E);
driver::CudaInstallationDetector CudaIncludeDetector(
Driver, llvm::Triple(Driver.getTargetTriple()), ParsedArgs);
UnifiedPath Path = CudaIncludeDetector.getIncludePath().str();
dpct::DpctGlobalInfo::setSDKVersion(CudaIncludeDetector.version());
if (!CudaIncludePath.getPath().empty()) {
if (!CudaIncludeDetector.isIncludePathValid()) {
ShowStatus(MigrationErrorInvalidCudaIncludePath);
dpctExit(MigrationErrorInvalidCudaIncludePath);
}
if (!CudaIncludeDetector.isVersionSupported() &&
!CudaIncludeDetector.isVersionPartSupported()) {
ShowStatus(MigrationErrorCudaVersionUnsupported);
dpctExit(MigrationErrorCudaVersionUnsupported);
}
} else if (!CudaIncludeDetector.isIncludePathValid()) {
ShowStatus(MigrationErrorCannotDetectCudaPath);
dpctExit(MigrationErrorCannotDetectCudaPath);
} else if (!CudaIncludeDetector.isVersionSupported() &&
!CudaIncludeDetector.isVersionPartSupported()) {
ShowStatus(MigrationErrorDetectedCudaVersionUnsupported);
dpctExit(MigrationErrorDetectedCudaVersionUnsupported);
}
if (Path.getCanonicalPath().empty()) {
ShowStatus(MigrationErrorInvalidCudaIncludePath);
dpctExit(MigrationErrorInvalidCudaIncludePath);
}
return Path;
}
static bool isCUDAHeaderRequired() { return !MigrateBuildScriptOnly; }
UnifiedPath getInstallPath(const char *invokeCommand) {
SmallString<512> InstalledPathStr(invokeCommand);
// Do a PATH lookup, if there are no directory components.
if (llvm::sys::path::filename(InstalledPathStr) == InstalledPathStr) {
if (llvm::ErrorOr<std::string> Tmp = llvm::sys::findProgramByName(
llvm::sys::path::filename(InstalledPathStr.str()))) {
InstalledPathStr = *Tmp;
}
}
UnifiedPath InstalledPath(InstalledPathStr);
StringRef InstalledPathParent(llvm::sys::path::parent_path(InstalledPath.getCanonicalPath()));
// Move up to parent directory of bin directory
InstalledPath = llvm::sys::path::parent_path(InstalledPathParent);
return InstalledPath;
}
unsigned int GetLinesNumber(clang::tooling::RefactoringTool &Tool,
UnifiedPath Path) {
// Set up Rewriter and to get source manager.
LangOptions DefaultLangOptions;
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
TextDiagnosticPrinter DiagnosticPrinter(llvm::errs(), &*DiagOpts);
DiagnosticsEngine Diagnostics(
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
&DiagnosticPrinter, false);
SourceManager Sources(Diagnostics, Tool.getFiles());
Rewriter Rewrite(Sources, DefaultLangOptions);
SourceManager &SM = Rewrite.getSourceMgr();
auto Entry = SM.getFileManager().getOptionalFileRef(Path.getCanonicalPath());
if (!Entry) {
std::string ErrMsg = "FilePath Invalid...\n";
PrintMsg(ErrMsg);
dpctExit(MigrationErrorInvalidFilePath);
}
FileID FID = SM.getOrCreateFileID(*Entry, SrcMgr::C_User);
SourceLocation EndOfFile = SM.getLocForEndOfFile(FID);
unsigned int LineNumber = SM.getSpellingLineNumber(EndOfFile, nullptr);
return LineNumber;
}
static void printMetrics(clang::tooling::RefactoringTool &Tool) {
size_t Count = 0;
for (const auto &Elem : LOCStaticsMap) {
// Skip invalid file path.
if (!llvm::sys::fs::exists(Elem.first))
continue;
unsigned TotalLines = GetLinesNumber(Tool, Elem.first);
unsigned TransToAPI = Elem.second[0];
unsigned TransToSYCL = Elem.second[1];
unsigned NotTrans = TotalLines - TransToSYCL - TransToAPI;
unsigned NotSupport = Elem.second[2];
if (Count == 0) {
DpctStats() << "\n";
DpctStats() << "File name, LOC migrated to SYCL, LOC migrated to helper "
"functions, "
"LOC not needed to migrate, LOC not able to migrate";
DpctStats() << "\n";
}
DpctStats() << Elem.first + ", " + std::to_string(TransToSYCL) + ", " +
std::to_string(TransToAPI) + ", " +
std::to_string(NotTrans) + ", " +
std::to_string(NotSupport);
DpctStats() << "\n";
Count++;
}
}
static void saveApisReport(void) {
if (ReportFilePrefix == "stdout") {
std::string buf;
llvm::raw_string_ostream OS(buf);
OS << "------------------APIS report--------------------\n";
OS << "API name\t\t\t\tFrequency";
OS << "\n";
for (const auto &Elem : SrcAPIStaticsMap) {
std::string APIName = Elem.first;
unsigned int Count = Elem.second;
OS << llvm::format("%-30s%16u\n", APIName.c_str(), Count);
}
OS << "-------------------------------------------------\n";
PrintMsg(OS.str());
} else {
std::string RFile = appendPath(
OutRootPath.getCanonicalPath().str(),
ReportFilePrefix + (ReportFormat.getValue() == ReportFormatEnum::RFE_CSV
? ".apis.csv"
: ".apis.log"));
createDirectories(llvm::sys::path::parent_path(RFile));
RawFDOStream File(RFile);
File << (ReportFormat.getValue() == ReportFormatEnum::RFE_CSV
? " API name, Frequency "
: "API name\t\t\t\tFrequency");
File << "\n";
for (const auto &Elem : SrcAPIStaticsMap) {
std::string APIName = Elem.first;
unsigned int Count = Elem.second;
if (ReportFormat.getValue() == ReportFormatEnum::RFE_CSV) {
File << "\"" << APIName << "\"," << std::to_string(Count) << "\n";
} else {
File << llvm::format("%-30s%16u\n", APIName.c_str(), Count);
}
}
}
}
static void saveStatsReport(clang::tooling::RefactoringTool &Tool,
double Duration) {
printMetrics(Tool);
DpctStats() << "\nTotal migration time: " + std::to_string(Duration) +
" ms\n";
if (ReportFilePrefix == "stdout") {
std::string buf;
llvm::raw_string_ostream OS(buf);
OS << "----------Stats report---------------\n";
OS << getDpctStatsStr() << "\n";
OS << "-------------------------------------\n";
PrintMsg(OS.str());
} else {
std::string RFile = appendPath(
OutRootPath.getCanonicalPath().str(),
ReportFilePrefix + (ReportFormat.getValue() == ReportFormatEnum::RFE_CSV
? ".stats.csv"
: ".stats.log"));
createDirectories(llvm::sys::path::parent_path(RFile));
writeDataToFile(RFile, getDpctStatsStr() + "\n");
}
}
static void saveDiagsReport() {
// DpctDiags() << "\n";
if (ReportFilePrefix == "stdout") {
std::string buf;
llvm::raw_string_ostream OS(buf);
OS << "--------Diags message----------------\n";
OS << getDpctDiagsStr() << "\n";
OS << "-------------------------------------\n";
PrintMsg(OS.str());
} else {
std::string RFile = appendPath(OutRootPath.getCanonicalPath().str(),
ReportFilePrefix + ".diags.log");
createDirectories(llvm::sys::path::parent_path(RFile));
writeDataToFile(RFile, getDpctStatsStr() + "\n");
}
}
std::string printCTVersion() {
std::string buf;
llvm::raw_string_ostream OS(buf);
OS << "\n"
<< TOOL_NAME << " version " << getDpctVersionStr() << "."
<< " Codebase:";
std::string Revision = getClangRevision();
if (!Revision.empty()) {
OS << '(';
if (!Revision.empty()) {
OS << Revision;
}
OS << ").";
}
OS << " clang version " << CLANG_VERSION_MAJOR << "." << CLANG_VERSION_MINOR
<< "." << CLANG_VERSION_PATCHLEVEL << "\n";
return OS.str();
}
static void DumpOutputFile(void) {
// Redirect stdout/stderr output to <file> if option "-output-file" is set
if (!OutputFile.empty()) {
std::string FilePath =
appendPath(OutRootPath.getCanonicalPath().str(), OutputFile);
createDirectories(llvm::sys::path::parent_path(FilePath));
writeDataToFile(FilePath, getDpctTermStr() + "\n");
}
}
void PrintReportOnFault(const std::string &FaultMsg) {
PrintMsg(FaultMsg);
saveApisReport();
saveDiagsReport();
if (ReportFilePrefix == "stdcout")
return;
std::string FileApis = appendPath(
OutRootPath.getCanonicalPath().str(),
ReportFilePrefix + (ReportFormat.getValue() == ReportFormatEnum::RFE_CSV
? ".apis.csv"
: ".apis.log"));
std::string FileDiags = appendPath(OutRootPath.getCanonicalPath().str(),
ReportFilePrefix + ".diags.log");
appendDataToFile(FileApis, FaultMsg);
appendDataToFile(FileDiags, FaultMsg);
DumpOutputFile();
}
void parseFormatStyle() {
StringRef StyleStr = "file"; // DPCTFormatStyle::Custom
if (clang::dpct::DpctGlobalInfo::getFormatStyle() ==
DPCTFormatStyle::FS_Google) {
StyleStr = "google";
} else if (clang::dpct::DpctGlobalInfo::getFormatStyle() ==
DPCTFormatStyle::FS_LLVM) {
StyleStr = "llvm";
}
UnifiedPath StyleSearchPath =
clang::tooling::getFormatSearchPath().getCanonicalPath().empty()
? clang::dpct::DpctGlobalInfo::getInRoot()
: clang::tooling::getFormatSearchPath();
llvm::Expected<clang::format::FormatStyle> StyleOrErr =
clang::format::getStyle(StyleStr, StyleSearchPath.getCanonicalPath(),
"llvm");
clang::format::FormatStyle Style;
if (!StyleOrErr) {
PrintMsg(llvm::toString(StyleOrErr.takeError()) + "\n");
PrintMsg("Using LLVM style as fallback formatting style.\n");
clang::format::FormatStyle FallbackStyle = clang::format::getNoStyle();
getPredefinedStyle("llvm", clang::format::FormatStyle::LanguageKind::LK_Cpp,
&FallbackStyle);
Style = FallbackStyle;
} else {
Style = StyleOrErr.get();
}
DpctGlobalInfo::setCodeFormatStyle(Style);
}
void updateCompatibilityVersionInfo(clang::tooling::UnifiedPath OutRoot,
std::string Major, std::string Minor) {
const std::string CmakeHelpFile =
appendPath(OutRoot.getCanonicalPath().str(), "dpct.cmake");
std::ifstream InFile(CmakeHelpFile);
if (!InFile) {
std::string ErrMsg = "Failed to open file: " + CmakeHelpFile;
ShowStatus(MigrationErrorReadWriteCMakeHelperFile, std::move(ErrMsg));
dpctExit(MigrationErrorReadWriteCMakeHelperFile);
}
const std::string VersionStr = Major + "." + Minor;
const int CompatibilityValue = std::stoi(Major) * 10 + std::stoi(Minor);
std::vector<std::string> Lines;
std::string Line;
bool Inserted = false;
// Constant block of content to insert
const std::vector<std::string> CompatibilityBlock = {
"set(COMPATIBILITY_VERSION " + VersionStr + ")",
"set(COMPATIBILITY_VALUE " + std::to_string(CompatibilityValue) + ")",
"set(COMPATIBILITY_VERSION_MAJOR " + Major + ")",
"set(COMPATIBILITY_VERSION_MINOR " + Minor + ")",
"" // Add an empty line for good format
};
auto isCommentOrEmpty = [](const std::string &Line) {
return Line.empty() || Line[0] == '#';
};
while (std::getline(InFile, Line)) {
// Insert the compatibility definition block after the first comment section
if (!Inserted && !isCommentOrEmpty(Line)) {
Lines.insert(Lines.end(), CompatibilityBlock.begin(),
CompatibilityBlock.end());
Inserted = true;
}
Lines.push_back(Line);
}
InFile.close();
std::ofstream OutFile(CmakeHelpFile);
if (!OutFile) {
std::string ErrMsg = "Failed to write to file: " + CmakeHelpFile;
ShowStatus(MigrationErrorReadWriteCMakeHelperFile, std::move(ErrMsg));
dpctExit(MigrationErrorReadWriteCMakeHelperFile);
}
for (const auto &Line : Lines) {
OutFile << Line << "\n";
}
OutFile.close();
}
static void loadMainSrcFileInfo(clang::tooling::UnifiedPath OutRoot) {
std::string YamlFilePath = appendPath(OutRoot.getCanonicalPath().str(),
DpctGlobalInfo::getYamlFileName());
auto PreTU = std::make_shared<clang::tooling::TranslationUnitReplacements>();
if (llvm::sys::fs::exists(YamlFilePath)) {
if (loadTUFromYaml(YamlFilePath, *PreTU) != 0) {
llvm::errs() << getLoadYamlFailWarning(YamlFilePath);
}
if (MigrateBuildScriptOnly && !DpctGlobalInfo::migratePythonScripts() ||
DpctGlobalInfo::migrateCMakeScripts()) {
std::string Major = PreTU->SDKVersionMajor;
std::string Minor = PreTU->SDKVersionMinor;
if (!Major.empty() && !Minor.empty()) {
updateCompatibilityVersionInfo(OutRoot, Major, Minor);
}
}
}
for (auto &Entry : PreTU->MainSourceFilesDigest) {
if (Entry.HasCUDASyntax)
MainSrcFilesHasCudaSyntex.insert(Entry.MainSourceFile);
}
// Currently, when "--use-experimental-features=device_global" and
// "--use-experimental-features=all" are specified, the migrated code should
// be compiled with C++20 or later.
auto Iter = PreTU->OptionMap.find("ExperimentalFlag");
if (Iter != PreTU->OptionMap.end()) {
if (Iter->second.Specified) {
const std::string Value = Iter->second.Value;
unsigned int UValue = std::stoul(Value);
if (UValue & (1 << static_cast<unsigned>(
ExperimentalFeatures::Exp_DeviceGlobal))) {
LANG_Cplusplus_20_Used = true;
}
}
}
}
void processPathToHelperFunctionAndExit(const char **argv) {
auto FindHelperPath = [&](const char *Cmd) {
SmallString<512> Path;
Path = getInstallPath(Cmd).getCanonicalPath();
llvm::sys::path::append(Path, "include");
if (!llvm::sys::fs::exists(Path))
return false;
else if (UseSYCLCompat) {
auto CompatPath = Path;
llvm::sys::path::append(CompatPath, "syclcompat");
if (!llvm::sys::fs::exists(CompatPath))
return false;
}
DpctLog() << Path << '\n';
return true;
};
auto Ret = MigrationSucceeded;
if (UseSYCLCompat) {
auto Success = FindHelperPath("clang");
Success |= FindHelperPath("icpx");
if (!Success) {
DpctLog() << "SYCLcompat is usually installed in include folder of "
"SYCL compiler.\n";
Ret = MigrationErrorInvalidInstallPath;
}
} else if (!FindHelperPath(argv[0])) {
Ret = MigrationErrorInvalidInstallPath;
}
ShowStatus(Ret, "Helper functions");
dpctExit(Ret);
}
void callIndependentToolAndExit(const std::string IndependentTool, int argc, const char **argv) {
SmallString<512> ExecutableScriptPath(DpctInstallPath.getCanonicalPath());
llvm::sys::path::append(ExecutableScriptPath, "bin", IndependentTool);
if (!llvm::sys::fs::exists(ExecutableScriptPath)) {
ShowStatus(MigrationErrorInvalidInstallPath, IndependentTool + " tool");
dpctExit(MigrationErrorInvalidInstallPath);
}
std::string Python = GetPython();
if (Python.empty()) {
ShowStatus(CallIndependentToolError, "python");
dpctExit(CallIndependentToolError);
}
std::string SystemCallCommand =
Python + " " + std::string(ExecutableScriptPath.str());
for (int Index = 2; Index < argc; Index++) {
SystemCallCommand.append(" ");
SystemCallCommand.append(std::string(argv[Index]));
}
int ProcessExitCode = system(SystemCallCommand.c_str());
if (ProcessExitCode) {
ShowStatus(CallIndependentToolError, std::move(IndependentTool));
dpctExit(CallIndependentToolError);
}
dpctExit(CallIndependentToolSucceeded);
}
void showReportHeader() {
std::string buf;
llvm::raw_string_ostream OS(buf);
OS << "Generate report: "
<< "report-type:"
<< (ReportType.getValue() == ReportTypeEnum::RTE_All
? "all"
: (ReportType.getValue() == ReportTypeEnum::RTE_APIs
? "apis"
: (ReportType.getValue() == ReportTypeEnum::RTE_Stats
? "stats"
: "diags")))
<< ", report-format:"
<< (ReportFormat.getValue() == ReportFormatEnum::RFE_CSV ? "csv"
: "formatted")
<< ", report-file-prefix:" << ReportFilePrefix << "\n";
PrintMsg(OS.str());
}
void checkIncMigrationOrExit() {
if (!MigrateBuildScriptOnly &&
clang::dpct::DpctGlobalInfo::isIncMigration()) {
std::string Msg;
if (!canContinueMigration(Msg)) {
ShowStatus(MigrationErrorDifferentOptSet, Msg);
dpctExit(MigrationErrorDifferentOptSet, false);
}
}
}
int migrateBuildScripts(const clang::tooling::UnifiedPath &InRoot,
const clang::tooling::UnifiedPath &OutRoot) {
if (cmakeScriptNotFound() && pythonBuildScriptNotFound()) {
std::cout << BuildScriptMigrationHelpHint << "\n";
} else {
if (DpctGlobalInfo::migrateCMakeScripts()) {
if (!cmakeScriptNotFound()) {
runWithCrashGuard(
[&]() { doCmakeScriptMigration(InRoot, OutRoot); },
"Error: dpct internal error. Migrating CMake scripts in \"" +
InRootPath.getCanonicalPath().str() +
"\" causing the error skipped. Migration continues.\n");
} else {
std::cout << CmakeScriptMigrationHelpHint << "\n";
}
}
if (DpctGlobalInfo::migratePythonScripts()) {
if (pythonMigrationRulesRegistered() && !pythonBuildScriptNotFound()) {
runWithCrashGuard(
[&]() { doPythonBuildScriptMigration(InRoot, OutRoot); },
"Error: dpct internal error. Migrating Python build scripts in \"" +
InRoot.getCanonicalPath().str() +
"\" causing the error skipped. Migration continues.\n");
} else if (pythonBuildScriptNotFound()) {
std::cout << PythonBuildScriptMigrationHelpHint << "\n";
}
}
}
return MigrationSucceeded;
}
void doBuildScriptMigration() {
loadMainSrcFileInfo(OutRootPath);
collectBuildScripts(InRootPath, OutRootPath);
migrateBuildScripts(InRootPath, OutRootPath);
}
// print APIMapping of Query
int showAPIMapping(StringRef SrcAPI, StringRef Option, RefactoringTool &Tool,
ReplTy &ReplSYCL) {
llvm::outs() << "CUDA API:" << llvm::raw_ostream::GREEN << SrcAPI
<< llvm::raw_ostream::RESET;
DiagnosticsEngine Diagnostics(
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
IntrusiveRefCntPtr<DiagnosticOptions>(new DiagnosticOptions()));
SourceManager Sources(Diagnostics, Tool.getFiles());
LangOptions DefaultLangOptions;
Rewriter Rewrite(Sources, DefaultLangOptions);
// Must be only 1 file.
tooling::applyAllReplacements(ReplSYCL.begin()->second, Rewrite);
const auto &RewriteBuffer = Rewrite.buffer_begin()->second;
static const std::string StartStr{"// Start"};
static const std::string EndStr{"// End"};
std::string MigratedStr{""};
bool Flag = false;
for (auto I = RewriteBuffer.begin(), E = RewriteBuffer.end(); I != E;
I.MoveToNextPiece()) {
size_t StartPos = 0;
if (!Flag) {
if (auto It = I.piece().find(StartStr); It != StringRef::npos) {
StartPos = It + StartStr.length();
Flag = true;
}
}
if (Flag) {
size_t EndPos = I.piece().size();
if (auto It = I.piece().find(EndStr); It != StringRef::npos) {
auto TempStr = I.piece().substr(0, It);
EndPos = TempStr.find_last_of('\n') + 1;
Flag = false;
}
MigratedStr += I.piece().substr(StartPos, EndPos - StartPos);
}
}
// For some cuda error handling APIs (currently only cudaGetErrorString), we
// use NoRewriteRewriter to do migration. So the comment in the argument
// part is kept in the migrated code. We remove those comments here.
// ATTENTION: There is A SPACE at the beginning of each comment.
static const std::unordered_set<std::string> CommentsNeedBeRemoved = {
" /*cudaError_t*/"};
for (const auto &Comment : CommentsNeedBeRemoved) {
size_t RemoveStartPos = MigratedStr.find(Comment);
if (RemoveStartPos != std::string::npos) {
MigratedStr.erase(RemoveStartPos, Comment.length());
break;
}
}
if (MigratedStr.find_first_not_of(" \n") == std::string::npos) {
llvm::outs() << "The API is Removed.\n";
} else {
llvm::outs() << "Is migrated to" << Option << ":" << llvm::raw_ostream::BLUE
<< MigratedStr << llvm::raw_ostream::RESET;
}
return MigrationSucceeded;
}
int runDPCT(int argc, const char **argv) {
isDPCT = true;
if (argc < 2) {
std::cout << CtHelpHint;
return MigrationErrorShowHelp;
}
clang::dpct::initCrashRecovery();
clang::dpct::DpctOptionBase::init();
#if defined(_WIN32)
// To support wildcard "*" in source file name in windows.
llvm::InitLLVM X(argc, argv);
#endif
// Set handle for libclangTooling to process message for dpct
clang::tooling::SetPrintHandle(PrintMsg);
clang::tooling::SetFileSetInCompilationDB(
dpct::DpctGlobalInfo::getFileSetInCompilationDB());
// CommonOptionsParser will adjust argc to the index of "--"
int OriginalArgc = argc;
clang::tooling::SetModuleFiles(dpct::DpctGlobalInfo::getModuleFiles());
#ifdef _WIN32
// Set function handle for libclangTooling to parse vcxproj file.
clang::tooling::SetParserHandle(vcxprojParser);
#endif
llvm::cl::SetVersionPrinter(
[](llvm::raw_ostream &OS) { OS << printCTVersion() << "\n"; });
auto OptParser = CommonOptionsParser::create(argc, argv, CtHelpCatAll,
llvm::cl::OneOrMore);
if (!OptParser) {
if (OptParser.errorIsA<DPCTError>()) {
llvm::Error NewE =
handleErrors(OptParser.takeError(), [](const DPCTError &DE) {
if (DE.EC == -101) {
ShowStatus(MigrationErrorCannotParseDatabase);
dpctExit(MigrationErrorCannotParseDatabase);
} else if (DE.EC == -102) {
ShowStatus(MigrationErrorCannotFindDatabase);
dpctExit(MigrationErrorCannotFindDatabase);
} else {
ShowStatus(MigrationError);
dpctExit(MigrationError);
}
});
}
// Filter and output error messages emitted by clang
auto E =
handleErrors(OptParser.takeError(), [](const llvm::StringError &E) {
DpctLog() << E.getMessage();
});
dpct::ShowStatus(MigrationOptionParsingError);
dpctExit(MigrationOptionParsingError);
}
// Option check: like conflict
DpctOptionBase::check();
if (UseSYCLCompat && USMLevel.getValue() == UsmLevel::UL_None) {
llvm::errs()
<< "Currently SYCLcompat header-only library (syclcompat:: namespace) "
"doesn't support buffer and accessor data management..\n";
ShowStatus(MigrationErrorConflictOptions);
dpctExit(MigrationErrorConflictOptions);
}
DpctInstallPath = getInstallPath(argv[0]);
InRootPath = InRoot;
OutRootPath = OutRoot;
std::string OutRootPathCUDACodepin = "";
CudaIncludePath = CudaInclude;
SDKPath = SDKPathOpt;
std::transform(
RuleFile.begin(), RuleFile.end(),
std::back_insert_iterator<std::vector<clang::tooling::UnifiedPath>>(
RuleFilePath),
[](const std::string &Str) { return clang::tooling::UnifiedPath(Str); });
std::transform(
AnalysisScopeOpt.begin(), AnalysisScopeOpt.end(),
std::back_insert_iterator<std::vector<clang::tooling::UnifiedPath>>(
AnalysisScope),
[](const std::string &Str) { return clang::tooling::UnifiedPath(Str); });
// Action: just show -- --help information and then exit
if (CommonOptionsParser::hasHelpOption(OriginalArgc, argv))
dpctExit(MigrationSucceeded);
// OC_Action
if (PathToHelperFunction) {
processPathToHelperFunctionAndExit(argv);
}
if (!OutputFile.empty()) {
// Set handle for libclangTooling to redirect warning message to DpctTerm
clang::tooling::SetDiagnosticOutput(DpctTerm());
}
initWarningIDs();
#ifndef _WIN32
// OC_Action
if (InterceptBuildCommand)
callIndependentToolAndExit("intercept-build", argc, argv);
#endif
// OC_Action
if (CodePinReport)
callIndependentToolAndExit("codepin-report.py", argc, argv);
if (AnalysisMode)
DpctGlobalInfo::enableAnalysisMode();
// Check Option Values...
validateInputDirectoryLengthOrExit("--in-root", InRootPath);
validateInputDirectoryLengthOrExit("--out-root", OutRootPath);
std::for_each(AnalysisScope.begin(), AnalysisScope.end(),
[](const clang::tooling::UnifiedPath &P) {
validateInputDirectoryLengthOrExit("--analysis-scope-path",
P);
});
validateInputDirectoryLengthOrExit("--cuda-include-path", CudaIncludePath);
validateInputDirectoryLengthOrExit("--output-file", OutputFile);
// Report file prefix is limited to 128, so that <report-type> and
// <report-format> can be extended later
checkOptionLengthLimitOrExit("--report-file-prefix", ReportFilePrefix);
checkSpecialCharsOrExit("--report-file-prefix", ReportFilePrefix);
clock_t StartTime = clock();
if (LimitChangeExtension) {
DpctGlobalInfo::addChangeExtensions(".cu");
DpctGlobalInfo::addChangeExtensions(".cuh");
}
if (InRootPath.getPath().empty() && ProcessAll) {
ShowStatus(MigrationErrorNoExplicitInRoot);
dpctExit(MigrationErrorNoExplicitInRoot);
}
if (MigrateBuildScriptOnly) {
if (InRootPath.getPath().empty() &&
!buildScriptFileSpecified(OptParser->getSourcePathList())) {
ShowStatus(MigrationErrorNoExplicitInRootAndBuildScript);
dpctExit(MigrationErrorNoExplicitInRootAndBuildScript);
}
}
if (!makeInRootCanonicalOrSetDefaults(InRootPath,
OptParser->getSourcePathList())) {
ShowStatus(MigrationErrorInvalidInRootOrOutRoot);
dpctExit(MigrationErrorInvalidInRootOrOutRoot);
}
if (!MigrateBuildScriptOnly) {
int ValidPath = validatePaths(InRootPath, OptParser->getSourcePathList());
if (ValidPath == -1) {
ShowStatus(MigrationErrorInvalidInRootPath);
dpctExit(MigrationErrorInvalidInRootPath);
} else if (ValidPath == -2) {
ShowStatus(MigrationErrorNoFileTypeAvail);
dpctExit(MigrationErrorNoFileTypeAvail);
}
if (buildScriptFileSpecified(OptParser->getSourcePathList())) {
ShowStatus(MigrateBuildScriptOnlyNotSpecifed);
dpctExit(MigrateBuildScriptOnlyNotSpecifed);
}
} else {
// To validate the path of CMake or Python build script file or directory
int ValidPath =
validateBuildScriptPaths(InRootPath, OptParser->getSourcePathList());
if (ValidPath == -1) {
ShowStatus(MigrationErrorInvalidInRootPath);
dpctExit(MigrationErrorInvalidInRootPath);
} else if (ValidPath < -1) {
ShowStatus(MigrationErrorBuildScriptPathInvalid);
dpctExit(MigrationErrorBuildScriptPathInvalid);
}
}
DpctGlobalInfo::setBuildScript(BuildScript.getBits());
bool BuildScriptsSpecified = DpctGlobalInfo::migrateCMakeScripts() ||
DpctGlobalInfo::migratePythonScripts();
if (MigrateBuildScriptOnly) {
if (!BuildScriptsSpecified) {
llvm::errs() << getBuildScriptNotSpecifiedWarning();
auto CMakeSelectionBits = 1 << (unsigned)BuildScriptKind::BS_CMake;
DpctGlobalInfo::setBuildScript(CMakeSelectionBits);
BuildScriptsSpecified = true;
}
} else {
if (BuildScriptsSpecified && !OptParser->getSourcePathList().empty()) {
ShowStatus(MigrateBuildScriptIncorrectUse);
dpctExit(MigrateBuildScriptIncorrectUse);
}
}
int SDKIncPathRes = checkSDKPathOrIncludePath(CudaIncludePath);
if (SDKIncPathRes == -1) {
ShowStatus(MigrationErrorInvalidCudaIncludePath);
dpctExit(MigrationErrorInvalidCudaIncludePath);
} else if (SDKIncPathRes == 0) {
RealSDKIncludePath = CudaIncludePath.getCanonicalPath();
HasSDKIncludeOption = true;
}
int SDKPathRes = checkSDKPathOrIncludePath(SDKPath);
if (SDKPathRes == -1) {
ShowStatus(MigrationErrorInvalidCudaIncludePath);
dpctExit(MigrationErrorInvalidCudaIncludePath);
} else if (SDKPathRes == 0) {
RealSDKPath = SDKPath.getCanonicalPath();
HasSDKPathOption = true;
}
bool GenReport = false;
#ifdef DPCT_DEBUG_BUILD
std::string &DVerbose = DiagsContent;
#else
std::string DVerbose = "";
#endif
if (!checkReportArgs(ReportType.getValue(), ReportFormat.getValue(),
ReportFilePrefix, ReportOnly, GenReport, DVerbose)) {
ShowStatus(MigrationErrorInvalidReportArgs);
dpctExit(MigrationErrorInvalidReportArgs);
}
if (GenReport)
showReportHeader();
ExtraIncPaths = OptParser->getExtraIncPathList();
if (isCUDAHeaderRequired()) {
// TODO: implement one of this for each source language.
CudaPath = getCudaInstallPath(OriginalArgc, argv);
DpctDiags() << "Cuda Include Path found: " << CudaPath.getCanonicalPath()
<< "\n";
}
// set source code
std::vector<std::string> SourcePathList;
if (QueryAPIMapping.getNumOccurrences()) {
if (QueryAPIMapping.getNumOccurrences() > 1) {
llvm::outs()
<< "Warning: Option --query-api-mapping is specified multi times, "
"only the last one is used, all other are ignored.\n";
}
// Set a virtual file for --query-api-mapping.
llvm::SmallString<16> VirtFolderSS;
llvm::sys::path::system_temp_directory(/*ErasedOnReboot=*/true, VirtFolderSS);
UnifiedPath VirtFolderPath(VirtFolderSS);
// Need set a virtual path and it will used by AnalysisScope.
InRootPath = VirtFolderPath;