-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockStridePass.cpp
2544 lines (2485 loc) · 129 KB
/
blockStridePass.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
#define debug_stride_pass false
//===- DIrectly Imported from Hello.cpp - Example code from "Writing an LLVM Pass" ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements two versions of block stride computation
// the static version prints them at compile time, the runtime version prints only
// at runtime.
// Prithayan Barua
//===----------------------------------------------------------------------===//
#include "llvm/IR/DebugInfo.h"
#include<iostream>
#include<sstream>
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/TypeBuilder.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Analysis/VectorUtils.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Function.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar/LICM.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AliasSetTracker.h"
#include "llvm/Analysis/BasicAliasAnalysis.h"
#include "llvm/Analysis/CaptureTracking.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/LoopPassManager.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/PredIteratorCache.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
#include <algorithm>
#include <vector>
#include <deque>
#include <set>
#include <map>
#include <algorithm>
#include <ostream>
#include <fstream>
#include <iostream>
using namespace llvm;
#define DEBUG_TYPE "hello"
//STATISTIC(HelloCounter, "Counts number of functions greeted");
namespace {
StringRef XblockIdxString("llvm.nvvm.read.ptx.sreg.ctaid.x" ) ;
StringRef YblockIdxString("llvm.nvvm.read.ptx.sreg.ctaid.y" ) ;
StringRef ZblockIdxString("llvm.nvvm.read.ptx.sreg.ctaid.z" ) ;
StringRef xthreadDim("llvm.nvvm.read.ptx.sreg.ntid.x");
StringRef ythreadDim("llvm.nvvm.read.ptx.sreg.ntid.y");
StringRef XthreadIdxString("llvm.nvvm.read.ptx.sreg.tid.x");
StringRef YthreadIdxString("llvm.nvvm.read.ptx.sreg.tid.y");
StringRef zthreadin("llvm.nvvm.read.ptx.sreg.tid.z");
int count_wrapper_print = 0;
// Insert Block Stride Computation Instruction
struct dynamicBlockStride : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
Function *wrapper_printfFunction;
Module *thisMod;
const DataLayout *dlayout ;
bool cannot_compute, got_a_phi_node;
bool got_block_index_instr, computed_stride_found;
bool getXblockStride ;
char block_stride_X;
Value *XblockDim;
Value *YblockDim;
Function *thisFunc;
std::set<Instruction*> alreadyDoneInstr_set;
std::set<const Value*> memWrittenSet;
Function *threadIndexFun;
Function *blockIndexFun;
Function *YblockIndexFun ;
Function *YthreadIndexFun;
// std::string print_msg;
GlobalVariable *printfStringMod;
std::set<Value* > visit_done_set;
DominatorTree *domTree;
dynamicBlockStride() : FunctionPass(ID) {
if (debug_stride_pass) errs()<<"\n registered on constructor";
//print_msg="Debug Stride = %d";
}
bool isFuncAlreadyDone(Function &Func ) {
static std::set<std::string> function_already_done_set;
if (function_already_done_set.find(std::string(Func.getName())) != function_already_done_set.end()) return true ;
function_already_done_set.insert(std::string(Func.getName()));
return false;
}
void initFuncData(Function &Func) {
thisFunc = &Func;
thisMod = (*inst_begin(Func)).getModule() ;
dlayout = &(Func.getParent()->getDataLayout());
alreadyDoneInstr_set.clear();
memWrittenSet.clear();
blockIndexFun = thisMod->getFunction(XblockIdxString );
threadIndexFun = thisMod->getFunction(XthreadIdxString );
YblockIndexFun = thisMod->getFunction(YblockIdxString );
YthreadIndexFun = thisMod->getFunction(YthreadIdxString );
getXblockStride = true;
//if (blockIndexFun != nullptr)
//errs()<<"\n got func::"<<*blockIndexFun;
//if (threadIndexFun != nullptr)
//errs()<<"\n got func::"<<*threadIndexFun;
domTree = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
}
void insert_printf(GlobalVariable *string_printf,Value *computedStride,IRBuilder<> &builder ) {
//if (compile_prinit) print_instr(computedStride);
//return; //TODO REMOVE THIS
std::vector<Value *> ArgsV;
//= getStringRef(print_msg );
Constant* zero_i64 = Constant::getNullValue(IntegerType::getInt64Ty(thisMod->getContext()));
ArrayRef< Value * > indices = {zero_i64,zero_i64};
PointerType *pty = dyn_cast<PointerType>(string_printf->getType());
GetElementPtrInst *gep_printf_string = GetElementPtrInst::Create( pty->getElementType(), string_printf,indices );
if (debug_stride_pass) errs()<<"printf string load:: " <<*gep_printf_string;
Value *printf_str_gep = builder.Insert(gep_printf_string,"tmp_blockstride_compute" );
////ArgsV.push_back( geti8StrVal(*thisMod));
//errs()<<"\n param type::"<<*computedStride->getType()<<"function wrapper::"<<*wrapper_printfFunction;
Type *struct_ty = StructType::get(computedStride->getType(),nullptr );
//Type *struct_ty = StructType::get(IntegerType::getInt32Ty(thisMod->getContext()),nullptr );
if (debug_stride_pass) errs()<<"\n struct type:: "<<*struct_ty;
Value * tmp_print_mem = builder.CreateAlloca(struct_ty ,nullptr, "tmp_stride_comp" );
if (debug_stride_pass) errs()<<"\n alloca instr::"<<*tmp_print_mem<<"\n";
Constant* zero_i32 = Constant::getNullValue(IntegerType::getInt32Ty(thisMod->getContext()));
ArrayRef< Value * > indices2 = {zero_i64,zero_i32};
//if (debug_stride_pass) errs()<<"\n Creating gep with pointer::"<<*tmp_print_mem<< "\n and indiex::"<<*indices[0]<<" and ::"<<*indices[1]<<"\n";
//if (debug_stride_pass) errs()<<"\n pointer type::"<<*cast<PointerType>(tmp_print_mem->getType()->getScalarType())->getElementType()<<"\n";
GetElementPtrInst *gepInstr = GetElementPtrInst::Create( struct_ty, tmp_print_mem,indices2 );
Value *print_args_pointer = builder.Insert(gepInstr,"tmp_blockstride_compute" );// builder.CreateGEP(tmp_print_mem,Constant::getNullValue(IntegerType::getInt32Ty(thisMod->getContext())));//indices);
if (debug_stride_pass) errs()<<"\n printargspointer::"<<*print_args_pointer<<"\n ";
Value *stored_arg = builder.CreateStore(computedStride,print_args_pointer );
if (debug_stride_pass) errs()<<"store::"<<*stored_arg;
Value *bitcast_arg = builder.CreateBitCast(tmp_print_mem,PointerType::get(IntegerType::getInt8Ty(thisMod->getContext()),0 ));
ArgsV.push_back(printf_str_gep);
ArgsV.push_back(bitcast_arg);
//if (debug_stride_pass) errs()<<"\n finally got bitcase as:"<<*bitcast_arg<<"\n and stored arg::"<<*stored_arg;
Type *ptr_i8 = PointerType::get(Type::getInt8Ty(thisMod->getContext()), 0);
llvm::Type *ArgTypes[] = { ptr_i8,ptr_i8 } ;
Function *vprintfFunction =dyn_cast<Function>( thisMod->getOrInsertFunction("vprintf",
FunctionType::get(IntegerType::getInt32Ty(thisMod->getContext()),
ArgTypes,false /*
this is var arg func type*/)
) );
if (vprintfFunction == nullptr ) {
if (debug_stride_pass) errs()<<"\n func def not found::";
return;
}
if (debug_stride_pass) errs()<<"\n vprintf::"<<*vprintfFunction;
Value* callinstr = builder.CreateCall(vprintfFunction,ArgsV );
if (debug_stride_pass) errs()<<"\n callinstr::"<<*callinstr;
}
Function* createNewPrintWrapper(GlobalVariable *string_printf){
count_wrapper_print++;
std::string funcName("wrapperPrint"+std::to_string(count_wrapper_print));
LLVMContext &C = thisMod->getContext();
Type *intTy= IntegerType::getInt64Ty(C);
Type *int32Ty= IntegerType::getInt32Ty(C);
Type *stringTy = string_printf->getType();
Type *Params[] = { intTy,intTy , stringTy, int32Ty, int32Ty,int32Ty, int32Ty };
FunctionType *FT =
FunctionType::get( Type::getVoidTy(C) , Params, false);
Function *fun =
Function::Create(FT, Function::InternalLinkage,funcName , thisMod );
Function::arg_iterator args = fun->arg_begin();
Value* x = &*args;
x->setName("stride_1");
args++;
Value* y = &*args;
y->setName("stride_0");
args++;
Value* s = &*args;
s->setName("print_str");
args++;
Value* bi = &*args;
bi->setName("blockInd");
args++;
Value* ti= &*args;
ti->setName("threadId");
args++;
Value* Ybi = &*args;
bi->setName("YblockInd");
args++;
Value* Yti= &*args;
ti->setName("YthreadId");
/* if (stride_1 == stride_0 ) {
printf
} else {
printf no stride
}
*/
BasicBlock* entry = BasicBlock::Create(thisMod->getContext(), "entry", fun);
BasicBlock* cond_true = BasicBlock::Create(thisMod->getContext(), "cond_true", fun);
BasicBlock* cond_true1 = BasicBlock::Create(thisMod->getContext(), "once_cond_true", fun);
//BasicBlock* cond_false1 = BasicBlock::Create(thisMod->getContext(), "cond_false1", fun);
BasicBlock* cond_true2 = BasicBlock::Create(thisMod->getContext(), "once_cond_true1", fun);
BasicBlock* cond_trueY = BasicBlock::Create(thisMod->getContext(), "once_cond_trueY1", fun);
BasicBlock* cond_trueY2 = BasicBlock::Create(thisMod->getContext(), "once_cond_trueY2", fun);
BasicBlock* cond_false = BasicBlock::Create(thisMod->getContext(), "cond_false", fun);
IRBuilder<> builder(entry);
Value* xEqualsY = builder.CreateICmpEQ(x, y, "tmp");
builder.CreateCondBr(xEqualsY,cond_true, cond_false);
builder.SetInsertPoint(cond_true);
Value* zero_i32 = Constant::getNullValue(IntegerType::getInt32Ty(thisMod->getContext()));
Value* xEqualsY1 = builder.CreateICmpEQ(ti, bi, "tmp");
builder.CreateCondBr(xEqualsY1,cond_true1, cond_false);
builder.SetInsertPoint(cond_true1);
Value* xEqualsY2 = builder.CreateICmpEQ(ti, zero_i32, "tmp");
builder.CreateCondBr(xEqualsY2,cond_true2, cond_false);
builder.SetInsertPoint(cond_true2);
Value* YEqualsY = builder.CreateICmpEQ(Yti, Ybi , "tmp");
builder.CreateCondBr(YEqualsY ,cond_trueY, cond_false);
builder.SetInsertPoint(cond_trueY);
Value* YEqualsY2 = builder.CreateICmpEQ(Yti, zero_i32 , "tmp");
builder.CreateCondBr(YEqualsY2 ,cond_trueY2, cond_false);
builder.SetInsertPoint(cond_trueY2);
uint64_t mytypeSize = dlayout->getTypeStoreSize(x->getType());
Value *constIntInit = ConstantInt::get(x->getType(),mytypeSize);
Value *blockStrideSize = builder.CreateBinOp(Instruction::Mul,constIntInit , x ,"final_stride_compute_mul");
insert_printf(string_printf, blockStrideSize, builder );
builder.CreateRetVoid();
builder.SetInsertPoint(cond_false);
builder.CreateRetVoid();
//builder.SetInsertPoint(cond_false1);
//builder.CreateRetVoid();
if (debug_stride_pass) errs()<<"\n new func::"<<*fun;
return fun;
}
bool runOnFunction(Function &Func) override {
if (isFuncAlreadyDone(Func)) return false;
//errs()<<"Before"<<Func;
bool written_once=false;
bool block_stride_computed=false;
Instruction *gep_last;
initFuncData(Func);
if (!getMemWrittenBy(Func)) return false;
// func is a pointer to a Function instance
for (Function::iterator basicBlockIterator = Func.begin(), basicBlockEnd = Func.end(); basicBlockIterator != basicBlockEnd; ++basicBlockIterator) {
//errs() << "Basic block (name=" << basicBlockIterator->getName() << ") has "<< basicBlockIterator->size() << " instructions.\n";
for (BasicBlock::iterator instructionIterator = basicBlockIterator->begin(), instructionEnd =
basicBlockIterator->end(); instructionIterator != instructionEnd;++instructionIterator) {
if (debug_stride_pass) errs() << *instructionIterator << "\n";
if (block_stride_computed && !written_once) {
errs() << "\nRunning Pass on Function::";
errs().write_escaped(Func.getName()) << '\n';
written_once=true;
}
if (GetElementPtrInst *gep= dyn_cast<GetElementPtrInst>(instructionIterator)) {
block_stride_computed = analyzeGEP(gep );
gep_last = gep;
}
}
}
//errs()<<"\n Mod func::"<<Func;
//errs()<<"After:\n"<<Func;
return true ;
}
bool isFuncArg(const Instruction *instr ){
/*Find if any part of the instruction can be traced to the function arguments*/
if (isa<Argument>(instr )) return true;
//return false;
std::set<const Instruction*> isFuncArg_visited_set;//to stop recursion, visiting same node again
return isFuncArg(instr , isFuncArg_visited_set) ;
}
bool isFuncArg(const Instruction *instr , std::set<const Instruction*> &isFuncArg_visited_set){
if (isFuncArg_visited_set.find(instr) != isFuncArg_visited_set.end() ) return false;
isFuncArg_visited_set.insert(instr);
for (int i=0, n= instr->getNumOperands();i<n;i++ ){
Value *op = instr->getOperand(i);
// errs()<<"\n op::"<<*op<<(isa<Argument>(op ));
if (isa<Argument>(op )) return true;
if (isa<Instruction>(op ))
if (isFuncArg(dyn_cast<Instruction>(op) , isFuncArg_visited_set ))return true;
}
return false;
}
bool analyzeGEP( GetElementPtrInst *gep ) {
static bool done_once=false;
//if (done_once ) return;
Value *mem = gep->getPointerOperand();
if (debug_stride_pass) errs()<<"\n Working with gep::"<<*gep;
if (const Instruction *i= dyn_cast<Instruction>(mem)){
// if (isFuncArg(i ) ) {
// //errs()<<"\n got an argument"<<*mem;
// }else {
// //errs()<<"\n Not an argument"<<*mem;
// return false;
// }
}
Value *index0 = gep->getOperand(1);
int memDim = (gep->getNumOperands()-1);
if (Instruction* indexInstr = dyn_cast<Instruction>(index0 ) ) {
if (alreadyDoneInstr_set.find(gep) != alreadyDoneInstr_set.end()) return false;
alreadyDoneInstr_set.insert(gep);
DILocation *loc = gep->getDebugLoc();
unsigned line_num = 0 ;
std::string filename_dbg;
if (loc) line_num = loc->getLine();
if (loc) filename_dbg = loc->getFilename().str();
errs()<<"\nAnalyzing memory:: "<<*mem<<" for file line: "<<filename_dbg<<":"<<line_num ;//<<" with dimensions::"<< memDim ;
for ( int block_stride_X=0;block_stride_X<2;block_stride_X++) {
getXblockStride = !block_stride_X;
IRBuilder<> builder(gep);
Value *blockStride_instr1 = getBlockStrideExpression(indexInstr,builder);
Value *blockStride_instr2 = getBlockStrideExpression(indexInstr,builder);
if (blockStride_instr1 == nullptr || blockStride_instr2 == nullptr) return false;
//gep->setOperand(1, blockStride_instr);
//errs()<< "Block Stride Instr::"<<*blockStride_instr1;
std::ostringstream s;
s<<"\n Block Stride in "<<(block_stride_X==0?"X":"Y")<<" dim for ::";
s<<std::string(mem->getName());
s<<" reference at "<<filename_dbg<<":"<<line_num<<" is %d";
std::string print_msg = s.str();
GlobalVariable *string_printf = getStringRef(print_msg );
Value *threadid =Constant::getNullValue(IntegerType::getInt32Ty(thisMod->getContext())) ;
Value *blockid = Constant::getNullValue(IntegerType::getInt32Ty(thisMod->getContext()));
Value *Ythreadid =Constant::getNullValue(IntegerType::getInt32Ty(thisMod->getContext())) ;
Value *Yblockid = Constant::getNullValue(IntegerType::getInt32Ty(thisMod->getContext()));
if (threadIndexFun != nullptr)
threadid= builder.CreateCall(threadIndexFun,{} );
if (blockIndexFun != nullptr)
blockid= builder.CreateCall(blockIndexFun );
if (YthreadIndexFun != nullptr)
Ythreadid= builder.CreateCall(YthreadIndexFun,{} );
if (YblockIndexFun != nullptr)
Yblockid= builder.CreateCall(YblockIndexFun );
Function *toCall = createNewPrintWrapper(string_printf);
//insert_block_index_call(builder, gep);
//instrument_printf_stride(print_msg, blockStrideSize, builder);
std::vector<Value *> argsV;
argsV.push_back(blockStride_instr1 );
argsV.push_back(blockStride_instr2 );
argsV.push_back(string_printf );
argsV.push_back(threadid);
argsV.push_back(blockid);
argsV.push_back(Ythreadid);
argsV.push_back(Yblockid);
Value *v = builder.CreateCall(toCall ,argsV );
if (debug_stride_pass)errs()<<"\n calling::"<<*v<<"\n blockid:"<<*blockid<<"\n threadid:"<<*threadid;
done_once=true;
break;
}
return true;
}
return false;
}
Value * getBlockStrideExpression(Instruction *indexI , IRBuilder<> &builder) {
bool blockIndexFound = false;
bool cannot_compute = false;
//if(!validBlockStrideExists(indexI )) return nullptr;
int r = (rand())%10;
Value *blockIndex_zero_gep = replaceBlockIndexWith(indexI,builder,r ,blockIndexFound, cannot_compute );
if (cannot_compute) return nullptr ;
if (debug_stride_pass)errs()<<"\n inserted instr::"<<*blockIndex_zero_gep;
Value *blockIndex_one_gep = replaceBlockIndexWith(indexI,builder,r+1,blockIndexFound, cannot_compute );
if (debug_stride_pass)errs()<<"\n inserted instr::"<<*blockIndex_one_gep;
Value *blockStride_instr = builder.CreateSub(blockIndex_one_gep,blockIndex_zero_gep, "blockStride_Compute" );
return blockStride_instr;
//return blockIndex_zero_gep;
}
Value* replaceBlockIndexWith(Instruction *instr , IRBuilder<> &builder, const int replaceWith, bool
&blockIndexFound , bool &cannot_compute){
std::set<Instruction*> visitedSet;
return replaceBlockIndexWith(instr , builder, replaceWith, blockIndexFound,visitedSet, cannot_compute ) ;
}
Value* replaceBlockIndexWith(Instruction *instr , IRBuilder<> &builder, const int replaceWith, bool
&blockIndexFound, std::set<Instruction*> &visitedSet , bool &cannot_compute){
if (cannot_compute || instr==nullptr ) {
if (debug_stride_pass)errs()<<"\n cant compute and instr is null";
cannot_compute=true;
return nullptr;
}
if (visitedSet.find(instr) != visitedSet.end()) {
return instr;
cannot_compute=true;
if (debug_stride_pass)errs()<<"\n cant compute already visited set"<<*instr;
return nullptr;
}
visitedSet.insert(instr);
if ( PHINode *index_phi = dyn_cast<PHINode>(instr)) {
int initEdge = getInitPhiEdge(index_phi);
if (initEdge == -1) {
cannot_compute = true;
if (debug_stride_pass)errs()<<"\n cant compute phi is null"<<*instr;
return nullptr;
}
Value *init_loop = index_phi->getIncomingValue(initEdge ); //TODO verify if this is always 0, or 1, by checking the basicblock
if (!isa<Instruction>(init_loop )) return init_loop;
return replaceBlockIndexWith(dyn_cast<Instruction>(init_loop), builder, replaceWith, blockIndexFound,visitedSet,cannot_compute);
}
if (instr->mayReadFromMemory() ) {
if (LoadInst *li = dyn_cast<LoadInst>(instr)) {
Value *memGep = li->getPointerOperand();
if (GetElementPtrInst *gep= dyn_cast<GetElementPtrInst>( memGep)){
Value *mem = gep->getPointerOperand();
if (memWrittenSet.find(mem) != memWrittenSet.end()) {
cannot_compute=true;
if (debug_stride_pass)
errs()<<"\n cant compute mem written in kernel"<<*instr;
return nullptr;
}
if (!validBlockStrideExists(gep )) {
return instr;
}
}
}
cannot_compute=true;
if (debug_stride_pass)
errs()<<"\n cant compute mem written in kernel"<<*instr;
return nullptr;
}
if (debug_stride_pass)errs()<<"\n working with ::"<<*instr;
Instruction *clonedInstr = instr->clone();
for (unsigned int i=0, num_ops = instr->getNumOperands() ; i<num_ops ; i++ ) {
Value *op_i = instr->getOperand(i);
if (!isa<Instruction>(op_i )) continue;
if (isBlockIndex(dyn_cast<Instruction>(op_i), getXblockStride,false )){//either thread or block index
if (debug_stride_pass)errs()<<"\n block index instr::"<<*op_i;
blockIndexFound=true;
Value *replacedVal = getReplacementVal(op_i->getType(),replaceWith ) ;
clonedInstr->setOperand(i,replacedVal );
}else if (isBlockIndex(dyn_cast<Instruction>(op_i), getXblockStride , true)) {
if (debug_stride_pass)errs()<<"\n thread index instr::"<<*op_i;
Value *replacedVal = getReplacementVal(op_i->getType(),0 ) ;//Using threadindex 0
clonedInstr->setOperand(i,replacedVal );
}
else if (isBlockIndex(dyn_cast<Instruction>(op_i), !getXblockStride,
true)||isBlockIndex(dyn_cast<Instruction>(op_i), !getXblockStride,false) ) {
Value *replacedVal = getReplacementVal(op_i->getType(),0 ) ;//Using threadindex 0
clonedInstr->setOperand(i,replacedVal );
}
else {
Value * replacedVal = replaceBlockIndexWith(dyn_cast<Instruction>(op_i) , builder, replaceWith,
blockIndexFound, visitedSet, cannot_compute ) ;
if (replacedVal == nullptr || cannot_compute){
cannot_compute = true;
if (debug_stride_pass)errs()<<"\n cant compute, nullptr returned"<<*instr;
return nullptr;
}
clonedInstr->setOperand(i,replacedVal );
}
}
if (cannot_compute) return nullptr;
Instruction *insertedInstr = builder.Insert(clonedInstr);
if (debug_stride_pass)errs()<<"\n cloned inserted instr::"<<*insertedInstr;
return insertedInstr;
}
Value *getReplacementVal(Type *ty, const int intV) {
Value* constInit = ConstantInt::get(ty ,intV);
return constInit;
}
bool validBlockStrideExists(Instruction *instr) {
std::set<Instruction * > visited_set;
return validBlockStrideExists(instr, visited_set);
}
bool validBlockStrideExists(Instruction *instr, std::set<Instruction * > &visited_set) {
if (visited_set.find(instr) != visited_set.end()) return false;
visited_set.insert(instr);
//errs()<<"\n checking for valid stride:"<<*instr;
for (unsigned int i=0, num_ops = instr->getNumOperands() ; i<num_ops ; i++ ) {
Value *op_i = instr->getOperand(i);
if (!isa<Instruction>(op_i )) continue;
if (isBlockIndex(dyn_cast<Instruction>(op_i), false)||isBlockIndex(dyn_cast<Instruction>(op_i),true) ) {
if (debug_stride_pass)errs()<<"\n Got index::"<<*op_i;
return true;
}
if (validBlockStrideExists(dyn_cast<Instruction>(op_i),visited_set)) return true;
}
return false;
}
bool isBlockIndex(Instruction *instr, bool xDim=true , bool isThreadIndex=false) {
if (CallInst *callerI = dyn_cast<CallInst>(instr)) {
Function * calledFunc = callerI->getCalledFunction();
if (calledFunc == nullptr) return false;
if (!calledFunc->hasName()) return false;
StringRef functionName = calledFunc->getName();
if (xDim && !isThreadIndex && functionName.equals(XblockIdxString ) )
return true;
else if (!xDim && !isThreadIndex&& functionName.equals(YblockIdxString ) )
return true;
else if (xDim && isThreadIndex && functionName.equals(XthreadIdxString ) )
return true;
else if (!xDim && isThreadIndex&& functionName.equals(YthreadIdxString ) )
return true;
}
return false;
}
int getInitPhiEdge( PHINode *index_phi) {
//errs()<<"\n phi node::"<<*index_phi;
for (int incoming_index=0,n=index_phi->getNumIncomingValues(); incoming_index<n; incoming_index++ ) {
Value *incoming1 = index_phi->getIncomingValue(incoming_index ); //TODO verify if this is always 0, or 1, by checking the basicblock
if (Instruction *def = dyn_cast<Instruction>(incoming1 ) ){
if (domTree->dominates(def, index_phi )) {
if (debug_stride_pass)errs()<<"\n def and index::"<<*def<<"\n"<<*index_phi;
return incoming_index;
}
}else {
return incoming_index;
}
}
return -1;
/*
BasicBlock *incoming1 = index_phi->getIncomingBlock(0);
BasicBlock *incoming2 = index_phi->getIncomingBlock(1);
BasicBlock *current = index_phi->getParent();
if (domTree->dominates()
BasicBlock *pred = current->getSinglePredecessor();
if (pred == nullptr) return -1;
if (incoming1 == pred ) return 0;
if (incoming2 == pred) return 1;
return -1;
*/
}
void instrument_printf_stride(std::string print_msg,Value *computedStride,IRBuilder<> &builder ,bool
compile_prinit=false ) {
//if (compile_prinit) print_instr(computedStride);
//return; //TODO REMOVE THIS
std::vector<Value *> ArgsV;
GlobalVariable *string_printf = getStringRef(print_msg );
Constant* zero_i64 = Constant::getNullValue(IntegerType::getInt64Ty(thisMod->getContext()));
ArrayRef< Value * > indices = {zero_i64,zero_i64};
PointerType *pty = dyn_cast<PointerType>(string_printf->getType());
GetElementPtrInst *gep_printf_string = GetElementPtrInst::Create( pty->getElementType(), string_printf,indices );
if (debug_stride_pass) errs()<<"printf string load:: " <<*gep_printf_string;
Value *printf_str_gep = builder.Insert(gep_printf_string,"tmp_blockstride_compute" );
////ArgsV.push_back( geti8StrVal(*thisMod));
//errs()<<"\n param type::"<<*computedStride->getType()<<"function wrapper::"<<*wrapper_printfFunction;
Type *struct_ty = StructType::get(computedStride->getType(),nullptr );
//Type *struct_ty = StructType::get(IntegerType::getInt32Ty(thisMod->getContext()),nullptr );
if (debug_stride_pass) errs()<<"\n struct type:: "<<*struct_ty;
Value * tmp_print_mem = builder.CreateAlloca(struct_ty ,nullptr, "tmp_stride_comp" );
if (debug_stride_pass) errs()<<"\n alloca instr::"<<*tmp_print_mem<<"\n";
Constant* zero_i32 = Constant::getNullValue(IntegerType::getInt32Ty(thisMod->getContext()));
ArrayRef< Value * > indices2 = {zero_i64,zero_i32};
//if (debug_stride_pass) errs()<<"\n Creating gep with pointer::"<<*tmp_print_mem<< "\n and indiex::"<<*indices[0]<<" and ::"<<*indices[1]<<"\n";
//if (debug_stride_pass) errs()<<"\n pointer type::"<<*cast<PointerType>(tmp_print_mem->getType()->getScalarType())->getElementType()<<"\n";
GetElementPtrInst *gepInstr = GetElementPtrInst::Create( struct_ty, tmp_print_mem,indices2 );
Value *print_args_pointer = builder.Insert(gepInstr,"tmp_blockstride_compute" );// builder.CreateGEP(tmp_print_mem,Constant::getNullValue(IntegerType::getInt32Ty(thisMod->getContext())));//indices);
if (debug_stride_pass) errs()<<"\n printargspointer::"<<*print_args_pointer<<"\n ";
Value *stored_arg = builder.CreateStore(computedStride,print_args_pointer );
if (debug_stride_pass) errs()<<"store::"<<*stored_arg;
Value *bitcast_arg = builder.CreateBitCast(tmp_print_mem,PointerType::get(IntegerType::getInt8Ty(thisMod->getContext()),0 ));
ArgsV.push_back(printf_str_gep);
ArgsV.push_back(bitcast_arg);
//if (debug_stride_pass) errs()<<"\n finally got bitcase as:"<<*bitcast_arg<<"\n and stored arg::"<<*stored_arg;
Type *ptr_i8 = PointerType::get(Type::getInt8Ty(thisMod->getContext()), 0);
llvm::Type *ArgTypes[] = { ptr_i8,ptr_i8 } ;
Function *vprintfFunction =dyn_cast<Function>( thisMod->getOrInsertFunction("vprintf",
FunctionType::get(IntegerType::getInt32Ty(thisMod->getContext()),
ArgTypes,false /*
this is var arg func type*/)
) );
if (vprintfFunction == nullptr ) {
if (debug_stride_pass) errs()<<"\n func def not found::";
return;
}
if (debug_stride_pass) errs()<<"\n vprintf::"<<*vprintfFunction;
Value* callinstr = builder.CreateCall(vprintfFunction,ArgsV );
if (debug_stride_pass)errs()<<"\n callinstr::"<<*callinstr;
}
GlobalVariable *getStringRef(std::string print_msg ) {
Module *M = thisMod;
// Create a constant internal string reference...
if (debug_stride_pass) errs()<<"\n get global for ::"<<print_msg;
Constant *Init =ConstantDataArray::getString(M->getContext(),print_msg);
// Create the global variable and record it in the module
// The GV will be renamed to a unique name if needed.
GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
GlobalValue::InternalLinkage, Init,
"trstr");
M->getGlobalList().push_back(GV);
return GV;
}
bool getMemWrittenBy(Function &F) {//returns if this has block index variables
if (memWrittenSet.size() != 0) return false;
bool hasBlockThreadIdx=false;
// func is a pointer to a Function instance
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
Instruction *op_i = &*I;
if (isBlockIndex(dyn_cast<Instruction>(op_i), true,false )|| isBlockIndex(dyn_cast<Instruction>(op_i), true , true
)|| (isBlockIndex(dyn_cast<Instruction>(op_i),false,false )|| isBlockIndex(dyn_cast<Instruction>(op_i), false, true ) ) ) {
hasBlockThreadIdx=true;
// if (isBlockIndex(dyn_cast<Instruction>(op_i), true , true ))
// threadIndexVal=op_i;
}
if (I->mayWriteToMemory()) {
const Value *pointerGep=nullptr;
Instruction* pinst = &*I;
if (const StoreInst *SI = dyn_cast<StoreInst>(pinst)) {
pointerGep = SI->getPointerOperand();
}else if (const AtomicRMWInst *SI = dyn_cast<AtomicRMWInst>(pinst)) {
pointerGep = SI->getPointerOperand();
}else if (const AtomicCmpXchgInst *SI = dyn_cast<AtomicCmpXchgInst>(pinst)) {
pointerGep = SI->getPointerOperand();
} else continue;
if (pointerGep != nullptr) {
if (const GetElementPtrInst *gep= dyn_cast<GetElementPtrInst>(pointerGep )) {
const Value *mem = gep->getPointerOperand();
memWrittenSet.insert(mem);
if (debug_stride_pass)errs() <<"\n Written mem:: "<< *mem;
}
}
}
}
return hasBlockThreadIdx;
}
// We don't modify the program, so we preserve all analyses.
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DominatorTreeWrapperPass>();
//AU.setPreservesCFG();
//// AU.setPreservesAll();
//AU.addRequired<TargetLibraryInfoWrapperPass>();
//AU.addRequired<DominatorTreeWrapperPass>();
//AU.addRequired<CallGraphWrapperPass>();
//AU.addRequired<LoopInfoWrapperPass>();
//getLoopAnalysisUsage(AU);
}
};
}
char dynamicBlockStride::ID=0;
static RegisterPass<dynamicBlockStride>
MY("dynamic_block_stride", "Compute Block Stride CUDA");
static void registerDynamicStridePass(const PassManagerBuilder &,
legacy::PassManagerBase &PM) {
/*PassRegistry &Registry = *PassRegistry::getPassRegistry();
initializeAnalysis(Registry);
initializeCore(Registry);
initializeScalarOpts(Registry);
initializeIPO(Registry);
initializeAnalysis(Registry);
initializeIPA(Registry);
initializeTransformUtils(Registry);
initializeInstCombine(Registry);
initializeInstrumentation(Registry);
initializeTarget(Registry);*/
//PM.add(new dynamicBlockStride());
}
//static RegisterStandardPasses RegisterMyPass(PassManagerBuilder::EP_EarlyAsPossible, registerComputeStridePass);
//static RegisterStandardPasses RegisterMyPass(PassManagerBuilder::EP_ModuleOptimizerEarly,registerComputeStridePass);
//static RegisterStandardPasses RegisterMyPass(PassManagerBuilder::EP_LoopOptimizerEnd,registerComputeStridePass);
//static RegisterStandardPasses RegisterMyPass(PassManagerBuilder::EP_ScalarOptimizerLate,registerDynamicStridePass);
//static RegisterStandardPasses RegisterMyPass(PassManagerBuilder::EP_OptimizerLast,registerDynamicStridePass);
namespace
{
StringRef XblockIdxString("llvm.nvvm.read.ptx.sreg.ctaid.x" ) ;
StringRef YblockIdxString("llvm.nvvm.read.ptx.sreg.ctaid.y" ) ;
StringRef ZblockIdxString("llvm.nvvm.read.ptx.sreg.ctaid.z" ) ;
StringRef xthreadDim("llvm.nvvm.read.ptx.sreg.ntid.x");
StringRef ythreadDim("llvm.nvvm.read.ptx.sreg.ntid.y");
StringRef xthreadin("llvm.nvvm.read.ptx.sreg.tid.x");
StringRef ythreadin("llvm.nvvm.read.ptx.sreg.tid.y");
StringRef zthreadin("llvm.nvvm.read.ptx.sreg.tid.z");
// Insert Block Stride Computation Instruction
struct ComputeBlockStride : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
Function *wrapper_printfFunction;
Module *thisMod;
const DataLayout *dlayout ;//used for sizeof
bool got_block_index_instr, computed_stride_found;
char block_stride_X;
Value *XblockDim;
Value *YblockDim;
Function *thisFunc;
std::set<Instruction*> alreadyDoneInstr_set;
std::set<std::string> function_already_done_set;
// std::string print_msg;
GlobalVariable *printfStringMod;
Value* XblockIndexV;
Value* YblockIndexV;
Value* XthreadIndexV;
Value* YthreadIndexV;
std::set<Value* > visit_done_set;
ComputeBlockStride() : FunctionPass(ID) {
if (debug_stride_pass) errs()<<"\n registered on constructor";
//print_msg="Debug Stride = %d";
XblockIndexV = nullptr;
YblockIndexV = nullptr;
XthreadIndexV = nullptr;
YthreadIndexV = nullptr;
}
bool runOnFunction(Function &Func) override {
thisFunc = &Func;
if (function_already_done_set.find(std::string(Func.getName())) != function_already_done_set.end()) return false;
function_already_done_set.insert(std::string(Func.getName()));
bool written_once=false;
isFuncArg_visited_set.clear();
//Instruction *firstInstr = &*inst_begin(Func);
Instruction *gep_last;
thisMod = (*inst_begin(Func)).getModule() ;
dlayout = &(Func.getParent()->getDataLayout());
got_block_index_instr = false;
computed_stride_found=false;
XblockDim=nullptr;
YblockDim=nullptr;
// func is a pointer to a Function instance
//getPrintfFunction((*inst_begin(Func)).getModule() ) ;
for (Function::iterator basicBlockIterator = Func.begin(), basicBlockEnd = Func.end(); basicBlockIterator != basicBlockEnd; ++basicBlockIterator) {
//errs() << "Basic block (name=" << basicBlockIterator->getName() << ") has "<< basicBlockIterator->size() << " instructions.\n";
for (BasicBlock::iterator instructionIterator = basicBlockIterator->begin(), instructionEnd =
basicBlockIterator->end(); instructionIterator != instructionEnd;++instructionIterator) {
if (debug_stride_pass) errs() << *instructionIterator << "\n";
if (!got_block_index_instr ) set_if_block_index_instr(cast<Instruction>( instructionIterator));
if ( CallInst *callerI = dyn_cast<CallInst>(instructionIterator)){
Function * calledFunc = callerI->getCalledFunction();
if (!calledFunc->hasName()) continue;
StringRef functionName = calledFunc->getName();
if (XblockIndexV == nullptr && functionName.equals(XblockIdxString ) )
XblockIndexV = callerI;
if (XthreadIndexV == nullptr && functionName.equals(xthreadin ) )
XthreadIndexV = callerI;
}
if (got_block_index_instr) {
if (!written_once) {
errs() << "\nRunning Pass on Function::";
errs().write_escaped(Func.getName()) << '\n';
written_once=true;
}
if (GetElementPtrInst *gep= dyn_cast<GetElementPtrInst>(instructionIterator)) {
IRBuilder<> l_builder(gep);
analyzeGEP(gep, l_builder );
gep_last = gep;
//errs()<<"\n Mod func::"<<Func;
//return true ;
}
}
}
}
if (0) //TODO REMOVE THIS
if (computed_stride_found ){
IRBuilder<> builder(gep_last );
if (XblockDim) {
std::string print_msg("\n XDIM=%d");
instrument_printf_stride(print_msg, XblockDim, builder);
}
if (YblockDim){
std::string print_msg("\n YDIM=%d");
instrument_printf_stride(print_msg, YblockDim, builder);
}
for (Function::arg_iterator ArgIt = Func.arg_begin(), End = Func.arg_end();ArgIt != End; ++ArgIt) {
Value *A = &*ArgIt;
if (!(A->getType()->isIntegerTy())) continue;
std::ostringstream s;
s<<"\n Argument ::"<<std::string(A->getName())<<"=%d ";
std::string print_msg = s.str();
instrument_printf_stride(print_msg, A, builder);
}
return true;
}
//errs()<<"\n Mod func::"<<Func;
return true ;
}
std::set<const Instruction*> isFuncArg_visited_set;
bool isFuncArg(const Instruction *instr ){
if (isFuncArg_visited_set.find(instr) != isFuncArg_visited_set.end() ) return false;
isFuncArg_visited_set.insert(instr);
for (int i=0, n= instr->getNumOperands();i<n;i++ ){
Value *op = instr->getOperand(i);
// errs()<<"\n op::"<<*op<<(isa<Argument>(op ));
if (isa<Argument>(op )) return true;
if (isa<Instruction>(op ))
if (isFuncArg(dyn_cast<Instruction>(op) ) )return true;
}
return false;
}
void analyzeGEP( GetElementPtrInst *gep,IRBuilder<> &builder ) {
Value *mem = gep->getPointerOperand();
if (debug_stride_pass) errs()<<"\n Working with gep::"<<*gep;
if (const Instruction *i= dyn_cast<Instruction>(mem)){
if (isFuncArg(i ) ) {
//errs()<<"\n got an argument"<<*mem;
}else {
//errs()<<"\n Not an argument"<<*mem;
return;
}
}
/*if (const Argument *arg = dyn_cast<Argument>(mem)){
errs()<<"\n got an argument"<<*mem;
} else {
errs()<<"\n Not an argument"<<*mem;
return;
}*/
Value *index0 = gep->getOperand(1);
int memDim = (gep->getNumOperands()-1);
if (Instruction* indexInstr = dyn_cast<Instruction>(index0 ) ) {
if (alreadyDoneInstr_set.find(gep) != alreadyDoneInstr_set.end()) return;
DILocation *loc = gep->getDebugLoc();
unsigned line_num = 0 ;
std::string filename_dbg;
if (loc) line_num = loc->getLine();
if (loc) filename_dbg = loc->getFilename().str();
errs()<<"\nAnalyzing memory:: "<<*mem<<" for file line: "<<filename_dbg<<":"<<line_num ;//<<" with dimensions::"<< memDim ;
for (block_stride_X=1;block_stride_X<=2;block_stride_X++) {
visit_done_set.clear();
Value *computedStride = nullptr;
cannot_compute= false;
got_a_phi_node = false;
bool is_index = get_block_stride_instr(indexInstr, builder, computedStride );
if ( !cannot_compute && computedStride != nullptr ) {
errs()<<"\t block stride in "<<(block_stride_X==1?"X":"Y") ;
if (is_index ){
errs()<< "::"<<*computedStride;
std::ostringstream s;
s<<"\n Block Stride in "<<(block_stride_X==1?"X":"Y")<<" dim for ::";
s<<std::string(mem->getName());
s<<" reference at line "<<line_num<<" is %d";
uint64_t mytypeSize = dlayout->getTypeStoreSize(computedStride->getType());
s<<" size="<<mytypeSize;
std::string print_msg = s.str();
//Value *blockStrideSize = builder.CreateBinOp(Instruction::Mul, mytypeSize, computedStride,"final_stride_compute_mul");
//insert_block_index_call(builder, gep);
instrument_printf_stride(print_msg, computedStride, builder, true);
computed_stride_found=true;
break;
} else
errs()<<" is 0";
}
if (cannot_compute) {
errs()<<"\t Could Not Compute Block Stride";
break;
}
}
alreadyDoneInstr_set.insert(gep);
}
}
void insert_block_index_call(IRBuilder<> &builder, Instruction *beforeInstr ) {
//Function *xblockIndexFunc =dyn_cast<Function>( thisMod->getOrInsertFunction("llvm.nvvm.read.ptx.sreg.ctaid.x",
// FunctionType::get(IntegerType::getInt32Ty(thisMod->getContext()),
// Type::getVoidTy(thisMod->getContext()) ,false)
// ) );
//Function *yblockIndexFunc =dyn_cast<Function>( thisMod->getOrInsertFunction("llvm.nvvm.read.ptx.sreg.ctaid.y",
// FunctionType::get(IntegerType::getInt32Ty(thisMod->getContext()),
// Type::getVoidTy(thisMod->getContext()) ,false)
// ) );
//Function *xthreadIndexFunc =dyn_cast<Function>( thisMod->getOrInsertFunction("llvm.nvvm.read.ptx.sreg.tid.x",
// FunctionType::get(IntegerType::getInt32Ty(thisMod->getContext()),
// Type::getVoidTy(thisMod->getContext()) ,false)
// ) );
if (XblockIndexV != nullptr) {
Value * cond = builder.CreateICmpEQ(XblockIndexV,llvm::ConstantInt::get(builder.getInt32Ty(),0));
BasicBlock *trueBlock1 = BasicBlock::Create( thisMod->getContext(), "print_true",thisFunc);
BasicBlock *falseBlock1 = BasicBlock::Create( thisMod->getContext(), "print_fals",thisFunc);
BranchInst *branch_index = builder.CreateCondBr ( cond,trueBlock1,beforeInstr->getParent());// falseBlock1);
//BranchInst *branch_index = BranchInst::Create(trueBlock1,beforeInstr->getParent(),cond, beforeInstr);
//builder.Insert(branch_index);
//builder.SetInsertPoint(falseBlock1);
//Instruction *falselastBr = builder.CreateBr(beforeInstr->getParent());
builder.SetInsertPoint(trueBlock1);
Instruction *lastBr = builder.CreateBr(beforeInstr->getParent());
builder.SetInsertPoint(lastBr);
errs()<<"\n func::"<<*XblockIndexV;
errs()<<"\n cond::"<<*cond;
errs()<<"\n branch ::"<< *branch_index ;
errs()<<"\n";
//errs()<<"\n inserted add::"<<*(builder.CreateAdd( ConstantInt::get(builder.getInt32Ty(),0),
//ConstantInt::get(builder.getInt32Ty(),0) ));
//builder.SetInsertPoint(trueBlock1);
//errs()<<"\n falsebasic block::"<<*falseBlock1;
errs()<<"\n true block::"<<*trueBlock1;
}
//BasicBlock *trueBlock2 = BasicBlock::Create( thisMod->getContext(), "print_true",thisFunc);
//BasicBlock *falseBlock2 = BasicBlock::Create( thisMod->getContext(), "print_true",thisFunc);
//Value* threadIndexV = builder.CreateCall(xthreadIndexFunc );
//builder.CreateCondBr(builder.CreateICmpEQ(threadIndexV,
// llvm::ConstantInt::get(builder.getInt32Ty(),
// 0)),
// trueBlock2, falseBlock2);
//builder.SetInsertPoint(trueBlock2);
}
void instrument_printf_stride(std::string print_msg,Value *computedStride,IRBuilder<> &builder ,bool
compile_prinit=false ) {
if (compile_prinit) print_instr(computedStride);
//return; //TODO REMOVE THIS
std::vector<Value *> ArgsV;
GlobalVariable *string_printf = getStringRef(print_msg );
Constant* zero_i64 = Constant::getNullValue(IntegerType::getInt64Ty(thisMod->getContext()));
ArrayRef< Value * > indices = {zero_i64,zero_i64};
PointerType *pty = dyn_cast<PointerType>(string_printf->getType());
GetElementPtrInst *gep_printf_string = GetElementPtrInst::Create( pty->getElementType(), string_printf,indices );
if (debug_stride_pass) errs()<<"printf string load:: " <<*gep_printf_string;
Value *printf_str_gep = builder.Insert(gep_printf_string,"tmp_blockstride_compute" );
////ArgsV.push_back( geti8StrVal(*thisMod));
//errs()<<"\n param type::"<<*computedStride->getType()<<"function wrapper::"<<*wrapper_printfFunction;
Type *struct_ty = StructType::get(computedStride->getType(),nullptr );
//Type *struct_ty = StructType::get(IntegerType::getInt32Ty(thisMod->getContext()),nullptr );
if (debug_stride_pass) errs()<<"\n struct type:: "<<*struct_ty;
Value * tmp_print_mem = builder.CreateAlloca(struct_ty ,nullptr, "tmp_stride_comp" );
if (debug_stride_pass) errs()<<"\n alloca instr::"<<*tmp_print_mem<<"\n";
Constant* zero_i32 = Constant::getNullValue(IntegerType::getInt32Ty(thisMod->getContext()));
ArrayRef< Value * > indices2 = {zero_i64,zero_i32};
//if (debug_stride_pass) errs()<<"\n Creating gep with pointer::"<<*tmp_print_mem<< "\n and indiex::"<<*indices[0]<<" and ::"<<*indices[1]<<"\n";
//if (debug_stride_pass) errs()<<"\n pointer type::"<<*cast<PointerType>(tmp_print_mem->getType()->getScalarType())->getElementType()<<"\n";
GetElementPtrInst *gepInstr = GetElementPtrInst::Create( struct_ty, tmp_print_mem,indices2 );
Value *print_args_pointer = builder.Insert(gepInstr,"tmp_blockstride_compute" );// builder.CreateGEP(tmp_print_mem,Constant::getNullValue(IntegerType::getInt32Ty(thisMod->getContext())));//indices);
if (debug_stride_pass) errs()<<"\n printargspointer::"<<*print_args_pointer<<"\n ";
Value *stored_arg = builder.CreateStore(computedStride,print_args_pointer );
if (debug_stride_pass) errs()<<"store::"<<*stored_arg;
Value *bitcast_arg = builder.CreateBitCast(tmp_print_mem,PointerType::get(IntegerType::getInt8Ty(thisMod->getContext()),0 ));
ArgsV.push_back(printf_str_gep);
ArgsV.push_back(bitcast_arg);
//if (debug_stride_pass) errs()<<"\n finally got bitcase as:"<<*bitcast_arg<<"\n and stored arg::"<<*stored_arg;
Type *ptr_i8 = PointerType::get(Type::getInt8Ty(thisMod->getContext()), 0);
llvm::Type *ArgTypes[] = { ptr_i8,ptr_i8 } ;
Function *vprintfFunction =dyn_cast<Function>( thisMod->getOrInsertFunction("vprintf",
FunctionType::get(IntegerType::getInt32Ty(thisMod->getContext()),
ArgTypes,false /*
this is var arg func type*/)
) );
if (vprintfFunction == nullptr ) {
if (debug_stride_pass) errs()<<"\n func def not found::";
return;
}
if (debug_stride_pass) errs()<<"\n vprintf::"<<*vprintfFunction;
Value* callinstr = builder.CreateCall(vprintfFunction,ArgsV );
}
void print_instr(Value *v_instr ){
if (Instruction *instr = dyn_cast<Instruction>(v_instr) ){
if (!(instr->getOpcode() == Instruction::ZExt|| instr->getOpcode() == Instruction::SExt))
errs()<<" ::"<<*v_instr;
for (int i=0,n=instr->getNumOperands(); i< n ; i++ ){
Value *op = instr->getOperand(i);
print_instr(op);
}
}
}
bool check_if_index_const(Value *v_instr,std::set<Value*> &visited_set ){
if (visited_set.find(v_instr) != visited_set.end() ) return true ;
visited_set.insert(v_instr);
if (Instruction *instr = dyn_cast<Instruction>(v_instr) ){
if (dyn_cast<CallInst>(instr))
return check_if_block_dim_call(instr);//const iff a block dim, else not const