forked from KhronosGroup/SPIRV-LLVM-Translator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OCL20ToSPIRV.cpp
1896 lines (1733 loc) · 74.3 KB
/
OCL20ToSPIRV.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
//===- OCL20ToSPIRV.cpp - Transform OCL20 to SPIR-V builtins ----*- C++ -*-===//
//
// The LLVM/SPIRV Translator
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
// Copyright (c) 2014 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal with the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimers in the documentation
// and/or other materials provided with the distribution.
// Neither the names of Advanced Micro Devices, Inc., nor the names of its
// contributors may be used to endorse or promote products derived from this
// Software without specific prior written permission.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
// THE SOFTWARE.
//
//===----------------------------------------------------------------------===//
//
// This file implements translation of OCL20 builtin functions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "cl20tospv"
#include "OCLTypeToSPIRV.h"
#include "OCLUtil.h"
#include "SPIRVInternal.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Pass.h"
#include "llvm/PassSupport.h"
#include "llvm/Support/Debug.h"
#include <algorithm>
#include <set>
using namespace llvm;
using namespace SPIRV;
using namespace OCLUtil;
namespace SPIRV {
static size_t getOCLCpp11AtomicMaxNumOps(StringRef Name) {
return StringSwitch<size_t>(Name)
.Cases("load", "flag_test_and_set", "flag_clear", 3)
.Cases("store", "exchange", 4)
.StartsWith("compare_exchange", 6)
.StartsWith("fetch", 4)
.Default(0);
}
class OCL20ToSPIRV : public ModulePass, public InstVisitor<OCL20ToSPIRV> {
public:
OCL20ToSPIRV() : ModulePass(ID), M(nullptr), Ctx(nullptr), CLVer(0) {
initializeOCL20ToSPIRVPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<OCLTypeToSPIRV>();
}
virtual void visitCallInst(CallInst &CI);
/// Transform barrier/work_group_barrier/sub_group_barrier
/// to __spirv_ControlBarrier.
/// barrier(flag) =>
/// __spirv_ControlBarrier(workgroup, workgroup, map(flag))
/// work_group_barrier(scope, flag) =>
/// __spirv_ControlBarrier(workgroup, map(scope), map(flag))
/// sub_group_barrier(scope, flag) =>
/// __spirv_ControlBarrier(subgroup, map(scope), map(flag))
void visitCallBarrier(CallInst *CI);
/// Erase useless convert functions.
/// \return true if the call instruction is erased.
bool eraseUselessConvert(CallInst *Call, const std::string &MangledName,
const std::string &DeMangledName);
/// Transform convert_ to
/// __spirv_{CastOpName}_R{TargeTyName}{_sat}{_rt[p|n|z|e]}
void visitCallConvert(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transform async_work_group{_strided}_copy.
/// async_work_group_copy(dst, src, n, event)
/// => async_work_group_strided_copy(dst, src, n, 1, event)
/// async_work_group_strided_copy(dst, src, n, stride, event)
/// => __spirv_AsyncGroupCopy(ScopeWorkGroup, dst, src, n, stride, event)
void visitCallAsyncWorkGroupCopy(CallInst *CI,
const std::string &DemangledName);
/// Transform OCL builtin function to SPIR-V builtin function.
void transBuiltin(CallInst *CI, OCLBuiltinTransInfo &Info);
/// Transform OCL work item builtin functions to SPIR-V builtin variables.
void transWorkItemBuiltinsToVariables();
/// Transform atomic_work_item_fence/mem_fence to __spirv_MemoryBarrier.
/// func(flag, order, scope) =>
/// __spirv_MemoryBarrier(map(scope), map(flag)|map(order))
void transMemoryBarrier(CallInst *CI, AtomicWorkItemFenceLiterals);
/// Transform all to __spirv_Op(All|Any). Note that the types mismatch so
// some extra code is emitted to convert between the two.
void visitCallAllAny(spv::Op OC, CallInst *CI);
/// Transform atomic_* to __spirv_Atomic*.
/// atomic_x(ptr_arg, args, order, scope) =>
/// __spirv_AtomicY(ptr_arg, map(order), map(scope), args)
void transAtomicBuiltin(CallInst *CI, OCLBuiltinTransInfo &Info);
/// Transform atomic_work_item_fence to __spirv_MemoryBarrier.
/// atomic_work_item_fence(flag, order, scope) =>
/// __spirv_MemoryBarrier(map(scope), map(flag)|map(order))
void visitCallAtomicWorkItemFence(CallInst *CI);
/// Transform atomic_compare_exchange call.
/// In atomic_compare_exchange, the expected value parameter is a pointer.
/// However in SPIR-V it is a value. The transformation adds a load
/// instruction, result of which is passed to atomic_compare_exchange as
/// argument.
/// The transformation adds a store instruction after the call, to update the
/// value in expected with the value pointed to by object. Though, it is not
/// necessary in case they are equal, this approach makes result code simpler.
/// Also ICmp instruction is added, because the call must return result of
/// comparison.
/// \returns the call instruction of atomic_compare_exchange_strong.
CallInst *visitCallAtomicCmpXchg(CallInst *CI,
const std::string &DemangledName);
/// Transform atomic_init.
/// atomic_init(p, x) => store p, x
void visitCallAtomicInit(CallInst *CI);
/// Transform legacy OCL 1.x atomic builtins to SPIR-V builtins for extensions
/// cl_khr_int64_base_atomics
/// cl_khr_int64_extended_atomics
/// Do nothing if the called function is not a legacy atomic builtin.
void visitCallAtomicLegacy(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transform OCL 2.0 C++11 atomic builtins to SPIR-V builtins.
/// Do nothing if the called function is not a C++11 atomic builtin.
void visitCallAtomicCpp11(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transform OCL builtin function to SPIR-V builtin function.
/// Assuming there is a simple name mapping without argument changes.
/// Should be called at last.
void visitCallBuiltinSimple(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transform get_image_{width|height|depth|dim}.
/// get_image_xxx(...) =>
/// dimension = __spirv_ImageQuerySizeLod_R{ReturnType}(...);
/// return dimension.{x|y|z};
void visitCallGetImageSize(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transform {work|sub}_group_x =>
/// __spirv_{OpName}
///
/// Special handling of work_group_broadcast.
/// work_group_broadcast(a, x, y, z)
/// =>
/// __spirv_GroupBroadcast(a, vec3(x, y, z))
void visitCallGroupBuiltin(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transform mem_fence to __spirv_MemoryBarrier.
/// mem_fence(flag) => __spirv_MemoryBarrier(Workgroup, map(flag))
void visitCallMemFence(CallInst *CI);
void visitCallNDRange(CallInst *CI, const std::string &DemangledName);
/// Transform read_image with sampler arguments.
/// read_image(image, sampler, ...) =>
/// sampled_image = __spirv_SampledImage(image, sampler);
/// return __spirv_ImageSampleExplicitLod_R{ReturnType}(sampled_image, ...);
void visitCallReadImageWithSampler(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transform read_image with msaa image arguments.
/// Sample argument must be acoded as Image Operand.
void visitCallReadImageMSAA(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transform {read|write}_image without sampler arguments.
void visitCallReadWriteImage(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transform to_{global|local|private}.
///
/// T* a = ...;
/// addr T* b = to_addr(a);
/// =>
/// i8* x = cast<i8*>(a);
/// addr i8* y = __spirv_GenericCastToPtr_ToAddr(x);
/// addr T* b = cast<addr T*>(y);
void visitCallToAddr(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transform return type of relatinal built-in functions like isnan, isfinite
/// to boolean values.
void visitCallRelational(CallInst *CI, const std::string &DemangledName);
/// Transform vector load/store functions to SPIR-V extended builtin
/// functions
/// {vload|vstore{a}}{_half}{n}{_rte|_rtz|_rtp|_rtn} =>
/// __spirv_ocl_{ExtendedInstructionOpCodeName}__R{ReturnType}
void visitCallVecLoadStore(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transforms get_mem_fence built-in to SPIR-V function and aligns result
/// values with SPIR 1.2. get_mem_fence(ptr) => __spirv_GenericPtrMemSemantics
/// GenericPtrMemSemantics valid values are 0x100, 0x200 and 0x300, where is
/// SPIR 1.2 defines them as 0x1, 0x2 and 0x3, so this function adjusts
/// GenericPtrMemSemantics results to SPIR 1.2 values.
void visitCallGetFence(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transforms OpDot instructions with a scalar type to a fmul instruction
void visitCallDot(CallInst *CI);
/// Fixes for built-in functions with vector+scalar arguments that are
/// translated to the SPIR-V instructions where all arguments must have the
/// same type.
void visitCallScalToVec(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// Transform get_image_channel_{order|data_type} built-in functions to
/// __spirv_ocl_{ImageQueryOrder|ImageQueryFormat}
void visitCallGetImageChannel(CallInst *CI, StringRef MangledName,
const std::string &DemangledName,
unsigned int Offset);
/// Transform enqueue_kernel and kernel query built-in functions to
/// spirv-friendly format filling arguments, required for device-side enqueue
/// instructions, but missed in the original call
void visitCallEnqueueKernel(CallInst *CI, const std::string &DemangledName);
void visitCallKernelQuery(CallInst *CI, const std::string &DemangledName);
/// For cl_intel_subgroups block read built-ins:
void visitSubgroupBlockReadINTEL(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// For cl_intel_subgroups block write built-ins:
void visitSubgroupBlockWriteINTEL(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
/// For cl_intel_media_block_io built-ins:
void visitSubgroupImageMediaBlockINTEL(CallInst *CI,
const std::string &DemangledName);
// For cl_intel_device_side_avc_motion_estimation built-ins
void visitSubgroupAVCBuiltinCall(CallInst *CI, StringRef MangledName,
const std::string &DemangledName);
void visitSubgroupAVCWrapperBuiltinCall(CallInst *CI, Op WrappedOC,
const std::string &DemangledName);
void visitSubgroupAVCBuiltinCallWithSampler(CallInst *CI,
StringRef MangledName,
const std::string &DemangledName);
static char ID;
private:
Module *M;
LLVMContext *Ctx;
unsigned CLVer; /// OpenCL version as major*10+minor
std::set<Value *> ValuesToDelete;
ConstantInt *addInt32(int I) { return getInt32(M, I); }
ConstantInt *addSizet(uint64_t I) { return getSizet(M, I); }
/// Get vector width from OpenCL vload* function name.
SPIRVWord getVecLoadWidth(const std::string &DemangledName) {
SPIRVWord Width = 0;
if (DemangledName == "vloada_half")
Width = 1;
else {
unsigned Loc = 5;
if (DemangledName.find("vload_half") == 0)
Loc = 10;
else if (DemangledName.find("vloada_half") == 0)
Loc = 11;
std::stringstream SS(DemangledName.substr(Loc));
SS >> Width;
}
return Width;
}
/// Transform OpenCL vload/vstore function name.
void transVecLoadStoreName(std::string &DemangledName,
const std::string &Stem, bool AlwaysN) {
auto HalfStem = Stem + "_half";
auto HalfStemR = HalfStem + "_r";
if (!AlwaysN && DemangledName == HalfStem)
return;
if (!AlwaysN && DemangledName.find(HalfStemR) == 0) {
DemangledName = HalfStemR;
return;
}
if (DemangledName.find(HalfStem) == 0) {
auto OldName = DemangledName;
DemangledName = HalfStem + "n";
if (OldName.find("_r") != std::string::npos)
DemangledName += "_r";
return;
}
if (DemangledName.find(Stem) == 0) {
DemangledName = Stem + "n";
return;
}
}
};
char OCL20ToSPIRV::ID = 0;
bool OCL20ToSPIRV::runOnModule(Module &Module) {
M = &Module;
Ctx = &M->getContext();
auto Src = getSPIRVSource(&Module);
if (std::get<0>(Src) != spv::SourceLanguageOpenCL_C)
return false;
CLVer = std::get<1>(Src);
if (CLVer > kOCLVer::CL20)
return false;
LLVM_DEBUG(dbgs() << "Enter OCL20ToSPIRV:\n");
transWorkItemBuiltinsToVariables();
visit(*M);
for (auto &I : ValuesToDelete)
if (auto Inst = dyn_cast<Instruction>(I))
Inst->eraseFromParent();
for (auto &I : ValuesToDelete)
if (auto GV = dyn_cast<GlobalValue>(I))
GV->eraseFromParent();
eraseUselessFunctions(M); // remove unused functions declarations
LLVM_DEBUG(dbgs() << "After OCL20ToSPIRV:\n" << *M);
std::string Err;
raw_string_ostream ErrorOS(Err);
if (verifyModule(*M, &ErrorOS)) {
LLVM_DEBUG(errs() << "Fails to verify module: " << ErrorOS.str());
}
return true;
}
// The order of handling OCL builtin functions is important.
// Workgroup functions need to be handled before pipe functions since
// there are functions fall into both categories.
void OCL20ToSPIRV::visitCallInst(CallInst &CI) {
LLVM_DEBUG(dbgs() << "[visistCallInst] " << CI << '\n');
auto F = CI.getCalledFunction();
if (!F)
return;
auto MangledName = F->getName();
std::string DemangledName;
if (!oclIsBuiltin(MangledName, &DemangledName))
return;
LLVM_DEBUG(dbgs() << "DemangledName: " << DemangledName << '\n');
if (DemangledName.find(kOCLBuiltinName::NDRangePrefix) == 0) {
visitCallNDRange(&CI, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::All) {
visitCallAllAny(OpAll, &CI);
return;
}
if (DemangledName == kOCLBuiltinName::Any) {
visitCallAllAny(OpAny, &CI);
return;
}
if (DemangledName.find(kOCLBuiltinName::AsyncWorkGroupCopy) == 0 ||
DemangledName.find(kOCLBuiltinName::AsyncWorkGroupStridedCopy) == 0) {
visitCallAsyncWorkGroupCopy(&CI, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::AtomicPrefix) == 0 ||
DemangledName.find(kOCLBuiltinName::AtomPrefix) == 0) {
// Compute atomic builtins do not support floating types.
if (CI.getType()->isFloatingPointTy() &&
isComputeAtomicOCLBuiltin(DemangledName))
return;
auto PCI = &CI;
if (DemangledName == kOCLBuiltinName::AtomicInit) {
visitCallAtomicInit(PCI);
return;
}
if (DemangledName == kOCLBuiltinName::AtomicWorkItemFence) {
visitCallAtomicWorkItemFence(PCI);
return;
}
if (DemangledName == kOCLBuiltinName::AtomicCmpXchgWeak ||
DemangledName == kOCLBuiltinName::AtomicCmpXchgStrong ||
DemangledName == kOCLBuiltinName::AtomicCmpXchgWeakExplicit ||
DemangledName == kOCLBuiltinName::AtomicCmpXchgStrongExplicit) {
assert(CLVer == kOCLVer::CL20 && "Wrong version of OpenCL");
PCI = visitCallAtomicCmpXchg(PCI, DemangledName);
}
visitCallAtomicLegacy(PCI, MangledName, DemangledName);
visitCallAtomicCpp11(PCI, MangledName, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::ConvertPrefix) == 0) {
visitCallConvert(&CI, MangledName, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::GetImageWidth ||
DemangledName == kOCLBuiltinName::GetImageHeight ||
DemangledName == kOCLBuiltinName::GetImageDepth ||
DemangledName == kOCLBuiltinName::GetImageDim ||
DemangledName == kOCLBuiltinName::GetImageArraySize) {
visitCallGetImageSize(&CI, MangledName, DemangledName);
return;
}
if ((DemangledName.find(kOCLBuiltinName::WorkGroupPrefix) == 0 &&
DemangledName != kOCLBuiltinName::WorkGroupBarrier) ||
DemangledName == kOCLBuiltinName::WaitGroupEvent ||
(DemangledName.find(kOCLBuiltinName::SubGroupPrefix) == 0 &&
DemangledName != kOCLBuiltinName::SubGroupBarrier)) {
visitCallGroupBuiltin(&CI, MangledName, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::MemFence) {
visitCallMemFence(&CI);
return;
}
if (DemangledName.find(kOCLBuiltinName::ReadImage) == 0) {
if (MangledName.find(kMangledName::Sampler) != StringRef::npos) {
visitCallReadImageWithSampler(&CI, MangledName, DemangledName);
return;
}
if (MangledName.find("msaa") != StringRef::npos) {
visitCallReadImageMSAA(&CI, MangledName, DemangledName);
return;
}
}
if (DemangledName.find(kOCLBuiltinName::ReadImage) == 0 ||
DemangledName.find(kOCLBuiltinName::WriteImage) == 0) {
visitCallReadWriteImage(&CI, MangledName, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::ToGlobal ||
DemangledName == kOCLBuiltinName::ToLocal ||
DemangledName == kOCLBuiltinName::ToPrivate) {
visitCallToAddr(&CI, MangledName, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::VLoadPrefix) == 0 ||
DemangledName.find(kOCLBuiltinName::VStorePrefix) == 0) {
visitCallVecLoadStore(&CI, MangledName, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::IsFinite ||
DemangledName == kOCLBuiltinName::IsInf ||
DemangledName == kOCLBuiltinName::IsNan ||
DemangledName == kOCLBuiltinName::IsNormal ||
DemangledName == kOCLBuiltinName::Signbit) {
visitCallRelational(&CI, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::WorkGroupBarrier ||
DemangledName == kOCLBuiltinName::Barrier ||
DemangledName == kOCLBuiltinName::SubGroupBarrier) {
visitCallBarrier(&CI);
return;
}
if (DemangledName == kOCLBuiltinName::GetFence) {
visitCallGetFence(&CI, MangledName, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::Dot &&
!(CI.getOperand(0)->getType()->isVectorTy())) {
visitCallDot(&CI);
return;
}
if (DemangledName == kOCLBuiltinName::FMin ||
DemangledName == kOCLBuiltinName::FMax ||
DemangledName == kOCLBuiltinName::Min ||
DemangledName == kOCLBuiltinName::Max ||
DemangledName == kOCLBuiltinName::Step ||
DemangledName == kOCLBuiltinName::SmoothStep ||
DemangledName == kOCLBuiltinName::Clamp ||
DemangledName == kOCLBuiltinName::Mix) {
visitCallScalToVec(&CI, MangledName, DemangledName);
return;
}
if (DemangledName == kOCLBuiltinName::GetImageChannelDataType) {
visitCallGetImageChannel(&CI, MangledName, DemangledName,
OCLImageChannelDataTypeOffset);
return;
}
if (DemangledName == kOCLBuiltinName::GetImageChannelOrder) {
visitCallGetImageChannel(&CI, MangledName, DemangledName,
OCLImageChannelOrderOffset);
return;
}
if (isEnqueueKernelBI(MangledName)) {
visitCallEnqueueKernel(&CI, DemangledName);
return;
}
if (isKernelQueryBI(MangledName)) {
visitCallKernelQuery(&CI, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::SubgroupBlockReadINTELPrefix) == 0) {
visitSubgroupBlockReadINTEL(&CI, MangledName, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::SubgroupBlockWriteINTELPrefix) == 0) {
visitSubgroupBlockWriteINTEL(&CI, MangledName, DemangledName);
return;
}
if (DemangledName.find(kOCLBuiltinName::SubgroupImageMediaBlockINTELPrefix) ==
0) {
visitSubgroupImageMediaBlockINTEL(&CI, DemangledName);
return;
}
// Handle 'cl_intel_device_side_avc_motion_estimation' extension built-ins
if (DemangledName.find(kOCLSubgroupsAVCIntel::Prefix) == 0 ||
// Workaround for a bug in the extension specification
DemangledName.find("intel_sub_group_ime_ref_window_size") == 0) {
if (MangledName.find(kMangledName::Sampler) != StringRef::npos)
visitSubgroupAVCBuiltinCallWithSampler(&CI, MangledName, DemangledName);
else
visitSubgroupAVCBuiltinCall(&CI, MangledName, DemangledName);
return;
}
visitCallBuiltinSimple(&CI, MangledName, DemangledName);
}
void OCL20ToSPIRV::visitCallNDRange(CallInst *CI,
const std::string &DemangledName) {
assert(DemangledName.find(kOCLBuiltinName::NDRangePrefix) == 0);
std::string LenStr = DemangledName.substr(8, 1);
auto Len = atoi(LenStr.c_str());
assert(Len >= 1 && Len <= 3);
// SPIR-V ndrange structure requires 3 members in the following order:
// global work offset
// global work size
// local work size
// The arguments need to add missing members.
AttributeList Attrs = CI->getCalledFunction()->getAttributes();
mutateCallInstSPIRV(
M, CI,
[=](CallInst *, std::vector<Value *> &Args) {
for (size_t I = 1, E = Args.size(); I != E; ++I)
Args[I] = getScalarOrArray(Args[I], Len, CI);
switch (Args.size()) {
case 2: {
// Has global work size.
auto T = Args[1]->getType();
auto C = getScalarOrArrayConstantInt(CI, T, Len, 0);
Args.push_back(C);
Args.push_back(C);
} break;
case 3: {
// Has global and local work size.
auto T = Args[1]->getType();
Args.push_back(getScalarOrArrayConstantInt(CI, T, Len, 0));
} break;
case 4: {
// Move offset arg to the end
auto OffsetPos = Args.begin() + 1;
Value *OffsetVal = *OffsetPos;
Args.erase(OffsetPos);
Args.push_back(OffsetVal);
} break;
default:
assert(0 && "Invalid number of arguments");
}
// Translate ndrange_ND into differently named SPIR-V decorated
// functions because they have array arugments of different dimension
// which mangled the same way.
return getSPIRVFuncName(OpBuildNDRange, "_" + LenStr + "D");
},
&Attrs);
}
void OCL20ToSPIRV::visitCallAsyncWorkGroupCopy(
CallInst *CI, const std::string &DemangledName) {
assert(CI->getCalledFunction() && "Unexpected indirect call");
AttributeList Attrs = CI->getCalledFunction()->getAttributes();
mutateCallInstSPIRV(M, CI,
[=](CallInst *, std::vector<Value *> &Args) {
if (DemangledName ==
OCLUtil::kOCLBuiltinName::AsyncWorkGroupCopy) {
Args.insert(Args.begin() + 3, addSizet(1));
}
Args.insert(Args.begin(), addInt32(ScopeWorkgroup));
return getSPIRVFuncName(OpGroupAsyncCopy);
},
&Attrs);
}
CallInst *
OCL20ToSPIRV::visitCallAtomicCmpXchg(CallInst *CI,
const std::string &DemangledName) {
AttributeList Attrs = CI->getCalledFunction()->getAttributes();
Value *Expected = nullptr;
CallInst *NewCI = nullptr;
mutateCallInstOCL(
M, CI,
[&](CallInst *CI, std::vector<Value *> &Args, Type *&RetTy) {
Expected = Args[1]; // temporary save second argument.
Args[1] = new LoadInst(Args[1], "exp", false, CI);
RetTy = Args[2]->getType();
assert(Args[0]->getType()->getPointerElementType()->isIntegerTy() &&
Args[1]->getType()->isIntegerTy() &&
Args[2]->getType()->isIntegerTy() &&
"In SPIR-V 1.0 arguments of OpAtomicCompareExchange must be "
"an integer type scalars");
return kOCLBuiltinName::AtomicCmpXchgStrong;
},
[&](CallInst *NCI) -> Instruction * {
NewCI = NCI;
Instruction *Store = new StoreInst(NCI, Expected, NCI->getNextNode());
return new ICmpInst(Store->getNextNode(), CmpInst::ICMP_EQ, NCI,
NCI->getArgOperand(1));
},
&Attrs);
return NewCI;
}
void OCL20ToSPIRV::visitCallAtomicInit(CallInst *CI) {
auto ST = new StoreInst(CI->getArgOperand(1), CI->getArgOperand(0), CI);
ST->takeName(CI);
CI->dropAllReferences();
CI->eraseFromParent();
}
void OCL20ToSPIRV::visitCallAllAny(spv::Op OC, CallInst *CI) {
assert(CI->getCalledFunction() && "Unexpected indirect call");
AttributeList Attrs = CI->getCalledFunction()->getAttributes();
auto Args = getArguments(CI);
assert(Args.size() == 1);
auto *ArgTy = Args[0]->getType();
auto Zero = Constant::getNullValue(Args[0]->getType());
auto *Cmp = CmpInst::Create(CmpInst::ICmp, CmpInst::ICMP_SLT, Args[0], Zero,
"cast", CI);
if (!isa<VectorType>(ArgTy)) {
auto *Cast = CastInst::CreateZExtOrBitCast(Cmp, Type::getInt32Ty(*Ctx), "",
Cmp->getNextNode());
CI->replaceAllUsesWith(Cast);
CI->eraseFromParent();
} else {
mutateCallInstSPIRV(
M, CI,
[&](CallInst *, std::vector<Value *> &Args, Type *&Ret) {
Args[0] = Cmp;
Ret = Type::getInt1Ty(*Ctx);
return getSPIRVFuncName(OC);
},
[&](CallInst *CI) -> Instruction * {
return CastInst::CreateZExtOrBitCast(CI, Type::getInt32Ty(*Ctx), "",
CI->getNextNode());
},
&Attrs);
}
}
void OCL20ToSPIRV::visitCallAtomicWorkItemFence(CallInst *CI) {
transMemoryBarrier(CI, getAtomicWorkItemFenceLiterals(CI));
}
void OCL20ToSPIRV::visitCallMemFence(CallInst *CI) {
transMemoryBarrier(
CI,
std::make_tuple(cast<ConstantInt>(CI->getArgOperand(0))->getZExtValue(),
OCLMO_relaxed, OCLMS_work_group));
}
void OCL20ToSPIRV::transMemoryBarrier(CallInst *CI,
AtomicWorkItemFenceLiterals Lit) {
assert(CI->getCalledFunction() && "Unexpected indirect call");
AttributeList Attrs = CI->getCalledFunction()->getAttributes();
mutateCallInstSPIRV(M, CI,
[=](CallInst *, std::vector<Value *> &Args) {
Args.resize(2);
Args[0] = addInt32(map<Scope>(std::get<2>(Lit)));
Args[1] = addInt32(mapOCLMemSemanticToSPIRV(
std::get<0>(Lit), std::get<1>(Lit)));
return getSPIRVFuncName(OpMemoryBarrier);
},
&Attrs);
}
void OCL20ToSPIRV::visitCallAtomicLegacy(CallInst *CI, StringRef MangledName,
const std::string &DemangledName) {
StringRef Stem = DemangledName;
if (Stem.startswith("atom_"))
Stem = Stem.drop_front(strlen("atom_"));
else if (Stem.startswith("atomic_"))
Stem = Stem.drop_front(strlen("atomic_"));
else
return;
std::string Sign;
std::string Postfix;
std::string Prefix;
if (Stem == "add" || Stem == "sub" || Stem == "and" || Stem == "or" ||
Stem == "xor" || Stem == "min" || Stem == "max") {
if ((Stem == "min" || Stem == "max") &&
isMangledTypeUnsigned(MangledName.back()))
Sign = 'u';
Prefix = "fetch_";
Postfix = "_explicit";
} else if (Stem == "xchg") {
Stem = "exchange";
Postfix = "_explicit";
} else if (Stem == "cmpxchg") {
Stem = "compare_exchange_strong";
Postfix = "_explicit";
} else if (Stem == "inc" || Stem == "dec") {
// do nothing
} else
return;
OCLBuiltinTransInfo Info;
Info.UniqName = "atomic_" + Prefix + Sign + Stem.str() + Postfix;
std::vector<int> PostOps;
PostOps.push_back(OCLLegacyAtomicMemOrder);
if (Stem.startswith("compare_exchange"))
PostOps.push_back(OCLLegacyAtomicMemOrder);
PostOps.push_back(OCLLegacyAtomicMemScope);
Info.PostProc = [=](std::vector<Value *> &Ops) {
for (auto &I : PostOps) {
Ops.push_back(addInt32(I));
}
};
transAtomicBuiltin(CI, Info);
}
void OCL20ToSPIRV::visitCallAtomicCpp11(CallInst *CI, StringRef MangledName,
const std::string &DemangledName) {
StringRef Stem = DemangledName;
if (Stem.startswith("atomic_"))
Stem = Stem.drop_front(strlen("atomic_"));
else
return;
std::string NewStem = Stem;
std::vector<int> PostOps;
if (Stem.startswith("store") || Stem.startswith("load") ||
Stem.startswith("exchange") || Stem.startswith("compare_exchange") ||
Stem.startswith("fetch") || Stem.startswith("flag")) {
if ((Stem.startswith("fetch_min") || Stem.startswith("fetch_max")) &&
containsUnsignedAtomicType(MangledName))
NewStem.insert(NewStem.begin() + strlen("fetch_"), 'u');
if (!Stem.endswith("_explicit")) {
NewStem = NewStem + "_explicit";
PostOps.push_back(OCLMO_seq_cst);
if (Stem.startswith("compare_exchange"))
PostOps.push_back(OCLMO_seq_cst);
PostOps.push_back(OCLMS_device);
} else {
auto MaxOps =
getOCLCpp11AtomicMaxNumOps(Stem.drop_back(strlen("_explicit")));
if (CI->getNumArgOperands() < MaxOps)
PostOps.push_back(OCLMS_device);
}
} else if (Stem == "work_item_fence") {
// do nothing
} else
return;
OCLBuiltinTransInfo Info;
Info.UniqName = std::string("atomic_") + NewStem;
Info.PostProc = [=](std::vector<Value *> &Ops) {
for (auto &I : PostOps) {
Ops.push_back(addInt32(I));
}
};
transAtomicBuiltin(CI, Info);
}
void OCL20ToSPIRV::transAtomicBuiltin(CallInst *CI, OCLBuiltinTransInfo &Info) {
AttributeList Attrs = CI->getCalledFunction()->getAttributes();
mutateCallInstSPIRV(
M, CI,
[=](CallInst *CI, std::vector<Value *> &Args) {
Info.PostProc(Args);
// Order of args in OCL20:
// object, 0-2 other args, 1-2 order, scope
const size_t NumOrder =
getAtomicBuiltinNumMemoryOrderArgs(Info.UniqName);
const size_t ArgsCount = Args.size();
const size_t ScopeIdx = ArgsCount - 1;
const size_t OrderIdx = ScopeIdx - NumOrder;
if (auto ScopeInt = dyn_cast_or_null<ConstantInt>(Args[ScopeIdx])) {
Args[ScopeIdx] = mapUInt(M, ScopeInt, [](unsigned I) {
return map<Scope>(static_cast<OCLScopeKind>(I));
});
} else {
// SPIR-V 1.3 r6 s2.16.2: All <id> used for Scope and Memory
// Semantics must be of an OpConstant.
Ctx->emitError(CI, "memory_scope argument needs to be constant");
}
for (size_t I = 0; I < NumOrder; ++I) {
if (auto OrderInt =
dyn_cast_or_null<ConstantInt>(Args[OrderIdx + I])) {
Args[OrderIdx + I] = mapUInt(M, OrderInt, [](unsigned Ord) {
return mapOCLMemSemanticToSPIRV(
0, static_cast<OCLMemOrderKind>(Ord));
});
} else {
// SPIR-V 1.3 r6 s2.16.2: All <id> used for Scope and Memory
// Semantics must be of an OpConstant.
Ctx->emitError(CI, "memory_order argument needs to be constant");
}
}
// Order of args in SPIR-V:
// object, scope, 1-2 order, 0-2 other args
std::swap(Args[1], Args[ScopeIdx]);
if (OrderIdx > 2) {
// For atomic_compare_exchange the swap above puts Comparator/Expected
// argument just where it should be, so don't move the last argument
// then.
int Offset =
Info.UniqName.find("atomic_compare_exchange") == 0 ? 1 : 0;
std::rotate(Args.begin() + 2, Args.begin() + OrderIdx,
Args.end() - Offset);
}
return getSPIRVFuncName(OCLSPIRVBuiltinMap::map(Info.UniqName));
},
&Attrs);
}
void OCL20ToSPIRV::visitCallBarrier(CallInst *CI) {
auto Lit = getBarrierLiterals(CI);
AttributeList Attrs = CI->getCalledFunction()->getAttributes();
mutateCallInstSPIRV(M, CI,
[=](CallInst *, std::vector<Value *> &Args) {
Args.resize(3);
// Execution scope
Args[0] = addInt32(map<Scope>(std::get<2>(Lit)));
// Memory scope
Args[1] = addInt32(map<Scope>(std::get<1>(Lit)));
// Use sequential consistent memory order by default.
// But if the flags argument is set to 0, we use
// None(Relaxed) memory order.
unsigned MemFenceFlag = std::get<0>(Lit);
OCLMemOrderKind MemOrder =
MemFenceFlag ? OCLMO_seq_cst : OCLMO_relaxed;
Args[2] = addInt32(mapOCLMemSemanticToSPIRV(
MemFenceFlag, MemOrder)); // Memory semantics
return getSPIRVFuncName(OpControlBarrier);
},
&Attrs);
}
void OCL20ToSPIRV::visitCallConvert(CallInst *CI, StringRef MangledName,
const std::string &DemangledName) {
if (eraseUselessConvert(CI, MangledName, DemangledName))
return;
Op OC = OpNop;
auto TargetTy = CI->getType();
auto SrcTy = CI->getArgOperand(0)->getType();
if (isa<VectorType>(TargetTy))
TargetTy = TargetTy->getVectorElementType();
if (isa<VectorType>(SrcTy))
SrcTy = SrcTy->getVectorElementType();
auto IsTargetInt = isa<IntegerType>(TargetTy);
std::string TargetTyName =
DemangledName.substr(strlen(kOCLBuiltinName::ConvertPrefix));
auto FirstUnderscoreLoc = TargetTyName.find('_');
if (FirstUnderscoreLoc != std::string::npos)
TargetTyName = TargetTyName.substr(0, FirstUnderscoreLoc);
TargetTyName = std::string("_R") + TargetTyName;
std::string Sat =
DemangledName.find("_sat") != std::string::npos ? "_sat" : "";
auto TargetSigned = DemangledName[8] != 'u';
if (isa<IntegerType>(SrcTy)) {
bool Signed = isLastFuncParamSigned(MangledName);
if (IsTargetInt) {
if (!Sat.empty() && TargetSigned != Signed) {
OC = Signed ? OpSatConvertSToU : OpSatConvertUToS;
Sat = "";
} else
OC = Signed ? OpSConvert : OpUConvert;
} else
OC = Signed ? OpConvertSToF : OpConvertUToF;
} else {
if (IsTargetInt) {
OC = TargetSigned ? OpConvertFToS : OpConvertFToU;
} else
OC = OpFConvert;
}
auto Loc = DemangledName.find("_rt");
std::string Rounding;
if (Loc != std::string::npos && !(isa<IntegerType>(SrcTy) && IsTargetInt)) {
Rounding = DemangledName.substr(Loc, 4);
}
assert(CI->getCalledFunction() && "Unexpected indirect call");
AttributeList Attrs = CI->getCalledFunction()->getAttributes();
mutateCallInstSPIRV(M, CI,
[=](CallInst *, std::vector<Value *> &Args) {
return getSPIRVFuncName(OC,
TargetTyName + Sat + Rounding);
},
&Attrs);
}
void OCL20ToSPIRV::visitCallGroupBuiltin(CallInst *CI, StringRef MangledName,
const std::string &OrigDemangledName) {
auto F = CI->getCalledFunction();
std::vector<int> PreOps;
std::string DemangledName = OrigDemangledName;
if (DemangledName == kOCLBuiltinName::WorkGroupBarrier)
return;
if (DemangledName == kOCLBuiltinName::WaitGroupEvent) {
PreOps.push_back(ScopeWorkgroup);
} else if (DemangledName.find(kOCLBuiltinName::WorkGroupPrefix) == 0) {
DemangledName.erase(0, strlen(kOCLBuiltinName::WorkPrefix));
PreOps.push_back(ScopeWorkgroup);
} else if (DemangledName.find(kOCLBuiltinName::SubGroupPrefix) == 0) {
DemangledName.erase(0, strlen(kOCLBuiltinName::SubPrefix));
PreOps.push_back(ScopeSubgroup);
} else
return;
if (DemangledName != kOCLBuiltinName::WaitGroupEvent) {
StringRef GroupOp = DemangledName;
GroupOp = GroupOp.drop_front(strlen(kSPIRVName::GroupPrefix));
SPIRSPIRVGroupOperationMap::foreachConditional(
[&](const std::string &S, SPIRVGroupOperationKind G) {
if (!GroupOp.startswith(S))
return true; // continue
PreOps.push_back(G);
StringRef Op = GroupOp.drop_front(S.size() + 1);
assert(!Op.empty() && "Invalid OpenCL group builtin function");
char OpTyC = 0;
auto NeedSign = Op == "max" || Op == "min";
auto OpTy = F->getReturnType();
if (OpTy->isFloatingPointTy())
OpTyC = 'f';
else if (OpTy->isIntegerTy()) {
if (!NeedSign)
OpTyC = 'i';
else {
if (isLastFuncParamSigned(F->getName()))
OpTyC = 's';
else
OpTyC = 'u';
}
} else
llvm_unreachable("Invalid OpenCL group builtin argument type");
DemangledName =
std::string(kSPIRVName::GroupPrefix) + OpTyC + Op.str();
return false; // break out of loop
});
}
bool IsGroupAllAny = (DemangledName.find("_all") != std::string::npos ||
DemangledName.find("_any") != std::string::npos);