blob: 2873f3831206d533c3cd09a6f2617c1fabdf5970 [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"
alan-baker4986eff2020-10-29 13:38:00 -040024#include "llvm/IR/Operator.h"
Kévin Petitf5b78a22018-10-25 14:32:17 +000025#include "llvm/IR/ValueSymbolTable.h"
David Neto118188e2018-08-24 11:27:54 -040026#include "llvm/Pass.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/raw_ostream.h"
alan-baker4986eff2020-10-29 13:38:00 -040029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
David Neto118188e2018-08-24 11:27:54 -040030#include "llvm/Transforms/Utils/Cloning.h"
David Neto22f144c2017-06-12 14:26:21 -040031
alan-bakere0902602020-03-23 08:43:40 -040032#include "spirv/unified1/spirv.hpp"
David Neto22f144c2017-06-12 14:26:21 -040033
alan-baker931d18a2019-12-12 08:21:32 -050034#include "clspv/AddressSpace.h"
Diego Novillo3cc8d7a2019-04-10 13:30:34 -040035#include "clspv/Option.h"
David Neto482550a2018-03-24 05:21:07 -070036
SJW2c317da2020-03-23 07:39:13 -050037#include "Builtins.h"
alan-baker931d18a2019-12-12 08:21:32 -050038#include "Constants.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040039#include "Passes.h"
40#include "SPIRVOp.h"
alan-bakerf906d2b2019-12-10 11:26:23 -050041#include "Types.h"
Diego Novilloa4c44fa2019-04-11 10:56:15 -040042
SJW2c317da2020-03-23 07:39:13 -050043using namespace clspv;
David Neto22f144c2017-06-12 14:26:21 -040044using namespace llvm;
45
46#define DEBUG_TYPE "ReplaceOpenCLBuiltin"
47
48namespace {
Kévin Petit8a560882019-03-21 15:24:34 +000049
David Neto22f144c2017-06-12 14:26:21 -040050uint32_t clz(uint32_t v) {
51 uint32_t r;
52 uint32_t shift;
53
54 r = (v > 0xFFFF) << 4;
55 v >>= r;
56 shift = (v > 0xFF) << 3;
57 v >>= shift;
58 r |= shift;
59 shift = (v > 0xF) << 2;
60 v >>= shift;
61 r |= shift;
62 shift = (v > 0x3) << 1;
63 v >>= shift;
64 r |= shift;
65 r |= (v >> 1);
66
67 return r;
68}
69
Kévin Petitfdfa92e2019-09-25 14:20:58 +010070Type *getIntOrIntVectorTyForCast(LLVMContext &C, Type *Ty) {
71 Type *IntTy = Type::getIntNTy(C, Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -040072 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-baker5a8c3be2020-09-09 13:44:26 -040073 IntTy = FixedVectorType::get(IntTy,
74 vec_ty->getElementCount().getKnownMinValue());
Kévin Petitfdfa92e2019-09-25 14:20:58 +010075 }
76 return IntTy;
77}
78
alan-baker4986eff2020-10-29 13:38:00 -040079Value *MemoryOrderSemantics(Value *order, bool is_global,
80 Instruction *InsertBefore,
81 spv::MemorySemanticsMask base_semantics) {
82 enum AtomicMemoryOrder : uint32_t {
83 kMemoryOrderRelaxed = 0,
84 kMemoryOrderAcquire = 2,
85 kMemoryOrderRelease = 3,
86 kMemoryOrderAcqRel = 4,
87 kMemoryOrderSeqCst = 5
88 };
89
90 IRBuilder<> builder(InsertBefore);
91
92 // Constants for OpenCL C 2.0 memory_order.
93 const auto relaxed = builder.getInt32(AtomicMemoryOrder::kMemoryOrderRelaxed);
94 const auto acquire = builder.getInt32(AtomicMemoryOrder::kMemoryOrderAcquire);
95 const auto release = builder.getInt32(AtomicMemoryOrder::kMemoryOrderRelease);
96 const auto acq_rel = builder.getInt32(AtomicMemoryOrder::kMemoryOrderAcqRel);
97
98 // Constants for SPIR-V ordering memory semantics.
99 const auto RelaxedSemantics = builder.getInt32(spv::MemorySemanticsMaskNone);
100 const auto AcquireSemantics =
101 builder.getInt32(spv::MemorySemanticsAcquireMask);
102 const auto ReleaseSemantics =
103 builder.getInt32(spv::MemorySemanticsReleaseMask);
104 const auto AcqRelSemantics =
105 builder.getInt32(spv::MemorySemanticsAcquireReleaseMask);
106
107 // Constants for SPIR-V storage class semantics.
108 const auto UniformSemantics =
109 builder.getInt32(spv::MemorySemanticsUniformMemoryMask);
110 const auto WorkgroupSemantics =
111 builder.getInt32(spv::MemorySemanticsWorkgroupMemoryMask);
112
113 // Instead of sequentially consistent, use acquire, release or acquire
114 // release semantics.
115 Value *base_order = nullptr;
116 switch (base_semantics) {
117 case spv::MemorySemanticsAcquireMask:
118 base_order = AcquireSemantics;
119 break;
120 case spv::MemorySemanticsReleaseMask:
121 base_order = ReleaseSemantics;
122 break;
123 default:
124 base_order = AcqRelSemantics;
125 break;
126 }
127
128 Value *storage = is_global ? UniformSemantics : WorkgroupSemantics;
129 if (order == nullptr)
130 return builder.CreateOr({storage, base_order});
131
132 auto is_relaxed = builder.CreateICmpEQ(order, relaxed);
133 auto is_acquire = builder.CreateICmpEQ(order, acquire);
134 auto is_release = builder.CreateICmpEQ(order, release);
135 auto is_acq_rel = builder.CreateICmpEQ(order, acq_rel);
136 auto semantics =
137 builder.CreateSelect(is_relaxed, RelaxedSemantics, base_order);
138 semantics = builder.CreateSelect(is_acquire, AcquireSemantics, semantics);
139 semantics = builder.CreateSelect(is_release, ReleaseSemantics, semantics);
140 semantics = builder.CreateSelect(is_acq_rel, AcqRelSemantics, semantics);
141 return builder.CreateOr({storage, semantics});
142}
143
144Value *MemoryScope(Value *scope, bool is_global, Instruction *InsertBefore) {
145 enum AtomicMemoryScope : uint32_t {
146 kMemoryScopeWorkItem = 0,
147 kMemoryScopeWorkGroup = 1,
148 kMemoryScopeDevice = 2,
149 kMemoryScopeAllSVMDevices = 3, // not supported
150 kMemoryScopeSubGroup = 4
151 };
152
153 IRBuilder<> builder(InsertBefore);
154
155 // Constants for OpenCL C 2.0 memory_scope.
156 const auto work_item =
157 builder.getInt32(AtomicMemoryScope::kMemoryScopeWorkItem);
158 const auto work_group =
159 builder.getInt32(AtomicMemoryScope::kMemoryScopeWorkGroup);
160 const auto sub_group =
161 builder.getInt32(AtomicMemoryScope::kMemoryScopeSubGroup);
162 const auto device = builder.getInt32(AtomicMemoryScope::kMemoryScopeDevice);
163
164 // Constants for SPIR-V memory scopes.
165 const auto InvocationScope = builder.getInt32(spv::ScopeInvocation);
166 const auto WorkgroupScope = builder.getInt32(spv::ScopeWorkgroup);
167 const auto DeviceScope = builder.getInt32(spv::ScopeDevice);
168 const auto SubgroupScope = builder.getInt32(spv::ScopeSubgroup);
169
170 auto base_scope = is_global ? DeviceScope : WorkgroupScope;
171 if (scope == nullptr)
172 return base_scope;
173
174 auto is_work_item = builder.CreateICmpEQ(scope, work_item);
175 auto is_work_group = builder.CreateICmpEQ(scope, work_group);
176 auto is_sub_group = builder.CreateICmpEQ(scope, sub_group);
177 auto is_device = builder.CreateICmpEQ(scope, device);
178
179 scope = builder.CreateSelect(is_work_item, InvocationScope, base_scope);
180 scope = builder.CreateSelect(is_work_group, WorkgroupScope, scope);
181 scope = builder.CreateSelect(is_sub_group, SubgroupScope, scope);
182 scope = builder.CreateSelect(is_device, DeviceScope, scope);
183
184 return scope;
185}
186
SJW2c317da2020-03-23 07:39:13 -0500187bool replaceCallsWithValue(Function &F,
188 std::function<Value *(CallInst *)> Replacer) {
189
190 bool Changed = false;
191
192 SmallVector<Instruction *, 4> ToRemoves;
193
194 // Walk the users of the function.
195 for (auto &U : F.uses()) {
196 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
197
198 auto NewValue = Replacer(CI);
199
200 if (NewValue != nullptr) {
201 CI->replaceAllUsesWith(NewValue);
202
203 // Lastly, remember to remove the user.
204 ToRemoves.push_back(CI);
205 }
206 }
207 }
208
209 Changed = !ToRemoves.empty();
210
211 // And cleanup the calls we don't use anymore.
212 for (auto V : ToRemoves) {
213 V->eraseFromParent();
214 }
215
216 return Changed;
217}
218
David Neto22f144c2017-06-12 14:26:21 -0400219struct ReplaceOpenCLBuiltinPass final : public ModulePass {
220 static char ID;
221 ReplaceOpenCLBuiltinPass() : ModulePass(ID) {}
222
223 bool runOnModule(Module &M) override;
SJW2c317da2020-03-23 07:39:13 -0500224 bool runOnFunction(Function &F);
225 bool replaceAbs(Function &F);
226 bool replaceAbsDiff(Function &F, bool is_signed);
227 bool replaceCopysign(Function &F);
228 bool replaceRecip(Function &F);
229 bool replaceDivide(Function &F);
230 bool replaceDot(Function &F);
231 bool replaceFmod(Function &F);
SJW61531372020-06-09 07:31:08 -0500232 bool replaceExp10(Function &F, const std::string &basename);
233 bool replaceLog10(Function &F, const std::string &basename);
gnl21636e7992020-09-09 16:08:16 +0100234 bool replaceLog1p(Function &F);
alan-baker12d2c182020-07-20 08:22:42 -0400235 bool replaceBarrier(Function &F, bool subgroup = false);
SJW2c317da2020-03-23 07:39:13 -0500236 bool replaceMemFence(Function &F, uint32_t semantics);
Kévin Petit1cb45112020-04-27 18:55:48 +0100237 bool replacePrefetch(Function &F);
SJW2c317da2020-03-23 07:39:13 -0500238 bool replaceRelational(Function &F, CmpInst::Predicate P, int32_t C);
239 bool replaceIsInfAndIsNan(Function &F, spv::Op SPIRVOp, int32_t isvec);
240 bool replaceIsFinite(Function &F);
241 bool replaceAllAndAny(Function &F, spv::Op SPIRVOp);
242 bool replaceUpsample(Function &F);
243 bool replaceRotate(Function &F);
244 bool replaceConvert(Function &F, bool SrcIsSigned, bool DstIsSigned);
245 bool replaceMulHi(Function &F, bool is_signed, bool is_mad = false);
246 bool replaceSelect(Function &F);
247 bool replaceBitSelect(Function &F);
SJW61531372020-06-09 07:31:08 -0500248 bool replaceStep(Function &F, bool is_smooth);
SJW2c317da2020-03-23 07:39:13 -0500249 bool replaceSignbit(Function &F, bool is_vec);
250 bool replaceMul(Function &F, bool is_float, bool is_mad);
251 bool replaceVloadHalf(Function &F, const std::string &name, int vec_size);
252 bool replaceVloadHalf(Function &F);
253 bool replaceVloadHalf2(Function &F);
254 bool replaceVloadHalf4(Function &F);
255 bool replaceClspvVloadaHalf2(Function &F);
256 bool replaceClspvVloadaHalf4(Function &F);
257 bool replaceVstoreHalf(Function &F, int vec_size);
258 bool replaceVstoreHalf(Function &F);
259 bool replaceVstoreHalf2(Function &F);
260 bool replaceVstoreHalf4(Function &F);
261 bool replaceHalfReadImage(Function &F);
262 bool replaceHalfWriteImage(Function &F);
263 bool replaceSampledReadImageWithIntCoords(Function &F);
264 bool replaceAtomics(Function &F, spv::Op Op);
265 bool replaceAtomics(Function &F, llvm::AtomicRMWInst::BinOp Op);
alan-baker4986eff2020-10-29 13:38:00 -0400266 bool replaceAtomicLoad(Function &F);
267 bool replaceExplicitAtomics(Function &F, spv::Op Op,
268 spv::MemorySemanticsMask semantics =
269 spv::MemorySemanticsAcquireReleaseMask);
270 bool replaceAtomicCompareExchange(Function &);
SJW2c317da2020-03-23 07:39:13 -0500271 bool replaceCross(Function &F);
272 bool replaceFract(Function &F, int vec_size);
273 bool replaceVload(Function &F);
274 bool replaceVstore(Function &F);
alan-bakera52b7312020-10-26 08:58:51 -0400275 bool replaceAddSat(Function &F, bool is_signed);
alan-bakerb6da5132020-10-29 15:59:06 -0400276 bool replaceHadd(Function &F, Instruction::BinaryOps join_opcode);
David Neto22f144c2017-06-12 14:26:21 -0400277};
SJW2c317da2020-03-23 07:39:13 -0500278
Kévin Petit91bc72e2019-04-08 15:17:46 +0100279} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400280
281char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400282INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
283 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400284
285namespace clspv {
286ModulePass *createReplaceOpenCLBuiltinPass() {
287 return new ReplaceOpenCLBuiltinPass();
288}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400289} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400290
291bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500292 std::list<Function *> func_list;
293 for (auto &F : M.getFunctionList()) {
294 // process only function declarations
295 if (F.isDeclaration() && runOnFunction(F)) {
296 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000297 }
298 }
SJW2c317da2020-03-23 07:39:13 -0500299 if (func_list.size() != 0) {
300 // recursively convert functions, but first remove dead
301 for (auto *F : func_list) {
302 if (F->use_empty()) {
303 F->eraseFromParent();
304 }
305 }
306 runOnModule(M);
307 return true;
308 }
309 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000310}
311
SJW2c317da2020-03-23 07:39:13 -0500312bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
313 auto &FI = Builtins::Lookup(&F);
314 switch (FI.getType()) {
315 case Builtins::kAbs:
316 if (!FI.getParameter(0).is_signed) {
317 return replaceAbs(F);
318 }
319 break;
320 case Builtins::kAbsDiff:
321 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
alan-bakera52b7312020-10-26 08:58:51 -0400322
323 case Builtins::kAddSat:
324 return replaceAddSat(F, FI.getParameter(0).is_signed);
325
alan-bakerb6da5132020-10-29 15:59:06 -0400326 case Builtins::kHadd:
327 return replaceHadd(F, Instruction::And);
328 case Builtins::kRhadd:
329 return replaceHadd(F, Instruction::Or);
330
SJW2c317da2020-03-23 07:39:13 -0500331 case Builtins::kCopysign:
332 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100333
SJW2c317da2020-03-23 07:39:13 -0500334 case Builtins::kHalfRecip:
335 case Builtins::kNativeRecip:
336 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100337
SJW2c317da2020-03-23 07:39:13 -0500338 case Builtins::kHalfDivide:
339 case Builtins::kNativeDivide:
340 return replaceDivide(F);
341
342 case Builtins::kDot:
343 return replaceDot(F);
344
345 case Builtins::kExp10:
346 case Builtins::kHalfExp10:
SJW61531372020-06-09 07:31:08 -0500347 case Builtins::kNativeExp10:
348 return replaceExp10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500349
350 case Builtins::kLog10:
351 case Builtins::kHalfLog10:
SJW61531372020-06-09 07:31:08 -0500352 case Builtins::kNativeLog10:
353 return replaceLog10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500354
gnl21636e7992020-09-09 16:08:16 +0100355 case Builtins::kLog1p:
356 return replaceLog1p(F);
357
SJW2c317da2020-03-23 07:39:13 -0500358 case Builtins::kFmod:
359 return replaceFmod(F);
360
361 case Builtins::kBarrier:
362 case Builtins::kWorkGroupBarrier:
363 return replaceBarrier(F);
364
alan-baker12d2c182020-07-20 08:22:42 -0400365 case Builtins::kSubGroupBarrier:
366 return replaceBarrier(F, true);
367
SJW2c317da2020-03-23 07:39:13 -0500368 case Builtins::kMemFence:
alan-baker12d2c182020-07-20 08:22:42 -0400369 return replaceMemFence(F, spv::MemorySemanticsAcquireReleaseMask);
SJW2c317da2020-03-23 07:39:13 -0500370 case Builtins::kReadMemFence:
371 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
372 case Builtins::kWriteMemFence:
373 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
374
375 // Relational
376 case Builtins::kIsequal:
377 return replaceRelational(F, CmpInst::FCMP_OEQ,
378 FI.getParameter(0).vector_size ? -1 : 1);
379 case Builtins::kIsgreater:
380 return replaceRelational(F, CmpInst::FCMP_OGT,
381 FI.getParameter(0).vector_size ? -1 : 1);
382 case Builtins::kIsgreaterequal:
383 return replaceRelational(F, CmpInst::FCMP_OGE,
384 FI.getParameter(0).vector_size ? -1 : 1);
385 case Builtins::kIsless:
386 return replaceRelational(F, CmpInst::FCMP_OLT,
387 FI.getParameter(0).vector_size ? -1 : 1);
388 case Builtins::kIslessequal:
389 return replaceRelational(F, CmpInst::FCMP_OLE,
390 FI.getParameter(0).vector_size ? -1 : 1);
391 case Builtins::kIsnotequal:
392 return replaceRelational(F, CmpInst::FCMP_ONE,
393 FI.getParameter(0).vector_size ? -1 : 1);
394
395 case Builtins::kIsinf: {
396 bool is_vec = FI.getParameter(0).vector_size != 0;
397 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
398 }
399 case Builtins::kIsnan: {
400 bool is_vec = FI.getParameter(0).vector_size != 0;
401 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
402 }
403
404 case Builtins::kIsfinite:
405 return replaceIsFinite(F);
406
407 case Builtins::kAll: {
408 bool is_vec = FI.getParameter(0).vector_size != 0;
409 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
410 }
411 case Builtins::kAny: {
412 bool is_vec = FI.getParameter(0).vector_size != 0;
413 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
414 }
415
416 case Builtins::kUpsample:
417 return replaceUpsample(F);
418
419 case Builtins::kRotate:
420 return replaceRotate(F);
421
422 case Builtins::kConvert:
423 return replaceConvert(F, FI.getParameter(0).is_signed,
424 FI.getReturnType().is_signed);
425
alan-baker4986eff2020-10-29 13:38:00 -0400426 // OpenCL 2.0 explicit atomics have different default scopes and semantics
427 // than legacy atomic functions.
428 case Builtins::kAtomicLoad:
429 case Builtins::kAtomicLoadExplicit:
430 return replaceAtomicLoad(F);
431 case Builtins::kAtomicStore:
432 case Builtins::kAtomicStoreExplicit:
433 return replaceExplicitAtomics(F, spv::OpAtomicStore,
434 spv::MemorySemanticsReleaseMask);
435 case Builtins::kAtomicExchange:
436 case Builtins::kAtomicExchangeExplicit:
437 return replaceExplicitAtomics(F, spv::OpAtomicExchange);
438 case Builtins::kAtomicFetchAdd:
439 case Builtins::kAtomicFetchAddExplicit:
440 return replaceExplicitAtomics(F, spv::OpAtomicIAdd);
441 case Builtins::kAtomicFetchSub:
442 case Builtins::kAtomicFetchSubExplicit:
443 return replaceExplicitAtomics(F, spv::OpAtomicISub);
444 case Builtins::kAtomicFetchOr:
445 case Builtins::kAtomicFetchOrExplicit:
446 return replaceExplicitAtomics(F, spv::OpAtomicOr);
447 case Builtins::kAtomicFetchXor:
448 case Builtins::kAtomicFetchXorExplicit:
449 return replaceExplicitAtomics(F, spv::OpAtomicXor);
450 case Builtins::kAtomicFetchAnd:
451 case Builtins::kAtomicFetchAndExplicit:
452 return replaceExplicitAtomics(F, spv::OpAtomicAnd);
453 case Builtins::kAtomicFetchMin:
454 case Builtins::kAtomicFetchMinExplicit:
455 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
456 ? spv::OpAtomicSMin
457 : spv::OpAtomicUMin);
458 case Builtins::kAtomicFetchMax:
459 case Builtins::kAtomicFetchMaxExplicit:
460 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
461 ? spv::OpAtomicSMax
462 : spv::OpAtomicUMax);
463 // Weak compare exchange is generated as strong compare exchange.
464 case Builtins::kAtomicCompareExchangeWeak:
465 case Builtins::kAtomicCompareExchangeWeakExplicit:
466 case Builtins::kAtomicCompareExchangeStrong:
467 case Builtins::kAtomicCompareExchangeStrongExplicit:
468 return replaceAtomicCompareExchange(F);
469
470 // Legacy atomic functions.
SJW2c317da2020-03-23 07:39:13 -0500471 case Builtins::kAtomicInc:
472 return replaceAtomics(F, spv::OpAtomicIIncrement);
473 case Builtins::kAtomicDec:
474 return replaceAtomics(F, spv::OpAtomicIDecrement);
475 case Builtins::kAtomicCmpxchg:
476 return replaceAtomics(F, spv::OpAtomicCompareExchange);
477 case Builtins::kAtomicAdd:
478 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
479 case Builtins::kAtomicSub:
480 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
481 case Builtins::kAtomicXchg:
482 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
483 case Builtins::kAtomicMin:
484 return replaceAtomics(F, FI.getParameter(0).is_signed
485 ? llvm::AtomicRMWInst::Min
486 : llvm::AtomicRMWInst::UMin);
487 case Builtins::kAtomicMax:
488 return replaceAtomics(F, FI.getParameter(0).is_signed
489 ? llvm::AtomicRMWInst::Max
490 : llvm::AtomicRMWInst::UMax);
491 case Builtins::kAtomicAnd:
492 return replaceAtomics(F, llvm::AtomicRMWInst::And);
493 case Builtins::kAtomicOr:
494 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
495 case Builtins::kAtomicXor:
496 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
497
498 case Builtins::kCross:
499 if (FI.getParameter(0).vector_size == 4) {
500 return replaceCross(F);
501 }
502 break;
503
504 case Builtins::kFract:
505 if (FI.getParameterCount()) {
506 return replaceFract(F, FI.getParameter(0).vector_size);
507 }
508 break;
509
510 case Builtins::kMadHi:
511 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
512 case Builtins::kMulHi:
513 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
514
515 case Builtins::kMad:
516 case Builtins::kMad24:
517 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
518 true);
519 case Builtins::kMul24:
520 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
521 false);
522
523 case Builtins::kSelect:
524 return replaceSelect(F);
525
526 case Builtins::kBitselect:
527 return replaceBitSelect(F);
528
529 case Builtins::kVload:
530 return replaceVload(F);
531
532 case Builtins::kVloadaHalf:
533 case Builtins::kVloadHalf:
534 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
535
536 case Builtins::kVstore:
537 return replaceVstore(F);
538
539 case Builtins::kVstoreHalf:
540 case Builtins::kVstoreaHalf:
541 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
542
543 case Builtins::kSmoothstep: {
544 int vec_size = FI.getLastParameter().vector_size;
545 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500546 return replaceStep(F, true);
SJW2c317da2020-03-23 07:39:13 -0500547 }
548 break;
549 }
550 case Builtins::kStep: {
551 int vec_size = FI.getLastParameter().vector_size;
552 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500553 return replaceStep(F, false);
SJW2c317da2020-03-23 07:39:13 -0500554 }
555 break;
556 }
557
558 case Builtins::kSignbit:
559 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
560
561 case Builtins::kReadImageh:
562 return replaceHalfReadImage(F);
563 case Builtins::kReadImagef:
564 case Builtins::kReadImagei:
565 case Builtins::kReadImageui: {
566 if (FI.getParameter(1).isSampler() &&
567 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
568 return replaceSampledReadImageWithIntCoords(F);
569 }
570 break;
571 }
572
573 case Builtins::kWriteImageh:
574 return replaceHalfWriteImage(F);
575
Kévin Petit1cb45112020-04-27 18:55:48 +0100576 case Builtins::kPrefetch:
577 return replacePrefetch(F);
578
SJW2c317da2020-03-23 07:39:13 -0500579 default:
580 break;
581 }
582
583 return false;
584}
585
586bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
587 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400588 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100589}
590
SJW2c317da2020-03-23 07:39:13 -0500591bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
592 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100593 auto XValue = CI->getOperand(0);
594 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100595
Kévin Petite8edce32019-04-10 14:23:32 +0100596 IRBuilder<> Builder(CI);
597 auto XmY = Builder.CreateSub(XValue, YValue);
598 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100599
SJW2c317da2020-03-23 07:39:13 -0500600 Value *Cmp = nullptr;
601 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100602 Cmp = Builder.CreateICmpSGT(YValue, XValue);
603 } else {
604 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100605 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100606
Kévin Petite8edce32019-04-10 14:23:32 +0100607 return Builder.CreateSelect(Cmp, YmX, XmY);
608 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100609}
610
SJW2c317da2020-03-23 07:39:13 -0500611bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
612 return replaceCallsWithValue(F, [&F](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100613 auto XValue = CI->getOperand(0);
614 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100615
Kévin Petite8edce32019-04-10 14:23:32 +0100616 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100617
SJW2c317da2020-03-23 07:39:13 -0500618 Type *IntTy = Type::getIntNTy(F.getContext(), Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -0400619 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400620 IntTy = FixedVectorType::get(
621 IntTy, vec_ty->getElementCount().getKnownMinValue());
Kévin Petit8c1be282019-04-02 19:34:25 +0100622 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100623
Kévin Petite8edce32019-04-10 14:23:32 +0100624 // Return X with the sign of Y
625
626 // Sign bit masks
627 auto SignBit = IntTy->getScalarSizeInBits() - 1;
628 auto SignBitMask = 1 << SignBit;
629 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
630 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
631
632 IRBuilder<> Builder(CI);
633
634 // Extract sign of Y
635 auto YInt = Builder.CreateBitCast(YValue, IntTy);
636 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
637
638 // Clear sign bit in X
639 auto XInt = Builder.CreateBitCast(XValue, IntTy);
640 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
641
642 // Insert sign bit of Y into X
643 auto NewXInt = Builder.CreateOr(XInt, YSign);
644
645 // And cast back to floating-point
646 return Builder.CreateBitCast(NewXInt, Ty);
647 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100648}
649
SJW2c317da2020-03-23 07:39:13 -0500650bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
651 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100652 // Recip has one arg.
653 auto Arg = CI->getOperand(0);
654 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
655 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
656 });
David Neto22f144c2017-06-12 14:26:21 -0400657}
658
SJW2c317da2020-03-23 07:39:13 -0500659bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
660 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100661 auto Op0 = CI->getOperand(0);
662 auto Op1 = CI->getOperand(1);
663 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
664 });
David Neto22f144c2017-06-12 14:26:21 -0400665}
666
SJW2c317da2020-03-23 07:39:13 -0500667bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
668 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100669 auto Op0 = CI->getOperand(0);
670 auto Op1 = CI->getOperand(1);
671
SJW2c317da2020-03-23 07:39:13 -0500672 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100673 if (Op0->getType()->isVectorTy()) {
674 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
675 CI->getType(), {Op0, Op1});
676 } else {
677 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
678 }
679
680 return V;
681 });
682}
683
SJW2c317da2020-03-23 07:39:13 -0500684bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
SJW61531372020-06-09 07:31:08 -0500685 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500686 // convert to natural
687 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500688 std::string NewFName = basename.substr(0, slen);
689 NewFName =
690 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400691
SJW2c317da2020-03-23 07:39:13 -0500692 Module &M = *F.getParent();
693 return replaceCallsWithValue(F, [&](CallInst *CI) {
694 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
695
696 auto Arg = CI->getOperand(0);
697
698 // Constant of the natural log of 10 (ln(10)).
699 const double Ln10 =
700 2.302585092994045684017991454684364207601101488628772976033;
701
702 auto Mul = BinaryOperator::Create(
703 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
704
705 return CallInst::Create(NewF, Mul, "", CI);
706 });
David Neto22f144c2017-06-12 14:26:21 -0400707}
708
SJW2c317da2020-03-23 07:39:13 -0500709bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100710 // OpenCL fmod(x,y) is x - y * trunc(x/y)
711 // The sign for a non-zero result is taken from x.
712 // (Try an example.)
713 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500714 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100715 auto Op0 = CI->getOperand(0);
716 auto Op1 = CI->getOperand(1);
717 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
718 });
719}
720
SJW2c317da2020-03-23 07:39:13 -0500721bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
SJW61531372020-06-09 07:31:08 -0500722 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500723 // convert to natural
724 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500725 std::string NewFName = basename.substr(0, slen);
726 NewFName =
727 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400728
SJW2c317da2020-03-23 07:39:13 -0500729 Module &M = *F.getParent();
730 return replaceCallsWithValue(F, [&](CallInst *CI) {
731 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
732
733 auto Arg = CI->getOperand(0);
734
735 // Constant of the reciprocal of the natural log of 10 (ln(10)).
736 const double Ln10 =
737 0.434294481903251827651128918916605082294397005803666566114;
738
739 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
740
741 return BinaryOperator::Create(Instruction::FMul,
742 ConstantFP::get(Arg->getType(), Ln10), NewCI,
743 "", CI);
744 });
David Neto22f144c2017-06-12 14:26:21 -0400745}
746
gnl21636e7992020-09-09 16:08:16 +0100747bool ReplaceOpenCLBuiltinPass::replaceLog1p(Function &F) {
748 // convert to natural
749 std::string NewFName =
750 Builtins::GetMangledFunctionName("log", F.getFunctionType());
751
752 Module &M = *F.getParent();
753 return replaceCallsWithValue(F, [&](CallInst *CI) {
754 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
755
756 auto Arg = CI->getOperand(0);
757
758 auto ArgP1 = BinaryOperator::Create(
759 Instruction::FAdd, ConstantFP::get(Arg->getType(), 1.0), Arg, "", CI);
760
761 return CallInst::Create(NewF, ArgP1, "", CI);
762 });
763}
764
alan-baker12d2c182020-07-20 08:22:42 -0400765bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F, bool subgroup) {
David Neto22f144c2017-06-12 14:26:21 -0400766
alan-bakerf6bc8252020-09-23 14:58:55 -0400767 enum {
768 CLK_LOCAL_MEM_FENCE = 0x01,
769 CLK_GLOBAL_MEM_FENCE = 0x02,
770 CLK_IMAGE_MEM_FENCE = 0x04
771 };
David Neto22f144c2017-06-12 14:26:21 -0400772
alan-baker12d2c182020-07-20 08:22:42 -0400773 return replaceCallsWithValue(F, [subgroup](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100774 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400775
Kévin Petitc4643922019-06-17 19:32:05 +0100776 // We need to map the OpenCL constants to the SPIR-V equivalents.
777 const auto LocalMemFence =
778 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
779 const auto GlobalMemFence =
780 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400781 const auto ImageMemFence =
782 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
alan-baker12d2c182020-07-20 08:22:42 -0400783 const auto ConstantAcquireRelease = ConstantInt::get(
784 Arg->getType(), spv::MemorySemanticsAcquireReleaseMask);
Kévin Petitc4643922019-06-17 19:32:05 +0100785 const auto ConstantScopeDevice =
786 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
787 const auto ConstantScopeWorkgroup =
788 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
alan-baker12d2c182020-07-20 08:22:42 -0400789 const auto ConstantScopeSubgroup =
790 ConstantInt::get(Arg->getType(), spv::ScopeSubgroup);
David Neto22f144c2017-06-12 14:26:21 -0400791
Kévin Petitc4643922019-06-17 19:32:05 +0100792 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
793 const auto LocalMemFenceMask =
794 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
795 const auto WorkgroupShiftAmount =
796 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
797 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
798 Instruction::Shl, LocalMemFenceMask,
799 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400800
Kévin Petitc4643922019-06-17 19:32:05 +0100801 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
802 const auto GlobalMemFenceMask =
803 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
804 const auto UniformShiftAmount =
805 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
806 const auto MemorySemanticsUniform = BinaryOperator::Create(
807 Instruction::Shl, GlobalMemFenceMask,
808 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400809
alan-bakerf6bc8252020-09-23 14:58:55 -0400810 // OpenCL 2.0
811 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
812 const auto ImageMemFenceMask =
813 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
814 const auto ImageShiftAmount =
815 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
816 const auto MemorySemanticsImage = BinaryOperator::Create(
817 Instruction::Shl, ImageMemFenceMask,
818 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
819
Kévin Petitc4643922019-06-17 19:32:05 +0100820 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400821 // MemorySemanticsSequentiallyConsistentMask.
822 auto MemorySemantics1 =
Kévin Petitc4643922019-06-17 19:32:05 +0100823 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
alan-baker12d2c182020-07-20 08:22:42 -0400824 ConstantAcquireRelease, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400825 auto MemorySemantics2 = BinaryOperator::Create(
826 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
827 auto MemorySemantics = BinaryOperator::Create(
828 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400829
alan-baker12d2c182020-07-20 08:22:42 -0400830 // If the memory scope is not specified explicitly, it is either Subgroup
831 // or Workgroup depending on the type of barrier.
832 Value *MemoryScope =
833 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
834 if (CI->data_operands_size() > 1) {
835 enum {
836 CL_MEMORY_SCOPE_WORKGROUP = 0x1,
837 CL_MEMORY_SCOPE_DEVICE = 0x2,
838 CL_MEMORY_SCOPE_SUBGROUP = 0x4
839 };
840 // The call was given an explicit memory scope.
841 const auto MemoryScopeSubgroup =
842 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_SUBGROUP);
843 const auto MemoryScopeDevice =
844 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_DEVICE);
David Neto22f144c2017-06-12 14:26:21 -0400845
alan-baker12d2c182020-07-20 08:22:42 -0400846 auto Cmp =
847 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
848 MemoryScopeSubgroup, CI->getOperand(1), "", CI);
849 MemoryScope = SelectInst::Create(Cmp, ConstantScopeSubgroup,
850 ConstantScopeWorkgroup, "", CI);
851 Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
852 MemoryScopeDevice, CI->getOperand(1), "", CI);
853 MemoryScope =
854 SelectInst::Create(Cmp, ConstantScopeDevice, MemoryScope, "", CI);
855 }
856
857 // Lastly, the Execution Scope is either Workgroup or Subgroup depending on
858 // the type of barrier;
859 const auto ExecutionScope =
860 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400861
Kévin Petitc4643922019-06-17 19:32:05 +0100862 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
alan-baker3d905692020-10-28 14:02:37 -0400863 {Attribute::NoDuplicate, Attribute::Convergent},
864 CI->getType(),
Kévin Petitc4643922019-06-17 19:32:05 +0100865 {ExecutionScope, MemoryScope, MemorySemantics});
866 });
David Neto22f144c2017-06-12 14:26:21 -0400867}
868
SJW2c317da2020-03-23 07:39:13 -0500869bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
870 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400871
SJW2c317da2020-03-23 07:39:13 -0500872 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerf6bc8252020-09-23 14:58:55 -0400873 enum {
874 CLK_LOCAL_MEM_FENCE = 0x01,
875 CLK_GLOBAL_MEM_FENCE = 0x02,
876 CLK_IMAGE_MEM_FENCE = 0x04,
877 };
David Neto22f144c2017-06-12 14:26:21 -0400878
SJW2c317da2020-03-23 07:39:13 -0500879 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400880
SJW2c317da2020-03-23 07:39:13 -0500881 // We need to map the OpenCL constants to the SPIR-V equivalents.
882 const auto LocalMemFence =
883 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
884 const auto GlobalMemFence =
885 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400886 const auto ImageMemFence =
887 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
SJW2c317da2020-03-23 07:39:13 -0500888 const auto ConstantMemorySemantics =
889 ConstantInt::get(Arg->getType(), semantics);
alan-baker12d2c182020-07-20 08:22:42 -0400890 const auto ConstantScopeWorkgroup =
891 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400892
SJW2c317da2020-03-23 07:39:13 -0500893 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
894 const auto LocalMemFenceMask =
895 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
896 const auto WorkgroupShiftAmount =
897 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
898 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
899 Instruction::Shl, LocalMemFenceMask,
900 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400901
SJW2c317da2020-03-23 07:39:13 -0500902 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
903 const auto GlobalMemFenceMask =
904 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
905 const auto UniformShiftAmount =
906 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
907 const auto MemorySemanticsUniform = BinaryOperator::Create(
908 Instruction::Shl, GlobalMemFenceMask,
909 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400910
alan-bakerf6bc8252020-09-23 14:58:55 -0400911 // OpenCL 2.0
912 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
913 const auto ImageMemFenceMask =
914 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
915 const auto ImageShiftAmount =
916 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
917 const auto MemorySemanticsImage = BinaryOperator::Create(
918 Instruction::Shl, ImageMemFenceMask,
919 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
920
SJW2c317da2020-03-23 07:39:13 -0500921 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400922 // |semantics|.
923 auto MemorySemantics1 =
SJW2c317da2020-03-23 07:39:13 -0500924 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
925 ConstantMemorySemantics, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400926 auto MemorySemantics2 = BinaryOperator::Create(
927 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
928 auto MemorySemantics = BinaryOperator::Create(
929 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400930
alan-baker12d2c182020-07-20 08:22:42 -0400931 // Memory Scope is always workgroup.
932 const auto MemoryScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400933
alan-baker3d905692020-10-28 14:02:37 -0400934 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier,
935 {Attribute::Convergent}, CI->getType(),
SJW2c317da2020-03-23 07:39:13 -0500936 {MemoryScope, MemorySemantics});
937 });
David Neto22f144c2017-06-12 14:26:21 -0400938}
939
Kévin Petit1cb45112020-04-27 18:55:48 +0100940bool ReplaceOpenCLBuiltinPass::replacePrefetch(Function &F) {
941 bool Changed = false;
942
943 SmallVector<Instruction *, 4> ToRemoves;
944
945 // Find all calls to the function
946 for (auto &U : F.uses()) {
947 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
948 ToRemoves.push_back(CI);
949 }
950 }
951
952 Changed = !ToRemoves.empty();
953
954 // Delete them
955 for (auto V : ToRemoves) {
956 V->eraseFromParent();
957 }
958
959 return Changed;
960}
961
SJW2c317da2020-03-23 07:39:13 -0500962bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
963 CmpInst::Predicate P,
964 int32_t C) {
965 return replaceCallsWithValue(F, [&](CallInst *CI) {
966 // The predicate to use in the CmpInst.
967 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -0400968
SJW2c317da2020-03-23 07:39:13 -0500969 // The value to return for true.
970 auto TrueValue = ConstantInt::getSigned(CI->getType(), C);
David Neto22f144c2017-06-12 14:26:21 -0400971
SJW2c317da2020-03-23 07:39:13 -0500972 // The value to return for false.
973 auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -0400974
SJW2c317da2020-03-23 07:39:13 -0500975 auto Arg1 = CI->getOperand(0);
976 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -0400977
SJW2c317da2020-03-23 07:39:13 -0500978 const auto Cmp =
979 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400980
SJW2c317da2020-03-23 07:39:13 -0500981 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
982 });
David Neto22f144c2017-06-12 14:26:21 -0400983}
984
SJW2c317da2020-03-23 07:39:13 -0500985bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
986 spv::Op SPIRVOp,
987 int32_t C) {
988 Module &M = *F.getParent();
989 return replaceCallsWithValue(F, [&](CallInst *CI) {
990 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -0400991
SJW2c317da2020-03-23 07:39:13 -0500992 // The value to return for true.
993 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -0400994
SJW2c317da2020-03-23 07:39:13 -0500995 // The value to return for false.
996 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -0400997
SJW2c317da2020-03-23 07:39:13 -0500998 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -0400999 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001000 CorrespondingBoolTy =
1001 FixedVectorType::get(Type::getInt1Ty(M.getContext()),
1002 CIVecTy->getElementCount().getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04001003 }
David Neto22f144c2017-06-12 14:26:21 -04001004
SJW2c317da2020-03-23 07:39:13 -05001005 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
1006 CorrespondingBoolTy, {CI->getOperand(0)});
1007
1008 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
1009 });
David Neto22f144c2017-06-12 14:26:21 -04001010}
1011
SJW2c317da2020-03-23 07:39:13 -05001012bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
1013 Module &M = *F.getParent();
1014 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001015 auto &C = M.getContext();
1016 auto Val = CI->getOperand(0);
1017 auto ValTy = Val->getType();
1018 auto RetTy = CI->getType();
1019
1020 // Get a suitable integer type to represent the number
1021 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
1022
1023 // Create Mask
1024 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -05001025 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001026 switch (ScalarSize) {
1027 case 16:
1028 InfMask = ConstantInt::get(IntTy, 0x7C00U);
1029 break;
1030 case 32:
1031 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
1032 break;
1033 case 64:
1034 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
1035 break;
1036 default:
1037 llvm_unreachable("Unsupported floating-point type");
1038 }
1039
1040 IRBuilder<> Builder(CI);
1041
1042 // Bitcast to int
1043 auto ValInt = Builder.CreateBitCast(Val, IntTy);
1044
1045 // Mask and compare
1046 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
1047 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
1048
1049 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -05001050 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001051 if (ValTy->isVectorTy()) {
1052 RetTrue = ConstantInt::getSigned(RetTy, -1);
1053 } else {
1054 RetTrue = ConstantInt::get(RetTy, 1);
1055 }
1056 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
1057 });
1058}
1059
SJW2c317da2020-03-23 07:39:13 -05001060bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
1061 Module &M = *F.getParent();
1062 return replaceCallsWithValue(F, [&](CallInst *CI) {
1063 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001064
SJW2c317da2020-03-23 07:39:13 -05001065 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +00001066
SJW2c317da2020-03-23 07:39:13 -05001067 // If the argument is a 32-bit int, just use a shift
1068 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
1069 V = BinaryOperator::Create(Instruction::LShr, Arg,
1070 ConstantInt::get(Arg->getType(), 31), "", CI);
1071 } else {
1072 // The value for zero to compare against.
1073 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -04001074
SJW2c317da2020-03-23 07:39:13 -05001075 // The value to return for true.
1076 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04001077
SJW2c317da2020-03-23 07:39:13 -05001078 // The value to return for false.
1079 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -04001080
SJW2c317da2020-03-23 07:39:13 -05001081 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
1082 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001083
SJW2c317da2020-03-23 07:39:13 -05001084 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -04001085
SJW2c317da2020-03-23 07:39:13 -05001086 // If we have a function to call, call it!
1087 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -04001088
SJW2c317da2020-03-23 07:39:13 -05001089 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -04001090
SJW2c317da2020-03-23 07:39:13 -05001091 const auto NewCI = clspv::InsertSPIRVOp(
1092 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
1093 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -04001094
SJW2c317da2020-03-23 07:39:13 -05001095 } else {
1096 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -04001097 }
1098
SJW2c317da2020-03-23 07:39:13 -05001099 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001100 }
SJW2c317da2020-03-23 07:39:13 -05001101 return V;
1102 });
David Neto22f144c2017-06-12 14:26:21 -04001103}
1104
SJW2c317da2020-03-23 07:39:13 -05001105bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
1106 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1107 // Get arguments
1108 auto HiValue = CI->getOperand(0);
1109 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +00001110
SJW2c317da2020-03-23 07:39:13 -05001111 // Don't touch overloads that aren't in OpenCL C
1112 auto HiType = HiValue->getType();
1113 auto LoType = LoValue->getType();
1114
1115 if (HiType != LoType) {
1116 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001117 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001118
SJW2c317da2020-03-23 07:39:13 -05001119 if (!HiType->isIntOrIntVectorTy()) {
1120 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001121 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001122
SJW2c317da2020-03-23 07:39:13 -05001123 if (HiType->getScalarSizeInBits() * 2 !=
1124 CI->getType()->getScalarSizeInBits()) {
1125 return nullptr;
1126 }
1127
1128 if ((HiType->getScalarSizeInBits() != 8) &&
1129 (HiType->getScalarSizeInBits() != 16) &&
1130 (HiType->getScalarSizeInBits() != 32)) {
1131 return nullptr;
1132 }
1133
James Pricecf53df42020-04-20 14:41:24 -04001134 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001135 unsigned NumElements = HiVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001136 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1137 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001138 return nullptr;
1139 }
1140 }
1141
1142 // Convert both operands to the result type
1143 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
1144 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
1145
1146 // Shift high operand
1147 auto ShiftAmount =
1148 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
1149 auto HiShifted =
1150 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
1151
1152 // OR both results
1153 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
1154 });
Kévin Petitbf0036c2019-03-06 13:57:10 +00001155}
1156
SJW2c317da2020-03-23 07:39:13 -05001157bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
1158 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1159 // Get arguments
1160 auto SrcValue = CI->getOperand(0);
1161 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +00001162
SJW2c317da2020-03-23 07:39:13 -05001163 // Don't touch overloads that aren't in OpenCL C
1164 auto SrcType = SrcValue->getType();
1165 auto RotType = RotAmount->getType();
1166
1167 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
1168 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001169 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001170
SJW2c317da2020-03-23 07:39:13 -05001171 if (!SrcType->isIntOrIntVectorTy()) {
1172 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001173 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001174
SJW2c317da2020-03-23 07:39:13 -05001175 if ((SrcType->getScalarSizeInBits() != 8) &&
1176 (SrcType->getScalarSizeInBits() != 16) &&
1177 (SrcType->getScalarSizeInBits() != 32) &&
1178 (SrcType->getScalarSizeInBits() != 64)) {
1179 return nullptr;
1180 }
1181
James Pricecf53df42020-04-20 14:41:24 -04001182 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001183 unsigned NumElements = SrcVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001184 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1185 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001186 return nullptr;
1187 }
1188 }
1189
1190 // The approach used is to shift the top bits down, the bottom bits up
1191 // and OR the two shifted values.
1192
1193 // The rotation amount is to be treated modulo the element size.
1194 // Since SPIR-V shift ops don't support this, let's apply the
1195 // modulo ahead of shifting. The element size is always a power of
1196 // two so we can just AND with a mask.
1197 auto ModMask =
1198 ConstantInt::get(SrcType, SrcType->getScalarSizeInBits() - 1);
1199 RotAmount =
1200 BinaryOperator::Create(Instruction::And, RotAmount, ModMask, "", CI);
1201
1202 // Let's calc the amount by which to shift top bits down
1203 auto ScalarSize = ConstantInt::get(SrcType, SrcType->getScalarSizeInBits());
1204 auto DownAmount =
1205 BinaryOperator::Create(Instruction::Sub, ScalarSize, RotAmount, "", CI);
1206
1207 // Now shift the bottom bits up and the top bits down
1208 auto LoRotated =
1209 BinaryOperator::Create(Instruction::Shl, SrcValue, RotAmount, "", CI);
1210 auto HiRotated =
1211 BinaryOperator::Create(Instruction::LShr, SrcValue, DownAmount, "", CI);
1212
1213 // Finally OR the two shifted values
1214 return BinaryOperator::Create(Instruction::Or, LoRotated, HiRotated, "",
1215 CI);
1216 });
Kévin Petitd44eef52019-03-08 13:22:14 +00001217}
1218
SJW2c317da2020-03-23 07:39:13 -05001219bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
1220 bool DstIsSigned) {
1221 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1222 Value *V = nullptr;
1223 // Get arguments
1224 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001225
SJW2c317da2020-03-23 07:39:13 -05001226 // Don't touch overloads that aren't in OpenCL C
1227 auto SrcType = SrcValue->getType();
1228 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001229
SJW2c317da2020-03-23 07:39:13 -05001230 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1231 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1232 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001233 }
1234
James Pricecf53df42020-04-20 14:41:24 -04001235 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001236 unsigned SrcNumElements =
1237 SrcVecType->getElementCount().getKnownMinValue();
1238 unsigned DstNumElements =
1239 cast<VectorType>(DstType)->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001240 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001241 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001242 }
1243
James Pricecf53df42020-04-20 14:41:24 -04001244 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1245 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1246 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001247 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001248 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001249 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001250
SJW2c317da2020-03-23 07:39:13 -05001251 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1252 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1253
1254 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1255 bool DstIsInt = DstType->isIntOrIntVectorTy();
1256
1257 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1258 // Unnecessary cast operation.
1259 V = SrcValue;
1260 } else if (SrcIsFloat && DstIsFloat) {
1261 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1262 } else if (SrcIsFloat && DstIsInt) {
1263 if (DstIsSigned) {
1264 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1265 } else {
1266 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1267 }
1268 } else if (SrcIsInt && DstIsFloat) {
1269 if (SrcIsSigned) {
1270 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1271 } else {
1272 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1273 }
1274 } else if (SrcIsInt && DstIsInt) {
1275 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1276 } else {
1277 // Not something we're supposed to handle, just move on
1278 }
1279
1280 return V;
1281 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001282}
1283
SJW2c317da2020-03-23 07:39:13 -05001284bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1285 bool is_mad) {
1286 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1287 Value *V = nullptr;
1288 // Get arguments
1289 auto AValue = CI->getOperand(0);
1290 auto BValue = CI->getOperand(1);
1291 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001292
SJW2c317da2020-03-23 07:39:13 -05001293 // Don't touch overloads that aren't in OpenCL C
1294 auto AType = AValue->getType();
1295 auto BType = BValue->getType();
1296 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001297
SJW2c317da2020-03-23 07:39:13 -05001298 if ((AType != BType) || (CI->getType() != AType) ||
1299 (is_mad && (AType != CType))) {
1300 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001301 }
1302
SJW2c317da2020-03-23 07:39:13 -05001303 if (!AType->isIntOrIntVectorTy()) {
1304 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001305 }
Kévin Petit8a560882019-03-21 15:24:34 +00001306
SJW2c317da2020-03-23 07:39:13 -05001307 if ((AType->getScalarSizeInBits() != 8) &&
1308 (AType->getScalarSizeInBits() != 16) &&
1309 (AType->getScalarSizeInBits() != 32) &&
1310 (AType->getScalarSizeInBits() != 64)) {
1311 return V;
1312 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001313
James Pricecf53df42020-04-20 14:41:24 -04001314 if (auto AVecType = dyn_cast<VectorType>(AType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001315 unsigned NumElements = AVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001316 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1317 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001318 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001319 }
1320 }
1321
SJW2c317da2020-03-23 07:39:13 -05001322 // Our SPIR-V op returns a struct, create a type for it
1323 SmallVector<Type *, 2> TwoValueType = {AType, AType};
1324 auto ExMulRetType = StructType::create(TwoValueType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001325
SJW2c317da2020-03-23 07:39:13 -05001326 // Select the appropriate signed/unsigned SPIR-V op
1327 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1328
1329 // Call the SPIR-V op
1330 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1331 ExMulRetType, {AValue, BValue});
1332
1333 // Get the high part of the result
1334 unsigned Idxs[] = {1};
1335 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1336
1337 // If we're handling a mad_hi, add the third argument to the result
1338 if (is_mad) {
1339 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001340 }
1341
SJW2c317da2020-03-23 07:39:13 -05001342 return V;
1343 });
Kévin Petit8a560882019-03-21 15:24:34 +00001344}
1345
SJW2c317da2020-03-23 07:39:13 -05001346bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1347 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1348 // Get arguments
1349 auto FalseValue = CI->getOperand(0);
1350 auto TrueValue = CI->getOperand(1);
1351 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001352
SJW2c317da2020-03-23 07:39:13 -05001353 // Don't touch overloads that aren't in OpenCL C
1354 auto FalseType = FalseValue->getType();
1355 auto TrueType = TrueValue->getType();
1356 auto PredicateType = PredicateValue->getType();
1357
1358 if (FalseType != TrueType) {
1359 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001360 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001361
SJW2c317da2020-03-23 07:39:13 -05001362 if (!PredicateType->isIntOrIntVectorTy()) {
1363 return nullptr;
1364 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001365
SJW2c317da2020-03-23 07:39:13 -05001366 if (!FalseType->isIntOrIntVectorTy() &&
1367 !FalseType->getScalarType()->isFloatingPointTy()) {
1368 return nullptr;
1369 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001370
SJW2c317da2020-03-23 07:39:13 -05001371 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1372 return nullptr;
1373 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001374
SJW2c317da2020-03-23 07:39:13 -05001375 if (FalseType->getScalarSizeInBits() !=
1376 PredicateType->getScalarSizeInBits()) {
1377 return nullptr;
1378 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001379
James Pricecf53df42020-04-20 14:41:24 -04001380 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001381 unsigned NumElements = FalseVecType->getElementCount().getKnownMinValue();
1382 if (NumElements != cast<VectorType>(PredicateType)
1383 ->getElementCount()
1384 .getKnownMinValue()) {
SJW2c317da2020-03-23 07:39:13 -05001385 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001386 }
1387
James Pricecf53df42020-04-20 14:41:24 -04001388 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1389 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001390 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001391 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001392 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001393
SJW2c317da2020-03-23 07:39:13 -05001394 // Create constant
1395 const auto ZeroValue = Constant::getNullValue(PredicateType);
1396
1397 // Scalar and vector are to be treated differently
1398 CmpInst::Predicate Pred;
1399 if (PredicateType->isVectorTy()) {
1400 Pred = CmpInst::ICMP_SLT;
1401 } else {
1402 Pred = CmpInst::ICMP_NE;
1403 }
1404
1405 // Create comparison instruction
1406 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1407 ZeroValue, "", CI);
1408
1409 // Create select
1410 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1411 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001412}
1413
SJW2c317da2020-03-23 07:39:13 -05001414bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1415 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1416 Value *V = nullptr;
1417 if (CI->getNumOperands() != 4) {
1418 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001419 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001420
SJW2c317da2020-03-23 07:39:13 -05001421 // Get arguments
1422 auto FalseValue = CI->getOperand(0);
1423 auto TrueValue = CI->getOperand(1);
1424 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001425
SJW2c317da2020-03-23 07:39:13 -05001426 // Don't touch overloads that aren't in OpenCL C
1427 auto FalseType = FalseValue->getType();
1428 auto TrueType = TrueValue->getType();
1429 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001430
SJW2c317da2020-03-23 07:39:13 -05001431 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1432 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001433 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001434
James Pricecf53df42020-04-20 14:41:24 -04001435 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001436 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1437 !TrueType->getScalarType()->isIntegerTy()) {
1438 return V;
1439 }
alan-baker5a8c3be2020-09-09 13:44:26 -04001440 unsigned NumElements = TrueVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001441 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1442 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001443 return V;
1444 }
1445 }
1446
1447 // Remember the type of the operands
1448 auto OpType = TrueType;
1449
1450 // The actual bit selection will always be done on an integer type,
1451 // declare it here
1452 Type *BitType;
1453
1454 // If the operands are float, then bitcast them to int
1455 if (OpType->getScalarType()->isFloatingPointTy()) {
1456
1457 // First create the new type
1458 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1459
1460 // Then bitcast all operands
1461 PredicateValue =
1462 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1463 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1464 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1465
1466 } else {
1467 // The operands have an integer type, use it directly
1468 BitType = OpType;
1469 }
1470
1471 // All the operands are now always integers
1472 // implement as (c & b) | (~c & a)
1473
1474 // Create our negated predicate value
1475 auto AllOnes = Constant::getAllOnesValue(BitType);
1476 auto NotPredicateValue = BinaryOperator::Create(
1477 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1478
1479 // Then put everything together
1480 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1481 FalseValue, "", CI);
1482 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1483 TrueValue, "", CI);
1484
1485 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1486
1487 // If we were dealing with a floating point type, we must bitcast
1488 // the result back to that
1489 if (OpType->getScalarType()->isFloatingPointTy()) {
1490 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1491 }
1492
1493 return V;
1494 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001495}
1496
SJW61531372020-06-09 07:31:08 -05001497bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth) {
SJW2c317da2020-03-23 07:39:13 -05001498 // convert to vector versions
1499 Module &M = *F.getParent();
1500 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1501 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1502 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001503
SJW2c317da2020-03-23 07:39:13 -05001504 // First figure out which function we're dealing with
1505 if (is_smooth) {
1506 ArgsToSplat.push_back(CI->getOperand(1));
1507 VectorArg = CI->getOperand(2);
1508 } else {
1509 VectorArg = CI->getOperand(1);
1510 }
1511
1512 // Splat arguments that need to be
1513 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001514 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001515
1516 for (auto arg : ArgsToSplat) {
1517 Value *NewVectorArg = UndefValue::get(VecType);
alan-baker5a8c3be2020-09-09 13:44:26 -04001518 for (auto i = 0; i < VecType->getElementCount().getKnownMinValue(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001519 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1520 NewVectorArg =
1521 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1522 }
1523 SplatArgs.push_back(NewVectorArg);
1524 }
1525
1526 // Replace the call with the vector/vector flavour
1527 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1528 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1529
SJW61531372020-06-09 07:31:08 -05001530 std::string NewFName = Builtins::GetMangledFunctionName(
1531 is_smooth ? "smoothstep" : "step", NewFType);
1532
SJW2c317da2020-03-23 07:39:13 -05001533 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1534
1535 SmallVector<Value *, 3> NewArgs;
1536 for (auto arg : SplatArgs) {
1537 NewArgs.push_back(arg);
1538 }
1539 NewArgs.push_back(VectorArg);
1540
1541 return CallInst::Create(NewF, NewArgs, "", CI);
1542 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001543}
1544
SJW2c317da2020-03-23 07:39:13 -05001545bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001546 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1547 auto Arg = CI->getOperand(0);
1548 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001549
SJW2c317da2020-03-23 07:39:13 -05001550 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001551
SJW2c317da2020-03-23 07:39:13 -05001552 return BinaryOperator::Create(Op, Bitcast,
1553 ConstantInt::get(CI->getType(), 31), "", CI);
1554 });
David Neto22f144c2017-06-12 14:26:21 -04001555}
1556
SJW2c317da2020-03-23 07:39:13 -05001557bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1558 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001559 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1560 // The multiply instruction to use.
1561 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001562
SJW2c317da2020-03-23 07:39:13 -05001563 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001564
SJW2c317da2020-03-23 07:39:13 -05001565 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1566 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001567
SJW2c317da2020-03-23 07:39:13 -05001568 if (is_mad) {
1569 // The add instruction to use.
1570 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001571
SJW2c317da2020-03-23 07:39:13 -05001572 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001573 }
David Neto22f144c2017-06-12 14:26:21 -04001574
SJW2c317da2020-03-23 07:39:13 -05001575 return V;
1576 });
David Neto22f144c2017-06-12 14:26:21 -04001577}
1578
SJW2c317da2020-03-23 07:39:13 -05001579bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001580 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1581 Value *V = nullptr;
1582 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001583
SJW2c317da2020-03-23 07:39:13 -05001584 auto data_type = data->getType();
1585 if (!data_type->isVectorTy())
1586 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001587
James Pricecf53df42020-04-20 14:41:24 -04001588 auto vec_data_type = cast<VectorType>(data_type);
1589
alan-baker5a8c3be2020-09-09 13:44:26 -04001590 auto elems = vec_data_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001591 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1592 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001593
SJW2c317da2020-03-23 07:39:13 -05001594 auto offset = CI->getOperand(1);
1595 auto ptr = CI->getOperand(2);
1596 auto ptr_type = ptr->getType();
1597 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001598 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001599 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001600
SJW2c317da2020-03-23 07:39:13 -05001601 // Avoid pointer casts. Instead generate the correct number of stores
1602 // and rely on drivers to coalesce appropriately.
1603 IRBuilder<> builder(CI);
1604 auto elems_const = builder.getInt32(elems);
1605 auto adjust = builder.CreateMul(offset, elems_const);
1606 for (auto i = 0; i < elems; ++i) {
1607 auto idx = builder.getInt32(i);
1608 auto add = builder.CreateAdd(adjust, idx);
1609 auto gep = builder.CreateGEP(ptr, add);
1610 auto extract = builder.CreateExtractElement(data, i);
1611 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001612 }
SJW2c317da2020-03-23 07:39:13 -05001613 return V;
1614 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001615}
1616
SJW2c317da2020-03-23 07:39:13 -05001617bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001618 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1619 Value *V = nullptr;
1620 auto ret_type = F.getReturnType();
1621 if (!ret_type->isVectorTy())
1622 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001623
James Pricecf53df42020-04-20 14:41:24 -04001624 auto vec_ret_type = cast<VectorType>(ret_type);
1625
alan-baker5a8c3be2020-09-09 13:44:26 -04001626 auto elems = vec_ret_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001627 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1628 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001629
SJW2c317da2020-03-23 07:39:13 -05001630 auto offset = CI->getOperand(0);
1631 auto ptr = CI->getOperand(1);
1632 auto ptr_type = ptr->getType();
1633 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001634 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001635 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001636
SJW2c317da2020-03-23 07:39:13 -05001637 // Avoid pointer casts. Instead generate the correct number of loads
1638 // and rely on drivers to coalesce appropriately.
1639 IRBuilder<> builder(CI);
1640 auto elems_const = builder.getInt32(elems);
1641 V = UndefValue::get(ret_type);
1642 auto adjust = builder.CreateMul(offset, elems_const);
1643 for (auto i = 0; i < elems; ++i) {
1644 auto idx = builder.getInt32(i);
1645 auto add = builder.CreateAdd(adjust, idx);
1646 auto gep = builder.CreateGEP(ptr, add);
1647 auto load = builder.CreateLoad(gep);
1648 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001649 }
SJW2c317da2020-03-23 07:39:13 -05001650 return V;
1651 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001652}
1653
SJW2c317da2020-03-23 07:39:13 -05001654bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1655 const std::string &name,
1656 int vec_size) {
1657 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1658 if (!vec_size) {
1659 // deduce vec_size from last character of name (e.g. vload_half4)
1660 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001661 }
SJW2c317da2020-03-23 07:39:13 -05001662 switch (vec_size) {
1663 case 2:
1664 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1665 case 4:
1666 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1667 case 0:
1668 if (!is_clspv_version) {
1669 return replaceVloadHalf(F);
1670 }
1671 default:
1672 llvm_unreachable("Unsupported vload_half vector size");
1673 break;
1674 }
1675 return false;
David Neto22f144c2017-06-12 14:26:21 -04001676}
1677
SJW2c317da2020-03-23 07:39:13 -05001678bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1679 Module &M = *F.getParent();
1680 return replaceCallsWithValue(F, [&](CallInst *CI) {
1681 // The index argument from vload_half.
1682 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001683
SJW2c317da2020-03-23 07:39:13 -05001684 // The pointer argument from vload_half.
1685 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001686
SJW2c317da2020-03-23 07:39:13 -05001687 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001688 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
SJW2c317da2020-03-23 07:39:13 -05001689 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1690
1691 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001692 auto SPIRVIntrinsic = clspv::UnpackFunction();
SJW2c317da2020-03-23 07:39:13 -05001693
1694 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1695
1696 Value *V = nullptr;
1697
alan-baker7efcaaa2020-05-06 19:33:27 -04001698 bool supports_16bit_storage = true;
1699 switch (Arg1->getType()->getPointerAddressSpace()) {
1700 case clspv::AddressSpace::Global:
1701 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1702 clspv::Option::StorageClass::kSSBO);
1703 break;
1704 case clspv::AddressSpace::Constant:
1705 if (clspv::Option::ConstantArgsInUniformBuffer())
1706 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1707 clspv::Option::StorageClass::kUBO);
1708 else
1709 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1710 clspv::Option::StorageClass::kSSBO);
1711 break;
1712 default:
1713 // Clspv will emit the Float16 capability if the half type is
1714 // encountered. That capability covers private and local addressspaces.
1715 break;
1716 }
1717
1718 if (supports_16bit_storage) {
SJW2c317da2020-03-23 07:39:13 -05001719 auto ShortTy = Type::getInt16Ty(M.getContext());
1720 auto ShortPointerTy =
1721 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1722
1723 // Cast the half* pointer to short*.
1724 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1725
1726 // Index into the correct address of the casted pointer.
1727 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1728
1729 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001730 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001731
1732 // ZExt the short -> int.
1733 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1734
1735 // Get our float2.
1736 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1737
1738 // Extract out the bottom element which is our float result.
1739 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1740 } else {
1741 // Assume the pointer argument points to storage aligned to 32bits
1742 // or more.
1743 // TODO(dneto): Do more analysis to make sure this is true?
1744 //
1745 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1746 // with:
1747 //
1748 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1749 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1750 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1751 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1752 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1753 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1754 // x float> %converted, %index_is_odd32
1755
1756 auto IntPointerTy =
1757 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1758
1759 // Cast the base pointer to int*.
1760 // In a valid call (according to assumptions), this should get
1761 // optimized away in the simplify GEP pass.
1762 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1763
1764 auto One = ConstantInt::get(IntTy, 1);
1765 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1766 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1767
1768 // Index into the correct address of the casted pointer.
1769 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1770
1771 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001772 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001773
1774 // Get our float2.
1775 auto Call = CallInst::Create(NewF, Load, "", CI);
1776
1777 // Extract out the float result, where the element number is
1778 // determined by whether the original index was even or odd.
1779 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1780 }
1781 return V;
1782 });
1783}
1784
1785bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1786 Module &M = *F.getParent();
1787 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001788 // The index argument from vload_half.
1789 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001790
Kévin Petite8edce32019-04-10 14:23:32 +01001791 // The pointer argument from vload_half.
1792 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001793
Kévin Petite8edce32019-04-10 14:23:32 +01001794 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001795 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001796 auto NewPointerTy =
1797 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001798 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001799
Kévin Petite8edce32019-04-10 14:23:32 +01001800 // Cast the half* pointer to int*.
1801 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001802
Kévin Petite8edce32019-04-10 14:23:32 +01001803 // Index into the correct address of the casted pointer.
1804 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001805
Kévin Petite8edce32019-04-10 14:23:32 +01001806 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001807 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001808
Kévin Petite8edce32019-04-10 14:23:32 +01001809 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001810 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001811
Kévin Petite8edce32019-04-10 14:23:32 +01001812 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001813
Kévin Petite8edce32019-04-10 14:23:32 +01001814 // Get our float2.
1815 return CallInst::Create(NewF, Load, "", CI);
1816 });
David Neto22f144c2017-06-12 14:26:21 -04001817}
1818
SJW2c317da2020-03-23 07:39:13 -05001819bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1820 Module &M = *F.getParent();
1821 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001822 // The index argument from vload_half.
1823 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001824
Kévin Petite8edce32019-04-10 14:23:32 +01001825 // The pointer argument from vload_half.
1826 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001827
Kévin Petite8edce32019-04-10 14:23:32 +01001828 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001829 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1830 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001831 auto NewPointerTy =
1832 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001833 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001834
Kévin Petite8edce32019-04-10 14:23:32 +01001835 // Cast the half* pointer to int2*.
1836 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001837
Kévin Petite8edce32019-04-10 14:23:32 +01001838 // Index into the correct address of the casted pointer.
1839 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001840
Kévin Petite8edce32019-04-10 14:23:32 +01001841 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001842 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001843
Kévin Petite8edce32019-04-10 14:23:32 +01001844 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001845 auto X =
1846 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1847 auto Y =
1848 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001849
Kévin Petite8edce32019-04-10 14:23:32 +01001850 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001851 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001852
Kévin Petite8edce32019-04-10 14:23:32 +01001853 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001854
Kévin Petite8edce32019-04-10 14:23:32 +01001855 // Get the lower (x & y) components of our final float4.
1856 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001857
Kévin Petite8edce32019-04-10 14:23:32 +01001858 // Get the higher (z & w) components of our final float4.
1859 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001860
Kévin Petite8edce32019-04-10 14:23:32 +01001861 Constant *ShuffleMask[4] = {
1862 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1863 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001864
Kévin Petite8edce32019-04-10 14:23:32 +01001865 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001866 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1867 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001868 });
David Neto22f144c2017-06-12 14:26:21 -04001869}
1870
SJW2c317da2020-03-23 07:39:13 -05001871bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001872
1873 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1874 //
1875 // %u = load i32 %ptr
1876 // %fxy = call <2 x float> Unpack2xHalf(u)
1877 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001878 Module &M = *F.getParent();
1879 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001880 auto Index = CI->getOperand(0);
1881 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001882
Kévin Petite8edce32019-04-10 14:23:32 +01001883 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001884 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001885 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001886
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001887 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001888 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001889
Kévin Petite8edce32019-04-10 14:23:32 +01001890 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001891 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001892
Kévin Petite8edce32019-04-10 14:23:32 +01001893 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001894
Kévin Petite8edce32019-04-10 14:23:32 +01001895 // Get our final float2.
1896 return CallInst::Create(NewF, Load, "", CI);
1897 });
David Neto6ad93232018-06-07 15:42:58 -07001898}
1899
SJW2c317da2020-03-23 07:39:13 -05001900bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001901
1902 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1903 //
1904 // %u2 = load <2 x i32> %ptr
1905 // %u2xy = extractelement %u2, 0
1906 // %u2zw = extractelement %u2, 1
1907 // %fxy = call <2 x float> Unpack2xHalf(uint)
1908 // %fzw = call <2 x float> Unpack2xHalf(uint)
1909 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001910 Module &M = *F.getParent();
1911 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001912 auto Index = CI->getOperand(0);
1913 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001914
Kévin Petite8edce32019-04-10 14:23:32 +01001915 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001916 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1917 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001918 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001919
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001920 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001921 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001922
Kévin Petite8edce32019-04-10 14:23:32 +01001923 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001924 auto X =
1925 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1926 auto Y =
1927 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001928
Kévin Petite8edce32019-04-10 14:23:32 +01001929 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001930 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001931
Kévin Petite8edce32019-04-10 14:23:32 +01001932 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001933
Kévin Petite8edce32019-04-10 14:23:32 +01001934 // Get the lower (x & y) components of our final float4.
1935 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001936
Kévin Petite8edce32019-04-10 14:23:32 +01001937 // Get the higher (z & w) components of our final float4.
1938 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001939
Kévin Petite8edce32019-04-10 14:23:32 +01001940 Constant *ShuffleMask[4] = {
1941 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1942 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001943
Kévin Petite8edce32019-04-10 14:23:32 +01001944 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001945 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1946 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001947 });
David Neto6ad93232018-06-07 15:42:58 -07001948}
1949
SJW2c317da2020-03-23 07:39:13 -05001950bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1951 switch (vec_size) {
1952 case 0:
1953 return replaceVstoreHalf(F);
1954 case 2:
1955 return replaceVstoreHalf2(F);
1956 case 4:
1957 return replaceVstoreHalf4(F);
1958 default:
1959 llvm_unreachable("Unsupported vstore_half vector size");
1960 break;
1961 }
1962 return false;
1963}
David Neto22f144c2017-06-12 14:26:21 -04001964
SJW2c317da2020-03-23 07:39:13 -05001965bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1966 Module &M = *F.getParent();
1967 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001968 // The value to store.
1969 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001970
Kévin Petite8edce32019-04-10 14:23:32 +01001971 // The index argument from vstore_half.
1972 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001973
Kévin Petite8edce32019-04-10 14:23:32 +01001974 // The pointer argument from vstore_half.
1975 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001976
Kévin Petite8edce32019-04-10 14:23:32 +01001977 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001978 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001979 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1980 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001981
Kévin Petite8edce32019-04-10 14:23:32 +01001982 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001983 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001984
Kévin Petite8edce32019-04-10 14:23:32 +01001985 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001986
Kévin Petite8edce32019-04-10 14:23:32 +01001987 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001988 auto TempVec = InsertElementInst::Create(
1989 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001990
Kévin Petite8edce32019-04-10 14:23:32 +01001991 // Pack the float2 -> half2 (in an int).
1992 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001993
alan-baker7efcaaa2020-05-06 19:33:27 -04001994 bool supports_16bit_storage = true;
1995 switch (Arg2->getType()->getPointerAddressSpace()) {
1996 case clspv::AddressSpace::Global:
1997 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1998 clspv::Option::StorageClass::kSSBO);
1999 break;
2000 case clspv::AddressSpace::Constant:
2001 if (clspv::Option::ConstantArgsInUniformBuffer())
2002 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2003 clspv::Option::StorageClass::kUBO);
2004 else
2005 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2006 clspv::Option::StorageClass::kSSBO);
2007 break;
2008 default:
2009 // Clspv will emit the Float16 capability if the half type is
2010 // encountered. That capability covers private and local addressspaces.
2011 break;
2012 }
2013
SJW2c317da2020-03-23 07:39:13 -05002014 Value *V = nullptr;
alan-baker7efcaaa2020-05-06 19:33:27 -04002015 if (supports_16bit_storage) {
Kévin Petite8edce32019-04-10 14:23:32 +01002016 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002017 auto ShortPointerTy =
2018 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002019
Kévin Petite8edce32019-04-10 14:23:32 +01002020 // Truncate our i32 to an i16.
2021 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002022
Kévin Petite8edce32019-04-10 14:23:32 +01002023 // Cast the half* pointer to short*.
2024 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002025
Kévin Petite8edce32019-04-10 14:23:32 +01002026 // Index into the correct address of the casted pointer.
2027 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002028
Kévin Petite8edce32019-04-10 14:23:32 +01002029 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05002030 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002031 } else {
2032 // We can only write to 32-bit aligned words.
2033 //
2034 // Assuming base is aligned to 32-bits, replace the equivalent of
2035 // vstore_half(value, index, base)
2036 // with:
2037 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
2038 // uint32_t write_to_upper_half = index & 1u;
2039 // uint32_t shift = write_to_upper_half << 4;
2040 //
2041 // // Pack the float value as a half number in bottom 16 bits
2042 // // of an i32.
2043 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
2044 //
2045 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
2046 // ^ ((packed & 0xffff) << shift)
2047 // // We only need relaxed consistency, but OpenCL 1.2 only has
2048 // // sequentially consistent atomics.
2049 // // TODO(dneto): Use relaxed consistency.
2050 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002051 auto IntPointerTy =
2052 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002053
Kévin Petite8edce32019-04-10 14:23:32 +01002054 auto Four = ConstantInt::get(IntTy, 4);
2055 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04002056
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002057 auto IndexIsOdd =
2058 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002059 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002060 auto IndexIntoI32 =
2061 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
2062 auto BaseI32Ptr =
2063 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
2064 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
2065 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04002066 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002067 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002068 auto MaskBitsToWrite =
2069 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
2070 auto MaskedCurrent = BinaryOperator::CreateAnd(
2071 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04002072
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002073 auto XLowerBits =
2074 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
2075 auto NewBitsToWrite =
2076 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
2077 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
2078 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04002079
Kévin Petite8edce32019-04-10 14:23:32 +01002080 // Generate the call to atomi_xor.
2081 SmallVector<Type *, 5> ParamTypes;
2082 // The pointer type.
2083 ParamTypes.push_back(IntPointerTy);
2084 // The Types for memory scope, semantics, and value.
2085 ParamTypes.push_back(IntTy);
2086 ParamTypes.push_back(IntTy);
2087 ParamTypes.push_back(IntTy);
2088 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
2089 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04002090
Kévin Petite8edce32019-04-10 14:23:32 +01002091 const auto ConstantScopeDevice =
2092 ConstantInt::get(IntTy, spv::ScopeDevice);
2093 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
2094 // (SPIR-V Workgroup).
2095 const auto AddrSpaceSemanticsBits =
2096 IntPointerTy->getPointerAddressSpace() == 1
2097 ? spv::MemorySemanticsUniformMemoryMask
2098 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04002099
Kévin Petite8edce32019-04-10 14:23:32 +01002100 // We're using relaxed consistency here.
2101 const auto ConstantMemorySemantics =
2102 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
2103 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04002104
Kévin Petite8edce32019-04-10 14:23:32 +01002105 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
2106 ConstantMemorySemantics, ValueToXor};
2107 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05002108
2109 // Return a Nop so the old Call is removed
2110 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
2111 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002112 }
David Neto22f144c2017-06-12 14:26:21 -04002113
SJW2c317da2020-03-23 07:39:13 -05002114 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01002115 });
David Neto22f144c2017-06-12 14:26:21 -04002116}
2117
SJW2c317da2020-03-23 07:39:13 -05002118bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
2119 Module &M = *F.getParent();
2120 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002121 // The value to store.
2122 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002123
Kévin Petite8edce32019-04-10 14:23:32 +01002124 // The index argument from vstore_half.
2125 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002126
Kévin Petite8edce32019-04-10 14:23:32 +01002127 // The pointer argument from vstore_half.
2128 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002129
Kévin Petite8edce32019-04-10 14:23:32 +01002130 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002131 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002132 auto NewPointerTy =
2133 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002134 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002135
Kévin Petite8edce32019-04-10 14:23:32 +01002136 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002137 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002138
Kévin Petite8edce32019-04-10 14:23:32 +01002139 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002140
Kévin Petite8edce32019-04-10 14:23:32 +01002141 // Turn the packed x & y into the final packing.
2142 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002143
Kévin Petite8edce32019-04-10 14:23:32 +01002144 // Cast the half* pointer to int*.
2145 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002146
Kévin Petite8edce32019-04-10 14:23:32 +01002147 // Index into the correct address of the casted pointer.
2148 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002149
Kévin Petite8edce32019-04-10 14:23:32 +01002150 // Store to the int* we casted to.
2151 return new StoreInst(X, Index, CI);
2152 });
David Neto22f144c2017-06-12 14:26:21 -04002153}
2154
SJW2c317da2020-03-23 07:39:13 -05002155bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
2156 Module &M = *F.getParent();
2157 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002158 // The value to store.
2159 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002160
Kévin Petite8edce32019-04-10 14:23:32 +01002161 // The index argument from vstore_half.
2162 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002163
Kévin Petite8edce32019-04-10 14:23:32 +01002164 // The pointer argument from vstore_half.
2165 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002166
Kévin Petite8edce32019-04-10 14:23:32 +01002167 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002168 auto Int2Ty = FixedVectorType::get(IntTy, 2);
2169 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002170 auto NewPointerTy =
2171 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002172 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002173
Kévin Petite8edce32019-04-10 14:23:32 +01002174 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
2175 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04002176
Kévin Petite8edce32019-04-10 14:23:32 +01002177 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002178 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2179 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002180
Kévin Petite8edce32019-04-10 14:23:32 +01002181 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
2182 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002183
Kévin Petite8edce32019-04-10 14:23:32 +01002184 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002185 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2186 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002187
Kévin Petite8edce32019-04-10 14:23:32 +01002188 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002189 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002190
Kévin Petite8edce32019-04-10 14:23:32 +01002191 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002192
Kévin Petite8edce32019-04-10 14:23:32 +01002193 // Turn the packed x & y into the final component of our int2.
2194 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002195
Kévin Petite8edce32019-04-10 14:23:32 +01002196 // Turn the packed z & w into the final component of our int2.
2197 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002198
Kévin Petite8edce32019-04-10 14:23:32 +01002199 auto Combine = InsertElementInst::Create(
2200 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002201 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
2202 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002203
Kévin Petite8edce32019-04-10 14:23:32 +01002204 // Cast the half* pointer to int2*.
2205 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002206
Kévin Petite8edce32019-04-10 14:23:32 +01002207 // Index into the correct address of the casted pointer.
2208 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002209
Kévin Petite8edce32019-04-10 14:23:32 +01002210 // Store to the int2* we casted to.
2211 return new StoreInst(Combine, Index, CI);
2212 });
David Neto22f144c2017-06-12 14:26:21 -04002213}
2214
SJW2c317da2020-03-23 07:39:13 -05002215bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
2216 // convert half to float
2217 Module &M = *F.getParent();
2218 return replaceCallsWithValue(F, [&](CallInst *CI) {
2219 SmallVector<Type *, 3> types;
2220 SmallVector<Value *, 3> args;
2221 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
2222 types.push_back(CI->getArgOperand(i)->getType());
2223 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05002224 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05002225
alan-baker5a8c3be2020-09-09 13:44:26 -04002226 auto NewFType =
2227 FunctionType::get(FixedVectorType::get(Type::getFloatTy(M.getContext()),
2228 cast<VectorType>(CI->getType())
2229 ->getElementCount()
2230 .getKnownMinValue()),
2231 types, false);
SJW2c317da2020-03-23 07:39:13 -05002232
SJW61531372020-06-09 07:31:08 -05002233 std::string NewFName =
2234 Builtins::GetMangledFunctionName("read_imagef", NewFType);
SJW2c317da2020-03-23 07:39:13 -05002235
2236 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2237
2238 auto NewCI = CallInst::Create(NewF, args, "", CI);
2239
2240 // Convert to the half type.
2241 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2242 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002243}
2244
SJW2c317da2020-03-23 07:39:13 -05002245bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
2246 // convert half to float
2247 Module &M = *F.getParent();
2248 return replaceCallsWithValue(F, [&](CallInst *CI) {
2249 SmallVector<Type *, 3> types(3);
2250 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002251
SJW2c317da2020-03-23 07:39:13 -05002252 // Image
2253 types[0] = CI->getArgOperand(0)->getType();
2254 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002255
SJW2c317da2020-03-23 07:39:13 -05002256 // Coord
2257 types[1] = CI->getArgOperand(1)->getType();
2258 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002259
SJW2c317da2020-03-23 07:39:13 -05002260 // Data
alan-baker5a8c3be2020-09-09 13:44:26 -04002261 types[2] =
2262 FixedVectorType::get(Type::getFloatTy(M.getContext()),
2263 cast<VectorType>(CI->getArgOperand(2)->getType())
2264 ->getElementCount()
2265 .getKnownMinValue());
alan-bakerf7e17cb2020-01-02 07:29:59 -05002266
SJW2c317da2020-03-23 07:39:13 -05002267 auto NewFType =
2268 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002269
SJW61531372020-06-09 07:31:08 -05002270 std::string NewFName =
2271 Builtins::GetMangledFunctionName("write_imagef", NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002272
SJW2c317da2020-03-23 07:39:13 -05002273 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002274
SJW2c317da2020-03-23 07:39:13 -05002275 // Convert data to the float type.
2276 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2277 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002278
SJW2c317da2020-03-23 07:39:13 -05002279 return CallInst::Create(NewF, args, "", CI);
2280 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002281}
2282
SJW2c317da2020-03-23 07:39:13 -05002283bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2284 Function &F) {
2285 // convert read_image with int coords to float coords
2286 Module &M = *F.getParent();
2287 return replaceCallsWithValue(F, [&](CallInst *CI) {
2288 // The image.
2289 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002290
SJW2c317da2020-03-23 07:39:13 -05002291 // The sampler.
2292 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002293
SJW2c317da2020-03-23 07:39:13 -05002294 // The coordinate (integer type that we can't handle).
2295 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002296
SJW2c317da2020-03-23 07:39:13 -05002297 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2298 uint32_t components =
2299 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2300 Type *float_ty = nullptr;
2301 if (components == 1) {
2302 float_ty = Type::getFloatTy(M.getContext());
2303 } else {
alan-baker5a8c3be2020-09-09 13:44:26 -04002304 float_ty = FixedVectorType::get(Type::getFloatTy(M.getContext()),
2305 cast<VectorType>(Arg2->getType())
2306 ->getElementCount()
2307 .getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04002308 }
David Neto22f144c2017-06-12 14:26:21 -04002309
SJW2c317da2020-03-23 07:39:13 -05002310 auto NewFType = FunctionType::get(
2311 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2312
2313 std::string NewFName = F.getName().str();
2314 NewFName[NewFName.length() - 1] = 'f';
2315
2316 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2317
2318 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2319
2320 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2321 });
David Neto22f144c2017-06-12 14:26:21 -04002322}
2323
SJW2c317da2020-03-23 07:39:13 -05002324bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2325 return replaceCallsWithValue(F, [&](CallInst *CI) {
2326 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002327
SJW2c317da2020-03-23 07:39:13 -05002328 // We need to map the OpenCL constants to the SPIR-V equivalents.
2329 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2330 const auto ConstantMemorySemantics = ConstantInt::get(
2331 IntTy, spv::MemorySemanticsUniformMemoryMask |
2332 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002333
SJW2c317da2020-03-23 07:39:13 -05002334 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002335
SJW2c317da2020-03-23 07:39:13 -05002336 // The pointer.
2337 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002338
SJW2c317da2020-03-23 07:39:13 -05002339 // The memory scope.
2340 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002341
SJW2c317da2020-03-23 07:39:13 -05002342 // The memory semantics.
2343 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002344
SJW2c317da2020-03-23 07:39:13 -05002345 if (2 < CI->getNumArgOperands()) {
2346 // The unequal memory semantics.
2347 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002348
SJW2c317da2020-03-23 07:39:13 -05002349 // The value.
2350 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002351
SJW2c317da2020-03-23 07:39:13 -05002352 // The comparator.
2353 Params.push_back(CI->getArgOperand(1));
2354 } else if (1 < CI->getNumArgOperands()) {
2355 // The value.
2356 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002357 }
David Neto22f144c2017-06-12 14:26:21 -04002358
SJW2c317da2020-03-23 07:39:13 -05002359 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2360 });
David Neto22f144c2017-06-12 14:26:21 -04002361}
2362
SJW2c317da2020-03-23 07:39:13 -05002363bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2364 llvm::AtomicRMWInst::BinOp Op) {
2365 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerd0eb9052020-07-07 13:12:01 -04002366 auto align = F.getParent()->getDataLayout().getABITypeAlign(
2367 CI->getArgOperand(1)->getType());
SJW2c317da2020-03-23 07:39:13 -05002368 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
alan-bakerd0eb9052020-07-07 13:12:01 -04002369 align, AtomicOrdering::SequentiallyConsistent,
SJW2c317da2020-03-23 07:39:13 -05002370 SyncScope::System, CI);
2371 });
2372}
David Neto22f144c2017-06-12 14:26:21 -04002373
SJW2c317da2020-03-23 07:39:13 -05002374bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2375 Module &M = *F.getParent();
2376 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002377 auto IntTy = Type::getInt32Ty(M.getContext());
2378 auto FloatTy = Type::getFloatTy(M.getContext());
2379
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002380 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2381 ConstantInt::get(IntTy, 1),
2382 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002383
2384 Constant *UpShuffleMask[4] = {
2385 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2386 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2387
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002388 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2389 UndefValue::get(FloatTy),
2390 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002391
Kévin Petite8edce32019-04-10 14:23:32 +01002392 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002393 auto Arg0 =
2394 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2395 ConstantVector::get(DownShuffleMask), "", CI);
2396 auto Arg1 =
2397 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2398 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002399 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002400
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002401 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
SJW61531372020-06-09 07:31:08 -05002402 auto NewFName = Builtins::GetMangledFunctionName("cross", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002403
SJW61531372020-06-09 07:31:08 -05002404 auto Cross3Func = M.getOrInsertFunction(NewFName, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002405
Kévin Petite8edce32019-04-10 14:23:32 +01002406 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002407
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002408 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2409 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002410 });
David Neto22f144c2017-06-12 14:26:21 -04002411}
David Neto62653202017-10-16 19:05:18 -04002412
SJW2c317da2020-03-23 07:39:13 -05002413bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002414 // OpenCL's float result = fract(float x, float* ptr)
2415 //
2416 // In the LLVM domain:
2417 //
2418 // %floor_result = call spir_func float @floor(float %x)
2419 // store float %floor_result, float * %ptr
2420 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2421 // %result = call spir_func float
2422 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2423 //
2424 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2425 // and clspv.fract occur in the SPIR-V generator pass:
2426 //
2427 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2428 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2429 // ...
2430 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2431 // OpStore %ptr %floor_result
2432 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2433 // %fract_result = OpExtInst %float
Marco Antognini55d51862020-07-21 17:50:07 +01002434 // %glsl_ext Nmin %fract_intermediate %just_under_1
David Neto62653202017-10-16 19:05:18 -04002435
David Neto62653202017-10-16 19:05:18 -04002436 using std::string;
2437
2438 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2439 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002440
SJW2c317da2020-03-23 07:39:13 -05002441 Module &M = *F.getParent();
2442 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto62653202017-10-16 19:05:18 -04002443
SJW2c317da2020-03-23 07:39:13 -05002444 // This is either float or a float vector. All the float-like
2445 // types are this type.
2446 auto result_ty = F.getReturnType();
2447
SJW61531372020-06-09 07:31:08 -05002448 std::string fmin_name = Builtins::GetMangledFunctionName("fmin", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002449 Function *fmin_fn = M.getFunction(fmin_name);
2450 if (!fmin_fn) {
2451 // Make the fmin function.
2452 FunctionType *fn_ty =
2453 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2454 fmin_fn =
2455 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2456 fmin_fn->addFnAttr(Attribute::ReadNone);
2457 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2458 }
2459
SJW61531372020-06-09 07:31:08 -05002460 std::string floor_name =
2461 Builtins::GetMangledFunctionName("floor", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002462 Function *floor_fn = M.getFunction(floor_name);
2463 if (!floor_fn) {
2464 // Make the floor function.
2465 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2466 floor_fn =
2467 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2468 floor_fn->addFnAttr(Attribute::ReadNone);
2469 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2470 }
2471
SJW61531372020-06-09 07:31:08 -05002472 std::string clspv_fract_name =
2473 Builtins::GetMangledFunctionName("clspv.fract", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002474 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2475 if (!clspv_fract_fn) {
2476 // Make the clspv_fract function.
2477 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2478 clspv_fract_fn = cast<Function>(
2479 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2480 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2481 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2482 }
2483
2484 // Number of significant significand bits, whether represented or not.
2485 unsigned num_significand_bits;
2486 switch (result_ty->getScalarType()->getTypeID()) {
2487 case Type::HalfTyID:
2488 num_significand_bits = 11;
2489 break;
2490 case Type::FloatTyID:
2491 num_significand_bits = 24;
2492 break;
2493 case Type::DoubleTyID:
2494 num_significand_bits = 53;
2495 break;
2496 default:
2497 llvm_unreachable("Unhandled float type when processing fract builtin");
2498 break;
2499 }
2500 // Beware that the disassembler displays this value as
2501 // OpConstant %float 1
2502 // which is not quite right.
2503 const double kJustUnderOneScalar =
2504 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2505
2506 Constant *just_under_one =
2507 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2508 if (result_ty->isVectorTy()) {
2509 just_under_one = ConstantVector::getSplat(
alan-baker931253b2020-08-20 17:15:38 -04002510 cast<VectorType>(result_ty)->getElementCount(), just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002511 }
2512
2513 IRBuilder<> Builder(CI);
2514
2515 auto arg = CI->getArgOperand(0);
2516 auto ptr = CI->getArgOperand(1);
2517
2518 // Compute floor result and store it.
2519 auto floor = Builder.CreateCall(floor_fn, {arg});
2520 Builder.CreateStore(floor, ptr);
2521
2522 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2523 auto fract_result =
2524 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2525
2526 return fract_result;
2527 });
David Neto62653202017-10-16 19:05:18 -04002528}
alan-bakera52b7312020-10-26 08:58:51 -04002529
alan-bakerb6da5132020-10-29 15:59:06 -04002530bool ReplaceOpenCLBuiltinPass::replaceHadd(Function &F,
2531 Instruction::BinaryOps join_opcode) {
2532 return replaceCallsWithValue(F, [join_opcode](CallInst *Call) {
2533 // a_shr = a >> 1
2534 // b_shr = b >> 1
2535 // add1 = a_shr + b_shr
2536 // join = a |join_opcode| b
2537 // and = join & 1
2538 // add = add1 + and
2539 const auto a = Call->getArgOperand(0);
2540 const auto b = Call->getArgOperand(1);
2541 IRBuilder<> builder(Call);
2542 auto a_shift = builder.CreateLShr(a, 1);
2543 auto b_shift = builder.CreateLShr(b, 1);
2544 auto add = builder.CreateAdd(a_shift, b_shift);
2545 auto join = BinaryOperator::Create(join_opcode, a, b, "", Call);
2546 auto constant_one = ConstantInt::get(a->getType(), 1);
2547 auto and_bit = builder.CreateAnd(join, constant_one);
2548 return builder.CreateAdd(add, and_bit);
2549 });
2550}
2551
alan-bakera52b7312020-10-26 08:58:51 -04002552bool ReplaceOpenCLBuiltinPass::replaceAddSat(Function &F, bool is_signed) {
2553 Module *module = F.getParent();
2554 return replaceCallsWithValue(F, [&module, is_signed](CallInst *Call) {
2555 // SPIR-V OpIAddCarry interprets inputs as unsigned. We use that
2556 // instruction for unsigned additions. For signed addition, it is more
2557 // complicated. For values with bit widths less than 32 bits, we extend
2558 // to the next power of two and perform the addition. For 32- and
2559 // 64-bit values we test the signedness of op1 to determine how to clamp
2560 // the addition.
2561 Type *ty = Call->getType();
2562 Value *op0 = Call->getArgOperand(0);
2563 Value *op1 = Call->getArgOperand(1);
2564 Value *result = nullptr;
2565 if (is_signed) {
2566 unsigned bitwidth = ty->getScalarSizeInBits();
2567 if (bitwidth < 32) {
2568 // sext_op0 = sext op0
2569 // sext_op1 = sext op1
2570 // add = add sext_op0 sext_op1
2571 // clamp = clamp(add, min, max)
2572 // result = trunc clamp
2573 unsigned extended_bits = static_cast<unsigned>(bitwidth << 1);
2574 // The clamp values are the signed min and max of the original bitwidth
2575 // sign extended to the extended bitwidth.
2576 Constant *scalar_min = ConstantInt::get(
2577 Call->getContext(),
2578 APInt::getSignedMinValue(bitwidth).sext(extended_bits));
2579 Constant *scalar_max = ConstantInt::get(
2580 Call->getContext(),
2581 APInt::getSignedMaxValue(bitwidth).sext(extended_bits));
2582 Constant *min = scalar_min;
2583 Constant *max = scalar_max;
2584 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2585 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2586 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2587 }
2588 Type *extended_scalar_ty =
2589 IntegerType::get(Call->getContext(), extended_bits);
2590 Type *extended_ty = extended_scalar_ty;
2591 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2592 extended_ty =
2593 VectorType::get(extended_scalar_ty, vec_ty->getElementCount());
2594 }
2595 auto sext_op0 =
2596 CastInst::Create(Instruction::SExt, op0, extended_ty, "", Call);
2597 auto sext_op1 =
2598 CastInst::Create(Instruction::SExt, op1, extended_ty, "", Call);
2599 // Add the nsw flag since we know no overflow can occur.
2600 auto add = BinaryOperator::CreateNSW(Instruction::Add, sext_op0,
2601 sext_op1, "", Call);
2602 FunctionType *func_ty = FunctionType::get(
2603 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2604
2605 // Don't use the type in GetMangledFunctionName to ensure we get
2606 // signed parameters.
2607 std::string sclamp_name = Builtins::GetMangledFunctionName("clamp");
2608 uint32_t vec_width = 1;
2609 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2610 vec_width = vec_ty->getElementCount().getKnownMinValue();
2611 }
2612 if (extended_bits == 32) {
2613 if (vec_width == 1) {
2614 sclamp_name += "iii";
2615 } else {
2616 sclamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
2617 }
2618 } else {
2619 if (vec_width == 1) {
2620 sclamp_name += "sss";
2621 } else {
2622 sclamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2623 }
2624 }
2625 auto sclamp_callee = module->getOrInsertFunction(sclamp_name, func_ty);
2626 auto clamp = CallInst::Create(sclamp_callee, {add, min, max}, "", Call);
2627 result = CastInst::Create(Instruction::Trunc, clamp, ty, "", Call);
2628 } else {
2629 // Pseudo-code:
2630 // c = a + b;
2631 // if (b < 0)
2632 // c = c > a ? min : c;
2633 // else
2634 // c = c < a ? max : c;
2635 //
2636 unsigned bitwidth = ty->getScalarSizeInBits();
2637 Constant *scalar_min = ConstantInt::get(
2638 Call->getContext(), APInt::getSignedMinValue(bitwidth));
2639 Constant *scalar_max = ConstantInt::get(
2640 Call->getContext(), APInt::getSignedMaxValue(bitwidth));
2641 Constant *min = scalar_min;
2642 Constant *max = scalar_max;
2643 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2644 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2645 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2646 }
2647 auto zero = Constant::getNullValue(ty);
2648 // Cannot add the nsw flag.
2649 auto add = BinaryOperator::Create(Instruction::Add, op0, op1, "", Call);
2650 auto add_gt_op0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SGT,
2651 add, op0, "", Call);
2652 auto min_clamp = SelectInst::Create(add_gt_op0, min, add, "", Call);
2653 auto add_lt_op0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
2654 add, op0, "", Call);
2655 auto max_clamp = SelectInst::Create(add_lt_op0, max, add, "", Call);
2656 auto op1_lt_0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
2657 op1, zero, "", Call);
2658 result = SelectInst::Create(op1_lt_0, min_clamp, max_clamp, "", Call);
2659 }
2660 } else {
2661 // Just use OpIAddCarry and use the carry to clamp the result.
2662 auto ret_ty = StructType::get(Call->getContext(), {ty, ty});
2663 auto add = clspv::InsertSPIRVOp(
2664 Call, spv::OpIAddCarry, {Attribute::ReadNone}, ret_ty, {op0, op1});
2665 auto ex0 = ExtractValueInst::Create(add, {0}, "", Call);
2666 auto ex1 = ExtractValueInst::Create(add, {1}, "", Call);
2667 auto cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, ex1,
2668 Constant::getNullValue(ty), "", Call);
2669 result =
2670 SelectInst::Create(cmp, ex0, Constant::getAllOnesValue(ty), "", Call);
2671 }
2672
2673 return result;
2674 });
2675}
alan-baker4986eff2020-10-29 13:38:00 -04002676
2677bool ReplaceOpenCLBuiltinPass::replaceAtomicLoad(Function &F) {
2678 return replaceCallsWithValue(F, [](CallInst *Call) {
2679 auto pointer = Call->getArgOperand(0);
2680 // Clang emits an address space cast to the generic address space. Skip the
2681 // cast and use the input directly.
2682 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2683 pointer = cast->getPointerOperand();
2684 }
2685 Value *order_arg =
2686 Call->getNumArgOperands() > 1 ? Call->getArgOperand(1) : nullptr;
2687 Value *scope_arg =
2688 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2689 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2690 clspv::AddressSpace::Global;
2691 auto order = MemoryOrderSemantics(order_arg, is_global, Call,
2692 spv::MemorySemanticsAcquireMask);
2693 auto scope = MemoryScope(scope_arg, is_global, Call);
2694 return InsertSPIRVOp(Call, spv::OpAtomicLoad, {Attribute::Convergent},
2695 Call->getType(), {pointer, scope, order});
2696 });
2697}
2698
2699bool ReplaceOpenCLBuiltinPass::replaceExplicitAtomics(
2700 Function &F, spv::Op Op, spv::MemorySemanticsMask semantics) {
2701 return replaceCallsWithValue(F, [Op, semantics](CallInst *Call) {
2702 auto pointer = Call->getArgOperand(0);
2703 // Clang emits an address space cast to the generic address space. Skip the
2704 // cast and use the input directly.
2705 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2706 pointer = cast->getPointerOperand();
2707 }
2708 Value *value = Call->getArgOperand(1);
2709 Value *order_arg =
2710 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2711 Value *scope_arg =
2712 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2713 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2714 clspv::AddressSpace::Global;
2715 auto scope = MemoryScope(scope_arg, is_global, Call);
2716 auto order = MemoryOrderSemantics(order_arg, is_global, Call, semantics);
2717 return InsertSPIRVOp(Call, Op, {Attribute::Convergent}, Call->getType(),
2718 {pointer, scope, order, value});
2719 });
2720}
2721
2722bool ReplaceOpenCLBuiltinPass::replaceAtomicCompareExchange(Function &F) {
2723 return replaceCallsWithValue(F, [](CallInst *Call) {
2724 auto pointer = Call->getArgOperand(0);
2725 // Clang emits an address space cast to the generic address space. Skip the
2726 // cast and use the input directly.
2727 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2728 pointer = cast->getPointerOperand();
2729 }
2730 auto expected = Call->getArgOperand(1);
2731 if (auto cast = dyn_cast<AddrSpaceCastOperator>(expected)) {
2732 expected = cast->getPointerOperand();
2733 }
2734 auto value = Call->getArgOperand(2);
2735 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2736 clspv::AddressSpace::Global;
2737 Value *success_arg =
2738 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2739 Value *failure_arg =
2740 Call->getNumArgOperands() > 4 ? Call->getArgOperand(4) : nullptr;
2741 Value *scope_arg =
2742 Call->getNumArgOperands() > 5 ? Call->getArgOperand(5) : nullptr;
2743 auto scope = MemoryScope(scope_arg, is_global, Call);
2744 auto success = MemoryOrderSemantics(success_arg, is_global, Call,
2745 spv::MemorySemanticsAcquireReleaseMask);
2746 auto failure = MemoryOrderSemantics(failure_arg, is_global, Call,
2747 spv::MemorySemanticsAcquireMask);
2748
2749 // If the value pointed to by |expected| equals the value pointed to by
2750 // |pointer|, |value| is written into |pointer|, otherwise the value in
2751 // |pointer| is written into |expected|. In order to avoid extra stores,
2752 // the basic block with the original atomic is split and the store is
2753 // performed in the |then| block. The condition is the inversion of the
2754 // comparison result.
2755 IRBuilder<> builder(Call);
2756 auto load = builder.CreateLoad(expected);
2757 auto cmp_xchg = InsertSPIRVOp(
2758 Call, spv::OpAtomicCompareExchange, {Attribute::Convergent},
2759 value->getType(), {pointer, scope, success, failure, value, load});
2760 auto cmp = builder.CreateICmpEQ(cmp_xchg, load);
2761 auto not_cmp = builder.CreateNot(cmp);
2762 auto then_branch = SplitBlockAndInsertIfThen(not_cmp, Call, false);
2763 builder.SetInsertPoint(then_branch);
2764 builder.CreateStore(cmp_xchg, expected);
2765 return cmp;
2766 });
2767}