blob: 5827e0ce755c02026a2290db0809f621121297d5 [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);
128 bool replaceRelational(Function &F, CmpInst::Predicate P, int32_t C);
129 bool replaceIsInfAndIsNan(Function &F, spv::Op SPIRVOp, int32_t isvec);
130 bool replaceIsFinite(Function &F);
131 bool replaceAllAndAny(Function &F, spv::Op SPIRVOp);
132 bool replaceUpsample(Function &F);
133 bool replaceRotate(Function &F);
134 bool replaceConvert(Function &F, bool SrcIsSigned, bool DstIsSigned);
135 bool replaceMulHi(Function &F, bool is_signed, bool is_mad = false);
136 bool replaceSelect(Function &F);
137 bool replaceBitSelect(Function &F);
138 bool replaceStep(Function &F, bool is_smooth, int vec_size);
139 bool replaceSignbit(Function &F, bool is_vec);
140 bool replaceMul(Function &F, bool is_float, bool is_mad);
141 bool replaceVloadHalf(Function &F, const std::string &name, int vec_size);
142 bool replaceVloadHalf(Function &F);
143 bool replaceVloadHalf2(Function &F);
144 bool replaceVloadHalf4(Function &F);
145 bool replaceClspvVloadaHalf2(Function &F);
146 bool replaceClspvVloadaHalf4(Function &F);
147 bool replaceVstoreHalf(Function &F, int vec_size);
148 bool replaceVstoreHalf(Function &F);
149 bool replaceVstoreHalf2(Function &F);
150 bool replaceVstoreHalf4(Function &F);
151 bool replaceHalfReadImage(Function &F);
152 bool replaceHalfWriteImage(Function &F);
153 bool replaceSampledReadImageWithIntCoords(Function &F);
154 bool replaceAtomics(Function &F, spv::Op Op);
155 bool replaceAtomics(Function &F, llvm::AtomicRMWInst::BinOp Op);
156 bool replaceCross(Function &F);
157 bool replaceFract(Function &F, int vec_size);
158 bool replaceVload(Function &F);
159 bool replaceVstore(Function &F);
David Neto22f144c2017-06-12 14:26:21 -0400160};
SJW2c317da2020-03-23 07:39:13 -0500161
Kévin Petit91bc72e2019-04-08 15:17:46 +0100162} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400163
164char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400165INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
166 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400167
168namespace clspv {
169ModulePass *createReplaceOpenCLBuiltinPass() {
170 return new ReplaceOpenCLBuiltinPass();
171}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400172} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400173
174bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500175 std::list<Function *> func_list;
176 for (auto &F : M.getFunctionList()) {
177 // process only function declarations
178 if (F.isDeclaration() && runOnFunction(F)) {
179 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000180 }
181 }
SJW2c317da2020-03-23 07:39:13 -0500182 if (func_list.size() != 0) {
183 // recursively convert functions, but first remove dead
184 for (auto *F : func_list) {
185 if (F->use_empty()) {
186 F->eraseFromParent();
187 }
188 }
189 runOnModule(M);
190 return true;
191 }
192 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000193}
194
SJW2c317da2020-03-23 07:39:13 -0500195bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
196 auto &FI = Builtins::Lookup(&F);
197 switch (FI.getType()) {
198 case Builtins::kAbs:
199 if (!FI.getParameter(0).is_signed) {
200 return replaceAbs(F);
201 }
202 break;
203 case Builtins::kAbsDiff:
204 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
205 case Builtins::kCopysign:
206 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100207
SJW2c317da2020-03-23 07:39:13 -0500208 case Builtins::kHalfRecip:
209 case Builtins::kNativeRecip:
210 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100211
SJW2c317da2020-03-23 07:39:13 -0500212 case Builtins::kHalfDivide:
213 case Builtins::kNativeDivide:
214 return replaceDivide(F);
215
216 case Builtins::kDot:
217 return replaceDot(F);
218
219 case Builtins::kExp10:
220 case Builtins::kHalfExp10:
221 case Builtins::kNativeExp10: {
222 auto &P0 = FI.getParameter(0);
223 return replaceExp10(F, FI.getName(), P0.vector_size, P0.byte_len);
224 }
225
226 case Builtins::kLog10:
227 case Builtins::kHalfLog10:
228 case Builtins::kNativeLog10: {
229 auto &P0 = FI.getParameter(0);
230 return replaceLog10(F, FI.getName(), P0.vector_size, P0.byte_len);
231 }
232
233 case Builtins::kFmod:
234 return replaceFmod(F);
235
236 case Builtins::kBarrier:
237 case Builtins::kWorkGroupBarrier:
238 return replaceBarrier(F);
239
240 case Builtins::kMemFence:
241 return replaceMemFence(F, spv::MemorySemanticsSequentiallyConsistentMask);
242 case Builtins::kReadMemFence:
243 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
244 case Builtins::kWriteMemFence:
245 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
246
247 // Relational
248 case Builtins::kIsequal:
249 return replaceRelational(F, CmpInst::FCMP_OEQ,
250 FI.getParameter(0).vector_size ? -1 : 1);
251 case Builtins::kIsgreater:
252 return replaceRelational(F, CmpInst::FCMP_OGT,
253 FI.getParameter(0).vector_size ? -1 : 1);
254 case Builtins::kIsgreaterequal:
255 return replaceRelational(F, CmpInst::FCMP_OGE,
256 FI.getParameter(0).vector_size ? -1 : 1);
257 case Builtins::kIsless:
258 return replaceRelational(F, CmpInst::FCMP_OLT,
259 FI.getParameter(0).vector_size ? -1 : 1);
260 case Builtins::kIslessequal:
261 return replaceRelational(F, CmpInst::FCMP_OLE,
262 FI.getParameter(0).vector_size ? -1 : 1);
263 case Builtins::kIsnotequal:
264 return replaceRelational(F, CmpInst::FCMP_ONE,
265 FI.getParameter(0).vector_size ? -1 : 1);
266
267 case Builtins::kIsinf: {
268 bool is_vec = FI.getParameter(0).vector_size != 0;
269 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
270 }
271 case Builtins::kIsnan: {
272 bool is_vec = FI.getParameter(0).vector_size != 0;
273 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
274 }
275
276 case Builtins::kIsfinite:
277 return replaceIsFinite(F);
278
279 case Builtins::kAll: {
280 bool is_vec = FI.getParameter(0).vector_size != 0;
281 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
282 }
283 case Builtins::kAny: {
284 bool is_vec = FI.getParameter(0).vector_size != 0;
285 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
286 }
287
288 case Builtins::kUpsample:
289 return replaceUpsample(F);
290
291 case Builtins::kRotate:
292 return replaceRotate(F);
293
294 case Builtins::kConvert:
295 return replaceConvert(F, FI.getParameter(0).is_signed,
296 FI.getReturnType().is_signed);
297
298 case Builtins::kAtomicInc:
299 return replaceAtomics(F, spv::OpAtomicIIncrement);
300 case Builtins::kAtomicDec:
301 return replaceAtomics(F, spv::OpAtomicIDecrement);
302 case Builtins::kAtomicCmpxchg:
303 return replaceAtomics(F, spv::OpAtomicCompareExchange);
304 case Builtins::kAtomicAdd:
305 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
306 case Builtins::kAtomicSub:
307 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
308 case Builtins::kAtomicXchg:
309 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
310 case Builtins::kAtomicMin:
311 return replaceAtomics(F, FI.getParameter(0).is_signed
312 ? llvm::AtomicRMWInst::Min
313 : llvm::AtomicRMWInst::UMin);
314 case Builtins::kAtomicMax:
315 return replaceAtomics(F, FI.getParameter(0).is_signed
316 ? llvm::AtomicRMWInst::Max
317 : llvm::AtomicRMWInst::UMax);
318 case Builtins::kAtomicAnd:
319 return replaceAtomics(F, llvm::AtomicRMWInst::And);
320 case Builtins::kAtomicOr:
321 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
322 case Builtins::kAtomicXor:
323 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
324
325 case Builtins::kCross:
326 if (FI.getParameter(0).vector_size == 4) {
327 return replaceCross(F);
328 }
329 break;
330
331 case Builtins::kFract:
332 if (FI.getParameterCount()) {
333 return replaceFract(F, FI.getParameter(0).vector_size);
334 }
335 break;
336
337 case Builtins::kMadHi:
338 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
339 case Builtins::kMulHi:
340 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
341
342 case Builtins::kMad:
343 case Builtins::kMad24:
344 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
345 true);
346 case Builtins::kMul24:
347 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
348 false);
349
350 case Builtins::kSelect:
351 return replaceSelect(F);
352
353 case Builtins::kBitselect:
354 return replaceBitSelect(F);
355
356 case Builtins::kVload:
357 return replaceVload(F);
358
359 case Builtins::kVloadaHalf:
360 case Builtins::kVloadHalf:
361 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
362
363 case Builtins::kVstore:
364 return replaceVstore(F);
365
366 case Builtins::kVstoreHalf:
367 case Builtins::kVstoreaHalf:
368 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
369
370 case Builtins::kSmoothstep: {
371 int vec_size = FI.getLastParameter().vector_size;
372 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
373 return replaceStep(F, true, vec_size);
374 }
375 break;
376 }
377 case Builtins::kStep: {
378 int vec_size = FI.getLastParameter().vector_size;
379 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
380 return replaceStep(F, false, vec_size);
381 }
382 break;
383 }
384
385 case Builtins::kSignbit:
386 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
387
388 case Builtins::kReadImageh:
389 return replaceHalfReadImage(F);
390 case Builtins::kReadImagef:
391 case Builtins::kReadImagei:
392 case Builtins::kReadImageui: {
393 if (FI.getParameter(1).isSampler() &&
394 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
395 return replaceSampledReadImageWithIntCoords(F);
396 }
397 break;
398 }
399
400 case Builtins::kWriteImageh:
401 return replaceHalfWriteImage(F);
402
403 default:
404 break;
405 }
406
407 return false;
408}
409
410bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
411 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400412 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100413}
414
SJW2c317da2020-03-23 07:39:13 -0500415bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
416 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100417 auto XValue = CI->getOperand(0);
418 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100419
Kévin Petite8edce32019-04-10 14:23:32 +0100420 IRBuilder<> Builder(CI);
421 auto XmY = Builder.CreateSub(XValue, YValue);
422 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100423
SJW2c317da2020-03-23 07:39:13 -0500424 Value *Cmp = nullptr;
425 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100426 Cmp = Builder.CreateICmpSGT(YValue, XValue);
427 } else {
428 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100429 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100430
Kévin Petite8edce32019-04-10 14:23:32 +0100431 return Builder.CreateSelect(Cmp, YmX, XmY);
432 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100433}
434
SJW2c317da2020-03-23 07:39:13 -0500435bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
436 return replaceCallsWithValue(F, [&F](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100437 auto XValue = CI->getOperand(0);
438 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100439
Kévin Petite8edce32019-04-10 14:23:32 +0100440 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100441
SJW2c317da2020-03-23 07:39:13 -0500442 Type *IntTy = Type::getIntNTy(F.getContext(), Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -0400443 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
444 IntTy = VectorType::get(IntTy, vec_ty->getNumElements());
Kévin Petit8c1be282019-04-02 19:34:25 +0100445 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100446
Kévin Petite8edce32019-04-10 14:23:32 +0100447 // Return X with the sign of Y
448
449 // Sign bit masks
450 auto SignBit = IntTy->getScalarSizeInBits() - 1;
451 auto SignBitMask = 1 << SignBit;
452 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
453 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
454
455 IRBuilder<> Builder(CI);
456
457 // Extract sign of Y
458 auto YInt = Builder.CreateBitCast(YValue, IntTy);
459 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
460
461 // Clear sign bit in X
462 auto XInt = Builder.CreateBitCast(XValue, IntTy);
463 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
464
465 // Insert sign bit of Y into X
466 auto NewXInt = Builder.CreateOr(XInt, YSign);
467
468 // And cast back to floating-point
469 return Builder.CreateBitCast(NewXInt, Ty);
470 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100471}
472
SJW2c317da2020-03-23 07:39:13 -0500473bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
474 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100475 // Recip has one arg.
476 auto Arg = CI->getOperand(0);
477 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
478 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
479 });
David Neto22f144c2017-06-12 14:26:21 -0400480}
481
SJW2c317da2020-03-23 07:39:13 -0500482bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
483 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100484 auto Op0 = CI->getOperand(0);
485 auto Op1 = CI->getOperand(1);
486 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
487 });
David Neto22f144c2017-06-12 14:26:21 -0400488}
489
SJW2c317da2020-03-23 07:39:13 -0500490bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
491 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100492 auto Op0 = CI->getOperand(0);
493 auto Op1 = CI->getOperand(1);
494
SJW2c317da2020-03-23 07:39:13 -0500495 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100496 if (Op0->getType()->isVectorTy()) {
497 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
498 CI->getType(), {Op0, Op1});
499 } else {
500 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
501 }
502
503 return V;
504 });
505}
506
SJW2c317da2020-03-23 07:39:13 -0500507bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
508 const std::string &basename,
509 int vec_size, int byte_len) {
510 // convert to natural
511 auto slen = basename.length() - 2;
512 std::string NewFName = "_Z" + std::to_string(slen) + basename.substr(0, slen);
513 if (vec_size) {
514 NewFName += "Dv" + std::to_string(vec_size) + "_";
515 }
516 switch (byte_len) {
517 case 4:
518 NewFName += "f";
519 break;
520 case 8:
521 NewFName += "d";
522 break;
523 default:
524 llvm_unreachable("Unsupported exp10 byte length");
525 break;
David Neto22f144c2017-06-12 14:26:21 -0400526 }
527
SJW2c317da2020-03-23 07:39:13 -0500528 Module &M = *F.getParent();
529 return replaceCallsWithValue(F, [&](CallInst *CI) {
530 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
531
532 auto Arg = CI->getOperand(0);
533
534 // Constant of the natural log of 10 (ln(10)).
535 const double Ln10 =
536 2.302585092994045684017991454684364207601101488628772976033;
537
538 auto Mul = BinaryOperator::Create(
539 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
540
541 return CallInst::Create(NewF, Mul, "", CI);
542 });
David Neto22f144c2017-06-12 14:26:21 -0400543}
544
SJW2c317da2020-03-23 07:39:13 -0500545bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100546 // OpenCL fmod(x,y) is x - y * trunc(x/y)
547 // The sign for a non-zero result is taken from x.
548 // (Try an example.)
549 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500550 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100551 auto Op0 = CI->getOperand(0);
552 auto Op1 = CI->getOperand(1);
553 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
554 });
555}
556
SJW2c317da2020-03-23 07:39:13 -0500557bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
558 const std::string &basename,
559 int vec_size, int byte_len) {
560 // convert to natural
561 auto slen = basename.length() - 2;
562 std::string NewFName = "_Z" + std::to_string(slen) + basename.substr(0, slen);
563 if (vec_size) {
564 NewFName += "Dv" + std::to_string(vec_size) + "_";
565 }
566 switch (byte_len) {
567 case 4:
568 NewFName += "f";
569 break;
570 case 8:
571 NewFName += "d";
572 break;
573 default:
574 llvm_unreachable("Unsupported log10 byte length");
575 break;
David Neto22f144c2017-06-12 14:26:21 -0400576 }
577
SJW2c317da2020-03-23 07:39:13 -0500578 Module &M = *F.getParent();
579 return replaceCallsWithValue(F, [&](CallInst *CI) {
580 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
581
582 auto Arg = CI->getOperand(0);
583
584 // Constant of the reciprocal of the natural log of 10 (ln(10)).
585 const double Ln10 =
586 0.434294481903251827651128918916605082294397005803666566114;
587
588 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
589
590 return BinaryOperator::Create(Instruction::FMul,
591 ConstantFP::get(Arg->getType(), Ln10), NewCI,
592 "", CI);
593 });
David Neto22f144c2017-06-12 14:26:21 -0400594}
595
SJW2c317da2020-03-23 07:39:13 -0500596bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F) {
David Neto22f144c2017-06-12 14:26:21 -0400597
598 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
599
SJW2c317da2020-03-23 07:39:13 -0500600 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100601 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400602
Kévin Petitc4643922019-06-17 19:32:05 +0100603 // We need to map the OpenCL constants to the SPIR-V equivalents.
604 const auto LocalMemFence =
605 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
606 const auto GlobalMemFence =
607 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
608 const auto ConstantSequentiallyConsistent = ConstantInt::get(
609 Arg->getType(), spv::MemorySemanticsSequentiallyConsistentMask);
610 const auto ConstantScopeDevice =
611 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
612 const auto ConstantScopeWorkgroup =
613 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400614
Kévin Petitc4643922019-06-17 19:32:05 +0100615 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
616 const auto LocalMemFenceMask =
617 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
618 const auto WorkgroupShiftAmount =
619 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
620 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
621 Instruction::Shl, LocalMemFenceMask,
622 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400623
Kévin Petitc4643922019-06-17 19:32:05 +0100624 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
625 const auto GlobalMemFenceMask =
626 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
627 const auto UniformShiftAmount =
628 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
629 const auto MemorySemanticsUniform = BinaryOperator::Create(
630 Instruction::Shl, GlobalMemFenceMask,
631 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400632
Kévin Petitc4643922019-06-17 19:32:05 +0100633 // And combine the above together, also adding in
634 // MemorySemanticsSequentiallyConsistentMask.
635 auto MemorySemantics =
636 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
637 ConstantSequentiallyConsistent, "", CI);
638 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
639 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400640
Kévin Petitc4643922019-06-17 19:32:05 +0100641 // For Memory Scope if we used CLK_GLOBAL_MEM_FENCE, we need to use
642 // Device Scope, otherwise Workgroup Scope.
643 const auto Cmp =
644 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, GlobalMemFenceMask,
645 GlobalMemFence, "", CI);
646 const auto MemoryScope = SelectInst::Create(Cmp, ConstantScopeDevice,
647 ConstantScopeWorkgroup, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400648
Kévin Petitc4643922019-06-17 19:32:05 +0100649 // Lastly, the Execution Scope is always Workgroup Scope.
650 const auto ExecutionScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400651
Kévin Petitc4643922019-06-17 19:32:05 +0100652 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
653 {Attribute::NoDuplicate}, CI->getType(),
654 {ExecutionScope, MemoryScope, MemorySemantics});
655 });
David Neto22f144c2017-06-12 14:26:21 -0400656}
657
SJW2c317da2020-03-23 07:39:13 -0500658bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
659 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400660
SJW2c317da2020-03-23 07:39:13 -0500661 return replaceCallsWithValue(F, [&](CallInst *CI) {
662 enum { CLK_LOCAL_MEM_FENCE = 0x01, CLK_GLOBAL_MEM_FENCE = 0x02 };
David Neto22f144c2017-06-12 14:26:21 -0400663
SJW2c317da2020-03-23 07:39:13 -0500664 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400665
SJW2c317da2020-03-23 07:39:13 -0500666 // We need to map the OpenCL constants to the SPIR-V equivalents.
667 const auto LocalMemFence =
668 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
669 const auto GlobalMemFence =
670 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
671 const auto ConstantMemorySemantics =
672 ConstantInt::get(Arg->getType(), semantics);
673 const auto ConstantScopeDevice =
674 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -0400675
SJW2c317da2020-03-23 07:39:13 -0500676 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
677 const auto LocalMemFenceMask =
678 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
679 const auto WorkgroupShiftAmount =
680 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
681 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
682 Instruction::Shl, LocalMemFenceMask,
683 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400684
SJW2c317da2020-03-23 07:39:13 -0500685 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
686 const auto GlobalMemFenceMask =
687 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
688 const auto UniformShiftAmount =
689 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
690 const auto MemorySemanticsUniform = BinaryOperator::Create(
691 Instruction::Shl, GlobalMemFenceMask,
692 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400693
SJW2c317da2020-03-23 07:39:13 -0500694 // And combine the above together, also adding in
695 // MemorySemanticsSequentiallyConsistentMask.
696 auto MemorySemantics =
697 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
698 ConstantMemorySemantics, "", CI);
699 MemorySemantics = BinaryOperator::Create(Instruction::Or, MemorySemantics,
700 MemorySemanticsUniform, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400701
SJW2c317da2020-03-23 07:39:13 -0500702 // Memory Scope is always device.
703 const auto MemoryScope = ConstantScopeDevice;
David Neto22f144c2017-06-12 14:26:21 -0400704
SJW2c317da2020-03-23 07:39:13 -0500705 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier, {}, CI->getType(),
706 {MemoryScope, MemorySemantics});
707 });
David Neto22f144c2017-06-12 14:26:21 -0400708}
709
SJW2c317da2020-03-23 07:39:13 -0500710bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
711 CmpInst::Predicate P,
712 int32_t C) {
713 return replaceCallsWithValue(F, [&](CallInst *CI) {
714 // The predicate to use in the CmpInst.
715 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -0400716
SJW2c317da2020-03-23 07:39:13 -0500717 // The value to return for true.
718 auto TrueValue = ConstantInt::getSigned(CI->getType(), C);
David Neto22f144c2017-06-12 14:26:21 -0400719
SJW2c317da2020-03-23 07:39:13 -0500720 // The value to return for false.
721 auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400722
SJW2c317da2020-03-23 07:39:13 -0500723 auto Arg1 = CI->getOperand(0);
724 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -0400725
SJW2c317da2020-03-23 07:39:13 -0500726 const auto Cmp =
727 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400728
SJW2c317da2020-03-23 07:39:13 -0500729 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
730 });
David Neto22f144c2017-06-12 14:26:21 -0400731}
732
SJW2c317da2020-03-23 07:39:13 -0500733bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
734 spv::Op SPIRVOp,
735 int32_t C) {
736 Module &M = *F.getParent();
737 return replaceCallsWithValue(F, [&](CallInst *CI) {
738 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -0400739
SJW2c317da2020-03-23 07:39:13 -0500740 // The value to return for true.
741 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -0400742
SJW2c317da2020-03-23 07:39:13 -0500743 // The value to return for false.
744 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -0400745
SJW2c317da2020-03-23 07:39:13 -0500746 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -0400747 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
SJW2c317da2020-03-23 07:39:13 -0500748 CorrespondingBoolTy = VectorType::get(Type::getInt1Ty(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -0400749 CIVecTy->getNumElements());
David Neto22f144c2017-06-12 14:26:21 -0400750 }
David Neto22f144c2017-06-12 14:26:21 -0400751
SJW2c317da2020-03-23 07:39:13 -0500752 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
753 CorrespondingBoolTy, {CI->getOperand(0)});
754
755 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
756 });
David Neto22f144c2017-06-12 14:26:21 -0400757}
758
SJW2c317da2020-03-23 07:39:13 -0500759bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
760 Module &M = *F.getParent();
761 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100762 auto &C = M.getContext();
763 auto Val = CI->getOperand(0);
764 auto ValTy = Val->getType();
765 auto RetTy = CI->getType();
766
767 // Get a suitable integer type to represent the number
768 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
769
770 // Create Mask
771 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -0500772 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100773 switch (ScalarSize) {
774 case 16:
775 InfMask = ConstantInt::get(IntTy, 0x7C00U);
776 break;
777 case 32:
778 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
779 break;
780 case 64:
781 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
782 break;
783 default:
784 llvm_unreachable("Unsupported floating-point type");
785 }
786
787 IRBuilder<> Builder(CI);
788
789 // Bitcast to int
790 auto ValInt = Builder.CreateBitCast(Val, IntTy);
791
792 // Mask and compare
793 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
794 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
795
796 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -0500797 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100798 if (ValTy->isVectorTy()) {
799 RetTrue = ConstantInt::getSigned(RetTy, -1);
800 } else {
801 RetTrue = ConstantInt::get(RetTy, 1);
802 }
803 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
804 });
805}
806
SJW2c317da2020-03-23 07:39:13 -0500807bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
808 Module &M = *F.getParent();
809 return replaceCallsWithValue(F, [&](CallInst *CI) {
810 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400811
SJW2c317da2020-03-23 07:39:13 -0500812 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +0000813
SJW2c317da2020-03-23 07:39:13 -0500814 // If the argument is a 32-bit int, just use a shift
815 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
816 V = BinaryOperator::Create(Instruction::LShr, Arg,
817 ConstantInt::get(Arg->getType(), 31), "", CI);
818 } else {
819 // The value for zero to compare against.
820 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -0400821
SJW2c317da2020-03-23 07:39:13 -0500822 // The value to return for true.
823 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -0400824
SJW2c317da2020-03-23 07:39:13 -0500825 // The value to return for false.
826 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400827
SJW2c317da2020-03-23 07:39:13 -0500828 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
829 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400830
SJW2c317da2020-03-23 07:39:13 -0500831 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -0400832
SJW2c317da2020-03-23 07:39:13 -0500833 // If we have a function to call, call it!
834 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -0400835
SJW2c317da2020-03-23 07:39:13 -0500836 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -0400837
SJW2c317da2020-03-23 07:39:13 -0500838 const auto NewCI = clspv::InsertSPIRVOp(
839 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
840 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -0400841
SJW2c317da2020-03-23 07:39:13 -0500842 } else {
843 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -0400844 }
845
SJW2c317da2020-03-23 07:39:13 -0500846 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400847 }
SJW2c317da2020-03-23 07:39:13 -0500848 return V;
849 });
David Neto22f144c2017-06-12 14:26:21 -0400850}
851
SJW2c317da2020-03-23 07:39:13 -0500852bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
853 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
854 // Get arguments
855 auto HiValue = CI->getOperand(0);
856 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +0000857
SJW2c317da2020-03-23 07:39:13 -0500858 // Don't touch overloads that aren't in OpenCL C
859 auto HiType = HiValue->getType();
860 auto LoType = LoValue->getType();
861
862 if (HiType != LoType) {
863 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000864 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000865
SJW2c317da2020-03-23 07:39:13 -0500866 if (!HiType->isIntOrIntVectorTy()) {
867 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000868 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000869
SJW2c317da2020-03-23 07:39:13 -0500870 if (HiType->getScalarSizeInBits() * 2 !=
871 CI->getType()->getScalarSizeInBits()) {
872 return nullptr;
873 }
874
875 if ((HiType->getScalarSizeInBits() != 8) &&
876 (HiType->getScalarSizeInBits() != 16) &&
877 (HiType->getScalarSizeInBits() != 32)) {
878 return nullptr;
879 }
880
James Pricecf53df42020-04-20 14:41:24 -0400881 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
882 unsigned NumElements = HiVecType->getNumElements();
883 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
884 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500885 return nullptr;
886 }
887 }
888
889 // Convert both operands to the result type
890 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
891 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
892
893 // Shift high operand
894 auto ShiftAmount =
895 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
896 auto HiShifted =
897 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
898
899 // OR both results
900 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
901 });
Kévin Petitbf0036c2019-03-06 13:57:10 +0000902}
903
SJW2c317da2020-03-23 07:39:13 -0500904bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
905 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
906 // Get arguments
907 auto SrcValue = CI->getOperand(0);
908 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +0000909
SJW2c317da2020-03-23 07:39:13 -0500910 // Don't touch overloads that aren't in OpenCL C
911 auto SrcType = SrcValue->getType();
912 auto RotType = RotAmount->getType();
913
914 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
915 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000916 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000917
SJW2c317da2020-03-23 07:39:13 -0500918 if (!SrcType->isIntOrIntVectorTy()) {
919 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +0000920 }
Kévin Petitd44eef52019-03-08 13:22:14 +0000921
SJW2c317da2020-03-23 07:39:13 -0500922 if ((SrcType->getScalarSizeInBits() != 8) &&
923 (SrcType->getScalarSizeInBits() != 16) &&
924 (SrcType->getScalarSizeInBits() != 32) &&
925 (SrcType->getScalarSizeInBits() != 64)) {
926 return nullptr;
927 }
928
James Pricecf53df42020-04-20 14:41:24 -0400929 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
930 unsigned NumElements = SrcVecType->getNumElements();
931 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
932 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500933 return nullptr;
934 }
935 }
936
937 // The approach used is to shift the top bits down, the bottom bits up
938 // and OR the two shifted values.
939
940 // The rotation amount is to be treated modulo the element size.
941 // Since SPIR-V shift ops don't support this, let's apply the
942 // modulo ahead of shifting. The element size is always a power of
943 // two so we can just AND with a mask.
944 auto ModMask =
945 ConstantInt::get(SrcType, SrcType->getScalarSizeInBits() - 1);
946 RotAmount =
947 BinaryOperator::Create(Instruction::And, RotAmount, ModMask, "", CI);
948
949 // Let's calc the amount by which to shift top bits down
950 auto ScalarSize = ConstantInt::get(SrcType, SrcType->getScalarSizeInBits());
951 auto DownAmount =
952 BinaryOperator::Create(Instruction::Sub, ScalarSize, RotAmount, "", CI);
953
954 // Now shift the bottom bits up and the top bits down
955 auto LoRotated =
956 BinaryOperator::Create(Instruction::Shl, SrcValue, RotAmount, "", CI);
957 auto HiRotated =
958 BinaryOperator::Create(Instruction::LShr, SrcValue, DownAmount, "", CI);
959
960 // Finally OR the two shifted values
961 return BinaryOperator::Create(Instruction::Or, LoRotated, HiRotated, "",
962 CI);
963 });
Kévin Petitd44eef52019-03-08 13:22:14 +0000964}
965
SJW2c317da2020-03-23 07:39:13 -0500966bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
967 bool DstIsSigned) {
968 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
969 Value *V = nullptr;
970 // Get arguments
971 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000972
SJW2c317da2020-03-23 07:39:13 -0500973 // Don't touch overloads that aren't in OpenCL C
974 auto SrcType = SrcValue->getType();
975 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000976
SJW2c317da2020-03-23 07:39:13 -0500977 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
978 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
979 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000980 }
981
James Pricecf53df42020-04-20 14:41:24 -0400982 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
983 unsigned SrcNumElements = SrcVecType->getNumElements();
984 unsigned DstNumElements = cast<VectorType>(DstType)->getNumElements();
985 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -0500986 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000987 }
988
James Pricecf53df42020-04-20 14:41:24 -0400989 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
990 (SrcNumElements != 4) && (SrcNumElements != 8) &&
991 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500992 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000993 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000994 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +0000995
SJW2c317da2020-03-23 07:39:13 -0500996 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
997 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
998
999 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1000 bool DstIsInt = DstType->isIntOrIntVectorTy();
1001
1002 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1003 // Unnecessary cast operation.
1004 V = SrcValue;
1005 } else if (SrcIsFloat && DstIsFloat) {
1006 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1007 } else if (SrcIsFloat && DstIsInt) {
1008 if (DstIsSigned) {
1009 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1010 } else {
1011 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1012 }
1013 } else if (SrcIsInt && DstIsFloat) {
1014 if (SrcIsSigned) {
1015 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1016 } else {
1017 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1018 }
1019 } else if (SrcIsInt && DstIsInt) {
1020 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1021 } else {
1022 // Not something we're supposed to handle, just move on
1023 }
1024
1025 return V;
1026 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001027}
1028
SJW2c317da2020-03-23 07:39:13 -05001029bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1030 bool is_mad) {
1031 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1032 Value *V = nullptr;
1033 // Get arguments
1034 auto AValue = CI->getOperand(0);
1035 auto BValue = CI->getOperand(1);
1036 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001037
SJW2c317da2020-03-23 07:39:13 -05001038 // Don't touch overloads that aren't in OpenCL C
1039 auto AType = AValue->getType();
1040 auto BType = BValue->getType();
1041 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001042
SJW2c317da2020-03-23 07:39:13 -05001043 if ((AType != BType) || (CI->getType() != AType) ||
1044 (is_mad && (AType != CType))) {
1045 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001046 }
1047
SJW2c317da2020-03-23 07:39:13 -05001048 if (!AType->isIntOrIntVectorTy()) {
1049 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001050 }
Kévin Petit8a560882019-03-21 15:24:34 +00001051
SJW2c317da2020-03-23 07:39:13 -05001052 if ((AType->getScalarSizeInBits() != 8) &&
1053 (AType->getScalarSizeInBits() != 16) &&
1054 (AType->getScalarSizeInBits() != 32) &&
1055 (AType->getScalarSizeInBits() != 64)) {
1056 return V;
1057 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001058
James Pricecf53df42020-04-20 14:41:24 -04001059 if (auto AVecType = dyn_cast<VectorType>(AType)) {
1060 unsigned NumElements = AVecType->getNumElements();
1061 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1062 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001063 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001064 }
1065 }
1066
SJW2c317da2020-03-23 07:39:13 -05001067 // Our SPIR-V op returns a struct, create a type for it
1068 SmallVector<Type *, 2> TwoValueType = {AType, AType};
1069 auto ExMulRetType = StructType::create(TwoValueType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001070
SJW2c317da2020-03-23 07:39:13 -05001071 // Select the appropriate signed/unsigned SPIR-V op
1072 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1073
1074 // Call the SPIR-V op
1075 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1076 ExMulRetType, {AValue, BValue});
1077
1078 // Get the high part of the result
1079 unsigned Idxs[] = {1};
1080 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1081
1082 // If we're handling a mad_hi, add the third argument to the result
1083 if (is_mad) {
1084 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001085 }
1086
SJW2c317da2020-03-23 07:39:13 -05001087 return V;
1088 });
Kévin Petit8a560882019-03-21 15:24:34 +00001089}
1090
SJW2c317da2020-03-23 07:39:13 -05001091bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1092 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1093 // Get arguments
1094 auto FalseValue = CI->getOperand(0);
1095 auto TrueValue = CI->getOperand(1);
1096 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001097
SJW2c317da2020-03-23 07:39:13 -05001098 // Don't touch overloads that aren't in OpenCL C
1099 auto FalseType = FalseValue->getType();
1100 auto TrueType = TrueValue->getType();
1101 auto PredicateType = PredicateValue->getType();
1102
1103 if (FalseType != TrueType) {
1104 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001105 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001106
SJW2c317da2020-03-23 07:39:13 -05001107 if (!PredicateType->isIntOrIntVectorTy()) {
1108 return nullptr;
1109 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001110
SJW2c317da2020-03-23 07:39:13 -05001111 if (!FalseType->isIntOrIntVectorTy() &&
1112 !FalseType->getScalarType()->isFloatingPointTy()) {
1113 return nullptr;
1114 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001115
SJW2c317da2020-03-23 07:39:13 -05001116 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1117 return nullptr;
1118 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001119
SJW2c317da2020-03-23 07:39:13 -05001120 if (FalseType->getScalarSizeInBits() !=
1121 PredicateType->getScalarSizeInBits()) {
1122 return nullptr;
1123 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001124
James Pricecf53df42020-04-20 14:41:24 -04001125 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
1126 unsigned NumElements = FalseVecType->getNumElements();
1127 if (NumElements != cast<VectorType>(PredicateType)->getNumElements()) {
SJW2c317da2020-03-23 07:39:13 -05001128 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001129 }
1130
James Pricecf53df42020-04-20 14:41:24 -04001131 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1132 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001133 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001134 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001135 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001136
SJW2c317da2020-03-23 07:39:13 -05001137 // Create constant
1138 const auto ZeroValue = Constant::getNullValue(PredicateType);
1139
1140 // Scalar and vector are to be treated differently
1141 CmpInst::Predicate Pred;
1142 if (PredicateType->isVectorTy()) {
1143 Pred = CmpInst::ICMP_SLT;
1144 } else {
1145 Pred = CmpInst::ICMP_NE;
1146 }
1147
1148 // Create comparison instruction
1149 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1150 ZeroValue, "", CI);
1151
1152 // Create select
1153 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1154 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001155}
1156
SJW2c317da2020-03-23 07:39:13 -05001157bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1158 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1159 Value *V = nullptr;
1160 if (CI->getNumOperands() != 4) {
1161 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001162 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001163
SJW2c317da2020-03-23 07:39:13 -05001164 // Get arguments
1165 auto FalseValue = CI->getOperand(0);
1166 auto TrueValue = CI->getOperand(1);
1167 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001168
SJW2c317da2020-03-23 07:39:13 -05001169 // Don't touch overloads that aren't in OpenCL C
1170 auto FalseType = FalseValue->getType();
1171 auto TrueType = TrueValue->getType();
1172 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001173
SJW2c317da2020-03-23 07:39:13 -05001174 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1175 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001176 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001177
James Pricecf53df42020-04-20 14:41:24 -04001178 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001179 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1180 !TrueType->getScalarType()->isIntegerTy()) {
1181 return V;
1182 }
James Pricecf53df42020-04-20 14:41:24 -04001183 unsigned NumElements = TrueVecType->getNumElements();
1184 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1185 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001186 return V;
1187 }
1188 }
1189
1190 // Remember the type of the operands
1191 auto OpType = TrueType;
1192
1193 // The actual bit selection will always be done on an integer type,
1194 // declare it here
1195 Type *BitType;
1196
1197 // If the operands are float, then bitcast them to int
1198 if (OpType->getScalarType()->isFloatingPointTy()) {
1199
1200 // First create the new type
1201 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1202
1203 // Then bitcast all operands
1204 PredicateValue =
1205 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1206 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1207 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1208
1209 } else {
1210 // The operands have an integer type, use it directly
1211 BitType = OpType;
1212 }
1213
1214 // All the operands are now always integers
1215 // implement as (c & b) | (~c & a)
1216
1217 // Create our negated predicate value
1218 auto AllOnes = Constant::getAllOnesValue(BitType);
1219 auto NotPredicateValue = BinaryOperator::Create(
1220 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1221
1222 // Then put everything together
1223 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1224 FalseValue, "", CI);
1225 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1226 TrueValue, "", CI);
1227
1228 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1229
1230 // If we were dealing with a floating point type, we must bitcast
1231 // the result back to that
1232 if (OpType->getScalarType()->isFloatingPointTy()) {
1233 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1234 }
1235
1236 return V;
1237 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001238}
1239
SJW2c317da2020-03-23 07:39:13 -05001240bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth,
1241 int vec_size) {
1242 // convert to vector versions
1243 Module &M = *F.getParent();
1244 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1245 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1246 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001247
SJW2c317da2020-03-23 07:39:13 -05001248 std::string NewFName = "_Z";
1249 if (is_smooth) {
1250 NewFName += std::to_string(10) + "smoothstepDv" +
1251 std::to_string(vec_size) + "_fS_S_";
1252 } else {
1253 NewFName +=
1254 std::to_string(4) + "stepDv" + std::to_string(vec_size) + "_fS_";
Kévin Petit6b0a9532018-10-30 20:00:39 +00001255 }
Kévin Petit6b0a9532018-10-30 20:00:39 +00001256
SJW2c317da2020-03-23 07:39:13 -05001257 // First figure out which function we're dealing with
1258 if (is_smooth) {
1259 ArgsToSplat.push_back(CI->getOperand(1));
1260 VectorArg = CI->getOperand(2);
1261 } else {
1262 VectorArg = CI->getOperand(1);
1263 }
1264
1265 // Splat arguments that need to be
1266 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001267 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001268
1269 for (auto arg : ArgsToSplat) {
1270 Value *NewVectorArg = UndefValue::get(VecType);
James Pricecf53df42020-04-20 14:41:24 -04001271 for (auto i = 0; i < VecType->getNumElements(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001272 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1273 NewVectorArg =
1274 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1275 }
1276 SplatArgs.push_back(NewVectorArg);
1277 }
1278
1279 // Replace the call with the vector/vector flavour
1280 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1281 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1282
1283 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1284
1285 SmallVector<Value *, 3> NewArgs;
1286 for (auto arg : SplatArgs) {
1287 NewArgs.push_back(arg);
1288 }
1289 NewArgs.push_back(VectorArg);
1290
1291 return CallInst::Create(NewF, NewArgs, "", CI);
1292 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001293}
1294
SJW2c317da2020-03-23 07:39:13 -05001295bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
1296 Module &M = *F.getParent();
1297 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1298 auto Arg = CI->getOperand(0);
1299 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001300
SJW2c317da2020-03-23 07:39:13 -05001301 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001302
SJW2c317da2020-03-23 07:39:13 -05001303 return BinaryOperator::Create(Op, Bitcast,
1304 ConstantInt::get(CI->getType(), 31), "", CI);
1305 });
David Neto22f144c2017-06-12 14:26:21 -04001306}
1307
SJW2c317da2020-03-23 07:39:13 -05001308bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1309 bool is_mad) {
1310 Module &M = *F.getParent();
1311 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1312 // The multiply instruction to use.
1313 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001314
SJW2c317da2020-03-23 07:39:13 -05001315 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001316
SJW2c317da2020-03-23 07:39:13 -05001317 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1318 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001319
SJW2c317da2020-03-23 07:39:13 -05001320 if (is_mad) {
1321 // The add instruction to use.
1322 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001323
SJW2c317da2020-03-23 07:39:13 -05001324 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001325 }
David Neto22f144c2017-06-12 14:26:21 -04001326
SJW2c317da2020-03-23 07:39:13 -05001327 return V;
1328 });
David Neto22f144c2017-06-12 14:26:21 -04001329}
1330
SJW2c317da2020-03-23 07:39:13 -05001331bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
1332 Module &M = *F.getParent();
1333 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1334 Value *V = nullptr;
1335 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001336
SJW2c317da2020-03-23 07:39:13 -05001337 auto data_type = data->getType();
1338 if (!data_type->isVectorTy())
1339 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001340
James Pricecf53df42020-04-20 14:41:24 -04001341 auto vec_data_type = cast<VectorType>(data_type);
1342
1343 auto elems = vec_data_type->getNumElements();
SJW2c317da2020-03-23 07:39:13 -05001344 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1345 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001346
SJW2c317da2020-03-23 07:39:13 -05001347 auto offset = CI->getOperand(1);
1348 auto ptr = CI->getOperand(2);
1349 auto ptr_type = ptr->getType();
1350 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001351 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001352 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001353
SJW2c317da2020-03-23 07:39:13 -05001354 // Avoid pointer casts. Instead generate the correct number of stores
1355 // and rely on drivers to coalesce appropriately.
1356 IRBuilder<> builder(CI);
1357 auto elems_const = builder.getInt32(elems);
1358 auto adjust = builder.CreateMul(offset, elems_const);
1359 for (auto i = 0; i < elems; ++i) {
1360 auto idx = builder.getInt32(i);
1361 auto add = builder.CreateAdd(adjust, idx);
1362 auto gep = builder.CreateGEP(ptr, add);
1363 auto extract = builder.CreateExtractElement(data, i);
1364 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001365 }
SJW2c317da2020-03-23 07:39:13 -05001366 return V;
1367 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001368}
1369
SJW2c317da2020-03-23 07:39:13 -05001370bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
1371 Module &M = *F.getParent();
1372 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1373 Value *V = nullptr;
1374 auto ret_type = F.getReturnType();
1375 if (!ret_type->isVectorTy())
1376 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001377
James Pricecf53df42020-04-20 14:41:24 -04001378 auto vec_ret_type = cast<VectorType>(ret_type);
1379
1380 auto elems = vec_ret_type->getNumElements();
SJW2c317da2020-03-23 07:39:13 -05001381 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1382 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001383
SJW2c317da2020-03-23 07:39:13 -05001384 auto offset = CI->getOperand(0);
1385 auto ptr = CI->getOperand(1);
1386 auto ptr_type = ptr->getType();
1387 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001388 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001389 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001390
SJW2c317da2020-03-23 07:39:13 -05001391 // Avoid pointer casts. Instead generate the correct number of loads
1392 // and rely on drivers to coalesce appropriately.
1393 IRBuilder<> builder(CI);
1394 auto elems_const = builder.getInt32(elems);
1395 V = UndefValue::get(ret_type);
1396 auto adjust = builder.CreateMul(offset, elems_const);
1397 for (auto i = 0; i < elems; ++i) {
1398 auto idx = builder.getInt32(i);
1399 auto add = builder.CreateAdd(adjust, idx);
1400 auto gep = builder.CreateGEP(ptr, add);
1401 auto load = builder.CreateLoad(gep);
1402 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001403 }
SJW2c317da2020-03-23 07:39:13 -05001404 return V;
1405 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001406}
1407
SJW2c317da2020-03-23 07:39:13 -05001408bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1409 const std::string &name,
1410 int vec_size) {
1411 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1412 if (!vec_size) {
1413 // deduce vec_size from last character of name (e.g. vload_half4)
1414 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001415 }
SJW2c317da2020-03-23 07:39:13 -05001416 switch (vec_size) {
1417 case 2:
1418 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1419 case 4:
1420 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1421 case 0:
1422 if (!is_clspv_version) {
1423 return replaceVloadHalf(F);
1424 }
1425 default:
1426 llvm_unreachable("Unsupported vload_half vector size");
1427 break;
1428 }
1429 return false;
David Neto22f144c2017-06-12 14:26:21 -04001430}
1431
SJW2c317da2020-03-23 07:39:13 -05001432bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1433 Module &M = *F.getParent();
1434 return replaceCallsWithValue(F, [&](CallInst *CI) {
1435 // The index argument from vload_half.
1436 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001437
SJW2c317da2020-03-23 07:39:13 -05001438 // The pointer argument from vload_half.
1439 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001440
SJW2c317da2020-03-23 07:39:13 -05001441 auto IntTy = Type::getInt32Ty(M.getContext());
1442 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1443 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1444
1445 // Our intrinsic to unpack a float2 from an int.
1446 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
1447
1448 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1449
1450 Value *V = nullptr;
1451
1452 if (clspv::Option::F16BitStorage()) {
1453 auto ShortTy = Type::getInt16Ty(M.getContext());
1454 auto ShortPointerTy =
1455 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1456
1457 // Cast the half* pointer to short*.
1458 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1459
1460 // Index into the correct address of the casted pointer.
1461 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1462
1463 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001464 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001465
1466 // ZExt the short -> int.
1467 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1468
1469 // Get our float2.
1470 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1471
1472 // Extract out the bottom element which is our float result.
1473 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1474 } else {
1475 // Assume the pointer argument points to storage aligned to 32bits
1476 // or more.
1477 // TODO(dneto): Do more analysis to make sure this is true?
1478 //
1479 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1480 // with:
1481 //
1482 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1483 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1484 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1485 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1486 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1487 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1488 // x float> %converted, %index_is_odd32
1489
1490 auto IntPointerTy =
1491 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1492
1493 // Cast the base pointer to int*.
1494 // In a valid call (according to assumptions), this should get
1495 // optimized away in the simplify GEP pass.
1496 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1497
1498 auto One = ConstantInt::get(IntTy, 1);
1499 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1500 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1501
1502 // Index into the correct address of the casted pointer.
1503 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1504
1505 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001506 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001507
1508 // Get our float2.
1509 auto Call = CallInst::Create(NewF, Load, "", CI);
1510
1511 // Extract out the float result, where the element number is
1512 // determined by whether the original index was even or odd.
1513 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1514 }
1515 return V;
1516 });
1517}
1518
1519bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1520 Module &M = *F.getParent();
1521 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001522 // The index argument from vload_half.
1523 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001524
Kévin Petite8edce32019-04-10 14:23:32 +01001525 // The pointer argument from vload_half.
1526 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001527
Kévin Petite8edce32019-04-10 14:23:32 +01001528 auto IntTy = Type::getInt32Ty(M.getContext());
1529 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001530 auto NewPointerTy =
1531 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001532 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001533
Kévin Petite8edce32019-04-10 14:23:32 +01001534 // Cast the half* pointer to int*.
1535 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001536
Kévin Petite8edce32019-04-10 14:23:32 +01001537 // Index into the correct address of the casted pointer.
1538 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001539
Kévin Petite8edce32019-04-10 14:23:32 +01001540 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001541 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001542
Kévin Petite8edce32019-04-10 14:23:32 +01001543 // Our intrinsic to unpack a float2 from an int.
1544 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001545
Kévin Petite8edce32019-04-10 14:23:32 +01001546 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001547
Kévin Petite8edce32019-04-10 14:23:32 +01001548 // Get our float2.
1549 return CallInst::Create(NewF, Load, "", CI);
1550 });
David Neto22f144c2017-06-12 14:26:21 -04001551}
1552
SJW2c317da2020-03-23 07:39:13 -05001553bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1554 Module &M = *F.getParent();
1555 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001556 // The index argument from vload_half.
1557 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001558
Kévin Petite8edce32019-04-10 14:23:32 +01001559 // The pointer argument from vload_half.
1560 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001561
Kévin Petite8edce32019-04-10 14:23:32 +01001562 auto IntTy = Type::getInt32Ty(M.getContext());
1563 auto Int2Ty = VectorType::get(IntTy, 2);
1564 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001565 auto NewPointerTy =
1566 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001567 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001568
Kévin Petite8edce32019-04-10 14:23:32 +01001569 // Cast the half* pointer to int2*.
1570 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001571
Kévin Petite8edce32019-04-10 14:23:32 +01001572 // Index into the correct address of the casted pointer.
1573 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001574
Kévin Petite8edce32019-04-10 14:23:32 +01001575 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001576 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001577
Kévin Petite8edce32019-04-10 14:23:32 +01001578 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001579 auto X =
1580 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1581 auto Y =
1582 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001583
Kévin Petite8edce32019-04-10 14:23:32 +01001584 // Our intrinsic to unpack a float2 from an int.
1585 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001586
Kévin Petite8edce32019-04-10 14:23:32 +01001587 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001588
Kévin Petite8edce32019-04-10 14:23:32 +01001589 // Get the lower (x & y) components of our final float4.
1590 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001591
Kévin Petite8edce32019-04-10 14:23:32 +01001592 // Get the higher (z & w) components of our final float4.
1593 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001594
Kévin Petite8edce32019-04-10 14:23:32 +01001595 Constant *ShuffleMask[4] = {
1596 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1597 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001598
Kévin Petite8edce32019-04-10 14:23:32 +01001599 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001600 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1601 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001602 });
David Neto22f144c2017-06-12 14:26:21 -04001603}
1604
SJW2c317da2020-03-23 07:39:13 -05001605bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001606
1607 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1608 //
1609 // %u = load i32 %ptr
1610 // %fxy = call <2 x float> Unpack2xHalf(u)
1611 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001612 Module &M = *F.getParent();
1613 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001614 auto Index = CI->getOperand(0);
1615 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001616
Kévin Petite8edce32019-04-10 14:23:32 +01001617 auto IntTy = Type::getInt32Ty(M.getContext());
1618 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1619 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001620
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001621 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001622 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001623
Kévin Petite8edce32019-04-10 14:23:32 +01001624 // Our intrinsic to unpack a float2 from an int.
1625 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07001626
Kévin Petite8edce32019-04-10 14:23:32 +01001627 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001628
Kévin Petite8edce32019-04-10 14:23:32 +01001629 // Get our final float2.
1630 return CallInst::Create(NewF, Load, "", CI);
1631 });
David Neto6ad93232018-06-07 15:42:58 -07001632}
1633
SJW2c317da2020-03-23 07:39:13 -05001634bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001635
1636 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1637 //
1638 // %u2 = load <2 x i32> %ptr
1639 // %u2xy = extractelement %u2, 0
1640 // %u2zw = extractelement %u2, 1
1641 // %fxy = call <2 x float> Unpack2xHalf(uint)
1642 // %fzw = call <2 x float> Unpack2xHalf(uint)
1643 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001644 Module &M = *F.getParent();
1645 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001646 auto Index = CI->getOperand(0);
1647 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001648
Kévin Petite8edce32019-04-10 14:23:32 +01001649 auto IntTy = Type::getInt32Ty(M.getContext());
1650 auto Int2Ty = VectorType::get(IntTy, 2);
1651 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1652 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001653
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001654 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001655 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001656
Kévin Petite8edce32019-04-10 14:23:32 +01001657 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001658 auto X =
1659 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1660 auto Y =
1661 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001662
Kévin Petite8edce32019-04-10 14:23:32 +01001663 // Our intrinsic to unpack a float2 from an int.
1664 auto SPIRVIntrinsic = "spirv.unpack.v2f16";
David Neto6ad93232018-06-07 15:42:58 -07001665
Kévin Petite8edce32019-04-10 14:23:32 +01001666 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001667
Kévin Petite8edce32019-04-10 14:23:32 +01001668 // Get the lower (x & y) components of our final float4.
1669 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001670
Kévin Petite8edce32019-04-10 14:23:32 +01001671 // Get the higher (z & w) components of our final float4.
1672 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001673
Kévin Petite8edce32019-04-10 14:23:32 +01001674 Constant *ShuffleMask[4] = {
1675 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1676 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001677
Kévin Petite8edce32019-04-10 14:23:32 +01001678 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001679 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1680 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001681 });
David Neto6ad93232018-06-07 15:42:58 -07001682}
1683
SJW2c317da2020-03-23 07:39:13 -05001684bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1685 switch (vec_size) {
1686 case 0:
1687 return replaceVstoreHalf(F);
1688 case 2:
1689 return replaceVstoreHalf2(F);
1690 case 4:
1691 return replaceVstoreHalf4(F);
1692 default:
1693 llvm_unreachable("Unsupported vstore_half vector size");
1694 break;
1695 }
1696 return false;
1697}
David Neto22f144c2017-06-12 14:26:21 -04001698
SJW2c317da2020-03-23 07:39:13 -05001699bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1700 Module &M = *F.getParent();
1701 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001702 // The value to store.
1703 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001704
Kévin Petite8edce32019-04-10 14:23:32 +01001705 // The index argument from vstore_half.
1706 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001707
Kévin Petite8edce32019-04-10 14:23:32 +01001708 // The pointer argument from vstore_half.
1709 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001710
Kévin Petite8edce32019-04-10 14:23:32 +01001711 auto IntTy = Type::getInt32Ty(M.getContext());
1712 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
1713 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1714 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001715
Kévin Petite8edce32019-04-10 14:23:32 +01001716 // Our intrinsic to pack a float2 to an int.
1717 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001718
Kévin Petite8edce32019-04-10 14:23:32 +01001719 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001720
Kévin Petite8edce32019-04-10 14:23:32 +01001721 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001722 auto TempVec = InsertElementInst::Create(
1723 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001724
Kévin Petite8edce32019-04-10 14:23:32 +01001725 // Pack the float2 -> half2 (in an int).
1726 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001727
SJW2c317da2020-03-23 07:39:13 -05001728 Value *V = nullptr;
Kévin Petite8edce32019-04-10 14:23:32 +01001729 if (clspv::Option::F16BitStorage()) {
1730 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001731 auto ShortPointerTy =
1732 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001733
Kévin Petite8edce32019-04-10 14:23:32 +01001734 // Truncate our i32 to an i16.
1735 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001736
Kévin Petite8edce32019-04-10 14:23:32 +01001737 // Cast the half* pointer to short*.
1738 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001739
Kévin Petite8edce32019-04-10 14:23:32 +01001740 // Index into the correct address of the casted pointer.
1741 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001742
Kévin Petite8edce32019-04-10 14:23:32 +01001743 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05001744 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001745 } else {
1746 // We can only write to 32-bit aligned words.
1747 //
1748 // Assuming base is aligned to 32-bits, replace the equivalent of
1749 // vstore_half(value, index, base)
1750 // with:
1751 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
1752 // uint32_t write_to_upper_half = index & 1u;
1753 // uint32_t shift = write_to_upper_half << 4;
1754 //
1755 // // Pack the float value as a half number in bottom 16 bits
1756 // // of an i32.
1757 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
1758 //
1759 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
1760 // ^ ((packed & 0xffff) << shift)
1761 // // We only need relaxed consistency, but OpenCL 1.2 only has
1762 // // sequentially consistent atomics.
1763 // // TODO(dneto): Use relaxed consistency.
1764 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001765 auto IntPointerTy =
1766 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001767
Kévin Petite8edce32019-04-10 14:23:32 +01001768 auto Four = ConstantInt::get(IntTy, 4);
1769 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04001770
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001771 auto IndexIsOdd =
1772 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001773 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001774 auto IndexIntoI32 =
1775 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
1776 auto BaseI32Ptr =
1777 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
1778 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
1779 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001780 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001781 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001782 auto MaskBitsToWrite =
1783 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
1784 auto MaskedCurrent = BinaryOperator::CreateAnd(
1785 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04001786
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001787 auto XLowerBits =
1788 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
1789 auto NewBitsToWrite =
1790 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
1791 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
1792 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04001793
Kévin Petite8edce32019-04-10 14:23:32 +01001794 // Generate the call to atomi_xor.
1795 SmallVector<Type *, 5> ParamTypes;
1796 // The pointer type.
1797 ParamTypes.push_back(IntPointerTy);
1798 // The Types for memory scope, semantics, and value.
1799 ParamTypes.push_back(IntTy);
1800 ParamTypes.push_back(IntTy);
1801 ParamTypes.push_back(IntTy);
1802 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
1803 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04001804
Kévin Petite8edce32019-04-10 14:23:32 +01001805 const auto ConstantScopeDevice =
1806 ConstantInt::get(IntTy, spv::ScopeDevice);
1807 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
1808 // (SPIR-V Workgroup).
1809 const auto AddrSpaceSemanticsBits =
1810 IntPointerTy->getPointerAddressSpace() == 1
1811 ? spv::MemorySemanticsUniformMemoryMask
1812 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04001813
Kévin Petite8edce32019-04-10 14:23:32 +01001814 // We're using relaxed consistency here.
1815 const auto ConstantMemorySemantics =
1816 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
1817 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04001818
Kévin Petite8edce32019-04-10 14:23:32 +01001819 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
1820 ConstantMemorySemantics, ValueToXor};
1821 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05001822
1823 // Return a Nop so the old Call is removed
1824 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
1825 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001826 }
David Neto22f144c2017-06-12 14:26:21 -04001827
SJW2c317da2020-03-23 07:39:13 -05001828 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01001829 });
David Neto22f144c2017-06-12 14:26:21 -04001830}
1831
SJW2c317da2020-03-23 07:39:13 -05001832bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
1833 Module &M = *F.getParent();
1834 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001835 // The value to store.
1836 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001837
Kévin Petite8edce32019-04-10 14:23:32 +01001838 // The index argument from vstore_half.
1839 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001840
Kévin Petite8edce32019-04-10 14:23:32 +01001841 // The pointer argument from vstore_half.
1842 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001843
Kévin Petite8edce32019-04-10 14:23:32 +01001844 auto IntTy = Type::getInt32Ty(M.getContext());
1845 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001846 auto NewPointerTy =
1847 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001848 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001849
Kévin Petite8edce32019-04-10 14:23:32 +01001850 // Our intrinsic to pack a float2 to an int.
1851 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001852
Kévin Petite8edce32019-04-10 14:23:32 +01001853 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001854
Kévin Petite8edce32019-04-10 14:23:32 +01001855 // Turn the packed x & y into the final packing.
1856 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001857
Kévin Petite8edce32019-04-10 14:23:32 +01001858 // Cast the half* pointer to int*.
1859 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001860
Kévin Petite8edce32019-04-10 14:23:32 +01001861 // Index into the correct address of the casted pointer.
1862 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001863
Kévin Petite8edce32019-04-10 14:23:32 +01001864 // Store to the int* we casted to.
1865 return new StoreInst(X, Index, CI);
1866 });
David Neto22f144c2017-06-12 14:26:21 -04001867}
1868
SJW2c317da2020-03-23 07:39:13 -05001869bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
1870 Module &M = *F.getParent();
1871 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001872 // The value to store.
1873 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001874
Kévin Petite8edce32019-04-10 14:23:32 +01001875 // The index argument from vstore_half.
1876 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001877
Kévin Petite8edce32019-04-10 14:23:32 +01001878 // The pointer argument from vstore_half.
1879 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001880
Kévin Petite8edce32019-04-10 14:23:32 +01001881 auto IntTy = Type::getInt32Ty(M.getContext());
1882 auto Int2Ty = VectorType::get(IntTy, 2);
1883 auto Float2Ty = VectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001884 auto NewPointerTy =
1885 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001886 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001887
Kévin Petite8edce32019-04-10 14:23:32 +01001888 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
1889 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04001890
Kévin Petite8edce32019-04-10 14:23:32 +01001891 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001892 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1893 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001894
Kévin Petite8edce32019-04-10 14:23:32 +01001895 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
1896 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001897
Kévin Petite8edce32019-04-10 14:23:32 +01001898 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001899 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
1900 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001901
Kévin Petite8edce32019-04-10 14:23:32 +01001902 // Our intrinsic to pack a float2 to an int.
1903 auto SPIRVIntrinsic = "spirv.pack.v2f16";
David Neto22f144c2017-06-12 14:26:21 -04001904
Kévin Petite8edce32019-04-10 14:23:32 +01001905 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001906
Kévin Petite8edce32019-04-10 14:23:32 +01001907 // Turn the packed x & y into the final component of our int2.
1908 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001909
Kévin Petite8edce32019-04-10 14:23:32 +01001910 // Turn the packed z & w into the final component of our int2.
1911 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001912
Kévin Petite8edce32019-04-10 14:23:32 +01001913 auto Combine = InsertElementInst::Create(
1914 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001915 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
1916 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001917
Kévin Petite8edce32019-04-10 14:23:32 +01001918 // Cast the half* pointer to int2*.
1919 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001920
Kévin Petite8edce32019-04-10 14:23:32 +01001921 // Index into the correct address of the casted pointer.
1922 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001923
Kévin Petite8edce32019-04-10 14:23:32 +01001924 // Store to the int2* we casted to.
1925 return new StoreInst(Combine, Index, CI);
1926 });
David Neto22f144c2017-06-12 14:26:21 -04001927}
1928
SJW2c317da2020-03-23 07:39:13 -05001929bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
1930 // convert half to float
1931 Module &M = *F.getParent();
1932 return replaceCallsWithValue(F, [&](CallInst *CI) {
1933 SmallVector<Type *, 3> types;
1934 SmallVector<Value *, 3> args;
1935 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
1936 types.push_back(CI->getArgOperand(i)->getType());
1937 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05001938 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05001939
SJW2c317da2020-03-23 07:39:13 -05001940 auto NewFType = FunctionType::get(
1941 VectorType::get(Type::getFloatTy(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -04001942 cast<VectorType>(CI->getType())->getNumElements()),
SJW2c317da2020-03-23 07:39:13 -05001943 types, false);
1944
1945 std::string NewFName = "_Z11read_imagef";
1946 NewFName += F.getName().str().substr(15);
1947
1948 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1949
1950 auto NewCI = CallInst::Create(NewF, args, "", CI);
1951
1952 // Convert to the half type.
1953 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
1954 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05001955}
1956
SJW2c317da2020-03-23 07:39:13 -05001957bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
1958 // convert half to float
1959 Module &M = *F.getParent();
1960 return replaceCallsWithValue(F, [&](CallInst *CI) {
1961 SmallVector<Type *, 3> types(3);
1962 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001963
SJW2c317da2020-03-23 07:39:13 -05001964 // Image
1965 types[0] = CI->getArgOperand(0)->getType();
1966 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001967
SJW2c317da2020-03-23 07:39:13 -05001968 // Coord
1969 types[1] = CI->getArgOperand(1)->getType();
1970 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001971
SJW2c317da2020-03-23 07:39:13 -05001972 // Data
1973 types[2] = VectorType::get(
1974 Type::getFloatTy(M.getContext()),
James Pricecf53df42020-04-20 14:41:24 -04001975 cast<VectorType>(CI->getArgOperand(2)->getType())->getNumElements());
alan-bakerf7e17cb2020-01-02 07:29:59 -05001976
SJW2c317da2020-03-23 07:39:13 -05001977 auto NewFType =
1978 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001979
SJW2c317da2020-03-23 07:39:13 -05001980 int slen = F.getName().size();
1981 std::string NewFName = "_Z12write_imagef";
1982 NewFName += F.getName().str().substr(16, slen - 16 - 2) + "f";
alan-bakerf7e17cb2020-01-02 07:29:59 -05001983
SJW2c317da2020-03-23 07:39:13 -05001984 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05001985
SJW2c317da2020-03-23 07:39:13 -05001986 // Convert data to the float type.
1987 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
1988 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05001989
SJW2c317da2020-03-23 07:39:13 -05001990 return CallInst::Create(NewF, args, "", CI);
1991 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05001992}
1993
SJW2c317da2020-03-23 07:39:13 -05001994bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
1995 Function &F) {
1996 // convert read_image with int coords to float coords
1997 Module &M = *F.getParent();
1998 return replaceCallsWithValue(F, [&](CallInst *CI) {
1999 // The image.
2000 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002001
SJW2c317da2020-03-23 07:39:13 -05002002 // The sampler.
2003 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002004
SJW2c317da2020-03-23 07:39:13 -05002005 // The coordinate (integer type that we can't handle).
2006 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002007
SJW2c317da2020-03-23 07:39:13 -05002008 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2009 uint32_t components =
2010 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2011 Type *float_ty = nullptr;
2012 if (components == 1) {
2013 float_ty = Type::getFloatTy(M.getContext());
2014 } else {
James Pricecf53df42020-04-20 14:41:24 -04002015 float_ty =
2016 VectorType::get(Type::getFloatTy(M.getContext()),
2017 cast<VectorType>(Arg2->getType())->getNumElements());
David Neto22f144c2017-06-12 14:26:21 -04002018 }
David Neto22f144c2017-06-12 14:26:21 -04002019
SJW2c317da2020-03-23 07:39:13 -05002020 auto NewFType = FunctionType::get(
2021 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2022
2023 std::string NewFName = F.getName().str();
2024 NewFName[NewFName.length() - 1] = 'f';
2025
2026 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2027
2028 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2029
2030 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2031 });
David Neto22f144c2017-06-12 14:26:21 -04002032}
2033
SJW2c317da2020-03-23 07:39:13 -05002034bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2035 return replaceCallsWithValue(F, [&](CallInst *CI) {
2036 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002037
SJW2c317da2020-03-23 07:39:13 -05002038 // We need to map the OpenCL constants to the SPIR-V equivalents.
2039 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2040 const auto ConstantMemorySemantics = ConstantInt::get(
2041 IntTy, spv::MemorySemanticsUniformMemoryMask |
2042 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002043
SJW2c317da2020-03-23 07:39:13 -05002044 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002045
SJW2c317da2020-03-23 07:39:13 -05002046 // The pointer.
2047 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002048
SJW2c317da2020-03-23 07:39:13 -05002049 // The memory scope.
2050 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002051
SJW2c317da2020-03-23 07:39:13 -05002052 // The memory semantics.
2053 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002054
SJW2c317da2020-03-23 07:39:13 -05002055 if (2 < CI->getNumArgOperands()) {
2056 // The unequal memory semantics.
2057 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002058
SJW2c317da2020-03-23 07:39:13 -05002059 // The value.
2060 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002061
SJW2c317da2020-03-23 07:39:13 -05002062 // The comparator.
2063 Params.push_back(CI->getArgOperand(1));
2064 } else if (1 < CI->getNumArgOperands()) {
2065 // The value.
2066 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002067 }
David Neto22f144c2017-06-12 14:26:21 -04002068
SJW2c317da2020-03-23 07:39:13 -05002069 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2070 });
David Neto22f144c2017-06-12 14:26:21 -04002071}
2072
SJW2c317da2020-03-23 07:39:13 -05002073bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2074 llvm::AtomicRMWInst::BinOp Op) {
2075 return replaceCallsWithValue(F, [&](CallInst *CI) {
2076 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
2077 AtomicOrdering::SequentiallyConsistent,
2078 SyncScope::System, CI);
2079 });
2080}
David Neto22f144c2017-06-12 14:26:21 -04002081
SJW2c317da2020-03-23 07:39:13 -05002082bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2083 Module &M = *F.getParent();
2084 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002085 auto IntTy = Type::getInt32Ty(M.getContext());
2086 auto FloatTy = Type::getFloatTy(M.getContext());
2087
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002088 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2089 ConstantInt::get(IntTy, 1),
2090 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002091
2092 Constant *UpShuffleMask[4] = {
2093 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2094 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2095
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002096 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2097 UndefValue::get(FloatTy),
2098 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002099
Kévin Petite8edce32019-04-10 14:23:32 +01002100 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002101 auto Arg0 =
2102 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2103 ConstantVector::get(DownShuffleMask), "", CI);
2104 auto Arg1 =
2105 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2106 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002107 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002108
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002109 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
David Neto22f144c2017-06-12 14:26:21 -04002110
Kévin Petite8edce32019-04-10 14:23:32 +01002111 auto Cross3Func = M.getOrInsertFunction("_Z5crossDv3_fS_", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002112
Kévin Petite8edce32019-04-10 14:23:32 +01002113 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002114
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002115 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2116 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002117 });
David Neto22f144c2017-06-12 14:26:21 -04002118}
David Neto62653202017-10-16 19:05:18 -04002119
SJW2c317da2020-03-23 07:39:13 -05002120bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002121 // OpenCL's float result = fract(float x, float* ptr)
2122 //
2123 // In the LLVM domain:
2124 //
2125 // %floor_result = call spir_func float @floor(float %x)
2126 // store float %floor_result, float * %ptr
2127 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2128 // %result = call spir_func float
2129 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2130 //
2131 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2132 // and clspv.fract occur in the SPIR-V generator pass:
2133 //
2134 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2135 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2136 // ...
2137 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2138 // OpStore %ptr %floor_result
2139 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2140 // %fract_result = OpExtInst %float
2141 // %glsl_ext Fmin %fract_intermediate %just_under_1
2142
David Neto62653202017-10-16 19:05:18 -04002143 using std::string;
2144
2145 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2146 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002147
SJW2c317da2020-03-23 07:39:13 -05002148 Module &M = *F.getParent();
2149 return replaceCallsWithValue(F, [&](CallInst *CI) {
2150 auto &Context = M.getContext();
David Neto62653202017-10-16 19:05:18 -04002151
SJW2c317da2020-03-23 07:39:13 -05002152 std::string floor_name = "_Z5floor";
2153 std::string fmin_name = "_Z4fmin";
2154 std::string clspv_fract_name = "clspv.fract.";
2155 if (vec_size) {
2156 floor_name += "Dv" + std::to_string(vec_size) + "_f";
2157 fmin_name += "Dv" + std::to_string(vec_size) + "_f";
2158 clspv_fract_name += "v" + std::to_string(vec_size) + "f";
2159 } else {
2160 floor_name += "ff";
2161 fmin_name += "ff";
2162 clspv_fract_name += "f";
David Neto62653202017-10-16 19:05:18 -04002163 }
David Neto62653202017-10-16 19:05:18 -04002164
SJW2c317da2020-03-23 07:39:13 -05002165 // This is either float or a float vector. All the float-like
2166 // types are this type.
2167 auto result_ty = F.getReturnType();
2168
2169 Function *fmin_fn = M.getFunction(fmin_name);
2170 if (!fmin_fn) {
2171 // Make the fmin function.
2172 FunctionType *fn_ty =
2173 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2174 fmin_fn =
2175 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2176 fmin_fn->addFnAttr(Attribute::ReadNone);
2177 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2178 }
2179
2180 Function *floor_fn = M.getFunction(floor_name);
2181 if (!floor_fn) {
2182 // Make the floor function.
2183 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2184 floor_fn =
2185 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2186 floor_fn->addFnAttr(Attribute::ReadNone);
2187 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2188 }
2189
2190 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2191 if (!clspv_fract_fn) {
2192 // Make the clspv_fract function.
2193 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2194 clspv_fract_fn = cast<Function>(
2195 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2196 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2197 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2198 }
2199
2200 // Number of significant significand bits, whether represented or not.
2201 unsigned num_significand_bits;
2202 switch (result_ty->getScalarType()->getTypeID()) {
2203 case Type::HalfTyID:
2204 num_significand_bits = 11;
2205 break;
2206 case Type::FloatTyID:
2207 num_significand_bits = 24;
2208 break;
2209 case Type::DoubleTyID:
2210 num_significand_bits = 53;
2211 break;
2212 default:
2213 llvm_unreachable("Unhandled float type when processing fract builtin");
2214 break;
2215 }
2216 // Beware that the disassembler displays this value as
2217 // OpConstant %float 1
2218 // which is not quite right.
2219 const double kJustUnderOneScalar =
2220 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2221
2222 Constant *just_under_one =
2223 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2224 if (result_ty->isVectorTy()) {
2225 just_under_one = ConstantVector::getSplat(
James Pricecf53df42020-04-20 14:41:24 -04002226 {cast<VectorType>(result_ty)->getNumElements(), false},
2227 just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002228 }
2229
2230 IRBuilder<> Builder(CI);
2231
2232 auto arg = CI->getArgOperand(0);
2233 auto ptr = CI->getArgOperand(1);
2234
2235 // Compute floor result and store it.
2236 auto floor = Builder.CreateCall(floor_fn, {arg});
2237 Builder.CreateStore(floor, ptr);
2238
2239 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2240 auto fract_result =
2241 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2242
2243 return fract_result;
2244 });
David Neto62653202017-10-16 19:05:18 -04002245}