-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathAnalysisInfo.cpp
More file actions
7635 lines (7368 loc) · 285 KB
/
AnalysisInfo.cpp
File metadata and controls
7635 lines (7368 loc) · 285 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
//===--------------- AnalysisInfo.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 "AnalysisInfo.h"
#include "Diagnostics/Diagnostics.h"
#include "MigrationReport/Statics.h"
#include "RuleInfra/ExprAnalysis.h"
#include "RuleInfra/MapNames.h"
#include "RulesLang/MapNamesLang.h"
#include "RulesMathLib/MapNamesRandom.h"
#include "TextModification.h"
#include "Utility.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/OperationKinds.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Tooling/Core/UnifiedPath.h"
#include "clang/Tooling/Tooling.h"
#include <algorithm>
#include <deque>
#include <optional>
#include <string>
#define TYPELOC_CAST(Target) static_cast<const Target &>(TL)
llvm::StringRef getReplacedName(const clang::NamedDecl *D) {
auto Iter = clang::dpct::MapNames::TypeNamesMap.find(D->getQualifiedNameAsString(false));
if (Iter != clang::dpct::MapNames::TypeNamesMap.end()) {
auto Range = clang::dpct::getDefinitionRange(D->getBeginLoc(), D->getEndLoc());
for (auto ItHeader = Iter->second->Includes.begin();
ItHeader != Iter->second->Includes.end(); ItHeader++) {
clang::dpct::DpctGlobalInfo::getInstance().insertHeader(Range.getBegin(),
*ItHeader);
}
return Iter->second->NewName;
}
return llvm::StringRef();
}
namespace clang {
extern std::function<bool(SourceLocation)> IsInAnalysisScopeFunc;
extern std::function<unsigned int()> GetRunRound;
extern std::function<void(SourceLocation, unsigned)> RecordTokenSplit;
namespace dpct {
///// global variable definition /////
std::vector<std::pair<HeaderType, std::string>> HeaderSpellings;
static const std::string RegexPrefix = "{{NEEDREPLACE", RegexSuffix = "}}";
///// global function definition /////
void initHeaderSpellings() {
HeaderSpellings = {
#define HEADER(Name, Spelling) {HT_##Name, Spelling},
#include "RulesInclude/HeaderTypes.inc"
};
}
const std::string &getDefaultString(HelperFuncType HFT) {
const static std::string NullString;
switch (HFT) {
case clang::dpct::HelperFuncType::HFT_DefaultQueue: {
const static std::string DefaultQueue =
DpctGlobalInfo::useNoQueueDevice()
? DpctGlobalInfo::getGlobalQueueName()
: DpctGlobalInfo::getDefaultQueueFreeFuncCall();
return DefaultQueue;
}
case clang::dpct::HelperFuncType::HFT_DefaultQueuePtr: {
const static std::string DefaultQueue =
DpctGlobalInfo::useNoQueueDevice()
? DpctGlobalInfo::getGlobalQueueName()
: (DpctGlobalInfo::useSYCLCompat()
? buildString(MapNames::getDpctNamespace() +
"get_current_device().default_queue()")
: buildString(
"&", DpctGlobalInfo::getDefaultQueueFreeFuncCall()));
return DefaultQueue;
}
case clang::dpct::HelperFuncType::HFT_CurrentDevice: {
const static std::string DefaultDevice =
DpctGlobalInfo::useNoQueueDevice()
? DpctGlobalInfo::getGlobalDeviceName()
: MapNames::getDpctNamespace() + "get_current_device()";
return DefaultDevice;
}
case clang::dpct::HelperFuncType::HFT_InitValue: {
return NullString;
}
}
clang::dpct::DpctDebugs()
<< "[HelperFuncType] Unexpected value: "
<< static_cast<std::underlying_type_t<HelperFuncType>>(HFT) << "\n";
assert(0);
return NullString;
}
std::string getStringForRegexDefaultQueueAndDevice(HelperFuncType HFT,
int Index) {
if (HFT == HelperFuncType::HFT_DefaultQueue ||
HFT == HelperFuncType::HFT_DefaultQueuePtr ||
HFT == HelperFuncType::HFT_CurrentDevice) {
if (DpctGlobalInfo::getDeviceChangedFlag() ||
!DpctGlobalInfo::getUsingDRYPattern()) {
return getDefaultString(HFT);
}
auto HelperFuncReplInfoIter =
DpctGlobalInfo::getHelperFuncReplInfoMap().find(Index);
if (HelperFuncReplInfoIter ==
DpctGlobalInfo::getHelperFuncReplInfoMap().end()) {
return getDefaultString(HFT);
}
std::string CounterKey =
HelperFuncReplInfoIter->second.DeclLocFile.getCanonicalPath().str() +
":" + std::to_string(HelperFuncReplInfoIter->second.DeclLocOffset);
auto TempVariableDeclCounterIter =
DpctGlobalInfo::getTempVariableDeclCounterMap().find(CounterKey);
if (TempVariableDeclCounterIter ==
DpctGlobalInfo::getTempVariableDeclCounterMap().end()) {
return getDefaultString(HFT);
}
return TempVariableDeclCounterIter->second
.PlaceholderStr[static_cast<int>(HFT)];
}
return "";
}
template <class T>
void removeDuplicateVar(GlobalMap<T> &VarMap,
std::unordered_set<std::string> &VarNames) {
auto Itr = VarMap.begin();
while (Itr != VarMap.end()) {
if (VarNames.find(Itr->second->getName()) == VarNames.end()) {
VarNames.insert(Itr->second->getName());
++Itr;
} else {
Itr = VarMap.erase(Itr);
}
}
}
template <class CallT>
bool deduceTemplateArguments(const CallT *C, const FunctionTemplateDecl *FTD,
std::vector<TemplateArgumentInfo> &TAIList) {
if (!FTD)
return false;
if (!DpctGlobalInfo::isInAnalysisScope(FTD->getBeginLoc()))
return false;
auto &TemplateParmsList = *FTD->getTemplateParameters();
if (TAIList.size() == TemplateParmsList.size())
return true;
if (TAIList.size() > TemplateParmsList.size())
return false;
TAIList.resize(TemplateParmsList.size());
auto ArgItr = C->arg_begin();
auto ParmItr = FTD->getTemplatedDecl()->param_begin();
while (ArgItr != C->arg_end() &&
ParmItr != FTD->getTemplatedDecl()->param_end()) {
deduceTemplateArgument(TAIList, *ArgItr, *ParmItr);
++ArgItr;
++ParmItr;
}
for (size_t i = 0; i < TAIList.size(); ++i) {
auto &Arg = TAIList[i];
if (!Arg.isNull())
continue;
auto TemplateParm = TemplateParmsList.getParam(i);
if (auto TTPD = dyn_cast<TemplateTypeParmDecl>(TemplateParm)) {
if (TTPD->hasDefaultArgument()) {
if (auto TSI = TTPD->getDefaultArgument().getTypeSourceInfo()) {
Arg.setAsType(TSI->getTypeLoc());
}
}
} else if (auto NTTPD = dyn_cast<NonTypeTemplateParmDecl>(TemplateParm)) {
if (NTTPD->hasDefaultArgument()) {
if (auto TSI = NTTPD->getDefaultArgument().getTypeSourceInfo()) {
Arg.setAsType(TSI->getTypeLoc());
}
}
}
}
return false;
}
template <class CallT>
bool deduceTemplateArguments(const CallT *C, const FunctionDecl *FD,
std::vector<TemplateArgumentInfo> &TAIList) {
if (FD)
return deduceTemplateArguments(C, FD->getPrimaryTemplate(), TAIList);
return false;
}
template <class CallT>
bool deduceTemplateArguments(const CallT *C, const NamedDecl *ND,
std::vector<TemplateArgumentInfo> &TAIList) {
if (!ND)
return false;
if (auto FTD = dyn_cast<FunctionTemplateDecl>(ND)) {
return deduceTemplateArguments(C, FTD, TAIList);
} else if (auto FD = dyn_cast<FunctionDecl>(ND)) {
return deduceTemplateArguments(C, FD, TAIList);
} else if (auto UD = dyn_cast<UsingShadowDecl>(ND)) {
return deduceTemplateArguments(C, UD->getUnderlyingDecl(), TAIList);
}
return false;
}
SourceLocation getActualInsertLocation(SourceLocation InsertLoc,
const SourceManager &SM,
const LangOptions &LO) {
do {
if (InsertLoc.isFileID())
return InsertLoc;
if (SM.isAtEndOfImmediateMacroExpansion(InsertLoc.getLocWithOffset(
Lexer::MeasureTokenLength(SM.getSpellingLoc(InsertLoc), SM, LO)))) {
// If InsertLoc is at the end of macro definition, continue to find
// immediate expansion. example: #define BBB int bbb #define CALL foo(int
// aaa, BBB) The insert location should be at the end of BBB instead of
// the end of bbb.
InsertLoc = SM.getImmediateExpansionRange(InsertLoc).getBegin();
} else if (SM.isMacroArgExpansion(InsertLoc)) {
// If is macro argument, continue to find if argument is macro or written
// code.
// example:
// #define BBB int b, int c = 0
// #define CALL(x) foo(int aaa, x)
// CALL(BBB)
InsertLoc = SM.getImmediateSpellingLoc(InsertLoc);
} else {
// Else return insert location directly,
return InsertLoc;
}
} while (true);
return InsertLoc;
}
template <class TargetType>
std::shared_ptr<TargetType> makeTextureObjectInfo(const ValueDecl *D,
bool IsKernelCall) {
if (IsKernelCall) {
if (auto VD = dyn_cast<VarDecl>(D)) {
return std::make_shared<TargetType>(VD);
}
} else if (const auto *PVD = dyn_cast<ParmVarDecl>(D);
PVD && PVD->getTypeSourceInfo()) {
return std::make_shared<TargetType>(PVD);
}
return std::shared_ptr<TargetType>();
}
bool isModuleFunction(const FunctionDecl *FD) {
auto &SM = DpctGlobalInfo::getSourceManager();
return FD->getLanguageLinkage() == CLanguageLinkage &&
FD->hasAttr<CUDAGlobalAttr>() &&
DpctGlobalInfo::getModuleFiles().find(
DpctGlobalInfo::getLocInfo(SM.getExpansionLoc(FD->getBeginLoc()))
.first) != DpctGlobalInfo::getModuleFiles().end();
}
void processTypeLoc(const TypeLoc &TL, ExprAnalysis &EA,
const SourceManager &SM) {
EA.analyze(TL);
if (EA.hasReplacement()) {
DpctGlobalInfo::getInstance().addReplacement(
std::make_shared<ExtReplacement>(SM, &TL, EA.getReplacedString(),
nullptr));
}
EA.applyAllSubExprRepl();
}
HelperFuncCatalog getQueueKind() {
if (DpctGlobalInfo::useSYCLCompat()) {
return HelperFuncCatalog::GetDefaultQueue;
}
if (DpctGlobalInfo::getUsmLevel() == UsmLevel::UL_Restricted) {
return HelperFuncCatalog::GetInOrderQueue;
}
return HelperFuncCatalog::GetOutOfOrderQueue;
}
///// class FreeQueriesInfo /////
class FreeQueriesInfo {
public:
enum FreeQueriesKind {
NdItem = 0,
Group,
SubGroup,
End,
};
static constexpr char FreeQueriesRegexCh = 'F';
private:
static constexpr unsigned KindBits = 4;
static constexpr unsigned KindMask = (1 << KindBits) - 1;
static constexpr unsigned MacroShiftBits = KindBits;
static constexpr unsigned MacroMask = 1 << MacroShiftBits;
static constexpr unsigned IndexShiftBits = MacroShiftBits + 1;
private:
struct FreeQueriesNames {
std::string NonFreeQueriesName;
std::string FreeQueriesFuncName;
std::string ExtraVariableName;
};
struct MacroInfo {
clang::tooling::UnifiedPath FilePath;
unsigned Offset;
unsigned Dimension = 0;
std::vector<unsigned> Infos;
};
static std::vector<std::shared_ptr<FreeQueriesInfo>> InfoList;
static std::vector<std::shared_ptr<MacroInfo>> MacroInfos;
clang::tooling::UnifiedPath FilePath;
unsigned ExtraDeclLoc = 0;
unsigned Counter[FreeQueriesKind::End] = {0};
std::string Indent;
std::string NL;
std::shared_ptr<DeviceFunctionInfo> FuncInfo;
unsigned Dimension = 3;
std::set<unsigned> Refs;
unsigned Idx = 0;
static const FreeQueriesNames &getNames(FreeQueriesKind);
static std::shared_ptr<FreeQueriesInfo> getInfo(const FunctionDecl *);
template <typename T>
static typename std::enable_if<std::is_same_v<T, unsigned> ||
std::is_same_v<T, std::string>>::type
printFreeQueriesFunctionName(llvm::raw_ostream &OS, FreeQueriesKind K,
T Dimension) {
OS << getNames(K).FreeQueriesFuncName;
if (K != FreeQueriesKind::SubGroup) {
OS << '<';
if constexpr (std::is_same_v<T, unsigned>) {
if (Dimension) {
OS << Dimension;
} else {
OS << "dpct_placeholder /* Fix the dimension manually */";
}
} else {
OS << Dimension;
}
OS << '>';
}
OS << "()";
}
static FreeQueriesKind getKind(unsigned Num) {
return static_cast<FreeQueriesKind>(Num & KindMask);
}
static unsigned getIndex(unsigned Num) { return Num >> IndexShiftBits; }
static bool isMacro(unsigned Num) { return Num & MacroMask; }
static unsigned getRegexNum(unsigned Idx, bool IsMacro,
FreeQueriesKind Kind) {
return static_cast<unsigned>((Idx << IndexShiftBits) |
(IsMacro * MacroMask) | (Kind & KindMask));
}
void emplaceExtraDecl();
void printImmediateText(llvm::raw_ostream &, SourceLocation, FreeQueriesKind);
std::string getReplaceString(FreeQueriesKind K);
public:
static void reset() {
InfoList.clear();
MacroInfos.clear();
}
template <class Node>
static void printImmediateText(llvm::raw_ostream &, const Node *,
const FunctionDecl *, FreeQueriesKind);
static void buildInfo() {
for (auto &Info : InfoList)
Info->emplaceExtraDecl();
for (auto &Info : MacroInfos) {
Info->Dimension = InfoList[Info->Infos.front()]->Dimension;
for (auto Idx : Info->Infos) {
if (Info->Dimension != InfoList[Idx]->Dimension) {
Info->Dimension = 0;
DiagnosticsUtils::report(Info->FilePath, Info->Offset,
Diagnostics::FREE_QUERIES_DIMENSION, true,
false);
break;
}
}
}
}
static std::string getReplaceString(unsigned Num);
FreeQueriesInfo() = default;
};
///// class RnnBackwardFuncInfoBuilder /////
class RnnBackwardFuncInfoBuilder {
std::vector<RnnBackwardFuncInfo> &RBFuncInfo;
std::vector<RnnBackwardFuncInfo> ValidBackwardDataFuncInfo;
std::vector<RnnBackwardFuncInfo> ValidBackwardWeightFuncInfo;
std::vector<std::shared_ptr<ExtReplacement>> Repls;
using InfoIter = std::vector<RnnBackwardFuncInfo>::iterator;
public:
RnnBackwardFuncInfoBuilder(std::vector<RnnBackwardFuncInfo> &Infos)
: RBFuncInfo(Infos){};
// This function check if the RNN function input referenced between
// backwarddata and backwardweight functiona call.
bool isInputNotChanged(InfoIter Data, InfoIter Weight) {
for (auto &RnnInput : Data->RnnInputDeclLoc) {
auto &RnnInputRefs =
DpctGlobalInfo::getRnnInputMap()[RnnInput][Data->FilePath];
for (auto &RnnInputRef : RnnInputRefs) {
if ((RnnInputRef > (Data->Offset + Data->Length - 1)) &&
RnnInputRef < Weight->Offset) {
return false;
}
}
}
return true;
}
// This function check if the backwarddata and backwardweight function
// call have same input.
bool isInputSame(InfoIter Data, InfoIter Weight) {
for (unsigned InputIndex = 0; InputIndex < 3; InputIndex++) {
if (Data->RnnInputDeclLoc[InputIndex] !=
Weight->RnnInputDeclLoc[InputIndex]) {
return false;
}
}
return true;
}
// This function check if the backwarddata and backwardweight function in
// the same scope and backwardweight called after backwarddata.
// For example, function will return ture for pattern in following pseudo
// code:
// if(...) {
// backwarddata(...);
// ..
// backwardweight(...);
// }
bool isValidScopeAndOrder(InfoIter Data, InfoIter Weight) {
return !((Data->CompoundLoc != Weight->CompoundLoc) &&
(Data->Offset >= Weight->Offset));
}
void build() {
if (RBFuncInfo.empty()) {
return;
}
for (auto &Info : RBFuncInfo) {
if (Info.isDataGradient) {
ValidBackwardDataFuncInfo.emplace_back(Info);
} else {
ValidBackwardWeightFuncInfo.emplace_back(Info);
}
}
std::vector<int> WeightPairdFlag(ValidBackwardWeightFuncInfo.size(), 0);
auto DataBegin = ValidBackwardDataFuncInfo.begin();
auto DataEnd = ValidBackwardDataFuncInfo.end();
auto WeightBegin = ValidBackwardWeightFuncInfo.begin();
auto WeightEnd = ValidBackwardWeightFuncInfo.end();
for (auto DataIter = DataBegin; DataIter != DataEnd; DataIter++) {
bool DataPaired = false;
for (auto WeightIter = WeightBegin; WeightIter != WeightEnd;
WeightIter++) {
if (isInputNotChanged(DataIter, WeightIter) &&
isInputSame(DataIter, WeightIter) &&
isValidScopeAndOrder(DataIter, WeightIter)) {
DataPaired = true;
WeightPairdFlag[WeightIter - WeightBegin] = 1;
auto Repl = generateReplacement(DataIter, WeightIter);
Repls.insert(Repls.end(), Repl.begin(), Repl.end());
break;
}
}
if (!DataPaired) {
DiagnosticsUtils::report(DataIter->FilePath, DataIter->Offset,
Diagnostics::API_NOT_MIGRATED, true, false,
"cudnnRNNBackwardData_v8");
}
}
for (auto WeightIter = WeightBegin; WeightIter != WeightEnd; WeightIter++) {
if (!WeightPairdFlag[WeightIter - WeightBegin]) {
DiagnosticsUtils::report(WeightIter->FilePath, WeightIter->Offset,
Diagnostics::API_NOT_MIGRATED, true, false,
"cudnnRNNBackwardWeights_v8");
}
}
}
std::vector<std::shared_ptr<ExtReplacement>> getReplacement() {
return Repls;
}
std::vector<std::shared_ptr<ExtReplacement>>
generateReplacement(InfoIter Data, InfoIter Weight) {
std::vector<std::shared_ptr<ExtReplacement>> Repls;
std::ostringstream DataRepl, WeightRepl;
RnnBackwardFuncInfo &DataFuncInfo = *Data;
RnnBackwardFuncInfo &WeightFuncInfo = *Weight;
requestFeature(HelperFeatureEnum::device_ext);
Diagnostics WarningType;
if (WeightFuncInfo.isAssigned) {
WarningType = Diagnostics::FUNC_CALL_REMOVED_0;
WeightRepl << "0";
} else {
WarningType = Diagnostics::FUNC_CALL_REMOVED;
}
DiagnosticsUtils::report(
WeightFuncInfo.FilePath, WeightFuncInfo.Offset, WarningType, true,
false, "cudnnRNNBackwardWeights_v8",
"this call and cudnnRNNBackwardData_v8 are migrated to a single "
"function call async_rnn_backward");
if (DataFuncInfo.isAssigned) {
DataRepl << MapNames::getCheckErrorMacroName() << "(";
requestFeature(HelperFeatureEnum::device_ext);
}
DataRepl << DataFuncInfo.FuncArgs[0] << ".async_rnn_backward("
<< DataFuncInfo.FuncArgs[1];
// Combine 21 args from backwarddata and 2 args from backwardweight
// into args of async_rnn_backward.
for (unsigned int index = 3; index <= 21; index++) {
DataRepl << ", " << DataFuncInfo.FuncArgs[index];
if (index == 6) {
DataRepl << ", " << WeightFuncInfo.FuncArgs[0];
} else if (index == 17) {
DataRepl << ", " << WeightFuncInfo.FuncArgs[1];
}
}
if (DataFuncInfo.isAssigned) {
DataRepl << "))";
} else {
DataRepl << ")";
}
Repls.emplace_back(std::make_shared<ExtReplacement>(
DataFuncInfo.FilePath, DataFuncInfo.Offset, DataFuncInfo.Length,
DataRepl.str(), nullptr));
Repls.emplace_back(std::make_shared<ExtReplacement>(
WeightFuncInfo.FilePath, WeightFuncInfo.Offset, WeightFuncInfo.Length,
WeightRepl.str(), nullptr));
return Repls;
}
};
///// class EventSyncTypeInfo /////
void EventSyncTypeInfo::buildInfo(clang::tooling::UnifiedPath FilePath,
unsigned int Offset) {
if (NeedReport)
DiagnosticsUtils::report(FilePath, Offset,
Diagnostics::NOERROR_RETURN_COMMA_OP, true, false);
if (IsAssigned && ReplText.empty()) {
ReplText = "0";
}
DpctGlobalInfo::getInstance().addReplacement(std::make_shared<ExtReplacement>(
FilePath, Offset, Length, ReplText, nullptr));
}
///// class TimeStubTypeInfo /////
void TimeStubTypeInfo::buildInfo(clang::tooling::UnifiedPath FilePath,
unsigned int Offset, bool isReplTxtWithSB) {
if (isReplTxtWithSB)
DpctGlobalInfo::getInstance().addReplacement(
std::make_shared<ExtReplacement>(FilePath, Offset, Length, StrWithSB,
nullptr));
else
DpctGlobalInfo::getInstance().addReplacement(
std::make_shared<ExtReplacement>(FilePath, Offset, Length, StrWithoutSB,
nullptr));
}
///// class BuiltinVarInfo /////
void BuiltinVarInfo::buildInfo(clang::tooling::UnifiedPath FilePath,
unsigned int Offset, unsigned int ID) {
std::string R = Repl + std::to_string(ID) + ")";
DpctGlobalInfo::getInstance().addReplacement(
std::make_shared<ExtReplacement>(FilePath, Offset, Len, R, nullptr));
}
///// class ParameterStream /////
ParameterStream &ParameterStream::operator<<(const std::string &InputParamStr) {
if (InputParamStr.size() == 0) {
return *this;
}
if (!FormatInformation.EnableFormat) {
// append the string directly
Str = Str + InputParamStr;
return *this;
}
if (FormatInformation.IsAllParamsOneLine) {
// all parameters are in one line
Str = Str + ", " + InputParamStr;
return *this;
}
if (FormatInformation.IsEachParamNL) {
// each parameter is in a single line
Str = Str + "," + getNL() + FormatInformation.NewLineIndentStr +
InputParamStr;
return *this;
}
// parameters will be inserted in one line unless the line length > column
// limit.
if (FormatInformation.CurrentLength + 2 + (int)InputParamStr.size() <=
ColumnLimit) {
Str = Str + ", " + InputParamStr;
FormatInformation.CurrentLength =
FormatInformation.CurrentLength + 2 + InputParamStr.size();
return *this;
} else {
Str = Str + std::string(",") + getNL() +
FormatInformation.NewLineIndentStr + InputParamStr;
FormatInformation.CurrentLength =
FormatInformation.NewLineIndentLength + InputParamStr.size();
return *this;
}
}
ParameterStream &ParameterStream::operator<<(int InputInt) {
return *this << std::to_string(InputInt);
}
///// class DpctFileInfo /////
void DpctFileInfo::buildReplacements() {
if (!isInAnalysisScope())
return;
if (FilePath.getCanonicalPath().empty())
return;
// Traverse all the global variables stored one by one to check if its name
// is same with normal global variable's name in host side, if the one is
// found, postfix "_ct" is added to this __constant__ symbol's name.
std::unordered_map<unsigned int, std::string> ReplUpdated;
for (const auto &Entry : MemVarMap) {
if (Entry.second->isIgnore() || !Entry.second->isConstant() ||
Entry.second->isUseDeviceGlobal())
continue;
auto Name = Entry.second->getName();
auto &GlobalVarNameSet = dpct::DpctGlobalInfo::getGlobalVarNameSet();
if (GlobalVarNameSet.find(Name) != end(GlobalVarNameSet)) {
Entry.second->setName(Name + "_ct");
}
std::string Repl = Entry.second->getDeclarationReplacement(nullptr);
auto FilePath = Entry.second->getFilePath();
auto Offset = Entry.second->getNewConstVarOffset();
auto Length = Entry.second->getNewConstVarLength();
auto &ReplText = ReplUpdated[Offset];
if (!ReplText.empty()) {
ReplText += getNL() + Repl;
} else {
ReplText = Repl;
}
auto R = std::make_shared<ExtReplacement>(FilePath, Offset, Length,
ReplText, nullptr);
addReplacement(R);
}
for (auto &Kernel : KernelMap)
Kernel.second->addReplacements();
for (auto &BuiltinVar : BuiltinVarInfoMap) {
auto Ptr = MemVarMap::getHeadWithoutPathCompression(
&(BuiltinVar.second.DFI->getVarMap()));
if (DpctGlobalInfo::getAssumedNDRangeDim() == 1 && Ptr) {
unsigned int ID = (Ptr->Dim == 1) ? 0 : 2;
BuiltinVar.second.buildInfo(FilePath, BuiltinVar.first, ID);
} else {
BuiltinVar.second.buildInfo(FilePath, BuiltinVar.first, 2);
}
}
for (auto &AtomicInfo : AtomicMap) {
if (std::get<2>(AtomicInfo.second))
DiagnosticsUtils::report(getFilePath(), std::get<0>(AtomicInfo.second),
Diagnostics::API_NOT_OCCURRED_IN_AST, true, true,
std::get<1>(AtomicInfo.second));
}
for (auto &DescInfo : EventSyncTypeMap) {
DescInfo.second.buildInfo(FilePath, DescInfo.first);
}
const auto &TimeStubBounds = getTimeStubBounds();
if (TimeStubBounds.empty()) {
for (auto &DescInfo : TimeStubTypeMap) {
DescInfo.second.buildInfo(FilePath, DescInfo.first,
/*bool isReplTxtWithSB*/ true);
}
} else {
for (auto &DescInfo : TimeStubTypeMap) {
bool isReplTxtWithSB = isReplTxtWithSubmitBarrier(DescInfo.first);
DescInfo.second.buildInfo(FilePath, DescInfo.first, isReplTxtWithSB);
}
}
buildRnnBackwardFuncInfo();
// insert header file of user defined rules
std::string InsertHeaderStr;
llvm::raw_string_ostream HeaderOS(InsertHeaderStr);
if (!InsertedHeaders.empty()) {
HeaderOS << getNL();
}
for (auto &HeaderStr : InsertedHeaders) {
if (HeaderStr[0] != '<' && HeaderStr[0] != '"') {
HeaderStr = "\"" + HeaderStr + "\"";
}
HeaderOS << "#include " << HeaderStr << getNL();
}
HeaderOS.flush();
insertHeader(std::move(InsertHeaderStr), LastIncludeOffset);
std::string InsertHeaderStrCUDA;
llvm::raw_string_ostream HeaderOSCUDA(InsertHeaderStrCUDA);
for (auto &HeaderStr : InsertedHeadersCUDA) {
if (HeaderStr[0] != '<' && HeaderStr[0] != '"') {
HeaderStr = "\"" + HeaderStr + "\"";
}
HeaderOSCUDA << getNL() << "#include " << HeaderStr;
}
HeaderOSCUDA.flush();
insertHeader(std::move(InsertHeaderStrCUDA), LastIncludeOffset, IP_Left,
RT_CUDAWithCodePin);
FreeQueriesInfo::buildInfo();
// This loop need to be put at the end of DpctFileInfo::buildReplacements.
// In addReplacement() the insertHeader() may be invoked, so the size of
// vector IncludeDirectiveInsertions may increase.
// So here cannot use for loop like "for(auto e : vec)" since the iterator may
// be invalid due to the allocation of new storage.
for (size_t I = 0, End = IncludeDirectiveInsertions.size(); I < End; I++) {
auto IncludeDirective = IncludeDirectiveInsertions[I];
bool IsInExternC = false;
unsigned int NewInsertLocation = 0;
for (auto &ExternCRange : ExternCRanges) {
if (IncludeDirective->getOffset() >= ExternCRange.first &&
IncludeDirective->getOffset() <= ExternCRange.second) {
IsInExternC = true;
NewInsertLocation = ExternCRange.first;
break;
}
}
if (IsInExternC) {
IncludeDirective->setOffset(NewInsertLocation);
}
addReplacement(IncludeDirective);
// Update the End since the size may be changed.
End = IncludeDirectiveInsertions.size();
}
}
void DpctFileInfo::setKernelCallDim() {
for (auto &Kernel : KernelMap)
Kernel.second->setKernelCallDim();
}
void DpctFileInfo::setKernelDim() {
for (auto &DeviceFunc : FuncMap) {
auto Info = DeviceFunc.second->getFuncInfo();
if (Info->isKernel() && !Info->isKernelInvoked()) {
Info->getVarMap().Dim = 3;
}
}
}
void DpctFileInfo::buildUnionFindSet() {
for (auto &Kernel : KernelMap)
Kernel.second->buildUnionFindSet();
}
void DpctFileInfo::buildUnionFindSetForUncalledFunc() {
for (auto &DeviceFunc : FuncMap) {
auto Info = DeviceFunc.second->getFuncInfo();
Info->buildInfo();
constructUnionFindSetRecursively(Info);
}
}
void DpctFileInfo::buildKernelInfo() {
for (auto &Kernel : KernelMap)
Kernel.second->buildInfo();
for (auto &D : FuncMap) {
if (auto I = D.second->getFuncInfo())
I->buildInfo();
}
}
void DpctFileInfo::buildRnnBackwardFuncInfo() {
RnnBackwardFuncInfoBuilder Builder(RBFuncInfo);
Builder.build();
for (auto &Repl : Builder.getReplacement()) {
addReplacement(Repl);
}
}
void DpctFileInfo::postProcess() {
if (!isInAnalysisScope())
return;
for (auto &D : FuncMap)
D.second->emplaceReplacement();
if (!ReplsSYCL->empty()) {
ReplsSYCL->postProcess();
if (DpctGlobalInfo::getRunRound() == 0) {
auto &CacheEntry =
DpctGlobalInfo::getInstance().getFileReplCache()[FilePath];
CacheEntry.first = ReplsCUDA;
CacheEntry.second = ReplsSYCL;
}
}
}
void DpctFileInfo::emplaceReplacements(
std::map<clang::tooling::UnifiedPath, tooling::Replacements> &ReplSet) {
if (!ReplsSYCL->empty())
ReplsSYCL->emplaceIntoReplSet(ReplSet[FilePath]);
}
void DpctFileInfo::addReplacement(std::shared_ptr<ExtReplacement> Repl) {
if (Repl->getLength() == 0 && Repl->getReplacementText().empty())
return;
if (Repl->IsForCodePin)
ReplsCUDA->addReplacement(Repl);
else
ReplsSYCL->addReplacement(Repl);
}
bool DpctFileInfo::isInAnalysisScope() {
return DpctGlobalInfo::isInAnalysisScope(FilePath);
}
void DpctFileInfo::setFileEnterOffset(unsigned Offset) {
auto MF = DpctGlobalInfo::getInstance().getMainFile();
if (!HasInclusionDirectiveSet.count(MF)) {
FirstIncludeOffset[MF] = Offset;
LastIncludeOffset = Offset;
}
}
void DpctFileInfo::setFirstIncludeOffset(unsigned Offset) {
auto MF = DpctGlobalInfo::getInstance().getMainFile();
if (!HasInclusionDirectiveSet.count(MF)) {
FirstIncludeOffset[MF] = Offset;
LastIncludeOffset = Offset;
HasInclusionDirectiveSet.insert(std::move(MF));
}
}
void DpctFileInfo::setHeaderInserted(HeaderType Header) {
DpctGlobalInfo::getHeaderInsertedBitMap()[FilePath][Header] = true;
}
void DpctFileInfo::setMathHeaderInserted(bool B) {
DpctGlobalInfo::getHeaderInsertedBitMap()[FilePath][HeaderType::HT_Math] = B;
}
void DpctFileInfo::setAlgorithmHeaderInserted(bool B) {
DpctGlobalInfo::getHeaderInsertedBitMap()[FilePath]
[HeaderType::HT_Algorithm] = B;
}
void DpctFileInfo::setTimeHeaderInserted(bool B) {
DpctGlobalInfo::getHeaderInsertedBitMap()[FilePath][HeaderType::HT_Time] = B;
}
void DpctFileInfo::concatHeader(llvm::raw_string_ostream &OS) {}
template <class FirstT, class... Args>
void DpctFileInfo::concatHeader(llvm::raw_string_ostream &OS, FirstT &&First,
Args &&...Arguments) {
appendString(OS, "#include ", std::forward<FirstT>(First), getNL());
concatHeader(OS, std::forward<Args>(Arguments)...);
}
std::optional<HeaderType> DpctFileInfo::findHeaderType(StringRef Header) {
auto Pos = llvm::find_if(
HeaderSpellings, [=](const std::pair<HeaderType, StringRef> &p) -> bool {
return p.second == Header;
});
if (Pos == std::end(HeaderSpellings))
return std::nullopt;
return Pos->first;
}
StringRef DpctFileInfo::getHeaderSpelling(HeaderType Value) {
if (Value < NUM_HEADERS)
return HeaderSpellings[Value].second;
// Only assertion in debug
assert(false && "unknown HeaderType");
return "";
}
void DpctFileInfo::insertHeader(HeaderType Type, unsigned Offset,
ReplacementType IsForCodePin) {
if (Type == HT_DPL_Algorithm || Type == HT_DPL_Execution || Type == HT_SYCL) {
if (auto MF = DpctGlobalInfo::getInstance().getMainFile())
if (this != MF.get() && FirstIncludeOffset.count(MF)) {
DpctGlobalInfo::getInstance().getMainFile()->insertHeader(
Type, FirstIncludeOffset.at(MF));
}
}
if (DpctGlobalInfo::getHeaderInsertedBitMap()[FilePath][Type])
return;
DpctGlobalInfo::getHeaderInsertedBitMap()[FilePath][Type] = true;
std::string ReplStr;
llvm::raw_string_ostream OS(ReplStr);
std::string MigratedMacroDefinitionStr;
llvm::raw_string_ostream MigratedMacroDefinitionOS(
MigratedMacroDefinitionStr);
switch (Type) {
// The #include of <oneapi/dpl/execution> and <oneapi/dpl/algorithm> were
// previously added here. However, due to some unfortunate include
// dependencies introduced with the PSTL/TBB headers from the gcc-9.3.0
// include files, those two headers must now be included before the
// <sycl/sycl.hpp> are included, so the FileInfo is set to hold a boolean
// that'll indicate whether to insert them when the #include <sycl/sycl.cpp>
// is added later
case HT_DPL_Algorithm:
case HT_DPL_Execution:
concatHeader(OS, getHeaderSpelling(Type));
if (auto Iter = FirstIncludeOffset.find(
DpctGlobalInfo::getInstance().getMainFile());
Iter != FirstIncludeOffset.end())
insertHeader(OS.str(), Iter->second, InsertPosition::IP_AlwaysLeft);
return;
case HT_SYCL:
// Add the label for profiling macro "DPCT_PROFILING_ENABLED", which will be
// replaced by "#define DPCT_PROFILING_ENABLED" or not in the post
// replacement.
if (DpctGlobalInfo::useExtLevelZero())
OS << "#define ONEAPI_BACKEND_LEVEL_ZERO_EXT" << getNL();
OS << "{{NEEDREPLACEP0}}";
if (DpctGlobalInfo::getUsmLevel() == UsmLevel::UL_None)
OS << "#define DPCT_USM_LEVEL_NONE" << getNL();
concatHeader(OS, getHeaderSpelling(Type));
if (DpctGlobalInfo::useSYCLCompat()) {
concatHeader(OS, getHeaderSpelling(HT_COMPAT_SYCLcompat));
DpctGlobalInfo::getHeaderInsertedBitMap()[FilePath]
[HT_COMPAT_SYCLcompat] = true;
} else {
concatHeader(OS, getHeaderSpelling(HT_DPCT_Dpct));
DpctGlobalInfo::getHeaderInsertedBitMap()[FilePath][HT_DPCT_Dpct] = true;
}
DpctGlobalInfo::printUsingNamespace(OS);
if (DpctGlobalInfo::useNoQueueDevice()) {
static bool Flag = true;
auto SourceFileType = GetSourceFileType(getFilePath());
if (Flag && (SourceFileType == SPT_CudaSource ||
SourceFileType == SPT_CppSource)) {
OS << MapNames::getClNamespace() << "device "
<< DpctGlobalInfo::getGlobalDeviceName()
<< "(sycl::default_selector_v);" << getNL();
// Now the UsmLevel must not be UL_None here.
OS << MapNames::getClNamespace() << "queue "
<< DpctGlobalInfo::getGlobalQueueName() << "("
<< DpctGlobalInfo::getGlobalDeviceName() << ", "
<< MapNames::getClNamespace() << "property_list{"
<< MapNames::getClNamespace() << "property::queue::in_order()";
// replaced to insert "property::queue::enable_profiling()" or not
// in the post replacement.
OS << "{{NEEDREPLACEI0}}";
OS << "});" << getNL();
Flag = false;
} else {
OS << "extern " << MapNames::getClNamespace() << "device "
<< DpctGlobalInfo::getGlobalDeviceName() << ";" << getNL();
// Now the UsmLevel must not be UL_None here.
OS << "extern " << MapNames::getClNamespace() << "queue "
<< DpctGlobalInfo::getGlobalQueueName() << ";" << getNL();
}
}
if (auto Iter = FirstIncludeOffset.find(
DpctGlobalInfo::getInstance().getMainFile());
Iter != FirstIncludeOffset.end())
insertHeader(OS.str(), Iter->second, InsertPosition::IP_Left);
if (!RTVersionValue.empty())
MigratedMacroDefinitionOS << "#define DPCT_COMPAT_RT_VERSION "
<< RTVersionValue << getNL();
if (!MajorVersionValue.empty())
MigratedMacroDefinitionOS << "#define DPCT_COMPAT_RT_MAJOR_VERSION "
<< MajorVersionValue << getNL();
if (!MinorVersionValue.empty())
MigratedMacroDefinitionOS << "#define DPCT_COMPAT_RT_MINOR_VERSION "
<< MinorVersionValue << getNL();
if (!CCLVerValue.empty())
MigratedMacroDefinitionOS << "#define DPCT_COMPAT_CCL_VERSION "
<< CCLVerValue << getNL();
insertHeader(MigratedMacroDefinitionOS.str(), FileBeginOffset,
InsertPosition::IP_AlwaysLeft);
for (const auto &File :
DpctGlobalInfo::getCustomHelperFunctionAddtionalIncludes()) {
if (auto Iter = FirstIncludeOffset.find(
DpctGlobalInfo::getInstance().getMainFile());
Iter != FirstIncludeOffset.end())
if (!File.empty() && File[0] == '<')
insertHeader("#include " + File + getNL(), Iter->second,
InsertPosition::IP_Right);
else
insertHeader("#include \"" + File + "\"" + getNL(), Iter->second,
InsertPosition::IP_Right);
}
return;
// Because <dpct/dpl_utils.hpp> includes <oneapi/dpl/execution> and
// <oneapi/dpl/algorithm>, so we have to make sure that
// <oneapi/dpl/execution> and <oneapi/dpl/algorithm> are inserted before
// <sycl/sycl.hpp>
// e.g.
// #include <sycl/sycl.hpp>
// #include <dpct/dpct.hpp>
// #include <dpct/dpl_utils.hpp>
// ...
// This will cause compilation error due to onedpl header dependence