blob: 11654f7bf46ee0c4d43a2e5714d609eb09cb4d90 [file] [log] [blame]
David Neto22f144c2017-06-12 14:26:21 -04001// Copyright 2017 The Clspv Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
David Neto62653202017-10-16 19:05:18 -040015#include <math.h>
16#include <string>
17#include <tuple>
18
Kévin Petit9d1a9d12019-03-25 15:23:46 +000019#include "llvm/ADT/StringSwitch.h"
David Neto118188e2018-08-24 11:27:54 -040020#include "llvm/IR/Constants.h"
David Neto118188e2018-08-24 11:27:54 -040021#include "llvm/IR/IRBuilder.h"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040022#include "llvm/IR/Instructions.h"
David Neto118188e2018-08-24 11:27:54 -040023#include "llvm/IR/Module.h"
Kévin Petitf5b78a22018-10-25 14:32:17 +000024#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040025#include "llvm/Pass.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040029
alan-bakere0902602020-03-23 08:43:40 -040030#include "spirv/unified1/spirv.hpp"
David Neto22f144c2017-06-12 14:26:21 -040031
alan-baker931d18a2019-12-12 08:21:32 -050032#include "clspv/AddressSpace.h"
James Pricec05f6052020-01-14 13:37:20 -050033#include "clspv/DescriptorMap.h"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040034#include "clspv/Option.h"
David Neto482550a2018-03-24 05:21:07 -070035
SJW2c317da2020-03-23 07:39:13 -050036#include "Builtins.h"
alan-baker931d18a2019-12-12 08:21:32 -050037#include "Constants.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040038#include "Passes.h"
39#include "SPIRVOp.h"
alan-bakerf906d2b2019-12-10 11:26:23 -050040#include "Types.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040041
SJW2c317da2020-03-23 07:39:13 -050042using namespace clspv;
David Neto22f144c2017-06-12 14:26:21 -040043using namespace llvm;
44
45#define DEBUG_TYPE "ReplaceOpenCLBuiltin"
46
47namespace {
Kévin Petit8a560882019-03-21 15:24:34 +000048
David Neto22f144c2017-06-12 14:26:21 -040049uint32_t clz(uint32_t v) {
50 uint32_t r;
51 uint32_t shift;
52
53 r = (v > 0xFFFF) << 4;
54 v >>= r;
55 shift = (v > 0xFF) << 3;
56 v >>= shift;
57 r |= shift;
58 shift = (v > 0xF) << 2;
59 v >>= shift;
60 r |= shift;
61 shift = (v > 0x3) << 1;
62 v >>= shift;
63 r |= shift;
64 r |= (v >> 1);
65
66 return r;
67}
68
Kévin Petitfdfa92e2019-09-25 14:20:58 +010069Type *getIntOrIntVectorTyForCast(LLVMContext &C, Type *Ty) {
70 Type *IntTy = Type::getIntNTy(C, Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -040071 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
72 IntTy = VectorType::get(IntTy, vec_ty->getNumElements());
Kévin Petitfdfa92e2019-09-25 14:20:58 +010073 }
74 return IntTy;
75}
76
SJW2c317da2020-03-23 07:39:13 -050077bool replaceCallsWithValue(Function &F,
78 std::function<Value *(CallInst *)> Replacer) {
79
80 bool Changed = false;
81
82 SmallVector<Instruction *, 4> ToRemoves;
83
84 // Walk the users of the function.
85 for (auto &U : F.uses()) {
86 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
87
88 auto NewValue = Replacer(CI);
89
90 if (NewValue != nullptr) {
91 CI->replaceAllUsesWith(NewValue);
92
93 // Lastly, remember to remove the user.
94 ToRemoves.push_back(CI);
95 }
96 }
97 }
98
99 Changed = !ToRemoves.empty();
100
101 // And cleanup the calls we don't use anymore.
102 for (auto V : ToRemoves) {
103 V->eraseFromParent();
104 }
105
106 return Changed;
107}
108
David Neto22f144c2017-06-12 14:26:21 -0400109struct ReplaceOpenCLBuiltinPass final : public ModulePass {
110 static char ID;
111 ReplaceOpenCLBuiltinPass() : ModulePass(ID) {}
112
113 bool runOnModule(Module &M) override;
SJW2c317da2020-03-23 07:39:13 -0500114 bool runOnFunction(Function &F);
115 bool replaceAbs(Function &F);
116 bool replaceAbsDiff(Function &F, bool is_signed);
117 bool replaceCopysign(Function &F);
118 bool replaceRecip(Function &F);
119 bool replaceDivide(Function &F);
120 bool replaceDot(Function &F);
121 bool replaceFmod(Function &F);
122 bool replaceExp10(Function &F, const std::string &basename, int vec_size,
123 int byte_len);
124 bool replaceLog10(Function &F, const std::string &basename, int vec_size,
125 int byte_len);
126 bool replaceBarrier(Function &F);
127 bool replaceMemFence(Function &F, uint32_t semantics);
Kévin Petit1cb45112020-04-27 18:55:48 +0100128 bool replacePrefetch(Function &F);
SJW2c317da2020-03-23 07:39:13 -0500129 bool replaceRelational(Function &F, CmpInst::Predicate P, int32_t C);
130 bool replaceIsInfAndIsNan(Function &F, spv::Op SPIRVOp, int32_t isvec);
131 bool replaceIsFinite(Function &F);
132 bool replaceAllAndAny(Function &F, spv::Op SPIRVOp);
133 bool replaceUpsample(Function &F);
134 bool replaceRotate(Function &F);
135 bool replaceConvert(Function &F, bool SrcIsSigned, bool DstIsSigned);
136 bool replaceMulHi(Function &F, bool is_signed, bool is_mad = false);
137 bool replaceSelect(Function &F);
138 bool replaceBitSelect(Function &F);
139 bool replaceStep(Function &F, bool is_smooth, int vec_size);
140 bool replaceSignbit(Function &F, bool is_vec);
141 bool replaceMul(Function &F, bool is_float, bool is_mad);
142 bool replaceVloadHalf(Function &F, const std::string &name, int vec_size);
143 bool replaceVloadHalf(Function &F);
144 bool replaceVloadHalf2(Function &F);
145 bool replaceVloadHalf4(Function &F);
146 bool replaceClspvVloadaHalf2(Function &F);
147 bool replaceClspvVloadaHalf4(Function &F);
148 bool replaceVstoreHalf(Function &F, int vec_size);
149 bool replaceVstoreHalf(Function &F);
150 bool replaceVstoreHalf2(Function &F);
151 bool replaceVstoreHalf4(Function &F);
152 bool replaceHalfReadImage(Function &F);
153 bool replaceHalfWriteImage(Function &F);
154 bool replaceSampledReadImageWithIntCoords(Function &F);
155 bool replaceAtomics(Function &F, spv::Op Op);
156 bool replaceAtomics(Function &F, llvm::AtomicRMWInst::BinOp Op);
157 bool replaceCross(Function &F);
158 bool replaceFract(Function &F, int vec_size);
159 bool replaceVload(Function &F);
160 bool replaceVstore(Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400161};
SJW2c317da2020-03-23 07:39:13 -0500162
Kévin Petit91bc72e2019-04-08 15:17:46 +0100163} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400164
165char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400166INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
167 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400168
169namespace clspv {
170ModulePass *createReplaceOpenCLBuiltinPass() {
171 return new ReplaceOpenCLBuiltinPass();
172}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400173} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400174
175bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500176 std::list<Function *> func_list;
177 for (auto &F : M.getFunctionList()) {
178 // process only function declarations
179 if (F.isDeclaration() && runOnFunction(F)) {
180 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000181 }
182 }
SJW2c317da2020-03-23 07:39:13 -0500183 if (func_list.size() != 0) {
184 // recursively convert functions, but first remove dead
185 for (auto *F : func_list) {
186 if (F->use_empty()) {
187 F->eraseFromParent();
188 }
189 }
190 runOnModule(M);
191 return true;
192 }
193 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000194}
195
SJW2c317da2020-03-23 07:39:13 -0500196bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
197 auto &FI = Builtins::Lookup(&F);
198 switch (FI.getType()) {
199 case Builtins::kAbs:
200 if (!FI.getParameter(0).is_signed) {
201 return replaceAbs(F);
202 }
203 break;
204 case Builtins::kAbsDiff:
205 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
206 case Builtins::kCopysign:
207 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100208
SJW2c317da2020-03-23 07:39:13 -0500209 case Builtins::kHalfRecip:
210 case Builtins::kNativeRecip:
211 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100212
SJW2c317da2020-03-23 07:39:13 -0500213 case Builtins::kHalfDivide:
214 case Builtins::kNativeDivide:
215 return replaceDivide(F);
216
217 case Builtins::kDot:
218 return replaceDot(F);
219
220 case Builtins::kExp10:
221 case Builtins::kHalfExp10:
222 case Builtins::kNativeExp10: {
223 auto &P0 = FI.getParameter(0);
224 return replaceExp10(F, FI.getName(), P0.vector_size, P0.byte_len);
225 }
226
227 case Builtins::kLog10:
228 case Builtins::kHalfLog10:
229 case Builtins::kNativeLog10: {
230 auto &P0 = FI.getParameter(0);
231 return replaceLog10(F, FI.getName(), P0.vector_size, P0.byte_len);
232 }
233
234 case Builtins::kFmod:
235 return replaceFmod(F);
236
237 case Builtins::kBarrier:
238 case Builtins::kWorkGroupBarrier:
239 return replaceBarrier(F);
240
241 case Builtins::kMemFence:
242 return replaceMemFence(F, spv::MemorySemanticsSequentiallyConsistentMask);
243 case Builtins::kReadMemFence:
244 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
245 case Builtins::kWriteMemFence:
246 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
247
248 // Relational
249 case Builtins::kIsequal:
250 return replaceRelational(F, CmpInst::FCMP_OEQ,
251 FI.getParameter(0).vector_size ? -1 : 1);
252 case Builtins::kIsgreater:
253 return replaceRelational(F, CmpInst::FCMP_OGT,
254 FI.getParameter(0).vector_size ? -1 : 1);
255 case Builtins::kIsgreaterequal:
256 return replaceRelational(F, CmpInst::FCMP_OGE,
257 FI.getParameter(0).vector_size ? -1 : 1);
258 case Builtins::kIsless:
259 return replaceRelational(F, CmpInst::FCMP_OLT,
260 FI.getParameter(0).vector_size ? -1 : 1);
261 case Builtins::kIslessequal:
262 return replaceRelational(F, CmpInst::FCMP_OLE,
263 FI.getParameter(0).vector_size ? -1 : 1);
264 case Builtins::kIsnotequal:
265 return replaceRelational(F, CmpInst::FCMP_ONE,
266 FI.getParameter(0).vector_size ? -1 : 1);
267
268 case Builtins::kIsinf: {
269 bool is_vec = FI.getParameter(0).vector_size != 0;
270 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
271 }
272 case Builtins::kIsnan: {
273 bool is_vec = FI.getParameter(0).vector_size != 0;
274 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
275 }
276
277 case Builtins::kIsfinite:
278 return replaceIsFinite(F);
279
280 case Builtins::kAll: {
281 bool is_vec = FI.getParameter(0).vector_size != 0;
282 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
283 }
284 case Builtins::kAny: {
285 bool is_vec = FI.getParameter(0).vector_size != 0;
286 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
287 }
288
289 case Builtins::kUpsample:
290 return replaceUpsample(F);
291
292 case Builtins::kRotate:
293 return replaceRotate(F);
294
295 case Builtins::kConvert:
296 return replaceConvert(F, FI.getParameter(0).is_signed,
297 FI.getReturnType().is_signed);
298
299 case Builtins::kAtomicInc:
300 return replaceAtomics(F, spv::OpAtomicIIncrement);
301 case Builtins::kAtomicDec:
302 return replaceAtomics(F, spv::OpAtomicIDecrement);
303 case Builtins::kAtomicCmpxchg:
304 return replaceAtomics(F, spv::OpAtomicCompareExchange);
305 case Builtins::kAtomicAdd:
306 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
307 case Builtins::kAtomicSub:
308 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
309 case Builtins::kAtomicXchg:
310 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
311 case Builtins::kAtomicMin:
312 return replaceAtomics(F, FI.getParameter(0).is_signed
313 ? llvm::AtomicRMWInst::Min
314 : llvm::AtomicRMWInst::UMin);
315 case Builtins::kAtomicMax:
316 return replaceAtomics(F, FI.getParameter(0).is_signed
317 ? llvm::AtomicRMWInst::Max
318 : llvm::AtomicRMWInst::UMax);
319 case Builtins::kAtomicAnd:
320 return replaceAtomics(F, llvm::AtomicRMWInst::And);
321 case Builtins::kAtomicOr:
322 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
323 case Builtins::kAtomicXor:
324 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
325
326 case Builtins::kCross:
327 if (FI.getParameter(0).vector_size == 4) {
328 return replaceCross(F);
329 }
330 break;
331
332 case Builtins::kFract:
333 if (FI.getParameterCount()) {
334 return replaceFract(F, FI.getParameter(0).vector_size);
335 }
336 break;
337
338 case Builtins::kMadHi:
339 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
340 case Builtins::kMulHi:
341 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
342
343 case Builtins::kMad:
344 case Builtins::kMad24:
345 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
346 true);
347 case Builtins::kMul24:
348 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
349 false);
350
351 case Builtins::kSelect:
352 return replaceSelect(F);
353
354 case Builtins::kBitselect:
355 return replaceBitSelect(F);
356
357 case Builtins::kVload:
358 return replaceVload(F);
359
360 case Builtins::kVloadaHalf:
361 case Builtins::kVloadHalf:
362 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
363
364 case Builtins::kVstore:
365 return replaceVstore(F);
366
367 case Builtins::kVstoreHalf:
368 case Builtins::kVstoreaHalf:
369 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
370
371 case Builtins::kSmoothstep: {
372 int vec_size = FI.getLastParameter().vector_size;
373 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
374 return replaceStep(F, true, vec_size);
375 }
376 break;
377 }
378 case Builtins::kStep: {
379 int vec_size = FI.getLastParameter().vector_size;
380 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
381 return replaceStep(F, false, vec_size);
382 }
383 break;
384 }
385
386 case Builtins::kSignbit:
387 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
388
389 case Builtins::kReadImageh:
390 return replaceHalfReadImage(F);
391 case Builtins::kReadImagef:
392 case Builtins::kReadImagei:
393 case Builtins::kReadImageui: {
394 if (FI.getParameter(1).isSampler() &&
395 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
396 return replaceSampledReadImageWithIntCoords(F);
397 }
398 break;
399 }
400
401 case Builtins::kWriteImageh:
402 return replaceHalfWriteImage(F);
403
Kévin Petit1cb45112020-04-27 18:55:48 +0100404 case Builtins::kPrefetch:
405 return replacePrefetch(F);
406
SJW2c317da2020-03-23 07:39:13 -0500407 default:
408 break;
409 }
410
411 return false;
412}
413
414bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
415 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400416 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100417}
418
SJW2c317da2020-03-23 07:39:13 -0500419bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
420 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100421 auto XValue = CI->getOperand(0);
422 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100423
Kévin Petite8edce32019-04-10 14:23:32 +0100424 IRBuilder<> Builder(CI);
425 auto XmY = Builder.CreateSub(XValue, YValue);
426 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100427
SJW2c317da2020-03-23 07:39:13 -0500428 Value *Cmp = nullptr;
429 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100430 Cmp = Builder.CreateICmpSGT(YValue, XValue);
431 } else {
432 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100433 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100434
Kévin Petite8edce32019-04-10 14:23:32 +0100435 return Builder.CreateSelect(Cmp, YmX, XmY);
436 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100437}
438
SJW2c317da2020-03-23 07:39:13 -0500439bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
440 return replaceCallsWithValue(F, [&F](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100441 auto XValue = CI->getOperand(0);
442 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100443
Kévin Petite8edce32019-04-10 14:23:32 +0100444 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100445
SJW2c317da2020-03-23 07:39:13 -0500446 Type *IntTy = Type::getIntNTy(F.getContext(), Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -0400447 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
448 IntTy = VectorType::get(IntTy, vec_ty->getNumElements());
Kévin Petit8c1be282019-04-02 19:34:25 +0100449 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100450
Kévin Petite8edce32019-04-10 14:23:32 +0100451 // Return X with the sign of Y
452
453 // Sign bit masks
454 auto SignBit = IntTy->getScalarSizeInBits() - 1;
455 auto SignBitMask = 1 << SignBit;
456 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
457 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
458
459 IRBuilder<> Builder(CI);
460
461 // Extract sign of Y
462 auto YInt = Builder.CreateBitCast(YValue, IntTy);
463 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
464
465 // Clear sign bit in X
466 auto XInt = Builder.CreateBitCast(XValue, IntTy);
467 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
468
469 // Insert sign bit of Y into X
470 auto NewXInt = Builder.CreateOr(XInt, YSign);
471
472 // And cast back to floating-point
473 return Builder.CreateBitCast(NewXInt, Ty);
474 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100475}
476
SJW2c317da2020-03-23 07:39:13 -0500477bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
478 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100479 // Recip has one arg.
480 auto Arg = CI->getOperand(0);
481 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
482 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
483 });
David Neto22f144c2017-06-12 14:26:21 -0400484}
485
SJW2c317da2020-03-23 07:39:13 -0500486bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
487 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100488 auto Op0 = CI->getOperand(0);
489 auto Op1 = CI->getOperand(1);
490 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
491 });
David Neto22f144c2017-06-12 14:26:21 -0400492}
493
SJW2c317da2020-03-23 07:39:13 -0500494bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
495 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100496 auto Op0 = CI->getOperand(0);
497 auto Op1 = CI->getOperand(1);
498
SJW2c317da2020-03-23 07:39:13 -0500499 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100500 if (Op0->getType()->isVectorTy()) {
501 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
502 CI->getType(), {Op0, Op1});
503 } else {
504 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
505 }
506
507 return V;
508 });
509}
510
SJW2c317da2020-03-23 07:39:13 -0500511bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
512 const std::string &basename,
513 int vec_size, int byte_len) {
514 // convert to natural
515 auto slen = basename.length() - 2;
516 std::string NewFName = "_Z" + std::to_string(slen) + basename.substr(0, slen);
517 if (vec_size) {
518 NewFName += "Dv" + std::to_string(vec_size) + "_";
519 }
520 switch (byte_len) {
521 case 4:
522 NewFName += "f";
523 break;
524 case 8:
525 NewFName += "d";
526 break;
527 default:
528 llvm_unreachable("Unsupported exp10 byte length");
529 break;
David Neto22f144c2017-06-12 14:26:21 -0400530 }
531
SJW2c317da2020-03-23 07:39:13 -0500532 Module &M = *F.getParent();
533 return replaceCallsWithValue(F, [&](CallInst *CI) {
534 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
535
536 auto Arg = CI->getOperand(0);
537
538 // Constant of the natural log of 10 (ln(10)).
539 const double Ln10 =
540 2.302585092994045684017991454684364207601101488628772976033;
541
542 auto Mul = BinaryOperator::Create(
543 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
544
545 return CallInst::Create(NewF, Mul, "", CI);
546 });
David Neto22f144c2017-06-12 14:26:21 -0400547}
548
SJW2c317da2020-03-23 07:39:13 -0500549bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100550 // OpenCL fmod(x,y) is x - y * trunc(x/y)
551 // The sign for a non-zero result is taken from x.
552 // (Try an example.)
553 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500554 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100555 auto Op0 = CI->getOperand(0);
556 auto Op1 = CI->getOperand(1);
557 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
558 });
559}
560
SJW2c317da2020-03-23 07:39:13 -0500561bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
562 const std::string &basename,
563 int vec_size, int byte_len) {
564 // convert to natural
565 auto slen = basename.length() - 2;
566 std::string NewFName = "_Z" + std::to_string(slen) + basename.substr(0, slen);
567 if (vec_size) {
568 NewFName += "Dv" + std::to_string(vec_size) + "_";
569 }
570 switch (byte_len) {
571 case 4:
572 NewFName += "f";
573 break;
574 case 8:
575 NewFName += "d";
576 break;
577 default:
578 llvm_unreachable("Unsupported log10 byte length");
579 break;
David Neto22f144c2017-06-12 14:26:21 -0400580 }
581
SJW2c317da2020-03-23 07:39:13 -0500582 Module &M = *F.getParent();
583 return replaceCallsWithValue(F, [&](CallInst *CI) {
584 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
585
586 auto Arg = CI->getOperand(0);
587
588 // Constant of the reciprocal of the natural log of 10 (ln(10)).
589 const double Ln10 =
590 0.434294481903251827651128918916605082294397005803666566114;
591
592 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
593
594 return BinaryOperator::Create(Instruction::FMul,
595 ConstantFP::get(Arg->getType(), Ln10), NewCI,
596 "", CI);
597 });
David Neto22f144c2017-06-12 14:26:21 -0400598}
599
SJW2c317da2020-03-23 07:39:13 -0500600bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -0400601
602 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
603
SJW2c317da2020-03-23 07:39:13 -0500604 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100605 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400606
Kévin Petitc4643922019-06-17 19:32:05 +0100607 // We need to map the OpenCL constants to the SPIR-V equivalents.
608 const auto LocalMemFence =
609 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
610 const auto GlobalMemFence =
611 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
612 const auto ConstantSequentiallyConsistent = ConstantInt::get(
613 Arg->getType(), spv::MemorySemanticsSequentiallyConsistentMask);
614 const auto ConstantScopeDevice =
615 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
616 const auto ConstantScopeWorkgroup =
617 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400618
Kévin Petitc4643922019-06-17 19:32:05 +0100619 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
620 const auto LocalMemFenceMask =
621 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
622 const auto WorkgroupShiftAmount =
623 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
624 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
625 Instruction::Shl, LocalMemFenceMask,
626 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400627
Kévin Petitc4643922019-06-17 19:32:05 +0100628 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
629 const auto GlobalMemFenceMask =
630 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
631 const auto UniformShiftAmount =
632 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
633 const auto MemorySemanticsUniform = BinaryOperator::Create(
634 Instruction::Shl, GlobalMemFenceMask,
635 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400636
Kévin Petitc4643922019-06-17 19:32:05 +0100637 // And combine the above together, also adding in
638 // MemorySemanticsSequentiallyConsistentMask.
639 auto MemorySemantics =
640 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
641 ConstantSequentiallyConsistent, "", CI);
642 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
643 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400644
Kévin Petitc4643922019-06-17 19:32:05 +0100645 // For Memory Scope if we used CLK_GLOBAL_MEM_FENCE, we need to use
646 // Device Scope, otherwise Workgroup Scope.
647 const auto Cmp =
648 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, GlobalMemFenceMask,
649 GlobalMemFence, "", CI);
650 const auto MemoryScope = SelectInst::Create(Cmp, ConstantScopeDevice,
651 ConstantScopeWorkgroup, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400652
Kévin Petitc4643922019-06-17 19:32:05 +0100653 // Lastly, the Execution Scope is always Workgroup Scope.
654 const auto ExecutionScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400655
Kévin Petitc4643922019-06-17 19:32:05 +0100656 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
657 {Attribute::NoDuplicate}, CI->getType(),
658 {ExecutionScope, MemoryScope, MemorySemantics});
659 });
David Neto22f144c2017-06-12 14:26:21 -0400660}
661
SJW2c317da2020-03-23 07:39:13 -0500662bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
663 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400664
SJW2c317da2020-03-23 07:39:13 -0500665 return replaceCallsWithValue(F, [&](CallInst *CI) {
666 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
David Neto22f144c2017-06-12 14:26:21 -0400667
SJW2c317da2020-03-23 07:39:13 -0500668 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400669
SJW2c317da2020-03-23 07:39:13 -0500670 // We need to map the OpenCL constants to the SPIR-V equivalents.
671 const auto LocalMemFence =
672 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
673 const auto GlobalMemFence =
674 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
675 const auto ConstantMemorySemantics =
676 ConstantInt::get(Arg->getType(), semantics);
677 const auto ConstantScopeDevice =
678 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -0400679
SJW2c317da2020-03-23 07:39:13 -0500680 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
681 const auto LocalMemFenceMask =
682 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
683 const auto WorkgroupShiftAmount =
684 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
685 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
686 Instruction::Shl, LocalMemFenceMask,
687 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400688
SJW2c317da2020-03-23 07:39:13 -0500689 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
690 const auto GlobalMemFenceMask =
691 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
692 const auto UniformShiftAmount =
693 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
694 const auto MemorySemanticsUniform = BinaryOperator::Create(
695 Instruction::Shl, GlobalMemFenceMask,
696 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400697
SJW2c317da2020-03-23 07:39:13 -0500698 // And combine the above together, also adding in
699 // MemorySemanticsSequentiallyConsistentMask.
700 auto MemorySemantics =
701 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
702 ConstantMemorySemantics, "", CI);
703 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
704 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400705
SJW2c317da2020-03-23 07:39:13 -0500706 // Memory Scope is always device.
707 const auto MemoryScope = ConstantScopeDevice;
David Neto22f144c2017-06-12 14:26:21 -0400708
SJW2c317da2020-03-23 07:39:13 -0500709 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier, {}, CI->getType(),
710 {MemoryScope, MemorySemantics});
711 });
David Neto22f144c2017-06-12 14:26:21 -0400712}
713
Kévin Petit1cb45112020-04-27 18:55:48 +0100714bool ReplaceOpenCLBuiltinPass::replacePrefetch(Function &F) {
715 bool Changed = false;
716
717 SmallVector<Instruction *, 4> ToRemoves;
718
719 // Find all calls to the function
720 for (auto &U : F.uses()) {
721 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
722 ToRemoves.push_back(CI);
723 }
724 }
725
726 Changed = !ToRemoves.empty();
727
728 // Delete them
729 for (auto V : ToRemoves) {
730 V->eraseFromParent();
731 }
732
733 return Changed;
734}
735
SJW2c317da2020-03-23 07:39:13 -0500736bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
737 CmpInst::Predicate P,
738 int32_t C) {
739 return replaceCallsWithValue(F, [&](CallInst *CI) {
740 // The predicate to use in the CmpInst.
741 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -0400742
SJW2c317da2020-03-23 07:39:13 -0500743 // The value to return for true.
744 auto TrueValue = ConstantInt::getSigned(CI->getType(), C);
David Neto22f144c2017-06-12 14:26:21 -0400745
SJW2c317da2020-03-23 07:39:13 -0500746 // The value to return for false.
747 auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400748
SJW2c317da2020-03-23 07:39:13 -0500749 auto Arg1 = CI->getOperand(0);
750 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -0400751
SJW2c317da2020-03-23 07:39:13 -0500752 const auto Cmp =
753 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400754
SJW2c317da2020-03-23 07:39:13 -0500755 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
756 });
David Neto22f144c2017-06-12 14:26:21 -0400757}
758
SJW2c317da2020-03-23 07:39:13 -0500759bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
760 spv::Op SPIRVOp,
761 int32_t C) {
762 Module &M = *F.getParent();
763 return replaceCallsWithValue(F, [&](CallInst *CI) {
764 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -0400765
SJW2c317da2020-03-23 07:39:13 -0500766 // The value to return for true.
767 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -0400768
SJW2c317da2020-03-23 07:39:13 -0500769 // The value to return for false.
770 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -0400771
SJW2c317da2020-03-23 07:39:13 -0500772 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -0400773 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
SJW2c317da2020-03-23 07:39:13 -0500774 CorrespondingBoolTy = VectorType::get(Type::getInt1Ty(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -0400775 CIVecTy->getNumElements());
David Neto22f144c2017-06-12 14:26:21 -0400776 }
David Neto22f144c2017-06-12 14:26:21 -0400777
SJW2c317da2020-03-23 07:39:13 -0500778 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
779 CorrespondingBoolTy, {CI->getOperand(0)});
780
781 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
782 });
David Neto22f144c2017-06-12 14:26:21 -0400783}
784
SJW2c317da2020-03-23 07:39:13 -0500785bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
786 Module &M = *F.getParent();
787 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100788 auto &C = M.getContext();
789 auto Val = CI->getOperand(0);
790 auto ValTy = Val->getType();
791 auto RetTy = CI->getType();
792
793 // Get a suitable integer type to represent the number
794 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
795
796 // Create Mask
797 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -0500798 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100799 switch (ScalarSize) {
800 case 16:
801 InfMask = ConstantInt::get(IntTy, 0x7C00U);
802 break;
803 case 32:
804 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
805 break;
806 case 64:
807 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
808 break;
809 default:
810 llvm_unreachable("Unsupported floating-point type");
811 }
812
813 IRBuilder<> Builder(CI);
814
815 // Bitcast to int
816 auto ValInt = Builder.CreateBitCast(Val, IntTy);
817
818 // Mask and compare
819 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
820 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
821
822 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -0500823 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100824 if (ValTy->isVectorTy()) {
825 RetTrue = ConstantInt::getSigned(RetTy, -1);
826 } else {
827 RetTrue = ConstantInt::get(RetTy, 1);
828 }
829 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
830 });
831}
832
SJW2c317da2020-03-23 07:39:13 -0500833bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
834 Module &M = *F.getParent();
835 return replaceCallsWithValue(F, [&](CallInst *CI) {
836 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400837
SJW2c317da2020-03-23 07:39:13 -0500838 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +0000839
SJW2c317da2020-03-23 07:39:13 -0500840 // If the argument is a 32-bit int, just use a shift
841 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
842 V = BinaryOperator::Create(Instruction::LShr, Arg,
843 ConstantInt::get(Arg->getType(), 31), "", CI);
844 } else {
845 // The value for zero to compare against.
846 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -0400847
SJW2c317da2020-03-23 07:39:13 -0500848 // The value to return for true.
849 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -0400850
SJW2c317da2020-03-23 07:39:13 -0500851 // The value to return for false.
852 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400853
SJW2c317da2020-03-23 07:39:13 -0500854 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
855 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400856
SJW2c317da2020-03-23 07:39:13 -0500857 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -0400858
SJW2c317da2020-03-23 07:39:13 -0500859 // If we have a function to call, call it!
860 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -0400861
SJW2c317da2020-03-23 07:39:13 -0500862 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -0400863
SJW2c317da2020-03-23 07:39:13 -0500864 const auto NewCI = clspv::InsertSPIRVOp(
865 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
866 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -0400867
SJW2c317da2020-03-23 07:39:13 -0500868 } else {
869 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -0400870 }
871
SJW2c317da2020-03-23 07:39:13 -0500872 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400873 }
SJW2c317da2020-03-23 07:39:13 -0500874 return V;
875 });
David Neto22f144c2017-06-12 14:26:21 -0400876}
877
SJW2c317da2020-03-23 07:39:13 -0500878bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
879 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
880 // Get arguments
881 auto HiValue = CI->getOperand(0);
882 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +0000883
SJW2c317da2020-03-23 07:39:13 -0500884 // Don't touch overloads that aren't in OpenCL C
885 auto HiType = HiValue->getType();
886 auto LoType = LoValue->getType();
887
888 if (HiType != LoType) {
889 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000890 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000891
SJW2c317da2020-03-23 07:39:13 -0500892 if (!HiType->isIntOrIntVectorTy()) {
893 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000894 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000895
SJW2c317da2020-03-23 07:39:13 -0500896 if (HiType->getScalarSizeInBits() * 2 !=
897 CI->getType()->getScalarSizeInBits()) {
898 return nullptr;
899 }
900
901 if ((HiType->getScalarSizeInBits() != 8) &&
902 (HiType->getScalarSizeInBits() != 16) &&
903 (HiType->getScalarSizeInBits() != 32)) {
904 return nullptr;
905 }
906
James Pricecf53df42020-04-20 14:41:24 -0400907 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
908 unsigned NumElements = HiVecType->getNumElements();
909 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
910 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500911 return nullptr;
912 }
913 }
914
915 // Convert both operands to the result type
916 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
917 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
918
919 // Shift high operand
920 auto ShiftAmount =
921 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
922 auto HiShifted =
923 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
924
925 // OR both results
926 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
927 });
Kévin Petitbf0036c2019-03-06 13:57:10 +0000928}
929
SJW2c317da2020-03-23 07:39:13 -0500930bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
931 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
932 // Get arguments
933 auto SrcValue = CI->getOperand(0);
934 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +0000935
SJW2c317da2020-03-23 07:39:13 -0500936 // Don't touch overloads that aren't in OpenCL C
937 auto SrcType = SrcValue->getType();
938 auto RotType = RotAmount->getType();
939
940 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
941 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000942 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000943
SJW2c317da2020-03-23 07:39:13 -0500944 if (!SrcType->isIntOrIntVectorTy()) {
945 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000946 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000947
SJW2c317da2020-03-23 07:39:13 -0500948 if ((SrcType->getScalarSizeInBits() != 8) &&
949 (SrcType->getScalarSizeInBits() != 16) &&
950 (SrcType->getScalarSizeInBits() != 32) &&
951 (SrcType->getScalarSizeInBits() != 64)) {
952 return nullptr;
953 }
954
James Pricecf53df42020-04-20 14:41:24 -0400955 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
956 unsigned NumElements = SrcVecType->getNumElements();
957 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
958 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500959 return nullptr;
960 }
961 }
962
963 // The approach used is to shift the top bits down, the bottom bits up
964 // and OR the two shifted values.
965
966 // The rotation amount is to be treated modulo the element size.
967 // Since SPIR-V shift ops don't support this, let's apply the
968 // modulo ahead of shifting. The element size is always a power of
969 // two so we can just AND with a mask.
970 auto ModMask =
971 ConstantInt::get(SrcType, SrcType->getScalarSizeInBits() - 1);
972 RotAmount =
973 BinaryOperator::Create(Instruction::And, RotAmount, ModMask, "", CI);
974
975 // Let's calc the amount by which to shift top bits down
976 auto ScalarSize = ConstantInt::get(SrcType, SrcType->getScalarSizeInBits());
977 auto DownAmount =
978 BinaryOperator::Create(Instruction::Sub, ScalarSize, RotAmount, "", CI);
979
980 // Now shift the bottom bits up and the top bits down
981 auto LoRotated =
982 BinaryOperator::Create(Instruction::Shl, SrcValue, RotAmount, "", CI);
983 auto HiRotated =
984 BinaryOperator::Create(Instruction::LShr, SrcValue, DownAmount, "", CI);
985
986 // Finally OR the two shifted values
987 return BinaryOperator::Create(Instruction::Or, LoRotated, HiRotated, "",
988 CI);
989 });
Kévin Petitd44eef52019-03-08 13:22:14 +0000990}
991
SJW2c317da2020-03-23 07:39:13 -0500992bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
993 bool DstIsSigned) {
994 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
995 Value *V = nullptr;
996 // Get arguments
997 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000998
SJW2c317da2020-03-23 07:39:13 -0500999 // Don't touch overloads that aren't in OpenCL C
1000 auto SrcType = SrcValue->getType();
1001 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001002
SJW2c317da2020-03-23 07:39:13 -05001003 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1004 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1005 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001006 }
1007
James Pricecf53df42020-04-20 14:41:24 -04001008 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
1009 unsigned SrcNumElements = SrcVecType->getNumElements();
1010 unsigned DstNumElements = cast<VectorType>(DstType)->getNumElements();
1011 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001012 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001013 }
1014
James Pricecf53df42020-04-20 14:41:24 -04001015 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1016 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1017 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001018 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001019 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001020 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001021
SJW2c317da2020-03-23 07:39:13 -05001022 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1023 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1024
1025 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1026 bool DstIsInt = DstType->isIntOrIntVectorTy();
1027
1028 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1029 // Unnecessary cast operation.
1030 V = SrcValue;
1031 } else if (SrcIsFloat && DstIsFloat) {
1032 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1033 } else if (SrcIsFloat && DstIsInt) {
1034 if (DstIsSigned) {
1035 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1036 } else {
1037 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1038 }
1039 } else if (SrcIsInt && DstIsFloat) {
1040 if (SrcIsSigned) {
1041 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1042 } else {
1043 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1044 }
1045 } else if (SrcIsInt && DstIsInt) {
1046 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1047 } else {
1048 // Not something we're supposed to handle, just move on
1049 }
1050
1051 return V;
1052 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001053}
1054
SJW2c317da2020-03-23 07:39:13 -05001055bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1056 bool is_mad) {
1057 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1058 Value *V = nullptr;
1059 // Get arguments
1060 auto AValue = CI->getOperand(0);
1061 auto BValue = CI->getOperand(1);
1062 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001063
SJW2c317da2020-03-23 07:39:13 -05001064 // Don't touch overloads that aren't in OpenCL C
1065 auto AType = AValue->getType();
1066 auto BType = BValue->getType();
1067 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001068
SJW2c317da2020-03-23 07:39:13 -05001069 if ((AType != BType) || (CI->getType() != AType) ||
1070 (is_mad && (AType != CType))) {
1071 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001072 }
1073
SJW2c317da2020-03-23 07:39:13 -05001074 if (!AType->isIntOrIntVectorTy()) {
1075 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001076 }
Kévin Petit8a560882019-03-21 15:24:34 +00001077
SJW2c317da2020-03-23 07:39:13 -05001078 if ((AType->getScalarSizeInBits() != 8) &&
1079 (AType->getScalarSizeInBits() != 16) &&
1080 (AType->getScalarSizeInBits() != 32) &&
1081 (AType->getScalarSizeInBits() != 64)) {
1082 return V;
1083 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001084
James Pricecf53df42020-04-20 14:41:24 -04001085 if (auto AVecType = dyn_cast<VectorType>(AType)) {
1086 unsigned NumElements = AVecType->getNumElements();
1087 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1088 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001089 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001090 }
1091 }
1092
SJW2c317da2020-03-23 07:39:13 -05001093 // Our SPIR-V op returns a struct, create a type for it
1094 SmallVector<Type *, 2> TwoValueType = {AType, AType};
1095 auto ExMulRetType = StructType::create(TwoValueType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001096
SJW2c317da2020-03-23 07:39:13 -05001097 // Select the appropriate signed/unsigned SPIR-V op
1098 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1099
1100 // Call the SPIR-V op
1101 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1102 ExMulRetType, {AValue, BValue});
1103
1104 // Get the high part of the result
1105 unsigned Idxs[] = {1};
1106 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1107
1108 // If we're handling a mad_hi, add the third argument to the result
1109 if (is_mad) {
1110 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001111 }
1112
SJW2c317da2020-03-23 07:39:13 -05001113 return V;
1114 });
Kévin Petit8a560882019-03-21 15:24:34 +00001115}
1116
SJW2c317da2020-03-23 07:39:13 -05001117bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1118 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1119 // Get arguments
1120 auto FalseValue = CI->getOperand(0);
1121 auto TrueValue = CI->getOperand(1);
1122 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001123
SJW2c317da2020-03-23 07:39:13 -05001124 // Don't touch overloads that aren't in OpenCL C
1125 auto FalseType = FalseValue->getType();
1126 auto TrueType = TrueValue->getType();
1127 auto PredicateType = PredicateValue->getType();
1128
1129 if (FalseType != TrueType) {
1130 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001131 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001132
SJW2c317da2020-03-23 07:39:13 -05001133 if (!PredicateType->isIntOrIntVectorTy()) {
1134 return nullptr;
1135 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001136
SJW2c317da2020-03-23 07:39:13 -05001137 if (!FalseType->isIntOrIntVectorTy() &&
1138 !FalseType->getScalarType()->isFloatingPointTy()) {
1139 return nullptr;
1140 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001141
SJW2c317da2020-03-23 07:39:13 -05001142 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1143 return nullptr;
1144 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001145
SJW2c317da2020-03-23 07:39:13 -05001146 if (FalseType->getScalarSizeInBits() !=
1147 PredicateType->getScalarSizeInBits()) {
1148 return nullptr;
1149 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001150
James Pricecf53df42020-04-20 14:41:24 -04001151 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
1152 unsigned NumElements = FalseVecType->getNumElements();
1153 if (NumElements != cast<VectorType>(PredicateType)->getNumElements()) {
SJW2c317da2020-03-23 07:39:13 -05001154 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001155 }
1156
James Pricecf53df42020-04-20 14:41:24 -04001157 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1158 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001159 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001160 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001161 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001162
SJW2c317da2020-03-23 07:39:13 -05001163 // Create constant
1164 const auto ZeroValue = Constant::getNullValue(PredicateType);
1165
1166 // Scalar and vector are to be treated differently
1167 CmpInst::Predicate Pred;
1168 if (PredicateType->isVectorTy()) {
1169 Pred = CmpInst::ICMP_SLT;
1170 } else {
1171 Pred = CmpInst::ICMP_NE;
1172 }
1173
1174 // Create comparison instruction
1175 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1176 ZeroValue, "", CI);
1177
1178 // Create select
1179 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1180 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001181}
1182
SJW2c317da2020-03-23 07:39:13 -05001183bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1184 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1185 Value *V = nullptr;
1186 if (CI->getNumOperands() != 4) {
1187 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001188 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001189
SJW2c317da2020-03-23 07:39:13 -05001190 // Get arguments
1191 auto FalseValue = CI->getOperand(0);
1192 auto TrueValue = CI->getOperand(1);
1193 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001194
SJW2c317da2020-03-23 07:39:13 -05001195 // Don't touch overloads that aren't in OpenCL C
1196 auto FalseType = FalseValue->getType();
1197 auto TrueType = TrueValue->getType();
1198 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001199
SJW2c317da2020-03-23 07:39:13 -05001200 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1201 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001202 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001203
James Pricecf53df42020-04-20 14:41:24 -04001204 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001205 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1206 !TrueType->getScalarType()->isIntegerTy()) {
1207 return V;
1208 }
James Pricecf53df42020-04-20 14:41:24 -04001209 unsigned NumElements = TrueVecType->getNumElements();
1210 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1211 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001212 return V;
1213 }
1214 }
1215
1216 // Remember the type of the operands
1217 auto OpType = TrueType;
1218
1219 // The actual bit selection will always be done on an integer type,
1220 // declare it here
1221 Type *BitType;
1222
1223 // If the operands are float, then bitcast them to int
1224 if (OpType->getScalarType()->isFloatingPointTy()) {
1225
1226 // First create the new type
1227 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1228
1229 // Then bitcast all operands
1230 PredicateValue =
1231 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1232 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1233 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1234
1235 } else {
1236 // The operands have an integer type, use it directly
1237 BitType = OpType;
1238 }
1239
1240 // All the operands are now always integers
1241 // implement as (c & b) | (~c & a)
1242
1243 // Create our negated predicate value
1244 auto AllOnes = Constant::getAllOnesValue(BitType);
1245 auto NotPredicateValue = BinaryOperator::Create(
1246 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1247
1248 // Then put everything together
1249 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1250 FalseValue, "", CI);
1251 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1252 TrueValue, "", CI);
1253
1254 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1255
1256 // If we were dealing with a floating point type, we must bitcast
1257 // the result back to that
1258 if (OpType->getScalarType()->isFloatingPointTy()) {
1259 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1260 }
1261
1262 return V;
1263 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001264}
1265
SJW2c317da2020-03-23 07:39:13 -05001266bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth,
1267 int vec_size) {
1268 // convert to vector versions
1269 Module &M = *F.getParent();
1270 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1271 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1272 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001273
SJW2c317da2020-03-23 07:39:13 -05001274 std::string NewFName = "_Z";
1275 if (is_smooth) {
1276 NewFName += std::to_string(10) + "smoothstepDv" +
1277 std::to_string(vec_size) + "_fS_S_";
1278 } else {
1279 NewFName +=
1280 std::to_string(4) + "stepDv" + std::to_string(vec_size) + "_fS_";
Kévin Petit6b0a9532018-10-30 20:00:39 +00001281 }
Kévin Petit6b0a9532018-10-30 20:00:39 +00001282
SJW2c317da2020-03-23 07:39:13 -05001283 // First figure out which function we're dealing with
1284 if (is_smooth) {
1285 ArgsToSplat.push_back(CI->getOperand(1));
1286 VectorArg = CI->getOperand(2);
1287 } else {
1288 VectorArg = CI->getOperand(1);
1289 }
1290
1291 // Splat arguments that need to be
1292 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001293 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001294
1295 for (auto arg : ArgsToSplat) {
1296 Value *NewVectorArg = UndefValue::get(VecType);
James Pricecf53df42020-04-20 14:41:24 -04001297 for (auto i = 0; i < VecType->getNumElements(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001298 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1299 NewVectorArg =
1300 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1301 }
1302 SplatArgs.push_back(NewVectorArg);
1303 }
1304
1305 // Replace the call with the vector/vector flavour
1306 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1307 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1308
1309 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1310
1311 SmallVector<Value *, 3> NewArgs;
1312 for (auto arg : SplatArgs) {
1313 NewArgs.push_back(arg);
1314 }
1315 NewArgs.push_back(VectorArg);
1316
1317 return CallInst::Create(NewF, NewArgs, "", CI);
1318 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001319}
1320
SJW2c317da2020-03-23 07:39:13 -05001321bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001322 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1323 auto Arg = CI->getOperand(0);
1324 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001325
SJW2c317da2020-03-23 07:39:13 -05001326 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001327
SJW2c317da2020-03-23 07:39:13 -05001328 return BinaryOperator::Create(Op, Bitcast,
1329 ConstantInt::get(CI->getType(), 31), "", CI);
1330 });
David Neto22f144c2017-06-12 14:26:21 -04001331}
1332
SJW2c317da2020-03-23 07:39:13 -05001333bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1334 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001335 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1336 // The multiply instruction to use.
1337 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001338
SJW2c317da2020-03-23 07:39:13 -05001339 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001340
SJW2c317da2020-03-23 07:39:13 -05001341 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1342 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001343
SJW2c317da2020-03-23 07:39:13 -05001344 if (is_mad) {
1345 // The add instruction to use.
1346 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001347
SJW2c317da2020-03-23 07:39:13 -05001348 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001349 }
David Neto22f144c2017-06-12 14:26:21 -04001350
SJW2c317da2020-03-23 07:39:13 -05001351 return V;
1352 });
David Neto22f144c2017-06-12 14:26:21 -04001353}
1354
SJW2c317da2020-03-23 07:39:13 -05001355bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001356 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1357 Value *V = nullptr;
1358 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001359
SJW2c317da2020-03-23 07:39:13 -05001360 auto data_type = data->getType();
1361 if (!data_type->isVectorTy())
1362 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001363
James Pricecf53df42020-04-20 14:41:24 -04001364 auto vec_data_type = cast<VectorType>(data_type);
1365
1366 auto elems = vec_data_type->getNumElements();
SJW2c317da2020-03-23 07:39:13 -05001367 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1368 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001369
SJW2c317da2020-03-23 07:39:13 -05001370 auto offset = CI->getOperand(1);
1371 auto ptr = CI->getOperand(2);
1372 auto ptr_type = ptr->getType();
1373 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001374 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001375 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001376
SJW2c317da2020-03-23 07:39:13 -05001377 // Avoid pointer casts. Instead generate the correct number of stores
1378 // and rely on drivers to coalesce appropriately.
1379 IRBuilder<> builder(CI);
1380 auto elems_const = builder.getInt32(elems);
1381 auto adjust = builder.CreateMul(offset, elems_const);
1382 for (auto i = 0; i < elems; ++i) {
1383 auto idx = builder.getInt32(i);
1384 auto add = builder.CreateAdd(adjust, idx);
1385 auto gep = builder.CreateGEP(ptr, add);
1386 auto extract = builder.CreateExtractElement(data, i);
1387 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001388 }
SJW2c317da2020-03-23 07:39:13 -05001389 return V;
1390 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001391}
1392
SJW2c317da2020-03-23 07:39:13 -05001393bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001394 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1395 Value *V = nullptr;
1396 auto ret_type = F.getReturnType();
1397 if (!ret_type->isVectorTy())
1398 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001399
James Pricecf53df42020-04-20 14:41:24 -04001400 auto vec_ret_type = cast<VectorType>(ret_type);
1401
1402 auto elems = vec_ret_type->getNumElements();
SJW2c317da2020-03-23 07:39:13 -05001403 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1404 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001405
SJW2c317da2020-03-23 07:39:13 -05001406 auto offset = CI->getOperand(0);
1407 auto ptr = CI->getOperand(1);
1408 auto ptr_type = ptr->getType();
1409 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001410 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001411 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001412
SJW2c317da2020-03-23 07:39:13 -05001413 // Avoid pointer casts. Instead generate the correct number of loads
1414 // and rely on drivers to coalesce appropriately.
1415 IRBuilder<> builder(CI);
1416 auto elems_const = builder.getInt32(elems);
1417 V = UndefValue::get(ret_type);
1418 auto adjust = builder.CreateMul(offset, elems_const);
1419 for (auto i = 0; i < elems; ++i) {
1420 auto idx = builder.getInt32(i);
1421 auto add = builder.CreateAdd(adjust, idx);
1422 auto gep = builder.CreateGEP(ptr, add);
1423 auto load = builder.CreateLoad(gep);
1424 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001425 }
SJW2c317da2020-03-23 07:39:13 -05001426 return V;
1427 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001428}
1429
SJW2c317da2020-03-23 07:39:13 -05001430bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1431 const std::string &name,
1432 int vec_size) {
1433 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1434 if (!vec_size) {
1435 // deduce vec_size from last character of name (e.g. vload_half4)
1436 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001437 }
SJW2c317da2020-03-23 07:39:13 -05001438 switch (vec_size) {
1439 case 2:
1440 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1441 case 4:
1442 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1443 case 0:
1444 if (!is_clspv_version) {
1445 return replaceVloadHalf(F);
1446 }
1447 default:
1448 llvm_unreachable("Unsupported vload_half vector size");
1449 break;
1450 }
1451 return false;
David Neto22f144c2017-06-12 14:26:21 -04001452}
1453
SJW2c317da2020-03-23 07:39:13 -05001454bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1455 Module &M = *F.getParent();
1456 return replaceCallsWithValue(F, [&](CallInst *CI) {
1457 // The index argument from vload_half.
1458 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001459
SJW2c317da2020-03-23 07:39:13 -05001460 // The pointer argument from vload_half.
1461 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001462
SJW2c317da2020-03-23 07:39:13 -05001463 auto IntTy = Type::getInt32Ty(M.getContext());
1464 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1465 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1466
1467 // Our intrinsic to unpack a float2 from an int.
1468 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
1469
1470 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1471
1472 Value *V = nullptr;
1473
1474 if (clspv::Option::F16BitStorage()) {
1475 auto ShortTy = Type::getInt16Ty(M.getContext());
1476 auto ShortPointerTy =
1477 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1478
1479 // Cast the half* pointer to short*.
1480 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1481
1482 // Index into the correct address of the casted pointer.
1483 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1484
1485 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001486 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001487
1488 // ZExt the short -> int.
1489 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1490
1491 // Get our float2.
1492 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1493
1494 // Extract out the bottom element which is our float result.
1495 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1496 } else {
1497 // Assume the pointer argument points to storage aligned to 32bits
1498 // or more.
1499 // TODO(dneto): Do more analysis to make sure this is true?
1500 //
1501 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1502 // with:
1503 //
1504 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1505 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1506 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1507 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1508 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1509 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1510 // x float> %converted, %index_is_odd32
1511
1512 auto IntPointerTy =
1513 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1514
1515 // Cast the base pointer to int*.
1516 // In a valid call (according to assumptions), this should get
1517 // optimized away in the simplify GEP pass.
1518 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1519
1520 auto One = ConstantInt::get(IntTy, 1);
1521 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1522 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1523
1524 // Index into the correct address of the casted pointer.
1525 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1526
1527 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001528 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001529
1530 // Get our float2.
1531 auto Call = CallInst::Create(NewF, Load, "", CI);
1532
1533 // Extract out the float result, where the element number is
1534 // determined by whether the original index was even or odd.
1535 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1536 }
1537 return V;
1538 });
1539}
1540
1541bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1542 Module &M = *F.getParent();
1543 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001544 // The index argument from vload_half.
1545 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001546
Kévin Petite8edce32019-04-10 14:23:32 +01001547 // The pointer argument from vload_half.
1548 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001549
Kévin Petite8edce32019-04-10 14:23:32 +01001550 auto IntTy = Type::getInt32Ty(M.getContext());
1551 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001552 auto NewPointerTy =
1553 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001554 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001555
Kévin Petite8edce32019-04-10 14:23:32 +01001556 // Cast the half* pointer to int*.
1557 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001558
Kévin Petite8edce32019-04-10 14:23:32 +01001559 // Index into the correct address of the casted pointer.
1560 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001561
Kévin Petite8edce32019-04-10 14:23:32 +01001562 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001563 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001564
Kévin Petite8edce32019-04-10 14:23:32 +01001565 // Our intrinsic to unpack a float2 from an int.
1566 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001567
Kévin Petite8edce32019-04-10 14:23:32 +01001568 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001569
Kévin Petite8edce32019-04-10 14:23:32 +01001570 // Get our float2.
1571 return CallInst::Create(NewF, Load, "", CI);
1572 });
David Neto22f144c2017-06-12 14:26:21 -04001573}
1574
SJW2c317da2020-03-23 07:39:13 -05001575bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1576 Module &M = *F.getParent();
1577 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001578 // The index argument from vload_half.
1579 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001580
Kévin Petite8edce32019-04-10 14:23:32 +01001581 // The pointer argument from vload_half.
1582 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001583
Kévin Petite8edce32019-04-10 14:23:32 +01001584 auto IntTy = Type::getInt32Ty(M.getContext());
1585 auto Int2Ty = VectorType::get(IntTy, 2);
1586 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001587 auto NewPointerTy =
1588 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001589 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001590
Kévin Petite8edce32019-04-10 14:23:32 +01001591 // Cast the half* pointer to int2*.
1592 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001593
Kévin Petite8edce32019-04-10 14:23:32 +01001594 // Index into the correct address of the casted pointer.
1595 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001596
Kévin Petite8edce32019-04-10 14:23:32 +01001597 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001598 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001599
Kévin Petite8edce32019-04-10 14:23:32 +01001600 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001601 auto X =
1602 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1603 auto Y =
1604 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001605
Kévin Petite8edce32019-04-10 14:23:32 +01001606 // Our intrinsic to unpack a float2 from an int.
1607 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001608
Kévin Petite8edce32019-04-10 14:23:32 +01001609 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001610
Kévin Petite8edce32019-04-10 14:23:32 +01001611 // Get the lower (x & y) components of our final float4.
1612 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001613
Kévin Petite8edce32019-04-10 14:23:32 +01001614 // Get the higher (z & w) components of our final float4.
1615 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001616
Kévin Petite8edce32019-04-10 14:23:32 +01001617 Constant *ShuffleMask[4] = {
1618 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1619 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001620
Kévin Petite8edce32019-04-10 14:23:32 +01001621 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001622 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1623 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001624 });
David Neto22f144c2017-06-12 14:26:21 -04001625}
1626
SJW2c317da2020-03-23 07:39:13 -05001627bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001628
1629 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1630 //
1631 // %u = load i32 %ptr
1632 // %fxy = call <2 x float> Unpack2xHalf(u)
1633 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001634 Module &M = *F.getParent();
1635 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001636 auto Index = CI->getOperand(0);
1637 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001638
Kévin Petite8edce32019-04-10 14:23:32 +01001639 auto IntTy = Type::getInt32Ty(M.getContext());
1640 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1641 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001642
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001643 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001644 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001645
Kévin Petite8edce32019-04-10 14:23:32 +01001646 // Our intrinsic to unpack a float2 from an int.
1647 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07001648
Kévin Petite8edce32019-04-10 14:23:32 +01001649 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001650
Kévin Petite8edce32019-04-10 14:23:32 +01001651 // Get our final float2.
1652 return CallInst::Create(NewF, Load, "", CI);
1653 });
David Neto6ad93232018-06-07 15:42:58 -07001654}
1655
SJW2c317da2020-03-23 07:39:13 -05001656bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001657
1658 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1659 //
1660 // %u2 = load <2 x i32> %ptr
1661 // %u2xy = extractelement %u2, 0
1662 // %u2zw = extractelement %u2, 1
1663 // %fxy = call <2 x float> Unpack2xHalf(uint)
1664 // %fzw = call <2 x float> Unpack2xHalf(uint)
1665 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001666 Module &M = *F.getParent();
1667 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001668 auto Index = CI->getOperand(0);
1669 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001670
Kévin Petite8edce32019-04-10 14:23:32 +01001671 auto IntTy = Type::getInt32Ty(M.getContext());
1672 auto Int2Ty = VectorType::get(IntTy, 2);
1673 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1674 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001675
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001676 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001677 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001678
Kévin Petite8edce32019-04-10 14:23:32 +01001679 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001680 auto X =
1681 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1682 auto Y =
1683 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001684
Kévin Petite8edce32019-04-10 14:23:32 +01001685 // Our intrinsic to unpack a float2 from an int.
1686 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07001687
Kévin Petite8edce32019-04-10 14:23:32 +01001688 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001689
Kévin Petite8edce32019-04-10 14:23:32 +01001690 // Get the lower (x & y) components of our final float4.
1691 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001692
Kévin Petite8edce32019-04-10 14:23:32 +01001693 // Get the higher (z & w) components of our final float4.
1694 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001695
Kévin Petite8edce32019-04-10 14:23:32 +01001696 Constant *ShuffleMask[4] = {
1697 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1698 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001699
Kévin Petite8edce32019-04-10 14:23:32 +01001700 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001701 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1702 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001703 });
David Neto6ad93232018-06-07 15:42:58 -07001704}
1705
SJW2c317da2020-03-23 07:39:13 -05001706bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1707 switch (vec_size) {
1708 case 0:
1709 return replaceVstoreHalf(F);
1710 case 2:
1711 return replaceVstoreHalf2(F);
1712 case 4:
1713 return replaceVstoreHalf4(F);
1714 default:
1715 llvm_unreachable("Unsupported vstore_half vector size");
1716 break;
1717 }
1718 return false;
1719}
David Neto22f144c2017-06-12 14:26:21 -04001720
SJW2c317da2020-03-23 07:39:13 -05001721bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1722 Module &M = *F.getParent();
1723 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001724 // The value to store.
1725 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001726
Kévin Petite8edce32019-04-10 14:23:32 +01001727 // The index argument from vstore_half.
1728 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001729
Kévin Petite8edce32019-04-10 14:23:32 +01001730 // The pointer argument from vstore_half.
1731 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001732
Kévin Petite8edce32019-04-10 14:23:32 +01001733 auto IntTy = Type::getInt32Ty(M.getContext());
1734 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1735 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1736 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001737
Kévin Petite8edce32019-04-10 14:23:32 +01001738 // Our intrinsic to pack a float2 to an int.
1739 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001740
Kévin Petite8edce32019-04-10 14:23:32 +01001741 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001742
Kévin Petite8edce32019-04-10 14:23:32 +01001743 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001744 auto TempVec = InsertElementInst::Create(
1745 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001746
Kévin Petite8edce32019-04-10 14:23:32 +01001747 // Pack the float2 -> half2 (in an int).
1748 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001749
SJW2c317da2020-03-23 07:39:13 -05001750 Value *V = nullptr;
Kévin Petite8edce32019-04-10 14:23:32 +01001751 if (clspv::Option::F16BitStorage()) {
1752 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001753 auto ShortPointerTy =
1754 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001755
Kévin Petite8edce32019-04-10 14:23:32 +01001756 // Truncate our i32 to an i16.
1757 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001758
Kévin Petite8edce32019-04-10 14:23:32 +01001759 // Cast the half* pointer to short*.
1760 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001761
Kévin Petite8edce32019-04-10 14:23:32 +01001762 // Index into the correct address of the casted pointer.
1763 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001764
Kévin Petite8edce32019-04-10 14:23:32 +01001765 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05001766 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001767 } else {
1768 // We can only write to 32-bit aligned words.
1769 //
1770 // Assuming base is aligned to 32-bits, replace the equivalent of
1771 // vstore_half(value, index, base)
1772 // with:
1773 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
1774 // uint32_t write_to_upper_half = index & 1u;
1775 // uint32_t shift = write_to_upper_half << 4;
1776 //
1777 // // Pack the float value as a half number in bottom 16 bits
1778 // // of an i32.
1779 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
1780 //
1781 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
1782 // ^ ((packed & 0xffff) << shift)
1783 // // We only need relaxed consistency, but OpenCL 1.2 only has
1784 // // sequentially consistent atomics.
1785 // // TODO(dneto): Use relaxed consistency.
1786 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001787 auto IntPointerTy =
1788 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001789
Kévin Petite8edce32019-04-10 14:23:32 +01001790 auto Four = ConstantInt::get(IntTy, 4);
1791 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04001792
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001793 auto IndexIsOdd =
1794 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001795 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001796 auto IndexIntoI32 =
1797 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
1798 auto BaseI32Ptr =
1799 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
1800 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
1801 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001802 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001803 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001804 auto MaskBitsToWrite =
1805 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
1806 auto MaskedCurrent = BinaryOperator::CreateAnd(
1807 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04001808
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001809 auto XLowerBits =
1810 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
1811 auto NewBitsToWrite =
1812 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
1813 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
1814 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04001815
Kévin Petite8edce32019-04-10 14:23:32 +01001816 // Generate the call to atomi_xor.
1817 SmallVector<Type *, 5> ParamTypes;
1818 // The pointer type.
1819 ParamTypes.push_back(IntPointerTy);
1820 // The Types for memory scope, semantics, and value.
1821 ParamTypes.push_back(IntTy);
1822 ParamTypes.push_back(IntTy);
1823 ParamTypes.push_back(IntTy);
1824 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
1825 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04001826
Kévin Petite8edce32019-04-10 14:23:32 +01001827 const auto ConstantScopeDevice =
1828 ConstantInt::get(IntTy, spv::ScopeDevice);
1829 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
1830 // (SPIR-V Workgroup).
1831 const auto AddrSpaceSemanticsBits =
1832 IntPointerTy->getPointerAddressSpace() == 1
1833 ? spv::MemorySemanticsUniformMemoryMask
1834 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04001835
Kévin Petite8edce32019-04-10 14:23:32 +01001836 // We're using relaxed consistency here.
1837 const auto ConstantMemorySemantics =
1838 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
1839 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04001840
Kévin Petite8edce32019-04-10 14:23:32 +01001841 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
1842 ConstantMemorySemantics, ValueToXor};
1843 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05001844
1845 // Return a Nop so the old Call is removed
1846 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
1847 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001848 }
David Neto22f144c2017-06-12 14:26:21 -04001849
SJW2c317da2020-03-23 07:39:13 -05001850 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01001851 });
David Neto22f144c2017-06-12 14:26:21 -04001852}
1853
SJW2c317da2020-03-23 07:39:13 -05001854bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
1855 Module &M = *F.getParent();
1856 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001857 // The value to store.
1858 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001859
Kévin Petite8edce32019-04-10 14:23:32 +01001860 // The index argument from vstore_half.
1861 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001862
Kévin Petite8edce32019-04-10 14:23:32 +01001863 // The pointer argument from vstore_half.
1864 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001865
Kévin Petite8edce32019-04-10 14:23:32 +01001866 auto IntTy = Type::getInt32Ty(M.getContext());
1867 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001868 auto NewPointerTy =
1869 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001870 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001871
Kévin Petite8edce32019-04-10 14:23:32 +01001872 // Our intrinsic to pack a float2 to an int.
1873 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001874
Kévin Petite8edce32019-04-10 14:23:32 +01001875 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001876
Kévin Petite8edce32019-04-10 14:23:32 +01001877 // Turn the packed x & y into the final packing.
1878 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001879
Kévin Petite8edce32019-04-10 14:23:32 +01001880 // Cast the half* pointer to int*.
1881 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001882
Kévin Petite8edce32019-04-10 14:23:32 +01001883 // Index into the correct address of the casted pointer.
1884 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001885
Kévin Petite8edce32019-04-10 14:23:32 +01001886 // Store to the int* we casted to.
1887 return new StoreInst(X, Index, CI);
1888 });
David Neto22f144c2017-06-12 14:26:21 -04001889}
1890
SJW2c317da2020-03-23 07:39:13 -05001891bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
1892 Module &M = *F.getParent();
1893 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001894 // The value to store.
1895 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001896
Kévin Petite8edce32019-04-10 14:23:32 +01001897 // The index argument from vstore_half.
1898 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001899
Kévin Petite8edce32019-04-10 14:23:32 +01001900 // The pointer argument from vstore_half.
1901 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001902
Kévin Petite8edce32019-04-10 14:23:32 +01001903 auto IntTy = Type::getInt32Ty(M.getContext());
1904 auto Int2Ty = VectorType::get(IntTy, 2);
1905 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001906 auto NewPointerTy =
1907 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001908 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001909
Kévin Petite8edce32019-04-10 14:23:32 +01001910 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
1911 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04001912
Kévin Petite8edce32019-04-10 14:23:32 +01001913 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001914 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1915 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001916
Kévin Petite8edce32019-04-10 14:23:32 +01001917 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
1918 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001919
Kévin Petite8edce32019-04-10 14:23:32 +01001920 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001921 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1922 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001923
Kévin Petite8edce32019-04-10 14:23:32 +01001924 // Our intrinsic to pack a float2 to an int.
1925 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001926
Kévin Petite8edce32019-04-10 14:23:32 +01001927 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001928
Kévin Petite8edce32019-04-10 14:23:32 +01001929 // Turn the packed x & y into the final component of our int2.
1930 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001931
Kévin Petite8edce32019-04-10 14:23:32 +01001932 // Turn the packed z & w into the final component of our int2.
1933 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001934
Kévin Petite8edce32019-04-10 14:23:32 +01001935 auto Combine = InsertElementInst::Create(
1936 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001937 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
1938 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001939
Kévin Petite8edce32019-04-10 14:23:32 +01001940 // Cast the half* pointer to int2*.
1941 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001942
Kévin Petite8edce32019-04-10 14:23:32 +01001943 // Index into the correct address of the casted pointer.
1944 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001945
Kévin Petite8edce32019-04-10 14:23:32 +01001946 // Store to the int2* we casted to.
1947 return new StoreInst(Combine, Index, CI);
1948 });
David Neto22f144c2017-06-12 14:26:21 -04001949}
1950
SJW2c317da2020-03-23 07:39:13 -05001951bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
1952 // convert half to float
1953 Module &M = *F.getParent();
1954 return replaceCallsWithValue(F, [&](CallInst *CI) {
1955 SmallVector<Type *, 3> types;
1956 SmallVector<Value *, 3> args;
1957 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
1958 types.push_back(CI->getArgOperand(i)->getType());
1959 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05001960 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05001961
SJW2c317da2020-03-23 07:39:13 -05001962 auto NewFType = FunctionType::get(
1963 VectorType::get(Type::getFloatTy(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -04001964 cast<VectorType>(CI->getType())->getNumElements()),
SJW2c317da2020-03-23 07:39:13 -05001965 types, false);
1966
1967 std::string NewFName = "_Z11read_imagef";
1968 NewFName += F.getName().str().substr(15);
1969
1970 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1971
1972 auto NewCI = CallInst::Create(NewF, args, "", CI);
1973
1974 // Convert to the half type.
1975 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
1976 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05001977}
1978
SJW2c317da2020-03-23 07:39:13 -05001979bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
1980 // convert half to float
1981 Module &M = *F.getParent();
1982 return replaceCallsWithValue(F, [&](CallInst *CI) {
1983 SmallVector<Type *, 3> types(3);
1984 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001985
SJW2c317da2020-03-23 07:39:13 -05001986 // Image
1987 types[0] = CI->getArgOperand(0)->getType();
1988 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001989
SJW2c317da2020-03-23 07:39:13 -05001990 // Coord
1991 types[1] = CI->getArgOperand(1)->getType();
1992 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001993
SJW2c317da2020-03-23 07:39:13 -05001994 // Data
1995 types[2] = VectorType::get(
1996 Type::getFloatTy(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -04001997 cast<VectorType>(CI->getArgOperand(2)->getType())->getNumElements());
alan-bakerf7e17cb2020-01-02 07:29:59 -05001998
SJW2c317da2020-03-23 07:39:13 -05001999 auto NewFType =
2000 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002001
SJW2c317da2020-03-23 07:39:13 -05002002 int slen = F.getName().size();
2003 std::string NewFName = "_Z12write_imagef";
2004 NewFName += F.getName().str().substr(16, slen - 16 - 2) + "f";
alan-bakerf7e17cb2020-01-02 07:29:59 -05002005
SJW2c317da2020-03-23 07:39:13 -05002006 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002007
SJW2c317da2020-03-23 07:39:13 -05002008 // Convert data to the float type.
2009 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2010 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002011
SJW2c317da2020-03-23 07:39:13 -05002012 return CallInst::Create(NewF, args, "", CI);
2013 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002014}
2015
SJW2c317da2020-03-23 07:39:13 -05002016bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2017 Function &F) {
2018 // convert read_image with int coords to float coords
2019 Module &M = *F.getParent();
2020 return replaceCallsWithValue(F, [&](CallInst *CI) {
2021 // The image.
2022 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002023
SJW2c317da2020-03-23 07:39:13 -05002024 // The sampler.
2025 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002026
SJW2c317da2020-03-23 07:39:13 -05002027 // The coordinate (integer type that we can't handle).
2028 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002029
SJW2c317da2020-03-23 07:39:13 -05002030 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2031 uint32_t components =
2032 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2033 Type *float_ty = nullptr;
2034 if (components == 1) {
2035 float_ty = Type::getFloatTy(M.getContext());
2036 } else {
James Pricecf53df42020-04-20 14:41:24 -04002037 float_ty =
2038 VectorType::get(Type::getFloatTy(M.getContext()),
2039 cast<VectorType>(Arg2->getType())->getNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002040 }
David Neto22f144c2017-06-12 14:26:21 -04002041
SJW2c317da2020-03-23 07:39:13 -05002042 auto NewFType = FunctionType::get(
2043 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2044
2045 std::string NewFName = F.getName().str();
2046 NewFName[NewFName.length() - 1] = 'f';
2047
2048 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2049
2050 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2051
2052 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2053 });
David Neto22f144c2017-06-12 14:26:21 -04002054}
2055
SJW2c317da2020-03-23 07:39:13 -05002056bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2057 return replaceCallsWithValue(F, [&](CallInst *CI) {
2058 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002059
SJW2c317da2020-03-23 07:39:13 -05002060 // We need to map the OpenCL constants to the SPIR-V equivalents.
2061 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2062 const auto ConstantMemorySemantics = ConstantInt::get(
2063 IntTy, spv::MemorySemanticsUniformMemoryMask |
2064 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002065
SJW2c317da2020-03-23 07:39:13 -05002066 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002067
SJW2c317da2020-03-23 07:39:13 -05002068 // The pointer.
2069 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002070
SJW2c317da2020-03-23 07:39:13 -05002071 // The memory scope.
2072 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002073
SJW2c317da2020-03-23 07:39:13 -05002074 // The memory semantics.
2075 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002076
SJW2c317da2020-03-23 07:39:13 -05002077 if (2 < CI->getNumArgOperands()) {
2078 // The unequal memory semantics.
2079 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002080
SJW2c317da2020-03-23 07:39:13 -05002081 // The value.
2082 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002083
SJW2c317da2020-03-23 07:39:13 -05002084 // The comparator.
2085 Params.push_back(CI->getArgOperand(1));
2086 } else if (1 < CI->getNumArgOperands()) {
2087 // The value.
2088 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002089 }
David Neto22f144c2017-06-12 14:26:21 -04002090
SJW2c317da2020-03-23 07:39:13 -05002091 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2092 });
David Neto22f144c2017-06-12 14:26:21 -04002093}
2094
SJW2c317da2020-03-23 07:39:13 -05002095bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2096 llvm::AtomicRMWInst::BinOp Op) {
2097 return replaceCallsWithValue(F, [&](CallInst *CI) {
2098 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
2099 AtomicOrdering::SequentiallyConsistent,
2100 SyncScope::System, CI);
2101 });
2102}
David Neto22f144c2017-06-12 14:26:21 -04002103
SJW2c317da2020-03-23 07:39:13 -05002104bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2105 Module &M = *F.getParent();
2106 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002107 auto IntTy = Type::getInt32Ty(M.getContext());
2108 auto FloatTy = Type::getFloatTy(M.getContext());
2109
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002110 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2111 ConstantInt::get(IntTy, 1),
2112 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002113
2114 Constant *UpShuffleMask[4] = {
2115 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2116 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2117
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002118 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2119 UndefValue::get(FloatTy),
2120 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002121
Kévin Petite8edce32019-04-10 14:23:32 +01002122 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002123 auto Arg0 =
2124 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2125 ConstantVector::get(DownShuffleMask), "", CI);
2126 auto Arg1 =
2127 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2128 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002129 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002130
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002131 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
David Neto22f144c2017-06-12 14:26:21 -04002132
Kévin Petite8edce32019-04-10 14:23:32 +01002133 auto Cross3Func = M.getOrInsertFunction("_Z5crossDv3_fS_", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002134
Kévin Petite8edce32019-04-10 14:23:32 +01002135 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002136
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002137 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2138 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002139 });
David Neto22f144c2017-06-12 14:26:21 -04002140}
David Neto62653202017-10-16 19:05:18 -04002141
SJW2c317da2020-03-23 07:39:13 -05002142bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002143 // OpenCL's float result = fract(float x, float* ptr)
2144 //
2145 // In the LLVM domain:
2146 //
2147 // %floor_result = call spir_func float @floor(float %x)
2148 // store float %floor_result, float * %ptr
2149 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2150 // %result = call spir_func float
2151 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2152 //
2153 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2154 // and clspv.fract occur in the SPIR-V generator pass:
2155 //
2156 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2157 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2158 // ...
2159 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2160 // OpStore %ptr %floor_result
2161 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2162 // %fract_result = OpExtInst %float
2163 // %glsl_ext Fmin %fract_intermediate %just_under_1
2164
David Neto62653202017-10-16 19:05:18 -04002165 using std::string;
2166
2167 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2168 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002169
SJW2c317da2020-03-23 07:39:13 -05002170 Module &M = *F.getParent();
2171 return replaceCallsWithValue(F, [&](CallInst *CI) {
SJW2c317da2020-03-23 07:39:13 -05002172 std::string floor_name = "_Z5floor";
2173 std::string fmin_name = "_Z4fmin";
2174 std::string clspv_fract_name = "clspv.fract.";
2175 if (vec_size) {
2176 floor_name += "Dv" + std::to_string(vec_size) + "_f";
2177 fmin_name += "Dv" + std::to_string(vec_size) + "_f";
2178 clspv_fract_name += "v" + std::to_string(vec_size) + "f";
2179 } else {
2180 floor_name += "ff";
2181 fmin_name += "ff";
2182 clspv_fract_name += "f";
David Neto62653202017-10-16 19:05:18 -04002183 }
David Neto62653202017-10-16 19:05:18 -04002184
SJW2c317da2020-03-23 07:39:13 -05002185 // This is either float or a float vector. All the float-like
2186 // types are this type.
2187 auto result_ty = F.getReturnType();
2188
2189 Function *fmin_fn = M.getFunction(fmin_name);
2190 if (!fmin_fn) {
2191 // Make the fmin function.
2192 FunctionType *fn_ty =
2193 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2194 fmin_fn =
2195 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2196 fmin_fn->addFnAttr(Attribute::ReadNone);
2197 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2198 }
2199
2200 Function *floor_fn = M.getFunction(floor_name);
2201 if (!floor_fn) {
2202 // Make the floor function.
2203 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2204 floor_fn =
2205 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2206 floor_fn->addFnAttr(Attribute::ReadNone);
2207 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2208 }
2209
2210 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2211 if (!clspv_fract_fn) {
2212 // Make the clspv_fract function.
2213 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2214 clspv_fract_fn = cast<Function>(
2215 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2216 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2217 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2218 }
2219
2220 // Number of significant significand bits, whether represented or not.
2221 unsigned num_significand_bits;
2222 switch (result_ty->getScalarType()->getTypeID()) {
2223 case Type::HalfTyID:
2224 num_significand_bits = 11;
2225 break;
2226 case Type::FloatTyID:
2227 num_significand_bits = 24;
2228 break;
2229 case Type::DoubleTyID:
2230 num_significand_bits = 53;
2231 break;
2232 default:
2233 llvm_unreachable("Unhandled float type when processing fract builtin");
2234 break;
2235 }
2236 // Beware that the disassembler displays this value as
2237 // OpConstant %float 1
2238 // which is not quite right.
2239 const double kJustUnderOneScalar =
2240 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2241
2242 Constant *just_under_one =
2243 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2244 if (result_ty->isVectorTy()) {
2245 just_under_one = ConstantVector::getSplat(
James Pricecf53df42020-04-20 14:41:24 -04002246 {cast<VectorType>(result_ty)->getNumElements(), false},
2247 just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002248 }
2249
2250 IRBuilder<> Builder(CI);
2251
2252 auto arg = CI->getArgOperand(0);
2253 auto ptr = CI->getArgOperand(1);
2254
2255 // Compute floor result and store it.
2256 auto floor = Builder.CreateCall(floor_fn, {arg});
2257 Builder.CreateStore(floor, ptr);
2258
2259 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2260 auto fract_result =
2261 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2262
2263 return fract_result;
2264 });
David Neto62653202017-10-16 19:05:18 -04002265}