-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhalf2_rewrite.cpp
1517 lines (1359 loc) · 61.1 KB
/
half2_rewrite.cpp
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
#include <sstream>
#include <string>
#include <vector> //for stack + info storage
#include <iostream>
#include <fstream>
#include <algorithm>
#include <stdio.h> //for getting file fd
#include "clang/Lex/Lexer.h" //for getting source code from the AST.
#include "clang/Basic/SourceLocation.h"
#include "clang/AST/AST.h"
#include "clang/AST/ParentMap.h"//for getting parent of a node
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_MODE false
#define HALF2_OVERLOAD_HEADER "half2_operator_overload.cuh"
#define HALF_OVERLOAD_HEADER "half_operator_overload.cuh"
//define half2 api here (with open parenthesis), in case Nvidia may change the API later.
#define HALF2_ADD "__hadd2("
#define HALF2_SUB "__hsub2("
#define HALF2_MUL "__hmul2("
#define HALF2_DIV "h2div("
#define FLOAT2HALF2 "__float2half2_rn("
#define HALF2_NEG "h2neg(" //math api doesn't have, need to append the implementation to the code.
//compare ops
#define HALF2_LT "__hlt2("
#define HALF2_LE "__hle2("
#define HALF2_EQ "__heq2("
#define HALF2_NE "__hne2("
#define HALF2_GT "__hgt2("
#define HALF2_GE "__hge2("
//math funcs
#define HALF2_COS "h2cos("
#define HALF2_SIN "h2sin("
#define HALF2_EXP "h2exp("
#define HALF2_EXP10 "h2exp10("
#define HALF2_EXP2 "h2exp2("
#define HALF2_LOG "h2log("
#define HALF2_LOG10 "h2log10("
#define HALF2_LOG2 "h2log2("
#define HALF2_RSQRT "h2rsqrt("
#define HALF2_SQRT "h2sqrt("
#define HALF2_ABS "h2abs("
//half version without simd
#define HALF_ADD "__hadd("
#define HALF_SUB "__hsub("
#define HALF_MUL "__hmul("
#define HALF_DIV "hdiv("
#define FLOAT2HALF "__float2half("
#define HALF_NEG "hneg(" //math api doesn't have, need to append the implementation to the code.
//compare ops
#define HALF_LT "__hlt("
#define HALF_LE "__hle("
#define HALF_EQ "__heq("
#define HALF_NE "__hne("
#define HALF_GT "__hgt("
#define HALF_GE "__hge("
//math funcs
#define HALF_COS "hcos("
#define HALF_SIN "hsin("
#define HALF_EXP "hexp("
#define HALF_EXP10 "hexp10("
#define HALF_EXP2 "hexp2("
#define HALF_LOG "hlog("
#define HALF_LOG10 "hlog10("
#define HALF_LOG2 "hlog2("
#define HALF_RSQRT "hrsqrt("
#define HALF_SQRT "hsqrt("
#define HALF_ABS "habs("
//end half version
//mathfunc float
#define FLOAT_DIV "fdividef("
#define FLOAT_COS "cosf("
#define FLOAT_SIN "sinf("
#define FLOAT_EXP "expf("
#define FLOAT_EXP10 "exp10f("
#define FLOAT_EXP2 "exp2f("
#define FLOAT_LOG "logf("
#define FLOAT_LOG10 "log10f("
#define FLOAT_LOG2 "log2f("
#define FLOAT_RSQRT "rsqrtf("
#define FLOAT_SQRT "sqrtf("
#define FLOAT_ABS "fabsf("
//mathfunc double
#define DOUBLE_COS "cos("
#define DOUBLE_SIN "sin("
#define DOUBLE_EXP "exp("
#define DOUBLE_EXP10 "exp10("
#define DOUBLE_EXP2 "exp2("
#define DOUBLE_LOG "log("
#define DOUBLE_LOG10 "log10("
#define DOUBLE_LOG2 "log2("
#define DOUBLE_RSQRT "rsqrt("
#define DOUBLE_SQRT "sqrt("
#define DOUBLE_ABS "fabs("
using namespace clang;
using namespace clang::driver;
using namespace clang::tooling;
using namespace llvm;
using namespace std;
static llvm::cl::OptionCategory ToolingSampleCategory("Tooling Sample");
//global variables to store variables info (type )/ can be read from a config file or be automatically detected by the tool
//rule to store vars: pair them with their parent function varname*****function_name. global vars => pair *****global
vector<pair<string,string> > IndexVars; //variables used for thread index
vector<pair<string,string> > NoThreadVars; //possible var used for identifying number of threads in device code: if (idx< n) {do sthing} else {do nothing}
vector<pair<string,string> > half2Vars; // variable are in half2 precision. due to complication of conversion from floating point literal to half2. there may be some constant/var decl need to be in float.
vector<pair<int,int> > if_stmt_linenumber; // <start_line,end_line> of an if/else condition, to keep track of divergence cuda code
vector<pair<int,IfStmt*> > if_stmt_endline;// <end_line, if_stmt pointer> of an if/else condition, to write post_process masking code & update translator's context
bool func_overload_mode = true; //in func_overload_mode, we use func overload header to rewrite half2 & half operations
bool half2_mode = true;
string half_type_string = "__half2";
bool first_statement = true;
// By implementing RecursiveASTVisitor, we can specify which AST nodes
// we're interested in by overriding relevant methods.
class MyASTVisitor : public RecursiveASTVisitor<MyASTVisitor> {
public:
MyASTVisitor(Rewriter &R,ASTContext *Context) : TheRewriter(R), Context(Context), CurrentFunc(nullptr), CudaCode(false){
currentIfLineNumber = make_pair(0,0);
currentElseLineNumber = make_pair(0,0);
insideIfCond = false;
insideElseBranch = false;
}
void removeCharsFromString( string &str, char* charsToRemove ) {
for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
}
}
bool IsFloatingPointType(string typeStr){
return (typeStr.find("double") != string::npos) || (typeStr.find("float") != string::npos);
}
bool IsIntegerType(string typeStr){
return (typeStr.find("int") != string::npos) || (typeStr.find("long") != string::npos);
}
bool IsThreadIDRelated(string expr){
return (expr.find("blockIdx") != string::npos) || (expr.find("blockDim") != string::npos)|| (expr.find("threadIdx") != string::npos);
}
bool IsHalf2Var(string varName){
pair<string,string> elementToFind1;
pair<string,string> elementToFind2;
pair<string,string> elementToFind3;
elementToFind1 = make_pair(varName, "");
elementToFind3 = make_pair(varName, varName); //for function
if (CurrentFunc!=nullptr)
elementToFind2 = make_pair(varName, CurrentFunc->getNameAsString());
else elementToFind2 = elementToFind1;
if((std::find(half2Vars.begin(), half2Vars.end(), elementToFind1) != half2Vars.end()) ||(std::find(half2Vars.begin(), half2Vars.end(), elementToFind2) != half2Vars.end()) ||(std::find(half2Vars.begin(), half2Vars.end(), elementToFind3) != half2Vars.end()))
return true ;
else return false;
}
bool IsThreadIdVar(string varName){
pair<string,string> elementToFind1;
pair<string,string> elementToFind2;
pair<string,string> elementToFind3;
elementToFind1 = make_pair(varName, "");
if (CurrentFunc!=nullptr)
elementToFind2 = make_pair(varName, CurrentFunc->getNameAsString());
else elementToFind2 = elementToFind1;
if((std::find(IndexVars.begin(), IndexVars.end(), elementToFind1) != IndexVars.end()) ||(std::find(IndexVars.begin(), IndexVars.end(), elementToFind2) != IndexVars.end()))
return true ;
else return false;
}
bool isProcessingFunction(string functionName){ //there are many aux function in cuda headers & clang headers for cuda. must filter it out, only process our target functions
return IsHalf2Var(functionName);
}
bool IsHalf2Expr(Expr* expr){
//cout<<"IsHalf2Expr " <<"\n";
Expr* exprIgnoreParensCasts = expr->IgnoreImpCasts()->IgnoreParens ();
//exprIgnoreParensCasts->dump();
if(isa <ArraySubscriptExpr> (exprIgnoreParensCasts ) || isa <DeclRefExpr>(exprIgnoreParensCasts ) || isa <UnaryOperator>(exprIgnoreParensCasts ) ){
// cout<<"inside if " <<"\n";
DeclRefExpr* declExpr = nullptr;
if (isa <ArraySubscriptExpr> (exprIgnoreParensCasts)){
ArraySubscriptExpr* subscriptExpr = cast<ArraySubscriptExpr>(exprIgnoreParensCasts);
if (isa <ArraySubscriptExpr>(subscriptExpr->getBase()->IgnoreImpCasts()))
subscriptExpr = cast<ArraySubscriptExpr>(subscriptExpr->getBase()->IgnoreImpCasts());
if (isa <DeclRefExpr> (subscriptExpr->getBase()->IgnoreImpCasts()))
declExpr = cast <DeclRefExpr> (subscriptExpr->getBase()->IgnoreImpCasts());
} else if (isa <UnaryOperator> (exprIgnoreParensCasts)){ //only the case *var when var is a pointer to a floating var
UnaryOperator * unaryOp = cast <UnaryOperator>(exprIgnoreParensCasts);
if(unaryOp->getOpcode() == UO_Deref)
exprIgnoreParensCasts = unaryOp->getSubExpr()->IgnoreCasts()->IgnoreImpCasts ();
}
if(isa <DeclRefExpr>(exprIgnoreParensCasts))
declExpr = cast <DeclRefExpr> (exprIgnoreParensCasts);
//subscriptExpr->dump();
if (declExpr!=nullptr){
string baseSrc = declExpr-> getDecl ()-> getNameAsString();
// cout<<"IsHalf2Expr not " << baseSrc<< " Is half2: "<<IsHalf2Var(baseSrc) <<"\n";
//if (IsHalf2Var(baseSrc)&& CurrentFunc==nullptr) return true;
//if (!IsHalf2Var(baseSrc)) return true; //ofc
return IsHalf2Var(baseSrc);
}
}
return false;
}
string getSourceTextFromSourceRange(SourceRange* sourceRange ){
return Lexer::getSourceText(CharSourceRange::getCharRange(*sourceRange),Context->getSourceManager(),LangOptions(), 0);
}
SourceRange* getSourceRangeIgnoreArrayRef(Expr* expr){ //return a source range of array name, in this way, we can retrieve it later e.g. expr = z[i] -> return sourcerange of the character "z"
if(DEBUG_MODE)
cout<<"getSourceRangeIgnoreArrayRef " <<"\n";
Expr* exprIgnoreParensCasts = expr->IgnoreImpCasts()->IgnoreParens ();
//exprIgnoreParensCasts->dump();
if(isa <ArraySubscriptExpr> (exprIgnoreParensCasts ) || isa <DeclRefExpr>(exprIgnoreParensCasts ) || isa <UnaryOperator>(exprIgnoreParensCasts ) ){
//cout<<"inside if " <<"\n";
DeclRefExpr* declExpr = nullptr;
if (isa <ArraySubscriptExpr> (exprIgnoreParensCasts)){
ArraySubscriptExpr* subscriptExpr = cast<ArraySubscriptExpr>(exprIgnoreParensCasts);
if (isa <ArraySubscriptExpr>(subscriptExpr->getBase()->IgnoreImpCasts()))
subscriptExpr = cast<ArraySubscriptExpr>(subscriptExpr->getBase()->IgnoreImpCasts());
if (isa <DeclRefExpr> (subscriptExpr->getBase()->IgnoreImpCasts()))
declExpr = cast <DeclRefExpr> (subscriptExpr->getBase()->IgnoreImpCasts());
} else if (isa <UnaryOperator> (exprIgnoreParensCasts)){ //only the case *var when var is a pointer to a floating var
UnaryOperator * unaryOp = cast <UnaryOperator>(exprIgnoreParensCasts);
if(unaryOp->getOpcode() == UO_Deref)
exprIgnoreParensCasts = unaryOp->getSubExpr()->IgnoreCasts()->IgnoreImpCasts ();
}
if(isa <DeclRefExpr>(exprIgnoreParensCasts))
declExpr = cast <DeclRefExpr> (exprIgnoreParensCasts);
//subscriptExpr->dump();
if (declExpr!=nullptr){
//string baseSrc = declExpr-> getDecl ()-> getNameAsString();
SourceLocation startLoc = declExpr->getLocStart ();
SourceLocation endLoc = declExpr->getLocEnd ();
// cout<<"IsHalf2Expr not " << baseSrc<< " Is half2: "<<IsHalf2Var(baseSrc) <<"\n";
//if (IsHalf2Var(baseSrc)&& CurrentFunc==nullptr) return true;
//if (!IsHalf2Var(baseSrc)) return true; //ofc
return new SourceRange (startLoc,endLoc );
} else return nullptr;
} else{ //no special case, treat like usual z_val => return range of z_val;
return new SourceRange(exprIgnoreParensCasts->getLocStart(), exprIgnoreParensCasts->getLocEnd());
}
}
void RewriteFunctionCall(CallExpr* E){
if(func_overload_mode)
return;
string funcName = Lexer::getSourceText(CharSourceRange::getCharRange(E->getLocStart(), E->getArg(0)->getLocStart()),Context->getSourceManager(),LangOptions(), 0);
int replaceLength = funcName.length();
removeCharsFromString( funcName, "_ " );
if(DEBUG_MODE)
cout<<"rewriteFunccall "<<funcName<<" " <<replaceLength<<"\n";
string replaceString = "";
if (funcName == FLOAT_DIV)
replaceString = half2_mode?HALF2_DIV:HALF_DIV;
else if (funcName==FLOAT_COS || funcName==DOUBLE_COS)
replaceString = half2_mode?HALF2_COS:HALF_COS;
else if (funcName==FLOAT_SIN || funcName==DOUBLE_SIN)
replaceString = half2_mode?HALF2_SIN:HALF_SIN;
else if (funcName==FLOAT_EXP || funcName==DOUBLE_EXP)
replaceString = half2_mode?HALF2_EXP:HALF_EXP;
else if (funcName==FLOAT_EXP10 || funcName==DOUBLE_EXP10)
replaceString = half2_mode?HALF2_EXP10:HALF_EXP10;
else if (funcName==FLOAT_EXP2 || funcName==DOUBLE_EXP2)
replaceString = half2_mode?HALF2_EXP2:HALF_EXP2;
else if (funcName==FLOAT_LOG || funcName==DOUBLE_LOG)
replaceString = half2_mode?HALF2_LOG:HALF_LOG;
else if (funcName==FLOAT_LOG10 || funcName==DOUBLE_LOG10)
replaceString = half2_mode?HALF2_LOG10:HALF_LOG10;
else if (funcName==FLOAT_LOG2 || funcName==DOUBLE_LOG2)
replaceString = half2_mode?HALF2_LOG2:HALF_LOG2;
else if (funcName==FLOAT_RSQRT || funcName==DOUBLE_RSQRT)
replaceString = half2_mode?HALF2_RSQRT:HALF_RSQRT;
else if (funcName==FLOAT_SQRT || funcName==DOUBLE_SQRT)
replaceString = half2_mode?HALF2_SQRT:HALF_SQRT;
else if (funcName==FLOAT_ABS || funcName==DOUBLE_ABS)
replaceString = half2_mode?HALF2_ABS:HALF_ABS;
if (replaceString!=""){
TheRewriter.ReplaceText(E->getLocStart(), replaceLength, replaceString);
}
return;
}
string insertStringBeforeChar(string target, string insert_str, string search_str){ //insert string before the first occurence of char
string result_str = ""+ target;
int insertPosition = result_str.find_first_of(search_str);
if(insertPosition== -1)
insertPosition = result_str.length();
result_str.insert(insertPosition,insert_str );
return result_str;
}
template <typename T>
void insertToVectorIfNotExist(vector<T> &vector_x, T val){
if (std::find(vector_x.begin(), vector_x.end(), val) == vector_x.end()) {
// someName not in name, add it
vector_x.push_back(val);
}
return;
}
string processAssignPreIff(IfStmt* ifStatement){
// cout <<"xxxxxxxxx"<<"processAssignPreIff"<<"\n";
stringstream ssResult;
for(string var : lhsMaskedInIffCond) {
string temp_var = proccessArrayRefStr(var);
ssResult << insertStringBeforeChar(temp_var,"_masked_"+ to_string(currentIfLineNumber.first), "[");
ssResult << " = "<<var << ";\n";
}
if (!lhsMaskedInElseCond.empty()){
for(string var : lhsMaskedInElseCond) {
string temp_var = proccessArrayRefStr(var);
ssResult << insertStringBeforeChar(temp_var,"_masked_"+ to_string(currentIfLineNumber.first), "[");
ssResult << "_else = "<<var << ";\n";
}
}
if(DEBUG_MODE)
cout<<ssResult.str() ;
//~ return "";
return ssResult.str();
}
string processAssignPostIff(IfStmt* ifStatement){
stringstream ssResult;
for (int i = 0; i<2; i++){
ssResult << "if((short*)&mask_if_"+ to_string(currentIfLineNumber.first) +"["<<i<<"]) { \n";
for(string var : lhsMaskedInIffCond) {
string temp_var = proccessArrayRefStr(var);
ssResult << insertStringBeforeChar("((__half*)&"+var,")",string ("[")); //var is the unmodified string
ssResult << "["<<i<<"] = ((__half*)&"+ temp_var +"_masked_"+ to_string(currentIfLineNumber.first)+ ")["<<i<<"] ;\n";
}
ssResult <<"}\n";
if (!lhsMaskedInElseCond.empty()){
ssResult <<"else{\n";
for(string var : lhsMaskedInElseCond) {
string temp_var = proccessArrayRefStr(var);
ssResult << insertStringBeforeChar("((__half*)&"+var,")",string ("["));
ssResult << "["<<i<<"] = ((__half*)&"+ temp_var +"_masked_"+ to_string(currentIfLineNumber.first)+ "_else)["<<i<<"] ;\n";
}
ssResult <<"}\n";
}
}
lhsMaskedInIffCond.clear();
lhsMaskedInElseCond.clear();
return ssResult.str();
}
string processCondStmtinIff(IfStmt* ifStatement){ //return processed cond statement for calculating mask e.g. if (x > 2) is the iffstmt at line no 32, return mask_id_32 = __hgt2(x, __float2half_rm(2.0));
Expr* CondExpr = ifStatement->getCond();
if (isa<BinaryOperator>(CondExpr))
{
BinaryOperator* binaryOp= dyn_cast<BinaryOperator>(CondExpr);
Expr* LHS = binaryOp->getLHS();
Expr* RHS = binaryOp->getRHS();
SourceRange LHSRange = LHS->getSourceRange();
LHSRange.setEnd(LHS->getLocEnd ().getLocWithOffset(1));
SourceRange RHSRange = RHS->getSourceRange();
RHSRange.setEnd(RHS->getLocEnd ().getLocWithOffset(1));
string leftString = "";
string rightString = "";
LHS -> dump();
RHS -> dump();
if (IsHalf2Expr (LHS))
leftString = getSourceTextFromSourceRange(&LHSRange);
else{
if (isa<IntegerLiteral>(LHS->IgnoreImpCasts()->IgnoreCasts()->IgnoreParens())) {
IntegerLiteral* intLiteral = dyn_cast<IntegerLiteral>(LHS->IgnoreImpCasts()->IgnoreCasts()->IgnoreParens());
leftString = half2_mode?FLOAT2HALF2:FLOAT2HALF +to_string(intLiteral->getValue().getLimitedValue ()) + ")";
} else if (isa<FloatingLiteral>(LHS->IgnoreImpCasts()->IgnoreCasts()->IgnoreParens())){
FloatingLiteral* floatLiteral = dyn_cast<FloatingLiteral>(LHS->IgnoreImpCasts()->IgnoreCasts()->IgnoreParens());
float fltEvalResult = 0.0;
if (APFloat::semanticsSizeInBits(floatLiteral->getValue().getSemantics()) == 64) //detect double the ugly way
fltEvalResult = (float) floatLiteral->getValue().convertToDouble () ;
else
fltEvalResult = floatLiteral->getValue().convertToFloat();
leftString = half2_mode?FLOAT2HALF2:FLOAT2HALF +to_string(fltEvalResult) + ")";
}else{
leftString = "complex expr, to be developed";
}
}
if (IsHalf2Expr (RHS))
rightString = getSourceTextFromSourceRange(&RHSRange);
else{
if (isa<IntegerLiteral>(RHS->IgnoreImpCasts()->IgnoreCasts()->IgnoreParens())) {
IntegerLiteral* intLiteral = dyn_cast<IntegerLiteral>(RHS->IgnoreImpCasts()->IgnoreCasts()->IgnoreParens());
rightString = half2_mode?FLOAT2HALF2:FLOAT2HALF +to_string(intLiteral->getValue().getLimitedValue ()) + ")";
} else if (isa<FloatingLiteral>(RHS->IgnoreImpCasts()->IgnoreCasts()->IgnoreParens())){
FloatingLiteral* floatLiteral = dyn_cast<FloatingLiteral>(RHS->IgnoreImpCasts()->IgnoreCasts()->IgnoreParens());
float fltEvalResult = 0.0;
if (APFloat::semanticsSizeInBits(floatLiteral->getValue().getSemantics()) == 64) //detect double the ugly way
fltEvalResult = (float) floatLiteral->getValue().convertToDouble () ;
else
fltEvalResult = floatLiteral->getValue().convertToFloat();
rightString = half2_mode?FLOAT2HALF2:FLOAT2HALF +to_string(fltEvalResult) + ")";
}else{
rightString = "complex expr, to be developed";
}
}
string result = "";
if(DEBUG_MODE)
cout<<"aaa " <<leftString <<" " << rightString<<" \n";
switch(binaryOp->getOpcode()){
case BO_LT:
result = half2_mode?HALF2_LT:HALF_GT + leftString + "," + rightString + ");\n";
break;
case BO_GT:
result = half2_mode?HALF2_GT:HALF_GT + leftString + "," + rightString + ");\n";
break;
case BO_EQ:
result = half2_mode?HALF2_EQ:HALF_EQ + leftString + "," + rightString + ");\n";
break;
case BO_NE:
result = half2_mode?HALF2_NE:HALF_NE+ leftString + "," + rightString + ");\n";
break;
case BO_LE:
result = half2_mode?HALF2_LE:HALF_LE + leftString + "," + rightString + ");\n";
break;
case BO_GE:
result = half2_mode?HALF2_GE:HALF_GE + leftString + "," + rightString + ");\n";
break;
default:
break;
}
return half_type_string+" mask_if_"+ to_string(currentIfLineNumber.first) + " = " + result;
} else return "";
}
string proccessArrayRefStr(string arrayRef){ //e.g. z_array[i] -> z_array_i
string result = "" + arrayRef;
int foundBracket = result.find("[");
if (foundBracket!= -1){
result.replace(foundBracket,1,"_");
removeCharsFromString(result,"["); //remove extra square brackets
removeCharsFromString(result,"]");
}
return result;
}
string addMaskForExpr(Expr* expr, bool notFound = false){ //add suffix _masked to a var if it present in the lhsMaskedInIffCond list, set notFound= true to rewrite anyway (dont check if found or not)
SourceRange * sourceRange = getSourceRangeIgnoreArrayRef(expr);
sourceRange->setEnd (sourceRange->getEnd().getLocWithOffset(1));
string lhsSource = "";
SourceRange fullRange = expr->getSourceRange();
fullRange.setEnd(fullRange.getEnd().getLocWithOffset(1));
if(isa <DeclRefExpr>(expr->IgnoreImpCasts()->IgnoreParens ())){
DeclRefExpr* declExpr = cast <DeclRefExpr> (expr->IgnoreImpCasts()->IgnoreParens ());
lhsSource = declExpr->getDecl()->getNameAsString ();
}else
lhsSource = getSourceTextFromSourceRange(&fullRange);//need to include x[i] with x
//~ string lhsSource = getSourceTextFromSourceRange(sourceRange);
if(DEBUG_MODE){
cout <<lhsSource<<" lhs source \n";
// lhsSource = proccessArrayRefStr(lhsSource);
// cout <<lhsSource<<" lhs source processed\n";
for(int i=0; i<lhsMaskedInIffCond.size(); ++i)
std::cout << lhsMaskedInIffCond[i] << ' ';
cout <<"\n";
}
if (( find(lhsMaskedInIffCond.begin(), lhsMaskedInIffCond.end(), lhsSource) != lhsMaskedInIffCond.end() ) ||notFound) {
//sthing strange here, need to reduce offset for correct string
//sourceRange->setEnd (sourceRange->getEnd().getLocWithOffset(-1));
//~ TheRewriter.InsertTextBefore(sourceRange->getEnd().getLocWithOffset(1), "_masked");
sourceRange->setEnd (sourceRange->getEnd().getLocWithOffset(-1));
string lhsSourceProcessed = proccessArrayRefStr(lhsSource) + "_masked_" + to_string(currentIfLineNumber.first);
if (insideElseBranch)
lhsSourceProcessed += "_else";
TheRewriter.ReplaceText(fullRange,lhsSourceProcessed);
// TheRewriter.InsertTextAfterToken(Context->getSourceManager().getExpansionLoc(sourceRange->getEnd()), "_masked_" + to_string(currentIfLineNumber.first)); //prevent duplicating with other iffs
if(DEBUG_MODE)
cout<<"added mask "<<lhsSource <<" \n";
}
//~ if (insideElseBranch)
//~ return lhsSource+ "_else";
return lhsSource;
}
void RewriteBinaryOp(SourceLocation leftLocation, SourceLocation rightLocation, BinaryOperator *E){
//Context->getSourceManager().getExpansionLoc() is used in case macro ID is included
//any case
if(!insideIfCond && func_overload_mode)
return;
if (insideIfCond && (E->getOpcode()!= BO_Assign)){
addMaskForExpr(E->getLHS());
addMaskForExpr(E->getRHS());
}
switch(E->getOpcode()){
case BO_AddAssign:
case BO_Add:
TheRewriter.InsertText(Context->getSourceManager().getExpansionLoc(leftLocation) ,half2_mode?HALF2_ADD:HALF_ADD);
break;
case BO_SubAssign:
case BO_Sub:
TheRewriter.InsertText(Context->getSourceManager().getExpansionLoc(leftLocation) ,half2_mode?HALF2_SUB:HALF_SUB);
break;
case BO_MulAssign:
case BO_Mul:
TheRewriter.InsertText(Context->getSourceManager().getExpansionLoc(leftLocation ),half2_mode?HALF2_MUL:HALF_MUL);
break;
case BO_DivAssign:
case BO_Div :
TheRewriter.InsertText(Context->getSourceManager().getExpansionLoc(leftLocation) ,half2_mode?HALF2_DIV:HALF_DIV);
break;
case BO_Assign:
if(DEBUG_MODE)
cout<<"rewrite binary op Assign "<<insideIfCond<<"\n";
if (insideIfCond){ //note down LHS to a vector, retrieve later
//~ SourceRange * sourceRange = getSourceRangeIgnoreArrayRef(E->getLHS());
//~ TheRewriter.InsertTextAfterToken(Context->getSourceManager().getExpansionLoc(sourceRange->getEnd()), "_masked");
//~ string lhsSource = getSourceTextFromSourceRange(sourceRange);
string lhsSource = addMaskForExpr(E->getLHS(),true);
if(DEBUG_MODE)
cout<<"added "<<lhsSource <<" to lhsMaskedInIffCond list";
//~ lhsMaskedInIffCond.push_back(lhsSource);
if (insideElseBranch)
insertToVectorIfNotExist(lhsMaskedInElseCond, lhsSource);
else
insertToVectorIfNotExist(lhsMaskedInIffCond, lhsSource);
//add the LHS sign to a list
}
return;//dont add , and ) at the end of this sw
break;// never happens
default:
return; //dont modify the source code for other ops. // need case =
}
TheRewriter.ReplaceText(E->getOperatorLoc(), E->getOpcodeStr().size(), ",");
TheRewriter.InsertTextAfterToken(Context->getSourceManager().getExpansionLoc(rightLocation), ")");
}
void RewriteLiterals(Expr* E){ //E can be floatingliteral, or any float-casted literals/function result
//simple mode , treat all literals are float. Integer will be automaticly casted to float by nvcc
// E->dump();
if(!insideIfCond && func_overload_mode)
return;
if (isa<CastExpr>(E)){
CastExpr* castExpr = cast<CastExpr>(E);
if(DEBUG_MODE){
cout << "rewrite literal cast expr \n";
// if (!(isa<FloatingLiteral>(castExpr->getSubExpr()) || isa<IntegerLiteral>(castExpr->getSubExpr())) )
// return; //not literals, more complex funcall, or arrayref ... doing nothing.
cout << "rewrite literal cast expr is cast literal \n";
}
}
TheRewriter.InsertText(Context->getSourceManager().getExpansionLoc(E->getLocStart ()), half2_mode?FLOAT2HALF2:FLOAT2HALF);
TheRewriter.InsertTextAfterToken(Context->getSourceManager().getExpansionLoc(E->getLocEnd ()), ")");
}
void RewriteUnaryOp(UnaryOperator * E){ //handle - (h2neg(x) call if x is not literal value)
TheRewriter.ReplaceText(E->getOperatorLoc(), 1, " ");
TheRewriter.InsertText(E->getOperatorLoc(),half2_mode?HALF2_NEG:HALF_NEG);
TheRewriter.InsertTextAfterToken(E->getLocEnd(), ")");
}
void RewriteFunctionDecl(FunctionDecl* F){
TheRewriter.ReplaceText(F->getReturnTypeSourceRange (), half_type_string);
}
void ProccessCompoundAssignOperator( CompoundAssignOperator *E){ //handle += *= /= ..
if(!insideIfCond && func_overload_mode)
return;
if (DEBUG_MODE)
std::cout<<"visit CompoundAssignOperator\n";
if (CudaCode){
string lhsTail = "";//some kind of expr DeclRefExpr needs this value to store the declname for lhs string we will insert to the left most location
if (IsFloatingPointType(E->getComputationLHSType().getAsString()) && IsFloatingPointType(E->getComputationResultType().getAsString())){
if (DEBUG_MODE)
std::cout<<"visit CompoundAssignOperator && cuda \n";
CharSourceRange sourceRange = CharSourceRange::getCharRange(E->getLHS()->getSourceRange());
sourceRange.setEnd (sourceRange.getEnd().getLocWithOffset(1)); //somehow lhs is missing 1 last char (right most) ??? workaround here
if (isa<UnaryOperator>(E->getLHS())){ //*d = *d +1.0 // deref unaryop
if(DEBUG_MODE)
std::cout<<"UnaryOperator lhs compound stmt \n";
UnaryOperator* unaryOp = cast<UnaryOperator>(E->getLHS());
CastExpr* castExpr = nullptr;
if (isa<CastExpr>(unaryOp->getSubExpr())){ //skip all CastExpr
if(DEBUG_MODE)
cout<<"cast sub expr \n";
castExpr = cast<CastExpr>(unaryOp->getSubExpr());
while (isa<CastExpr>(castExpr->getSubExpr())){//skip all CastExpr //preventive
castExpr = cast<CastExpr>(castExpr->getSubExpr());
}
}
sourceRange.setBegin (unaryOp->getOperatorLoc());
sourceRange.setEnd (unaryOp->getSubExpr ()->getLocEnd());
Expr * subExpr ;
if (castExpr == nullptr )
subExpr = unaryOp->getSubExpr ();
else
subExpr =castExpr->getSubExpr ();
if (isa<DeclRefExpr>(subExpr)){ //insert declname to the right of the unaryoperator
if(DEBUG_MODE)
cout<<"cast DeclRefExpr \n";
DeclRefExpr *declRefExpr = cast<DeclRefExpr>(subExpr);
lhsTail= declRefExpr->getDecl ()->getNameAsString ();
}
}
string lhsString = Lexer::getSourceText(sourceRange, Context->getSourceManager(), LangOptions(), 0) ;
lhsString = lhsString + lhsTail ;
if (insideIfCond){ //note down LHS to a vector, retrieve later
SourceRange * sourceRange = getSourceRangeIgnoreArrayRef(E->getLHS());
sourceRange->setEnd (sourceRange->getEnd().getLocWithOffset(1));
string lhsSource = getSourceTextFromSourceRange(sourceRange);
if(DEBUG_MODE)
cout<<"added "<<lhsSource <<" to lhsMaskedInIffCond list";
if (insideElseBranch)
insertToVectorIfNotExist(lhsMaskedInElseCond, lhsSource);
else
insertToVectorIfNotExist(lhsMaskedInIffCond, lhsSource); //maybe we should consider check for duplicate data in lhsMaskedInIffCond. not necessary now
//dirty trick here, if lhsString contains [, insert _masked before [. else, insert it at the end of lhsString
int insertPosition = lhsString.find_first_of("[");;
if(insertPosition== -1)
insertPosition = lhsString.length();
lhsString.insert(insertPosition,"_masked_"+ to_string(currentIfLineNumber.first));
}
if (DEBUG_MODE)
std::cout<<"lhsString "<< lhsString<<"\n";
TheRewriter.InsertText(E->getLHS()->getExprLoc() ,lhsString + " = ");
//~ TheRewriter.InsertTextBefore(E->getLHS()->getExprLoc().getLocWithOffset (-1) ,lhsString + " = ");
SourceLocation rightLocation = E->getLocEnd(); //3 = len " = "
SourceLocation leftLocation = E->getLHS()->getExprLoc();
RewriteBinaryOp(leftLocation,rightLocation,E);
}
}
}
bool VisitUnaryOperator (UnaryOperator * E){ //handle - (h2neg(x) call if x is not literal value)
if(!insideIfCond && func_overload_mode)
return true;
if (CudaCode){
if (DEBUG_MODE)
cout<<"visit UnaryOperator cuda\n";
if(E->getOpcode() == UO_Deref)
if(DEBUG_MODE)
cout<<"UO deref found\n";
if ( E->getOpcode() == UO_Minus ){
if (!isa<FloatingLiteral>(E->getSubExpr())){
if(DEBUG_MODE)
cout<<"neg unary op on var \n";
Expr* childExpr = E->getSubExpr()->IgnoreCasts()->IgnoreImpCasts ();
string varName = "";
bool validHalf2Var = false;
if (isa<ArraySubscriptExpr>(childExpr)){ //array ref
ArraySubscriptExpr* subscriptExpr = cast<ArraySubscriptExpr>(childExpr);
if (isa <ArraySubscriptExpr>(subscriptExpr->getBase()->IgnoreImpCasts())) //2d arrays ?
subscriptExpr = cast<ArraySubscriptExpr>(subscriptExpr->getBase()->IgnoreImpCasts());
if (isa <DeclRefExpr> (subscriptExpr->getBase()->IgnoreImpCasts())){
DeclRefExpr* declExpr = cast <DeclRefExpr> (subscriptExpr->getBase()->IgnoreImpCasts());
varName = declExpr-> getDecl ()-> getNameAsString();
if (IsHalf2Var(varName) && CurrentFunc!=nullptr) validHalf2Var = true;
}
}
else if (isa<DeclRefExpr>(childExpr)) { //single var name
if(DEBUG_MODE)
cout<<"DeclRefExpr \n";
DeclRefExpr* declExpr = cast <DeclRefExpr> (childExpr);
varName = declExpr-> getDecl ()-> getNameAsString();
if (IsHalf2Var(varName) && CurrentFunc!=nullptr) validHalf2Var = true;
}
if (validHalf2Var)
RewriteUnaryOp(E);
else {//try to traverse back to its parent
//this attemp failed for an unknown reason http://stackoverflow.com/questions/40871961/clang-astcontext-getparents-always-returns-an-empty-list
// work around : try to get to this point from its parent (CastExpr)
}
} else {
if(DEBUG_MODE)
cout<<"neg unary op on floating literal \n";
RewriteLiterals(E);
}
}
}
return true;
}
// void reWriteIndexLocation (Sour) //i => i/2 where suitable
void processRewriteArraySubscriptIndex(Expr* E){
if(DEBUG_MODE)
cout <<" processRewriteArraySubscriptExpr \n";
Expr* exprPlain = E->IgnoreImpCasts()->IgnoreParens ();
if (isa <DeclRefExpr>(exprPlain)){ //simplest case a[tid]/ rewrite a[tid/2]
// cout<<"simplest case \n";
DeclRefExpr* declRefExpr= cast<DeclRefExpr>(exprPlain);
if(DEBUG_MODE)
cout<<declRefExpr->getDecl ()->getNameAsString()<<"\n";
if (IsThreadIdVar(declRefExpr->getDecl ()->getNameAsString()))
{
// cout<<"inside iff \n";
TheRewriter.InsertTextAfterToken(Context->getSourceManager().getExpansionLoc(declRefExpr->getLocEnd ()), "/2");
}
}else if(isa <BinaryOperator>(exprPlain)){//recursively find tid loc //push back at LHS, popback at RHS
//support 3 levels recursion/ i.e. ((a+b) + (c+d))*e
vector<int> opcode_vec ; //BFS
SourceLocation threadIdLocation ;
bool foundIdx = false;
BinaryOperator* binaryop = cast<BinaryOperator>(exprPlain);
opcode_vec.push_back(binaryop->getOpcode());
if(isa <DeclRefExpr>(binaryop->getLHS()->IgnoreImpCasts()->IgnoreParens ()))
{
DeclRefExpr* declRefExpr= cast<DeclRefExpr>(binaryop->getLHS()->IgnoreImpCasts()->IgnoreParens ());
if (IsThreadIdVar(declRefExpr->getDecl ()->getNameAsString()))
{
if(DEBUG_MODE)
cout<<"caught LHS \n" ;
foundIdx = !foundIdx;
threadIdLocation = declRefExpr->getLocEnd ();
}
} else if(isa <DeclRefExpr>(binaryop->getRHS()->IgnoreImpCasts()->IgnoreParens ()))
{
DeclRefExpr* declRefExpr= cast<DeclRefExpr>(binaryop->getRHS()->IgnoreImpCasts()->IgnoreParens ());
if (IsThreadIdVar(declRefExpr->getDecl ()->getNameAsString()))
{
if(DEBUG_MODE)
cout<<"caught RHS \n" ;
foundIdx = !foundIdx;
threadIdLocation = declRefExpr->getLocEnd ();
}
}
else{ //binaryop
if(isa <BinaryOperator>(binaryop->getLHS()->IgnoreImpCasts()->IgnoreParens ())){ //LHS
BinaryOperator* binaryop1 = cast<BinaryOperator>((binaryop->getLHS()->IgnoreImpCasts()->IgnoreParens ()));
if(!foundIdx)
opcode_vec.push_back(binaryop1->getOpcode());
if(isa <DeclRefExpr>(binaryop1->getLHS()->IgnoreImpCasts()->IgnoreParens ()))
{
DeclRefExpr* declRefExpr= cast<DeclRefExpr>(binaryop1->getLHS()->IgnoreImpCasts()->IgnoreParens ());
if (IsThreadIdVar(declRefExpr->getDecl ()->getNameAsString()))
{
if(DEBUG_MODE)
cout<<"caught tid LHS LHS\n" ;
foundIdx = !foundIdx;
threadIdLocation = declRefExpr->getLocEnd ();
}
} else{
//do nothing, need to refactor this code to recursive version to process this
}
if(isa <DeclRefExpr>(binaryop1->getRHS()->IgnoreImpCasts()->IgnoreParens ()))
{
DeclRefExpr* declRefExpr= cast<DeclRefExpr>(binaryop1->getRHS()->IgnoreImpCasts()->IgnoreParens ());
if (IsThreadIdVar(declRefExpr->getDecl ()->getNameAsString()))
{
if(DEBUG_MODE)
cout<<"caught tid LHS RHS\n" ;
foundIdx = !foundIdx;
threadIdLocation = declRefExpr->getLocEnd ();
}
} else{
//do nothing
}
if(!foundIdx)
opcode_vec.pop_back() ;
}//end LHS
if(isa <BinaryOperator>(binaryop->getRHS()->IgnoreImpCasts()->IgnoreParens ())){ //RHS
BinaryOperator* binaryop1 = cast<BinaryOperator>((binaryop->getRHS()->IgnoreImpCasts()->IgnoreParens ()));
if(!foundIdx)
opcode_vec.push_back(binaryop1->getOpcode());
if(isa <DeclRefExpr>(binaryop1->getLHS()->IgnoreImpCasts()->IgnoreParens ()))
{
DeclRefExpr* declRefExpr= cast<DeclRefExpr>(binaryop1->getLHS()->IgnoreImpCasts()->IgnoreParens ());
if (IsThreadIdVar(declRefExpr->getDecl ()->getNameAsString()))
{
if(DEBUG_MODE)
cout<<"caught tid RHS LHS\n" ;
foundIdx = !foundIdx;
threadIdLocation = declRefExpr->getLocEnd ();
}
} else{
//do nothing, need to refactor this code to recursive version to process this
}
if(isa <DeclRefExpr>(binaryop1->getRHS()->IgnoreImpCasts()->IgnoreParens ()))
{
DeclRefExpr* declRefExpr= cast<DeclRefExpr>(binaryop1->getRHS()->IgnoreImpCasts()->IgnoreParens ());
if (IsThreadIdVar(declRefExpr->getDecl ()->getNameAsString()))
{
if(DEBUG_MODE)
cout<<"caught tid RHS RHS\n" ;
foundIdx = !foundIdx;
threadIdLocation = declRefExpr->getLocEnd ();
}
} else{
//do nothing
}
if(!foundIdx)
opcode_vec.pop_back() ;
}
}
//process after found:
if (foundIdx){
bool valid_simpleFunc = true; //check if idx in form M[A*idx + B] where A must equal 1, which means all ops in opcode_vec != div or mul
if(DEBUG_MODE)
cout <<" end , found idx :";
for (int i = 0;i<opcode_vec.size();i++){
if(opcode_vec[i] == BO_Mul || opcode_vec[i] == BO_Div)
valid_simpleFunc= false;
//cout<<opcode_vec[i]<< " ";
}
//cout <<"\n";
if (valid_simpleFunc){
if(DEBUG_MODE)
cout <<"idX linear to array ref. rewrite \n";
TheRewriter.InsertTextAfterToken(Context->getSourceManager().getExpansionLoc(threadIdLocation), "/2");
}
}
else{
cout <<"Not supported array subcript formula, not processed \n";
}
}
}
bool VisitArraySubscriptExpr(ArraySubscriptExpr* E){ //rewrite array access for half2 type
if (!half2_mode)
return true;
Expr* base = E->getBase();
Expr* index = E->getIdx();
//base->IgnoreParens ()->();
//index->IgnoreParens ()->dump();
DeclRefExpr* declExpr = nullptr ;
if (isa <DeclRefExpr> (base->IgnoreImpCasts()))
declExpr = cast <DeclRefExpr> (E->getBase()->IgnoreImpCasts());
if (declExpr == nullptr) return true;
SourceRange *indexrange = new SourceRange(index->IgnoreImpCasts () ->getLocStart(), index ->IgnoreImpCasts ()->getLocEnd());
// SourceRange *baserange = new SourceRange(E->IgnoreImpCasts () ->getLocStart(), base->getLocEnd());
// baserange->setEnd (baserange->getEnd().getLocWithOffset(1));
if(DEBUG_MODE)
cout <<"VisitArraySubscriptExpr : base " <<declExpr->getDecl ()->getNameAsString()<<" index "<<getSourceTextFromSourceRange(indexrange)<<"\n";
if (IsHalf2Var(declExpr->getDecl ()->getNameAsString()))
processRewriteArraySubscriptIndex(index);
return true;
}
bool VisitCallExpr(CallExpr *E){
if (DEBUG_MODE){
cout<<"visit call expr \n";
string fullSrc = Lexer::getSourceText(CharSourceRange::getCharRange(E->getSourceRange()),Context->getSourceManager(),LangOptions(), 0);
string toFirstArg = "none ";
if(E->getNumArgs () >=1)
toFirstArg = Lexer::getSourceText(CharSourceRange::getCharRange(E->getLocStart(), E->getArg(0)->getLocStart().getLocWithOffset (-1) ),Context->getSourceManager(),LangOptions(), 0);
cout << "fullSrc " << fullSrc << "\n";
cout << "func name only " << toFirstArg << "\n";
}
if (E->getDirectCallee()!=nullptr && (E->getNumArgs () >=1)){
FunctionDecl *directCallee = E->getDirectCallee();
if (directCallee->hasAttr<CUDADeviceAttr>() ||directCallee->hasAttr<CUDAGlobalAttr>() ){
RewriteFunctionCall(E);
//rewrite args if they are floating literal or integer literals;
for (int i = 0; i< E->getNumArgs ();i++){
Expr* arg = E->getArg(i)->IgnoreImpCasts()->IgnoreImplicit()->IgnoreParens();
if (isa<FloatingLiteral>(arg) || isa<IntegerLiteral>(arg))
RewriteLiterals(arg);
}
}
}
return true;
}
bool VisitCastExpr(CastExpr *E){
if (CudaCode){
if (isa<UnaryOperator>(E->getSubExpr()))
{
UnaryOperator* unaryOp = cast<UnaryOperator>(E->getSubExpr());
if (DEBUG_MODE)
cout<<"VisitCastExpr cuda unaryop\n";
if (unaryOp->getOpcode() == UO_Minus && (isa<IntegerLiteral>(unaryOp->getSubExpr())))
{
if(DEBUG_MODE)
cout <<"rewrite literals child of cast expr\n";
RewriteLiterals(unaryOp); // rewrite literals because we will use float2half2_rn (neg intliteral);
}
}
}
return true;
}
//TODO change IsFloatingPointType = IsSIMDType, provide short2
bool VisitBinaryOperator(BinaryOperator *E){
if (DEBUG_MODE){
std::cout<<"visit binary operator \n";
std::cout<<"binary operator inside iff cond, rewrite with masking\n";
(E->getLHS())->dump();
(E->getRHS())->dump();
}
QualType LHSType = E->getLHS()->getType();
QualType RHSType = E->getRHS()->getType();
if (IsFloatingPointType(LHSType.getAsString()) /*&& IsFloatingPointType(RHSType.getAsString())*/){
if (CudaCode) {
if (DEBUG_MODE)
std::cout<<"binary op in cuda detected \n";
if(isa<CompoundAssignOperator>(E)){//handle += *= /= ..
CompoundAssignOperator * compoundAssignOp = cast<CompoundAssignOperator>(E);
ProccessCompoundAssignOperator(compoundAssignOp);
return true;
}
else { //simple binary op
SourceLocation leftLocation = E->getLHS()->getExprLoc();
SourceLocation rightLocation = E->getRHS()->getLocEnd();
if (isa<BinaryOperator>(E->getLHS())) {
if (DEBUG_MODE)
std::cout<<"LHS is Binary op\n";
BinaryOperator *binaryOp = cast<BinaryOperator>(E->getLHS());
while (isa<BinaryOperator>(binaryOp->getLHS())){ //recursively get to the left most position of binaryop
binaryOp = cast<BinaryOperator>(binaryOp->getLHS());
}
leftLocation = binaryOp->getLHS()->getExprLoc();
}else if (isa<BinaryOperator>(E->getRHS())) {
if (DEBUG_MODE)
std::cout<<"RHS is Binary op\n";
BinaryOperator *binaryOp = cast<BinaryOperator>(E->getRHS());
while (isa<BinaryOperator>(binaryOp->getRHS())){ //recursively get to the right most position of binaryop
binaryOp = cast<BinaryOperator>(binaryOp->getRHS());
}
rightLocation = binaryOp->getRHS()->getLocEnd();
}
if(E->HasSideEffects(*Context) == false)
{
if(DEBUG_MODE)
cout<< "no side effect \n";
if (E->isEvaluatable (*Context)){//eval and return
if(DEBUG_MODE)
cout<< "isEvaluatable \n";
APFloat evalResult(0.0);
if (E->EvaluateAsFloat(evalResult,*Context)){
float fltEvalResult = 0.0;
if (APFloat::semanticsSizeInBits(evalResult.getSemantics()) == 64) //detect double the ugly way
fltEvalResult = (float) evalResult.convertToDouble () ;
else
fltEvalResult = evalResult.convertToFloat();
if(DEBUG_MODE)
cout<< "eval result " << fltEvalResult <<"\n";
SourceRange replaceRange;
replaceRange.setBegin(E->getLHS()->getExprLoc());
replaceRange.setEnd(E->getRHS()->getLocEnd());
std::ostringstream ss;
ss << fltEvalResult;
std::string fltEvalString(ss.str());
TheRewriter.ReplaceText(replaceRange, string(fltEvalString) );
return true;
}
}
}
RewriteBinaryOp(leftLocation,rightLocation,E );
bool LHSSubcript = false;
bool RHSSubcript = false;
Expr *LHSIgnoreParensCasts = E->getLHS()->IgnoreImpCasts()->IgnoreParens ();