blob: c2a025c089af783decd94b20025d8d2c19ac2eb1 [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
alan-bakerfd22ae12020-10-29 15:59:22 -04001190 // Replace with LLVM's funnel shift left intrinsic because it is more
1191 // generic than rotate.
1192 Function *intrinsic =
1193 Intrinsic::getDeclaration(F.getParent(), Intrinsic::fshl, SrcType);
1194 return CallInst::Create(intrinsic->getFunctionType(), intrinsic,
1195 {SrcValue, SrcValue, RotAmount}, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001196 });
Kévin Petitd44eef52019-03-08 13:22:14 +00001197}
1198
SJW2c317da2020-03-23 07:39:13 -05001199bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
1200 bool DstIsSigned) {
1201 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1202 Value *V = nullptr;
1203 // Get arguments
1204 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001205
SJW2c317da2020-03-23 07:39:13 -05001206 // Don't touch overloads that aren't in OpenCL C
1207 auto SrcType = SrcValue->getType();
1208 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001209
SJW2c317da2020-03-23 07:39:13 -05001210 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1211 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1212 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001213 }
1214
James Pricecf53df42020-04-20 14:41:24 -04001215 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001216 unsigned SrcNumElements =
1217 SrcVecType->getElementCount().getKnownMinValue();
1218 unsigned DstNumElements =
1219 cast<VectorType>(DstType)->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001220 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001221 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001222 }
1223
James Pricecf53df42020-04-20 14:41:24 -04001224 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1225 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1226 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001227 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001228 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001229 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001230
SJW2c317da2020-03-23 07:39:13 -05001231 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1232 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1233
1234 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1235 bool DstIsInt = DstType->isIntOrIntVectorTy();
1236
1237 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1238 // Unnecessary cast operation.
1239 V = SrcValue;
1240 } else if (SrcIsFloat && DstIsFloat) {
1241 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1242 } else if (SrcIsFloat && DstIsInt) {
1243 if (DstIsSigned) {
1244 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1245 } else {
1246 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1247 }
1248 } else if (SrcIsInt && DstIsFloat) {
1249 if (SrcIsSigned) {
1250 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1251 } else {
1252 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1253 }
1254 } else if (SrcIsInt && DstIsInt) {
1255 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1256 } else {
1257 // Not something we're supposed to handle, just move on
1258 }
1259
1260 return V;
1261 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001262}
1263
SJW2c317da2020-03-23 07:39:13 -05001264bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1265 bool is_mad) {
1266 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1267 Value *V = nullptr;
1268 // Get arguments
1269 auto AValue = CI->getOperand(0);
1270 auto BValue = CI->getOperand(1);
1271 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001272
SJW2c317da2020-03-23 07:39:13 -05001273 // Don't touch overloads that aren't in OpenCL C
1274 auto AType = AValue->getType();
1275 auto BType = BValue->getType();
1276 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001277
SJW2c317da2020-03-23 07:39:13 -05001278 if ((AType != BType) || (CI->getType() != AType) ||
1279 (is_mad && (AType != CType))) {
1280 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001281 }
1282
SJW2c317da2020-03-23 07:39:13 -05001283 if (!AType->isIntOrIntVectorTy()) {
1284 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001285 }
Kévin Petit8a560882019-03-21 15:24:34 +00001286
SJW2c317da2020-03-23 07:39:13 -05001287 if ((AType->getScalarSizeInBits() != 8) &&
1288 (AType->getScalarSizeInBits() != 16) &&
1289 (AType->getScalarSizeInBits() != 32) &&
1290 (AType->getScalarSizeInBits() != 64)) {
1291 return V;
1292 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001293
James Pricecf53df42020-04-20 14:41:24 -04001294 if (auto AVecType = dyn_cast<VectorType>(AType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001295 unsigned NumElements = AVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001296 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1297 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001298 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001299 }
1300 }
1301
SJW2c317da2020-03-23 07:39:13 -05001302 // Our SPIR-V op returns a struct, create a type for it
1303 SmallVector<Type *, 2> TwoValueType = {AType, AType};
1304 auto ExMulRetType = StructType::create(TwoValueType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001305
SJW2c317da2020-03-23 07:39:13 -05001306 // Select the appropriate signed/unsigned SPIR-V op
1307 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1308
1309 // Call the SPIR-V op
1310 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1311 ExMulRetType, {AValue, BValue});
1312
1313 // Get the high part of the result
1314 unsigned Idxs[] = {1};
1315 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1316
1317 // If we're handling a mad_hi, add the third argument to the result
1318 if (is_mad) {
1319 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001320 }
1321
SJW2c317da2020-03-23 07:39:13 -05001322 return V;
1323 });
Kévin Petit8a560882019-03-21 15:24:34 +00001324}
1325
SJW2c317da2020-03-23 07:39:13 -05001326bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1327 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1328 // Get arguments
1329 auto FalseValue = CI->getOperand(0);
1330 auto TrueValue = CI->getOperand(1);
1331 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001332
SJW2c317da2020-03-23 07:39:13 -05001333 // Don't touch overloads that aren't in OpenCL C
1334 auto FalseType = FalseValue->getType();
1335 auto TrueType = TrueValue->getType();
1336 auto PredicateType = PredicateValue->getType();
1337
1338 if (FalseType != TrueType) {
1339 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001340 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001341
SJW2c317da2020-03-23 07:39:13 -05001342 if (!PredicateType->isIntOrIntVectorTy()) {
1343 return nullptr;
1344 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001345
SJW2c317da2020-03-23 07:39:13 -05001346 if (!FalseType->isIntOrIntVectorTy() &&
1347 !FalseType->getScalarType()->isFloatingPointTy()) {
1348 return nullptr;
1349 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001350
SJW2c317da2020-03-23 07:39:13 -05001351 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1352 return nullptr;
1353 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001354
SJW2c317da2020-03-23 07:39:13 -05001355 if (FalseType->getScalarSizeInBits() !=
1356 PredicateType->getScalarSizeInBits()) {
1357 return nullptr;
1358 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001359
James Pricecf53df42020-04-20 14:41:24 -04001360 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001361 unsigned NumElements = FalseVecType->getElementCount().getKnownMinValue();
1362 if (NumElements != cast<VectorType>(PredicateType)
1363 ->getElementCount()
1364 .getKnownMinValue()) {
SJW2c317da2020-03-23 07:39:13 -05001365 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001366 }
1367
James Pricecf53df42020-04-20 14:41:24 -04001368 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1369 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001370 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001371 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001372 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001373
SJW2c317da2020-03-23 07:39:13 -05001374 // Create constant
1375 const auto ZeroValue = Constant::getNullValue(PredicateType);
1376
1377 // Scalar and vector are to be treated differently
1378 CmpInst::Predicate Pred;
1379 if (PredicateType->isVectorTy()) {
1380 Pred = CmpInst::ICMP_SLT;
1381 } else {
1382 Pred = CmpInst::ICMP_NE;
1383 }
1384
1385 // Create comparison instruction
1386 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1387 ZeroValue, "", CI);
1388
1389 // Create select
1390 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1391 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001392}
1393
SJW2c317da2020-03-23 07:39:13 -05001394bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1395 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1396 Value *V = nullptr;
1397 if (CI->getNumOperands() != 4) {
1398 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001399 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001400
SJW2c317da2020-03-23 07:39:13 -05001401 // Get arguments
1402 auto FalseValue = CI->getOperand(0);
1403 auto TrueValue = CI->getOperand(1);
1404 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001405
SJW2c317da2020-03-23 07:39:13 -05001406 // Don't touch overloads that aren't in OpenCL C
1407 auto FalseType = FalseValue->getType();
1408 auto TrueType = TrueValue->getType();
1409 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001410
SJW2c317da2020-03-23 07:39:13 -05001411 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1412 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001413 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001414
James Pricecf53df42020-04-20 14:41:24 -04001415 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001416 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1417 !TrueType->getScalarType()->isIntegerTy()) {
1418 return V;
1419 }
alan-baker5a8c3be2020-09-09 13:44:26 -04001420 unsigned NumElements = TrueVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001421 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1422 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001423 return V;
1424 }
1425 }
1426
1427 // Remember the type of the operands
1428 auto OpType = TrueType;
1429
1430 // The actual bit selection will always be done on an integer type,
1431 // declare it here
1432 Type *BitType;
1433
1434 // If the operands are float, then bitcast them to int
1435 if (OpType->getScalarType()->isFloatingPointTy()) {
1436
1437 // First create the new type
1438 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1439
1440 // Then bitcast all operands
1441 PredicateValue =
1442 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1443 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1444 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1445
1446 } else {
1447 // The operands have an integer type, use it directly
1448 BitType = OpType;
1449 }
1450
1451 // All the operands are now always integers
1452 // implement as (c & b) | (~c & a)
1453
1454 // Create our negated predicate value
1455 auto AllOnes = Constant::getAllOnesValue(BitType);
1456 auto NotPredicateValue = BinaryOperator::Create(
1457 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1458
1459 // Then put everything together
1460 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1461 FalseValue, "", CI);
1462 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1463 TrueValue, "", CI);
1464
1465 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1466
1467 // If we were dealing with a floating point type, we must bitcast
1468 // the result back to that
1469 if (OpType->getScalarType()->isFloatingPointTy()) {
1470 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1471 }
1472
1473 return V;
1474 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001475}
1476
SJW61531372020-06-09 07:31:08 -05001477bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth) {
SJW2c317da2020-03-23 07:39:13 -05001478 // convert to vector versions
1479 Module &M = *F.getParent();
1480 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1481 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1482 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001483
SJW2c317da2020-03-23 07:39:13 -05001484 // First figure out which function we're dealing with
1485 if (is_smooth) {
1486 ArgsToSplat.push_back(CI->getOperand(1));
1487 VectorArg = CI->getOperand(2);
1488 } else {
1489 VectorArg = CI->getOperand(1);
1490 }
1491
1492 // Splat arguments that need to be
1493 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001494 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001495
1496 for (auto arg : ArgsToSplat) {
1497 Value *NewVectorArg = UndefValue::get(VecType);
alan-baker5a8c3be2020-09-09 13:44:26 -04001498 for (auto i = 0; i < VecType->getElementCount().getKnownMinValue(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001499 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1500 NewVectorArg =
1501 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1502 }
1503 SplatArgs.push_back(NewVectorArg);
1504 }
1505
1506 // Replace the call with the vector/vector flavour
1507 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1508 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1509
SJW61531372020-06-09 07:31:08 -05001510 std::string NewFName = Builtins::GetMangledFunctionName(
1511 is_smooth ? "smoothstep" : "step", NewFType);
1512
SJW2c317da2020-03-23 07:39:13 -05001513 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1514
1515 SmallVector<Value *, 3> NewArgs;
1516 for (auto arg : SplatArgs) {
1517 NewArgs.push_back(arg);
1518 }
1519 NewArgs.push_back(VectorArg);
1520
1521 return CallInst::Create(NewF, NewArgs, "", CI);
1522 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001523}
1524
SJW2c317da2020-03-23 07:39:13 -05001525bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001526 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1527 auto Arg = CI->getOperand(0);
1528 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001529
SJW2c317da2020-03-23 07:39:13 -05001530 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001531
SJW2c317da2020-03-23 07:39:13 -05001532 return BinaryOperator::Create(Op, Bitcast,
1533 ConstantInt::get(CI->getType(), 31), "", CI);
1534 });
David Neto22f144c2017-06-12 14:26:21 -04001535}
1536
SJW2c317da2020-03-23 07:39:13 -05001537bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1538 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001539 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1540 // The multiply instruction to use.
1541 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001542
SJW2c317da2020-03-23 07:39:13 -05001543 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001544
SJW2c317da2020-03-23 07:39:13 -05001545 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1546 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001547
SJW2c317da2020-03-23 07:39:13 -05001548 if (is_mad) {
1549 // The add instruction to use.
1550 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001551
SJW2c317da2020-03-23 07:39:13 -05001552 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001553 }
David Neto22f144c2017-06-12 14:26:21 -04001554
SJW2c317da2020-03-23 07:39:13 -05001555 return V;
1556 });
David Neto22f144c2017-06-12 14:26:21 -04001557}
1558
SJW2c317da2020-03-23 07:39:13 -05001559bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001560 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1561 Value *V = nullptr;
1562 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001563
SJW2c317da2020-03-23 07:39:13 -05001564 auto data_type = data->getType();
1565 if (!data_type->isVectorTy())
1566 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001567
James Pricecf53df42020-04-20 14:41:24 -04001568 auto vec_data_type = cast<VectorType>(data_type);
1569
alan-baker5a8c3be2020-09-09 13:44:26 -04001570 auto elems = vec_data_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001571 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1572 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001573
SJW2c317da2020-03-23 07:39:13 -05001574 auto offset = CI->getOperand(1);
1575 auto ptr = CI->getOperand(2);
1576 auto ptr_type = ptr->getType();
1577 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001578 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001579 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001580
SJW2c317da2020-03-23 07:39:13 -05001581 // Avoid pointer casts. Instead generate the correct number of stores
1582 // and rely on drivers to coalesce appropriately.
1583 IRBuilder<> builder(CI);
1584 auto elems_const = builder.getInt32(elems);
1585 auto adjust = builder.CreateMul(offset, elems_const);
1586 for (auto i = 0; i < elems; ++i) {
1587 auto idx = builder.getInt32(i);
1588 auto add = builder.CreateAdd(adjust, idx);
1589 auto gep = builder.CreateGEP(ptr, add);
1590 auto extract = builder.CreateExtractElement(data, i);
1591 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001592 }
SJW2c317da2020-03-23 07:39:13 -05001593 return V;
1594 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001595}
1596
SJW2c317da2020-03-23 07:39:13 -05001597bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001598 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1599 Value *V = nullptr;
1600 auto ret_type = F.getReturnType();
1601 if (!ret_type->isVectorTy())
1602 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001603
James Pricecf53df42020-04-20 14:41:24 -04001604 auto vec_ret_type = cast<VectorType>(ret_type);
1605
alan-baker5a8c3be2020-09-09 13:44:26 -04001606 auto elems = vec_ret_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001607 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1608 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001609
SJW2c317da2020-03-23 07:39:13 -05001610 auto offset = CI->getOperand(0);
1611 auto ptr = CI->getOperand(1);
1612 auto ptr_type = ptr->getType();
1613 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001614 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001615 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001616
SJW2c317da2020-03-23 07:39:13 -05001617 // Avoid pointer casts. Instead generate the correct number of loads
1618 // and rely on drivers to coalesce appropriately.
1619 IRBuilder<> builder(CI);
1620 auto elems_const = builder.getInt32(elems);
1621 V = UndefValue::get(ret_type);
1622 auto adjust = builder.CreateMul(offset, elems_const);
1623 for (auto i = 0; i < elems; ++i) {
1624 auto idx = builder.getInt32(i);
1625 auto add = builder.CreateAdd(adjust, idx);
1626 auto gep = builder.CreateGEP(ptr, add);
1627 auto load = builder.CreateLoad(gep);
1628 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001629 }
SJW2c317da2020-03-23 07:39:13 -05001630 return V;
1631 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001632}
1633
SJW2c317da2020-03-23 07:39:13 -05001634bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1635 const std::string &name,
1636 int vec_size) {
1637 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1638 if (!vec_size) {
1639 // deduce vec_size from last character of name (e.g. vload_half4)
1640 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001641 }
SJW2c317da2020-03-23 07:39:13 -05001642 switch (vec_size) {
1643 case 2:
1644 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1645 case 4:
1646 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1647 case 0:
1648 if (!is_clspv_version) {
1649 return replaceVloadHalf(F);
1650 }
1651 default:
1652 llvm_unreachable("Unsupported vload_half vector size");
1653 break;
1654 }
1655 return false;
David Neto22f144c2017-06-12 14:26:21 -04001656}
1657
SJW2c317da2020-03-23 07:39:13 -05001658bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1659 Module &M = *F.getParent();
1660 return replaceCallsWithValue(F, [&](CallInst *CI) {
1661 // The index argument from vload_half.
1662 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001663
SJW2c317da2020-03-23 07:39:13 -05001664 // The pointer argument from vload_half.
1665 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001666
SJW2c317da2020-03-23 07:39:13 -05001667 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001668 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
SJW2c317da2020-03-23 07:39:13 -05001669 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1670
1671 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001672 auto SPIRVIntrinsic = clspv::UnpackFunction();
SJW2c317da2020-03-23 07:39:13 -05001673
1674 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1675
1676 Value *V = nullptr;
1677
alan-baker7efcaaa2020-05-06 19:33:27 -04001678 bool supports_16bit_storage = true;
1679 switch (Arg1->getType()->getPointerAddressSpace()) {
1680 case clspv::AddressSpace::Global:
1681 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1682 clspv::Option::StorageClass::kSSBO);
1683 break;
1684 case clspv::AddressSpace::Constant:
1685 if (clspv::Option::ConstantArgsInUniformBuffer())
1686 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1687 clspv::Option::StorageClass::kUBO);
1688 else
1689 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1690 clspv::Option::StorageClass::kSSBO);
1691 break;
1692 default:
1693 // Clspv will emit the Float16 capability if the half type is
1694 // encountered. That capability covers private and local addressspaces.
1695 break;
1696 }
1697
1698 if (supports_16bit_storage) {
SJW2c317da2020-03-23 07:39:13 -05001699 auto ShortTy = Type::getInt16Ty(M.getContext());
1700 auto ShortPointerTy =
1701 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1702
1703 // Cast the half* pointer to short*.
1704 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1705
1706 // Index into the correct address of the casted pointer.
1707 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1708
1709 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001710 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001711
1712 // ZExt the short -> int.
1713 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1714
1715 // Get our float2.
1716 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1717
1718 // Extract out the bottom element which is our float result.
1719 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1720 } else {
1721 // Assume the pointer argument points to storage aligned to 32bits
1722 // or more.
1723 // TODO(dneto): Do more analysis to make sure this is true?
1724 //
1725 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1726 // with:
1727 //
1728 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1729 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1730 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1731 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1732 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1733 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1734 // x float> %converted, %index_is_odd32
1735
1736 auto IntPointerTy =
1737 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1738
1739 // Cast the base pointer to int*.
1740 // In a valid call (according to assumptions), this should get
1741 // optimized away in the simplify GEP pass.
1742 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1743
1744 auto One = ConstantInt::get(IntTy, 1);
1745 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1746 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1747
1748 // Index into the correct address of the casted pointer.
1749 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1750
1751 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001752 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001753
1754 // Get our float2.
1755 auto Call = CallInst::Create(NewF, Load, "", CI);
1756
1757 // Extract out the float result, where the element number is
1758 // determined by whether the original index was even or odd.
1759 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1760 }
1761 return V;
1762 });
1763}
1764
1765bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1766 Module &M = *F.getParent();
1767 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001768 // The index argument from vload_half.
1769 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001770
Kévin Petite8edce32019-04-10 14:23:32 +01001771 // The pointer argument from vload_half.
1772 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001773
Kévin Petite8edce32019-04-10 14:23:32 +01001774 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001775 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001776 auto NewPointerTy =
1777 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001778 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001779
Kévin Petite8edce32019-04-10 14:23:32 +01001780 // Cast the half* pointer to int*.
1781 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001782
Kévin Petite8edce32019-04-10 14:23:32 +01001783 // Index into the correct address of the casted pointer.
1784 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001785
Kévin Petite8edce32019-04-10 14:23:32 +01001786 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001787 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001788
Kévin Petite8edce32019-04-10 14:23:32 +01001789 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001790 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001791
Kévin Petite8edce32019-04-10 14:23:32 +01001792 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001793
Kévin Petite8edce32019-04-10 14:23:32 +01001794 // Get our float2.
1795 return CallInst::Create(NewF, Load, "", CI);
1796 });
David Neto22f144c2017-06-12 14:26:21 -04001797}
1798
SJW2c317da2020-03-23 07:39:13 -05001799bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1800 Module &M = *F.getParent();
1801 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001802 // The index argument from vload_half.
1803 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001804
Kévin Petite8edce32019-04-10 14:23:32 +01001805 // The pointer argument from vload_half.
1806 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001807
Kévin Petite8edce32019-04-10 14:23:32 +01001808 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001809 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1810 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001811 auto NewPointerTy =
1812 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001813 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001814
Kévin Petite8edce32019-04-10 14:23:32 +01001815 // Cast the half* pointer to int2*.
1816 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001817
Kévin Petite8edce32019-04-10 14:23:32 +01001818 // Index into the correct address of the casted pointer.
1819 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001820
Kévin Petite8edce32019-04-10 14:23:32 +01001821 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001822 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001823
Kévin Petite8edce32019-04-10 14:23:32 +01001824 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001825 auto X =
1826 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1827 auto Y =
1828 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001829
Kévin Petite8edce32019-04-10 14:23:32 +01001830 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001831 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001832
Kévin Petite8edce32019-04-10 14:23:32 +01001833 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001834
Kévin Petite8edce32019-04-10 14:23:32 +01001835 // Get the lower (x & y) components of our final float4.
1836 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001837
Kévin Petite8edce32019-04-10 14:23:32 +01001838 // Get the higher (z & w) components of our final float4.
1839 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001840
Kévin Petite8edce32019-04-10 14:23:32 +01001841 Constant *ShuffleMask[4] = {
1842 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1843 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001844
Kévin Petite8edce32019-04-10 14:23:32 +01001845 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001846 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1847 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001848 });
David Neto22f144c2017-06-12 14:26:21 -04001849}
1850
SJW2c317da2020-03-23 07:39:13 -05001851bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001852
1853 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1854 //
1855 // %u = load i32 %ptr
1856 // %fxy = call <2 x float> Unpack2xHalf(u)
1857 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001858 Module &M = *F.getParent();
1859 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001860 auto Index = CI->getOperand(0);
1861 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001862
Kévin Petite8edce32019-04-10 14:23:32 +01001863 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001864 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001865 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001866
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001867 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001868 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001869
Kévin Petite8edce32019-04-10 14:23:32 +01001870 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001871 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001872
Kévin Petite8edce32019-04-10 14:23:32 +01001873 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001874
Kévin Petite8edce32019-04-10 14:23:32 +01001875 // Get our final float2.
1876 return CallInst::Create(NewF, Load, "", CI);
1877 });
David Neto6ad93232018-06-07 15:42:58 -07001878}
1879
SJW2c317da2020-03-23 07:39:13 -05001880bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001881
1882 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1883 //
1884 // %u2 = load <2 x i32> %ptr
1885 // %u2xy = extractelement %u2, 0
1886 // %u2zw = extractelement %u2, 1
1887 // %fxy = call <2 x float> Unpack2xHalf(uint)
1888 // %fzw = call <2 x float> Unpack2xHalf(uint)
1889 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001890 Module &M = *F.getParent();
1891 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001892 auto Index = CI->getOperand(0);
1893 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001894
Kévin Petite8edce32019-04-10 14:23:32 +01001895 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001896 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1897 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001898 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001899
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001900 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001901 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001902
Kévin Petite8edce32019-04-10 14:23:32 +01001903 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001904 auto X =
1905 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1906 auto Y =
1907 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001908
Kévin Petite8edce32019-04-10 14:23:32 +01001909 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001910 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001911
Kévin Petite8edce32019-04-10 14:23:32 +01001912 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001913
Kévin Petite8edce32019-04-10 14:23:32 +01001914 // Get the lower (x & y) components of our final float4.
1915 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001916
Kévin Petite8edce32019-04-10 14:23:32 +01001917 // Get the higher (z & w) components of our final float4.
1918 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001919
Kévin Petite8edce32019-04-10 14:23:32 +01001920 Constant *ShuffleMask[4] = {
1921 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1922 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001923
Kévin Petite8edce32019-04-10 14:23:32 +01001924 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001925 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1926 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001927 });
David Neto6ad93232018-06-07 15:42:58 -07001928}
1929
SJW2c317da2020-03-23 07:39:13 -05001930bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1931 switch (vec_size) {
1932 case 0:
1933 return replaceVstoreHalf(F);
1934 case 2:
1935 return replaceVstoreHalf2(F);
1936 case 4:
1937 return replaceVstoreHalf4(F);
1938 default:
1939 llvm_unreachable("Unsupported vstore_half vector size");
1940 break;
1941 }
1942 return false;
1943}
David Neto22f144c2017-06-12 14:26:21 -04001944
SJW2c317da2020-03-23 07:39:13 -05001945bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1946 Module &M = *F.getParent();
1947 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001948 // The value to store.
1949 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001950
Kévin Petite8edce32019-04-10 14:23:32 +01001951 // The index argument from vstore_half.
1952 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001953
Kévin Petite8edce32019-04-10 14:23:32 +01001954 // The pointer argument from vstore_half.
1955 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001956
Kévin Petite8edce32019-04-10 14:23:32 +01001957 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001958 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001959 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1960 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001961
Kévin Petite8edce32019-04-10 14:23:32 +01001962 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001963 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001964
Kévin Petite8edce32019-04-10 14:23:32 +01001965 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001966
Kévin Petite8edce32019-04-10 14:23:32 +01001967 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001968 auto TempVec = InsertElementInst::Create(
1969 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001970
Kévin Petite8edce32019-04-10 14:23:32 +01001971 // Pack the float2 -> half2 (in an int).
1972 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001973
alan-baker7efcaaa2020-05-06 19:33:27 -04001974 bool supports_16bit_storage = true;
1975 switch (Arg2->getType()->getPointerAddressSpace()) {
1976 case clspv::AddressSpace::Global:
1977 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1978 clspv::Option::StorageClass::kSSBO);
1979 break;
1980 case clspv::AddressSpace::Constant:
1981 if (clspv::Option::ConstantArgsInUniformBuffer())
1982 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1983 clspv::Option::StorageClass::kUBO);
1984 else
1985 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1986 clspv::Option::StorageClass::kSSBO);
1987 break;
1988 default:
1989 // Clspv will emit the Float16 capability if the half type is
1990 // encountered. That capability covers private and local addressspaces.
1991 break;
1992 }
1993
SJW2c317da2020-03-23 07:39:13 -05001994 Value *V = nullptr;
alan-baker7efcaaa2020-05-06 19:33:27 -04001995 if (supports_16bit_storage) {
Kévin Petite8edce32019-04-10 14:23:32 +01001996 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001997 auto ShortPointerTy =
1998 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04001999
Kévin Petite8edce32019-04-10 14:23:32 +01002000 // Truncate our i32 to an i16.
2001 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002002
Kévin Petite8edce32019-04-10 14:23:32 +01002003 // Cast the half* pointer to short*.
2004 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002005
Kévin Petite8edce32019-04-10 14:23:32 +01002006 // Index into the correct address of the casted pointer.
2007 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002008
Kévin Petite8edce32019-04-10 14:23:32 +01002009 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05002010 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002011 } else {
2012 // We can only write to 32-bit aligned words.
2013 //
2014 // Assuming base is aligned to 32-bits, replace the equivalent of
2015 // vstore_half(value, index, base)
2016 // with:
2017 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
2018 // uint32_t write_to_upper_half = index & 1u;
2019 // uint32_t shift = write_to_upper_half << 4;
2020 //
2021 // // Pack the float value as a half number in bottom 16 bits
2022 // // of an i32.
2023 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
2024 //
2025 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
2026 // ^ ((packed & 0xffff) << shift)
2027 // // We only need relaxed consistency, but OpenCL 1.2 only has
2028 // // sequentially consistent atomics.
2029 // // TODO(dneto): Use relaxed consistency.
2030 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002031 auto IntPointerTy =
2032 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002033
Kévin Petite8edce32019-04-10 14:23:32 +01002034 auto Four = ConstantInt::get(IntTy, 4);
2035 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04002036
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002037 auto IndexIsOdd =
2038 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002039 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002040 auto IndexIntoI32 =
2041 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
2042 auto BaseI32Ptr =
2043 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
2044 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
2045 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04002046 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002047 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002048 auto MaskBitsToWrite =
2049 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
2050 auto MaskedCurrent = BinaryOperator::CreateAnd(
2051 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04002052
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002053 auto XLowerBits =
2054 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
2055 auto NewBitsToWrite =
2056 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
2057 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
2058 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04002059
Kévin Petite8edce32019-04-10 14:23:32 +01002060 // Generate the call to atomi_xor.
2061 SmallVector<Type *, 5> ParamTypes;
2062 // The pointer type.
2063 ParamTypes.push_back(IntPointerTy);
2064 // The Types for memory scope, semantics, and value.
2065 ParamTypes.push_back(IntTy);
2066 ParamTypes.push_back(IntTy);
2067 ParamTypes.push_back(IntTy);
2068 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
2069 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04002070
Kévin Petite8edce32019-04-10 14:23:32 +01002071 const auto ConstantScopeDevice =
2072 ConstantInt::get(IntTy, spv::ScopeDevice);
2073 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
2074 // (SPIR-V Workgroup).
2075 const auto AddrSpaceSemanticsBits =
2076 IntPointerTy->getPointerAddressSpace() == 1
2077 ? spv::MemorySemanticsUniformMemoryMask
2078 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04002079
Kévin Petite8edce32019-04-10 14:23:32 +01002080 // We're using relaxed consistency here.
2081 const auto ConstantMemorySemantics =
2082 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
2083 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04002084
Kévin Petite8edce32019-04-10 14:23:32 +01002085 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
2086 ConstantMemorySemantics, ValueToXor};
2087 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05002088
2089 // Return a Nop so the old Call is removed
2090 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
2091 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002092 }
David Neto22f144c2017-06-12 14:26:21 -04002093
SJW2c317da2020-03-23 07:39:13 -05002094 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01002095 });
David Neto22f144c2017-06-12 14:26:21 -04002096}
2097
SJW2c317da2020-03-23 07:39:13 -05002098bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
2099 Module &M = *F.getParent();
2100 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002101 // The value to store.
2102 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002103
Kévin Petite8edce32019-04-10 14:23:32 +01002104 // The index argument from vstore_half.
2105 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002106
Kévin Petite8edce32019-04-10 14:23:32 +01002107 // The pointer argument from vstore_half.
2108 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002109
Kévin Petite8edce32019-04-10 14:23:32 +01002110 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002111 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002112 auto NewPointerTy =
2113 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002114 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002115
Kévin Petite8edce32019-04-10 14:23:32 +01002116 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002117 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002118
Kévin Petite8edce32019-04-10 14:23:32 +01002119 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002120
Kévin Petite8edce32019-04-10 14:23:32 +01002121 // Turn the packed x & y into the final packing.
2122 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002123
Kévin Petite8edce32019-04-10 14:23:32 +01002124 // Cast the half* pointer to int*.
2125 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002126
Kévin Petite8edce32019-04-10 14:23:32 +01002127 // Index into the correct address of the casted pointer.
2128 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002129
Kévin Petite8edce32019-04-10 14:23:32 +01002130 // Store to the int* we casted to.
2131 return new StoreInst(X, Index, CI);
2132 });
David Neto22f144c2017-06-12 14:26:21 -04002133}
2134
SJW2c317da2020-03-23 07:39:13 -05002135bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
2136 Module &M = *F.getParent();
2137 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002138 // The value to store.
2139 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002140
Kévin Petite8edce32019-04-10 14:23:32 +01002141 // The index argument from vstore_half.
2142 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002143
Kévin Petite8edce32019-04-10 14:23:32 +01002144 // The pointer argument from vstore_half.
2145 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002146
Kévin Petite8edce32019-04-10 14:23:32 +01002147 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002148 auto Int2Ty = FixedVectorType::get(IntTy, 2);
2149 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002150 auto NewPointerTy =
2151 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002152 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002153
Kévin Petite8edce32019-04-10 14:23:32 +01002154 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
2155 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04002156
Kévin Petite8edce32019-04-10 14:23:32 +01002157 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002158 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2159 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002160
Kévin Petite8edce32019-04-10 14:23:32 +01002161 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
2162 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002163
Kévin Petite8edce32019-04-10 14:23:32 +01002164 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002165 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2166 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002167
Kévin Petite8edce32019-04-10 14:23:32 +01002168 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002169 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002170
Kévin Petite8edce32019-04-10 14:23:32 +01002171 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002172
Kévin Petite8edce32019-04-10 14:23:32 +01002173 // Turn the packed x & y into the final component of our int2.
2174 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002175
Kévin Petite8edce32019-04-10 14:23:32 +01002176 // Turn the packed z & w into the final component of our int2.
2177 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002178
Kévin Petite8edce32019-04-10 14:23:32 +01002179 auto Combine = InsertElementInst::Create(
2180 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002181 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
2182 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002183
Kévin Petite8edce32019-04-10 14:23:32 +01002184 // Cast the half* pointer to int2*.
2185 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002186
Kévin Petite8edce32019-04-10 14:23:32 +01002187 // Index into the correct address of the casted pointer.
2188 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002189
Kévin Petite8edce32019-04-10 14:23:32 +01002190 // Store to the int2* we casted to.
2191 return new StoreInst(Combine, Index, CI);
2192 });
David Neto22f144c2017-06-12 14:26:21 -04002193}
2194
SJW2c317da2020-03-23 07:39:13 -05002195bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
2196 // convert half to float
2197 Module &M = *F.getParent();
2198 return replaceCallsWithValue(F, [&](CallInst *CI) {
2199 SmallVector<Type *, 3> types;
2200 SmallVector<Value *, 3> args;
2201 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
2202 types.push_back(CI->getArgOperand(i)->getType());
2203 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05002204 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05002205
alan-baker5a8c3be2020-09-09 13:44:26 -04002206 auto NewFType =
2207 FunctionType::get(FixedVectorType::get(Type::getFloatTy(M.getContext()),
2208 cast<VectorType>(CI->getType())
2209 ->getElementCount()
2210 .getKnownMinValue()),
2211 types, false);
SJW2c317da2020-03-23 07:39:13 -05002212
SJW61531372020-06-09 07:31:08 -05002213 std::string NewFName =
2214 Builtins::GetMangledFunctionName("read_imagef", NewFType);
SJW2c317da2020-03-23 07:39:13 -05002215
2216 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2217
2218 auto NewCI = CallInst::Create(NewF, args, "", CI);
2219
2220 // Convert to the half type.
2221 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2222 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002223}
2224
SJW2c317da2020-03-23 07:39:13 -05002225bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
2226 // convert half to float
2227 Module &M = *F.getParent();
2228 return replaceCallsWithValue(F, [&](CallInst *CI) {
2229 SmallVector<Type *, 3> types(3);
2230 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002231
SJW2c317da2020-03-23 07:39:13 -05002232 // Image
2233 types[0] = CI->getArgOperand(0)->getType();
2234 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002235
SJW2c317da2020-03-23 07:39:13 -05002236 // Coord
2237 types[1] = CI->getArgOperand(1)->getType();
2238 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002239
SJW2c317da2020-03-23 07:39:13 -05002240 // Data
alan-baker5a8c3be2020-09-09 13:44:26 -04002241 types[2] =
2242 FixedVectorType::get(Type::getFloatTy(M.getContext()),
2243 cast<VectorType>(CI->getArgOperand(2)->getType())
2244 ->getElementCount()
2245 .getKnownMinValue());
alan-bakerf7e17cb2020-01-02 07:29:59 -05002246
SJW2c317da2020-03-23 07:39:13 -05002247 auto NewFType =
2248 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002249
SJW61531372020-06-09 07:31:08 -05002250 std::string NewFName =
2251 Builtins::GetMangledFunctionName("write_imagef", NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002252
SJW2c317da2020-03-23 07:39:13 -05002253 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002254
SJW2c317da2020-03-23 07:39:13 -05002255 // Convert data to the float type.
2256 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2257 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002258
SJW2c317da2020-03-23 07:39:13 -05002259 return CallInst::Create(NewF, args, "", CI);
2260 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002261}
2262
SJW2c317da2020-03-23 07:39:13 -05002263bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2264 Function &F) {
2265 // convert read_image with int coords to float coords
2266 Module &M = *F.getParent();
2267 return replaceCallsWithValue(F, [&](CallInst *CI) {
2268 // The image.
2269 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002270
SJW2c317da2020-03-23 07:39:13 -05002271 // The sampler.
2272 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002273
SJW2c317da2020-03-23 07:39:13 -05002274 // The coordinate (integer type that we can't handle).
2275 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002276
SJW2c317da2020-03-23 07:39:13 -05002277 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2278 uint32_t components =
2279 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2280 Type *float_ty = nullptr;
2281 if (components == 1) {
2282 float_ty = Type::getFloatTy(M.getContext());
2283 } else {
alan-baker5a8c3be2020-09-09 13:44:26 -04002284 float_ty = FixedVectorType::get(Type::getFloatTy(M.getContext()),
2285 cast<VectorType>(Arg2->getType())
2286 ->getElementCount()
2287 .getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04002288 }
David Neto22f144c2017-06-12 14:26:21 -04002289
SJW2c317da2020-03-23 07:39:13 -05002290 auto NewFType = FunctionType::get(
2291 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2292
2293 std::string NewFName = F.getName().str();
2294 NewFName[NewFName.length() - 1] = 'f';
2295
2296 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2297
2298 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2299
2300 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2301 });
David Neto22f144c2017-06-12 14:26:21 -04002302}
2303
SJW2c317da2020-03-23 07:39:13 -05002304bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2305 return replaceCallsWithValue(F, [&](CallInst *CI) {
2306 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002307
SJW2c317da2020-03-23 07:39:13 -05002308 // We need to map the OpenCL constants to the SPIR-V equivalents.
2309 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2310 const auto ConstantMemorySemantics = ConstantInt::get(
2311 IntTy, spv::MemorySemanticsUniformMemoryMask |
2312 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002313
SJW2c317da2020-03-23 07:39:13 -05002314 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002315
SJW2c317da2020-03-23 07:39:13 -05002316 // The pointer.
2317 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002318
SJW2c317da2020-03-23 07:39:13 -05002319 // The memory scope.
2320 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002321
SJW2c317da2020-03-23 07:39:13 -05002322 // The memory semantics.
2323 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002324
SJW2c317da2020-03-23 07:39:13 -05002325 if (2 < CI->getNumArgOperands()) {
2326 // The unequal memory semantics.
2327 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002328
SJW2c317da2020-03-23 07:39:13 -05002329 // The value.
2330 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002331
SJW2c317da2020-03-23 07:39:13 -05002332 // The comparator.
2333 Params.push_back(CI->getArgOperand(1));
2334 } else if (1 < CI->getNumArgOperands()) {
2335 // The value.
2336 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002337 }
David Neto22f144c2017-06-12 14:26:21 -04002338
SJW2c317da2020-03-23 07:39:13 -05002339 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2340 });
David Neto22f144c2017-06-12 14:26:21 -04002341}
2342
SJW2c317da2020-03-23 07:39:13 -05002343bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2344 llvm::AtomicRMWInst::BinOp Op) {
2345 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerd0eb9052020-07-07 13:12:01 -04002346 auto align = F.getParent()->getDataLayout().getABITypeAlign(
2347 CI->getArgOperand(1)->getType());
SJW2c317da2020-03-23 07:39:13 -05002348 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
alan-bakerd0eb9052020-07-07 13:12:01 -04002349 align, AtomicOrdering::SequentiallyConsistent,
SJW2c317da2020-03-23 07:39:13 -05002350 SyncScope::System, CI);
2351 });
2352}
David Neto22f144c2017-06-12 14:26:21 -04002353
SJW2c317da2020-03-23 07:39:13 -05002354bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2355 Module &M = *F.getParent();
2356 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002357 auto IntTy = Type::getInt32Ty(M.getContext());
2358 auto FloatTy = Type::getFloatTy(M.getContext());
2359
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002360 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2361 ConstantInt::get(IntTy, 1),
2362 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002363
2364 Constant *UpShuffleMask[4] = {
2365 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2366 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2367
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002368 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2369 UndefValue::get(FloatTy),
2370 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002371
Kévin Petite8edce32019-04-10 14:23:32 +01002372 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002373 auto Arg0 =
2374 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2375 ConstantVector::get(DownShuffleMask), "", CI);
2376 auto Arg1 =
2377 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2378 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002379 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002380
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002381 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
SJW61531372020-06-09 07:31:08 -05002382 auto NewFName = Builtins::GetMangledFunctionName("cross", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002383
SJW61531372020-06-09 07:31:08 -05002384 auto Cross3Func = M.getOrInsertFunction(NewFName, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002385
Kévin Petite8edce32019-04-10 14:23:32 +01002386 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002387
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002388 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2389 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002390 });
David Neto22f144c2017-06-12 14:26:21 -04002391}
David Neto62653202017-10-16 19:05:18 -04002392
SJW2c317da2020-03-23 07:39:13 -05002393bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002394 // OpenCL's float result = fract(float x, float* ptr)
2395 //
2396 // In the LLVM domain:
2397 //
2398 // %floor_result = call spir_func float @floor(float %x)
2399 // store float %floor_result, float * %ptr
2400 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2401 // %result = call spir_func float
2402 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2403 //
2404 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2405 // and clspv.fract occur in the SPIR-V generator pass:
2406 //
2407 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2408 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2409 // ...
2410 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2411 // OpStore %ptr %floor_result
2412 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2413 // %fract_result = OpExtInst %float
Marco Antognini55d51862020-07-21 17:50:07 +01002414 // %glsl_ext Nmin %fract_intermediate %just_under_1
David Neto62653202017-10-16 19:05:18 -04002415
David Neto62653202017-10-16 19:05:18 -04002416 using std::string;
2417
2418 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2419 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002420
SJW2c317da2020-03-23 07:39:13 -05002421 Module &M = *F.getParent();
2422 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto62653202017-10-16 19:05:18 -04002423
SJW2c317da2020-03-23 07:39:13 -05002424 // This is either float or a float vector. All the float-like
2425 // types are this type.
2426 auto result_ty = F.getReturnType();
2427
SJW61531372020-06-09 07:31:08 -05002428 std::string fmin_name = Builtins::GetMangledFunctionName("fmin", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002429 Function *fmin_fn = M.getFunction(fmin_name);
2430 if (!fmin_fn) {
2431 // Make the fmin function.
2432 FunctionType *fn_ty =
2433 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2434 fmin_fn =
2435 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2436 fmin_fn->addFnAttr(Attribute::ReadNone);
2437 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2438 }
2439
SJW61531372020-06-09 07:31:08 -05002440 std::string floor_name =
2441 Builtins::GetMangledFunctionName("floor", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002442 Function *floor_fn = M.getFunction(floor_name);
2443 if (!floor_fn) {
2444 // Make the floor function.
2445 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2446 floor_fn =
2447 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2448 floor_fn->addFnAttr(Attribute::ReadNone);
2449 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2450 }
2451
SJW61531372020-06-09 07:31:08 -05002452 std::string clspv_fract_name =
2453 Builtins::GetMangledFunctionName("clspv.fract", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002454 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2455 if (!clspv_fract_fn) {
2456 // Make the clspv_fract function.
2457 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2458 clspv_fract_fn = cast<Function>(
2459 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2460 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2461 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2462 }
2463
2464 // Number of significant significand bits, whether represented or not.
2465 unsigned num_significand_bits;
2466 switch (result_ty->getScalarType()->getTypeID()) {
2467 case Type::HalfTyID:
2468 num_significand_bits = 11;
2469 break;
2470 case Type::FloatTyID:
2471 num_significand_bits = 24;
2472 break;
2473 case Type::DoubleTyID:
2474 num_significand_bits = 53;
2475 break;
2476 default:
2477 llvm_unreachable("Unhandled float type when processing fract builtin");
2478 break;
2479 }
2480 // Beware that the disassembler displays this value as
2481 // OpConstant %float 1
2482 // which is not quite right.
2483 const double kJustUnderOneScalar =
2484 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2485
2486 Constant *just_under_one =
2487 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2488 if (result_ty->isVectorTy()) {
2489 just_under_one = ConstantVector::getSplat(
alan-baker931253b2020-08-20 17:15:38 -04002490 cast<VectorType>(result_ty)->getElementCount(), just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002491 }
2492
2493 IRBuilder<> Builder(CI);
2494
2495 auto arg = CI->getArgOperand(0);
2496 auto ptr = CI->getArgOperand(1);
2497
2498 // Compute floor result and store it.
2499 auto floor = Builder.CreateCall(floor_fn, {arg});
2500 Builder.CreateStore(floor, ptr);
2501
2502 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2503 auto fract_result =
2504 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2505
2506 return fract_result;
2507 });
David Neto62653202017-10-16 19:05:18 -04002508}
alan-bakera52b7312020-10-26 08:58:51 -04002509
alan-bakerb6da5132020-10-29 15:59:06 -04002510bool ReplaceOpenCLBuiltinPass::replaceHadd(Function &F,
2511 Instruction::BinaryOps join_opcode) {
2512 return replaceCallsWithValue(F, [join_opcode](CallInst *Call) {
2513 // a_shr = a >> 1
2514 // b_shr = b >> 1
2515 // add1 = a_shr + b_shr
2516 // join = a |join_opcode| b
2517 // and = join & 1
2518 // add = add1 + and
2519 const auto a = Call->getArgOperand(0);
2520 const auto b = Call->getArgOperand(1);
2521 IRBuilder<> builder(Call);
2522 auto a_shift = builder.CreateLShr(a, 1);
2523 auto b_shift = builder.CreateLShr(b, 1);
2524 auto add = builder.CreateAdd(a_shift, b_shift);
2525 auto join = BinaryOperator::Create(join_opcode, a, b, "", Call);
2526 auto constant_one = ConstantInt::get(a->getType(), 1);
2527 auto and_bit = builder.CreateAnd(join, constant_one);
2528 return builder.CreateAdd(add, and_bit);
2529 });
2530}
2531
alan-bakera52b7312020-10-26 08:58:51 -04002532bool ReplaceOpenCLBuiltinPass::replaceAddSat(Function &F, bool is_signed) {
2533 Module *module = F.getParent();
2534 return replaceCallsWithValue(F, [&module, is_signed](CallInst *Call) {
2535 // SPIR-V OpIAddCarry interprets inputs as unsigned. We use that
2536 // instruction for unsigned additions. For signed addition, it is more
2537 // complicated. For values with bit widths less than 32 bits, we extend
2538 // to the next power of two and perform the addition. For 32- and
2539 // 64-bit values we test the signedness of op1 to determine how to clamp
2540 // the addition.
2541 Type *ty = Call->getType();
2542 Value *op0 = Call->getArgOperand(0);
2543 Value *op1 = Call->getArgOperand(1);
2544 Value *result = nullptr;
2545 if (is_signed) {
2546 unsigned bitwidth = ty->getScalarSizeInBits();
2547 if (bitwidth < 32) {
2548 // sext_op0 = sext op0
2549 // sext_op1 = sext op1
2550 // add = add sext_op0 sext_op1
2551 // clamp = clamp(add, min, max)
2552 // result = trunc clamp
2553 unsigned extended_bits = static_cast<unsigned>(bitwidth << 1);
2554 // The clamp values are the signed min and max of the original bitwidth
2555 // sign extended to the extended bitwidth.
2556 Constant *scalar_min = ConstantInt::get(
2557 Call->getContext(),
2558 APInt::getSignedMinValue(bitwidth).sext(extended_bits));
2559 Constant *scalar_max = ConstantInt::get(
2560 Call->getContext(),
2561 APInt::getSignedMaxValue(bitwidth).sext(extended_bits));
2562 Constant *min = scalar_min;
2563 Constant *max = scalar_max;
2564 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2565 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2566 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2567 }
2568 Type *extended_scalar_ty =
2569 IntegerType::get(Call->getContext(), extended_bits);
2570 Type *extended_ty = extended_scalar_ty;
2571 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2572 extended_ty =
2573 VectorType::get(extended_scalar_ty, vec_ty->getElementCount());
2574 }
2575 auto sext_op0 =
2576 CastInst::Create(Instruction::SExt, op0, extended_ty, "", Call);
2577 auto sext_op1 =
2578 CastInst::Create(Instruction::SExt, op1, extended_ty, "", Call);
2579 // Add the nsw flag since we know no overflow can occur.
2580 auto add = BinaryOperator::CreateNSW(Instruction::Add, sext_op0,
2581 sext_op1, "", Call);
2582 FunctionType *func_ty = FunctionType::get(
2583 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2584
2585 // Don't use the type in GetMangledFunctionName to ensure we get
2586 // signed parameters.
2587 std::string sclamp_name = Builtins::GetMangledFunctionName("clamp");
2588 uint32_t vec_width = 1;
2589 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2590 vec_width = vec_ty->getElementCount().getKnownMinValue();
2591 }
2592 if (extended_bits == 32) {
2593 if (vec_width == 1) {
2594 sclamp_name += "iii";
2595 } else {
2596 sclamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
2597 }
2598 } else {
2599 if (vec_width == 1) {
2600 sclamp_name += "sss";
2601 } else {
2602 sclamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2603 }
2604 }
2605 auto sclamp_callee = module->getOrInsertFunction(sclamp_name, func_ty);
2606 auto clamp = CallInst::Create(sclamp_callee, {add, min, max}, "", Call);
2607 result = CastInst::Create(Instruction::Trunc, clamp, ty, "", Call);
2608 } else {
2609 // Pseudo-code:
2610 // c = a + b;
2611 // if (b < 0)
2612 // c = c > a ? min : c;
2613 // else
2614 // c = c < a ? max : c;
2615 //
2616 unsigned bitwidth = ty->getScalarSizeInBits();
2617 Constant *scalar_min = ConstantInt::get(
2618 Call->getContext(), APInt::getSignedMinValue(bitwidth));
2619 Constant *scalar_max = ConstantInt::get(
2620 Call->getContext(), APInt::getSignedMaxValue(bitwidth));
2621 Constant *min = scalar_min;
2622 Constant *max = scalar_max;
2623 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2624 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2625 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2626 }
2627 auto zero = Constant::getNullValue(ty);
2628 // Cannot add the nsw flag.
2629 auto add = BinaryOperator::Create(Instruction::Add, op0, op1, "", Call);
2630 auto add_gt_op0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SGT,
2631 add, op0, "", Call);
2632 auto min_clamp = SelectInst::Create(add_gt_op0, min, add, "", Call);
2633 auto add_lt_op0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
2634 add, op0, "", Call);
2635 auto max_clamp = SelectInst::Create(add_lt_op0, max, add, "", Call);
2636 auto op1_lt_0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
2637 op1, zero, "", Call);
2638 result = SelectInst::Create(op1_lt_0, min_clamp, max_clamp, "", Call);
2639 }
2640 } else {
2641 // Just use OpIAddCarry and use the carry to clamp the result.
2642 auto ret_ty = StructType::get(Call->getContext(), {ty, ty});
2643 auto add = clspv::InsertSPIRVOp(
2644 Call, spv::OpIAddCarry, {Attribute::ReadNone}, ret_ty, {op0, op1});
2645 auto ex0 = ExtractValueInst::Create(add, {0}, "", Call);
2646 auto ex1 = ExtractValueInst::Create(add, {1}, "", Call);
2647 auto cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, ex1,
2648 Constant::getNullValue(ty), "", Call);
2649 result =
2650 SelectInst::Create(cmp, ex0, Constant::getAllOnesValue(ty), "", Call);
2651 }
2652
2653 return result;
2654 });
2655}
alan-baker4986eff2020-10-29 13:38:00 -04002656
2657bool ReplaceOpenCLBuiltinPass::replaceAtomicLoad(Function &F) {
2658 return replaceCallsWithValue(F, [](CallInst *Call) {
2659 auto pointer = Call->getArgOperand(0);
2660 // Clang emits an address space cast to the generic address space. Skip the
2661 // cast and use the input directly.
2662 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2663 pointer = cast->getPointerOperand();
2664 }
2665 Value *order_arg =
2666 Call->getNumArgOperands() > 1 ? Call->getArgOperand(1) : nullptr;
2667 Value *scope_arg =
2668 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2669 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2670 clspv::AddressSpace::Global;
2671 auto order = MemoryOrderSemantics(order_arg, is_global, Call,
2672 spv::MemorySemanticsAcquireMask);
2673 auto scope = MemoryScope(scope_arg, is_global, Call);
2674 return InsertSPIRVOp(Call, spv::OpAtomicLoad, {Attribute::Convergent},
2675 Call->getType(), {pointer, scope, order});
2676 });
2677}
2678
2679bool ReplaceOpenCLBuiltinPass::replaceExplicitAtomics(
2680 Function &F, spv::Op Op, spv::MemorySemanticsMask semantics) {
2681 return replaceCallsWithValue(F, [Op, semantics](CallInst *Call) {
2682 auto pointer = Call->getArgOperand(0);
2683 // Clang emits an address space cast to the generic address space. Skip the
2684 // cast and use the input directly.
2685 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2686 pointer = cast->getPointerOperand();
2687 }
2688 Value *value = Call->getArgOperand(1);
2689 Value *order_arg =
2690 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2691 Value *scope_arg =
2692 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2693 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2694 clspv::AddressSpace::Global;
2695 auto scope = MemoryScope(scope_arg, is_global, Call);
2696 auto order = MemoryOrderSemantics(order_arg, is_global, Call, semantics);
2697 return InsertSPIRVOp(Call, Op, {Attribute::Convergent}, Call->getType(),
2698 {pointer, scope, order, value});
2699 });
2700}
2701
2702bool ReplaceOpenCLBuiltinPass::replaceAtomicCompareExchange(Function &F) {
2703 return replaceCallsWithValue(F, [](CallInst *Call) {
2704 auto pointer = Call->getArgOperand(0);
2705 // Clang emits an address space cast to the generic address space. Skip the
2706 // cast and use the input directly.
2707 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2708 pointer = cast->getPointerOperand();
2709 }
2710 auto expected = Call->getArgOperand(1);
2711 if (auto cast = dyn_cast<AddrSpaceCastOperator>(expected)) {
2712 expected = cast->getPointerOperand();
2713 }
2714 auto value = Call->getArgOperand(2);
2715 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2716 clspv::AddressSpace::Global;
2717 Value *success_arg =
2718 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2719 Value *failure_arg =
2720 Call->getNumArgOperands() > 4 ? Call->getArgOperand(4) : nullptr;
2721 Value *scope_arg =
2722 Call->getNumArgOperands() > 5 ? Call->getArgOperand(5) : nullptr;
2723 auto scope = MemoryScope(scope_arg, is_global, Call);
2724 auto success = MemoryOrderSemantics(success_arg, is_global, Call,
2725 spv::MemorySemanticsAcquireReleaseMask);
2726 auto failure = MemoryOrderSemantics(failure_arg, is_global, Call,
2727 spv::MemorySemanticsAcquireMask);
2728
2729 // If the value pointed to by |expected| equals the value pointed to by
2730 // |pointer|, |value| is written into |pointer|, otherwise the value in
2731 // |pointer| is written into |expected|. In order to avoid extra stores,
2732 // the basic block with the original atomic is split and the store is
2733 // performed in the |then| block. The condition is the inversion of the
2734 // comparison result.
2735 IRBuilder<> builder(Call);
2736 auto load = builder.CreateLoad(expected);
2737 auto cmp_xchg = InsertSPIRVOp(
2738 Call, spv::OpAtomicCompareExchange, {Attribute::Convergent},
2739 value->getType(), {pointer, scope, success, failure, value, load});
2740 auto cmp = builder.CreateICmpEQ(cmp_xchg, load);
2741 auto not_cmp = builder.CreateNot(cmp);
2742 auto then_branch = SplitBlockAndInsertIfThen(not_cmp, Call, false);
2743 builder.SetInsertPoint(then_branch);
2744 builder.CreateStore(cmp_xchg, expected);
2745 return cmp;
2746 });
2747}