blob: eb600eb0d575e8c030434ce746031409a36af669 [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"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040033#include "clspv/Option.h"
David Neto482550a2018-03-24 05:21:07 -070034
SJW2c317da2020-03-23 07:39:13 -050035#include "Builtins.h"
alan-baker931d18a2019-12-12 08:21:32 -050036#include "Constants.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040037#include "Passes.h"
38#include "SPIRVOp.h"
alan-bakerf906d2b2019-12-10 11:26:23 -050039#include "Types.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040040
SJW2c317da2020-03-23 07:39:13 -050041using namespace clspv;
David Neto22f144c2017-06-12 14:26:21 -040042using namespace llvm;
43
44#define DEBUG_TYPE "ReplaceOpenCLBuiltin"
45
46namespace {
Kévin Petit8a560882019-03-21 15:24:34 +000047
David Neto22f144c2017-06-12 14:26:21 -040048uint32_t clz(uint32_t v) {
49 uint32_t r;
50 uint32_t shift;
51
52 r = (v > 0xFFFF) << 4;
53 v >>= r;
54 shift = (v > 0xFF) << 3;
55 v >>= shift;
56 r |= shift;
57 shift = (v > 0xF) << 2;
58 v >>= shift;
59 r |= shift;
60 shift = (v > 0x3) << 1;
61 v >>= shift;
62 r |= shift;
63 r |= (v >> 1);
64
65 return r;
66}
67
Kévin Petitfdfa92e2019-09-25 14:20:58 +010068Type *getIntOrIntVectorTyForCast(LLVMContext &C, Type *Ty) {
69 Type *IntTy = Type::getIntNTy(C, Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -040070 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-baker5a8c3be2020-09-09 13:44:26 -040071 IntTy = FixedVectorType::get(IntTy,
72 vec_ty->getElementCount().getKnownMinValue());
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);
SJW61531372020-06-09 07:31:08 -0500122 bool replaceExp10(Function &F, const std::string &basename);
123 bool replaceLog10(Function &F, const std::string &basename);
gnl21636e7992020-09-09 16:08:16 +0100124 bool replaceLog1p(Function &F);
alan-baker12d2c182020-07-20 08:22:42 -0400125 bool replaceBarrier(Function &F, bool subgroup = false);
SJW2c317da2020-03-23 07:39:13 -0500126 bool replaceMemFence(Function &F, uint32_t semantics);
Kévin Petit1cb45112020-04-27 18:55:48 +0100127 bool replacePrefetch(Function &F);
SJW2c317da2020-03-23 07:39:13 -0500128 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);
SJW61531372020-06-09 07:31:08 -0500138 bool replaceStep(Function &F, bool is_smooth);
SJW2c317da2020-03-23 07:39:13 -0500139 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);
alan-bakera52b7312020-10-26 08:58:51 -0400160 bool replaceAddSat(Function &F, bool is_signed);
David Neto22f144c2017-06-12 14:26:21 -0400161};
SJW2c317da2020-03-23 07:39:13 -0500162
Kévin Petit91bc72e2019-04-08 15:17:46 +0100163} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400164
165char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400166INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
167 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400168
169namespace clspv {
170ModulePass *createReplaceOpenCLBuiltinPass() {
171 return new ReplaceOpenCLBuiltinPass();
172}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400173} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400174
175bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500176 std::list<Function *> func_list;
177 for (auto &F : M.getFunctionList()) {
178 // process only function declarations
179 if (F.isDeclaration() && runOnFunction(F)) {
180 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000181 }
182 }
SJW2c317da2020-03-23 07:39:13 -0500183 if (func_list.size() != 0) {
184 // recursively convert functions, but first remove dead
185 for (auto *F : func_list) {
186 if (F->use_empty()) {
187 F->eraseFromParent();
188 }
189 }
190 runOnModule(M);
191 return true;
192 }
193 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000194}
195
SJW2c317da2020-03-23 07:39:13 -0500196bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
197 auto &FI = Builtins::Lookup(&F);
198 switch (FI.getType()) {
199 case Builtins::kAbs:
200 if (!FI.getParameter(0).is_signed) {
201 return replaceAbs(F);
202 }
203 break;
204 case Builtins::kAbsDiff:
205 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
alan-bakera52b7312020-10-26 08:58:51 -0400206
207 case Builtins::kAddSat:
208 return replaceAddSat(F, FI.getParameter(0).is_signed);
209
SJW2c317da2020-03-23 07:39:13 -0500210 case Builtins::kCopysign:
211 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100212
SJW2c317da2020-03-23 07:39:13 -0500213 case Builtins::kHalfRecip:
214 case Builtins::kNativeRecip:
215 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100216
SJW2c317da2020-03-23 07:39:13 -0500217 case Builtins::kHalfDivide:
218 case Builtins::kNativeDivide:
219 return replaceDivide(F);
220
221 case Builtins::kDot:
222 return replaceDot(F);
223
224 case Builtins::kExp10:
225 case Builtins::kHalfExp10:
SJW61531372020-06-09 07:31:08 -0500226 case Builtins::kNativeExp10:
227 return replaceExp10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500228
229 case Builtins::kLog10:
230 case Builtins::kHalfLog10:
SJW61531372020-06-09 07:31:08 -0500231 case Builtins::kNativeLog10:
232 return replaceLog10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500233
gnl21636e7992020-09-09 16:08:16 +0100234 case Builtins::kLog1p:
235 return replaceLog1p(F);
236
SJW2c317da2020-03-23 07:39:13 -0500237 case Builtins::kFmod:
238 return replaceFmod(F);
239
240 case Builtins::kBarrier:
241 case Builtins::kWorkGroupBarrier:
242 return replaceBarrier(F);
243
alan-baker12d2c182020-07-20 08:22:42 -0400244 case Builtins::kSubGroupBarrier:
245 return replaceBarrier(F, true);
246
SJW2c317da2020-03-23 07:39:13 -0500247 case Builtins::kMemFence:
alan-baker12d2c182020-07-20 08:22:42 -0400248 return replaceMemFence(F, spv::MemorySemanticsAcquireReleaseMask);
SJW2c317da2020-03-23 07:39:13 -0500249 case Builtins::kReadMemFence:
250 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
251 case Builtins::kWriteMemFence:
252 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
253
254 // Relational
255 case Builtins::kIsequal:
256 return replaceRelational(F, CmpInst::FCMP_OEQ,
257 FI.getParameter(0).vector_size ? -1 : 1);
258 case Builtins::kIsgreater:
259 return replaceRelational(F, CmpInst::FCMP_OGT,
260 FI.getParameter(0).vector_size ? -1 : 1);
261 case Builtins::kIsgreaterequal:
262 return replaceRelational(F, CmpInst::FCMP_OGE,
263 FI.getParameter(0).vector_size ? -1 : 1);
264 case Builtins::kIsless:
265 return replaceRelational(F, CmpInst::FCMP_OLT,
266 FI.getParameter(0).vector_size ? -1 : 1);
267 case Builtins::kIslessequal:
268 return replaceRelational(F, CmpInst::FCMP_OLE,
269 FI.getParameter(0).vector_size ? -1 : 1);
270 case Builtins::kIsnotequal:
271 return replaceRelational(F, CmpInst::FCMP_ONE,
272 FI.getParameter(0).vector_size ? -1 : 1);
273
274 case Builtins::kIsinf: {
275 bool is_vec = FI.getParameter(0).vector_size != 0;
276 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
277 }
278 case Builtins::kIsnan: {
279 bool is_vec = FI.getParameter(0).vector_size != 0;
280 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
281 }
282
283 case Builtins::kIsfinite:
284 return replaceIsFinite(F);
285
286 case Builtins::kAll: {
287 bool is_vec = FI.getParameter(0).vector_size != 0;
288 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
289 }
290 case Builtins::kAny: {
291 bool is_vec = FI.getParameter(0).vector_size != 0;
292 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
293 }
294
295 case Builtins::kUpsample:
296 return replaceUpsample(F);
297
298 case Builtins::kRotate:
299 return replaceRotate(F);
300
301 case Builtins::kConvert:
302 return replaceConvert(F, FI.getParameter(0).is_signed,
303 FI.getReturnType().is_signed);
304
305 case Builtins::kAtomicInc:
306 return replaceAtomics(F, spv::OpAtomicIIncrement);
307 case Builtins::kAtomicDec:
308 return replaceAtomics(F, spv::OpAtomicIDecrement);
309 case Builtins::kAtomicCmpxchg:
310 return replaceAtomics(F, spv::OpAtomicCompareExchange);
311 case Builtins::kAtomicAdd:
312 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
313 case Builtins::kAtomicSub:
314 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
315 case Builtins::kAtomicXchg:
316 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
317 case Builtins::kAtomicMin:
318 return replaceAtomics(F, FI.getParameter(0).is_signed
319 ? llvm::AtomicRMWInst::Min
320 : llvm::AtomicRMWInst::UMin);
321 case Builtins::kAtomicMax:
322 return replaceAtomics(F, FI.getParameter(0).is_signed
323 ? llvm::AtomicRMWInst::Max
324 : llvm::AtomicRMWInst::UMax);
325 case Builtins::kAtomicAnd:
326 return replaceAtomics(F, llvm::AtomicRMWInst::And);
327 case Builtins::kAtomicOr:
328 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
329 case Builtins::kAtomicXor:
330 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
331
332 case Builtins::kCross:
333 if (FI.getParameter(0).vector_size == 4) {
334 return replaceCross(F);
335 }
336 break;
337
338 case Builtins::kFract:
339 if (FI.getParameterCount()) {
340 return replaceFract(F, FI.getParameter(0).vector_size);
341 }
342 break;
343
344 case Builtins::kMadHi:
345 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
346 case Builtins::kMulHi:
347 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
348
349 case Builtins::kMad:
350 case Builtins::kMad24:
351 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
352 true);
353 case Builtins::kMul24:
354 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
355 false);
356
357 case Builtins::kSelect:
358 return replaceSelect(F);
359
360 case Builtins::kBitselect:
361 return replaceBitSelect(F);
362
363 case Builtins::kVload:
364 return replaceVload(F);
365
366 case Builtins::kVloadaHalf:
367 case Builtins::kVloadHalf:
368 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
369
370 case Builtins::kVstore:
371 return replaceVstore(F);
372
373 case Builtins::kVstoreHalf:
374 case Builtins::kVstoreaHalf:
375 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
376
377 case Builtins::kSmoothstep: {
378 int vec_size = FI.getLastParameter().vector_size;
379 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500380 return replaceStep(F, true);
SJW2c317da2020-03-23 07:39:13 -0500381 }
382 break;
383 }
384 case Builtins::kStep: {
385 int vec_size = FI.getLastParameter().vector_size;
386 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500387 return replaceStep(F, false);
SJW2c317da2020-03-23 07:39:13 -0500388 }
389 break;
390 }
391
392 case Builtins::kSignbit:
393 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
394
395 case Builtins::kReadImageh:
396 return replaceHalfReadImage(F);
397 case Builtins::kReadImagef:
398 case Builtins::kReadImagei:
399 case Builtins::kReadImageui: {
400 if (FI.getParameter(1).isSampler() &&
401 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
402 return replaceSampledReadImageWithIntCoords(F);
403 }
404 break;
405 }
406
407 case Builtins::kWriteImageh:
408 return replaceHalfWriteImage(F);
409
Kévin Petit1cb45112020-04-27 18:55:48 +0100410 case Builtins::kPrefetch:
411 return replacePrefetch(F);
412
SJW2c317da2020-03-23 07:39:13 -0500413 default:
414 break;
415 }
416
417 return false;
418}
419
420bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
421 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400422 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100423}
424
SJW2c317da2020-03-23 07:39:13 -0500425bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
426 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100427 auto XValue = CI->getOperand(0);
428 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100429
Kévin Petite8edce32019-04-10 14:23:32 +0100430 IRBuilder<> Builder(CI);
431 auto XmY = Builder.CreateSub(XValue, YValue);
432 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100433
SJW2c317da2020-03-23 07:39:13 -0500434 Value *Cmp = nullptr;
435 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100436 Cmp = Builder.CreateICmpSGT(YValue, XValue);
437 } else {
438 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100439 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100440
Kévin Petite8edce32019-04-10 14:23:32 +0100441 return Builder.CreateSelect(Cmp, YmX, XmY);
442 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100443}
444
SJW2c317da2020-03-23 07:39:13 -0500445bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
446 return replaceCallsWithValue(F, [&F](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100447 auto XValue = CI->getOperand(0);
448 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100449
Kévin Petite8edce32019-04-10 14:23:32 +0100450 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100451
SJW2c317da2020-03-23 07:39:13 -0500452 Type *IntTy = Type::getIntNTy(F.getContext(), Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -0400453 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400454 IntTy = FixedVectorType::get(
455 IntTy, vec_ty->getElementCount().getKnownMinValue());
Kévin Petit8c1be282019-04-02 19:34:25 +0100456 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100457
Kévin Petite8edce32019-04-10 14:23:32 +0100458 // Return X with the sign of Y
459
460 // Sign bit masks
461 auto SignBit = IntTy->getScalarSizeInBits() - 1;
462 auto SignBitMask = 1 << SignBit;
463 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
464 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
465
466 IRBuilder<> Builder(CI);
467
468 // Extract sign of Y
469 auto YInt = Builder.CreateBitCast(YValue, IntTy);
470 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
471
472 // Clear sign bit in X
473 auto XInt = Builder.CreateBitCast(XValue, IntTy);
474 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
475
476 // Insert sign bit of Y into X
477 auto NewXInt = Builder.CreateOr(XInt, YSign);
478
479 // And cast back to floating-point
480 return Builder.CreateBitCast(NewXInt, Ty);
481 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100482}
483
SJW2c317da2020-03-23 07:39:13 -0500484bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
485 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100486 // Recip has one arg.
487 auto Arg = CI->getOperand(0);
488 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
489 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
490 });
David Neto22f144c2017-06-12 14:26:21 -0400491}
492
SJW2c317da2020-03-23 07:39:13 -0500493bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
494 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100495 auto Op0 = CI->getOperand(0);
496 auto Op1 = CI->getOperand(1);
497 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
498 });
David Neto22f144c2017-06-12 14:26:21 -0400499}
500
SJW2c317da2020-03-23 07:39:13 -0500501bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
502 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100503 auto Op0 = CI->getOperand(0);
504 auto Op1 = CI->getOperand(1);
505
SJW2c317da2020-03-23 07:39:13 -0500506 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100507 if (Op0->getType()->isVectorTy()) {
508 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
509 CI->getType(), {Op0, Op1});
510 } else {
511 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
512 }
513
514 return V;
515 });
516}
517
SJW2c317da2020-03-23 07:39:13 -0500518bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
SJW61531372020-06-09 07:31:08 -0500519 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500520 // convert to natural
521 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500522 std::string NewFName = basename.substr(0, slen);
523 NewFName =
524 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400525
SJW2c317da2020-03-23 07:39:13 -0500526 Module &M = *F.getParent();
527 return replaceCallsWithValue(F, [&](CallInst *CI) {
528 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
529
530 auto Arg = CI->getOperand(0);
531
532 // Constant of the natural log of 10 (ln(10)).
533 const double Ln10 =
534 2.302585092994045684017991454684364207601101488628772976033;
535
536 auto Mul = BinaryOperator::Create(
537 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
538
539 return CallInst::Create(NewF, Mul, "", CI);
540 });
David Neto22f144c2017-06-12 14:26:21 -0400541}
542
SJW2c317da2020-03-23 07:39:13 -0500543bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100544 // OpenCL fmod(x,y) is x - y * trunc(x/y)
545 // The sign for a non-zero result is taken from x.
546 // (Try an example.)
547 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500548 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100549 auto Op0 = CI->getOperand(0);
550 auto Op1 = CI->getOperand(1);
551 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
552 });
553}
554
SJW2c317da2020-03-23 07:39:13 -0500555bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
SJW61531372020-06-09 07:31:08 -0500556 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500557 // convert to natural
558 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500559 std::string NewFName = basename.substr(0, slen);
560 NewFName =
561 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400562
SJW2c317da2020-03-23 07:39:13 -0500563 Module &M = *F.getParent();
564 return replaceCallsWithValue(F, [&](CallInst *CI) {
565 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
566
567 auto Arg = CI->getOperand(0);
568
569 // Constant of the reciprocal of the natural log of 10 (ln(10)).
570 const double Ln10 =
571 0.434294481903251827651128918916605082294397005803666566114;
572
573 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
574
575 return BinaryOperator::Create(Instruction::FMul,
576 ConstantFP::get(Arg->getType(), Ln10), NewCI,
577 "", CI);
578 });
David Neto22f144c2017-06-12 14:26:21 -0400579}
580
gnl21636e7992020-09-09 16:08:16 +0100581bool ReplaceOpenCLBuiltinPass::replaceLog1p(Function &F) {
582 // convert to natural
583 std::string NewFName =
584 Builtins::GetMangledFunctionName("log", F.getFunctionType());
585
586 Module &M = *F.getParent();
587 return replaceCallsWithValue(F, [&](CallInst *CI) {
588 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
589
590 auto Arg = CI->getOperand(0);
591
592 auto ArgP1 = BinaryOperator::Create(
593 Instruction::FAdd, ConstantFP::get(Arg->getType(), 1.0), Arg, "", CI);
594
595 return CallInst::Create(NewF, ArgP1, "", CI);
596 });
597}
598
alan-baker12d2c182020-07-20 08:22:42 -0400599bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F, bool subgroup) {
David Neto22f144c2017-06-12 14:26:21 -0400600
alan-bakerf6bc8252020-09-23 14:58:55 -0400601 enum {
602 CLK_LOCAL_MEM_FENCE = 0x01,
603 CLK_GLOBAL_MEM_FENCE = 0x02,
604 CLK_IMAGE_MEM_FENCE = 0x04
605 };
David Neto22f144c2017-06-12 14:26:21 -0400606
alan-baker12d2c182020-07-20 08:22:42 -0400607 return replaceCallsWithValue(F, [subgroup](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100608 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400609
Kévin Petitc4643922019-06-17 19:32:05 +0100610 // We need to map the OpenCL constants to the SPIR-V equivalents.
611 const auto LocalMemFence =
612 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
613 const auto GlobalMemFence =
614 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400615 const auto ImageMemFence =
616 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
alan-baker12d2c182020-07-20 08:22:42 -0400617 const auto ConstantAcquireRelease = ConstantInt::get(
618 Arg->getType(), spv::MemorySemanticsAcquireReleaseMask);
Kévin Petitc4643922019-06-17 19:32:05 +0100619 const auto ConstantScopeDevice =
620 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
621 const auto ConstantScopeWorkgroup =
622 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
alan-baker12d2c182020-07-20 08:22:42 -0400623 const auto ConstantScopeSubgroup =
624 ConstantInt::get(Arg->getType(), spv::ScopeSubgroup);
David Neto22f144c2017-06-12 14:26:21 -0400625
Kévin Petitc4643922019-06-17 19:32:05 +0100626 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
627 const auto LocalMemFenceMask =
628 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
629 const auto WorkgroupShiftAmount =
630 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
631 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
632 Instruction::Shl, LocalMemFenceMask,
633 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400634
Kévin Petitc4643922019-06-17 19:32:05 +0100635 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
636 const auto GlobalMemFenceMask =
637 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
638 const auto UniformShiftAmount =
639 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
640 const auto MemorySemanticsUniform = BinaryOperator::Create(
641 Instruction::Shl, GlobalMemFenceMask,
642 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400643
alan-bakerf6bc8252020-09-23 14:58:55 -0400644 // OpenCL 2.0
645 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
646 const auto ImageMemFenceMask =
647 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
648 const auto ImageShiftAmount =
649 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
650 const auto MemorySemanticsImage = BinaryOperator::Create(
651 Instruction::Shl, ImageMemFenceMask,
652 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
653
Kévin Petitc4643922019-06-17 19:32:05 +0100654 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400655 // MemorySemanticsSequentiallyConsistentMask.
656 auto MemorySemantics1 =
Kévin Petitc4643922019-06-17 19:32:05 +0100657 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
alan-baker12d2c182020-07-20 08:22:42 -0400658 ConstantAcquireRelease, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400659 auto MemorySemantics2 = BinaryOperator::Create(
660 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
661 auto MemorySemantics = BinaryOperator::Create(
662 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400663
alan-baker12d2c182020-07-20 08:22:42 -0400664 // If the memory scope is not specified explicitly, it is either Subgroup
665 // or Workgroup depending on the type of barrier.
666 Value *MemoryScope =
667 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
668 if (CI->data_operands_size() > 1) {
669 enum {
670 CL_MEMORY_SCOPE_WORKGROUP = 0x1,
671 CL_MEMORY_SCOPE_DEVICE = 0x2,
672 CL_MEMORY_SCOPE_SUBGROUP = 0x4
673 };
674 // The call was given an explicit memory scope.
675 const auto MemoryScopeSubgroup =
676 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_SUBGROUP);
677 const auto MemoryScopeDevice =
678 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_DEVICE);
David Neto22f144c2017-06-12 14:26:21 -0400679
alan-baker12d2c182020-07-20 08:22:42 -0400680 auto Cmp =
681 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
682 MemoryScopeSubgroup, CI->getOperand(1), "", CI);
683 MemoryScope = SelectInst::Create(Cmp, ConstantScopeSubgroup,
684 ConstantScopeWorkgroup, "", CI);
685 Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
686 MemoryScopeDevice, CI->getOperand(1), "", CI);
687 MemoryScope =
688 SelectInst::Create(Cmp, ConstantScopeDevice, MemoryScope, "", CI);
689 }
690
691 // Lastly, the Execution Scope is either Workgroup or Subgroup depending on
692 // the type of barrier;
693 const auto ExecutionScope =
694 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400695
Kévin Petitc4643922019-06-17 19:32:05 +0100696 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
alan-baker3d905692020-10-28 14:02:37 -0400697 {Attribute::NoDuplicate, Attribute::Convergent},
698 CI->getType(),
Kévin Petitc4643922019-06-17 19:32:05 +0100699 {ExecutionScope, MemoryScope, MemorySemantics});
700 });
David Neto22f144c2017-06-12 14:26:21 -0400701}
702
SJW2c317da2020-03-23 07:39:13 -0500703bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
704 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400705
SJW2c317da2020-03-23 07:39:13 -0500706 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerf6bc8252020-09-23 14:58:55 -0400707 enum {
708 CLK_LOCAL_MEM_FENCE = 0x01,
709 CLK_GLOBAL_MEM_FENCE = 0x02,
710 CLK_IMAGE_MEM_FENCE = 0x04,
711 };
David Neto22f144c2017-06-12 14:26:21 -0400712
SJW2c317da2020-03-23 07:39:13 -0500713 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400714
SJW2c317da2020-03-23 07:39:13 -0500715 // We need to map the OpenCL constants to the SPIR-V equivalents.
716 const auto LocalMemFence =
717 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
718 const auto GlobalMemFence =
719 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400720 const auto ImageMemFence =
721 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
SJW2c317da2020-03-23 07:39:13 -0500722 const auto ConstantMemorySemantics =
723 ConstantInt::get(Arg->getType(), semantics);
alan-baker12d2c182020-07-20 08:22:42 -0400724 const auto ConstantScopeWorkgroup =
725 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400726
SJW2c317da2020-03-23 07:39:13 -0500727 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
728 const auto LocalMemFenceMask =
729 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
730 const auto WorkgroupShiftAmount =
731 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
732 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
733 Instruction::Shl, LocalMemFenceMask,
734 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400735
SJW2c317da2020-03-23 07:39:13 -0500736 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
737 const auto GlobalMemFenceMask =
738 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
739 const auto UniformShiftAmount =
740 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
741 const auto MemorySemanticsUniform = BinaryOperator::Create(
742 Instruction::Shl, GlobalMemFenceMask,
743 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400744
alan-bakerf6bc8252020-09-23 14:58:55 -0400745 // OpenCL 2.0
746 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
747 const auto ImageMemFenceMask =
748 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
749 const auto ImageShiftAmount =
750 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
751 const auto MemorySemanticsImage = BinaryOperator::Create(
752 Instruction::Shl, ImageMemFenceMask,
753 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
754
SJW2c317da2020-03-23 07:39:13 -0500755 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400756 // |semantics|.
757 auto MemorySemantics1 =
SJW2c317da2020-03-23 07:39:13 -0500758 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
759 ConstantMemorySemantics, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400760 auto MemorySemantics2 = BinaryOperator::Create(
761 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
762 auto MemorySemantics = BinaryOperator::Create(
763 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400764
alan-baker12d2c182020-07-20 08:22:42 -0400765 // Memory Scope is always workgroup.
766 const auto MemoryScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400767
alan-baker3d905692020-10-28 14:02:37 -0400768 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier,
769 {Attribute::Convergent}, CI->getType(),
SJW2c317da2020-03-23 07:39:13 -0500770 {MemoryScope, MemorySemantics});
771 });
David Neto22f144c2017-06-12 14:26:21 -0400772}
773
Kévin Petit1cb45112020-04-27 18:55:48 +0100774bool ReplaceOpenCLBuiltinPass::replacePrefetch(Function &F) {
775 bool Changed = false;
776
777 SmallVector<Instruction *, 4> ToRemoves;
778
779 // Find all calls to the function
780 for (auto &U : F.uses()) {
781 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
782 ToRemoves.push_back(CI);
783 }
784 }
785
786 Changed = !ToRemoves.empty();
787
788 // Delete them
789 for (auto V : ToRemoves) {
790 V->eraseFromParent();
791 }
792
793 return Changed;
794}
795
SJW2c317da2020-03-23 07:39:13 -0500796bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
797 CmpInst::Predicate P,
798 int32_t C) {
799 return replaceCallsWithValue(F, [&](CallInst *CI) {
800 // The predicate to use in the CmpInst.
801 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -0400802
SJW2c317da2020-03-23 07:39:13 -0500803 // The value to return for true.
804 auto TrueValue = ConstantInt::getSigned(CI->getType(), C);
David Neto22f144c2017-06-12 14:26:21 -0400805
SJW2c317da2020-03-23 07:39:13 -0500806 // The value to return for false.
807 auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400808
SJW2c317da2020-03-23 07:39:13 -0500809 auto Arg1 = CI->getOperand(0);
810 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -0400811
SJW2c317da2020-03-23 07:39:13 -0500812 const auto Cmp =
813 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400814
SJW2c317da2020-03-23 07:39:13 -0500815 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
816 });
David Neto22f144c2017-06-12 14:26:21 -0400817}
818
SJW2c317da2020-03-23 07:39:13 -0500819bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
820 spv::Op SPIRVOp,
821 int32_t C) {
822 Module &M = *F.getParent();
823 return replaceCallsWithValue(F, [&](CallInst *CI) {
824 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -0400825
SJW2c317da2020-03-23 07:39:13 -0500826 // The value to return for true.
827 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -0400828
SJW2c317da2020-03-23 07:39:13 -0500829 // The value to return for false.
830 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -0400831
SJW2c317da2020-03-23 07:39:13 -0500832 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -0400833 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400834 CorrespondingBoolTy =
835 FixedVectorType::get(Type::getInt1Ty(M.getContext()),
836 CIVecTy->getElementCount().getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -0400837 }
David Neto22f144c2017-06-12 14:26:21 -0400838
SJW2c317da2020-03-23 07:39:13 -0500839 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
840 CorrespondingBoolTy, {CI->getOperand(0)});
841
842 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
843 });
David Neto22f144c2017-06-12 14:26:21 -0400844}
845
SJW2c317da2020-03-23 07:39:13 -0500846bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
847 Module &M = *F.getParent();
848 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100849 auto &C = M.getContext();
850 auto Val = CI->getOperand(0);
851 auto ValTy = Val->getType();
852 auto RetTy = CI->getType();
853
854 // Get a suitable integer type to represent the number
855 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
856
857 // Create Mask
858 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -0500859 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100860 switch (ScalarSize) {
861 case 16:
862 InfMask = ConstantInt::get(IntTy, 0x7C00U);
863 break;
864 case 32:
865 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
866 break;
867 case 64:
868 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
869 break;
870 default:
871 llvm_unreachable("Unsupported floating-point type");
872 }
873
874 IRBuilder<> Builder(CI);
875
876 // Bitcast to int
877 auto ValInt = Builder.CreateBitCast(Val, IntTy);
878
879 // Mask and compare
880 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
881 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
882
883 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -0500884 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +0100885 if (ValTy->isVectorTy()) {
886 RetTrue = ConstantInt::getSigned(RetTy, -1);
887 } else {
888 RetTrue = ConstantInt::get(RetTy, 1);
889 }
890 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
891 });
892}
893
SJW2c317da2020-03-23 07:39:13 -0500894bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
895 Module &M = *F.getParent();
896 return replaceCallsWithValue(F, [&](CallInst *CI) {
897 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400898
SJW2c317da2020-03-23 07:39:13 -0500899 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +0000900
SJW2c317da2020-03-23 07:39:13 -0500901 // If the argument is a 32-bit int, just use a shift
902 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
903 V = BinaryOperator::Create(Instruction::LShr, Arg,
904 ConstantInt::get(Arg->getType(), 31), "", CI);
905 } else {
906 // The value for zero to compare against.
907 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -0400908
SJW2c317da2020-03-23 07:39:13 -0500909 // The value to return for true.
910 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -0400911
SJW2c317da2020-03-23 07:39:13 -0500912 // The value to return for false.
913 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400914
SJW2c317da2020-03-23 07:39:13 -0500915 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
916 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400917
SJW2c317da2020-03-23 07:39:13 -0500918 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -0400919
SJW2c317da2020-03-23 07:39:13 -0500920 // If we have a function to call, call it!
921 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -0400922
SJW2c317da2020-03-23 07:39:13 -0500923 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -0400924
SJW2c317da2020-03-23 07:39:13 -0500925 const auto NewCI = clspv::InsertSPIRVOp(
926 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
927 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -0400928
SJW2c317da2020-03-23 07:39:13 -0500929 } else {
930 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -0400931 }
932
SJW2c317da2020-03-23 07:39:13 -0500933 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400934 }
SJW2c317da2020-03-23 07:39:13 -0500935 return V;
936 });
David Neto22f144c2017-06-12 14:26:21 -0400937}
938
SJW2c317da2020-03-23 07:39:13 -0500939bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
940 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
941 // Get arguments
942 auto HiValue = CI->getOperand(0);
943 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +0000944
SJW2c317da2020-03-23 07:39:13 -0500945 // Don't touch overloads that aren't in OpenCL C
946 auto HiType = HiValue->getType();
947 auto LoType = LoValue->getType();
948
949 if (HiType != LoType) {
950 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000951 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000952
SJW2c317da2020-03-23 07:39:13 -0500953 if (!HiType->isIntOrIntVectorTy()) {
954 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +0000955 }
Kévin Petitbf0036c2019-03-06 13:57:10 +0000956
SJW2c317da2020-03-23 07:39:13 -0500957 if (HiType->getScalarSizeInBits() * 2 !=
958 CI->getType()->getScalarSizeInBits()) {
959 return nullptr;
960 }
961
962 if ((HiType->getScalarSizeInBits() != 8) &&
963 (HiType->getScalarSizeInBits() != 16) &&
964 (HiType->getScalarSizeInBits() != 32)) {
965 return nullptr;
966 }
967
James Pricecf53df42020-04-20 14:41:24 -0400968 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400969 unsigned NumElements = HiVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -0400970 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
971 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -0500972 return nullptr;
973 }
974 }
975
976 // Convert both operands to the result type
977 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
978 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
979
980 // Shift high operand
981 auto ShiftAmount =
982 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
983 auto HiShifted =
984 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
985
986 // OR both results
987 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
988 });
Kévin Petitbf0036c2019-03-06 13:57:10 +0000989}
990
SJW2c317da2020-03-23 07:39:13 -0500991bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
992 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
993 // Get arguments
994 auto SrcValue = CI->getOperand(0);
995 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +0000996
SJW2c317da2020-03-23 07:39:13 -0500997 // Don't touch overloads that aren't in OpenCL C
998 auto SrcType = SrcValue->getType();
999 auto RotType = RotAmount->getType();
1000
1001 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
1002 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001003 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001004
SJW2c317da2020-03-23 07:39:13 -05001005 if (!SrcType->isIntOrIntVectorTy()) {
1006 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001007 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001008
SJW2c317da2020-03-23 07:39:13 -05001009 if ((SrcType->getScalarSizeInBits() != 8) &&
1010 (SrcType->getScalarSizeInBits() != 16) &&
1011 (SrcType->getScalarSizeInBits() != 32) &&
1012 (SrcType->getScalarSizeInBits() != 64)) {
1013 return nullptr;
1014 }
1015
James Pricecf53df42020-04-20 14:41:24 -04001016 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001017 unsigned NumElements = SrcVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001018 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1019 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001020 return nullptr;
1021 }
1022 }
1023
1024 // The approach used is to shift the top bits down, the bottom bits up
1025 // and OR the two shifted values.
1026
1027 // The rotation amount is to be treated modulo the element size.
1028 // Since SPIR-V shift ops don't support this, let's apply the
1029 // modulo ahead of shifting. The element size is always a power of
1030 // two so we can just AND with a mask.
1031 auto ModMask =
1032 ConstantInt::get(SrcType, SrcType->getScalarSizeInBits() - 1);
1033 RotAmount =
1034 BinaryOperator::Create(Instruction::And, RotAmount, ModMask, "", CI);
1035
1036 // Let's calc the amount by which to shift top bits down
1037 auto ScalarSize = ConstantInt::get(SrcType, SrcType->getScalarSizeInBits());
1038 auto DownAmount =
1039 BinaryOperator::Create(Instruction::Sub, ScalarSize, RotAmount, "", CI);
1040
1041 // Now shift the bottom bits up and the top bits down
1042 auto LoRotated =
1043 BinaryOperator::Create(Instruction::Shl, SrcValue, RotAmount, "", CI);
1044 auto HiRotated =
1045 BinaryOperator::Create(Instruction::LShr, SrcValue, DownAmount, "", CI);
1046
1047 // Finally OR the two shifted values
1048 return BinaryOperator::Create(Instruction::Or, LoRotated, HiRotated, "",
1049 CI);
1050 });
Kévin Petitd44eef52019-03-08 13:22:14 +00001051}
1052
SJW2c317da2020-03-23 07:39:13 -05001053bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
1054 bool DstIsSigned) {
1055 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1056 Value *V = nullptr;
1057 // Get arguments
1058 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001059
SJW2c317da2020-03-23 07:39:13 -05001060 // Don't touch overloads that aren't in OpenCL C
1061 auto SrcType = SrcValue->getType();
1062 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001063
SJW2c317da2020-03-23 07:39:13 -05001064 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1065 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1066 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001067 }
1068
James Pricecf53df42020-04-20 14:41:24 -04001069 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001070 unsigned SrcNumElements =
1071 SrcVecType->getElementCount().getKnownMinValue();
1072 unsigned DstNumElements =
1073 cast<VectorType>(DstType)->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001074 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001075 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001076 }
1077
James Pricecf53df42020-04-20 14:41:24 -04001078 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1079 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1080 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001081 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001082 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001083 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001084
SJW2c317da2020-03-23 07:39:13 -05001085 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1086 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1087
1088 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1089 bool DstIsInt = DstType->isIntOrIntVectorTy();
1090
1091 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1092 // Unnecessary cast operation.
1093 V = SrcValue;
1094 } else if (SrcIsFloat && DstIsFloat) {
1095 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1096 } else if (SrcIsFloat && DstIsInt) {
1097 if (DstIsSigned) {
1098 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1099 } else {
1100 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1101 }
1102 } else if (SrcIsInt && DstIsFloat) {
1103 if (SrcIsSigned) {
1104 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1105 } else {
1106 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1107 }
1108 } else if (SrcIsInt && DstIsInt) {
1109 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1110 } else {
1111 // Not something we're supposed to handle, just move on
1112 }
1113
1114 return V;
1115 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001116}
1117
SJW2c317da2020-03-23 07:39:13 -05001118bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1119 bool is_mad) {
1120 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1121 Value *V = nullptr;
1122 // Get arguments
1123 auto AValue = CI->getOperand(0);
1124 auto BValue = CI->getOperand(1);
1125 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001126
SJW2c317da2020-03-23 07:39:13 -05001127 // Don't touch overloads that aren't in OpenCL C
1128 auto AType = AValue->getType();
1129 auto BType = BValue->getType();
1130 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001131
SJW2c317da2020-03-23 07:39:13 -05001132 if ((AType != BType) || (CI->getType() != AType) ||
1133 (is_mad && (AType != CType))) {
1134 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001135 }
1136
SJW2c317da2020-03-23 07:39:13 -05001137 if (!AType->isIntOrIntVectorTy()) {
1138 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001139 }
Kévin Petit8a560882019-03-21 15:24:34 +00001140
SJW2c317da2020-03-23 07:39:13 -05001141 if ((AType->getScalarSizeInBits() != 8) &&
1142 (AType->getScalarSizeInBits() != 16) &&
1143 (AType->getScalarSizeInBits() != 32) &&
1144 (AType->getScalarSizeInBits() != 64)) {
1145 return V;
1146 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001147
James Pricecf53df42020-04-20 14:41:24 -04001148 if (auto AVecType = dyn_cast<VectorType>(AType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001149 unsigned NumElements = AVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001150 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1151 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001152 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001153 }
1154 }
1155
SJW2c317da2020-03-23 07:39:13 -05001156 // Our SPIR-V op returns a struct, create a type for it
1157 SmallVector<Type *, 2> TwoValueType = {AType, AType};
1158 auto ExMulRetType = StructType::create(TwoValueType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001159
SJW2c317da2020-03-23 07:39:13 -05001160 // Select the appropriate signed/unsigned SPIR-V op
1161 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1162
1163 // Call the SPIR-V op
1164 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1165 ExMulRetType, {AValue, BValue});
1166
1167 // Get the high part of the result
1168 unsigned Idxs[] = {1};
1169 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1170
1171 // If we're handling a mad_hi, add the third argument to the result
1172 if (is_mad) {
1173 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001174 }
1175
SJW2c317da2020-03-23 07:39:13 -05001176 return V;
1177 });
Kévin Petit8a560882019-03-21 15:24:34 +00001178}
1179
SJW2c317da2020-03-23 07:39:13 -05001180bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1181 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1182 // Get arguments
1183 auto FalseValue = CI->getOperand(0);
1184 auto TrueValue = CI->getOperand(1);
1185 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001186
SJW2c317da2020-03-23 07:39:13 -05001187 // Don't touch overloads that aren't in OpenCL C
1188 auto FalseType = FalseValue->getType();
1189 auto TrueType = TrueValue->getType();
1190 auto PredicateType = PredicateValue->getType();
1191
1192 if (FalseType != TrueType) {
1193 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001194 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001195
SJW2c317da2020-03-23 07:39:13 -05001196 if (!PredicateType->isIntOrIntVectorTy()) {
1197 return nullptr;
1198 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001199
SJW2c317da2020-03-23 07:39:13 -05001200 if (!FalseType->isIntOrIntVectorTy() &&
1201 !FalseType->getScalarType()->isFloatingPointTy()) {
1202 return nullptr;
1203 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001204
SJW2c317da2020-03-23 07:39:13 -05001205 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1206 return nullptr;
1207 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001208
SJW2c317da2020-03-23 07:39:13 -05001209 if (FalseType->getScalarSizeInBits() !=
1210 PredicateType->getScalarSizeInBits()) {
1211 return nullptr;
1212 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001213
James Pricecf53df42020-04-20 14:41:24 -04001214 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001215 unsigned NumElements = FalseVecType->getElementCount().getKnownMinValue();
1216 if (NumElements != cast<VectorType>(PredicateType)
1217 ->getElementCount()
1218 .getKnownMinValue()) {
SJW2c317da2020-03-23 07:39:13 -05001219 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001220 }
1221
James Pricecf53df42020-04-20 14:41:24 -04001222 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1223 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001224 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001225 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001226 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001227
SJW2c317da2020-03-23 07:39:13 -05001228 // Create constant
1229 const auto ZeroValue = Constant::getNullValue(PredicateType);
1230
1231 // Scalar and vector are to be treated differently
1232 CmpInst::Predicate Pred;
1233 if (PredicateType->isVectorTy()) {
1234 Pred = CmpInst::ICMP_SLT;
1235 } else {
1236 Pred = CmpInst::ICMP_NE;
1237 }
1238
1239 // Create comparison instruction
1240 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1241 ZeroValue, "", CI);
1242
1243 // Create select
1244 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1245 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001246}
1247
SJW2c317da2020-03-23 07:39:13 -05001248bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1249 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1250 Value *V = nullptr;
1251 if (CI->getNumOperands() != 4) {
1252 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001253 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001254
SJW2c317da2020-03-23 07:39:13 -05001255 // Get arguments
1256 auto FalseValue = CI->getOperand(0);
1257 auto TrueValue = CI->getOperand(1);
1258 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001259
SJW2c317da2020-03-23 07:39:13 -05001260 // Don't touch overloads that aren't in OpenCL C
1261 auto FalseType = FalseValue->getType();
1262 auto TrueType = TrueValue->getType();
1263 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001264
SJW2c317da2020-03-23 07:39:13 -05001265 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1266 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001267 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001268
James Pricecf53df42020-04-20 14:41:24 -04001269 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001270 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1271 !TrueType->getScalarType()->isIntegerTy()) {
1272 return V;
1273 }
alan-baker5a8c3be2020-09-09 13:44:26 -04001274 unsigned NumElements = TrueVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001275 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1276 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001277 return V;
1278 }
1279 }
1280
1281 // Remember the type of the operands
1282 auto OpType = TrueType;
1283
1284 // The actual bit selection will always be done on an integer type,
1285 // declare it here
1286 Type *BitType;
1287
1288 // If the operands are float, then bitcast them to int
1289 if (OpType->getScalarType()->isFloatingPointTy()) {
1290
1291 // First create the new type
1292 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1293
1294 // Then bitcast all operands
1295 PredicateValue =
1296 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1297 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1298 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1299
1300 } else {
1301 // The operands have an integer type, use it directly
1302 BitType = OpType;
1303 }
1304
1305 // All the operands are now always integers
1306 // implement as (c & b) | (~c & a)
1307
1308 // Create our negated predicate value
1309 auto AllOnes = Constant::getAllOnesValue(BitType);
1310 auto NotPredicateValue = BinaryOperator::Create(
1311 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1312
1313 // Then put everything together
1314 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1315 FalseValue, "", CI);
1316 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1317 TrueValue, "", CI);
1318
1319 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1320
1321 // If we were dealing with a floating point type, we must bitcast
1322 // the result back to that
1323 if (OpType->getScalarType()->isFloatingPointTy()) {
1324 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1325 }
1326
1327 return V;
1328 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001329}
1330
SJW61531372020-06-09 07:31:08 -05001331bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth) {
SJW2c317da2020-03-23 07:39:13 -05001332 // convert to vector versions
1333 Module &M = *F.getParent();
1334 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1335 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1336 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001337
SJW2c317da2020-03-23 07:39:13 -05001338 // First figure out which function we're dealing with
1339 if (is_smooth) {
1340 ArgsToSplat.push_back(CI->getOperand(1));
1341 VectorArg = CI->getOperand(2);
1342 } else {
1343 VectorArg = CI->getOperand(1);
1344 }
1345
1346 // Splat arguments that need to be
1347 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001348 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001349
1350 for (auto arg : ArgsToSplat) {
1351 Value *NewVectorArg = UndefValue::get(VecType);
alan-baker5a8c3be2020-09-09 13:44:26 -04001352 for (auto i = 0; i < VecType->getElementCount().getKnownMinValue(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001353 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1354 NewVectorArg =
1355 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1356 }
1357 SplatArgs.push_back(NewVectorArg);
1358 }
1359
1360 // Replace the call with the vector/vector flavour
1361 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1362 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1363
SJW61531372020-06-09 07:31:08 -05001364 std::string NewFName = Builtins::GetMangledFunctionName(
1365 is_smooth ? "smoothstep" : "step", NewFType);
1366
SJW2c317da2020-03-23 07:39:13 -05001367 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1368
1369 SmallVector<Value *, 3> NewArgs;
1370 for (auto arg : SplatArgs) {
1371 NewArgs.push_back(arg);
1372 }
1373 NewArgs.push_back(VectorArg);
1374
1375 return CallInst::Create(NewF, NewArgs, "", CI);
1376 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001377}
1378
SJW2c317da2020-03-23 07:39:13 -05001379bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001380 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1381 auto Arg = CI->getOperand(0);
1382 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001383
SJW2c317da2020-03-23 07:39:13 -05001384 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001385
SJW2c317da2020-03-23 07:39:13 -05001386 return BinaryOperator::Create(Op, Bitcast,
1387 ConstantInt::get(CI->getType(), 31), "", CI);
1388 });
David Neto22f144c2017-06-12 14:26:21 -04001389}
1390
SJW2c317da2020-03-23 07:39:13 -05001391bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1392 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001393 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1394 // The multiply instruction to use.
1395 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001396
SJW2c317da2020-03-23 07:39:13 -05001397 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001398
SJW2c317da2020-03-23 07:39:13 -05001399 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1400 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001401
SJW2c317da2020-03-23 07:39:13 -05001402 if (is_mad) {
1403 // The add instruction to use.
1404 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001405
SJW2c317da2020-03-23 07:39:13 -05001406 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001407 }
David Neto22f144c2017-06-12 14:26:21 -04001408
SJW2c317da2020-03-23 07:39:13 -05001409 return V;
1410 });
David Neto22f144c2017-06-12 14:26:21 -04001411}
1412
SJW2c317da2020-03-23 07:39:13 -05001413bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001414 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1415 Value *V = nullptr;
1416 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001417
SJW2c317da2020-03-23 07:39:13 -05001418 auto data_type = data->getType();
1419 if (!data_type->isVectorTy())
1420 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001421
James Pricecf53df42020-04-20 14:41:24 -04001422 auto vec_data_type = cast<VectorType>(data_type);
1423
alan-baker5a8c3be2020-09-09 13:44:26 -04001424 auto elems = vec_data_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001425 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1426 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001427
SJW2c317da2020-03-23 07:39:13 -05001428 auto offset = CI->getOperand(1);
1429 auto ptr = CI->getOperand(2);
1430 auto ptr_type = ptr->getType();
1431 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001432 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001433 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001434
SJW2c317da2020-03-23 07:39:13 -05001435 // Avoid pointer casts. Instead generate the correct number of stores
1436 // and rely on drivers to coalesce appropriately.
1437 IRBuilder<> builder(CI);
1438 auto elems_const = builder.getInt32(elems);
1439 auto adjust = builder.CreateMul(offset, elems_const);
1440 for (auto i = 0; i < elems; ++i) {
1441 auto idx = builder.getInt32(i);
1442 auto add = builder.CreateAdd(adjust, idx);
1443 auto gep = builder.CreateGEP(ptr, add);
1444 auto extract = builder.CreateExtractElement(data, i);
1445 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001446 }
SJW2c317da2020-03-23 07:39:13 -05001447 return V;
1448 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001449}
1450
SJW2c317da2020-03-23 07:39:13 -05001451bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001452 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1453 Value *V = nullptr;
1454 auto ret_type = F.getReturnType();
1455 if (!ret_type->isVectorTy())
1456 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001457
James Pricecf53df42020-04-20 14:41:24 -04001458 auto vec_ret_type = cast<VectorType>(ret_type);
1459
alan-baker5a8c3be2020-09-09 13:44:26 -04001460 auto elems = vec_ret_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001461 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1462 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001463
SJW2c317da2020-03-23 07:39:13 -05001464 auto offset = CI->getOperand(0);
1465 auto ptr = CI->getOperand(1);
1466 auto ptr_type = ptr->getType();
1467 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001468 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001469 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001470
SJW2c317da2020-03-23 07:39:13 -05001471 // Avoid pointer casts. Instead generate the correct number of loads
1472 // and rely on drivers to coalesce appropriately.
1473 IRBuilder<> builder(CI);
1474 auto elems_const = builder.getInt32(elems);
1475 V = UndefValue::get(ret_type);
1476 auto adjust = builder.CreateMul(offset, elems_const);
1477 for (auto i = 0; i < elems; ++i) {
1478 auto idx = builder.getInt32(i);
1479 auto add = builder.CreateAdd(adjust, idx);
1480 auto gep = builder.CreateGEP(ptr, add);
1481 auto load = builder.CreateLoad(gep);
1482 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001483 }
SJW2c317da2020-03-23 07:39:13 -05001484 return V;
1485 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001486}
1487
SJW2c317da2020-03-23 07:39:13 -05001488bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1489 const std::string &name,
1490 int vec_size) {
1491 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1492 if (!vec_size) {
1493 // deduce vec_size from last character of name (e.g. vload_half4)
1494 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001495 }
SJW2c317da2020-03-23 07:39:13 -05001496 switch (vec_size) {
1497 case 2:
1498 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1499 case 4:
1500 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1501 case 0:
1502 if (!is_clspv_version) {
1503 return replaceVloadHalf(F);
1504 }
1505 default:
1506 llvm_unreachable("Unsupported vload_half vector size");
1507 break;
1508 }
1509 return false;
David Neto22f144c2017-06-12 14:26:21 -04001510}
1511
SJW2c317da2020-03-23 07:39:13 -05001512bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1513 Module &M = *F.getParent();
1514 return replaceCallsWithValue(F, [&](CallInst *CI) {
1515 // The index argument from vload_half.
1516 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001517
SJW2c317da2020-03-23 07:39:13 -05001518 // The pointer argument from vload_half.
1519 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001520
SJW2c317da2020-03-23 07:39:13 -05001521 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001522 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
SJW2c317da2020-03-23 07:39:13 -05001523 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1524
1525 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001526 auto SPIRVIntrinsic = clspv::UnpackFunction();
SJW2c317da2020-03-23 07:39:13 -05001527
1528 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1529
1530 Value *V = nullptr;
1531
alan-baker7efcaaa2020-05-06 19:33:27 -04001532 bool supports_16bit_storage = true;
1533 switch (Arg1->getType()->getPointerAddressSpace()) {
1534 case clspv::AddressSpace::Global:
1535 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1536 clspv::Option::StorageClass::kSSBO);
1537 break;
1538 case clspv::AddressSpace::Constant:
1539 if (clspv::Option::ConstantArgsInUniformBuffer())
1540 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1541 clspv::Option::StorageClass::kUBO);
1542 else
1543 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1544 clspv::Option::StorageClass::kSSBO);
1545 break;
1546 default:
1547 // Clspv will emit the Float16 capability if the half type is
1548 // encountered. That capability covers private and local addressspaces.
1549 break;
1550 }
1551
1552 if (supports_16bit_storage) {
SJW2c317da2020-03-23 07:39:13 -05001553 auto ShortTy = Type::getInt16Ty(M.getContext());
1554 auto ShortPointerTy =
1555 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1556
1557 // Cast the half* pointer to short*.
1558 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1559
1560 // Index into the correct address of the casted pointer.
1561 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1562
1563 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001564 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001565
1566 // ZExt the short -> int.
1567 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1568
1569 // Get our float2.
1570 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1571
1572 // Extract out the bottom element which is our float result.
1573 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1574 } else {
1575 // Assume the pointer argument points to storage aligned to 32bits
1576 // or more.
1577 // TODO(dneto): Do more analysis to make sure this is true?
1578 //
1579 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1580 // with:
1581 //
1582 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1583 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1584 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1585 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1586 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1587 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1588 // x float> %converted, %index_is_odd32
1589
1590 auto IntPointerTy =
1591 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1592
1593 // Cast the base pointer to int*.
1594 // In a valid call (according to assumptions), this should get
1595 // optimized away in the simplify GEP pass.
1596 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1597
1598 auto One = ConstantInt::get(IntTy, 1);
1599 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1600 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1601
1602 // Index into the correct address of the casted pointer.
1603 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1604
1605 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001606 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001607
1608 // Get our float2.
1609 auto Call = CallInst::Create(NewF, Load, "", CI);
1610
1611 // Extract out the float result, where the element number is
1612 // determined by whether the original index was even or odd.
1613 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1614 }
1615 return V;
1616 });
1617}
1618
1619bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1620 Module &M = *F.getParent();
1621 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001622 // The index argument from vload_half.
1623 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001624
Kévin Petite8edce32019-04-10 14:23:32 +01001625 // The pointer argument from vload_half.
1626 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001627
Kévin Petite8edce32019-04-10 14:23:32 +01001628 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001629 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001630 auto NewPointerTy =
1631 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001632 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001633
Kévin Petite8edce32019-04-10 14:23:32 +01001634 // Cast the half* pointer to int*.
1635 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001636
Kévin Petite8edce32019-04-10 14:23:32 +01001637 // Index into the correct address of the casted pointer.
1638 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001639
Kévin Petite8edce32019-04-10 14:23:32 +01001640 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001641 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001642
Kévin Petite8edce32019-04-10 14:23:32 +01001643 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001644 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001645
Kévin Petite8edce32019-04-10 14:23:32 +01001646 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001647
Kévin Petite8edce32019-04-10 14:23:32 +01001648 // Get our float2.
1649 return CallInst::Create(NewF, Load, "", CI);
1650 });
David Neto22f144c2017-06-12 14:26:21 -04001651}
1652
SJW2c317da2020-03-23 07:39:13 -05001653bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1654 Module &M = *F.getParent();
1655 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001656 // The index argument from vload_half.
1657 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001658
Kévin Petite8edce32019-04-10 14:23:32 +01001659 // The pointer argument from vload_half.
1660 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001661
Kévin Petite8edce32019-04-10 14:23:32 +01001662 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001663 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1664 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001665 auto NewPointerTy =
1666 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001667 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001668
Kévin Petite8edce32019-04-10 14:23:32 +01001669 // Cast the half* pointer to int2*.
1670 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001671
Kévin Petite8edce32019-04-10 14:23:32 +01001672 // Index into the correct address of the casted pointer.
1673 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001674
Kévin Petite8edce32019-04-10 14:23:32 +01001675 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001676 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001677
Kévin Petite8edce32019-04-10 14:23:32 +01001678 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001679 auto X =
1680 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1681 auto Y =
1682 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001683
Kévin Petite8edce32019-04-10 14:23:32 +01001684 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001685 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001686
Kévin Petite8edce32019-04-10 14:23:32 +01001687 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001688
Kévin Petite8edce32019-04-10 14:23:32 +01001689 // Get the lower (x & y) components of our final float4.
1690 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001691
Kévin Petite8edce32019-04-10 14:23:32 +01001692 // Get the higher (z & w) components of our final float4.
1693 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001694
Kévin Petite8edce32019-04-10 14:23:32 +01001695 Constant *ShuffleMask[4] = {
1696 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1697 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001698
Kévin Petite8edce32019-04-10 14:23:32 +01001699 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001700 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1701 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001702 });
David Neto22f144c2017-06-12 14:26:21 -04001703}
1704
SJW2c317da2020-03-23 07:39:13 -05001705bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001706
1707 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1708 //
1709 // %u = load i32 %ptr
1710 // %fxy = call <2 x float> Unpack2xHalf(u)
1711 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001712 Module &M = *F.getParent();
1713 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001714 auto Index = CI->getOperand(0);
1715 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001716
Kévin Petite8edce32019-04-10 14:23:32 +01001717 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001718 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001719 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001720
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001721 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001722 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001723
Kévin Petite8edce32019-04-10 14:23:32 +01001724 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001725 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001726
Kévin Petite8edce32019-04-10 14:23:32 +01001727 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001728
Kévin Petite8edce32019-04-10 14:23:32 +01001729 // Get our final float2.
1730 return CallInst::Create(NewF, Load, "", CI);
1731 });
David Neto6ad93232018-06-07 15:42:58 -07001732}
1733
SJW2c317da2020-03-23 07:39:13 -05001734bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001735
1736 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1737 //
1738 // %u2 = load <2 x i32> %ptr
1739 // %u2xy = extractelement %u2, 0
1740 // %u2zw = extractelement %u2, 1
1741 // %fxy = call <2 x float> Unpack2xHalf(uint)
1742 // %fzw = call <2 x float> Unpack2xHalf(uint)
1743 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001744 Module &M = *F.getParent();
1745 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001746 auto Index = CI->getOperand(0);
1747 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001748
Kévin Petite8edce32019-04-10 14:23:32 +01001749 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001750 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1751 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001752 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001753
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001754 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001755 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001756
Kévin Petite8edce32019-04-10 14:23:32 +01001757 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001758 auto X =
1759 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1760 auto Y =
1761 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001762
Kévin Petite8edce32019-04-10 14:23:32 +01001763 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001764 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001765
Kévin Petite8edce32019-04-10 14:23:32 +01001766 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001767
Kévin Petite8edce32019-04-10 14:23:32 +01001768 // Get the lower (x & y) components of our final float4.
1769 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001770
Kévin Petite8edce32019-04-10 14:23:32 +01001771 // Get the higher (z & w) components of our final float4.
1772 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001773
Kévin Petite8edce32019-04-10 14:23:32 +01001774 Constant *ShuffleMask[4] = {
1775 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1776 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001777
Kévin Petite8edce32019-04-10 14:23:32 +01001778 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001779 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1780 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001781 });
David Neto6ad93232018-06-07 15:42:58 -07001782}
1783
SJW2c317da2020-03-23 07:39:13 -05001784bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1785 switch (vec_size) {
1786 case 0:
1787 return replaceVstoreHalf(F);
1788 case 2:
1789 return replaceVstoreHalf2(F);
1790 case 4:
1791 return replaceVstoreHalf4(F);
1792 default:
1793 llvm_unreachable("Unsupported vstore_half vector size");
1794 break;
1795 }
1796 return false;
1797}
David Neto22f144c2017-06-12 14:26:21 -04001798
SJW2c317da2020-03-23 07:39:13 -05001799bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1800 Module &M = *F.getParent();
1801 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001802 // The value to store.
1803 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001804
Kévin Petite8edce32019-04-10 14:23:32 +01001805 // The index argument from vstore_half.
1806 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001807
Kévin Petite8edce32019-04-10 14:23:32 +01001808 // The pointer argument from vstore_half.
1809 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001810
Kévin Petite8edce32019-04-10 14:23:32 +01001811 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001812 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001813 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1814 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001815
Kévin Petite8edce32019-04-10 14:23:32 +01001816 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001817 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001818
Kévin Petite8edce32019-04-10 14:23:32 +01001819 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001820
Kévin Petite8edce32019-04-10 14:23:32 +01001821 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001822 auto TempVec = InsertElementInst::Create(
1823 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001824
Kévin Petite8edce32019-04-10 14:23:32 +01001825 // Pack the float2 -> half2 (in an int).
1826 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001827
alan-baker7efcaaa2020-05-06 19:33:27 -04001828 bool supports_16bit_storage = true;
1829 switch (Arg2->getType()->getPointerAddressSpace()) {
1830 case clspv::AddressSpace::Global:
1831 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1832 clspv::Option::StorageClass::kSSBO);
1833 break;
1834 case clspv::AddressSpace::Constant:
1835 if (clspv::Option::ConstantArgsInUniformBuffer())
1836 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1837 clspv::Option::StorageClass::kUBO);
1838 else
1839 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1840 clspv::Option::StorageClass::kSSBO);
1841 break;
1842 default:
1843 // Clspv will emit the Float16 capability if the half type is
1844 // encountered. That capability covers private and local addressspaces.
1845 break;
1846 }
1847
SJW2c317da2020-03-23 07:39:13 -05001848 Value *V = nullptr;
alan-baker7efcaaa2020-05-06 19:33:27 -04001849 if (supports_16bit_storage) {
Kévin Petite8edce32019-04-10 14:23:32 +01001850 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001851 auto ShortPointerTy =
1852 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001853
Kévin Petite8edce32019-04-10 14:23:32 +01001854 // Truncate our i32 to an i16.
1855 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001856
Kévin Petite8edce32019-04-10 14:23:32 +01001857 // Cast the half* pointer to short*.
1858 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001859
Kévin Petite8edce32019-04-10 14:23:32 +01001860 // Index into the correct address of the casted pointer.
1861 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001862
Kévin Petite8edce32019-04-10 14:23:32 +01001863 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05001864 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001865 } else {
1866 // We can only write to 32-bit aligned words.
1867 //
1868 // Assuming base is aligned to 32-bits, replace the equivalent of
1869 // vstore_half(value, index, base)
1870 // with:
1871 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
1872 // uint32_t write_to_upper_half = index & 1u;
1873 // uint32_t shift = write_to_upper_half << 4;
1874 //
1875 // // Pack the float value as a half number in bottom 16 bits
1876 // // of an i32.
1877 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
1878 //
1879 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
1880 // ^ ((packed & 0xffff) << shift)
1881 // // We only need relaxed consistency, but OpenCL 1.2 only has
1882 // // sequentially consistent atomics.
1883 // // TODO(dneto): Use relaxed consistency.
1884 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001885 auto IntPointerTy =
1886 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001887
Kévin Petite8edce32019-04-10 14:23:32 +01001888 auto Four = ConstantInt::get(IntTy, 4);
1889 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04001890
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001891 auto IndexIsOdd =
1892 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001893 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001894 auto IndexIntoI32 =
1895 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
1896 auto BaseI32Ptr =
1897 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
1898 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
1899 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001900 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001901 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001902 auto MaskBitsToWrite =
1903 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
1904 auto MaskedCurrent = BinaryOperator::CreateAnd(
1905 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04001906
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001907 auto XLowerBits =
1908 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
1909 auto NewBitsToWrite =
1910 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
1911 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
1912 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04001913
Kévin Petite8edce32019-04-10 14:23:32 +01001914 // Generate the call to atomi_xor.
1915 SmallVector<Type *, 5> ParamTypes;
1916 // The pointer type.
1917 ParamTypes.push_back(IntPointerTy);
1918 // The Types for memory scope, semantics, and value.
1919 ParamTypes.push_back(IntTy);
1920 ParamTypes.push_back(IntTy);
1921 ParamTypes.push_back(IntTy);
1922 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
1923 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04001924
Kévin Petite8edce32019-04-10 14:23:32 +01001925 const auto ConstantScopeDevice =
1926 ConstantInt::get(IntTy, spv::ScopeDevice);
1927 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
1928 // (SPIR-V Workgroup).
1929 const auto AddrSpaceSemanticsBits =
1930 IntPointerTy->getPointerAddressSpace() == 1
1931 ? spv::MemorySemanticsUniformMemoryMask
1932 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04001933
Kévin Petite8edce32019-04-10 14:23:32 +01001934 // We're using relaxed consistency here.
1935 const auto ConstantMemorySemantics =
1936 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
1937 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04001938
Kévin Petite8edce32019-04-10 14:23:32 +01001939 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
1940 ConstantMemorySemantics, ValueToXor};
1941 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05001942
1943 // Return a Nop so the old Call is removed
1944 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
1945 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001946 }
David Neto22f144c2017-06-12 14:26:21 -04001947
SJW2c317da2020-03-23 07:39:13 -05001948 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01001949 });
David Neto22f144c2017-06-12 14:26:21 -04001950}
1951
SJW2c317da2020-03-23 07:39:13 -05001952bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
1953 Module &M = *F.getParent();
1954 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001955 // The value to store.
1956 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001957
Kévin Petite8edce32019-04-10 14:23:32 +01001958 // The index argument from vstore_half.
1959 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001960
Kévin Petite8edce32019-04-10 14:23:32 +01001961 // The pointer argument from vstore_half.
1962 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001963
Kévin Petite8edce32019-04-10 14:23:32 +01001964 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001965 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001966 auto NewPointerTy =
1967 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001968 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04001969
Kévin Petite8edce32019-04-10 14:23:32 +01001970 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001971 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001972
Kévin Petite8edce32019-04-10 14:23:32 +01001973 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001974
Kévin Petite8edce32019-04-10 14:23:32 +01001975 // Turn the packed x & y into the final packing.
1976 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001977
Kévin Petite8edce32019-04-10 14:23:32 +01001978 // Cast the half* pointer to int*.
1979 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001980
Kévin Petite8edce32019-04-10 14:23:32 +01001981 // Index into the correct address of the casted pointer.
1982 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001983
Kévin Petite8edce32019-04-10 14:23:32 +01001984 // Store to the int* we casted to.
1985 return new StoreInst(X, Index, CI);
1986 });
David Neto22f144c2017-06-12 14:26:21 -04001987}
1988
SJW2c317da2020-03-23 07:39:13 -05001989bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
1990 Module &M = *F.getParent();
1991 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001992 // The value to store.
1993 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001994
Kévin Petite8edce32019-04-10 14:23:32 +01001995 // The index argument from vstore_half.
1996 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001997
Kévin Petite8edce32019-04-10 14:23:32 +01001998 // The pointer argument from vstore_half.
1999 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002000
Kévin Petite8edce32019-04-10 14:23:32 +01002001 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002002 auto Int2Ty = FixedVectorType::get(IntTy, 2);
2003 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002004 auto NewPointerTy =
2005 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002006 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002007
Kévin Petite8edce32019-04-10 14:23:32 +01002008 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
2009 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04002010
Kévin Petite8edce32019-04-10 14:23:32 +01002011 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002012 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2013 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002014
Kévin Petite8edce32019-04-10 14:23:32 +01002015 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
2016 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002017
Kévin Petite8edce32019-04-10 14:23:32 +01002018 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002019 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2020 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002021
Kévin Petite8edce32019-04-10 14:23:32 +01002022 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002023 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002024
Kévin Petite8edce32019-04-10 14:23:32 +01002025 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002026
Kévin Petite8edce32019-04-10 14:23:32 +01002027 // Turn the packed x & y into the final component of our int2.
2028 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002029
Kévin Petite8edce32019-04-10 14:23:32 +01002030 // Turn the packed z & w into the final component of our int2.
2031 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002032
Kévin Petite8edce32019-04-10 14:23:32 +01002033 auto Combine = InsertElementInst::Create(
2034 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002035 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
2036 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002037
Kévin Petite8edce32019-04-10 14:23:32 +01002038 // Cast the half* pointer to int2*.
2039 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002040
Kévin Petite8edce32019-04-10 14:23:32 +01002041 // Index into the correct address of the casted pointer.
2042 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002043
Kévin Petite8edce32019-04-10 14:23:32 +01002044 // Store to the int2* we casted to.
2045 return new StoreInst(Combine, Index, CI);
2046 });
David Neto22f144c2017-06-12 14:26:21 -04002047}
2048
SJW2c317da2020-03-23 07:39:13 -05002049bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
2050 // convert half to float
2051 Module &M = *F.getParent();
2052 return replaceCallsWithValue(F, [&](CallInst *CI) {
2053 SmallVector<Type *, 3> types;
2054 SmallVector<Value *, 3> args;
2055 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
2056 types.push_back(CI->getArgOperand(i)->getType());
2057 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05002058 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05002059
alan-baker5a8c3be2020-09-09 13:44:26 -04002060 auto NewFType =
2061 FunctionType::get(FixedVectorType::get(Type::getFloatTy(M.getContext()),
2062 cast<VectorType>(CI->getType())
2063 ->getElementCount()
2064 .getKnownMinValue()),
2065 types, false);
SJW2c317da2020-03-23 07:39:13 -05002066
SJW61531372020-06-09 07:31:08 -05002067 std::string NewFName =
2068 Builtins::GetMangledFunctionName("read_imagef", NewFType);
SJW2c317da2020-03-23 07:39:13 -05002069
2070 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2071
2072 auto NewCI = CallInst::Create(NewF, args, "", CI);
2073
2074 // Convert to the half type.
2075 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2076 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002077}
2078
SJW2c317da2020-03-23 07:39:13 -05002079bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
2080 // convert half to float
2081 Module &M = *F.getParent();
2082 return replaceCallsWithValue(F, [&](CallInst *CI) {
2083 SmallVector<Type *, 3> types(3);
2084 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002085
SJW2c317da2020-03-23 07:39:13 -05002086 // Image
2087 types[0] = CI->getArgOperand(0)->getType();
2088 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002089
SJW2c317da2020-03-23 07:39:13 -05002090 // Coord
2091 types[1] = CI->getArgOperand(1)->getType();
2092 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002093
SJW2c317da2020-03-23 07:39:13 -05002094 // Data
alan-baker5a8c3be2020-09-09 13:44:26 -04002095 types[2] =
2096 FixedVectorType::get(Type::getFloatTy(M.getContext()),
2097 cast<VectorType>(CI->getArgOperand(2)->getType())
2098 ->getElementCount()
2099 .getKnownMinValue());
alan-bakerf7e17cb2020-01-02 07:29:59 -05002100
SJW2c317da2020-03-23 07:39:13 -05002101 auto NewFType =
2102 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002103
SJW61531372020-06-09 07:31:08 -05002104 std::string NewFName =
2105 Builtins::GetMangledFunctionName("write_imagef", NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002106
SJW2c317da2020-03-23 07:39:13 -05002107 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002108
SJW2c317da2020-03-23 07:39:13 -05002109 // Convert data to the float type.
2110 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2111 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002112
SJW2c317da2020-03-23 07:39:13 -05002113 return CallInst::Create(NewF, args, "", CI);
2114 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002115}
2116
SJW2c317da2020-03-23 07:39:13 -05002117bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2118 Function &F) {
2119 // convert read_image with int coords to float coords
2120 Module &M = *F.getParent();
2121 return replaceCallsWithValue(F, [&](CallInst *CI) {
2122 // The image.
2123 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002124
SJW2c317da2020-03-23 07:39:13 -05002125 // The sampler.
2126 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002127
SJW2c317da2020-03-23 07:39:13 -05002128 // The coordinate (integer type that we can't handle).
2129 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002130
SJW2c317da2020-03-23 07:39:13 -05002131 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2132 uint32_t components =
2133 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2134 Type *float_ty = nullptr;
2135 if (components == 1) {
2136 float_ty = Type::getFloatTy(M.getContext());
2137 } else {
alan-baker5a8c3be2020-09-09 13:44:26 -04002138 float_ty = FixedVectorType::get(Type::getFloatTy(M.getContext()),
2139 cast<VectorType>(Arg2->getType())
2140 ->getElementCount()
2141 .getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04002142 }
David Neto22f144c2017-06-12 14:26:21 -04002143
SJW2c317da2020-03-23 07:39:13 -05002144 auto NewFType = FunctionType::get(
2145 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2146
2147 std::string NewFName = F.getName().str();
2148 NewFName[NewFName.length() - 1] = 'f';
2149
2150 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2151
2152 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2153
2154 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2155 });
David Neto22f144c2017-06-12 14:26:21 -04002156}
2157
SJW2c317da2020-03-23 07:39:13 -05002158bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2159 return replaceCallsWithValue(F, [&](CallInst *CI) {
2160 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002161
SJW2c317da2020-03-23 07:39:13 -05002162 // We need to map the OpenCL constants to the SPIR-V equivalents.
2163 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2164 const auto ConstantMemorySemantics = ConstantInt::get(
2165 IntTy, spv::MemorySemanticsUniformMemoryMask |
2166 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002167
SJW2c317da2020-03-23 07:39:13 -05002168 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002169
SJW2c317da2020-03-23 07:39:13 -05002170 // The pointer.
2171 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002172
SJW2c317da2020-03-23 07:39:13 -05002173 // The memory scope.
2174 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002175
SJW2c317da2020-03-23 07:39:13 -05002176 // The memory semantics.
2177 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002178
SJW2c317da2020-03-23 07:39:13 -05002179 if (2 < CI->getNumArgOperands()) {
2180 // The unequal memory semantics.
2181 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002182
SJW2c317da2020-03-23 07:39:13 -05002183 // The value.
2184 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002185
SJW2c317da2020-03-23 07:39:13 -05002186 // The comparator.
2187 Params.push_back(CI->getArgOperand(1));
2188 } else if (1 < CI->getNumArgOperands()) {
2189 // The value.
2190 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002191 }
David Neto22f144c2017-06-12 14:26:21 -04002192
SJW2c317da2020-03-23 07:39:13 -05002193 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2194 });
David Neto22f144c2017-06-12 14:26:21 -04002195}
2196
SJW2c317da2020-03-23 07:39:13 -05002197bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2198 llvm::AtomicRMWInst::BinOp Op) {
2199 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerd0eb9052020-07-07 13:12:01 -04002200 auto align = F.getParent()->getDataLayout().getABITypeAlign(
2201 CI->getArgOperand(1)->getType());
SJW2c317da2020-03-23 07:39:13 -05002202 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
alan-bakerd0eb9052020-07-07 13:12:01 -04002203 align, AtomicOrdering::SequentiallyConsistent,
SJW2c317da2020-03-23 07:39:13 -05002204 SyncScope::System, CI);
2205 });
2206}
David Neto22f144c2017-06-12 14:26:21 -04002207
SJW2c317da2020-03-23 07:39:13 -05002208bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2209 Module &M = *F.getParent();
2210 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002211 auto IntTy = Type::getInt32Ty(M.getContext());
2212 auto FloatTy = Type::getFloatTy(M.getContext());
2213
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002214 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2215 ConstantInt::get(IntTy, 1),
2216 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002217
2218 Constant *UpShuffleMask[4] = {
2219 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2220 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2221
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002222 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2223 UndefValue::get(FloatTy),
2224 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002225
Kévin Petite8edce32019-04-10 14:23:32 +01002226 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002227 auto Arg0 =
2228 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2229 ConstantVector::get(DownShuffleMask), "", CI);
2230 auto Arg1 =
2231 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2232 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002233 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002234
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002235 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
SJW61531372020-06-09 07:31:08 -05002236 auto NewFName = Builtins::GetMangledFunctionName("cross", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002237
SJW61531372020-06-09 07:31:08 -05002238 auto Cross3Func = M.getOrInsertFunction(NewFName, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002239
Kévin Petite8edce32019-04-10 14:23:32 +01002240 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002241
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002242 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2243 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002244 });
David Neto22f144c2017-06-12 14:26:21 -04002245}
David Neto62653202017-10-16 19:05:18 -04002246
SJW2c317da2020-03-23 07:39:13 -05002247bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002248 // OpenCL's float result = fract(float x, float* ptr)
2249 //
2250 // In the LLVM domain:
2251 //
2252 // %floor_result = call spir_func float @floor(float %x)
2253 // store float %floor_result, float * %ptr
2254 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2255 // %result = call spir_func float
2256 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2257 //
2258 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2259 // and clspv.fract occur in the SPIR-V generator pass:
2260 //
2261 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2262 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2263 // ...
2264 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2265 // OpStore %ptr %floor_result
2266 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2267 // %fract_result = OpExtInst %float
Marco Antognini55d51862020-07-21 17:50:07 +01002268 // %glsl_ext Nmin %fract_intermediate %just_under_1
David Neto62653202017-10-16 19:05:18 -04002269
David Neto62653202017-10-16 19:05:18 -04002270 using std::string;
2271
2272 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2273 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002274
SJW2c317da2020-03-23 07:39:13 -05002275 Module &M = *F.getParent();
2276 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto62653202017-10-16 19:05:18 -04002277
SJW2c317da2020-03-23 07:39:13 -05002278 // This is either float or a float vector. All the float-like
2279 // types are this type.
2280 auto result_ty = F.getReturnType();
2281
SJW61531372020-06-09 07:31:08 -05002282 std::string fmin_name = Builtins::GetMangledFunctionName("fmin", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002283 Function *fmin_fn = M.getFunction(fmin_name);
2284 if (!fmin_fn) {
2285 // Make the fmin function.
2286 FunctionType *fn_ty =
2287 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2288 fmin_fn =
2289 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2290 fmin_fn->addFnAttr(Attribute::ReadNone);
2291 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2292 }
2293
SJW61531372020-06-09 07:31:08 -05002294 std::string floor_name =
2295 Builtins::GetMangledFunctionName("floor", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002296 Function *floor_fn = M.getFunction(floor_name);
2297 if (!floor_fn) {
2298 // Make the floor function.
2299 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2300 floor_fn =
2301 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2302 floor_fn->addFnAttr(Attribute::ReadNone);
2303 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2304 }
2305
SJW61531372020-06-09 07:31:08 -05002306 std::string clspv_fract_name =
2307 Builtins::GetMangledFunctionName("clspv.fract", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002308 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2309 if (!clspv_fract_fn) {
2310 // Make the clspv_fract function.
2311 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2312 clspv_fract_fn = cast<Function>(
2313 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2314 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2315 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2316 }
2317
2318 // Number of significant significand bits, whether represented or not.
2319 unsigned num_significand_bits;
2320 switch (result_ty->getScalarType()->getTypeID()) {
2321 case Type::HalfTyID:
2322 num_significand_bits = 11;
2323 break;
2324 case Type::FloatTyID:
2325 num_significand_bits = 24;
2326 break;
2327 case Type::DoubleTyID:
2328 num_significand_bits = 53;
2329 break;
2330 default:
2331 llvm_unreachable("Unhandled float type when processing fract builtin");
2332 break;
2333 }
2334 // Beware that the disassembler displays this value as
2335 // OpConstant %float 1
2336 // which is not quite right.
2337 const double kJustUnderOneScalar =
2338 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2339
2340 Constant *just_under_one =
2341 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2342 if (result_ty->isVectorTy()) {
2343 just_under_one = ConstantVector::getSplat(
alan-baker931253b2020-08-20 17:15:38 -04002344 cast<VectorType>(result_ty)->getElementCount(), just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002345 }
2346
2347 IRBuilder<> Builder(CI);
2348
2349 auto arg = CI->getArgOperand(0);
2350 auto ptr = CI->getArgOperand(1);
2351
2352 // Compute floor result and store it.
2353 auto floor = Builder.CreateCall(floor_fn, {arg});
2354 Builder.CreateStore(floor, ptr);
2355
2356 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2357 auto fract_result =
2358 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2359
2360 return fract_result;
2361 });
David Neto62653202017-10-16 19:05:18 -04002362}
alan-bakera52b7312020-10-26 08:58:51 -04002363
2364bool ReplaceOpenCLBuiltinPass::replaceAddSat(Function &F, bool is_signed) {
2365 Module *module = F.getParent();
2366 return replaceCallsWithValue(F, [&module, is_signed](CallInst *Call) {
2367 // SPIR-V OpIAddCarry interprets inputs as unsigned. We use that
2368 // instruction for unsigned additions. For signed addition, it is more
2369 // complicated. For values with bit widths less than 32 bits, we extend
2370 // to the next power of two and perform the addition. For 32- and
2371 // 64-bit values we test the signedness of op1 to determine how to clamp
2372 // the addition.
2373 Type *ty = Call->getType();
2374 Value *op0 = Call->getArgOperand(0);
2375 Value *op1 = Call->getArgOperand(1);
2376 Value *result = nullptr;
2377 if (is_signed) {
2378 unsigned bitwidth = ty->getScalarSizeInBits();
2379 if (bitwidth < 32) {
2380 // sext_op0 = sext op0
2381 // sext_op1 = sext op1
2382 // add = add sext_op0 sext_op1
2383 // clamp = clamp(add, min, max)
2384 // result = trunc clamp
2385 unsigned extended_bits = static_cast<unsigned>(bitwidth << 1);
2386 // The clamp values are the signed min and max of the original bitwidth
2387 // sign extended to the extended bitwidth.
2388 Constant *scalar_min = ConstantInt::get(
2389 Call->getContext(),
2390 APInt::getSignedMinValue(bitwidth).sext(extended_bits));
2391 Constant *scalar_max = ConstantInt::get(
2392 Call->getContext(),
2393 APInt::getSignedMaxValue(bitwidth).sext(extended_bits));
2394 Constant *min = scalar_min;
2395 Constant *max = scalar_max;
2396 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2397 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2398 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2399 }
2400 Type *extended_scalar_ty =
2401 IntegerType::get(Call->getContext(), extended_bits);
2402 Type *extended_ty = extended_scalar_ty;
2403 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2404 extended_ty =
2405 VectorType::get(extended_scalar_ty, vec_ty->getElementCount());
2406 }
2407 auto sext_op0 =
2408 CastInst::Create(Instruction::SExt, op0, extended_ty, "", Call);
2409 auto sext_op1 =
2410 CastInst::Create(Instruction::SExt, op1, extended_ty, "", Call);
2411 // Add the nsw flag since we know no overflow can occur.
2412 auto add = BinaryOperator::CreateNSW(Instruction::Add, sext_op0,
2413 sext_op1, "", Call);
2414 FunctionType *func_ty = FunctionType::get(
2415 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2416
2417 // Don't use the type in GetMangledFunctionName to ensure we get
2418 // signed parameters.
2419 std::string sclamp_name = Builtins::GetMangledFunctionName("clamp");
2420 uint32_t vec_width = 1;
2421 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2422 vec_width = vec_ty->getElementCount().getKnownMinValue();
2423 }
2424 if (extended_bits == 32) {
2425 if (vec_width == 1) {
2426 sclamp_name += "iii";
2427 } else {
2428 sclamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
2429 }
2430 } else {
2431 if (vec_width == 1) {
2432 sclamp_name += "sss";
2433 } else {
2434 sclamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2435 }
2436 }
2437 auto sclamp_callee = module->getOrInsertFunction(sclamp_name, func_ty);
2438 auto clamp = CallInst::Create(sclamp_callee, {add, min, max}, "", Call);
2439 result = CastInst::Create(Instruction::Trunc, clamp, ty, "", Call);
2440 } else {
2441 // Pseudo-code:
2442 // c = a + b;
2443 // if (b < 0)
2444 // c = c > a ? min : c;
2445 // else
2446 // c = c < a ? max : c;
2447 //
2448 unsigned bitwidth = ty->getScalarSizeInBits();
2449 Constant *scalar_min = ConstantInt::get(
2450 Call->getContext(), APInt::getSignedMinValue(bitwidth));
2451 Constant *scalar_max = ConstantInt::get(
2452 Call->getContext(), APInt::getSignedMaxValue(bitwidth));
2453 Constant *min = scalar_min;
2454 Constant *max = scalar_max;
2455 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2456 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2457 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2458 }
2459 auto zero = Constant::getNullValue(ty);
2460 // Cannot add the nsw flag.
2461 auto add = BinaryOperator::Create(Instruction::Add, op0, op1, "", Call);
2462 auto add_gt_op0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SGT,
2463 add, op0, "", Call);
2464 auto min_clamp = SelectInst::Create(add_gt_op0, min, add, "", Call);
2465 auto add_lt_op0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
2466 add, op0, "", Call);
2467 auto max_clamp = SelectInst::Create(add_lt_op0, max, add, "", Call);
2468 auto op1_lt_0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
2469 op1, zero, "", Call);
2470 result = SelectInst::Create(op1_lt_0, min_clamp, max_clamp, "", Call);
2471 }
2472 } else {
2473 // Just use OpIAddCarry and use the carry to clamp the result.
2474 auto ret_ty = StructType::get(Call->getContext(), {ty, ty});
2475 auto add = clspv::InsertSPIRVOp(
2476 Call, spv::OpIAddCarry, {Attribute::ReadNone}, ret_ty, {op0, op1});
2477 auto ex0 = ExtractValueInst::Create(add, {0}, "", Call);
2478 auto ex1 = ExtractValueInst::Create(add, {1}, "", Call);
2479 auto cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, ex1,
2480 Constant::getNullValue(ty), "", Call);
2481 result =
2482 SelectInst::Create(cmp, ex0, Constant::getAllOnesValue(ty), "", Call);
2483 }
2484
2485 return result;
2486 });
2487}