blob: fd1e28f0e403616aef1f527433f6cdc59be1516a [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;
alan-baker6b9d1ee2020-11-03 23:11:32 -0500224
225private:
SJW2c317da2020-03-23 07:39:13 -0500226 bool runOnFunction(Function &F);
227 bool replaceAbs(Function &F);
228 bool replaceAbsDiff(Function &F, bool is_signed);
229 bool replaceCopysign(Function &F);
230 bool replaceRecip(Function &F);
231 bool replaceDivide(Function &F);
232 bool replaceDot(Function &F);
233 bool replaceFmod(Function &F);
SJW61531372020-06-09 07:31:08 -0500234 bool replaceExp10(Function &F, const std::string &basename);
235 bool replaceLog10(Function &F, const std::string &basename);
gnl21636e7992020-09-09 16:08:16 +0100236 bool replaceLog1p(Function &F);
alan-baker12d2c182020-07-20 08:22:42 -0400237 bool replaceBarrier(Function &F, bool subgroup = false);
SJW2c317da2020-03-23 07:39:13 -0500238 bool replaceMemFence(Function &F, uint32_t semantics);
Kévin Petit1cb45112020-04-27 18:55:48 +0100239 bool replacePrefetch(Function &F);
SJW2c317da2020-03-23 07:39:13 -0500240 bool replaceRelational(Function &F, CmpInst::Predicate P, int32_t C);
241 bool replaceIsInfAndIsNan(Function &F, spv::Op SPIRVOp, int32_t isvec);
242 bool replaceIsFinite(Function &F);
243 bool replaceAllAndAny(Function &F, spv::Op SPIRVOp);
244 bool replaceUpsample(Function &F);
245 bool replaceRotate(Function &F);
246 bool replaceConvert(Function &F, bool SrcIsSigned, bool DstIsSigned);
247 bool replaceMulHi(Function &F, bool is_signed, bool is_mad = false);
248 bool replaceSelect(Function &F);
249 bool replaceBitSelect(Function &F);
SJW61531372020-06-09 07:31:08 -0500250 bool replaceStep(Function &F, bool is_smooth);
SJW2c317da2020-03-23 07:39:13 -0500251 bool replaceSignbit(Function &F, bool is_vec);
252 bool replaceMul(Function &F, bool is_float, bool is_mad);
253 bool replaceVloadHalf(Function &F, const std::string &name, int vec_size);
254 bool replaceVloadHalf(Function &F);
255 bool replaceVloadHalf2(Function &F);
256 bool replaceVloadHalf4(Function &F);
257 bool replaceClspvVloadaHalf2(Function &F);
258 bool replaceClspvVloadaHalf4(Function &F);
259 bool replaceVstoreHalf(Function &F, int vec_size);
260 bool replaceVstoreHalf(Function &F);
261 bool replaceVstoreHalf2(Function &F);
262 bool replaceVstoreHalf4(Function &F);
263 bool replaceHalfReadImage(Function &F);
264 bool replaceHalfWriteImage(Function &F);
265 bool replaceSampledReadImageWithIntCoords(Function &F);
266 bool replaceAtomics(Function &F, spv::Op Op);
267 bool replaceAtomics(Function &F, llvm::AtomicRMWInst::BinOp Op);
alan-baker4986eff2020-10-29 13:38:00 -0400268 bool replaceAtomicLoad(Function &F);
269 bool replaceExplicitAtomics(Function &F, spv::Op Op,
270 spv::MemorySemanticsMask semantics =
271 spv::MemorySemanticsAcquireReleaseMask);
272 bool replaceAtomicCompareExchange(Function &);
SJW2c317da2020-03-23 07:39:13 -0500273 bool replaceCross(Function &F);
274 bool replaceFract(Function &F, int vec_size);
275 bool replaceVload(Function &F);
276 bool replaceVstore(Function &F);
alan-baker3f1bf492020-11-05 09:07:36 -0500277 bool replaceAddSubSat(Function &F, bool is_signed, bool is_add);
Kévin Petit8576f682020-11-02 14:51:32 +0000278 bool replaceHadd(Function &F, bool is_signed,
279 Instruction::BinaryOps join_opcode);
alan-baker2cecaa72020-11-05 14:05:20 -0500280 bool replaceCountZeroes(Function &F, bool leading);
alan-baker6b9d1ee2020-11-03 23:11:32 -0500281 bool replaceMadSat(Function &F, bool is_signed);
282
283 // Caches struct types for { |type|, |type| }. This prevents
284 // getOrInsertFunction from introducing a bitcasts between structs with
285 // identical contents.
286 Type *GetPairStruct(Type *type);
287
288 DenseMap<Type *, Type *> PairStructMap;
David Neto22f144c2017-06-12 14:26:21 -0400289};
SJW2c317da2020-03-23 07:39:13 -0500290
Kévin Petit91bc72e2019-04-08 15:17:46 +0100291} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400292
293char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400294INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
295 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400296
297namespace clspv {
298ModulePass *createReplaceOpenCLBuiltinPass() {
299 return new ReplaceOpenCLBuiltinPass();
300}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400301} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400302
303bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500304 std::list<Function *> func_list;
305 for (auto &F : M.getFunctionList()) {
306 // process only function declarations
307 if (F.isDeclaration() && runOnFunction(F)) {
308 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000309 }
310 }
SJW2c317da2020-03-23 07:39:13 -0500311 if (func_list.size() != 0) {
312 // recursively convert functions, but first remove dead
313 for (auto *F : func_list) {
314 if (F->use_empty()) {
315 F->eraseFromParent();
316 }
317 }
318 runOnModule(M);
319 return true;
320 }
321 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000322}
323
SJW2c317da2020-03-23 07:39:13 -0500324bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
325 auto &FI = Builtins::Lookup(&F);
326 switch (FI.getType()) {
327 case Builtins::kAbs:
328 if (!FI.getParameter(0).is_signed) {
329 return replaceAbs(F);
330 }
331 break;
332 case Builtins::kAbsDiff:
333 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
alan-bakera52b7312020-10-26 08:58:51 -0400334
335 case Builtins::kAddSat:
alan-baker3f1bf492020-11-05 09:07:36 -0500336 return replaceAddSubSat(F, FI.getParameter(0).is_signed, true);
alan-bakera52b7312020-10-26 08:58:51 -0400337
alan-bakercc2bafb2020-11-02 08:30:18 -0500338 case Builtins::kClz:
alan-baker2cecaa72020-11-05 14:05:20 -0500339 return replaceCountZeroes(F, true);
340
341 case Builtins::kCtz:
342 return replaceCountZeroes(F, false);
alan-bakercc2bafb2020-11-02 08:30:18 -0500343
alan-bakerb6da5132020-10-29 15:59:06 -0400344 case Builtins::kHadd:
Kévin Petit8576f682020-11-02 14:51:32 +0000345 return replaceHadd(F, FI.getParameter(0).is_signed, Instruction::And);
alan-bakerb6da5132020-10-29 15:59:06 -0400346 case Builtins::kRhadd:
Kévin Petit8576f682020-11-02 14:51:32 +0000347 return replaceHadd(F, FI.getParameter(0).is_signed, Instruction::Or);
alan-bakerb6da5132020-10-29 15:59:06 -0400348
SJW2c317da2020-03-23 07:39:13 -0500349 case Builtins::kCopysign:
350 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100351
SJW2c317da2020-03-23 07:39:13 -0500352 case Builtins::kHalfRecip:
353 case Builtins::kNativeRecip:
354 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100355
SJW2c317da2020-03-23 07:39:13 -0500356 case Builtins::kHalfDivide:
357 case Builtins::kNativeDivide:
358 return replaceDivide(F);
359
360 case Builtins::kDot:
361 return replaceDot(F);
362
363 case Builtins::kExp10:
364 case Builtins::kHalfExp10:
SJW61531372020-06-09 07:31:08 -0500365 case Builtins::kNativeExp10:
366 return replaceExp10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500367
368 case Builtins::kLog10:
369 case Builtins::kHalfLog10:
SJW61531372020-06-09 07:31:08 -0500370 case Builtins::kNativeLog10:
371 return replaceLog10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500372
gnl21636e7992020-09-09 16:08:16 +0100373 case Builtins::kLog1p:
374 return replaceLog1p(F);
375
SJW2c317da2020-03-23 07:39:13 -0500376 case Builtins::kFmod:
377 return replaceFmod(F);
378
379 case Builtins::kBarrier:
380 case Builtins::kWorkGroupBarrier:
381 return replaceBarrier(F);
382
alan-baker12d2c182020-07-20 08:22:42 -0400383 case Builtins::kSubGroupBarrier:
384 return replaceBarrier(F, true);
385
SJW2c317da2020-03-23 07:39:13 -0500386 case Builtins::kMemFence:
alan-baker12d2c182020-07-20 08:22:42 -0400387 return replaceMemFence(F, spv::MemorySemanticsAcquireReleaseMask);
SJW2c317da2020-03-23 07:39:13 -0500388 case Builtins::kReadMemFence:
389 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
390 case Builtins::kWriteMemFence:
391 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
392
393 // Relational
394 case Builtins::kIsequal:
395 return replaceRelational(F, CmpInst::FCMP_OEQ,
396 FI.getParameter(0).vector_size ? -1 : 1);
397 case Builtins::kIsgreater:
398 return replaceRelational(F, CmpInst::FCMP_OGT,
399 FI.getParameter(0).vector_size ? -1 : 1);
400 case Builtins::kIsgreaterequal:
401 return replaceRelational(F, CmpInst::FCMP_OGE,
402 FI.getParameter(0).vector_size ? -1 : 1);
403 case Builtins::kIsless:
404 return replaceRelational(F, CmpInst::FCMP_OLT,
405 FI.getParameter(0).vector_size ? -1 : 1);
406 case Builtins::kIslessequal:
407 return replaceRelational(F, CmpInst::FCMP_OLE,
408 FI.getParameter(0).vector_size ? -1 : 1);
409 case Builtins::kIsnotequal:
410 return replaceRelational(F, CmpInst::FCMP_ONE,
411 FI.getParameter(0).vector_size ? -1 : 1);
412
413 case Builtins::kIsinf: {
414 bool is_vec = FI.getParameter(0).vector_size != 0;
415 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
416 }
417 case Builtins::kIsnan: {
418 bool is_vec = FI.getParameter(0).vector_size != 0;
419 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
420 }
421
422 case Builtins::kIsfinite:
423 return replaceIsFinite(F);
424
425 case Builtins::kAll: {
426 bool is_vec = FI.getParameter(0).vector_size != 0;
427 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
428 }
429 case Builtins::kAny: {
430 bool is_vec = FI.getParameter(0).vector_size != 0;
431 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
432 }
433
434 case Builtins::kUpsample:
435 return replaceUpsample(F);
436
437 case Builtins::kRotate:
438 return replaceRotate(F);
439
440 case Builtins::kConvert:
441 return replaceConvert(F, FI.getParameter(0).is_signed,
442 FI.getReturnType().is_signed);
443
alan-baker4986eff2020-10-29 13:38:00 -0400444 // OpenCL 2.0 explicit atomics have different default scopes and semantics
445 // than legacy atomic functions.
446 case Builtins::kAtomicLoad:
447 case Builtins::kAtomicLoadExplicit:
448 return replaceAtomicLoad(F);
449 case Builtins::kAtomicStore:
450 case Builtins::kAtomicStoreExplicit:
451 return replaceExplicitAtomics(F, spv::OpAtomicStore,
452 spv::MemorySemanticsReleaseMask);
453 case Builtins::kAtomicExchange:
454 case Builtins::kAtomicExchangeExplicit:
455 return replaceExplicitAtomics(F, spv::OpAtomicExchange);
456 case Builtins::kAtomicFetchAdd:
457 case Builtins::kAtomicFetchAddExplicit:
458 return replaceExplicitAtomics(F, spv::OpAtomicIAdd);
459 case Builtins::kAtomicFetchSub:
460 case Builtins::kAtomicFetchSubExplicit:
461 return replaceExplicitAtomics(F, spv::OpAtomicISub);
462 case Builtins::kAtomicFetchOr:
463 case Builtins::kAtomicFetchOrExplicit:
464 return replaceExplicitAtomics(F, spv::OpAtomicOr);
465 case Builtins::kAtomicFetchXor:
466 case Builtins::kAtomicFetchXorExplicit:
467 return replaceExplicitAtomics(F, spv::OpAtomicXor);
468 case Builtins::kAtomicFetchAnd:
469 case Builtins::kAtomicFetchAndExplicit:
470 return replaceExplicitAtomics(F, spv::OpAtomicAnd);
471 case Builtins::kAtomicFetchMin:
472 case Builtins::kAtomicFetchMinExplicit:
473 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
474 ? spv::OpAtomicSMin
475 : spv::OpAtomicUMin);
476 case Builtins::kAtomicFetchMax:
477 case Builtins::kAtomicFetchMaxExplicit:
478 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
479 ? spv::OpAtomicSMax
480 : spv::OpAtomicUMax);
481 // Weak compare exchange is generated as strong compare exchange.
482 case Builtins::kAtomicCompareExchangeWeak:
483 case Builtins::kAtomicCompareExchangeWeakExplicit:
484 case Builtins::kAtomicCompareExchangeStrong:
485 case Builtins::kAtomicCompareExchangeStrongExplicit:
486 return replaceAtomicCompareExchange(F);
487
488 // Legacy atomic functions.
SJW2c317da2020-03-23 07:39:13 -0500489 case Builtins::kAtomicInc:
490 return replaceAtomics(F, spv::OpAtomicIIncrement);
491 case Builtins::kAtomicDec:
492 return replaceAtomics(F, spv::OpAtomicIDecrement);
493 case Builtins::kAtomicCmpxchg:
494 return replaceAtomics(F, spv::OpAtomicCompareExchange);
495 case Builtins::kAtomicAdd:
496 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
497 case Builtins::kAtomicSub:
498 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
499 case Builtins::kAtomicXchg:
500 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
501 case Builtins::kAtomicMin:
502 return replaceAtomics(F, FI.getParameter(0).is_signed
503 ? llvm::AtomicRMWInst::Min
504 : llvm::AtomicRMWInst::UMin);
505 case Builtins::kAtomicMax:
506 return replaceAtomics(F, FI.getParameter(0).is_signed
507 ? llvm::AtomicRMWInst::Max
508 : llvm::AtomicRMWInst::UMax);
509 case Builtins::kAtomicAnd:
510 return replaceAtomics(F, llvm::AtomicRMWInst::And);
511 case Builtins::kAtomicOr:
512 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
513 case Builtins::kAtomicXor:
514 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
515
516 case Builtins::kCross:
517 if (FI.getParameter(0).vector_size == 4) {
518 return replaceCross(F);
519 }
520 break;
521
522 case Builtins::kFract:
523 if (FI.getParameterCount()) {
524 return replaceFract(F, FI.getParameter(0).vector_size);
525 }
526 break;
527
528 case Builtins::kMadHi:
529 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
530 case Builtins::kMulHi:
531 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
532
alan-baker6b9d1ee2020-11-03 23:11:32 -0500533 case Builtins::kMadSat:
534 return replaceMadSat(F, FI.getParameter(0).is_signed);
535
SJW2c317da2020-03-23 07:39:13 -0500536 case Builtins::kMad:
537 case Builtins::kMad24:
538 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
539 true);
540 case Builtins::kMul24:
541 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
542 false);
543
544 case Builtins::kSelect:
545 return replaceSelect(F);
546
547 case Builtins::kBitselect:
548 return replaceBitSelect(F);
549
550 case Builtins::kVload:
551 return replaceVload(F);
552
553 case Builtins::kVloadaHalf:
554 case Builtins::kVloadHalf:
555 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
556
557 case Builtins::kVstore:
558 return replaceVstore(F);
559
560 case Builtins::kVstoreHalf:
561 case Builtins::kVstoreaHalf:
562 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
563
564 case Builtins::kSmoothstep: {
565 int vec_size = FI.getLastParameter().vector_size;
566 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500567 return replaceStep(F, true);
SJW2c317da2020-03-23 07:39:13 -0500568 }
569 break;
570 }
571 case Builtins::kStep: {
572 int vec_size = FI.getLastParameter().vector_size;
573 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500574 return replaceStep(F, false);
SJW2c317da2020-03-23 07:39:13 -0500575 }
576 break;
577 }
578
579 case Builtins::kSignbit:
580 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
581
alan-baker3f1bf492020-11-05 09:07:36 -0500582 case Builtins::kSubSat:
583 return replaceAddSubSat(F, FI.getParameter(0).is_signed, false);
584
SJW2c317da2020-03-23 07:39:13 -0500585 case Builtins::kReadImageh:
586 return replaceHalfReadImage(F);
587 case Builtins::kReadImagef:
588 case Builtins::kReadImagei:
589 case Builtins::kReadImageui: {
590 if (FI.getParameter(1).isSampler() &&
591 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
592 return replaceSampledReadImageWithIntCoords(F);
593 }
594 break;
595 }
596
597 case Builtins::kWriteImageh:
598 return replaceHalfWriteImage(F);
599
Kévin Petit1cb45112020-04-27 18:55:48 +0100600 case Builtins::kPrefetch:
601 return replacePrefetch(F);
602
SJW2c317da2020-03-23 07:39:13 -0500603 default:
604 break;
605 }
606
607 return false;
608}
609
alan-baker6b9d1ee2020-11-03 23:11:32 -0500610Type *ReplaceOpenCLBuiltinPass::GetPairStruct(Type *type) {
611 auto iter = PairStructMap.find(type);
612 if (iter != PairStructMap.end())
613 return iter->second;
614
615 auto new_struct = StructType::get(type->getContext(), {type, type});
616 PairStructMap[type] = new_struct;
617 return new_struct;
618}
619
SJW2c317da2020-03-23 07:39:13 -0500620bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
621 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400622 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100623}
624
SJW2c317da2020-03-23 07:39:13 -0500625bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
626 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100627 auto XValue = CI->getOperand(0);
628 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100629
Kévin Petite8edce32019-04-10 14:23:32 +0100630 IRBuilder<> Builder(CI);
631 auto XmY = Builder.CreateSub(XValue, YValue);
632 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100633
SJW2c317da2020-03-23 07:39:13 -0500634 Value *Cmp = nullptr;
635 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100636 Cmp = Builder.CreateICmpSGT(YValue, XValue);
637 } else {
638 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100639 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100640
Kévin Petite8edce32019-04-10 14:23:32 +0100641 return Builder.CreateSelect(Cmp, YmX, XmY);
642 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100643}
644
SJW2c317da2020-03-23 07:39:13 -0500645bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
646 return replaceCallsWithValue(F, [&F](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100647 auto XValue = CI->getOperand(0);
648 auto YValue = CI->getOperand(1);
Kévin Petit8c1be282019-04-02 19:34:25 +0100649
Kévin Petite8edce32019-04-10 14:23:32 +0100650 auto Ty = XValue->getType();
Kévin Petit8c1be282019-04-02 19:34:25 +0100651
SJW2c317da2020-03-23 07:39:13 -0500652 Type *IntTy = Type::getIntNTy(F.getContext(), Ty->getScalarSizeInBits());
James Pricecf53df42020-04-20 14:41:24 -0400653 if (auto vec_ty = dyn_cast<VectorType>(Ty)) {
alan-baker5a8c3be2020-09-09 13:44:26 -0400654 IntTy = FixedVectorType::get(
655 IntTy, vec_ty->getElementCount().getKnownMinValue());
Kévin Petit8c1be282019-04-02 19:34:25 +0100656 }
Kévin Petit8c1be282019-04-02 19:34:25 +0100657
Kévin Petite8edce32019-04-10 14:23:32 +0100658 // Return X with the sign of Y
659
660 // Sign bit masks
661 auto SignBit = IntTy->getScalarSizeInBits() - 1;
662 auto SignBitMask = 1 << SignBit;
663 auto SignBitMaskValue = ConstantInt::get(IntTy, SignBitMask);
664 auto NotSignBitMaskValue = ConstantInt::get(IntTy, ~SignBitMask);
665
666 IRBuilder<> Builder(CI);
667
668 // Extract sign of Y
669 auto YInt = Builder.CreateBitCast(YValue, IntTy);
670 auto YSign = Builder.CreateAnd(YInt, SignBitMaskValue);
671
672 // Clear sign bit in X
673 auto XInt = Builder.CreateBitCast(XValue, IntTy);
674 XInt = Builder.CreateAnd(XInt, NotSignBitMaskValue);
675
676 // Insert sign bit of Y into X
677 auto NewXInt = Builder.CreateOr(XInt, YSign);
678
679 // And cast back to floating-point
680 return Builder.CreateBitCast(NewXInt, Ty);
681 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100682}
683
SJW2c317da2020-03-23 07:39:13 -0500684bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
685 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100686 // Recip has one arg.
687 auto Arg = CI->getOperand(0);
688 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
689 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
690 });
David Neto22f144c2017-06-12 14:26:21 -0400691}
692
SJW2c317da2020-03-23 07:39:13 -0500693bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
694 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100695 auto Op0 = CI->getOperand(0);
696 auto Op1 = CI->getOperand(1);
697 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
698 });
David Neto22f144c2017-06-12 14:26:21 -0400699}
700
SJW2c317da2020-03-23 07:39:13 -0500701bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
702 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100703 auto Op0 = CI->getOperand(0);
704 auto Op1 = CI->getOperand(1);
705
SJW2c317da2020-03-23 07:39:13 -0500706 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100707 if (Op0->getType()->isVectorTy()) {
708 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
709 CI->getType(), {Op0, Op1});
710 } else {
711 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
712 }
713
714 return V;
715 });
716}
717
SJW2c317da2020-03-23 07:39:13 -0500718bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
SJW61531372020-06-09 07:31:08 -0500719 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500720 // convert to natural
721 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500722 std::string NewFName = basename.substr(0, slen);
723 NewFName =
724 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400725
SJW2c317da2020-03-23 07:39:13 -0500726 Module &M = *F.getParent();
727 return replaceCallsWithValue(F, [&](CallInst *CI) {
728 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
729
730 auto Arg = CI->getOperand(0);
731
732 // Constant of the natural log of 10 (ln(10)).
733 const double Ln10 =
734 2.302585092994045684017991454684364207601101488628772976033;
735
736 auto Mul = BinaryOperator::Create(
737 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
738
739 return CallInst::Create(NewF, Mul, "", CI);
740 });
David Neto22f144c2017-06-12 14:26:21 -0400741}
742
SJW2c317da2020-03-23 07:39:13 -0500743bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100744 // OpenCL fmod(x,y) is x - y * trunc(x/y)
745 // The sign for a non-zero result is taken from x.
746 // (Try an example.)
747 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500748 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100749 auto Op0 = CI->getOperand(0);
750 auto Op1 = CI->getOperand(1);
751 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
752 });
753}
754
SJW2c317da2020-03-23 07:39:13 -0500755bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
SJW61531372020-06-09 07:31:08 -0500756 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500757 // convert to natural
758 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500759 std::string NewFName = basename.substr(0, slen);
760 NewFName =
761 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400762
SJW2c317da2020-03-23 07:39:13 -0500763 Module &M = *F.getParent();
764 return replaceCallsWithValue(F, [&](CallInst *CI) {
765 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
766
767 auto Arg = CI->getOperand(0);
768
769 // Constant of the reciprocal of the natural log of 10 (ln(10)).
770 const double Ln10 =
771 0.434294481903251827651128918916605082294397005803666566114;
772
773 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
774
775 return BinaryOperator::Create(Instruction::FMul,
776 ConstantFP::get(Arg->getType(), Ln10), NewCI,
777 "", CI);
778 });
David Neto22f144c2017-06-12 14:26:21 -0400779}
780
gnl21636e7992020-09-09 16:08:16 +0100781bool ReplaceOpenCLBuiltinPass::replaceLog1p(Function &F) {
782 // convert to natural
783 std::string NewFName =
784 Builtins::GetMangledFunctionName("log", F.getFunctionType());
785
786 Module &M = *F.getParent();
787 return replaceCallsWithValue(F, [&](CallInst *CI) {
788 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
789
790 auto Arg = CI->getOperand(0);
791
792 auto ArgP1 = BinaryOperator::Create(
793 Instruction::FAdd, ConstantFP::get(Arg->getType(), 1.0), Arg, "", CI);
794
795 return CallInst::Create(NewF, ArgP1, "", CI);
796 });
797}
798
alan-baker12d2c182020-07-20 08:22:42 -0400799bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F, bool subgroup) {
David Neto22f144c2017-06-12 14:26:21 -0400800
alan-bakerf6bc8252020-09-23 14:58:55 -0400801 enum {
802 CLK_LOCAL_MEM_FENCE = 0x01,
803 CLK_GLOBAL_MEM_FENCE = 0x02,
804 CLK_IMAGE_MEM_FENCE = 0x04
805 };
David Neto22f144c2017-06-12 14:26:21 -0400806
alan-baker12d2c182020-07-20 08:22:42 -0400807 return replaceCallsWithValue(F, [subgroup](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100808 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400809
Kévin Petitc4643922019-06-17 19:32:05 +0100810 // We need to map the OpenCL constants to the SPIR-V equivalents.
811 const auto LocalMemFence =
812 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
813 const auto GlobalMemFence =
814 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400815 const auto ImageMemFence =
816 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
alan-baker12d2c182020-07-20 08:22:42 -0400817 const auto ConstantAcquireRelease = ConstantInt::get(
818 Arg->getType(), spv::MemorySemanticsAcquireReleaseMask);
Kévin Petitc4643922019-06-17 19:32:05 +0100819 const auto ConstantScopeDevice =
820 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
821 const auto ConstantScopeWorkgroup =
822 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
alan-baker12d2c182020-07-20 08:22:42 -0400823 const auto ConstantScopeSubgroup =
824 ConstantInt::get(Arg->getType(), spv::ScopeSubgroup);
David Neto22f144c2017-06-12 14:26:21 -0400825
Kévin Petitc4643922019-06-17 19:32:05 +0100826 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
827 const auto LocalMemFenceMask =
828 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
829 const auto WorkgroupShiftAmount =
830 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
831 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
832 Instruction::Shl, LocalMemFenceMask,
833 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400834
Kévin Petitc4643922019-06-17 19:32:05 +0100835 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
836 const auto GlobalMemFenceMask =
837 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
838 const auto UniformShiftAmount =
839 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
840 const auto MemorySemanticsUniform = BinaryOperator::Create(
841 Instruction::Shl, GlobalMemFenceMask,
842 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400843
alan-bakerf6bc8252020-09-23 14:58:55 -0400844 // OpenCL 2.0
845 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
846 const auto ImageMemFenceMask =
847 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
848 const auto ImageShiftAmount =
849 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
850 const auto MemorySemanticsImage = BinaryOperator::Create(
851 Instruction::Shl, ImageMemFenceMask,
852 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
853
Kévin Petitc4643922019-06-17 19:32:05 +0100854 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400855 // MemorySemanticsSequentiallyConsistentMask.
856 auto MemorySemantics1 =
Kévin Petitc4643922019-06-17 19:32:05 +0100857 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
alan-baker12d2c182020-07-20 08:22:42 -0400858 ConstantAcquireRelease, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400859 auto MemorySemantics2 = BinaryOperator::Create(
860 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
861 auto MemorySemantics = BinaryOperator::Create(
862 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400863
alan-baker12d2c182020-07-20 08:22:42 -0400864 // If the memory scope is not specified explicitly, it is either Subgroup
865 // or Workgroup depending on the type of barrier.
866 Value *MemoryScope =
867 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
868 if (CI->data_operands_size() > 1) {
869 enum {
870 CL_MEMORY_SCOPE_WORKGROUP = 0x1,
871 CL_MEMORY_SCOPE_DEVICE = 0x2,
872 CL_MEMORY_SCOPE_SUBGROUP = 0x4
873 };
874 // The call was given an explicit memory scope.
875 const auto MemoryScopeSubgroup =
876 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_SUBGROUP);
877 const auto MemoryScopeDevice =
878 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_DEVICE);
David Neto22f144c2017-06-12 14:26:21 -0400879
alan-baker12d2c182020-07-20 08:22:42 -0400880 auto Cmp =
881 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
882 MemoryScopeSubgroup, CI->getOperand(1), "", CI);
883 MemoryScope = SelectInst::Create(Cmp, ConstantScopeSubgroup,
884 ConstantScopeWorkgroup, "", CI);
885 Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
886 MemoryScopeDevice, CI->getOperand(1), "", CI);
887 MemoryScope =
888 SelectInst::Create(Cmp, ConstantScopeDevice, MemoryScope, "", CI);
889 }
890
891 // Lastly, the Execution Scope is either Workgroup or Subgroup depending on
892 // the type of barrier;
893 const auto ExecutionScope =
894 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400895
Kévin Petitc4643922019-06-17 19:32:05 +0100896 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
alan-baker3d905692020-10-28 14:02:37 -0400897 {Attribute::NoDuplicate, Attribute::Convergent},
898 CI->getType(),
Kévin Petitc4643922019-06-17 19:32:05 +0100899 {ExecutionScope, MemoryScope, MemorySemantics});
900 });
David Neto22f144c2017-06-12 14:26:21 -0400901}
902
SJW2c317da2020-03-23 07:39:13 -0500903bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
904 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400905
SJW2c317da2020-03-23 07:39:13 -0500906 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerf6bc8252020-09-23 14:58:55 -0400907 enum {
908 CLK_LOCAL_MEM_FENCE = 0x01,
909 CLK_GLOBAL_MEM_FENCE = 0x02,
910 CLK_IMAGE_MEM_FENCE = 0x04,
911 };
David Neto22f144c2017-06-12 14:26:21 -0400912
SJW2c317da2020-03-23 07:39:13 -0500913 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400914
SJW2c317da2020-03-23 07:39:13 -0500915 // We need to map the OpenCL constants to the SPIR-V equivalents.
916 const auto LocalMemFence =
917 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
918 const auto GlobalMemFence =
919 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400920 const auto ImageMemFence =
921 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
SJW2c317da2020-03-23 07:39:13 -0500922 const auto ConstantMemorySemantics =
923 ConstantInt::get(Arg->getType(), semantics);
alan-baker12d2c182020-07-20 08:22:42 -0400924 const auto ConstantScopeWorkgroup =
925 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400926
SJW2c317da2020-03-23 07:39:13 -0500927 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
928 const auto LocalMemFenceMask =
929 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
930 const auto WorkgroupShiftAmount =
931 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
932 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
933 Instruction::Shl, LocalMemFenceMask,
934 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400935
SJW2c317da2020-03-23 07:39:13 -0500936 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
937 const auto GlobalMemFenceMask =
938 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
939 const auto UniformShiftAmount =
940 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
941 const auto MemorySemanticsUniform = BinaryOperator::Create(
942 Instruction::Shl, GlobalMemFenceMask,
943 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400944
alan-bakerf6bc8252020-09-23 14:58:55 -0400945 // OpenCL 2.0
946 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
947 const auto ImageMemFenceMask =
948 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
949 const auto ImageShiftAmount =
950 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
951 const auto MemorySemanticsImage = BinaryOperator::Create(
952 Instruction::Shl, ImageMemFenceMask,
953 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
954
SJW2c317da2020-03-23 07:39:13 -0500955 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400956 // |semantics|.
957 auto MemorySemantics1 =
SJW2c317da2020-03-23 07:39:13 -0500958 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
959 ConstantMemorySemantics, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400960 auto MemorySemantics2 = BinaryOperator::Create(
961 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
962 auto MemorySemantics = BinaryOperator::Create(
963 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400964
alan-baker12d2c182020-07-20 08:22:42 -0400965 // Memory Scope is always workgroup.
966 const auto MemoryScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400967
alan-baker3d905692020-10-28 14:02:37 -0400968 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier,
969 {Attribute::Convergent}, CI->getType(),
SJW2c317da2020-03-23 07:39:13 -0500970 {MemoryScope, MemorySemantics});
971 });
David Neto22f144c2017-06-12 14:26:21 -0400972}
973
Kévin Petit1cb45112020-04-27 18:55:48 +0100974bool ReplaceOpenCLBuiltinPass::replacePrefetch(Function &F) {
975 bool Changed = false;
976
977 SmallVector<Instruction *, 4> ToRemoves;
978
979 // Find all calls to the function
980 for (auto &U : F.uses()) {
981 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
982 ToRemoves.push_back(CI);
983 }
984 }
985
986 Changed = !ToRemoves.empty();
987
988 // Delete them
989 for (auto V : ToRemoves) {
990 V->eraseFromParent();
991 }
992
993 return Changed;
994}
995
SJW2c317da2020-03-23 07:39:13 -0500996bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
997 CmpInst::Predicate P,
998 int32_t C) {
999 return replaceCallsWithValue(F, [&](CallInst *CI) {
1000 // The predicate to use in the CmpInst.
1001 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -04001002
SJW2c317da2020-03-23 07:39:13 -05001003 // The value to return for true.
1004 auto TrueValue = ConstantInt::getSigned(CI->getType(), C);
David Neto22f144c2017-06-12 14:26:21 -04001005
SJW2c317da2020-03-23 07:39:13 -05001006 // The value to return for false.
1007 auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -04001008
SJW2c317da2020-03-23 07:39:13 -05001009 auto Arg1 = CI->getOperand(0);
1010 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001011
SJW2c317da2020-03-23 07:39:13 -05001012 const auto Cmp =
1013 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001014
SJW2c317da2020-03-23 07:39:13 -05001015 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1016 });
David Neto22f144c2017-06-12 14:26:21 -04001017}
1018
SJW2c317da2020-03-23 07:39:13 -05001019bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
1020 spv::Op SPIRVOp,
1021 int32_t C) {
1022 Module &M = *F.getParent();
1023 return replaceCallsWithValue(F, [&](CallInst *CI) {
1024 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -04001025
SJW2c317da2020-03-23 07:39:13 -05001026 // The value to return for true.
1027 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -04001028
SJW2c317da2020-03-23 07:39:13 -05001029 // The value to return for false.
1030 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -04001031
SJW2c317da2020-03-23 07:39:13 -05001032 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -04001033 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001034 CorrespondingBoolTy =
1035 FixedVectorType::get(Type::getInt1Ty(M.getContext()),
1036 CIVecTy->getElementCount().getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04001037 }
David Neto22f144c2017-06-12 14:26:21 -04001038
SJW2c317da2020-03-23 07:39:13 -05001039 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
1040 CorrespondingBoolTy, {CI->getOperand(0)});
1041
1042 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
1043 });
David Neto22f144c2017-06-12 14:26:21 -04001044}
1045
SJW2c317da2020-03-23 07:39:13 -05001046bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
1047 Module &M = *F.getParent();
1048 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001049 auto &C = M.getContext();
1050 auto Val = CI->getOperand(0);
1051 auto ValTy = Val->getType();
1052 auto RetTy = CI->getType();
1053
1054 // Get a suitable integer type to represent the number
1055 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
1056
1057 // Create Mask
1058 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -05001059 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001060 switch (ScalarSize) {
1061 case 16:
1062 InfMask = ConstantInt::get(IntTy, 0x7C00U);
1063 break;
1064 case 32:
1065 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
1066 break;
1067 case 64:
1068 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
1069 break;
1070 default:
1071 llvm_unreachable("Unsupported floating-point type");
1072 }
1073
1074 IRBuilder<> Builder(CI);
1075
1076 // Bitcast to int
1077 auto ValInt = Builder.CreateBitCast(Val, IntTy);
1078
1079 // Mask and compare
1080 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
1081 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
1082
1083 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -05001084 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001085 if (ValTy->isVectorTy()) {
1086 RetTrue = ConstantInt::getSigned(RetTy, -1);
1087 } else {
1088 RetTrue = ConstantInt::get(RetTy, 1);
1089 }
1090 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
1091 });
1092}
1093
SJW2c317da2020-03-23 07:39:13 -05001094bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
1095 Module &M = *F.getParent();
1096 return replaceCallsWithValue(F, [&](CallInst *CI) {
1097 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001098
SJW2c317da2020-03-23 07:39:13 -05001099 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +00001100
SJW2c317da2020-03-23 07:39:13 -05001101 // If the argument is a 32-bit int, just use a shift
1102 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
1103 V = BinaryOperator::Create(Instruction::LShr, Arg,
1104 ConstantInt::get(Arg->getType(), 31), "", CI);
1105 } else {
1106 // The value for zero to compare against.
1107 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -04001108
SJW2c317da2020-03-23 07:39:13 -05001109 // The value to return for true.
1110 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04001111
SJW2c317da2020-03-23 07:39:13 -05001112 // The value to return for false.
1113 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -04001114
SJW2c317da2020-03-23 07:39:13 -05001115 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
1116 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001117
SJW2c317da2020-03-23 07:39:13 -05001118 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -04001119
SJW2c317da2020-03-23 07:39:13 -05001120 // If we have a function to call, call it!
1121 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -04001122
SJW2c317da2020-03-23 07:39:13 -05001123 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -04001124
SJW2c317da2020-03-23 07:39:13 -05001125 const auto NewCI = clspv::InsertSPIRVOp(
1126 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
1127 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -04001128
SJW2c317da2020-03-23 07:39:13 -05001129 } else {
1130 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -04001131 }
1132
SJW2c317da2020-03-23 07:39:13 -05001133 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001134 }
SJW2c317da2020-03-23 07:39:13 -05001135 return V;
1136 });
David Neto22f144c2017-06-12 14:26:21 -04001137}
1138
SJW2c317da2020-03-23 07:39:13 -05001139bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
1140 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1141 // Get arguments
1142 auto HiValue = CI->getOperand(0);
1143 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +00001144
SJW2c317da2020-03-23 07:39:13 -05001145 // Don't touch overloads that aren't in OpenCL C
1146 auto HiType = HiValue->getType();
1147 auto LoType = LoValue->getType();
1148
1149 if (HiType != LoType) {
1150 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001151 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001152
SJW2c317da2020-03-23 07:39:13 -05001153 if (!HiType->isIntOrIntVectorTy()) {
1154 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001155 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001156
SJW2c317da2020-03-23 07:39:13 -05001157 if (HiType->getScalarSizeInBits() * 2 !=
1158 CI->getType()->getScalarSizeInBits()) {
1159 return nullptr;
1160 }
1161
1162 if ((HiType->getScalarSizeInBits() != 8) &&
1163 (HiType->getScalarSizeInBits() != 16) &&
1164 (HiType->getScalarSizeInBits() != 32)) {
1165 return nullptr;
1166 }
1167
James Pricecf53df42020-04-20 14:41:24 -04001168 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001169 unsigned NumElements = HiVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001170 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1171 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001172 return nullptr;
1173 }
1174 }
1175
1176 // Convert both operands to the result type
1177 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
1178 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
1179
1180 // Shift high operand
1181 auto ShiftAmount =
1182 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
1183 auto HiShifted =
1184 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
1185
1186 // OR both results
1187 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
1188 });
Kévin Petitbf0036c2019-03-06 13:57:10 +00001189}
1190
SJW2c317da2020-03-23 07:39:13 -05001191bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
1192 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1193 // Get arguments
1194 auto SrcValue = CI->getOperand(0);
1195 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +00001196
SJW2c317da2020-03-23 07:39:13 -05001197 // Don't touch overloads that aren't in OpenCL C
1198 auto SrcType = SrcValue->getType();
1199 auto RotType = RotAmount->getType();
1200
1201 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
1202 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001203 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001204
SJW2c317da2020-03-23 07:39:13 -05001205 if (!SrcType->isIntOrIntVectorTy()) {
1206 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001207 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001208
SJW2c317da2020-03-23 07:39:13 -05001209 if ((SrcType->getScalarSizeInBits() != 8) &&
1210 (SrcType->getScalarSizeInBits() != 16) &&
1211 (SrcType->getScalarSizeInBits() != 32) &&
1212 (SrcType->getScalarSizeInBits() != 64)) {
1213 return nullptr;
1214 }
1215
James Pricecf53df42020-04-20 14:41:24 -04001216 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001217 unsigned NumElements = SrcVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001218 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1219 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001220 return nullptr;
1221 }
1222 }
1223
alan-bakerfd22ae12020-10-29 15:59:22 -04001224 // Replace with LLVM's funnel shift left intrinsic because it is more
1225 // generic than rotate.
1226 Function *intrinsic =
1227 Intrinsic::getDeclaration(F.getParent(), Intrinsic::fshl, SrcType);
1228 return CallInst::Create(intrinsic->getFunctionType(), intrinsic,
1229 {SrcValue, SrcValue, RotAmount}, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001230 });
Kévin Petitd44eef52019-03-08 13:22:14 +00001231}
1232
SJW2c317da2020-03-23 07:39:13 -05001233bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
1234 bool DstIsSigned) {
1235 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1236 Value *V = nullptr;
1237 // Get arguments
1238 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001239
SJW2c317da2020-03-23 07:39:13 -05001240 // Don't touch overloads that aren't in OpenCL C
1241 auto SrcType = SrcValue->getType();
1242 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001243
SJW2c317da2020-03-23 07:39:13 -05001244 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1245 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1246 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001247 }
1248
James Pricecf53df42020-04-20 14:41:24 -04001249 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001250 unsigned SrcNumElements =
1251 SrcVecType->getElementCount().getKnownMinValue();
1252 unsigned DstNumElements =
1253 cast<VectorType>(DstType)->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001254 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001255 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001256 }
1257
James Pricecf53df42020-04-20 14:41:24 -04001258 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1259 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1260 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001261 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001262 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001263 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001264
SJW2c317da2020-03-23 07:39:13 -05001265 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1266 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1267
1268 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1269 bool DstIsInt = DstType->isIntOrIntVectorTy();
1270
1271 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1272 // Unnecessary cast operation.
1273 V = SrcValue;
1274 } else if (SrcIsFloat && DstIsFloat) {
1275 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1276 } else if (SrcIsFloat && DstIsInt) {
1277 if (DstIsSigned) {
1278 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1279 } else {
1280 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1281 }
1282 } else if (SrcIsInt && DstIsFloat) {
1283 if (SrcIsSigned) {
1284 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1285 } else {
1286 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1287 }
1288 } else if (SrcIsInt && DstIsInt) {
1289 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1290 } else {
1291 // Not something we're supposed to handle, just move on
1292 }
1293
1294 return V;
1295 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001296}
1297
SJW2c317da2020-03-23 07:39:13 -05001298bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1299 bool is_mad) {
1300 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1301 Value *V = nullptr;
1302 // Get arguments
1303 auto AValue = CI->getOperand(0);
1304 auto BValue = CI->getOperand(1);
1305 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001306
SJW2c317da2020-03-23 07:39:13 -05001307 // Don't touch overloads that aren't in OpenCL C
1308 auto AType = AValue->getType();
1309 auto BType = BValue->getType();
1310 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001311
SJW2c317da2020-03-23 07:39:13 -05001312 if ((AType != BType) || (CI->getType() != AType) ||
1313 (is_mad && (AType != CType))) {
1314 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001315 }
1316
SJW2c317da2020-03-23 07:39:13 -05001317 if (!AType->isIntOrIntVectorTy()) {
1318 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001319 }
Kévin Petit8a560882019-03-21 15:24:34 +00001320
SJW2c317da2020-03-23 07:39:13 -05001321 if ((AType->getScalarSizeInBits() != 8) &&
1322 (AType->getScalarSizeInBits() != 16) &&
1323 (AType->getScalarSizeInBits() != 32) &&
1324 (AType->getScalarSizeInBits() != 64)) {
1325 return V;
1326 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001327
James Pricecf53df42020-04-20 14:41:24 -04001328 if (auto AVecType = dyn_cast<VectorType>(AType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001329 unsigned NumElements = AVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001330 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1331 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001332 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001333 }
1334 }
1335
SJW2c317da2020-03-23 07:39:13 -05001336 // Our SPIR-V op returns a struct, create a type for it
alan-baker6b9d1ee2020-11-03 23:11:32 -05001337 auto ExMulRetType = GetPairStruct(AType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001338
SJW2c317da2020-03-23 07:39:13 -05001339 // Select the appropriate signed/unsigned SPIR-V op
1340 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1341
1342 // Call the SPIR-V op
1343 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1344 ExMulRetType, {AValue, BValue});
1345
1346 // Get the high part of the result
1347 unsigned Idxs[] = {1};
1348 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1349
1350 // If we're handling a mad_hi, add the third argument to the result
1351 if (is_mad) {
1352 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001353 }
1354
SJW2c317da2020-03-23 07:39:13 -05001355 return V;
1356 });
Kévin Petit8a560882019-03-21 15:24:34 +00001357}
1358
SJW2c317da2020-03-23 07:39:13 -05001359bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1360 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1361 // Get arguments
1362 auto FalseValue = CI->getOperand(0);
1363 auto TrueValue = CI->getOperand(1);
1364 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001365
SJW2c317da2020-03-23 07:39:13 -05001366 // Don't touch overloads that aren't in OpenCL C
1367 auto FalseType = FalseValue->getType();
1368 auto TrueType = TrueValue->getType();
1369 auto PredicateType = PredicateValue->getType();
1370
1371 if (FalseType != TrueType) {
1372 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001373 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001374
SJW2c317da2020-03-23 07:39:13 -05001375 if (!PredicateType->isIntOrIntVectorTy()) {
1376 return nullptr;
1377 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001378
SJW2c317da2020-03-23 07:39:13 -05001379 if (!FalseType->isIntOrIntVectorTy() &&
1380 !FalseType->getScalarType()->isFloatingPointTy()) {
1381 return nullptr;
1382 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001383
SJW2c317da2020-03-23 07:39:13 -05001384 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1385 return nullptr;
1386 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001387
SJW2c317da2020-03-23 07:39:13 -05001388 if (FalseType->getScalarSizeInBits() !=
1389 PredicateType->getScalarSizeInBits()) {
1390 return nullptr;
1391 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001392
James Pricecf53df42020-04-20 14:41:24 -04001393 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001394 unsigned NumElements = FalseVecType->getElementCount().getKnownMinValue();
1395 if (NumElements != cast<VectorType>(PredicateType)
1396 ->getElementCount()
1397 .getKnownMinValue()) {
SJW2c317da2020-03-23 07:39:13 -05001398 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001399 }
1400
James Pricecf53df42020-04-20 14:41:24 -04001401 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1402 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001403 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001404 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001405 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001406
SJW2c317da2020-03-23 07:39:13 -05001407 // Create constant
1408 const auto ZeroValue = Constant::getNullValue(PredicateType);
1409
1410 // Scalar and vector are to be treated differently
1411 CmpInst::Predicate Pred;
1412 if (PredicateType->isVectorTy()) {
1413 Pred = CmpInst::ICMP_SLT;
1414 } else {
1415 Pred = CmpInst::ICMP_NE;
1416 }
1417
1418 // Create comparison instruction
1419 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1420 ZeroValue, "", CI);
1421
1422 // Create select
1423 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1424 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001425}
1426
SJW2c317da2020-03-23 07:39:13 -05001427bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1428 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1429 Value *V = nullptr;
1430 if (CI->getNumOperands() != 4) {
1431 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001432 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001433
SJW2c317da2020-03-23 07:39:13 -05001434 // Get arguments
1435 auto FalseValue = CI->getOperand(0);
1436 auto TrueValue = CI->getOperand(1);
1437 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001438
SJW2c317da2020-03-23 07:39:13 -05001439 // Don't touch overloads that aren't in OpenCL C
1440 auto FalseType = FalseValue->getType();
1441 auto TrueType = TrueValue->getType();
1442 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001443
SJW2c317da2020-03-23 07:39:13 -05001444 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1445 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001446 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001447
James Pricecf53df42020-04-20 14:41:24 -04001448 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001449 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1450 !TrueType->getScalarType()->isIntegerTy()) {
1451 return V;
1452 }
alan-baker5a8c3be2020-09-09 13:44:26 -04001453 unsigned NumElements = TrueVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001454 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1455 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001456 return V;
1457 }
1458 }
1459
1460 // Remember the type of the operands
1461 auto OpType = TrueType;
1462
1463 // The actual bit selection will always be done on an integer type,
1464 // declare it here
1465 Type *BitType;
1466
1467 // If the operands are float, then bitcast them to int
1468 if (OpType->getScalarType()->isFloatingPointTy()) {
1469
1470 // First create the new type
1471 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1472
1473 // Then bitcast all operands
1474 PredicateValue =
1475 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1476 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1477 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1478
1479 } else {
1480 // The operands have an integer type, use it directly
1481 BitType = OpType;
1482 }
1483
1484 // All the operands are now always integers
1485 // implement as (c & b) | (~c & a)
1486
1487 // Create our negated predicate value
1488 auto AllOnes = Constant::getAllOnesValue(BitType);
1489 auto NotPredicateValue = BinaryOperator::Create(
1490 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1491
1492 // Then put everything together
1493 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1494 FalseValue, "", CI);
1495 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1496 TrueValue, "", CI);
1497
1498 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1499
1500 // If we were dealing with a floating point type, we must bitcast
1501 // the result back to that
1502 if (OpType->getScalarType()->isFloatingPointTy()) {
1503 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1504 }
1505
1506 return V;
1507 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001508}
1509
SJW61531372020-06-09 07:31:08 -05001510bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth) {
SJW2c317da2020-03-23 07:39:13 -05001511 // convert to vector versions
1512 Module &M = *F.getParent();
1513 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1514 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1515 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001516
SJW2c317da2020-03-23 07:39:13 -05001517 // First figure out which function we're dealing with
1518 if (is_smooth) {
1519 ArgsToSplat.push_back(CI->getOperand(1));
1520 VectorArg = CI->getOperand(2);
1521 } else {
1522 VectorArg = CI->getOperand(1);
1523 }
1524
1525 // Splat arguments that need to be
1526 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001527 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001528
1529 for (auto arg : ArgsToSplat) {
1530 Value *NewVectorArg = UndefValue::get(VecType);
alan-baker5a8c3be2020-09-09 13:44:26 -04001531 for (auto i = 0; i < VecType->getElementCount().getKnownMinValue(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001532 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1533 NewVectorArg =
1534 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1535 }
1536 SplatArgs.push_back(NewVectorArg);
1537 }
1538
1539 // Replace the call with the vector/vector flavour
1540 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1541 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1542
SJW61531372020-06-09 07:31:08 -05001543 std::string NewFName = Builtins::GetMangledFunctionName(
1544 is_smooth ? "smoothstep" : "step", NewFType);
1545
SJW2c317da2020-03-23 07:39:13 -05001546 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1547
1548 SmallVector<Value *, 3> NewArgs;
1549 for (auto arg : SplatArgs) {
1550 NewArgs.push_back(arg);
1551 }
1552 NewArgs.push_back(VectorArg);
1553
1554 return CallInst::Create(NewF, NewArgs, "", CI);
1555 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001556}
1557
SJW2c317da2020-03-23 07:39:13 -05001558bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001559 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1560 auto Arg = CI->getOperand(0);
1561 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001562
SJW2c317da2020-03-23 07:39:13 -05001563 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001564
SJW2c317da2020-03-23 07:39:13 -05001565 return BinaryOperator::Create(Op, Bitcast,
1566 ConstantInt::get(CI->getType(), 31), "", CI);
1567 });
David Neto22f144c2017-06-12 14:26:21 -04001568}
1569
SJW2c317da2020-03-23 07:39:13 -05001570bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1571 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001572 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1573 // The multiply instruction to use.
1574 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001575
SJW2c317da2020-03-23 07:39:13 -05001576 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001577
SJW2c317da2020-03-23 07:39:13 -05001578 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1579 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001580
SJW2c317da2020-03-23 07:39:13 -05001581 if (is_mad) {
1582 // The add instruction to use.
1583 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001584
SJW2c317da2020-03-23 07:39:13 -05001585 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001586 }
David Neto22f144c2017-06-12 14:26:21 -04001587
SJW2c317da2020-03-23 07:39:13 -05001588 return V;
1589 });
David Neto22f144c2017-06-12 14:26:21 -04001590}
1591
SJW2c317da2020-03-23 07:39:13 -05001592bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001593 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1594 Value *V = nullptr;
1595 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001596
SJW2c317da2020-03-23 07:39:13 -05001597 auto data_type = data->getType();
1598 if (!data_type->isVectorTy())
1599 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001600
James Pricecf53df42020-04-20 14:41:24 -04001601 auto vec_data_type = cast<VectorType>(data_type);
1602
alan-baker5a8c3be2020-09-09 13:44:26 -04001603 auto elems = vec_data_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001604 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1605 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001606
SJW2c317da2020-03-23 07:39:13 -05001607 auto offset = CI->getOperand(1);
1608 auto ptr = CI->getOperand(2);
1609 auto ptr_type = ptr->getType();
1610 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001611 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001612 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001613
SJW2c317da2020-03-23 07:39:13 -05001614 // Avoid pointer casts. Instead generate the correct number of stores
1615 // and rely on drivers to coalesce appropriately.
1616 IRBuilder<> builder(CI);
1617 auto elems_const = builder.getInt32(elems);
1618 auto adjust = builder.CreateMul(offset, elems_const);
1619 for (auto i = 0; i < elems; ++i) {
1620 auto idx = builder.getInt32(i);
1621 auto add = builder.CreateAdd(adjust, idx);
1622 auto gep = builder.CreateGEP(ptr, add);
1623 auto extract = builder.CreateExtractElement(data, i);
1624 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001625 }
SJW2c317da2020-03-23 07:39:13 -05001626 return V;
1627 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001628}
1629
SJW2c317da2020-03-23 07:39:13 -05001630bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001631 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1632 Value *V = nullptr;
1633 auto ret_type = F.getReturnType();
1634 if (!ret_type->isVectorTy())
1635 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001636
James Pricecf53df42020-04-20 14:41:24 -04001637 auto vec_ret_type = cast<VectorType>(ret_type);
1638
alan-baker5a8c3be2020-09-09 13:44:26 -04001639 auto elems = vec_ret_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001640 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1641 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001642
SJW2c317da2020-03-23 07:39:13 -05001643 auto offset = CI->getOperand(0);
1644 auto ptr = CI->getOperand(1);
1645 auto ptr_type = ptr->getType();
1646 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001647 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001648 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001649
SJW2c317da2020-03-23 07:39:13 -05001650 // Avoid pointer casts. Instead generate the correct number of loads
1651 // and rely on drivers to coalesce appropriately.
1652 IRBuilder<> builder(CI);
1653 auto elems_const = builder.getInt32(elems);
1654 V = UndefValue::get(ret_type);
1655 auto adjust = builder.CreateMul(offset, elems_const);
1656 for (auto i = 0; i < elems; ++i) {
1657 auto idx = builder.getInt32(i);
1658 auto add = builder.CreateAdd(adjust, idx);
1659 auto gep = builder.CreateGEP(ptr, add);
1660 auto load = builder.CreateLoad(gep);
1661 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001662 }
SJW2c317da2020-03-23 07:39:13 -05001663 return V;
1664 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001665}
1666
SJW2c317da2020-03-23 07:39:13 -05001667bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1668 const std::string &name,
1669 int vec_size) {
1670 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1671 if (!vec_size) {
1672 // deduce vec_size from last character of name (e.g. vload_half4)
1673 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001674 }
SJW2c317da2020-03-23 07:39:13 -05001675 switch (vec_size) {
1676 case 2:
1677 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1678 case 4:
1679 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1680 case 0:
1681 if (!is_clspv_version) {
1682 return replaceVloadHalf(F);
1683 }
1684 default:
1685 llvm_unreachable("Unsupported vload_half vector size");
1686 break;
1687 }
1688 return false;
David Neto22f144c2017-06-12 14:26:21 -04001689}
1690
SJW2c317da2020-03-23 07:39:13 -05001691bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1692 Module &M = *F.getParent();
1693 return replaceCallsWithValue(F, [&](CallInst *CI) {
1694 // The index argument from vload_half.
1695 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001696
SJW2c317da2020-03-23 07:39:13 -05001697 // The pointer argument from vload_half.
1698 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001699
SJW2c317da2020-03-23 07:39:13 -05001700 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001701 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
SJW2c317da2020-03-23 07:39:13 -05001702 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1703
1704 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001705 auto SPIRVIntrinsic = clspv::UnpackFunction();
SJW2c317da2020-03-23 07:39:13 -05001706
1707 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1708
1709 Value *V = nullptr;
1710
alan-baker7efcaaa2020-05-06 19:33:27 -04001711 bool supports_16bit_storage = true;
1712 switch (Arg1->getType()->getPointerAddressSpace()) {
1713 case clspv::AddressSpace::Global:
1714 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1715 clspv::Option::StorageClass::kSSBO);
1716 break;
1717 case clspv::AddressSpace::Constant:
1718 if (clspv::Option::ConstantArgsInUniformBuffer())
1719 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1720 clspv::Option::StorageClass::kUBO);
1721 else
1722 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1723 clspv::Option::StorageClass::kSSBO);
1724 break;
1725 default:
1726 // Clspv will emit the Float16 capability if the half type is
1727 // encountered. That capability covers private and local addressspaces.
1728 break;
1729 }
1730
1731 if (supports_16bit_storage) {
SJW2c317da2020-03-23 07:39:13 -05001732 auto ShortTy = Type::getInt16Ty(M.getContext());
1733 auto ShortPointerTy =
1734 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1735
1736 // Cast the half* pointer to short*.
1737 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1738
1739 // Index into the correct address of the casted pointer.
1740 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1741
1742 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001743 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001744
1745 // ZExt the short -> int.
1746 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1747
1748 // Get our float2.
1749 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1750
1751 // Extract out the bottom element which is our float result.
1752 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1753 } else {
1754 // Assume the pointer argument points to storage aligned to 32bits
1755 // or more.
1756 // TODO(dneto): Do more analysis to make sure this is true?
1757 //
1758 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1759 // with:
1760 //
1761 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1762 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1763 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1764 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1765 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1766 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1767 // x float> %converted, %index_is_odd32
1768
1769 auto IntPointerTy =
1770 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1771
1772 // Cast the base pointer to int*.
1773 // In a valid call (according to assumptions), this should get
1774 // optimized away in the simplify GEP pass.
1775 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1776
1777 auto One = ConstantInt::get(IntTy, 1);
1778 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1779 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1780
1781 // Index into the correct address of the casted pointer.
1782 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1783
1784 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001785 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001786
1787 // Get our float2.
1788 auto Call = CallInst::Create(NewF, Load, "", CI);
1789
1790 // Extract out the float result, where the element number is
1791 // determined by whether the original index was even or odd.
1792 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1793 }
1794 return V;
1795 });
1796}
1797
1798bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1799 Module &M = *F.getParent();
1800 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001801 // The index argument from vload_half.
1802 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001803
Kévin Petite8edce32019-04-10 14:23:32 +01001804 // The pointer argument from vload_half.
1805 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001806
Kévin Petite8edce32019-04-10 14:23:32 +01001807 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001808 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001809 auto NewPointerTy =
1810 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001811 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001812
Kévin Petite8edce32019-04-10 14:23:32 +01001813 // Cast the half* pointer to int*.
1814 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001815
Kévin Petite8edce32019-04-10 14:23:32 +01001816 // Index into the correct address of the casted pointer.
1817 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001818
Kévin Petite8edce32019-04-10 14:23:32 +01001819 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001820 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001821
Kévin Petite8edce32019-04-10 14:23:32 +01001822 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001823 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001824
Kévin Petite8edce32019-04-10 14:23:32 +01001825 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001826
Kévin Petite8edce32019-04-10 14:23:32 +01001827 // Get our float2.
1828 return CallInst::Create(NewF, Load, "", CI);
1829 });
David Neto22f144c2017-06-12 14:26:21 -04001830}
1831
SJW2c317da2020-03-23 07:39:13 -05001832bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1833 Module &M = *F.getParent();
1834 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001835 // The index argument from vload_half.
1836 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001837
Kévin Petite8edce32019-04-10 14:23:32 +01001838 // The pointer argument from vload_half.
1839 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001840
Kévin Petite8edce32019-04-10 14:23:32 +01001841 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001842 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1843 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001844 auto NewPointerTy =
1845 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001846 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001847
Kévin Petite8edce32019-04-10 14:23:32 +01001848 // Cast the half* pointer to int2*.
1849 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001850
Kévin Petite8edce32019-04-10 14:23:32 +01001851 // Index into the correct address of the casted pointer.
1852 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001853
Kévin Petite8edce32019-04-10 14:23:32 +01001854 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001855 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001856
Kévin Petite8edce32019-04-10 14:23:32 +01001857 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001858 auto X =
1859 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1860 auto Y =
1861 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001862
Kévin Petite8edce32019-04-10 14:23:32 +01001863 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001864 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001865
Kévin Petite8edce32019-04-10 14:23:32 +01001866 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001867
Kévin Petite8edce32019-04-10 14:23:32 +01001868 // Get the lower (x & y) components of our final float4.
1869 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001870
Kévin Petite8edce32019-04-10 14:23:32 +01001871 // Get the higher (z & w) components of our final float4.
1872 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001873
Kévin Petite8edce32019-04-10 14:23:32 +01001874 Constant *ShuffleMask[4] = {
1875 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1876 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001877
Kévin Petite8edce32019-04-10 14:23:32 +01001878 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001879 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1880 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001881 });
David Neto22f144c2017-06-12 14:26:21 -04001882}
1883
SJW2c317da2020-03-23 07:39:13 -05001884bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001885
1886 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1887 //
1888 // %u = load i32 %ptr
1889 // %fxy = call <2 x float> Unpack2xHalf(u)
1890 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001891 Module &M = *F.getParent();
1892 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001893 auto Index = CI->getOperand(0);
1894 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001895
Kévin Petite8edce32019-04-10 14:23:32 +01001896 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001897 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(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001901 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001902
Kévin Petite8edce32019-04-10 14:23:32 +01001903 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001904 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001905
Kévin Petite8edce32019-04-10 14:23:32 +01001906 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001907
Kévin Petite8edce32019-04-10 14:23:32 +01001908 // Get our final float2.
1909 return CallInst::Create(NewF, Load, "", CI);
1910 });
David Neto6ad93232018-06-07 15:42:58 -07001911}
1912
SJW2c317da2020-03-23 07:39:13 -05001913bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001914
1915 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1916 //
1917 // %u2 = load <2 x i32> %ptr
1918 // %u2xy = extractelement %u2, 0
1919 // %u2zw = extractelement %u2, 1
1920 // %fxy = call <2 x float> Unpack2xHalf(uint)
1921 // %fzw = call <2 x float> Unpack2xHalf(uint)
1922 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001923 Module &M = *F.getParent();
1924 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001925 auto Index = CI->getOperand(0);
1926 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001927
Kévin Petite8edce32019-04-10 14:23:32 +01001928 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001929 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1930 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001931 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001932
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001933 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001934 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001935
Kévin Petite8edce32019-04-10 14:23:32 +01001936 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001937 auto X =
1938 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1939 auto Y =
1940 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001941
Kévin Petite8edce32019-04-10 14:23:32 +01001942 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001943 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001944
Kévin Petite8edce32019-04-10 14:23:32 +01001945 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001946
Kévin Petite8edce32019-04-10 14:23:32 +01001947 // Get the lower (x & y) components of our final float4.
1948 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001949
Kévin Petite8edce32019-04-10 14:23:32 +01001950 // Get the higher (z & w) components of our final float4.
1951 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001952
Kévin Petite8edce32019-04-10 14:23:32 +01001953 Constant *ShuffleMask[4] = {
1954 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1955 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001956
Kévin Petite8edce32019-04-10 14:23:32 +01001957 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001958 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1959 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001960 });
David Neto6ad93232018-06-07 15:42:58 -07001961}
1962
SJW2c317da2020-03-23 07:39:13 -05001963bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1964 switch (vec_size) {
1965 case 0:
1966 return replaceVstoreHalf(F);
1967 case 2:
1968 return replaceVstoreHalf2(F);
1969 case 4:
1970 return replaceVstoreHalf4(F);
1971 default:
1972 llvm_unreachable("Unsupported vstore_half vector size");
1973 break;
1974 }
1975 return false;
1976}
David Neto22f144c2017-06-12 14:26:21 -04001977
SJW2c317da2020-03-23 07:39:13 -05001978bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1979 Module &M = *F.getParent();
1980 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001981 // The value to store.
1982 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001983
Kévin Petite8edce32019-04-10 14:23:32 +01001984 // The index argument from vstore_half.
1985 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001986
Kévin Petite8edce32019-04-10 14:23:32 +01001987 // The pointer argument from vstore_half.
1988 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001989
Kévin Petite8edce32019-04-10 14:23:32 +01001990 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001991 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001992 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1993 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001994
Kévin Petite8edce32019-04-10 14:23:32 +01001995 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001996 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001997
Kévin Petite8edce32019-04-10 14:23:32 +01001998 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001999
Kévin Petite8edce32019-04-10 14:23:32 +01002000 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002001 auto TempVec = InsertElementInst::Create(
2002 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002003
Kévin Petite8edce32019-04-10 14:23:32 +01002004 // Pack the float2 -> half2 (in an int).
2005 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002006
alan-baker7efcaaa2020-05-06 19:33:27 -04002007 bool supports_16bit_storage = true;
2008 switch (Arg2->getType()->getPointerAddressSpace()) {
2009 case clspv::AddressSpace::Global:
2010 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2011 clspv::Option::StorageClass::kSSBO);
2012 break;
2013 case clspv::AddressSpace::Constant:
2014 if (clspv::Option::ConstantArgsInUniformBuffer())
2015 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2016 clspv::Option::StorageClass::kUBO);
2017 else
2018 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2019 clspv::Option::StorageClass::kSSBO);
2020 break;
2021 default:
2022 // Clspv will emit the Float16 capability if the half type is
2023 // encountered. That capability covers private and local addressspaces.
2024 break;
2025 }
2026
SJW2c317da2020-03-23 07:39:13 -05002027 Value *V = nullptr;
alan-baker7efcaaa2020-05-06 19:33:27 -04002028 if (supports_16bit_storage) {
Kévin Petite8edce32019-04-10 14:23:32 +01002029 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002030 auto ShortPointerTy =
2031 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002032
Kévin Petite8edce32019-04-10 14:23:32 +01002033 // Truncate our i32 to an i16.
2034 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002035
Kévin Petite8edce32019-04-10 14:23:32 +01002036 // Cast the half* pointer to short*.
2037 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002038
Kévin Petite8edce32019-04-10 14:23:32 +01002039 // Index into the correct address of the casted pointer.
2040 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002041
Kévin Petite8edce32019-04-10 14:23:32 +01002042 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05002043 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002044 } else {
2045 // We can only write to 32-bit aligned words.
2046 //
2047 // Assuming base is aligned to 32-bits, replace the equivalent of
2048 // vstore_half(value, index, base)
2049 // with:
2050 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
2051 // uint32_t write_to_upper_half = index & 1u;
2052 // uint32_t shift = write_to_upper_half << 4;
2053 //
2054 // // Pack the float value as a half number in bottom 16 bits
2055 // // of an i32.
2056 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
2057 //
2058 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
2059 // ^ ((packed & 0xffff) << shift)
2060 // // We only need relaxed consistency, but OpenCL 1.2 only has
2061 // // sequentially consistent atomics.
2062 // // TODO(dneto): Use relaxed consistency.
2063 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002064 auto IntPointerTy =
2065 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002066
Kévin Petite8edce32019-04-10 14:23:32 +01002067 auto Four = ConstantInt::get(IntTy, 4);
2068 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04002069
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002070 auto IndexIsOdd =
2071 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002072 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002073 auto IndexIntoI32 =
2074 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
2075 auto BaseI32Ptr =
2076 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
2077 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
2078 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04002079 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002080 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002081 auto MaskBitsToWrite =
2082 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
2083 auto MaskedCurrent = BinaryOperator::CreateAnd(
2084 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04002085
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002086 auto XLowerBits =
2087 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
2088 auto NewBitsToWrite =
2089 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
2090 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
2091 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04002092
Kévin Petite8edce32019-04-10 14:23:32 +01002093 // Generate the call to atomi_xor.
2094 SmallVector<Type *, 5> ParamTypes;
2095 // The pointer type.
2096 ParamTypes.push_back(IntPointerTy);
2097 // The Types for memory scope, semantics, and value.
2098 ParamTypes.push_back(IntTy);
2099 ParamTypes.push_back(IntTy);
2100 ParamTypes.push_back(IntTy);
2101 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
2102 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04002103
Kévin Petite8edce32019-04-10 14:23:32 +01002104 const auto ConstantScopeDevice =
2105 ConstantInt::get(IntTy, spv::ScopeDevice);
2106 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
2107 // (SPIR-V Workgroup).
2108 const auto AddrSpaceSemanticsBits =
2109 IntPointerTy->getPointerAddressSpace() == 1
2110 ? spv::MemorySemanticsUniformMemoryMask
2111 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04002112
Kévin Petite8edce32019-04-10 14:23:32 +01002113 // We're using relaxed consistency here.
2114 const auto ConstantMemorySemantics =
2115 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
2116 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04002117
Kévin Petite8edce32019-04-10 14:23:32 +01002118 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
2119 ConstantMemorySemantics, ValueToXor};
2120 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05002121
2122 // Return a Nop so the old Call is removed
2123 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
2124 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002125 }
David Neto22f144c2017-06-12 14:26:21 -04002126
SJW2c317da2020-03-23 07:39:13 -05002127 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01002128 });
David Neto22f144c2017-06-12 14:26:21 -04002129}
2130
SJW2c317da2020-03-23 07:39:13 -05002131bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
2132 Module &M = *F.getParent();
2133 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002134 // The value to store.
2135 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002136
Kévin Petite8edce32019-04-10 14:23:32 +01002137 // The index argument from vstore_half.
2138 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002139
Kévin Petite8edce32019-04-10 14:23:32 +01002140 // The pointer argument from vstore_half.
2141 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002142
Kévin Petite8edce32019-04-10 14:23:32 +01002143 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002144 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002145 auto NewPointerTy =
2146 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002147 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002148
Kévin Petite8edce32019-04-10 14:23:32 +01002149 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002150 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002151
Kévin Petite8edce32019-04-10 14:23:32 +01002152 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002153
Kévin Petite8edce32019-04-10 14:23:32 +01002154 // Turn the packed x & y into the final packing.
2155 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002156
Kévin Petite8edce32019-04-10 14:23:32 +01002157 // Cast the half* pointer to int*.
2158 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002159
Kévin Petite8edce32019-04-10 14:23:32 +01002160 // Index into the correct address of the casted pointer.
2161 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002162
Kévin Petite8edce32019-04-10 14:23:32 +01002163 // Store to the int* we casted to.
2164 return new StoreInst(X, Index, CI);
2165 });
David Neto22f144c2017-06-12 14:26:21 -04002166}
2167
SJW2c317da2020-03-23 07:39:13 -05002168bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
2169 Module &M = *F.getParent();
2170 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002171 // The value to store.
2172 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002173
Kévin Petite8edce32019-04-10 14:23:32 +01002174 // The index argument from vstore_half.
2175 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002176
Kévin Petite8edce32019-04-10 14:23:32 +01002177 // The pointer argument from vstore_half.
2178 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002179
Kévin Petite8edce32019-04-10 14:23:32 +01002180 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002181 auto Int2Ty = FixedVectorType::get(IntTy, 2);
2182 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002183 auto NewPointerTy =
2184 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002185 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002186
Kévin Petite8edce32019-04-10 14:23:32 +01002187 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
2188 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04002189
Kévin Petite8edce32019-04-10 14:23:32 +01002190 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002191 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2192 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002193
Kévin Petite8edce32019-04-10 14:23:32 +01002194 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
2195 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002196
Kévin Petite8edce32019-04-10 14:23:32 +01002197 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002198 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2199 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002200
Kévin Petite8edce32019-04-10 14:23:32 +01002201 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002202 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002203
Kévin Petite8edce32019-04-10 14:23:32 +01002204 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002205
Kévin Petite8edce32019-04-10 14:23:32 +01002206 // Turn the packed x & y into the final component of our int2.
2207 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002208
Kévin Petite8edce32019-04-10 14:23:32 +01002209 // Turn the packed z & w into the final component of our int2.
2210 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002211
Kévin Petite8edce32019-04-10 14:23:32 +01002212 auto Combine = InsertElementInst::Create(
2213 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002214 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
2215 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002216
Kévin Petite8edce32019-04-10 14:23:32 +01002217 // Cast the half* pointer to int2*.
2218 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002219
Kévin Petite8edce32019-04-10 14:23:32 +01002220 // Index into the correct address of the casted pointer.
2221 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002222
Kévin Petite8edce32019-04-10 14:23:32 +01002223 // Store to the int2* we casted to.
2224 return new StoreInst(Combine, Index, CI);
2225 });
David Neto22f144c2017-06-12 14:26:21 -04002226}
2227
SJW2c317da2020-03-23 07:39:13 -05002228bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
2229 // convert half to float
2230 Module &M = *F.getParent();
2231 return replaceCallsWithValue(F, [&](CallInst *CI) {
2232 SmallVector<Type *, 3> types;
2233 SmallVector<Value *, 3> args;
2234 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
2235 types.push_back(CI->getArgOperand(i)->getType());
2236 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05002237 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05002238
alan-baker5a8c3be2020-09-09 13:44:26 -04002239 auto NewFType =
2240 FunctionType::get(FixedVectorType::get(Type::getFloatTy(M.getContext()),
2241 cast<VectorType>(CI->getType())
2242 ->getElementCount()
2243 .getKnownMinValue()),
2244 types, false);
SJW2c317da2020-03-23 07:39:13 -05002245
SJW61531372020-06-09 07:31:08 -05002246 std::string NewFName =
2247 Builtins::GetMangledFunctionName("read_imagef", NewFType);
SJW2c317da2020-03-23 07:39:13 -05002248
2249 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2250
2251 auto NewCI = CallInst::Create(NewF, args, "", CI);
2252
2253 // Convert to the half type.
2254 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2255 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002256}
2257
SJW2c317da2020-03-23 07:39:13 -05002258bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
2259 // convert half to float
2260 Module &M = *F.getParent();
2261 return replaceCallsWithValue(F, [&](CallInst *CI) {
2262 SmallVector<Type *, 3> types(3);
2263 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002264
SJW2c317da2020-03-23 07:39:13 -05002265 // Image
2266 types[0] = CI->getArgOperand(0)->getType();
2267 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002268
SJW2c317da2020-03-23 07:39:13 -05002269 // Coord
2270 types[1] = CI->getArgOperand(1)->getType();
2271 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002272
SJW2c317da2020-03-23 07:39:13 -05002273 // Data
alan-baker5a8c3be2020-09-09 13:44:26 -04002274 types[2] =
2275 FixedVectorType::get(Type::getFloatTy(M.getContext()),
2276 cast<VectorType>(CI->getArgOperand(2)->getType())
2277 ->getElementCount()
2278 .getKnownMinValue());
alan-bakerf7e17cb2020-01-02 07:29:59 -05002279
SJW2c317da2020-03-23 07:39:13 -05002280 auto NewFType =
2281 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002282
SJW61531372020-06-09 07:31:08 -05002283 std::string NewFName =
2284 Builtins::GetMangledFunctionName("write_imagef", NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002285
SJW2c317da2020-03-23 07:39:13 -05002286 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002287
SJW2c317da2020-03-23 07:39:13 -05002288 // Convert data to the float type.
2289 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2290 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002291
SJW2c317da2020-03-23 07:39:13 -05002292 return CallInst::Create(NewF, args, "", CI);
2293 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002294}
2295
SJW2c317da2020-03-23 07:39:13 -05002296bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2297 Function &F) {
2298 // convert read_image with int coords to float coords
2299 Module &M = *F.getParent();
2300 return replaceCallsWithValue(F, [&](CallInst *CI) {
2301 // The image.
2302 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002303
SJW2c317da2020-03-23 07:39:13 -05002304 // The sampler.
2305 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002306
SJW2c317da2020-03-23 07:39:13 -05002307 // The coordinate (integer type that we can't handle).
2308 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002309
SJW2c317da2020-03-23 07:39:13 -05002310 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2311 uint32_t components =
2312 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2313 Type *float_ty = nullptr;
2314 if (components == 1) {
2315 float_ty = Type::getFloatTy(M.getContext());
2316 } else {
alan-baker5a8c3be2020-09-09 13:44:26 -04002317 float_ty = FixedVectorType::get(Type::getFloatTy(M.getContext()),
2318 cast<VectorType>(Arg2->getType())
2319 ->getElementCount()
2320 .getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04002321 }
David Neto22f144c2017-06-12 14:26:21 -04002322
SJW2c317da2020-03-23 07:39:13 -05002323 auto NewFType = FunctionType::get(
2324 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2325
2326 std::string NewFName = F.getName().str();
2327 NewFName[NewFName.length() - 1] = 'f';
2328
2329 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2330
2331 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2332
2333 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2334 });
David Neto22f144c2017-06-12 14:26:21 -04002335}
2336
SJW2c317da2020-03-23 07:39:13 -05002337bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2338 return replaceCallsWithValue(F, [&](CallInst *CI) {
2339 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002340
SJW2c317da2020-03-23 07:39:13 -05002341 // We need to map the OpenCL constants to the SPIR-V equivalents.
2342 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2343 const auto ConstantMemorySemantics = ConstantInt::get(
2344 IntTy, spv::MemorySemanticsUniformMemoryMask |
2345 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002346
SJW2c317da2020-03-23 07:39:13 -05002347 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002348
SJW2c317da2020-03-23 07:39:13 -05002349 // The pointer.
2350 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002351
SJW2c317da2020-03-23 07:39:13 -05002352 // The memory scope.
2353 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002354
SJW2c317da2020-03-23 07:39:13 -05002355 // The memory semantics.
2356 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002357
SJW2c317da2020-03-23 07:39:13 -05002358 if (2 < CI->getNumArgOperands()) {
2359 // The unequal memory semantics.
2360 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002361
SJW2c317da2020-03-23 07:39:13 -05002362 // The value.
2363 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002364
SJW2c317da2020-03-23 07:39:13 -05002365 // The comparator.
2366 Params.push_back(CI->getArgOperand(1));
2367 } else if (1 < CI->getNumArgOperands()) {
2368 // The value.
2369 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002370 }
David Neto22f144c2017-06-12 14:26:21 -04002371
SJW2c317da2020-03-23 07:39:13 -05002372 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2373 });
David Neto22f144c2017-06-12 14:26:21 -04002374}
2375
SJW2c317da2020-03-23 07:39:13 -05002376bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2377 llvm::AtomicRMWInst::BinOp Op) {
2378 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerd0eb9052020-07-07 13:12:01 -04002379 auto align = F.getParent()->getDataLayout().getABITypeAlign(
2380 CI->getArgOperand(1)->getType());
SJW2c317da2020-03-23 07:39:13 -05002381 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
alan-bakerd0eb9052020-07-07 13:12:01 -04002382 align, AtomicOrdering::SequentiallyConsistent,
SJW2c317da2020-03-23 07:39:13 -05002383 SyncScope::System, CI);
2384 });
2385}
David Neto22f144c2017-06-12 14:26:21 -04002386
SJW2c317da2020-03-23 07:39:13 -05002387bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2388 Module &M = *F.getParent();
2389 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002390 auto IntTy = Type::getInt32Ty(M.getContext());
2391 auto FloatTy = Type::getFloatTy(M.getContext());
2392
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002393 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2394 ConstantInt::get(IntTy, 1),
2395 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002396
2397 Constant *UpShuffleMask[4] = {
2398 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2399 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2400
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002401 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2402 UndefValue::get(FloatTy),
2403 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002404
Kévin Petite8edce32019-04-10 14:23:32 +01002405 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002406 auto Arg0 =
2407 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2408 ConstantVector::get(DownShuffleMask), "", CI);
2409 auto Arg1 =
2410 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2411 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002412 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002413
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002414 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
SJW61531372020-06-09 07:31:08 -05002415 auto NewFName = Builtins::GetMangledFunctionName("cross", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002416
SJW61531372020-06-09 07:31:08 -05002417 auto Cross3Func = M.getOrInsertFunction(NewFName, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002418
Kévin Petite8edce32019-04-10 14:23:32 +01002419 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002420
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002421 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2422 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002423 });
David Neto22f144c2017-06-12 14:26:21 -04002424}
David Neto62653202017-10-16 19:05:18 -04002425
SJW2c317da2020-03-23 07:39:13 -05002426bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002427 // OpenCL's float result = fract(float x, float* ptr)
2428 //
2429 // In the LLVM domain:
2430 //
2431 // %floor_result = call spir_func float @floor(float %x)
2432 // store float %floor_result, float * %ptr
2433 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2434 // %result = call spir_func float
2435 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2436 //
2437 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2438 // and clspv.fract occur in the SPIR-V generator pass:
2439 //
2440 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2441 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2442 // ...
2443 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2444 // OpStore %ptr %floor_result
2445 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2446 // %fract_result = OpExtInst %float
Marco Antognini55d51862020-07-21 17:50:07 +01002447 // %glsl_ext Nmin %fract_intermediate %just_under_1
David Neto62653202017-10-16 19:05:18 -04002448
David Neto62653202017-10-16 19:05:18 -04002449 using std::string;
2450
2451 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2452 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002453
SJW2c317da2020-03-23 07:39:13 -05002454 Module &M = *F.getParent();
2455 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto62653202017-10-16 19:05:18 -04002456
SJW2c317da2020-03-23 07:39:13 -05002457 // This is either float or a float vector. All the float-like
2458 // types are this type.
2459 auto result_ty = F.getReturnType();
2460
SJW61531372020-06-09 07:31:08 -05002461 std::string fmin_name = Builtins::GetMangledFunctionName("fmin", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002462 Function *fmin_fn = M.getFunction(fmin_name);
2463 if (!fmin_fn) {
2464 // Make the fmin function.
2465 FunctionType *fn_ty =
2466 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2467 fmin_fn =
2468 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2469 fmin_fn->addFnAttr(Attribute::ReadNone);
2470 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2471 }
2472
SJW61531372020-06-09 07:31:08 -05002473 std::string floor_name =
2474 Builtins::GetMangledFunctionName("floor", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002475 Function *floor_fn = M.getFunction(floor_name);
2476 if (!floor_fn) {
2477 // Make the floor function.
2478 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2479 floor_fn =
2480 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2481 floor_fn->addFnAttr(Attribute::ReadNone);
2482 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2483 }
2484
SJW61531372020-06-09 07:31:08 -05002485 std::string clspv_fract_name =
2486 Builtins::GetMangledFunctionName("clspv.fract", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002487 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2488 if (!clspv_fract_fn) {
2489 // Make the clspv_fract function.
2490 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2491 clspv_fract_fn = cast<Function>(
2492 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2493 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2494 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2495 }
2496
2497 // Number of significant significand bits, whether represented or not.
2498 unsigned num_significand_bits;
2499 switch (result_ty->getScalarType()->getTypeID()) {
2500 case Type::HalfTyID:
2501 num_significand_bits = 11;
2502 break;
2503 case Type::FloatTyID:
2504 num_significand_bits = 24;
2505 break;
2506 case Type::DoubleTyID:
2507 num_significand_bits = 53;
2508 break;
2509 default:
2510 llvm_unreachable("Unhandled float type when processing fract builtin");
2511 break;
2512 }
2513 // Beware that the disassembler displays this value as
2514 // OpConstant %float 1
2515 // which is not quite right.
2516 const double kJustUnderOneScalar =
2517 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2518
2519 Constant *just_under_one =
2520 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2521 if (result_ty->isVectorTy()) {
2522 just_under_one = ConstantVector::getSplat(
alan-baker931253b2020-08-20 17:15:38 -04002523 cast<VectorType>(result_ty)->getElementCount(), just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002524 }
2525
2526 IRBuilder<> Builder(CI);
2527
2528 auto arg = CI->getArgOperand(0);
2529 auto ptr = CI->getArgOperand(1);
2530
2531 // Compute floor result and store it.
2532 auto floor = Builder.CreateCall(floor_fn, {arg});
2533 Builder.CreateStore(floor, ptr);
2534
2535 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2536 auto fract_result =
2537 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2538
2539 return fract_result;
2540 });
David Neto62653202017-10-16 19:05:18 -04002541}
alan-bakera52b7312020-10-26 08:58:51 -04002542
Kévin Petit8576f682020-11-02 14:51:32 +00002543bool ReplaceOpenCLBuiltinPass::replaceHadd(Function &F, bool is_signed,
alan-bakerb6da5132020-10-29 15:59:06 -04002544 Instruction::BinaryOps join_opcode) {
Kévin Petit8576f682020-11-02 14:51:32 +00002545 return replaceCallsWithValue(F, [is_signed, join_opcode](CallInst *Call) {
alan-bakerb6da5132020-10-29 15:59:06 -04002546 // a_shr = a >> 1
2547 // b_shr = b >> 1
2548 // add1 = a_shr + b_shr
2549 // join = a |join_opcode| b
2550 // and = join & 1
2551 // add = add1 + and
2552 const auto a = Call->getArgOperand(0);
2553 const auto b = Call->getArgOperand(1);
2554 IRBuilder<> builder(Call);
Kévin Petit8576f682020-11-02 14:51:32 +00002555 Value *a_shift, *b_shift;
2556 if (is_signed) {
2557 a_shift = builder.CreateAShr(a, 1);
2558 b_shift = builder.CreateAShr(b, 1);
2559 } else {
2560 a_shift = builder.CreateLShr(a, 1);
2561 b_shift = builder.CreateLShr(b, 1);
2562 }
alan-bakerb6da5132020-10-29 15:59:06 -04002563 auto add = builder.CreateAdd(a_shift, b_shift);
2564 auto join = BinaryOperator::Create(join_opcode, a, b, "", Call);
2565 auto constant_one = ConstantInt::get(a->getType(), 1);
2566 auto and_bit = builder.CreateAnd(join, constant_one);
2567 return builder.CreateAdd(add, and_bit);
2568 });
2569}
2570
alan-baker3f1bf492020-11-05 09:07:36 -05002571bool ReplaceOpenCLBuiltinPass::replaceAddSubSat(Function &F, bool is_signed,
2572 bool is_add) {
2573 return replaceCallsWithValue(F, [&F, this, is_signed,
2574 is_add](CallInst *Call) {
2575 auto ty = Call->getType();
2576 auto a = Call->getArgOperand(0);
2577 auto b = Call->getArgOperand(1);
2578 IRBuilder<> builder(Call);
alan-bakera52b7312020-10-26 08:58:51 -04002579 if (is_signed) {
2580 unsigned bitwidth = ty->getScalarSizeInBits();
2581 if (bitwidth < 32) {
alan-baker3f1bf492020-11-05 09:07:36 -05002582 unsigned extended_width = bitwidth << 1;
2583 Type *extended_ty =
2584 IntegerType::get(Call->getContext(), extended_width);
2585 Constant *min = ConstantInt::get(
alan-bakera52b7312020-10-26 08:58:51 -04002586 Call->getContext(),
alan-baker3f1bf492020-11-05 09:07:36 -05002587 APInt::getSignedMinValue(bitwidth).sext(extended_width));
2588 Constant *max = ConstantInt::get(
alan-bakera52b7312020-10-26 08:58:51 -04002589 Call->getContext(),
alan-baker3f1bf492020-11-05 09:07:36 -05002590 APInt::getSignedMaxValue(bitwidth).sext(extended_width));
alan-bakera52b7312020-10-26 08:58:51 -04002591 // Don't use the type in GetMangledFunctionName to ensure we get
2592 // signed parameters.
2593 std::string sclamp_name = Builtins::GetMangledFunctionName("clamp");
alan-bakera52b7312020-10-26 08:58:51 -04002594 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
alan-baker3f1bf492020-11-05 09:07:36 -05002595 extended_ty = VectorType::get(extended_ty, vec_ty->getElementCount());
2596 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2597 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2598 unsigned vec_width = vec_ty->getElementCount().getKnownMinValue();
2599 if (extended_width == 32) {
alan-bakera52b7312020-10-26 08:58:51 -04002600 sclamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
alan-bakera52b7312020-10-26 08:58:51 -04002601 } else {
2602 sclamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2603 }
alan-baker3f1bf492020-11-05 09:07:36 -05002604 } else {
2605 if (extended_width == 32) {
2606 sclamp_name += "iii";
2607 } else {
2608 sclamp_name += "sss";
2609 }
alan-bakera52b7312020-10-26 08:58:51 -04002610 }
alan-baker3f1bf492020-11-05 09:07:36 -05002611
2612 auto sext_a = builder.CreateSExt(a, extended_ty);
2613 auto sext_b = builder.CreateSExt(b, extended_ty);
2614 Value *op = nullptr;
2615 // Extended operations won't wrap.
2616 if (is_add)
2617 op = builder.CreateAdd(sext_a, sext_b, "", true, true);
2618 else
2619 op = builder.CreateSub(sext_a, sext_b, "", true, true);
2620 auto clamp_ty = FunctionType::get(
2621 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2622 auto callee = F.getParent()->getOrInsertFunction(sclamp_name, clamp_ty);
2623 auto clamp = builder.CreateCall(callee, {op, min, max});
2624 return builder.CreateTrunc(clamp, ty);
alan-bakera52b7312020-10-26 08:58:51 -04002625 } else {
alan-baker3f1bf492020-11-05 09:07:36 -05002626 // Add:
2627 // c = a + b
alan-bakera52b7312020-10-26 08:58:51 -04002628 // if (b < 0)
2629 // c = c > a ? min : c;
2630 // else
alan-baker3f1bf492020-11-05 09:07:36 -05002631 // c = c < a ? max : c;
alan-bakera52b7312020-10-26 08:58:51 -04002632 //
alan-baker3f1bf492020-11-05 09:07:36 -05002633 // Sub:
2634 // c = a - b;
2635 // if (b < 0)
2636 // c = c < a ? max : c;
2637 // else
2638 // c = c > a ? min : c;
2639 Constant *min = ConstantInt::get(Call->getContext(),
2640 APInt::getSignedMinValue(bitwidth));
2641 Constant *max = ConstantInt::get(Call->getContext(),
2642 APInt::getSignedMaxValue(bitwidth));
alan-bakera52b7312020-10-26 08:58:51 -04002643 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2644 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2645 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2646 }
alan-baker3f1bf492020-11-05 09:07:36 -05002647 Value *op = nullptr;
2648 if (is_add) {
2649 op = builder.CreateAdd(a, b);
2650 } else {
2651 op = builder.CreateSub(a, b);
2652 }
2653 auto b_lt_0 = builder.CreateICmpSLT(b, Constant::getNullValue(ty));
2654 auto op_gt_a = builder.CreateICmpSGT(op, a);
2655 auto op_lt_a = builder.CreateICmpSLT(op, a);
2656 auto neg_cmp = is_add ? op_gt_a : op_lt_a;
2657 auto pos_cmp = is_add ? op_lt_a : op_gt_a;
2658 auto neg_value = is_add ? min : max;
2659 auto pos_value = is_add ? max : min;
2660 auto neg_clamp = builder.CreateSelect(neg_cmp, neg_value, op);
2661 auto pos_clamp = builder.CreateSelect(pos_cmp, pos_value, op);
2662 return builder.CreateSelect(b_lt_0, neg_clamp, pos_clamp);
alan-bakera52b7312020-10-26 08:58:51 -04002663 }
2664 } else {
alan-baker3f1bf492020-11-05 09:07:36 -05002665 // Replace with OpIAddCarry/OpISubBorrow and clamp to max/0 on a
2666 // carr/borrow.
2667 spv::Op op = is_add ? spv::OpIAddCarry : spv::OpISubBorrow;
2668 auto clamp_value =
2669 is_add ? Constant::getAllOnesValue(ty) : Constant::getNullValue(ty);
2670 auto struct_ty = GetPairStruct(ty);
2671 auto call =
2672 InsertSPIRVOp(Call, op, {Attribute::ReadNone}, struct_ty, {a, b});
2673 auto add_sub = builder.CreateExtractValue(call, {0});
2674 auto carry_borrow = builder.CreateExtractValue(call, {1});
2675 auto cmp = builder.CreateICmpEQ(carry_borrow, Constant::getNullValue(ty));
2676 return builder.CreateSelect(cmp, add_sub, clamp_value);
alan-bakera52b7312020-10-26 08:58:51 -04002677 }
alan-bakera52b7312020-10-26 08:58:51 -04002678 });
2679}
alan-baker4986eff2020-10-29 13:38:00 -04002680
2681bool ReplaceOpenCLBuiltinPass::replaceAtomicLoad(Function &F) {
2682 return replaceCallsWithValue(F, [](CallInst *Call) {
2683 auto pointer = Call->getArgOperand(0);
2684 // Clang emits an address space cast to the generic address space. Skip the
2685 // cast and use the input directly.
2686 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2687 pointer = cast->getPointerOperand();
2688 }
2689 Value *order_arg =
2690 Call->getNumArgOperands() > 1 ? Call->getArgOperand(1) : nullptr;
2691 Value *scope_arg =
2692 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2693 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2694 clspv::AddressSpace::Global;
2695 auto order = MemoryOrderSemantics(order_arg, is_global, Call,
2696 spv::MemorySemanticsAcquireMask);
2697 auto scope = MemoryScope(scope_arg, is_global, Call);
2698 return InsertSPIRVOp(Call, spv::OpAtomicLoad, {Attribute::Convergent},
2699 Call->getType(), {pointer, scope, order});
2700 });
2701}
2702
2703bool ReplaceOpenCLBuiltinPass::replaceExplicitAtomics(
2704 Function &F, spv::Op Op, spv::MemorySemanticsMask semantics) {
2705 return replaceCallsWithValue(F, [Op, semantics](CallInst *Call) {
2706 auto pointer = Call->getArgOperand(0);
2707 // Clang emits an address space cast to the generic address space. Skip the
2708 // cast and use the input directly.
2709 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2710 pointer = cast->getPointerOperand();
2711 }
2712 Value *value = Call->getArgOperand(1);
2713 Value *order_arg =
2714 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2715 Value *scope_arg =
2716 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2717 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2718 clspv::AddressSpace::Global;
2719 auto scope = MemoryScope(scope_arg, is_global, Call);
2720 auto order = MemoryOrderSemantics(order_arg, is_global, Call, semantics);
2721 return InsertSPIRVOp(Call, Op, {Attribute::Convergent}, Call->getType(),
2722 {pointer, scope, order, value});
2723 });
2724}
2725
2726bool ReplaceOpenCLBuiltinPass::replaceAtomicCompareExchange(Function &F) {
2727 return replaceCallsWithValue(F, [](CallInst *Call) {
2728 auto pointer = Call->getArgOperand(0);
2729 // Clang emits an address space cast to the generic address space. Skip the
2730 // cast and use the input directly.
2731 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2732 pointer = cast->getPointerOperand();
2733 }
2734 auto expected = Call->getArgOperand(1);
2735 if (auto cast = dyn_cast<AddrSpaceCastOperator>(expected)) {
2736 expected = cast->getPointerOperand();
2737 }
2738 auto value = Call->getArgOperand(2);
2739 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2740 clspv::AddressSpace::Global;
2741 Value *success_arg =
2742 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2743 Value *failure_arg =
2744 Call->getNumArgOperands() > 4 ? Call->getArgOperand(4) : nullptr;
2745 Value *scope_arg =
2746 Call->getNumArgOperands() > 5 ? Call->getArgOperand(5) : nullptr;
2747 auto scope = MemoryScope(scope_arg, is_global, Call);
2748 auto success = MemoryOrderSemantics(success_arg, is_global, Call,
2749 spv::MemorySemanticsAcquireReleaseMask);
2750 auto failure = MemoryOrderSemantics(failure_arg, is_global, Call,
2751 spv::MemorySemanticsAcquireMask);
2752
2753 // If the value pointed to by |expected| equals the value pointed to by
2754 // |pointer|, |value| is written into |pointer|, otherwise the value in
2755 // |pointer| is written into |expected|. In order to avoid extra stores,
2756 // the basic block with the original atomic is split and the store is
2757 // performed in the |then| block. The condition is the inversion of the
2758 // comparison result.
2759 IRBuilder<> builder(Call);
2760 auto load = builder.CreateLoad(expected);
2761 auto cmp_xchg = InsertSPIRVOp(
2762 Call, spv::OpAtomicCompareExchange, {Attribute::Convergent},
2763 value->getType(), {pointer, scope, success, failure, value, load});
2764 auto cmp = builder.CreateICmpEQ(cmp_xchg, load);
2765 auto not_cmp = builder.CreateNot(cmp);
2766 auto then_branch = SplitBlockAndInsertIfThen(not_cmp, Call, false);
2767 builder.SetInsertPoint(then_branch);
2768 builder.CreateStore(cmp_xchg, expected);
2769 return cmp;
2770 });
2771}
alan-bakercc2bafb2020-11-02 08:30:18 -05002772
alan-baker2cecaa72020-11-05 14:05:20 -05002773bool ReplaceOpenCLBuiltinPass::replaceCountZeroes(Function &F, bool leading) {
alan-bakercc2bafb2020-11-02 08:30:18 -05002774 if (!isa<IntegerType>(F.getReturnType()->getScalarType()))
2775 return false;
2776
2777 auto bitwidth = F.getReturnType()->getScalarSizeInBits();
2778 if (bitwidth == 32 || bitwidth > 64)
2779 return false;
2780
alan-baker2cecaa72020-11-05 14:05:20 -05002781 return replaceCallsWithValue(F, [&F, bitwidth, leading](CallInst *Call) {
alan-bakercc2bafb2020-11-02 08:30:18 -05002782 auto in = Call->getArgOperand(0);
2783 IRBuilder<> builder(Call);
2784 auto int32_ty = builder.getInt32Ty();
2785 Type *ty = int32_ty;
alan-baker2cecaa72020-11-05 14:05:20 -05002786 Constant *c32 = builder.getInt32(32);
alan-bakercc2bafb2020-11-02 08:30:18 -05002787 if (auto vec_ty = dyn_cast<VectorType>(Call->getType())) {
2788 ty = VectorType::get(ty, vec_ty->getElementCount());
alan-baker2cecaa72020-11-05 14:05:20 -05002789 c32 = ConstantVector::getSplat(vec_ty->getElementCount(), c32);
alan-bakercc2bafb2020-11-02 08:30:18 -05002790 }
alan-baker2cecaa72020-11-05 14:05:20 -05002791 auto func_32bit_ty = FunctionType::get(ty, {ty}, false);
2792 std::string func_32bit_name =
2793 Builtins::GetMangledFunctionName((leading ? "clz" : "ctz"), ty);
2794 auto func_32bit =
2795 F.getParent()->getOrInsertFunction(func_32bit_name, func_32bit_ty);
alan-bakercc2bafb2020-11-02 08:30:18 -05002796 if (bitwidth < 32) {
alan-baker2cecaa72020-11-05 14:05:20 -05002797 // Extend the input to 32-bits and perform a clz/ctz.
alan-bakercc2bafb2020-11-02 08:30:18 -05002798 auto zext = builder.CreateZExt(in, ty);
alan-baker2cecaa72020-11-05 14:05:20 -05002799 Value *call_input = zext;
2800 if (!leading) {
2801 // Or the extended input value with a constant that caps the max to the
2802 // right bitwidth (e.g. 256 for i8 and 65536 for i16).
2803 Constant *mask = builder.getInt32(1 << bitwidth);
2804 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2805 mask = ConstantVector::getSplat(vec_ty->getElementCount(), mask);
2806 }
2807 call_input = builder.CreateOr(zext, mask);
alan-bakercc2bafb2020-11-02 08:30:18 -05002808 }
alan-baker2cecaa72020-11-05 14:05:20 -05002809 auto call = builder.CreateCall(func_32bit, {call_input});
2810 Value *tmp = call;
2811 if (leading) {
2812 // Clz is implemented as 31 - FindUMsb(|zext|), so adjust the result
2813 // the right bitwidth.
2814 Constant *sub_const = builder.getInt32(32 - bitwidth);
2815 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2816 sub_const =
2817 ConstantVector::getSplat(vec_ty->getElementCount(), sub_const);
2818 }
2819 tmp = builder.CreateSub(call, sub_const);
2820 }
2821 // Truncate the intermediate result to the right size.
2822 return builder.CreateTrunc(tmp, Call->getType());
alan-bakercc2bafb2020-11-02 08:30:18 -05002823 } else {
alan-baker2cecaa72020-11-05 14:05:20 -05002824 // Perform a 32-bit version of clz/ctz on each half of the 64-bit input.
alan-bakercc2bafb2020-11-02 08:30:18 -05002825 auto lshr = builder.CreateLShr(in, 32);
2826 auto top_bits = builder.CreateTrunc(lshr, ty);
2827 auto bot_bits = builder.CreateTrunc(in, ty);
alan-baker2cecaa72020-11-05 14:05:20 -05002828 auto top_func = builder.CreateCall(func_32bit, {top_bits});
2829 auto bot_func = builder.CreateCall(func_32bit, {bot_bits});
2830 Value *tmp = nullptr;
2831 if (leading) {
2832 // For clz, if clz(top) is 32, return 32 + clz(bot).
2833 auto cmp = builder.CreateICmpEQ(top_func, c32);
2834 auto adjust = builder.CreateAdd(bot_func, c32);
2835 tmp = builder.CreateSelect(cmp, adjust, top_func);
2836 } else {
2837 // For ctz, if clz(bot) is 32, return 32 + ctz(top)
2838 auto bot_cmp = builder.CreateICmpEQ(bot_func, c32);
2839 auto adjust = builder.CreateAdd(top_func, c32);
2840 tmp = builder.CreateSelect(bot_cmp, adjust, bot_func);
alan-bakercc2bafb2020-11-02 08:30:18 -05002841 }
alan-baker2cecaa72020-11-05 14:05:20 -05002842 // Extend the intermediate result to the correct size.
2843 return builder.CreateZExt(tmp, Call->getType());
alan-bakercc2bafb2020-11-02 08:30:18 -05002844 }
2845 });
2846}
alan-baker6b9d1ee2020-11-03 23:11:32 -05002847
2848bool ReplaceOpenCLBuiltinPass::replaceMadSat(Function &F, bool is_signed) {
2849 return replaceCallsWithValue(F, [&F, is_signed, this](CallInst *Call) {
2850 const auto ty = Call->getType();
2851 const auto a = Call->getArgOperand(0);
2852 const auto b = Call->getArgOperand(1);
2853 const auto c = Call->getArgOperand(2);
2854 IRBuilder<> builder(Call);
2855 if (is_signed) {
2856 unsigned bitwidth = Call->getType()->getScalarSizeInBits();
2857 if (bitwidth < 32) {
2858 // mul = sext(a) * sext(b)
2859 // add = mul + sext(c)
2860 // res = clamp(add, MIN, MAX)
2861 unsigned extended_width = bitwidth << 1;
2862 Type *extended_ty = IntegerType::get(F.getContext(), extended_width);
2863 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2864 extended_ty = VectorType::get(extended_ty, vec_ty->getElementCount());
2865 }
2866 auto a_sext = builder.CreateSExt(a, extended_ty);
2867 auto b_sext = builder.CreateSExt(b, extended_ty);
2868 auto c_sext = builder.CreateSExt(c, extended_ty);
2869 // Extended the size so no overflows occur.
2870 auto mul = builder.CreateMul(a_sext, b_sext, "", true, true);
2871 auto add = builder.CreateAdd(mul, c_sext, "", true, true);
2872 auto func_ty = FunctionType::get(
2873 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2874 // Don't use function type because we need signed parameters.
2875 std::string clamp_name = Builtins::GetMangledFunctionName("clamp");
2876 // The clamp values are the signed min and max of the original bitwidth
2877 // sign extended to the extended bitwidth.
2878 Constant *min = ConstantInt::get(
2879 Call->getContext(),
2880 APInt::getSignedMinValue(bitwidth).sext(extended_width));
2881 Constant *max = ConstantInt::get(
2882 Call->getContext(),
2883 APInt::getSignedMaxValue(bitwidth).sext(extended_width));
2884 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2885 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2886 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2887 unsigned vec_width = vec_ty->getElementCount().getKnownMinValue();
2888 if (extended_width == 32)
2889 clamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
2890 else
2891 clamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2892 } else {
2893 if (extended_width == 32)
2894 clamp_name += "iii";
2895 else
2896 clamp_name += "sss";
2897 }
2898 auto callee = F.getParent()->getOrInsertFunction(clamp_name, func_ty);
2899 auto clamp = builder.CreateCall(callee, {add, min, max});
2900 return builder.CreateTrunc(clamp, ty);
2901 } else {
2902 auto struct_ty = GetPairStruct(ty);
2903 // Compute
2904 // {hi, lo} = smul_extended(a, b)
2905 // add = lo + c
2906 auto mul_ext = InsertSPIRVOp(Call, spv::OpSMulExtended,
2907 {Attribute::ReadNone}, struct_ty, {a, b});
2908 auto mul_lo = builder.CreateExtractValue(mul_ext, {0});
2909 auto mul_hi = builder.CreateExtractValue(mul_ext, {1});
2910 auto add = builder.CreateAdd(mul_lo, c);
2911
2912 // Constants for use in the calculation.
2913 Constant *min = ConstantInt::get(Call->getContext(),
2914 APInt::getSignedMinValue(bitwidth));
2915 Constant *max = ConstantInt::get(Call->getContext(),
2916 APInt::getSignedMaxValue(bitwidth));
2917 Constant *max_plus_1 = ConstantInt::get(
2918 Call->getContext(),
2919 APInt::getSignedMaxValue(bitwidth) + APInt(bitwidth, 1));
2920 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2921 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2922 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2923 max_plus_1 =
2924 ConstantVector::getSplat(vec_ty->getElementCount(), max_plus_1);
2925 }
2926
2927 auto a_xor_b = builder.CreateXor(a, b);
2928 auto same_sign =
2929 builder.CreateICmpSGT(a_xor_b, Constant::getAllOnesValue(ty));
2930 auto different_sign = builder.CreateNot(same_sign);
2931 auto hi_eq_0 = builder.CreateICmpEQ(mul_hi, Constant::getNullValue(ty));
2932 auto hi_ne_0 = builder.CreateNot(hi_eq_0);
2933 auto lo_ge_max = builder.CreateICmpUGE(mul_lo, max);
2934 auto c_gt_0 = builder.CreateICmpSGT(c, Constant::getNullValue(ty));
2935 auto c_lt_0 = builder.CreateICmpSLT(c, Constant::getNullValue(ty));
2936 auto add_gt_max = builder.CreateICmpUGT(add, max);
2937 auto hi_eq_m1 =
2938 builder.CreateICmpEQ(mul_hi, Constant::getAllOnesValue(ty));
2939 auto hi_ne_m1 = builder.CreateNot(hi_eq_m1);
2940 auto lo_le_max_plus_1 = builder.CreateICmpULE(mul_lo, max_plus_1);
2941 auto max_sub_lo = builder.CreateSub(max, mul_lo);
2942 auto c_lt_max_sub_lo = builder.CreateICmpULT(c, max_sub_lo);
2943
2944 // Equivalent to:
2945 // if (((x < 0) == (y < 0)) && mul_hi != 0)
2946 // return MAX
2947 // if (mul_hi == 0 && mul_lo >= MAX && (z > 0 || add > MAX))
2948 // return MAX
2949 // if (((x < 0) != (y < 0)) && mul_hi != -1)
2950 // return MIN
2951 // if (hi == -1 && mul_lo <= (MAX + 1) && (z < 0 || z < (MAX - mul_lo))
2952 // return MIN
2953 // return add
2954 auto max_clamp_1 = builder.CreateAnd(same_sign, hi_ne_0);
2955 auto max_clamp_2 = builder.CreateOr(c_gt_0, add_gt_max);
2956 auto tmp = builder.CreateAnd(hi_eq_0, lo_ge_max);
2957 max_clamp_2 = builder.CreateAnd(tmp, max_clamp_2);
2958 auto max_clamp = builder.CreateOr(max_clamp_1, max_clamp_2);
2959 auto min_clamp_1 = builder.CreateAnd(different_sign, hi_ne_m1);
2960 auto min_clamp_2 = builder.CreateOr(c_lt_0, c_lt_max_sub_lo);
2961 tmp = builder.CreateAnd(hi_eq_m1, lo_le_max_plus_1);
2962 min_clamp_2 = builder.CreateAnd(tmp, min_clamp_2);
2963 auto min_clamp = builder.CreateOr(min_clamp_1, min_clamp_2);
2964 auto sel = builder.CreateSelect(min_clamp, min, add);
2965 return builder.CreateSelect(max_clamp, max, sel);
2966 }
2967 } else {
2968 // {lo, hi} = mul_extended(a, b)
2969 // {add, carry} = add_carry(lo, c)
2970 // cmp = (mul_hi | carry) == 0
2971 // mad_sat = cmp ? add : MAX
2972 auto struct_ty = GetPairStruct(ty);
2973 auto mul_ext = InsertSPIRVOp(Call, spv::OpUMulExtended,
2974 {Attribute::ReadNone}, struct_ty, {a, b});
2975 auto mul_lo = builder.CreateExtractValue(mul_ext, {0});
2976 auto mul_hi = builder.CreateExtractValue(mul_ext, {1});
2977 auto add_carry =
2978 InsertSPIRVOp(Call, spv::OpIAddCarry, {Attribute::ReadNone},
2979 struct_ty, {mul_lo, c});
2980 auto add = builder.CreateExtractValue(add_carry, {0});
2981 auto carry = builder.CreateExtractValue(add_carry, {1});
2982 auto or_value = builder.CreateOr(mul_hi, carry);
2983 auto cmp = builder.CreateICmpEQ(or_value, Constant::getNullValue(ty));
2984 return builder.CreateSelect(cmp, add, Constant::getAllOnesValue(ty));
2985 }
2986 });
2987}