blob: b9ac3859672f212996369c0f9d6cf9f8206a5e3f [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);
alan-baker3e217772020-11-07 17:29:40 -0500240 bool replaceRelational(Function &F, CmpInst::Predicate P);
SJW2c317da2020-03-23 07:39:13 -0500241 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);
alan-baker15106572020-11-06 15:08:10 -0500282 bool replaceOrdered(Function &F, bool is_ordered);
alan-baker497920b2020-11-09 16:41:36 -0500283 bool replaceIsNormal(Function &F);
alan-bakere0406e72020-11-10 12:32:04 -0500284 bool replaceFDim(Function &F);
alan-baker3e0de472020-12-08 15:57:17 -0500285 bool replaceRound(Function &F);
286 bool replaceTrigPi(Function &F, Builtins::BuiltinType type);
alan-baker6b9d1ee2020-11-03 23:11:32 -0500287
288 // Caches struct types for { |type|, |type| }. This prevents
289 // getOrInsertFunction from introducing a bitcasts between structs with
290 // identical contents.
291 Type *GetPairStruct(Type *type);
292
293 DenseMap<Type *, Type *> PairStructMap;
David Neto22f144c2017-06-12 14:26:21 -0400294};
SJW2c317da2020-03-23 07:39:13 -0500295
Kévin Petit91bc72e2019-04-08 15:17:46 +0100296} // namespace
David Neto22f144c2017-06-12 14:26:21 -0400297
298char ReplaceOpenCLBuiltinPass::ID = 0;
Diego Novilloa4c44fa2019-04-11 10:56:15 -0400299INITIALIZE_PASS(ReplaceOpenCLBuiltinPass, "ReplaceOpenCLBuiltin",
300 "Replace OpenCL Builtins Pass", false, false)
David Neto22f144c2017-06-12 14:26:21 -0400301
302namespace clspv {
303ModulePass *createReplaceOpenCLBuiltinPass() {
304 return new ReplaceOpenCLBuiltinPass();
305}
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400306} // namespace clspv
David Neto22f144c2017-06-12 14:26:21 -0400307
308bool ReplaceOpenCLBuiltinPass::runOnModule(Module &M) {
SJW2c317da2020-03-23 07:39:13 -0500309 std::list<Function *> func_list;
310 for (auto &F : M.getFunctionList()) {
311 // process only function declarations
312 if (F.isDeclaration() && runOnFunction(F)) {
313 func_list.push_front(&F);
Kévin Petit2444e9b2018-11-09 14:14:37 +0000314 }
315 }
SJW2c317da2020-03-23 07:39:13 -0500316 if (func_list.size() != 0) {
317 // recursively convert functions, but first remove dead
318 for (auto *F : func_list) {
319 if (F->use_empty()) {
320 F->eraseFromParent();
321 }
322 }
323 runOnModule(M);
324 return true;
325 }
326 return false;
Kévin Petit2444e9b2018-11-09 14:14:37 +0000327}
328
SJW2c317da2020-03-23 07:39:13 -0500329bool ReplaceOpenCLBuiltinPass::runOnFunction(Function &F) {
330 auto &FI = Builtins::Lookup(&F);
331 switch (FI.getType()) {
332 case Builtins::kAbs:
333 if (!FI.getParameter(0).is_signed) {
334 return replaceAbs(F);
335 }
336 break;
337 case Builtins::kAbsDiff:
338 return replaceAbsDiff(F, FI.getParameter(0).is_signed);
alan-bakera52b7312020-10-26 08:58:51 -0400339
340 case Builtins::kAddSat:
alan-baker3f1bf492020-11-05 09:07:36 -0500341 return replaceAddSubSat(F, FI.getParameter(0).is_signed, true);
alan-bakera52b7312020-10-26 08:58:51 -0400342
alan-bakercc2bafb2020-11-02 08:30:18 -0500343 case Builtins::kClz:
alan-baker2cecaa72020-11-05 14:05:20 -0500344 return replaceCountZeroes(F, true);
345
346 case Builtins::kCtz:
347 return replaceCountZeroes(F, false);
alan-bakercc2bafb2020-11-02 08:30:18 -0500348
alan-bakerb6da5132020-10-29 15:59:06 -0400349 case Builtins::kHadd:
Kévin Petit8576f682020-11-02 14:51:32 +0000350 return replaceHadd(F, FI.getParameter(0).is_signed, Instruction::And);
alan-bakerb6da5132020-10-29 15:59:06 -0400351 case Builtins::kRhadd:
Kévin Petit8576f682020-11-02 14:51:32 +0000352 return replaceHadd(F, FI.getParameter(0).is_signed, Instruction::Or);
alan-bakerb6da5132020-10-29 15:59:06 -0400353
SJW2c317da2020-03-23 07:39:13 -0500354 case Builtins::kCopysign:
355 return replaceCopysign(F);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100356
SJW2c317da2020-03-23 07:39:13 -0500357 case Builtins::kHalfRecip:
358 case Builtins::kNativeRecip:
359 return replaceRecip(F);
Kévin Petite8edce32019-04-10 14:23:32 +0100360
SJW2c317da2020-03-23 07:39:13 -0500361 case Builtins::kHalfDivide:
362 case Builtins::kNativeDivide:
363 return replaceDivide(F);
364
365 case Builtins::kDot:
366 return replaceDot(F);
367
368 case Builtins::kExp10:
369 case Builtins::kHalfExp10:
SJW61531372020-06-09 07:31:08 -0500370 case Builtins::kNativeExp10:
371 return replaceExp10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500372
373 case Builtins::kLog10:
374 case Builtins::kHalfLog10:
SJW61531372020-06-09 07:31:08 -0500375 case Builtins::kNativeLog10:
376 return replaceLog10(F, FI.getName());
SJW2c317da2020-03-23 07:39:13 -0500377
gnl21636e7992020-09-09 16:08:16 +0100378 case Builtins::kLog1p:
379 return replaceLog1p(F);
380
alan-bakere0406e72020-11-10 12:32:04 -0500381 case Builtins::kFdim:
382 return replaceFDim(F);
383
SJW2c317da2020-03-23 07:39:13 -0500384 case Builtins::kFmod:
385 return replaceFmod(F);
386
alan-baker3e0de472020-12-08 15:57:17 -0500387 case Builtins::kRound:
388 return replaceRound(F);
389
390 case Builtins::kCospi:
391 case Builtins::kSinpi:
392 case Builtins::kTanpi:
393 return replaceTrigPi(F, FI.getType());
394
SJW2c317da2020-03-23 07:39:13 -0500395 case Builtins::kBarrier:
396 case Builtins::kWorkGroupBarrier:
397 return replaceBarrier(F);
398
alan-baker12d2c182020-07-20 08:22:42 -0400399 case Builtins::kSubGroupBarrier:
400 return replaceBarrier(F, true);
401
SJW2c317da2020-03-23 07:39:13 -0500402 case Builtins::kMemFence:
alan-baker12d2c182020-07-20 08:22:42 -0400403 return replaceMemFence(F, spv::MemorySemanticsAcquireReleaseMask);
SJW2c317da2020-03-23 07:39:13 -0500404 case Builtins::kReadMemFence:
405 return replaceMemFence(F, spv::MemorySemanticsAcquireMask);
406 case Builtins::kWriteMemFence:
407 return replaceMemFence(F, spv::MemorySemanticsReleaseMask);
408
409 // Relational
410 case Builtins::kIsequal:
alan-baker3e217772020-11-07 17:29:40 -0500411 return replaceRelational(F, CmpInst::FCMP_OEQ);
SJW2c317da2020-03-23 07:39:13 -0500412 case Builtins::kIsgreater:
alan-baker3e217772020-11-07 17:29:40 -0500413 return replaceRelational(F, CmpInst::FCMP_OGT);
SJW2c317da2020-03-23 07:39:13 -0500414 case Builtins::kIsgreaterequal:
alan-baker3e217772020-11-07 17:29:40 -0500415 return replaceRelational(F, CmpInst::FCMP_OGE);
SJW2c317da2020-03-23 07:39:13 -0500416 case Builtins::kIsless:
alan-baker3e217772020-11-07 17:29:40 -0500417 return replaceRelational(F, CmpInst::FCMP_OLT);
SJW2c317da2020-03-23 07:39:13 -0500418 case Builtins::kIslessequal:
alan-baker3e217772020-11-07 17:29:40 -0500419 return replaceRelational(F, CmpInst::FCMP_OLE);
SJW2c317da2020-03-23 07:39:13 -0500420 case Builtins::kIsnotequal:
alan-baker3e217772020-11-07 17:29:40 -0500421 return replaceRelational(F, CmpInst::FCMP_UNE);
422 case Builtins::kIslessgreater:
423 return replaceRelational(F, CmpInst::FCMP_ONE);
SJW2c317da2020-03-23 07:39:13 -0500424
alan-baker15106572020-11-06 15:08:10 -0500425 case Builtins::kIsordered:
426 return replaceOrdered(F, true);
427
428 case Builtins::kIsunordered:
429 return replaceOrdered(F, false);
430
SJW2c317da2020-03-23 07:39:13 -0500431 case Builtins::kIsinf: {
432 bool is_vec = FI.getParameter(0).vector_size != 0;
433 return replaceIsInfAndIsNan(F, spv::OpIsInf, is_vec ? -1 : 1);
434 }
435 case Builtins::kIsnan: {
436 bool is_vec = FI.getParameter(0).vector_size != 0;
437 return replaceIsInfAndIsNan(F, spv::OpIsNan, is_vec ? -1 : 1);
438 }
439
440 case Builtins::kIsfinite:
441 return replaceIsFinite(F);
442
443 case Builtins::kAll: {
444 bool is_vec = FI.getParameter(0).vector_size != 0;
445 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAll);
446 }
447 case Builtins::kAny: {
448 bool is_vec = FI.getParameter(0).vector_size != 0;
449 return replaceAllAndAny(F, !is_vec ? spv::OpNop : spv::OpAny);
450 }
451
alan-baker497920b2020-11-09 16:41:36 -0500452 case Builtins::kIsnormal:
453 return replaceIsNormal(F);
454
SJW2c317da2020-03-23 07:39:13 -0500455 case Builtins::kUpsample:
456 return replaceUpsample(F);
457
458 case Builtins::kRotate:
459 return replaceRotate(F);
460
461 case Builtins::kConvert:
462 return replaceConvert(F, FI.getParameter(0).is_signed,
463 FI.getReturnType().is_signed);
464
alan-baker4986eff2020-10-29 13:38:00 -0400465 // OpenCL 2.0 explicit atomics have different default scopes and semantics
466 // than legacy atomic functions.
467 case Builtins::kAtomicLoad:
468 case Builtins::kAtomicLoadExplicit:
469 return replaceAtomicLoad(F);
470 case Builtins::kAtomicStore:
471 case Builtins::kAtomicStoreExplicit:
472 return replaceExplicitAtomics(F, spv::OpAtomicStore,
473 spv::MemorySemanticsReleaseMask);
474 case Builtins::kAtomicExchange:
475 case Builtins::kAtomicExchangeExplicit:
476 return replaceExplicitAtomics(F, spv::OpAtomicExchange);
477 case Builtins::kAtomicFetchAdd:
478 case Builtins::kAtomicFetchAddExplicit:
479 return replaceExplicitAtomics(F, spv::OpAtomicIAdd);
480 case Builtins::kAtomicFetchSub:
481 case Builtins::kAtomicFetchSubExplicit:
482 return replaceExplicitAtomics(F, spv::OpAtomicISub);
483 case Builtins::kAtomicFetchOr:
484 case Builtins::kAtomicFetchOrExplicit:
485 return replaceExplicitAtomics(F, spv::OpAtomicOr);
486 case Builtins::kAtomicFetchXor:
487 case Builtins::kAtomicFetchXorExplicit:
488 return replaceExplicitAtomics(F, spv::OpAtomicXor);
489 case Builtins::kAtomicFetchAnd:
490 case Builtins::kAtomicFetchAndExplicit:
491 return replaceExplicitAtomics(F, spv::OpAtomicAnd);
492 case Builtins::kAtomicFetchMin:
493 case Builtins::kAtomicFetchMinExplicit:
494 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
495 ? spv::OpAtomicSMin
496 : spv::OpAtomicUMin);
497 case Builtins::kAtomicFetchMax:
498 case Builtins::kAtomicFetchMaxExplicit:
499 return replaceExplicitAtomics(F, FI.getParameter(1).is_signed
500 ? spv::OpAtomicSMax
501 : spv::OpAtomicUMax);
502 // Weak compare exchange is generated as strong compare exchange.
503 case Builtins::kAtomicCompareExchangeWeak:
504 case Builtins::kAtomicCompareExchangeWeakExplicit:
505 case Builtins::kAtomicCompareExchangeStrong:
506 case Builtins::kAtomicCompareExchangeStrongExplicit:
507 return replaceAtomicCompareExchange(F);
508
509 // Legacy atomic functions.
SJW2c317da2020-03-23 07:39:13 -0500510 case Builtins::kAtomicInc:
511 return replaceAtomics(F, spv::OpAtomicIIncrement);
512 case Builtins::kAtomicDec:
513 return replaceAtomics(F, spv::OpAtomicIDecrement);
514 case Builtins::kAtomicCmpxchg:
515 return replaceAtomics(F, spv::OpAtomicCompareExchange);
516 case Builtins::kAtomicAdd:
517 return replaceAtomics(F, llvm::AtomicRMWInst::Add);
518 case Builtins::kAtomicSub:
519 return replaceAtomics(F, llvm::AtomicRMWInst::Sub);
520 case Builtins::kAtomicXchg:
521 return replaceAtomics(F, llvm::AtomicRMWInst::Xchg);
522 case Builtins::kAtomicMin:
523 return replaceAtomics(F, FI.getParameter(0).is_signed
524 ? llvm::AtomicRMWInst::Min
525 : llvm::AtomicRMWInst::UMin);
526 case Builtins::kAtomicMax:
527 return replaceAtomics(F, FI.getParameter(0).is_signed
528 ? llvm::AtomicRMWInst::Max
529 : llvm::AtomicRMWInst::UMax);
530 case Builtins::kAtomicAnd:
531 return replaceAtomics(F, llvm::AtomicRMWInst::And);
532 case Builtins::kAtomicOr:
533 return replaceAtomics(F, llvm::AtomicRMWInst::Or);
534 case Builtins::kAtomicXor:
535 return replaceAtomics(F, llvm::AtomicRMWInst::Xor);
536
537 case Builtins::kCross:
538 if (FI.getParameter(0).vector_size == 4) {
539 return replaceCross(F);
540 }
541 break;
542
543 case Builtins::kFract:
544 if (FI.getParameterCount()) {
545 return replaceFract(F, FI.getParameter(0).vector_size);
546 }
547 break;
548
549 case Builtins::kMadHi:
550 return replaceMulHi(F, FI.getParameter(0).is_signed, true);
551 case Builtins::kMulHi:
552 return replaceMulHi(F, FI.getParameter(0).is_signed, false);
553
alan-baker6b9d1ee2020-11-03 23:11:32 -0500554 case Builtins::kMadSat:
555 return replaceMadSat(F, FI.getParameter(0).is_signed);
556
SJW2c317da2020-03-23 07:39:13 -0500557 case Builtins::kMad:
558 case Builtins::kMad24:
559 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
560 true);
561 case Builtins::kMul24:
562 return replaceMul(F, FI.getParameter(0).type_id == llvm::Type::FloatTyID,
563 false);
564
565 case Builtins::kSelect:
566 return replaceSelect(F);
567
568 case Builtins::kBitselect:
569 return replaceBitSelect(F);
570
571 case Builtins::kVload:
572 return replaceVload(F);
573
574 case Builtins::kVloadaHalf:
575 case Builtins::kVloadHalf:
576 return replaceVloadHalf(F, FI.getName(), FI.getParameter(0).vector_size);
577
578 case Builtins::kVstore:
579 return replaceVstore(F);
580
581 case Builtins::kVstoreHalf:
582 case Builtins::kVstoreaHalf:
583 return replaceVstoreHalf(F, FI.getParameter(0).vector_size);
584
585 case Builtins::kSmoothstep: {
586 int vec_size = FI.getLastParameter().vector_size;
587 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500588 return replaceStep(F, true);
SJW2c317da2020-03-23 07:39:13 -0500589 }
590 break;
591 }
592 case Builtins::kStep: {
593 int vec_size = FI.getLastParameter().vector_size;
594 if (FI.getParameter(0).vector_size == 0 && vec_size != 0) {
SJW61531372020-06-09 07:31:08 -0500595 return replaceStep(F, false);
SJW2c317da2020-03-23 07:39:13 -0500596 }
597 break;
598 }
599
600 case Builtins::kSignbit:
601 return replaceSignbit(F, FI.getParameter(0).vector_size != 0);
602
alan-baker3f1bf492020-11-05 09:07:36 -0500603 case Builtins::kSubSat:
604 return replaceAddSubSat(F, FI.getParameter(0).is_signed, false);
605
SJW2c317da2020-03-23 07:39:13 -0500606 case Builtins::kReadImageh:
607 return replaceHalfReadImage(F);
608 case Builtins::kReadImagef:
609 case Builtins::kReadImagei:
610 case Builtins::kReadImageui: {
611 if (FI.getParameter(1).isSampler() &&
612 FI.getParameter(2).type_id == llvm::Type::IntegerTyID) {
613 return replaceSampledReadImageWithIntCoords(F);
614 }
615 break;
616 }
617
618 case Builtins::kWriteImageh:
619 return replaceHalfWriteImage(F);
620
Kévin Petit1cb45112020-04-27 18:55:48 +0100621 case Builtins::kPrefetch:
622 return replacePrefetch(F);
623
SJW2c317da2020-03-23 07:39:13 -0500624 default:
625 break;
626 }
627
628 return false;
629}
630
alan-baker6b9d1ee2020-11-03 23:11:32 -0500631Type *ReplaceOpenCLBuiltinPass::GetPairStruct(Type *type) {
632 auto iter = PairStructMap.find(type);
633 if (iter != PairStructMap.end())
634 return iter->second;
635
636 auto new_struct = StructType::get(type->getContext(), {type, type});
637 PairStructMap[type] = new_struct;
638 return new_struct;
639}
640
SJW2c317da2020-03-23 07:39:13 -0500641bool ReplaceOpenCLBuiltinPass::replaceAbs(Function &F) {
642 return replaceCallsWithValue(F,
Diego Novillo3cc8d7a2019-04-10 13:30:34 -0400643 [](CallInst *CI) { return CI->getOperand(0); });
Kévin Petite8edce32019-04-10 14:23:32 +0100644}
645
SJW2c317da2020-03-23 07:39:13 -0500646bool ReplaceOpenCLBuiltinPass::replaceAbsDiff(Function &F, bool is_signed) {
647 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100648 auto XValue = CI->getOperand(0);
649 auto YValue = CI->getOperand(1);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100650
Kévin Petite8edce32019-04-10 14:23:32 +0100651 IRBuilder<> Builder(CI);
652 auto XmY = Builder.CreateSub(XValue, YValue);
653 auto YmX = Builder.CreateSub(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100654
SJW2c317da2020-03-23 07:39:13 -0500655 Value *Cmp = nullptr;
656 if (is_signed) {
Kévin Petite8edce32019-04-10 14:23:32 +0100657 Cmp = Builder.CreateICmpSGT(YValue, XValue);
658 } else {
659 Cmp = Builder.CreateICmpUGT(YValue, XValue);
Kévin Petit91bc72e2019-04-08 15:17:46 +0100660 }
Kévin Petit91bc72e2019-04-08 15:17:46 +0100661
Kévin Petite8edce32019-04-10 14:23:32 +0100662 return Builder.CreateSelect(Cmp, YmX, XmY);
663 });
Kévin Petit91bc72e2019-04-08 15:17:46 +0100664}
665
SJW2c317da2020-03-23 07:39:13 -0500666bool ReplaceOpenCLBuiltinPass::replaceCopysign(Function &F) {
alan-baker5f2e88e2020-12-07 15:24:04 -0500667 return replaceCallsWithValue(F, [&F](CallInst *Call) {
668 const auto x = Call->getArgOperand(0);
669 const auto y = Call->getArgOperand(1);
670 auto intrinsic = Intrinsic::getDeclaration(
671 F.getParent(), Intrinsic::copysign, Call->getType());
672 return CallInst::Create(intrinsic->getFunctionType(), intrinsic, {x, y}, "",
673 Call);
Kévin Petite8edce32019-04-10 14:23:32 +0100674 });
Kévin Petit8c1be282019-04-02 19:34:25 +0100675}
676
SJW2c317da2020-03-23 07:39:13 -0500677bool ReplaceOpenCLBuiltinPass::replaceRecip(Function &F) {
678 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100679 // Recip has one arg.
680 auto Arg = CI->getOperand(0);
681 auto Cst1 = ConstantFP::get(Arg->getType(), 1.0);
682 return BinaryOperator::Create(Instruction::FDiv, Cst1, Arg, "", CI);
683 });
David Neto22f144c2017-06-12 14:26:21 -0400684}
685
SJW2c317da2020-03-23 07:39:13 -0500686bool ReplaceOpenCLBuiltinPass::replaceDivide(Function &F) {
687 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +0100688 auto Op0 = CI->getOperand(0);
689 auto Op1 = CI->getOperand(1);
690 return BinaryOperator::Create(Instruction::FDiv, Op0, Op1, "", CI);
691 });
David Neto22f144c2017-06-12 14:26:21 -0400692}
693
SJW2c317da2020-03-23 07:39:13 -0500694bool ReplaceOpenCLBuiltinPass::replaceDot(Function &F) {
695 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit1329a002019-06-15 05:54:05 +0100696 auto Op0 = CI->getOperand(0);
697 auto Op1 = CI->getOperand(1);
698
SJW2c317da2020-03-23 07:39:13 -0500699 Value *V = nullptr;
Kévin Petit1329a002019-06-15 05:54:05 +0100700 if (Op0->getType()->isVectorTy()) {
701 V = clspv::InsertSPIRVOp(CI, spv::OpDot, {Attribute::ReadNone},
702 CI->getType(), {Op0, Op1});
703 } else {
704 V = BinaryOperator::Create(Instruction::FMul, Op0, Op1, "", CI);
705 }
706
707 return V;
708 });
709}
710
SJW2c317da2020-03-23 07:39:13 -0500711bool ReplaceOpenCLBuiltinPass::replaceExp10(Function &F,
SJW61531372020-06-09 07:31:08 -0500712 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500713 // convert to natural
714 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500715 std::string NewFName = basename.substr(0, slen);
716 NewFName =
717 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400718
SJW2c317da2020-03-23 07:39:13 -0500719 Module &M = *F.getParent();
720 return replaceCallsWithValue(F, [&](CallInst *CI) {
721 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
722
723 auto Arg = CI->getOperand(0);
724
725 // Constant of the natural log of 10 (ln(10)).
726 const double Ln10 =
727 2.302585092994045684017991454684364207601101488628772976033;
728
729 auto Mul = BinaryOperator::Create(
730 Instruction::FMul, ConstantFP::get(Arg->getType(), Ln10), Arg, "", CI);
731
732 return CallInst::Create(NewF, Mul, "", CI);
733 });
David Neto22f144c2017-06-12 14:26:21 -0400734}
735
SJW2c317da2020-03-23 07:39:13 -0500736bool ReplaceOpenCLBuiltinPass::replaceFmod(Function &F) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100737 // OpenCL fmod(x,y) is x - y * trunc(x/y)
738 // The sign for a non-zero result is taken from x.
739 // (Try an example.)
740 // So translate to FRem
SJW2c317da2020-03-23 07:39:13 -0500741 return replaceCallsWithValue(F, [](CallInst *CI) {
Kévin Petit0644a9c2019-06-20 21:08:46 +0100742 auto Op0 = CI->getOperand(0);
743 auto Op1 = CI->getOperand(1);
744 return BinaryOperator::Create(Instruction::FRem, Op0, Op1, "", CI);
745 });
746}
747
SJW2c317da2020-03-23 07:39:13 -0500748bool ReplaceOpenCLBuiltinPass::replaceLog10(Function &F,
SJW61531372020-06-09 07:31:08 -0500749 const std::string &basename) {
SJW2c317da2020-03-23 07:39:13 -0500750 // convert to natural
751 auto slen = basename.length() - 2;
SJW61531372020-06-09 07:31:08 -0500752 std::string NewFName = basename.substr(0, slen);
753 NewFName =
754 Builtins::GetMangledFunctionName(NewFName.c_str(), F.getFunctionType());
David Neto22f144c2017-06-12 14:26:21 -0400755
SJW2c317da2020-03-23 07:39:13 -0500756 Module &M = *F.getParent();
757 return replaceCallsWithValue(F, [&](CallInst *CI) {
758 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
759
760 auto Arg = CI->getOperand(0);
761
762 // Constant of the reciprocal of the natural log of 10 (ln(10)).
763 const double Ln10 =
764 0.434294481903251827651128918916605082294397005803666566114;
765
766 auto NewCI = CallInst::Create(NewF, Arg, "", CI);
767
768 return BinaryOperator::Create(Instruction::FMul,
769 ConstantFP::get(Arg->getType(), Ln10), NewCI,
770 "", CI);
771 });
David Neto22f144c2017-06-12 14:26:21 -0400772}
773
gnl21636e7992020-09-09 16:08:16 +0100774bool ReplaceOpenCLBuiltinPass::replaceLog1p(Function &F) {
775 // convert to natural
776 std::string NewFName =
777 Builtins::GetMangledFunctionName("log", F.getFunctionType());
778
779 Module &M = *F.getParent();
780 return replaceCallsWithValue(F, [&](CallInst *CI) {
781 auto NewF = M.getOrInsertFunction(NewFName, F.getFunctionType());
782
783 auto Arg = CI->getOperand(0);
784
785 auto ArgP1 = BinaryOperator::Create(
786 Instruction::FAdd, ConstantFP::get(Arg->getType(), 1.0), Arg, "", CI);
787
788 return CallInst::Create(NewF, ArgP1, "", CI);
789 });
790}
791
alan-baker12d2c182020-07-20 08:22:42 -0400792bool ReplaceOpenCLBuiltinPass::replaceBarrier(Function &F, bool subgroup) {
David Neto22f144c2017-06-12 14:26:21 -0400793
alan-bakerf6bc8252020-09-23 14:58:55 -0400794 enum {
795 CLK_LOCAL_MEM_FENCE = 0x01,
796 CLK_GLOBAL_MEM_FENCE = 0x02,
797 CLK_IMAGE_MEM_FENCE = 0x04
798 };
David Neto22f144c2017-06-12 14:26:21 -0400799
alan-baker12d2c182020-07-20 08:22:42 -0400800 return replaceCallsWithValue(F, [subgroup](CallInst *CI) {
Kévin Petitc4643922019-06-17 19:32:05 +0100801 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400802
Kévin Petitc4643922019-06-17 19:32:05 +0100803 // We need to map the OpenCL constants to the SPIR-V equivalents.
804 const auto LocalMemFence =
805 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
806 const auto GlobalMemFence =
807 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400808 const auto ImageMemFence =
809 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
alan-baker12d2c182020-07-20 08:22:42 -0400810 const auto ConstantAcquireRelease = ConstantInt::get(
811 Arg->getType(), spv::MemorySemanticsAcquireReleaseMask);
Kévin Petitc4643922019-06-17 19:32:05 +0100812 const auto ConstantScopeDevice =
813 ConstantInt::get(Arg->getType(), spv::ScopeDevice);
814 const auto ConstantScopeWorkgroup =
815 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
alan-baker12d2c182020-07-20 08:22:42 -0400816 const auto ConstantScopeSubgroup =
817 ConstantInt::get(Arg->getType(), spv::ScopeSubgroup);
David Neto22f144c2017-06-12 14:26:21 -0400818
Kévin Petitc4643922019-06-17 19:32:05 +0100819 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
820 const auto LocalMemFenceMask =
821 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
822 const auto WorkgroupShiftAmount =
823 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
824 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
825 Instruction::Shl, LocalMemFenceMask,
826 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400827
Kévin Petitc4643922019-06-17 19:32:05 +0100828 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
829 const auto GlobalMemFenceMask =
830 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
831 const auto UniformShiftAmount =
832 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
833 const auto MemorySemanticsUniform = BinaryOperator::Create(
834 Instruction::Shl, GlobalMemFenceMask,
835 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400836
alan-bakerf6bc8252020-09-23 14:58:55 -0400837 // OpenCL 2.0
838 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
839 const auto ImageMemFenceMask =
840 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
841 const auto ImageShiftAmount =
842 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
843 const auto MemorySemanticsImage = BinaryOperator::Create(
844 Instruction::Shl, ImageMemFenceMask,
845 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
846
Kévin Petitc4643922019-06-17 19:32:05 +0100847 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400848 // MemorySemanticsSequentiallyConsistentMask.
849 auto MemorySemantics1 =
Kévin Petitc4643922019-06-17 19:32:05 +0100850 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
alan-baker12d2c182020-07-20 08:22:42 -0400851 ConstantAcquireRelease, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400852 auto MemorySemantics2 = BinaryOperator::Create(
853 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
854 auto MemorySemantics = BinaryOperator::Create(
855 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400856
alan-baker12d2c182020-07-20 08:22:42 -0400857 // If the memory scope is not specified explicitly, it is either Subgroup
858 // or Workgroup depending on the type of barrier.
859 Value *MemoryScope =
860 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
861 if (CI->data_operands_size() > 1) {
862 enum {
863 CL_MEMORY_SCOPE_WORKGROUP = 0x1,
864 CL_MEMORY_SCOPE_DEVICE = 0x2,
865 CL_MEMORY_SCOPE_SUBGROUP = 0x4
866 };
867 // The call was given an explicit memory scope.
868 const auto MemoryScopeSubgroup =
869 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_SUBGROUP);
870 const auto MemoryScopeDevice =
871 ConstantInt::get(Arg->getType(), CL_MEMORY_SCOPE_DEVICE);
David Neto22f144c2017-06-12 14:26:21 -0400872
alan-baker12d2c182020-07-20 08:22:42 -0400873 auto Cmp =
874 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
875 MemoryScopeSubgroup, CI->getOperand(1), "", CI);
876 MemoryScope = SelectInst::Create(Cmp, ConstantScopeSubgroup,
877 ConstantScopeWorkgroup, "", CI);
878 Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
879 MemoryScopeDevice, CI->getOperand(1), "", CI);
880 MemoryScope =
881 SelectInst::Create(Cmp, ConstantScopeDevice, MemoryScope, "", CI);
882 }
883
884 // Lastly, the Execution Scope is either Workgroup or Subgroup depending on
885 // the type of barrier;
886 const auto ExecutionScope =
887 subgroup ? ConstantScopeSubgroup : ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400888
Kévin Petitc4643922019-06-17 19:32:05 +0100889 return clspv::InsertSPIRVOp(CI, spv::OpControlBarrier,
alan-baker3d905692020-10-28 14:02:37 -0400890 {Attribute::NoDuplicate, Attribute::Convergent},
891 CI->getType(),
Kévin Petitc4643922019-06-17 19:32:05 +0100892 {ExecutionScope, MemoryScope, MemorySemantics});
893 });
David Neto22f144c2017-06-12 14:26:21 -0400894}
895
SJW2c317da2020-03-23 07:39:13 -0500896bool ReplaceOpenCLBuiltinPass::replaceMemFence(Function &F,
897 uint32_t semantics) {
David Neto22f144c2017-06-12 14:26:21 -0400898
SJW2c317da2020-03-23 07:39:13 -0500899 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerf6bc8252020-09-23 14:58:55 -0400900 enum {
901 CLK_LOCAL_MEM_FENCE = 0x01,
902 CLK_GLOBAL_MEM_FENCE = 0x02,
903 CLK_IMAGE_MEM_FENCE = 0x04,
904 };
David Neto22f144c2017-06-12 14:26:21 -0400905
SJW2c317da2020-03-23 07:39:13 -0500906 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -0400907
SJW2c317da2020-03-23 07:39:13 -0500908 // We need to map the OpenCL constants to the SPIR-V equivalents.
909 const auto LocalMemFence =
910 ConstantInt::get(Arg->getType(), CLK_LOCAL_MEM_FENCE);
911 const auto GlobalMemFence =
912 ConstantInt::get(Arg->getType(), CLK_GLOBAL_MEM_FENCE);
alan-bakerf6bc8252020-09-23 14:58:55 -0400913 const auto ImageMemFence =
914 ConstantInt::get(Arg->getType(), CLK_IMAGE_MEM_FENCE);
SJW2c317da2020-03-23 07:39:13 -0500915 const auto ConstantMemorySemantics =
916 ConstantInt::get(Arg->getType(), semantics);
alan-baker12d2c182020-07-20 08:22:42 -0400917 const auto ConstantScopeWorkgroup =
918 ConstantInt::get(Arg->getType(), spv::ScopeWorkgroup);
David Neto22f144c2017-06-12 14:26:21 -0400919
SJW2c317da2020-03-23 07:39:13 -0500920 // Map CLK_LOCAL_MEM_FENCE to MemorySemanticsWorkgroupMemoryMask.
921 const auto LocalMemFenceMask =
922 BinaryOperator::Create(Instruction::And, LocalMemFence, Arg, "", CI);
923 const auto WorkgroupShiftAmount =
924 clz(spv::MemorySemanticsWorkgroupMemoryMask) - clz(CLK_LOCAL_MEM_FENCE);
925 const auto MemorySemanticsWorkgroup = BinaryOperator::Create(
926 Instruction::Shl, LocalMemFenceMask,
927 ConstantInt::get(Arg->getType(), WorkgroupShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400928
SJW2c317da2020-03-23 07:39:13 -0500929 // Map CLK_GLOBAL_MEM_FENCE to MemorySemanticsUniformMemoryMask.
930 const auto GlobalMemFenceMask =
931 BinaryOperator::Create(Instruction::And, GlobalMemFence, Arg, "", CI);
932 const auto UniformShiftAmount =
933 clz(spv::MemorySemanticsUniformMemoryMask) - clz(CLK_GLOBAL_MEM_FENCE);
934 const auto MemorySemanticsUniform = BinaryOperator::Create(
935 Instruction::Shl, GlobalMemFenceMask,
936 ConstantInt::get(Arg->getType(), UniformShiftAmount), "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400937
alan-bakerf6bc8252020-09-23 14:58:55 -0400938 // OpenCL 2.0
939 // Map CLK_IMAGE_MEM_FENCE to MemorySemanticsImageMemoryMask.
940 const auto ImageMemFenceMask =
941 BinaryOperator::Create(Instruction::And, ImageMemFence, Arg, "", CI);
942 const auto ImageShiftAmount =
943 clz(spv::MemorySemanticsImageMemoryMask) - clz(CLK_IMAGE_MEM_FENCE);
944 const auto MemorySemanticsImage = BinaryOperator::Create(
945 Instruction::Shl, ImageMemFenceMask,
946 ConstantInt::get(Arg->getType(), ImageShiftAmount), "", CI);
947
SJW2c317da2020-03-23 07:39:13 -0500948 // And combine the above together, also adding in
alan-bakerf6bc8252020-09-23 14:58:55 -0400949 // |semantics|.
950 auto MemorySemantics1 =
SJW2c317da2020-03-23 07:39:13 -0500951 BinaryOperator::Create(Instruction::Or, MemorySemanticsWorkgroup,
952 ConstantMemorySemantics, "", CI);
alan-bakerf6bc8252020-09-23 14:58:55 -0400953 auto MemorySemantics2 = BinaryOperator::Create(
954 Instruction::Or, MemorySemanticsUniform, MemorySemanticsImage, "", CI);
955 auto MemorySemantics = BinaryOperator::Create(
956 Instruction::Or, MemorySemantics1, MemorySemantics2, "", CI);
David Neto22f144c2017-06-12 14:26:21 -0400957
alan-baker12d2c182020-07-20 08:22:42 -0400958 // Memory Scope is always workgroup.
959 const auto MemoryScope = ConstantScopeWorkgroup;
David Neto22f144c2017-06-12 14:26:21 -0400960
alan-baker3d905692020-10-28 14:02:37 -0400961 return clspv::InsertSPIRVOp(CI, spv::OpMemoryBarrier,
962 {Attribute::Convergent}, CI->getType(),
SJW2c317da2020-03-23 07:39:13 -0500963 {MemoryScope, MemorySemantics});
964 });
David Neto22f144c2017-06-12 14:26:21 -0400965}
966
Kévin Petit1cb45112020-04-27 18:55:48 +0100967bool ReplaceOpenCLBuiltinPass::replacePrefetch(Function &F) {
968 bool Changed = false;
969
970 SmallVector<Instruction *, 4> ToRemoves;
971
972 // Find all calls to the function
973 for (auto &U : F.uses()) {
974 if (auto CI = dyn_cast<CallInst>(U.getUser())) {
975 ToRemoves.push_back(CI);
976 }
977 }
978
979 Changed = !ToRemoves.empty();
980
981 // Delete them
982 for (auto V : ToRemoves) {
983 V->eraseFromParent();
984 }
985
986 return Changed;
987}
988
SJW2c317da2020-03-23 07:39:13 -0500989bool ReplaceOpenCLBuiltinPass::replaceRelational(Function &F,
alan-baker3e217772020-11-07 17:29:40 -0500990 CmpInst::Predicate P) {
SJW2c317da2020-03-23 07:39:13 -0500991 return replaceCallsWithValue(F, [&](CallInst *CI) {
992 // The predicate to use in the CmpInst.
993 auto Predicate = P;
David Neto22f144c2017-06-12 14:26:21 -0400994
SJW2c317da2020-03-23 07:39:13 -0500995 auto Arg1 = CI->getOperand(0);
996 auto Arg2 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -0400997
SJW2c317da2020-03-23 07:39:13 -0500998 const auto Cmp =
999 CmpInst::Create(Instruction::FCmp, Predicate, Arg1, Arg2, "", CI);
alan-baker3e217772020-11-07 17:29:40 -05001000 if (isa<VectorType>(F.getReturnType()))
1001 return CastInst::Create(Instruction::SExt, Cmp, CI->getType(), "", CI);
1002 return CastInst::Create(Instruction::ZExt, Cmp, CI->getType(), "", CI);
SJW2c317da2020-03-23 07:39:13 -05001003 });
David Neto22f144c2017-06-12 14:26:21 -04001004}
1005
SJW2c317da2020-03-23 07:39:13 -05001006bool ReplaceOpenCLBuiltinPass::replaceIsInfAndIsNan(Function &F,
1007 spv::Op SPIRVOp,
1008 int32_t C) {
1009 Module &M = *F.getParent();
1010 return replaceCallsWithValue(F, [&](CallInst *CI) {
1011 const auto CITy = CI->getType();
David Neto22f144c2017-06-12 14:26:21 -04001012
SJW2c317da2020-03-23 07:39:13 -05001013 // The value to return for true.
1014 auto TrueValue = ConstantInt::getSigned(CITy, C);
David Neto22f144c2017-06-12 14:26:21 -04001015
SJW2c317da2020-03-23 07:39:13 -05001016 // The value to return for false.
1017 auto FalseValue = Constant::getNullValue(CITy);
David Neto22f144c2017-06-12 14:26:21 -04001018
SJW2c317da2020-03-23 07:39:13 -05001019 Type *CorrespondingBoolTy = Type::getInt1Ty(M.getContext());
James Pricecf53df42020-04-20 14:41:24 -04001020 if (auto CIVecTy = dyn_cast<VectorType>(CITy)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001021 CorrespondingBoolTy =
1022 FixedVectorType::get(Type::getInt1Ty(M.getContext()),
1023 CIVecTy->getElementCount().getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04001024 }
David Neto22f144c2017-06-12 14:26:21 -04001025
SJW2c317da2020-03-23 07:39:13 -05001026 auto NewCI = clspv::InsertSPIRVOp(CI, SPIRVOp, {Attribute::ReadNone},
1027 CorrespondingBoolTy, {CI->getOperand(0)});
1028
1029 return SelectInst::Create(NewCI, TrueValue, FalseValue, "", CI);
1030 });
David Neto22f144c2017-06-12 14:26:21 -04001031}
1032
SJW2c317da2020-03-23 07:39:13 -05001033bool ReplaceOpenCLBuiltinPass::replaceIsFinite(Function &F) {
1034 Module &M = *F.getParent();
1035 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001036 auto &C = M.getContext();
1037 auto Val = CI->getOperand(0);
1038 auto ValTy = Val->getType();
1039 auto RetTy = CI->getType();
1040
1041 // Get a suitable integer type to represent the number
1042 auto IntTy = getIntOrIntVectorTyForCast(C, ValTy);
1043
1044 // Create Mask
1045 auto ScalarSize = ValTy->getScalarSizeInBits();
SJW2c317da2020-03-23 07:39:13 -05001046 Value *InfMask = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001047 switch (ScalarSize) {
1048 case 16:
1049 InfMask = ConstantInt::get(IntTy, 0x7C00U);
1050 break;
1051 case 32:
1052 InfMask = ConstantInt::get(IntTy, 0x7F800000U);
1053 break;
1054 case 64:
1055 InfMask = ConstantInt::get(IntTy, 0x7FF0000000000000ULL);
1056 break;
1057 default:
1058 llvm_unreachable("Unsupported floating-point type");
1059 }
1060
1061 IRBuilder<> Builder(CI);
1062
1063 // Bitcast to int
1064 auto ValInt = Builder.CreateBitCast(Val, IntTy);
1065
1066 // Mask and compare
1067 auto InfBits = Builder.CreateAnd(InfMask, ValInt);
1068 auto Cmp = Builder.CreateICmp(CmpInst::ICMP_EQ, InfBits, InfMask);
1069
1070 auto RetFalse = ConstantInt::get(RetTy, 0);
SJW2c317da2020-03-23 07:39:13 -05001071 Value *RetTrue = nullptr;
Kévin Petitfdfa92e2019-09-25 14:20:58 +01001072 if (ValTy->isVectorTy()) {
1073 RetTrue = ConstantInt::getSigned(RetTy, -1);
1074 } else {
1075 RetTrue = ConstantInt::get(RetTy, 1);
1076 }
1077 return Builder.CreateSelect(Cmp, RetFalse, RetTrue);
1078 });
1079}
1080
SJW2c317da2020-03-23 07:39:13 -05001081bool ReplaceOpenCLBuiltinPass::replaceAllAndAny(Function &F, spv::Op SPIRVOp) {
1082 Module &M = *F.getParent();
1083 return replaceCallsWithValue(F, [&](CallInst *CI) {
1084 auto Arg = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001085
SJW2c317da2020-03-23 07:39:13 -05001086 Value *V = nullptr;
Kévin Petitfd27cca2018-10-31 13:00:17 +00001087
SJW2c317da2020-03-23 07:39:13 -05001088 // If the argument is a 32-bit int, just use a shift
1089 if (Arg->getType() == Type::getInt32Ty(M.getContext())) {
1090 V = BinaryOperator::Create(Instruction::LShr, Arg,
1091 ConstantInt::get(Arg->getType(), 31), "", CI);
1092 } else {
1093 // The value for zero to compare against.
1094 const auto ZeroValue = Constant::getNullValue(Arg->getType());
David Neto22f144c2017-06-12 14:26:21 -04001095
SJW2c317da2020-03-23 07:39:13 -05001096 // The value to return for true.
1097 const auto TrueValue = ConstantInt::get(CI->getType(), 1);
David Neto22f144c2017-06-12 14:26:21 -04001098
SJW2c317da2020-03-23 07:39:13 -05001099 // The value to return for false.
1100 const auto FalseValue = Constant::getNullValue(CI->getType());
David Neto22f144c2017-06-12 14:26:21 -04001101
SJW2c317da2020-03-23 07:39:13 -05001102 const auto Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_SLT,
1103 Arg, ZeroValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001104
SJW2c317da2020-03-23 07:39:13 -05001105 Value *SelectSource = nullptr;
David Neto22f144c2017-06-12 14:26:21 -04001106
SJW2c317da2020-03-23 07:39:13 -05001107 // If we have a function to call, call it!
1108 if (SPIRVOp != spv::OpNop) {
David Neto22f144c2017-06-12 14:26:21 -04001109
SJW2c317da2020-03-23 07:39:13 -05001110 const auto BoolTy = Type::getInt1Ty(M.getContext());
David Neto22f144c2017-06-12 14:26:21 -04001111
SJW2c317da2020-03-23 07:39:13 -05001112 const auto NewCI = clspv::InsertSPIRVOp(
1113 CI, SPIRVOp, {Attribute::ReadNone}, BoolTy, {Cmp});
1114 SelectSource = NewCI;
David Neto22f144c2017-06-12 14:26:21 -04001115
SJW2c317da2020-03-23 07:39:13 -05001116 } else {
1117 SelectSource = Cmp;
David Neto22f144c2017-06-12 14:26:21 -04001118 }
1119
SJW2c317da2020-03-23 07:39:13 -05001120 V = SelectInst::Create(SelectSource, TrueValue, FalseValue, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001121 }
SJW2c317da2020-03-23 07:39:13 -05001122 return V;
1123 });
David Neto22f144c2017-06-12 14:26:21 -04001124}
1125
SJW2c317da2020-03-23 07:39:13 -05001126bool ReplaceOpenCLBuiltinPass::replaceUpsample(Function &F) {
1127 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1128 // Get arguments
1129 auto HiValue = CI->getOperand(0);
1130 auto LoValue = CI->getOperand(1);
Kévin Petitbf0036c2019-03-06 13:57:10 +00001131
SJW2c317da2020-03-23 07:39:13 -05001132 // Don't touch overloads that aren't in OpenCL C
1133 auto HiType = HiValue->getType();
1134 auto LoType = LoValue->getType();
1135
1136 if (HiType != LoType) {
1137 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001138 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001139
SJW2c317da2020-03-23 07:39:13 -05001140 if (!HiType->isIntOrIntVectorTy()) {
1141 return nullptr;
Kévin Petitbf0036c2019-03-06 13:57:10 +00001142 }
Kévin Petitbf0036c2019-03-06 13:57:10 +00001143
SJW2c317da2020-03-23 07:39:13 -05001144 if (HiType->getScalarSizeInBits() * 2 !=
1145 CI->getType()->getScalarSizeInBits()) {
1146 return nullptr;
1147 }
1148
1149 if ((HiType->getScalarSizeInBits() != 8) &&
1150 (HiType->getScalarSizeInBits() != 16) &&
1151 (HiType->getScalarSizeInBits() != 32)) {
1152 return nullptr;
1153 }
1154
James Pricecf53df42020-04-20 14:41:24 -04001155 if (auto HiVecType = dyn_cast<VectorType>(HiType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001156 unsigned NumElements = HiVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001157 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1158 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001159 return nullptr;
1160 }
1161 }
1162
1163 // Convert both operands to the result type
1164 auto HiCast = CastInst::CreateZExtOrBitCast(HiValue, CI->getType(), "", CI);
1165 auto LoCast = CastInst::CreateZExtOrBitCast(LoValue, CI->getType(), "", CI);
1166
1167 // Shift high operand
1168 auto ShiftAmount =
1169 ConstantInt::get(CI->getType(), HiType->getScalarSizeInBits());
1170 auto HiShifted =
1171 BinaryOperator::Create(Instruction::Shl, HiCast, ShiftAmount, "", CI);
1172
1173 // OR both results
1174 return BinaryOperator::Create(Instruction::Or, HiShifted, LoCast, "", CI);
1175 });
Kévin Petitbf0036c2019-03-06 13:57:10 +00001176}
1177
SJW2c317da2020-03-23 07:39:13 -05001178bool ReplaceOpenCLBuiltinPass::replaceRotate(Function &F) {
1179 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1180 // Get arguments
1181 auto SrcValue = CI->getOperand(0);
1182 auto RotAmount = CI->getOperand(1);
Kévin Petitd44eef52019-03-08 13:22:14 +00001183
SJW2c317da2020-03-23 07:39:13 -05001184 // Don't touch overloads that aren't in OpenCL C
1185 auto SrcType = SrcValue->getType();
1186 auto RotType = RotAmount->getType();
1187
1188 if ((SrcType != RotType) || (CI->getType() != SrcType)) {
1189 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001190 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001191
SJW2c317da2020-03-23 07:39:13 -05001192 if (!SrcType->isIntOrIntVectorTy()) {
1193 return nullptr;
Kévin Petitd44eef52019-03-08 13:22:14 +00001194 }
Kévin Petitd44eef52019-03-08 13:22:14 +00001195
SJW2c317da2020-03-23 07:39:13 -05001196 if ((SrcType->getScalarSizeInBits() != 8) &&
1197 (SrcType->getScalarSizeInBits() != 16) &&
1198 (SrcType->getScalarSizeInBits() != 32) &&
1199 (SrcType->getScalarSizeInBits() != 64)) {
1200 return nullptr;
1201 }
1202
James Pricecf53df42020-04-20 14:41:24 -04001203 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001204 unsigned NumElements = SrcVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001205 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1206 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001207 return nullptr;
1208 }
1209 }
1210
alan-bakerfd22ae12020-10-29 15:59:22 -04001211 // Replace with LLVM's funnel shift left intrinsic because it is more
1212 // generic than rotate.
1213 Function *intrinsic =
1214 Intrinsic::getDeclaration(F.getParent(), Intrinsic::fshl, SrcType);
1215 return CallInst::Create(intrinsic->getFunctionType(), intrinsic,
1216 {SrcValue, SrcValue, RotAmount}, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001217 });
Kévin Petitd44eef52019-03-08 13:22:14 +00001218}
1219
SJW2c317da2020-03-23 07:39:13 -05001220bool ReplaceOpenCLBuiltinPass::replaceConvert(Function &F, bool SrcIsSigned,
1221 bool DstIsSigned) {
1222 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1223 Value *V = nullptr;
1224 // Get arguments
1225 auto SrcValue = CI->getOperand(0);
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001226
SJW2c317da2020-03-23 07:39:13 -05001227 // Don't touch overloads that aren't in OpenCL C
1228 auto SrcType = SrcValue->getType();
1229 auto DstType = CI->getType();
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001230
SJW2c317da2020-03-23 07:39:13 -05001231 if ((SrcType->isVectorTy() && !DstType->isVectorTy()) ||
1232 (!SrcType->isVectorTy() && DstType->isVectorTy())) {
1233 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001234 }
1235
James Pricecf53df42020-04-20 14:41:24 -04001236 if (auto SrcVecType = dyn_cast<VectorType>(SrcType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001237 unsigned SrcNumElements =
1238 SrcVecType->getElementCount().getKnownMinValue();
1239 unsigned DstNumElements =
1240 cast<VectorType>(DstType)->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001241 if (SrcNumElements != DstNumElements) {
SJW2c317da2020-03-23 07:39:13 -05001242 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001243 }
1244
James Pricecf53df42020-04-20 14:41:24 -04001245 if ((SrcNumElements != 2) && (SrcNumElements != 3) &&
1246 (SrcNumElements != 4) && (SrcNumElements != 8) &&
1247 (SrcNumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001248 return V;
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001249 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001250 }
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001251
SJW2c317da2020-03-23 07:39:13 -05001252 bool SrcIsFloat = SrcType->getScalarType()->isFloatingPointTy();
1253 bool DstIsFloat = DstType->getScalarType()->isFloatingPointTy();
1254
1255 bool SrcIsInt = SrcType->isIntOrIntVectorTy();
1256 bool DstIsInt = DstType->isIntOrIntVectorTy();
1257
1258 if (SrcType == DstType && DstIsSigned == SrcIsSigned) {
1259 // Unnecessary cast operation.
1260 V = SrcValue;
1261 } else if (SrcIsFloat && DstIsFloat) {
1262 V = CastInst::CreateFPCast(SrcValue, DstType, "", CI);
1263 } else if (SrcIsFloat && DstIsInt) {
1264 if (DstIsSigned) {
1265 V = CastInst::Create(Instruction::FPToSI, SrcValue, DstType, "", CI);
1266 } else {
1267 V = CastInst::Create(Instruction::FPToUI, SrcValue, DstType, "", CI);
1268 }
1269 } else if (SrcIsInt && DstIsFloat) {
1270 if (SrcIsSigned) {
1271 V = CastInst::Create(Instruction::SIToFP, SrcValue, DstType, "", CI);
1272 } else {
1273 V = CastInst::Create(Instruction::UIToFP, SrcValue, DstType, "", CI);
1274 }
1275 } else if (SrcIsInt && DstIsInt) {
1276 V = CastInst::CreateIntegerCast(SrcValue, DstType, SrcIsSigned, "", CI);
1277 } else {
1278 // Not something we're supposed to handle, just move on
1279 }
1280
1281 return V;
1282 });
Kévin Petit9d1a9d12019-03-25 15:23:46 +00001283}
1284
SJW2c317da2020-03-23 07:39:13 -05001285bool ReplaceOpenCLBuiltinPass::replaceMulHi(Function &F, bool is_signed,
1286 bool is_mad) {
1287 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1288 Value *V = nullptr;
1289 // Get arguments
1290 auto AValue = CI->getOperand(0);
1291 auto BValue = CI->getOperand(1);
1292 auto CValue = CI->getOperand(2);
Kévin Petit8a560882019-03-21 15:24:34 +00001293
SJW2c317da2020-03-23 07:39:13 -05001294 // Don't touch overloads that aren't in OpenCL C
1295 auto AType = AValue->getType();
1296 auto BType = BValue->getType();
1297 auto CType = CValue->getType();
Kévin Petit8a560882019-03-21 15:24:34 +00001298
SJW2c317da2020-03-23 07:39:13 -05001299 if ((AType != BType) || (CI->getType() != AType) ||
1300 (is_mad && (AType != CType))) {
1301 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001302 }
1303
SJW2c317da2020-03-23 07:39:13 -05001304 if (!AType->isIntOrIntVectorTy()) {
1305 return V;
Kévin Petit8a560882019-03-21 15:24:34 +00001306 }
Kévin Petit8a560882019-03-21 15:24:34 +00001307
SJW2c317da2020-03-23 07:39:13 -05001308 if ((AType->getScalarSizeInBits() != 8) &&
1309 (AType->getScalarSizeInBits() != 16) &&
1310 (AType->getScalarSizeInBits() != 32) &&
1311 (AType->getScalarSizeInBits() != 64)) {
1312 return V;
1313 }
Kévin Petit617a76d2019-04-04 13:54:16 +01001314
James Pricecf53df42020-04-20 14:41:24 -04001315 if (auto AVecType = dyn_cast<VectorType>(AType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001316 unsigned NumElements = AVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001317 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1318 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001319 return V;
Kévin Petit617a76d2019-04-04 13:54:16 +01001320 }
1321 }
1322
SJW2c317da2020-03-23 07:39:13 -05001323 // Our SPIR-V op returns a struct, create a type for it
alan-baker6b9d1ee2020-11-03 23:11:32 -05001324 auto ExMulRetType = GetPairStruct(AType);
Kévin Petit617a76d2019-04-04 13:54:16 +01001325
SJW2c317da2020-03-23 07:39:13 -05001326 // Select the appropriate signed/unsigned SPIR-V op
1327 spv::Op opcode = is_signed ? spv::OpSMulExtended : spv::OpUMulExtended;
1328
1329 // Call the SPIR-V op
1330 auto Call = clspv::InsertSPIRVOp(CI, opcode, {Attribute::ReadNone},
1331 ExMulRetType, {AValue, BValue});
1332
1333 // Get the high part of the result
1334 unsigned Idxs[] = {1};
1335 V = ExtractValueInst::Create(Call, Idxs, "", CI);
1336
1337 // If we're handling a mad_hi, add the third argument to the result
1338 if (is_mad) {
1339 V = BinaryOperator::Create(Instruction::Add, V, CValue, "", CI);
Kévin Petit617a76d2019-04-04 13:54:16 +01001340 }
1341
SJW2c317da2020-03-23 07:39:13 -05001342 return V;
1343 });
Kévin Petit8a560882019-03-21 15:24:34 +00001344}
1345
SJW2c317da2020-03-23 07:39:13 -05001346bool ReplaceOpenCLBuiltinPass::replaceSelect(Function &F) {
1347 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1348 // Get arguments
1349 auto FalseValue = CI->getOperand(0);
1350 auto TrueValue = CI->getOperand(1);
1351 auto PredicateValue = CI->getOperand(2);
Kévin Petitf5b78a22018-10-25 14:32:17 +00001352
SJW2c317da2020-03-23 07:39:13 -05001353 // Don't touch overloads that aren't in OpenCL C
1354 auto FalseType = FalseValue->getType();
1355 auto TrueType = TrueValue->getType();
1356 auto PredicateType = PredicateValue->getType();
1357
1358 if (FalseType != TrueType) {
1359 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001360 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001361
SJW2c317da2020-03-23 07:39:13 -05001362 if (!PredicateType->isIntOrIntVectorTy()) {
1363 return nullptr;
1364 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001365
SJW2c317da2020-03-23 07:39:13 -05001366 if (!FalseType->isIntOrIntVectorTy() &&
1367 !FalseType->getScalarType()->isFloatingPointTy()) {
1368 return nullptr;
1369 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001370
SJW2c317da2020-03-23 07:39:13 -05001371 if (FalseType->isVectorTy() && !PredicateType->isVectorTy()) {
1372 return nullptr;
1373 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001374
SJW2c317da2020-03-23 07:39:13 -05001375 if (FalseType->getScalarSizeInBits() !=
1376 PredicateType->getScalarSizeInBits()) {
1377 return nullptr;
1378 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001379
James Pricecf53df42020-04-20 14:41:24 -04001380 if (auto FalseVecType = dyn_cast<VectorType>(FalseType)) {
alan-baker5a8c3be2020-09-09 13:44:26 -04001381 unsigned NumElements = FalseVecType->getElementCount().getKnownMinValue();
1382 if (NumElements != cast<VectorType>(PredicateType)
1383 ->getElementCount()
1384 .getKnownMinValue()) {
SJW2c317da2020-03-23 07:39:13 -05001385 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001386 }
1387
James Pricecf53df42020-04-20 14:41:24 -04001388 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1389 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001390 return nullptr;
Kévin Petitf5b78a22018-10-25 14:32:17 +00001391 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001392 }
Kévin Petitf5b78a22018-10-25 14:32:17 +00001393
SJW2c317da2020-03-23 07:39:13 -05001394 // Create constant
1395 const auto ZeroValue = Constant::getNullValue(PredicateType);
1396
1397 // Scalar and vector are to be treated differently
1398 CmpInst::Predicate Pred;
1399 if (PredicateType->isVectorTy()) {
1400 Pred = CmpInst::ICMP_SLT;
1401 } else {
1402 Pred = CmpInst::ICMP_NE;
1403 }
1404
1405 // Create comparison instruction
1406 auto Cmp = CmpInst::Create(Instruction::ICmp, Pred, PredicateValue,
1407 ZeroValue, "", CI);
1408
1409 // Create select
1410 return SelectInst::Create(Cmp, TrueValue, FalseValue, "", CI);
1411 });
Kévin Petitf5b78a22018-10-25 14:32:17 +00001412}
1413
SJW2c317da2020-03-23 07:39:13 -05001414bool ReplaceOpenCLBuiltinPass::replaceBitSelect(Function &F) {
1415 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1416 Value *V = nullptr;
1417 if (CI->getNumOperands() != 4) {
1418 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001419 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001420
SJW2c317da2020-03-23 07:39:13 -05001421 // Get arguments
1422 auto FalseValue = CI->getOperand(0);
1423 auto TrueValue = CI->getOperand(1);
1424 auto PredicateValue = CI->getOperand(2);
Kévin Petite7d0cce2018-10-31 12:38:56 +00001425
SJW2c317da2020-03-23 07:39:13 -05001426 // Don't touch overloads that aren't in OpenCL C
1427 auto FalseType = FalseValue->getType();
1428 auto TrueType = TrueValue->getType();
1429 auto PredicateType = PredicateValue->getType();
Kévin Petite7d0cce2018-10-31 12:38:56 +00001430
SJW2c317da2020-03-23 07:39:13 -05001431 if ((FalseType != TrueType) || (PredicateType != TrueType)) {
1432 return V;
Kévin Petite7d0cce2018-10-31 12:38:56 +00001433 }
Kévin Petite7d0cce2018-10-31 12:38:56 +00001434
James Pricecf53df42020-04-20 14:41:24 -04001435 if (auto TrueVecType = dyn_cast<VectorType>(TrueType)) {
SJW2c317da2020-03-23 07:39:13 -05001436 if (!TrueType->getScalarType()->isFloatingPointTy() &&
1437 !TrueType->getScalarType()->isIntegerTy()) {
1438 return V;
1439 }
alan-baker5a8c3be2020-09-09 13:44:26 -04001440 unsigned NumElements = TrueVecType->getElementCount().getKnownMinValue();
James Pricecf53df42020-04-20 14:41:24 -04001441 if ((NumElements != 2) && (NumElements != 3) && (NumElements != 4) &&
1442 (NumElements != 8) && (NumElements != 16)) {
SJW2c317da2020-03-23 07:39:13 -05001443 return V;
1444 }
1445 }
1446
1447 // Remember the type of the operands
1448 auto OpType = TrueType;
1449
1450 // The actual bit selection will always be done on an integer type,
1451 // declare it here
1452 Type *BitType;
1453
1454 // If the operands are float, then bitcast them to int
1455 if (OpType->getScalarType()->isFloatingPointTy()) {
1456
1457 // First create the new type
1458 BitType = getIntOrIntVectorTyForCast(F.getContext(), OpType);
1459
1460 // Then bitcast all operands
1461 PredicateValue =
1462 CastInst::CreateZExtOrBitCast(PredicateValue, BitType, "", CI);
1463 FalseValue = CastInst::CreateZExtOrBitCast(FalseValue, BitType, "", CI);
1464 TrueValue = CastInst::CreateZExtOrBitCast(TrueValue, BitType, "", CI);
1465
1466 } else {
1467 // The operands have an integer type, use it directly
1468 BitType = OpType;
1469 }
1470
1471 // All the operands are now always integers
1472 // implement as (c & b) | (~c & a)
1473
1474 // Create our negated predicate value
1475 auto AllOnes = Constant::getAllOnesValue(BitType);
1476 auto NotPredicateValue = BinaryOperator::Create(
1477 Instruction::Xor, PredicateValue, AllOnes, "", CI);
1478
1479 // Then put everything together
1480 auto BitsFalse = BinaryOperator::Create(Instruction::And, NotPredicateValue,
1481 FalseValue, "", CI);
1482 auto BitsTrue = BinaryOperator::Create(Instruction::And, PredicateValue,
1483 TrueValue, "", CI);
1484
1485 V = BinaryOperator::Create(Instruction::Or, BitsFalse, BitsTrue, "", CI);
1486
1487 // If we were dealing with a floating point type, we must bitcast
1488 // the result back to that
1489 if (OpType->getScalarType()->isFloatingPointTy()) {
1490 V = CastInst::CreateZExtOrBitCast(V, OpType, "", CI);
1491 }
1492
1493 return V;
1494 });
Kévin Petite7d0cce2018-10-31 12:38:56 +00001495}
1496
SJW61531372020-06-09 07:31:08 -05001497bool ReplaceOpenCLBuiltinPass::replaceStep(Function &F, bool is_smooth) {
SJW2c317da2020-03-23 07:39:13 -05001498 // convert to vector versions
1499 Module &M = *F.getParent();
1500 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1501 SmallVector<Value *, 2> ArgsToSplat = {CI->getOperand(0)};
1502 Value *VectorArg = nullptr;
Kévin Petit6b0a9532018-10-30 20:00:39 +00001503
SJW2c317da2020-03-23 07:39:13 -05001504 // First figure out which function we're dealing with
1505 if (is_smooth) {
1506 ArgsToSplat.push_back(CI->getOperand(1));
1507 VectorArg = CI->getOperand(2);
1508 } else {
1509 VectorArg = CI->getOperand(1);
1510 }
1511
1512 // Splat arguments that need to be
1513 SmallVector<Value *, 2> SplatArgs;
James Pricecf53df42020-04-20 14:41:24 -04001514 auto VecType = cast<VectorType>(VectorArg->getType());
SJW2c317da2020-03-23 07:39:13 -05001515
1516 for (auto arg : ArgsToSplat) {
1517 Value *NewVectorArg = UndefValue::get(VecType);
alan-baker5a8c3be2020-09-09 13:44:26 -04001518 for (auto i = 0; i < VecType->getElementCount().getKnownMinValue(); i++) {
SJW2c317da2020-03-23 07:39:13 -05001519 auto index = ConstantInt::get(Type::getInt32Ty(M.getContext()), i);
1520 NewVectorArg =
1521 InsertElementInst::Create(NewVectorArg, arg, index, "", CI);
1522 }
1523 SplatArgs.push_back(NewVectorArg);
1524 }
1525
1526 // Replace the call with the vector/vector flavour
1527 SmallVector<Type *, 3> NewArgTypes(ArgsToSplat.size() + 1, VecType);
1528 const auto NewFType = FunctionType::get(CI->getType(), NewArgTypes, false);
1529
SJW61531372020-06-09 07:31:08 -05001530 std::string NewFName = Builtins::GetMangledFunctionName(
1531 is_smooth ? "smoothstep" : "step", NewFType);
1532
SJW2c317da2020-03-23 07:39:13 -05001533 const auto NewF = M.getOrInsertFunction(NewFName, NewFType);
1534
1535 SmallVector<Value *, 3> NewArgs;
1536 for (auto arg : SplatArgs) {
1537 NewArgs.push_back(arg);
1538 }
1539 NewArgs.push_back(VectorArg);
1540
1541 return CallInst::Create(NewF, NewArgs, "", CI);
1542 });
Kévin Petit6b0a9532018-10-30 20:00:39 +00001543}
1544
SJW2c317da2020-03-23 07:39:13 -05001545bool ReplaceOpenCLBuiltinPass::replaceSignbit(Function &F, bool is_vec) {
SJW2c317da2020-03-23 07:39:13 -05001546 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1547 auto Arg = CI->getOperand(0);
1548 auto Op = is_vec ? Instruction::AShr : Instruction::LShr;
David Neto22f144c2017-06-12 14:26:21 -04001549
SJW2c317da2020-03-23 07:39:13 -05001550 auto Bitcast = CastInst::CreateZExtOrBitCast(Arg, CI->getType(), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001551
SJW2c317da2020-03-23 07:39:13 -05001552 return BinaryOperator::Create(Op, Bitcast,
1553 ConstantInt::get(CI->getType(), 31), "", CI);
1554 });
David Neto22f144c2017-06-12 14:26:21 -04001555}
1556
SJW2c317da2020-03-23 07:39:13 -05001557bool ReplaceOpenCLBuiltinPass::replaceMul(Function &F, bool is_float,
1558 bool is_mad) {
SJW2c317da2020-03-23 07:39:13 -05001559 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1560 // The multiply instruction to use.
1561 auto MulInst = is_float ? Instruction::FMul : Instruction::Mul;
David Neto22f144c2017-06-12 14:26:21 -04001562
SJW2c317da2020-03-23 07:39:13 -05001563 SmallVector<Value *, 8> Args(CI->arg_begin(), CI->arg_end());
David Neto22f144c2017-06-12 14:26:21 -04001564
SJW2c317da2020-03-23 07:39:13 -05001565 Value *V = BinaryOperator::Create(MulInst, CI->getArgOperand(0),
1566 CI->getArgOperand(1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001567
SJW2c317da2020-03-23 07:39:13 -05001568 if (is_mad) {
1569 // The add instruction to use.
1570 auto AddInst = is_float ? Instruction::FAdd : Instruction::Add;
David Neto22f144c2017-06-12 14:26:21 -04001571
SJW2c317da2020-03-23 07:39:13 -05001572 V = BinaryOperator::Create(AddInst, V, CI->getArgOperand(2), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001573 }
David Neto22f144c2017-06-12 14:26:21 -04001574
SJW2c317da2020-03-23 07:39:13 -05001575 return V;
1576 });
David Neto22f144c2017-06-12 14:26:21 -04001577}
1578
SJW2c317da2020-03-23 07:39:13 -05001579bool ReplaceOpenCLBuiltinPass::replaceVstore(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001580 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1581 Value *V = nullptr;
1582 auto data = CI->getOperand(0);
Derek Chowcfd368b2017-10-19 20:58:45 -07001583
SJW2c317da2020-03-23 07:39:13 -05001584 auto data_type = data->getType();
1585 if (!data_type->isVectorTy())
1586 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001587
James Pricecf53df42020-04-20 14:41:24 -04001588 auto vec_data_type = cast<VectorType>(data_type);
1589
alan-baker5a8c3be2020-09-09 13:44:26 -04001590 auto elems = vec_data_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001591 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1592 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001593
SJW2c317da2020-03-23 07:39:13 -05001594 auto offset = CI->getOperand(1);
1595 auto ptr = CI->getOperand(2);
1596 auto ptr_type = ptr->getType();
1597 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001598 if (pointee_type != vec_data_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001599 return V;
alan-bakerf795f392019-06-11 18:24:34 -04001600
SJW2c317da2020-03-23 07:39:13 -05001601 // Avoid pointer casts. Instead generate the correct number of stores
1602 // and rely on drivers to coalesce appropriately.
1603 IRBuilder<> builder(CI);
1604 auto elems_const = builder.getInt32(elems);
1605 auto adjust = builder.CreateMul(offset, elems_const);
1606 for (auto i = 0; i < elems; ++i) {
1607 auto idx = builder.getInt32(i);
1608 auto add = builder.CreateAdd(adjust, idx);
1609 auto gep = builder.CreateGEP(ptr, add);
1610 auto extract = builder.CreateExtractElement(data, i);
1611 V = builder.CreateStore(extract, gep);
Derek Chowcfd368b2017-10-19 20:58:45 -07001612 }
SJW2c317da2020-03-23 07:39:13 -05001613 return V;
1614 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001615}
1616
SJW2c317da2020-03-23 07:39:13 -05001617bool ReplaceOpenCLBuiltinPass::replaceVload(Function &F) {
SJW2c317da2020-03-23 07:39:13 -05001618 return replaceCallsWithValue(F, [&](CallInst *CI) -> llvm::Value * {
1619 Value *V = nullptr;
1620 auto ret_type = F.getReturnType();
1621 if (!ret_type->isVectorTy())
1622 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001623
James Pricecf53df42020-04-20 14:41:24 -04001624 auto vec_ret_type = cast<VectorType>(ret_type);
1625
alan-baker5a8c3be2020-09-09 13:44:26 -04001626 auto elems = vec_ret_type->getElementCount().getKnownMinValue();
SJW2c317da2020-03-23 07:39:13 -05001627 if (elems != 2 && elems != 3 && elems != 4 && elems != 8 && elems != 16)
1628 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001629
SJW2c317da2020-03-23 07:39:13 -05001630 auto offset = CI->getOperand(0);
1631 auto ptr = CI->getOperand(1);
1632 auto ptr_type = ptr->getType();
1633 auto pointee_type = ptr_type->getPointerElementType();
James Pricecf53df42020-04-20 14:41:24 -04001634 if (pointee_type != vec_ret_type->getElementType())
SJW2c317da2020-03-23 07:39:13 -05001635 return V;
Derek Chowcfd368b2017-10-19 20:58:45 -07001636
SJW2c317da2020-03-23 07:39:13 -05001637 // Avoid pointer casts. Instead generate the correct number of loads
1638 // and rely on drivers to coalesce appropriately.
1639 IRBuilder<> builder(CI);
1640 auto elems_const = builder.getInt32(elems);
1641 V = UndefValue::get(ret_type);
1642 auto adjust = builder.CreateMul(offset, elems_const);
1643 for (auto i = 0; i < elems; ++i) {
1644 auto idx = builder.getInt32(i);
1645 auto add = builder.CreateAdd(adjust, idx);
1646 auto gep = builder.CreateGEP(ptr, add);
1647 auto load = builder.CreateLoad(gep);
1648 V = builder.CreateInsertElement(V, load, i);
Derek Chowcfd368b2017-10-19 20:58:45 -07001649 }
SJW2c317da2020-03-23 07:39:13 -05001650 return V;
1651 });
Derek Chowcfd368b2017-10-19 20:58:45 -07001652}
1653
SJW2c317da2020-03-23 07:39:13 -05001654bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F,
1655 const std::string &name,
1656 int vec_size) {
1657 bool is_clspv_version = !name.compare(0, 8, "__clspv_");
1658 if (!vec_size) {
1659 // deduce vec_size from last character of name (e.g. vload_half4)
1660 vec_size = std::atoi(&name.back());
David Neto22f144c2017-06-12 14:26:21 -04001661 }
SJW2c317da2020-03-23 07:39:13 -05001662 switch (vec_size) {
1663 case 2:
1664 return is_clspv_version ? replaceClspvVloadaHalf2(F) : replaceVloadHalf2(F);
1665 case 4:
1666 return is_clspv_version ? replaceClspvVloadaHalf4(F) : replaceVloadHalf4(F);
1667 case 0:
1668 if (!is_clspv_version) {
1669 return replaceVloadHalf(F);
1670 }
1671 default:
1672 llvm_unreachable("Unsupported vload_half vector size");
1673 break;
1674 }
1675 return false;
David Neto22f144c2017-06-12 14:26:21 -04001676}
1677
SJW2c317da2020-03-23 07:39:13 -05001678bool ReplaceOpenCLBuiltinPass::replaceVloadHalf(Function &F) {
1679 Module &M = *F.getParent();
1680 return replaceCallsWithValue(F, [&](CallInst *CI) {
1681 // The index argument from vload_half.
1682 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001683
SJW2c317da2020-03-23 07:39:13 -05001684 // The pointer argument from vload_half.
1685 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001686
SJW2c317da2020-03-23 07:39:13 -05001687 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001688 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
SJW2c317da2020-03-23 07:39:13 -05001689 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
1690
1691 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001692 auto SPIRVIntrinsic = clspv::UnpackFunction();
SJW2c317da2020-03-23 07:39:13 -05001693
1694 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
1695
1696 Value *V = nullptr;
1697
alan-baker7efcaaa2020-05-06 19:33:27 -04001698 bool supports_16bit_storage = true;
1699 switch (Arg1->getType()->getPointerAddressSpace()) {
1700 case clspv::AddressSpace::Global:
1701 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1702 clspv::Option::StorageClass::kSSBO);
1703 break;
1704 case clspv::AddressSpace::Constant:
1705 if (clspv::Option::ConstantArgsInUniformBuffer())
1706 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1707 clspv::Option::StorageClass::kUBO);
1708 else
1709 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1710 clspv::Option::StorageClass::kSSBO);
1711 break;
1712 default:
1713 // Clspv will emit the Float16 capability if the half type is
1714 // encountered. That capability covers private and local addressspaces.
1715 break;
1716 }
1717
1718 if (supports_16bit_storage) {
SJW2c317da2020-03-23 07:39:13 -05001719 auto ShortTy = Type::getInt16Ty(M.getContext());
1720 auto ShortPointerTy =
1721 PointerType::get(ShortTy, Arg1->getType()->getPointerAddressSpace());
1722
1723 // Cast the half* pointer to short*.
1724 auto Cast = CastInst::CreatePointerCast(Arg1, ShortPointerTy, "", CI);
1725
1726 // Index into the correct address of the casted pointer.
1727 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg0, "", CI);
1728
1729 // Load from the short* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001730 auto Load = new LoadInst(ShortTy, Index, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001731
1732 // ZExt the short -> int.
1733 auto ZExt = CastInst::CreateZExtOrBitCast(Load, IntTy, "", CI);
1734
1735 // Get our float2.
1736 auto Call = CallInst::Create(NewF, ZExt, "", CI);
1737
1738 // Extract out the bottom element which is our float result.
1739 V = ExtractElementInst::Create(Call, ConstantInt::get(IntTy, 0), "", CI);
1740 } else {
1741 // Assume the pointer argument points to storage aligned to 32bits
1742 // or more.
1743 // TODO(dneto): Do more analysis to make sure this is true?
1744 //
1745 // Replace call vstore_half(i32 %index, half addrspace(1) %base)
1746 // with:
1747 //
1748 // %base_i32_ptr = bitcast half addrspace(1)* %base to i32
1749 // addrspace(1)* %index_is_odd32 = and i32 %index, 1 %index_i32 =
1750 // lshr i32 %index, 1 %in_ptr = getlementptr i32, i32
1751 // addrspace(1)* %base_i32_ptr, %index_i32 %value_i32 = load i32,
1752 // i32 addrspace(1)* %in_ptr %converted = call <2 x float>
1753 // @spirv.unpack.v2f16(i32 %value_i32) %value = extractelement <2
1754 // x float> %converted, %index_is_odd32
1755
1756 auto IntPointerTy =
1757 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
1758
1759 // Cast the base pointer to int*.
1760 // In a valid call (according to assumptions), this should get
1761 // optimized away in the simplify GEP pass.
1762 auto Cast = CastInst::CreatePointerCast(Arg1, IntPointerTy, "", CI);
1763
1764 auto One = ConstantInt::get(IntTy, 1);
1765 auto IndexIsOdd = BinaryOperator::CreateAnd(Arg0, One, "", CI);
1766 auto IndexIntoI32 = BinaryOperator::CreateLShr(Arg0, One, "", CI);
1767
1768 // Index into the correct address of the casted pointer.
1769 auto Ptr = GetElementPtrInst::Create(IntTy, Cast, IndexIntoI32, "", CI);
1770
1771 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001772 auto Load = new LoadInst(IntTy, Ptr, "", CI);
SJW2c317da2020-03-23 07:39:13 -05001773
1774 // Get our float2.
1775 auto Call = CallInst::Create(NewF, Load, "", CI);
1776
1777 // Extract out the float result, where the element number is
1778 // determined by whether the original index was even or odd.
1779 V = ExtractElementInst::Create(Call, IndexIsOdd, "", CI);
1780 }
1781 return V;
1782 });
1783}
1784
1785bool ReplaceOpenCLBuiltinPass::replaceVloadHalf2(Function &F) {
1786 Module &M = *F.getParent();
1787 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001788 // The index argument from vload_half.
1789 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001790
Kévin Petite8edce32019-04-10 14:23:32 +01001791 // The pointer argument from vload_half.
1792 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001793
Kévin Petite8edce32019-04-10 14:23:32 +01001794 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001795 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001796 auto NewPointerTy =
1797 PointerType::get(IntTy, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001798 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001799
Kévin Petite8edce32019-04-10 14:23:32 +01001800 // Cast the half* pointer to int*.
1801 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001802
Kévin Petite8edce32019-04-10 14:23:32 +01001803 // Index into the correct address of the casted pointer.
1804 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001805
Kévin Petite8edce32019-04-10 14:23:32 +01001806 // Load from the int* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001807 auto Load = new LoadInst(IntTy, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001808
Kévin Petite8edce32019-04-10 14:23:32 +01001809 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001810 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001811
Kévin Petite8edce32019-04-10 14:23:32 +01001812 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001813
Kévin Petite8edce32019-04-10 14:23:32 +01001814 // Get our float2.
1815 return CallInst::Create(NewF, Load, "", CI);
1816 });
David Neto22f144c2017-06-12 14:26:21 -04001817}
1818
SJW2c317da2020-03-23 07:39:13 -05001819bool ReplaceOpenCLBuiltinPass::replaceVloadHalf4(Function &F) {
1820 Module &M = *F.getParent();
1821 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001822 // The index argument from vload_half.
1823 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001824
Kévin Petite8edce32019-04-10 14:23:32 +01001825 // The pointer argument from vload_half.
1826 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001827
Kévin Petite8edce32019-04-10 14:23:32 +01001828 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001829 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1830 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001831 auto NewPointerTy =
1832 PointerType::get(Int2Ty, Arg1->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01001833 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto22f144c2017-06-12 14:26:21 -04001834
Kévin Petite8edce32019-04-10 14:23:32 +01001835 // Cast the half* pointer to int2*.
1836 auto Cast = CastInst::CreatePointerCast(Arg1, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001837
Kévin Petite8edce32019-04-10 14:23:32 +01001838 // Index into the correct address of the casted pointer.
1839 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001840
Kévin Petite8edce32019-04-10 14:23:32 +01001841 // Load from the int2* we casted to.
alan-baker741fd1f2020-04-14 17:38:15 -04001842 auto Load = new LoadInst(Int2Ty, Index, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001843
Kévin Petite8edce32019-04-10 14:23:32 +01001844 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001845 auto X =
1846 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1847 auto Y =
1848 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001849
Kévin Petite8edce32019-04-10 14:23:32 +01001850 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001851 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001852
Kévin Petite8edce32019-04-10 14:23:32 +01001853 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001854
Kévin Petite8edce32019-04-10 14:23:32 +01001855 // Get the lower (x & y) components of our final float4.
1856 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001857
Kévin Petite8edce32019-04-10 14:23:32 +01001858 // Get the higher (z & w) components of our final float4.
1859 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001860
Kévin Petite8edce32019-04-10 14:23:32 +01001861 Constant *ShuffleMask[4] = {
1862 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1863 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04001864
Kévin Petite8edce32019-04-10 14:23:32 +01001865 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001866 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1867 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001868 });
David Neto22f144c2017-06-12 14:26:21 -04001869}
1870
SJW2c317da2020-03-23 07:39:13 -05001871bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf2(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001872
1873 // Replace __clspv_vloada_half2(uint Index, global uint* Ptr) with:
1874 //
1875 // %u = load i32 %ptr
1876 // %fxy = call <2 x float> Unpack2xHalf(u)
1877 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001878 Module &M = *F.getParent();
1879 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001880 auto Index = CI->getOperand(0);
1881 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001882
Kévin Petite8edce32019-04-10 14:23:32 +01001883 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001884 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001885 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001886
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001887 auto IndexedPtr = GetElementPtrInst::Create(IntTy, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001888 auto Load = new LoadInst(IntTy, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001889
Kévin Petite8edce32019-04-10 14:23:32 +01001890 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001891 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001892
Kévin Petite8edce32019-04-10 14:23:32 +01001893 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001894
Kévin Petite8edce32019-04-10 14:23:32 +01001895 // Get our final float2.
1896 return CallInst::Create(NewF, Load, "", CI);
1897 });
David Neto6ad93232018-06-07 15:42:58 -07001898}
1899
SJW2c317da2020-03-23 07:39:13 -05001900bool ReplaceOpenCLBuiltinPass::replaceClspvVloadaHalf4(Function &F) {
David Neto6ad93232018-06-07 15:42:58 -07001901
1902 // Replace __clspv_vloada_half4(uint Index, global uint2* Ptr) with:
1903 //
1904 // %u2 = load <2 x i32> %ptr
1905 // %u2xy = extractelement %u2, 0
1906 // %u2zw = extractelement %u2, 1
1907 // %fxy = call <2 x float> Unpack2xHalf(uint)
1908 // %fzw = call <2 x float> Unpack2xHalf(uint)
1909 // %result = shufflevector %fxy %fzw <4 x i32> <0, 1, 2, 3>
SJW2c317da2020-03-23 07:39:13 -05001910 Module &M = *F.getParent();
1911 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001912 auto Index = CI->getOperand(0);
1913 auto Ptr = CI->getOperand(1);
David Neto6ad93232018-06-07 15:42:58 -07001914
Kévin Petite8edce32019-04-10 14:23:32 +01001915 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001916 auto Int2Ty = FixedVectorType::get(IntTy, 2);
1917 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001918 auto NewFType = FunctionType::get(Float2Ty, IntTy, false);
David Neto6ad93232018-06-07 15:42:58 -07001919
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001920 auto IndexedPtr = GetElementPtrInst::Create(Int2Ty, Ptr, Index, "", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04001921 auto Load = new LoadInst(Int2Ty, IndexedPtr, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001922
Kévin Petite8edce32019-04-10 14:23:32 +01001923 // Extract each element from the loaded int2.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001924 auto X =
1925 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 0), "", CI);
1926 auto Y =
1927 ExtractElementInst::Create(Load, ConstantInt::get(IntTy, 1), "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001928
Kévin Petite8edce32019-04-10 14:23:32 +01001929 // Our intrinsic to unpack a float2 from an int.
SJW61531372020-06-09 07:31:08 -05001930 auto SPIRVIntrinsic = clspv::UnpackFunction();
David Neto6ad93232018-06-07 15:42:58 -07001931
Kévin Petite8edce32019-04-10 14:23:32 +01001932 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto6ad93232018-06-07 15:42:58 -07001933
Kévin Petite8edce32019-04-10 14:23:32 +01001934 // Get the lower (x & y) components of our final float4.
1935 auto Lo = CallInst::Create(NewF, X, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001936
Kévin Petite8edce32019-04-10 14:23:32 +01001937 // Get the higher (z & w) components of our final float4.
1938 auto Hi = CallInst::Create(NewF, Y, "", CI);
David Neto6ad93232018-06-07 15:42:58 -07001939
Kévin Petite8edce32019-04-10 14:23:32 +01001940 Constant *ShuffleMask[4] = {
1941 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
1942 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
David Neto6ad93232018-06-07 15:42:58 -07001943
Kévin Petite8edce32019-04-10 14:23:32 +01001944 // Combine our two float2's into one float4.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001945 return new ShuffleVectorInst(Lo, Hi, ConstantVector::get(ShuffleMask), "",
1946 CI);
Kévin Petite8edce32019-04-10 14:23:32 +01001947 });
David Neto6ad93232018-06-07 15:42:58 -07001948}
1949
SJW2c317da2020-03-23 07:39:13 -05001950bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F, int vec_size) {
1951 switch (vec_size) {
1952 case 0:
1953 return replaceVstoreHalf(F);
1954 case 2:
1955 return replaceVstoreHalf2(F);
1956 case 4:
1957 return replaceVstoreHalf4(F);
1958 default:
1959 llvm_unreachable("Unsupported vstore_half vector size");
1960 break;
1961 }
1962 return false;
1963}
David Neto22f144c2017-06-12 14:26:21 -04001964
SJW2c317da2020-03-23 07:39:13 -05001965bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf(Function &F) {
1966 Module &M = *F.getParent();
1967 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01001968 // The value to store.
1969 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04001970
Kévin Petite8edce32019-04-10 14:23:32 +01001971 // The index argument from vstore_half.
1972 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04001973
Kévin Petite8edce32019-04-10 14:23:32 +01001974 // The pointer argument from vstore_half.
1975 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04001976
Kévin Petite8edce32019-04-10 14:23:32 +01001977 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04001978 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Kévin Petite8edce32019-04-10 14:23:32 +01001979 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
1980 auto One = ConstantInt::get(IntTy, 1);
David Neto22f144c2017-06-12 14:26:21 -04001981
Kévin Petite8edce32019-04-10 14:23:32 +01001982 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05001983 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04001984
Kévin Petite8edce32019-04-10 14:23:32 +01001985 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04001986
Kévin Petite8edce32019-04-10 14:23:32 +01001987 // Insert our value into a float2 so that we can pack it.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04001988 auto TempVec = InsertElementInst::Create(
1989 UndefValue::get(Float2Ty), Arg0, ConstantInt::get(IntTy, 0), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001990
Kévin Petite8edce32019-04-10 14:23:32 +01001991 // Pack the float2 -> half2 (in an int).
1992 auto X = CallInst::Create(NewF, TempVec, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04001993
alan-baker7efcaaa2020-05-06 19:33:27 -04001994 bool supports_16bit_storage = true;
1995 switch (Arg2->getType()->getPointerAddressSpace()) {
1996 case clspv::AddressSpace::Global:
1997 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
1998 clspv::Option::StorageClass::kSSBO);
1999 break;
2000 case clspv::AddressSpace::Constant:
2001 if (clspv::Option::ConstantArgsInUniformBuffer())
2002 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2003 clspv::Option::StorageClass::kUBO);
2004 else
2005 supports_16bit_storage = clspv::Option::Supports16BitStorageClass(
2006 clspv::Option::StorageClass::kSSBO);
2007 break;
2008 default:
2009 // Clspv will emit the Float16 capability if the half type is
2010 // encountered. That capability covers private and local addressspaces.
2011 break;
2012 }
2013
SJW2c317da2020-03-23 07:39:13 -05002014 Value *V = nullptr;
alan-baker7efcaaa2020-05-06 19:33:27 -04002015 if (supports_16bit_storage) {
Kévin Petite8edce32019-04-10 14:23:32 +01002016 auto ShortTy = Type::getInt16Ty(M.getContext());
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002017 auto ShortPointerTy =
2018 PointerType::get(ShortTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002019
Kévin Petite8edce32019-04-10 14:23:32 +01002020 // Truncate our i32 to an i16.
2021 auto Trunc = CastInst::CreateTruncOrBitCast(X, ShortTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002022
Kévin Petite8edce32019-04-10 14:23:32 +01002023 // Cast the half* pointer to short*.
2024 auto Cast = CastInst::CreatePointerCast(Arg2, ShortPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002025
Kévin Petite8edce32019-04-10 14:23:32 +01002026 // Index into the correct address of the casted pointer.
2027 auto Index = GetElementPtrInst::Create(ShortTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002028
Kévin Petite8edce32019-04-10 14:23:32 +01002029 // Store to the int* we casted to.
SJW2c317da2020-03-23 07:39:13 -05002030 V = new StoreInst(Trunc, Index, CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002031 } else {
2032 // We can only write to 32-bit aligned words.
2033 //
2034 // Assuming base is aligned to 32-bits, replace the equivalent of
2035 // vstore_half(value, index, base)
2036 // with:
2037 // uint32_t* target_ptr = (uint32_t*)(base) + index / 2;
2038 // uint32_t write_to_upper_half = index & 1u;
2039 // uint32_t shift = write_to_upper_half << 4;
2040 //
2041 // // Pack the float value as a half number in bottom 16 bits
2042 // // of an i32.
2043 // uint32_t packed = spirv.pack.v2f16((float2)(value, undef));
2044 //
2045 // uint32_t xor_value = (*target_ptr & (0xffff << shift))
2046 // ^ ((packed & 0xffff) << shift)
2047 // // We only need relaxed consistency, but OpenCL 1.2 only has
2048 // // sequentially consistent atomics.
2049 // // TODO(dneto): Use relaxed consistency.
2050 // atomic_xor(target_ptr, xor_value)
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002051 auto IntPointerTy =
2052 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
David Neto22f144c2017-06-12 14:26:21 -04002053
Kévin Petite8edce32019-04-10 14:23:32 +01002054 auto Four = ConstantInt::get(IntTy, 4);
2055 auto FFFF = ConstantInt::get(IntTy, 0xffff);
David Neto17852de2017-05-29 17:29:31 -04002056
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002057 auto IndexIsOdd =
2058 BinaryOperator::CreateAnd(Arg1, One, "index_is_odd_i32", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002059 // Compute index / 2
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002060 auto IndexIntoI32 =
2061 BinaryOperator::CreateLShr(Arg1, One, "index_into_i32", CI);
2062 auto BaseI32Ptr =
2063 CastInst::CreatePointerCast(Arg2, IntPointerTy, "base_i32_ptr", CI);
2064 auto OutPtr = GetElementPtrInst::Create(IntTy, BaseI32Ptr, IndexIntoI32,
2065 "base_i32_ptr", CI);
alan-baker741fd1f2020-04-14 17:38:15 -04002066 auto CurrentValue = new LoadInst(IntTy, OutPtr, "current_value", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002067 auto Shift = BinaryOperator::CreateShl(IndexIsOdd, Four, "shift", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002068 auto MaskBitsToWrite =
2069 BinaryOperator::CreateShl(FFFF, Shift, "mask_bits_to_write", CI);
2070 auto MaskedCurrent = BinaryOperator::CreateAnd(
2071 MaskBitsToWrite, CurrentValue, "masked_current", CI);
David Neto17852de2017-05-29 17:29:31 -04002072
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002073 auto XLowerBits =
2074 BinaryOperator::CreateAnd(X, FFFF, "lower_bits_of_packed", CI);
2075 auto NewBitsToWrite =
2076 BinaryOperator::CreateShl(XLowerBits, Shift, "new_bits_to_write", CI);
2077 auto ValueToXor = BinaryOperator::CreateXor(MaskedCurrent, NewBitsToWrite,
2078 "value_to_xor", CI);
David Neto17852de2017-05-29 17:29:31 -04002079
Kévin Petite8edce32019-04-10 14:23:32 +01002080 // Generate the call to atomi_xor.
2081 SmallVector<Type *, 5> ParamTypes;
2082 // The pointer type.
2083 ParamTypes.push_back(IntPointerTy);
2084 // The Types for memory scope, semantics, and value.
2085 ParamTypes.push_back(IntTy);
2086 ParamTypes.push_back(IntTy);
2087 ParamTypes.push_back(IntTy);
2088 auto NewFType = FunctionType::get(IntTy, ParamTypes, false);
2089 auto NewF = M.getOrInsertFunction("spirv.atomic_xor", NewFType);
David Neto17852de2017-05-29 17:29:31 -04002090
Kévin Petite8edce32019-04-10 14:23:32 +01002091 const auto ConstantScopeDevice =
2092 ConstantInt::get(IntTy, spv::ScopeDevice);
2093 // Assume the pointee is in OpenCL global (SPIR-V Uniform) or local
2094 // (SPIR-V Workgroup).
2095 const auto AddrSpaceSemanticsBits =
2096 IntPointerTy->getPointerAddressSpace() == 1
2097 ? spv::MemorySemanticsUniformMemoryMask
2098 : spv::MemorySemanticsWorkgroupMemoryMask;
David Neto17852de2017-05-29 17:29:31 -04002099
Kévin Petite8edce32019-04-10 14:23:32 +01002100 // We're using relaxed consistency here.
2101 const auto ConstantMemorySemantics =
2102 ConstantInt::get(IntTy, spv::MemorySemanticsUniformMemoryMask |
2103 AddrSpaceSemanticsBits);
David Neto17852de2017-05-29 17:29:31 -04002104
Kévin Petite8edce32019-04-10 14:23:32 +01002105 SmallVector<Value *, 5> Params{OutPtr, ConstantScopeDevice,
2106 ConstantMemorySemantics, ValueToXor};
2107 CallInst::Create(NewF, Params, "store_halfword_xor_trick", CI);
SJW2c317da2020-03-23 07:39:13 -05002108
2109 // Return a Nop so the old Call is removed
2110 Function *donothing = Intrinsic::getDeclaration(&M, Intrinsic::donothing);
2111 V = CallInst::Create(donothing, {}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002112 }
David Neto22f144c2017-06-12 14:26:21 -04002113
SJW2c317da2020-03-23 07:39:13 -05002114 return V;
Kévin Petite8edce32019-04-10 14:23:32 +01002115 });
David Neto22f144c2017-06-12 14:26:21 -04002116}
2117
SJW2c317da2020-03-23 07:39:13 -05002118bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf2(Function &F) {
2119 Module &M = *F.getParent();
2120 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002121 // The value to store.
2122 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002123
Kévin Petite8edce32019-04-10 14:23:32 +01002124 // The index argument from vstore_half.
2125 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002126
Kévin Petite8edce32019-04-10 14:23:32 +01002127 // The pointer argument from vstore_half.
2128 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002129
Kévin Petite8edce32019-04-10 14:23:32 +01002130 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002131 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002132 auto NewPointerTy =
2133 PointerType::get(IntTy, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002134 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002135
Kévin Petite8edce32019-04-10 14:23:32 +01002136 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002137 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002138
Kévin Petite8edce32019-04-10 14:23:32 +01002139 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002140
Kévin Petite8edce32019-04-10 14:23:32 +01002141 // Turn the packed x & y into the final packing.
2142 auto X = CallInst::Create(NewF, Arg0, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002143
Kévin Petite8edce32019-04-10 14:23:32 +01002144 // Cast the half* pointer to int*.
2145 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002146
Kévin Petite8edce32019-04-10 14:23:32 +01002147 // Index into the correct address of the casted pointer.
2148 auto Index = GetElementPtrInst::Create(IntTy, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002149
Kévin Petite8edce32019-04-10 14:23:32 +01002150 // Store to the int* we casted to.
2151 return new StoreInst(X, Index, CI);
2152 });
David Neto22f144c2017-06-12 14:26:21 -04002153}
2154
SJW2c317da2020-03-23 07:39:13 -05002155bool ReplaceOpenCLBuiltinPass::replaceVstoreHalf4(Function &F) {
2156 Module &M = *F.getParent();
2157 return replaceCallsWithValue(F, [&](CallInst *CI) {
Kévin Petite8edce32019-04-10 14:23:32 +01002158 // The value to store.
2159 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002160
Kévin Petite8edce32019-04-10 14:23:32 +01002161 // The index argument from vstore_half.
2162 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002163
Kévin Petite8edce32019-04-10 14:23:32 +01002164 // The pointer argument from vstore_half.
2165 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002166
Kévin Petite8edce32019-04-10 14:23:32 +01002167 auto IntTy = Type::getInt32Ty(M.getContext());
alan-bakerb3e2b6d2020-06-24 23:59:57 -04002168 auto Int2Ty = FixedVectorType::get(IntTy, 2);
2169 auto Float2Ty = FixedVectorType::get(Type::getFloatTy(M.getContext()), 2);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002170 auto NewPointerTy =
2171 PointerType::get(Int2Ty, Arg2->getType()->getPointerAddressSpace());
Kévin Petite8edce32019-04-10 14:23:32 +01002172 auto NewFType = FunctionType::get(IntTy, Float2Ty, false);
David Neto22f144c2017-06-12 14:26:21 -04002173
Kévin Petite8edce32019-04-10 14:23:32 +01002174 Constant *LoShuffleMask[2] = {ConstantInt::get(IntTy, 0),
2175 ConstantInt::get(IntTy, 1)};
David Neto22f144c2017-06-12 14:26:21 -04002176
Kévin Petite8edce32019-04-10 14:23:32 +01002177 // Extract out the x & y components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002178 auto Lo = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2179 ConstantVector::get(LoShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002180
Kévin Petite8edce32019-04-10 14:23:32 +01002181 Constant *HiShuffleMask[2] = {ConstantInt::get(IntTy, 2),
2182 ConstantInt::get(IntTy, 3)};
David Neto22f144c2017-06-12 14:26:21 -04002183
Kévin Petite8edce32019-04-10 14:23:32 +01002184 // Extract out the z & w components of our to store value.
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002185 auto Hi = new ShuffleVectorInst(Arg0, UndefValue::get(Arg0->getType()),
2186 ConstantVector::get(HiShuffleMask), "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002187
Kévin Petite8edce32019-04-10 14:23:32 +01002188 // Our intrinsic to pack a float2 to an int.
SJW61531372020-06-09 07:31:08 -05002189 auto SPIRVIntrinsic = clspv::PackFunction();
David Neto22f144c2017-06-12 14:26:21 -04002190
Kévin Petite8edce32019-04-10 14:23:32 +01002191 auto NewF = M.getOrInsertFunction(SPIRVIntrinsic, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002192
Kévin Petite8edce32019-04-10 14:23:32 +01002193 // Turn the packed x & y into the final component of our int2.
2194 auto X = CallInst::Create(NewF, Lo, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002195
Kévin Petite8edce32019-04-10 14:23:32 +01002196 // Turn the packed z & w into the final component of our int2.
2197 auto Y = CallInst::Create(NewF, Hi, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002198
Kévin Petite8edce32019-04-10 14:23:32 +01002199 auto Combine = InsertElementInst::Create(
2200 UndefValue::get(Int2Ty), X, ConstantInt::get(IntTy, 0), "", CI);
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002201 Combine = InsertElementInst::Create(Combine, Y, ConstantInt::get(IntTy, 1),
2202 "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002203
Kévin Petite8edce32019-04-10 14:23:32 +01002204 // Cast the half* pointer to int2*.
2205 auto Cast = CastInst::CreatePointerCast(Arg2, NewPointerTy, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002206
Kévin Petite8edce32019-04-10 14:23:32 +01002207 // Index into the correct address of the casted pointer.
2208 auto Index = GetElementPtrInst::Create(Int2Ty, Cast, Arg1, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002209
Kévin Petite8edce32019-04-10 14:23:32 +01002210 // Store to the int2* we casted to.
2211 return new StoreInst(Combine, Index, CI);
2212 });
David Neto22f144c2017-06-12 14:26:21 -04002213}
2214
SJW2c317da2020-03-23 07:39:13 -05002215bool ReplaceOpenCLBuiltinPass::replaceHalfReadImage(Function &F) {
2216 // convert half to float
2217 Module &M = *F.getParent();
2218 return replaceCallsWithValue(F, [&](CallInst *CI) {
2219 SmallVector<Type *, 3> types;
2220 SmallVector<Value *, 3> args;
2221 for (auto i = 0; i < CI->getNumArgOperands(); ++i) {
2222 types.push_back(CI->getArgOperand(i)->getType());
2223 args.push_back(CI->getArgOperand(i));
alan-bakerf7e17cb2020-01-02 07:29:59 -05002224 }
alan-bakerf7e17cb2020-01-02 07:29:59 -05002225
alan-baker5a8c3be2020-09-09 13:44:26 -04002226 auto NewFType =
2227 FunctionType::get(FixedVectorType::get(Type::getFloatTy(M.getContext()),
2228 cast<VectorType>(CI->getType())
2229 ->getElementCount()
2230 .getKnownMinValue()),
2231 types, false);
SJW2c317da2020-03-23 07:39:13 -05002232
SJW61531372020-06-09 07:31:08 -05002233 std::string NewFName =
2234 Builtins::GetMangledFunctionName("read_imagef", NewFType);
SJW2c317da2020-03-23 07:39:13 -05002235
2236 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2237
2238 auto NewCI = CallInst::Create(NewF, args, "", CI);
2239
2240 // Convert to the half type.
2241 return CastInst::CreateFPCast(NewCI, CI->getType(), "", CI);
2242 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002243}
2244
SJW2c317da2020-03-23 07:39:13 -05002245bool ReplaceOpenCLBuiltinPass::replaceHalfWriteImage(Function &F) {
2246 // convert half to float
2247 Module &M = *F.getParent();
2248 return replaceCallsWithValue(F, [&](CallInst *CI) {
2249 SmallVector<Type *, 3> types(3);
2250 SmallVector<Value *, 3> args(3);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002251
SJW2c317da2020-03-23 07:39:13 -05002252 // Image
2253 types[0] = CI->getArgOperand(0)->getType();
2254 args[0] = CI->getArgOperand(0);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002255
SJW2c317da2020-03-23 07:39:13 -05002256 // Coord
2257 types[1] = CI->getArgOperand(1)->getType();
2258 args[1] = CI->getArgOperand(1);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002259
SJW2c317da2020-03-23 07:39:13 -05002260 // Data
alan-baker5a8c3be2020-09-09 13:44:26 -04002261 types[2] =
2262 FixedVectorType::get(Type::getFloatTy(M.getContext()),
2263 cast<VectorType>(CI->getArgOperand(2)->getType())
2264 ->getElementCount()
2265 .getKnownMinValue());
alan-bakerf7e17cb2020-01-02 07:29:59 -05002266
SJW2c317da2020-03-23 07:39:13 -05002267 auto NewFType =
2268 FunctionType::get(Type::getVoidTy(M.getContext()), types, false);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002269
SJW61531372020-06-09 07:31:08 -05002270 std::string NewFName =
2271 Builtins::GetMangledFunctionName("write_imagef", NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002272
SJW2c317da2020-03-23 07:39:13 -05002273 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
alan-bakerf7e17cb2020-01-02 07:29:59 -05002274
SJW2c317da2020-03-23 07:39:13 -05002275 // Convert data to the float type.
2276 auto Cast = CastInst::CreateFPCast(CI->getArgOperand(2), types[2], "", CI);
2277 args[2] = Cast;
alan-bakerf7e17cb2020-01-02 07:29:59 -05002278
SJW2c317da2020-03-23 07:39:13 -05002279 return CallInst::Create(NewF, args, "", CI);
2280 });
alan-bakerf7e17cb2020-01-02 07:29:59 -05002281}
2282
SJW2c317da2020-03-23 07:39:13 -05002283bool ReplaceOpenCLBuiltinPass::replaceSampledReadImageWithIntCoords(
2284 Function &F) {
2285 // convert read_image with int coords to float coords
2286 Module &M = *F.getParent();
2287 return replaceCallsWithValue(F, [&](CallInst *CI) {
2288 // The image.
2289 auto Arg0 = CI->getOperand(0);
David Neto22f144c2017-06-12 14:26:21 -04002290
SJW2c317da2020-03-23 07:39:13 -05002291 // The sampler.
2292 auto Arg1 = CI->getOperand(1);
David Neto22f144c2017-06-12 14:26:21 -04002293
SJW2c317da2020-03-23 07:39:13 -05002294 // The coordinate (integer type that we can't handle).
2295 auto Arg2 = CI->getOperand(2);
David Neto22f144c2017-06-12 14:26:21 -04002296
SJW2c317da2020-03-23 07:39:13 -05002297 uint32_t dim = clspv::ImageDimensionality(Arg0->getType());
2298 uint32_t components =
2299 dim + (clspv::IsArrayImageType(Arg0->getType()) ? 1 : 0);
2300 Type *float_ty = nullptr;
2301 if (components == 1) {
2302 float_ty = Type::getFloatTy(M.getContext());
2303 } else {
alan-baker5a8c3be2020-09-09 13:44:26 -04002304 float_ty = FixedVectorType::get(Type::getFloatTy(M.getContext()),
2305 cast<VectorType>(Arg2->getType())
2306 ->getElementCount()
2307 .getKnownMinValue());
David Neto22f144c2017-06-12 14:26:21 -04002308 }
David Neto22f144c2017-06-12 14:26:21 -04002309
SJW2c317da2020-03-23 07:39:13 -05002310 auto NewFType = FunctionType::get(
2311 CI->getType(), {Arg0->getType(), Arg1->getType(), float_ty}, false);
2312
2313 std::string NewFName = F.getName().str();
2314 NewFName[NewFName.length() - 1] = 'f';
2315
2316 auto NewF = M.getOrInsertFunction(NewFName, NewFType);
2317
2318 auto Cast = CastInst::Create(Instruction::SIToFP, Arg2, float_ty, "", CI);
2319
2320 return CallInst::Create(NewF, {Arg0, Arg1, Cast}, "", CI);
2321 });
David Neto22f144c2017-06-12 14:26:21 -04002322}
2323
SJW2c317da2020-03-23 07:39:13 -05002324bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F, spv::Op Op) {
2325 return replaceCallsWithValue(F, [&](CallInst *CI) {
2326 auto IntTy = Type::getInt32Ty(F.getContext());
David Neto22f144c2017-06-12 14:26:21 -04002327
SJW2c317da2020-03-23 07:39:13 -05002328 // We need to map the OpenCL constants to the SPIR-V equivalents.
2329 const auto ConstantScopeDevice = ConstantInt::get(IntTy, spv::ScopeDevice);
2330 const auto ConstantMemorySemantics = ConstantInt::get(
2331 IntTy, spv::MemorySemanticsUniformMemoryMask |
2332 spv::MemorySemanticsSequentiallyConsistentMask);
David Neto22f144c2017-06-12 14:26:21 -04002333
SJW2c317da2020-03-23 07:39:13 -05002334 SmallVector<Value *, 5> Params;
David Neto22f144c2017-06-12 14:26:21 -04002335
SJW2c317da2020-03-23 07:39:13 -05002336 // The pointer.
2337 Params.push_back(CI->getArgOperand(0));
David Neto22f144c2017-06-12 14:26:21 -04002338
SJW2c317da2020-03-23 07:39:13 -05002339 // The memory scope.
2340 Params.push_back(ConstantScopeDevice);
David Neto22f144c2017-06-12 14:26:21 -04002341
SJW2c317da2020-03-23 07:39:13 -05002342 // The memory semantics.
2343 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002344
SJW2c317da2020-03-23 07:39:13 -05002345 if (2 < CI->getNumArgOperands()) {
2346 // The unequal memory semantics.
2347 Params.push_back(ConstantMemorySemantics);
David Neto22f144c2017-06-12 14:26:21 -04002348
SJW2c317da2020-03-23 07:39:13 -05002349 // The value.
2350 Params.push_back(CI->getArgOperand(2));
David Neto22f144c2017-06-12 14:26:21 -04002351
SJW2c317da2020-03-23 07:39:13 -05002352 // The comparator.
2353 Params.push_back(CI->getArgOperand(1));
2354 } else if (1 < CI->getNumArgOperands()) {
2355 // The value.
2356 Params.push_back(CI->getArgOperand(1));
David Neto22f144c2017-06-12 14:26:21 -04002357 }
David Neto22f144c2017-06-12 14:26:21 -04002358
SJW2c317da2020-03-23 07:39:13 -05002359 return clspv::InsertSPIRVOp(CI, Op, {}, CI->getType(), Params);
2360 });
David Neto22f144c2017-06-12 14:26:21 -04002361}
2362
SJW2c317da2020-03-23 07:39:13 -05002363bool ReplaceOpenCLBuiltinPass::replaceAtomics(Function &F,
2364 llvm::AtomicRMWInst::BinOp Op) {
2365 return replaceCallsWithValue(F, [&](CallInst *CI) {
alan-bakerd0eb9052020-07-07 13:12:01 -04002366 auto align = F.getParent()->getDataLayout().getABITypeAlign(
2367 CI->getArgOperand(1)->getType());
SJW2c317da2020-03-23 07:39:13 -05002368 return new AtomicRMWInst(Op, CI->getArgOperand(0), CI->getArgOperand(1),
alan-bakerd0eb9052020-07-07 13:12:01 -04002369 align, AtomicOrdering::SequentiallyConsistent,
SJW2c317da2020-03-23 07:39:13 -05002370 SyncScope::System, CI);
2371 });
2372}
David Neto22f144c2017-06-12 14:26:21 -04002373
SJW2c317da2020-03-23 07:39:13 -05002374bool ReplaceOpenCLBuiltinPass::replaceCross(Function &F) {
2375 Module &M = *F.getParent();
2376 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto22f144c2017-06-12 14:26:21 -04002377 auto IntTy = Type::getInt32Ty(M.getContext());
2378 auto FloatTy = Type::getFloatTy(M.getContext());
2379
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002380 Constant *DownShuffleMask[3] = {ConstantInt::get(IntTy, 0),
2381 ConstantInt::get(IntTy, 1),
2382 ConstantInt::get(IntTy, 2)};
David Neto22f144c2017-06-12 14:26:21 -04002383
2384 Constant *UpShuffleMask[4] = {
2385 ConstantInt::get(IntTy, 0), ConstantInt::get(IntTy, 1),
2386 ConstantInt::get(IntTy, 2), ConstantInt::get(IntTy, 3)};
2387
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002388 Constant *FloatVec[3] = {ConstantFP::get(FloatTy, 0.0f),
2389 UndefValue::get(FloatTy),
2390 UndefValue::get(FloatTy)};
David Neto22f144c2017-06-12 14:26:21 -04002391
Kévin Petite8edce32019-04-10 14:23:32 +01002392 auto Vec4Ty = CI->getArgOperand(0)->getType();
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002393 auto Arg0 =
2394 new ShuffleVectorInst(CI->getArgOperand(0), UndefValue::get(Vec4Ty),
2395 ConstantVector::get(DownShuffleMask), "", CI);
2396 auto Arg1 =
2397 new ShuffleVectorInst(CI->getArgOperand(1), UndefValue::get(Vec4Ty),
2398 ConstantVector::get(DownShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002399 auto Vec3Ty = Arg0->getType();
David Neto22f144c2017-06-12 14:26:21 -04002400
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002401 auto NewFType = FunctionType::get(Vec3Ty, {Vec3Ty, Vec3Ty}, false);
SJW61531372020-06-09 07:31:08 -05002402 auto NewFName = Builtins::GetMangledFunctionName("cross", NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002403
SJW61531372020-06-09 07:31:08 -05002404 auto Cross3Func = M.getOrInsertFunction(NewFName, NewFType);
David Neto22f144c2017-06-12 14:26:21 -04002405
Kévin Petite8edce32019-04-10 14:23:32 +01002406 auto DownResult = CallInst::Create(Cross3Func, {Arg0, Arg1}, "", CI);
David Neto22f144c2017-06-12 14:26:21 -04002407
Diego Novillo3cc8d7a2019-04-10 13:30:34 -04002408 return new ShuffleVectorInst(DownResult, ConstantVector::get(FloatVec),
2409 ConstantVector::get(UpShuffleMask), "", CI);
Kévin Petite8edce32019-04-10 14:23:32 +01002410 });
David Neto22f144c2017-06-12 14:26:21 -04002411}
David Neto62653202017-10-16 19:05:18 -04002412
SJW2c317da2020-03-23 07:39:13 -05002413bool ReplaceOpenCLBuiltinPass::replaceFract(Function &F, int vec_size) {
David Neto62653202017-10-16 19:05:18 -04002414 // OpenCL's float result = fract(float x, float* ptr)
2415 //
2416 // In the LLVM domain:
2417 //
2418 // %floor_result = call spir_func float @floor(float %x)
2419 // store float %floor_result, float * %ptr
2420 // %fract_intermediate = call spir_func float @clspv.fract(float %x)
2421 // %result = call spir_func float
2422 // @fmin(float %fract_intermediate, float 0x1.fffffep-1f)
2423 //
2424 // Becomes in the SPIR-V domain, where translations of floor, fmin,
2425 // and clspv.fract occur in the SPIR-V generator pass:
2426 //
2427 // %glsl_ext = OpExtInstImport "GLSL.std.450"
2428 // %just_under_1 = OpConstant %float 0x1.fffffep-1f
2429 // ...
2430 // %floor_result = OpExtInst %float %glsl_ext Floor %x
2431 // OpStore %ptr %floor_result
2432 // %fract_intermediate = OpExtInst %float %glsl_ext Fract %x
2433 // %fract_result = OpExtInst %float
Marco Antognini55d51862020-07-21 17:50:07 +01002434 // %glsl_ext Nmin %fract_intermediate %just_under_1
David Neto62653202017-10-16 19:05:18 -04002435
David Neto62653202017-10-16 19:05:18 -04002436 using std::string;
2437
2438 // Mapping from the fract builtin to the floor, fmin, and clspv.fract builtins
2439 // we need. The clspv.fract builtin is the same as GLSL.std.450 Fract.
David Neto62653202017-10-16 19:05:18 -04002440
SJW2c317da2020-03-23 07:39:13 -05002441 Module &M = *F.getParent();
2442 return replaceCallsWithValue(F, [&](CallInst *CI) {
David Neto62653202017-10-16 19:05:18 -04002443
SJW2c317da2020-03-23 07:39:13 -05002444 // This is either float or a float vector. All the float-like
2445 // types are this type.
2446 auto result_ty = F.getReturnType();
2447
SJW61531372020-06-09 07:31:08 -05002448 std::string fmin_name = Builtins::GetMangledFunctionName("fmin", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002449 Function *fmin_fn = M.getFunction(fmin_name);
2450 if (!fmin_fn) {
2451 // Make the fmin function.
2452 FunctionType *fn_ty =
2453 FunctionType::get(result_ty, {result_ty, result_ty}, false);
2454 fmin_fn =
2455 cast<Function>(M.getOrInsertFunction(fmin_name, fn_ty).getCallee());
2456 fmin_fn->addFnAttr(Attribute::ReadNone);
2457 fmin_fn->setCallingConv(CallingConv::SPIR_FUNC);
2458 }
2459
SJW61531372020-06-09 07:31:08 -05002460 std::string floor_name =
2461 Builtins::GetMangledFunctionName("floor", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002462 Function *floor_fn = M.getFunction(floor_name);
2463 if (!floor_fn) {
2464 // Make the floor function.
2465 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2466 floor_fn =
2467 cast<Function>(M.getOrInsertFunction(floor_name, fn_ty).getCallee());
2468 floor_fn->addFnAttr(Attribute::ReadNone);
2469 floor_fn->setCallingConv(CallingConv::SPIR_FUNC);
2470 }
2471
SJW61531372020-06-09 07:31:08 -05002472 std::string clspv_fract_name =
2473 Builtins::GetMangledFunctionName("clspv.fract", result_ty);
SJW2c317da2020-03-23 07:39:13 -05002474 Function *clspv_fract_fn = M.getFunction(clspv_fract_name);
2475 if (!clspv_fract_fn) {
2476 // Make the clspv_fract function.
2477 FunctionType *fn_ty = FunctionType::get(result_ty, {result_ty}, false);
2478 clspv_fract_fn = cast<Function>(
2479 M.getOrInsertFunction(clspv_fract_name, fn_ty).getCallee());
2480 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
2481 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
2482 }
2483
2484 // Number of significant significand bits, whether represented or not.
2485 unsigned num_significand_bits;
2486 switch (result_ty->getScalarType()->getTypeID()) {
2487 case Type::HalfTyID:
2488 num_significand_bits = 11;
2489 break;
2490 case Type::FloatTyID:
2491 num_significand_bits = 24;
2492 break;
2493 case Type::DoubleTyID:
2494 num_significand_bits = 53;
2495 break;
2496 default:
2497 llvm_unreachable("Unhandled float type when processing fract builtin");
2498 break;
2499 }
2500 // Beware that the disassembler displays this value as
2501 // OpConstant %float 1
2502 // which is not quite right.
2503 const double kJustUnderOneScalar =
2504 ldexp(double((1 << num_significand_bits) - 1), -num_significand_bits);
2505
2506 Constant *just_under_one =
2507 ConstantFP::get(result_ty->getScalarType(), kJustUnderOneScalar);
2508 if (result_ty->isVectorTy()) {
2509 just_under_one = ConstantVector::getSplat(
alan-baker931253b2020-08-20 17:15:38 -04002510 cast<VectorType>(result_ty)->getElementCount(), just_under_one);
SJW2c317da2020-03-23 07:39:13 -05002511 }
2512
2513 IRBuilder<> Builder(CI);
2514
2515 auto arg = CI->getArgOperand(0);
2516 auto ptr = CI->getArgOperand(1);
2517
2518 // Compute floor result and store it.
2519 auto floor = Builder.CreateCall(floor_fn, {arg});
2520 Builder.CreateStore(floor, ptr);
2521
2522 auto fract_intermediate = Builder.CreateCall(clspv_fract_fn, arg);
2523 auto fract_result =
2524 Builder.CreateCall(fmin_fn, {fract_intermediate, just_under_one});
2525
2526 return fract_result;
2527 });
David Neto62653202017-10-16 19:05:18 -04002528}
alan-bakera52b7312020-10-26 08:58:51 -04002529
Kévin Petit8576f682020-11-02 14:51:32 +00002530bool ReplaceOpenCLBuiltinPass::replaceHadd(Function &F, bool is_signed,
alan-bakerb6da5132020-10-29 15:59:06 -04002531 Instruction::BinaryOps join_opcode) {
Kévin Petit8576f682020-11-02 14:51:32 +00002532 return replaceCallsWithValue(F, [is_signed, join_opcode](CallInst *Call) {
alan-bakerb6da5132020-10-29 15:59:06 -04002533 // a_shr = a >> 1
2534 // b_shr = b >> 1
2535 // add1 = a_shr + b_shr
2536 // join = a |join_opcode| b
2537 // and = join & 1
2538 // add = add1 + and
2539 const auto a = Call->getArgOperand(0);
2540 const auto b = Call->getArgOperand(1);
2541 IRBuilder<> builder(Call);
Kévin Petit8576f682020-11-02 14:51:32 +00002542 Value *a_shift, *b_shift;
2543 if (is_signed) {
2544 a_shift = builder.CreateAShr(a, 1);
2545 b_shift = builder.CreateAShr(b, 1);
2546 } else {
2547 a_shift = builder.CreateLShr(a, 1);
2548 b_shift = builder.CreateLShr(b, 1);
2549 }
alan-bakerb6da5132020-10-29 15:59:06 -04002550 auto add = builder.CreateAdd(a_shift, b_shift);
2551 auto join = BinaryOperator::Create(join_opcode, a, b, "", Call);
2552 auto constant_one = ConstantInt::get(a->getType(), 1);
2553 auto and_bit = builder.CreateAnd(join, constant_one);
2554 return builder.CreateAdd(add, and_bit);
2555 });
2556}
2557
alan-baker3f1bf492020-11-05 09:07:36 -05002558bool ReplaceOpenCLBuiltinPass::replaceAddSubSat(Function &F, bool is_signed,
2559 bool is_add) {
2560 return replaceCallsWithValue(F, [&F, this, is_signed,
2561 is_add](CallInst *Call) {
2562 auto ty = Call->getType();
2563 auto a = Call->getArgOperand(0);
2564 auto b = Call->getArgOperand(1);
2565 IRBuilder<> builder(Call);
alan-bakera52b7312020-10-26 08:58:51 -04002566 if (is_signed) {
2567 unsigned bitwidth = ty->getScalarSizeInBits();
2568 if (bitwidth < 32) {
alan-baker3f1bf492020-11-05 09:07:36 -05002569 unsigned extended_width = bitwidth << 1;
2570 Type *extended_ty =
2571 IntegerType::get(Call->getContext(), extended_width);
2572 Constant *min = ConstantInt::get(
alan-bakera52b7312020-10-26 08:58:51 -04002573 Call->getContext(),
alan-baker3f1bf492020-11-05 09:07:36 -05002574 APInt::getSignedMinValue(bitwidth).sext(extended_width));
2575 Constant *max = ConstantInt::get(
alan-bakera52b7312020-10-26 08:58:51 -04002576 Call->getContext(),
alan-baker3f1bf492020-11-05 09:07:36 -05002577 APInt::getSignedMaxValue(bitwidth).sext(extended_width));
alan-bakera52b7312020-10-26 08:58:51 -04002578 // Don't use the type in GetMangledFunctionName to ensure we get
2579 // signed parameters.
2580 std::string sclamp_name = Builtins::GetMangledFunctionName("clamp");
alan-bakera52b7312020-10-26 08:58:51 -04002581 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
alan-baker3f1bf492020-11-05 09:07:36 -05002582 extended_ty = VectorType::get(extended_ty, vec_ty->getElementCount());
2583 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2584 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2585 unsigned vec_width = vec_ty->getElementCount().getKnownMinValue();
2586 if (extended_width == 32) {
alan-bakera52b7312020-10-26 08:58:51 -04002587 sclamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
alan-bakera52b7312020-10-26 08:58:51 -04002588 } else {
2589 sclamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2590 }
alan-baker3f1bf492020-11-05 09:07:36 -05002591 } else {
2592 if (extended_width == 32) {
2593 sclamp_name += "iii";
2594 } else {
2595 sclamp_name += "sss";
2596 }
alan-bakera52b7312020-10-26 08:58:51 -04002597 }
alan-baker3f1bf492020-11-05 09:07:36 -05002598
2599 auto sext_a = builder.CreateSExt(a, extended_ty);
2600 auto sext_b = builder.CreateSExt(b, extended_ty);
2601 Value *op = nullptr;
2602 // Extended operations won't wrap.
2603 if (is_add)
2604 op = builder.CreateAdd(sext_a, sext_b, "", true, true);
2605 else
2606 op = builder.CreateSub(sext_a, sext_b, "", true, true);
2607 auto clamp_ty = FunctionType::get(
2608 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2609 auto callee = F.getParent()->getOrInsertFunction(sclamp_name, clamp_ty);
2610 auto clamp = builder.CreateCall(callee, {op, min, max});
2611 return builder.CreateTrunc(clamp, ty);
alan-bakera52b7312020-10-26 08:58:51 -04002612 } else {
alan-baker3f1bf492020-11-05 09:07:36 -05002613 // Add:
2614 // c = a + b
alan-bakera52b7312020-10-26 08:58:51 -04002615 // if (b < 0)
2616 // c = c > a ? min : c;
2617 // else
alan-baker3f1bf492020-11-05 09:07:36 -05002618 // c = c < a ? max : c;
alan-bakera52b7312020-10-26 08:58:51 -04002619 //
alan-baker3f1bf492020-11-05 09:07:36 -05002620 // Sub:
2621 // c = a - b;
2622 // if (b < 0)
2623 // c = c < a ? max : c;
2624 // else
2625 // c = c > a ? min : c;
2626 Constant *min = ConstantInt::get(Call->getContext(),
2627 APInt::getSignedMinValue(bitwidth));
2628 Constant *max = ConstantInt::get(Call->getContext(),
2629 APInt::getSignedMaxValue(bitwidth));
alan-bakera52b7312020-10-26 08:58:51 -04002630 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2631 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2632 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2633 }
alan-baker3f1bf492020-11-05 09:07:36 -05002634 Value *op = nullptr;
2635 if (is_add) {
2636 op = builder.CreateAdd(a, b);
2637 } else {
2638 op = builder.CreateSub(a, b);
2639 }
2640 auto b_lt_0 = builder.CreateICmpSLT(b, Constant::getNullValue(ty));
2641 auto op_gt_a = builder.CreateICmpSGT(op, a);
2642 auto op_lt_a = builder.CreateICmpSLT(op, a);
2643 auto neg_cmp = is_add ? op_gt_a : op_lt_a;
2644 auto pos_cmp = is_add ? op_lt_a : op_gt_a;
2645 auto neg_value = is_add ? min : max;
2646 auto pos_value = is_add ? max : min;
2647 auto neg_clamp = builder.CreateSelect(neg_cmp, neg_value, op);
2648 auto pos_clamp = builder.CreateSelect(pos_cmp, pos_value, op);
2649 return builder.CreateSelect(b_lt_0, neg_clamp, pos_clamp);
alan-bakera52b7312020-10-26 08:58:51 -04002650 }
2651 } else {
alan-baker3f1bf492020-11-05 09:07:36 -05002652 // Replace with OpIAddCarry/OpISubBorrow and clamp to max/0 on a
2653 // carr/borrow.
2654 spv::Op op = is_add ? spv::OpIAddCarry : spv::OpISubBorrow;
2655 auto clamp_value =
2656 is_add ? Constant::getAllOnesValue(ty) : Constant::getNullValue(ty);
2657 auto struct_ty = GetPairStruct(ty);
2658 auto call =
2659 InsertSPIRVOp(Call, op, {Attribute::ReadNone}, struct_ty, {a, b});
2660 auto add_sub = builder.CreateExtractValue(call, {0});
2661 auto carry_borrow = builder.CreateExtractValue(call, {1});
2662 auto cmp = builder.CreateICmpEQ(carry_borrow, Constant::getNullValue(ty));
2663 return builder.CreateSelect(cmp, add_sub, clamp_value);
alan-bakera52b7312020-10-26 08:58:51 -04002664 }
alan-bakera52b7312020-10-26 08:58:51 -04002665 });
2666}
alan-baker4986eff2020-10-29 13:38:00 -04002667
2668bool ReplaceOpenCLBuiltinPass::replaceAtomicLoad(Function &F) {
2669 return replaceCallsWithValue(F, [](CallInst *Call) {
2670 auto pointer = Call->getArgOperand(0);
2671 // Clang emits an address space cast to the generic address space. Skip the
2672 // cast and use the input directly.
2673 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2674 pointer = cast->getPointerOperand();
2675 }
2676 Value *order_arg =
2677 Call->getNumArgOperands() > 1 ? Call->getArgOperand(1) : nullptr;
2678 Value *scope_arg =
2679 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2680 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2681 clspv::AddressSpace::Global;
2682 auto order = MemoryOrderSemantics(order_arg, is_global, Call,
2683 spv::MemorySemanticsAcquireMask);
2684 auto scope = MemoryScope(scope_arg, is_global, Call);
2685 return InsertSPIRVOp(Call, spv::OpAtomicLoad, {Attribute::Convergent},
2686 Call->getType(), {pointer, scope, order});
2687 });
2688}
2689
2690bool ReplaceOpenCLBuiltinPass::replaceExplicitAtomics(
2691 Function &F, spv::Op Op, spv::MemorySemanticsMask semantics) {
2692 return replaceCallsWithValue(F, [Op, semantics](CallInst *Call) {
2693 auto pointer = Call->getArgOperand(0);
2694 // Clang emits an address space cast to the generic address space. Skip the
2695 // cast and use the input directly.
2696 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2697 pointer = cast->getPointerOperand();
2698 }
2699 Value *value = Call->getArgOperand(1);
2700 Value *order_arg =
2701 Call->getNumArgOperands() > 2 ? Call->getArgOperand(2) : nullptr;
2702 Value *scope_arg =
2703 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2704 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2705 clspv::AddressSpace::Global;
2706 auto scope = MemoryScope(scope_arg, is_global, Call);
2707 auto order = MemoryOrderSemantics(order_arg, is_global, Call, semantics);
2708 return InsertSPIRVOp(Call, Op, {Attribute::Convergent}, Call->getType(),
2709 {pointer, scope, order, value});
2710 });
2711}
2712
2713bool ReplaceOpenCLBuiltinPass::replaceAtomicCompareExchange(Function &F) {
2714 return replaceCallsWithValue(F, [](CallInst *Call) {
2715 auto pointer = Call->getArgOperand(0);
2716 // Clang emits an address space cast to the generic address space. Skip the
2717 // cast and use the input directly.
2718 if (auto cast = dyn_cast<AddrSpaceCastOperator>(pointer)) {
2719 pointer = cast->getPointerOperand();
2720 }
2721 auto expected = Call->getArgOperand(1);
2722 if (auto cast = dyn_cast<AddrSpaceCastOperator>(expected)) {
2723 expected = cast->getPointerOperand();
2724 }
2725 auto value = Call->getArgOperand(2);
2726 bool is_global = pointer->getType()->getPointerAddressSpace() ==
2727 clspv::AddressSpace::Global;
2728 Value *success_arg =
2729 Call->getNumArgOperands() > 3 ? Call->getArgOperand(3) : nullptr;
2730 Value *failure_arg =
2731 Call->getNumArgOperands() > 4 ? Call->getArgOperand(4) : nullptr;
2732 Value *scope_arg =
2733 Call->getNumArgOperands() > 5 ? Call->getArgOperand(5) : nullptr;
2734 auto scope = MemoryScope(scope_arg, is_global, Call);
2735 auto success = MemoryOrderSemantics(success_arg, is_global, Call,
2736 spv::MemorySemanticsAcquireReleaseMask);
2737 auto failure = MemoryOrderSemantics(failure_arg, is_global, Call,
2738 spv::MemorySemanticsAcquireMask);
2739
2740 // If the value pointed to by |expected| equals the value pointed to by
2741 // |pointer|, |value| is written into |pointer|, otherwise the value in
2742 // |pointer| is written into |expected|. In order to avoid extra stores,
2743 // the basic block with the original atomic is split and the store is
2744 // performed in the |then| block. The condition is the inversion of the
2745 // comparison result.
2746 IRBuilder<> builder(Call);
2747 auto load = builder.CreateLoad(expected);
2748 auto cmp_xchg = InsertSPIRVOp(
2749 Call, spv::OpAtomicCompareExchange, {Attribute::Convergent},
2750 value->getType(), {pointer, scope, success, failure, value, load});
2751 auto cmp = builder.CreateICmpEQ(cmp_xchg, load);
2752 auto not_cmp = builder.CreateNot(cmp);
2753 auto then_branch = SplitBlockAndInsertIfThen(not_cmp, Call, false);
2754 builder.SetInsertPoint(then_branch);
2755 builder.CreateStore(cmp_xchg, expected);
2756 return cmp;
2757 });
2758}
alan-bakercc2bafb2020-11-02 08:30:18 -05002759
alan-baker2cecaa72020-11-05 14:05:20 -05002760bool ReplaceOpenCLBuiltinPass::replaceCountZeroes(Function &F, bool leading) {
alan-bakercc2bafb2020-11-02 08:30:18 -05002761 if (!isa<IntegerType>(F.getReturnType()->getScalarType()))
2762 return false;
2763
2764 auto bitwidth = F.getReturnType()->getScalarSizeInBits();
alan-baker5f2e88e2020-12-07 15:24:04 -05002765 if (bitwidth > 64)
alan-bakercc2bafb2020-11-02 08:30:18 -05002766 return false;
2767
alan-baker5f2e88e2020-12-07 15:24:04 -05002768 return replaceCallsWithValue(F, [&F, leading](CallInst *Call) {
2769 Function *intrinsic = Intrinsic::getDeclaration(
2770 F.getParent(), leading ? Intrinsic::ctlz : Intrinsic::cttz,
2771 Call->getType());
2772 const auto c_false = ConstantInt::getFalse(Call->getContext());
2773 return CallInst::Create(intrinsic->getFunctionType(), intrinsic,
2774 {Call->getArgOperand(0), c_false}, "", Call);
alan-bakercc2bafb2020-11-02 08:30:18 -05002775 });
2776}
alan-baker6b9d1ee2020-11-03 23:11:32 -05002777
2778bool ReplaceOpenCLBuiltinPass::replaceMadSat(Function &F, bool is_signed) {
2779 return replaceCallsWithValue(F, [&F, is_signed, this](CallInst *Call) {
2780 const auto ty = Call->getType();
2781 const auto a = Call->getArgOperand(0);
2782 const auto b = Call->getArgOperand(1);
2783 const auto c = Call->getArgOperand(2);
2784 IRBuilder<> builder(Call);
2785 if (is_signed) {
2786 unsigned bitwidth = Call->getType()->getScalarSizeInBits();
2787 if (bitwidth < 32) {
2788 // mul = sext(a) * sext(b)
2789 // add = mul + sext(c)
2790 // res = clamp(add, MIN, MAX)
2791 unsigned extended_width = bitwidth << 1;
2792 Type *extended_ty = IntegerType::get(F.getContext(), extended_width);
2793 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2794 extended_ty = VectorType::get(extended_ty, vec_ty->getElementCount());
2795 }
2796 auto a_sext = builder.CreateSExt(a, extended_ty);
2797 auto b_sext = builder.CreateSExt(b, extended_ty);
2798 auto c_sext = builder.CreateSExt(c, extended_ty);
2799 // Extended the size so no overflows occur.
2800 auto mul = builder.CreateMul(a_sext, b_sext, "", true, true);
2801 auto add = builder.CreateAdd(mul, c_sext, "", true, true);
2802 auto func_ty = FunctionType::get(
2803 extended_ty, {extended_ty, extended_ty, extended_ty}, false);
2804 // Don't use function type because we need signed parameters.
2805 std::string clamp_name = Builtins::GetMangledFunctionName("clamp");
2806 // The clamp values are the signed min and max of the original bitwidth
2807 // sign extended to the extended bitwidth.
2808 Constant *min = ConstantInt::get(
2809 Call->getContext(),
2810 APInt::getSignedMinValue(bitwidth).sext(extended_width));
2811 Constant *max = ConstantInt::get(
2812 Call->getContext(),
2813 APInt::getSignedMaxValue(bitwidth).sext(extended_width));
2814 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2815 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2816 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2817 unsigned vec_width = vec_ty->getElementCount().getKnownMinValue();
2818 if (extended_width == 32)
2819 clamp_name += "Dv" + std::to_string(vec_width) + "_iS_S_";
2820 else
2821 clamp_name += "Dv" + std::to_string(vec_width) + "_sS_S_";
2822 } else {
2823 if (extended_width == 32)
2824 clamp_name += "iii";
2825 else
2826 clamp_name += "sss";
2827 }
2828 auto callee = F.getParent()->getOrInsertFunction(clamp_name, func_ty);
2829 auto clamp = builder.CreateCall(callee, {add, min, max});
2830 return builder.CreateTrunc(clamp, ty);
2831 } else {
2832 auto struct_ty = GetPairStruct(ty);
2833 // Compute
2834 // {hi, lo} = smul_extended(a, b)
2835 // add = lo + c
2836 auto mul_ext = InsertSPIRVOp(Call, spv::OpSMulExtended,
2837 {Attribute::ReadNone}, struct_ty, {a, b});
2838 auto mul_lo = builder.CreateExtractValue(mul_ext, {0});
2839 auto mul_hi = builder.CreateExtractValue(mul_ext, {1});
2840 auto add = builder.CreateAdd(mul_lo, c);
2841
2842 // Constants for use in the calculation.
2843 Constant *min = ConstantInt::get(Call->getContext(),
2844 APInt::getSignedMinValue(bitwidth));
2845 Constant *max = ConstantInt::get(Call->getContext(),
2846 APInt::getSignedMaxValue(bitwidth));
2847 Constant *max_plus_1 = ConstantInt::get(
2848 Call->getContext(),
2849 APInt::getSignedMaxValue(bitwidth) + APInt(bitwidth, 1));
2850 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2851 min = ConstantVector::getSplat(vec_ty->getElementCount(), min);
2852 max = ConstantVector::getSplat(vec_ty->getElementCount(), max);
2853 max_plus_1 =
2854 ConstantVector::getSplat(vec_ty->getElementCount(), max_plus_1);
2855 }
2856
2857 auto a_xor_b = builder.CreateXor(a, b);
2858 auto same_sign =
2859 builder.CreateICmpSGT(a_xor_b, Constant::getAllOnesValue(ty));
2860 auto different_sign = builder.CreateNot(same_sign);
2861 auto hi_eq_0 = builder.CreateICmpEQ(mul_hi, Constant::getNullValue(ty));
2862 auto hi_ne_0 = builder.CreateNot(hi_eq_0);
2863 auto lo_ge_max = builder.CreateICmpUGE(mul_lo, max);
2864 auto c_gt_0 = builder.CreateICmpSGT(c, Constant::getNullValue(ty));
2865 auto c_lt_0 = builder.CreateICmpSLT(c, Constant::getNullValue(ty));
2866 auto add_gt_max = builder.CreateICmpUGT(add, max);
2867 auto hi_eq_m1 =
2868 builder.CreateICmpEQ(mul_hi, Constant::getAllOnesValue(ty));
2869 auto hi_ne_m1 = builder.CreateNot(hi_eq_m1);
2870 auto lo_le_max_plus_1 = builder.CreateICmpULE(mul_lo, max_plus_1);
2871 auto max_sub_lo = builder.CreateSub(max, mul_lo);
2872 auto c_lt_max_sub_lo = builder.CreateICmpULT(c, max_sub_lo);
2873
2874 // Equivalent to:
2875 // if (((x < 0) == (y < 0)) && mul_hi != 0)
2876 // return MAX
2877 // if (mul_hi == 0 && mul_lo >= MAX && (z > 0 || add > MAX))
2878 // return MAX
2879 // if (((x < 0) != (y < 0)) && mul_hi != -1)
2880 // return MIN
2881 // if (hi == -1 && mul_lo <= (MAX + 1) && (z < 0 || z < (MAX - mul_lo))
2882 // return MIN
2883 // return add
2884 auto max_clamp_1 = builder.CreateAnd(same_sign, hi_ne_0);
2885 auto max_clamp_2 = builder.CreateOr(c_gt_0, add_gt_max);
2886 auto tmp = builder.CreateAnd(hi_eq_0, lo_ge_max);
2887 max_clamp_2 = builder.CreateAnd(tmp, max_clamp_2);
2888 auto max_clamp = builder.CreateOr(max_clamp_1, max_clamp_2);
2889 auto min_clamp_1 = builder.CreateAnd(different_sign, hi_ne_m1);
2890 auto min_clamp_2 = builder.CreateOr(c_lt_0, c_lt_max_sub_lo);
2891 tmp = builder.CreateAnd(hi_eq_m1, lo_le_max_plus_1);
2892 min_clamp_2 = builder.CreateAnd(tmp, min_clamp_2);
2893 auto min_clamp = builder.CreateOr(min_clamp_1, min_clamp_2);
2894 auto sel = builder.CreateSelect(min_clamp, min, add);
2895 return builder.CreateSelect(max_clamp, max, sel);
2896 }
2897 } else {
2898 // {lo, hi} = mul_extended(a, b)
2899 // {add, carry} = add_carry(lo, c)
2900 // cmp = (mul_hi | carry) == 0
2901 // mad_sat = cmp ? add : MAX
2902 auto struct_ty = GetPairStruct(ty);
2903 auto mul_ext = InsertSPIRVOp(Call, spv::OpUMulExtended,
2904 {Attribute::ReadNone}, struct_ty, {a, b});
2905 auto mul_lo = builder.CreateExtractValue(mul_ext, {0});
2906 auto mul_hi = builder.CreateExtractValue(mul_ext, {1});
2907 auto add_carry =
2908 InsertSPIRVOp(Call, spv::OpIAddCarry, {Attribute::ReadNone},
2909 struct_ty, {mul_lo, c});
2910 auto add = builder.CreateExtractValue(add_carry, {0});
2911 auto carry = builder.CreateExtractValue(add_carry, {1});
2912 auto or_value = builder.CreateOr(mul_hi, carry);
2913 auto cmp = builder.CreateICmpEQ(or_value, Constant::getNullValue(ty));
2914 return builder.CreateSelect(cmp, add, Constant::getAllOnesValue(ty));
2915 }
2916 });
2917}
alan-baker15106572020-11-06 15:08:10 -05002918
2919bool ReplaceOpenCLBuiltinPass::replaceOrdered(Function &F, bool is_ordered) {
2920 if (!isa<IntegerType>(F.getReturnType()->getScalarType()))
2921 return false;
2922
2923 if (F.getFunctionType()->getNumParams() != 2)
2924 return false;
2925
2926 if (F.getFunctionType()->getParamType(0) !=
2927 F.getFunctionType()->getParamType(1)) {
2928 return false;
2929 }
2930
2931 switch (F.getFunctionType()->getParamType(0)->getScalarType()->getTypeID()) {
2932 case Type::FloatTyID:
2933 case Type::HalfTyID:
2934 case Type::DoubleTyID:
2935 break;
2936 default:
2937 return false;
2938 }
2939
2940 // Scalar versions all return an int, while vector versions return a vector
2941 // of an equally sized integer types (e.g. short, int or long).
2942 if (isa<VectorType>(F.getReturnType())) {
2943 if (F.getReturnType()->getScalarSizeInBits() !=
2944 F.getFunctionType()->getParamType(0)->getScalarSizeInBits()) {
2945 return false;
2946 }
2947 } else {
2948 if (F.getReturnType()->getScalarSizeInBits() != 32)
2949 return false;
2950 }
2951
2952 return replaceCallsWithValue(F, [is_ordered](CallInst *Call) {
2953 // Replace with a floating point [un]ordered comparison followed by an
2954 // extension.
2955 auto x = Call->getArgOperand(0);
2956 auto y = Call->getArgOperand(1);
2957 IRBuilder<> builder(Call);
2958 Value *tmp = nullptr;
2959 if (is_ordered) {
2960 // This leads to a slight inefficiency in the SPIR-V that is easy for
2961 // drivers to optimize where the SPIR-V for the comparison and the
2962 // extension could be fused to drop the inversion of the OpIsNan.
2963 tmp = builder.CreateFCmpORD(x, y);
2964 } else {
2965 tmp = builder.CreateFCmpUNO(x, y);
2966 }
2967 // OpenCL CTS requires that vector versions use sign extension, but scalar
2968 // versions use zero extension.
2969 if (isa<VectorType>(Call->getType()))
2970 return builder.CreateSExt(tmp, Call->getType());
2971 return builder.CreateZExt(tmp, Call->getType());
2972 });
2973}
alan-baker497920b2020-11-09 16:41:36 -05002974
2975bool ReplaceOpenCLBuiltinPass::replaceIsNormal(Function &F) {
2976 return replaceCallsWithValue(F, [this](CallInst *Call) {
2977 auto ty = Call->getType();
2978 auto x = Call->getArgOperand(0);
2979 unsigned width = x->getType()->getScalarSizeInBits();
2980 Type *int_ty = IntegerType::get(Call->getContext(), width);
2981 uint64_t abs_mask = 0x7fffffff;
2982 uint64_t exp_mask = 0x7f800000;
2983 uint64_t min_mask = 0x00800000;
2984 if (width == 16) {
2985 abs_mask = 0x7fff;
2986 exp_mask = 0x7c00;
2987 min_mask = 0x0400;
2988 } else if (width == 64) {
2989 abs_mask = 0x7fffffffffffffff;
2990 exp_mask = 0x7ff0000000000000;
2991 min_mask = 0x0010000000000000;
2992 }
2993 Constant *abs_const = ConstantInt::get(int_ty, APInt(width, abs_mask));
2994 Constant *exp_const = ConstantInt::get(int_ty, APInt(width, exp_mask));
2995 Constant *min_const = ConstantInt::get(int_ty, APInt(width, min_mask));
2996 if (auto vec_ty = dyn_cast<VectorType>(ty)) {
2997 int_ty = VectorType::get(int_ty, vec_ty->getElementCount());
2998 abs_const =
2999 ConstantVector::getSplat(vec_ty->getElementCount(), abs_const);
3000 exp_const =
3001 ConstantVector::getSplat(vec_ty->getElementCount(), exp_const);
3002 min_const =
3003 ConstantVector::getSplat(vec_ty->getElementCount(), min_const);
3004 }
3005 // Drop the sign bit and then check that the number is between
3006 // (exclusive) the min and max exponent values for the bit width.
3007 IRBuilder<> builder(Call);
3008 auto bitcast = builder.CreateBitCast(x, int_ty);
3009 auto abs = builder.CreateAnd(bitcast, abs_const);
3010 auto lt = builder.CreateICmpULT(abs, exp_const);
3011 auto ge = builder.CreateICmpUGE(abs, min_const);
3012 auto tmp = builder.CreateAnd(lt, ge);
3013 // OpenCL CTS requires that vector versions use sign extension, but scalar
3014 // versions use zero extension.
3015 if (isa<VectorType>(ty))
3016 return builder.CreateSExt(tmp, ty);
3017 return builder.CreateZExt(tmp, ty);
3018 });
3019}
alan-bakere0406e72020-11-10 12:32:04 -05003020
3021bool ReplaceOpenCLBuiltinPass::replaceFDim(Function &F) {
3022 return replaceCallsWithValue(F, [](CallInst *Call) {
3023 const auto x = Call->getArgOperand(0);
3024 const auto y = Call->getArgOperand(1);
3025 IRBuilder<> builder(Call);
3026 auto sub = builder.CreateFSub(x, y);
3027 auto cmp = builder.CreateFCmpUGT(x, y);
3028 return builder.CreateSelect(cmp, sub,
3029 Constant::getNullValue(Call->getType()));
3030 });
3031}
alan-baker3e0de472020-12-08 15:57:17 -05003032
3033bool ReplaceOpenCLBuiltinPass::replaceRound(Function &F) {
3034 return replaceCallsWithValue(F, [&F](CallInst *Call) {
3035 const auto x = Call->getArgOperand(0);
3036 const double c_halfway = 0.5;
3037 auto halfway = ConstantFP::get(Call->getType(), c_halfway);
3038
3039 const auto clspv_fract_name =
3040 Builtins::GetMangledFunctionName("clspv.fract", F.getFunctionType());
3041 Function *clspv_fract_fn = F.getParent()->getFunction(clspv_fract_name);
3042 if (!clspv_fract_fn) {
3043 // Make the clspv_fract function.
3044 clspv_fract_fn = cast<Function>(
3045 F.getParent()
3046 ->getOrInsertFunction(clspv_fract_name, F.getFunctionType())
3047 .getCallee());
3048 clspv_fract_fn->addFnAttr(Attribute::ReadNone);
3049 clspv_fract_fn->setCallingConv(CallingConv::SPIR_FUNC);
3050 }
3051
3052 auto ceil = Intrinsic::getDeclaration(F.getParent(), Intrinsic::ceil,
3053 Call->getType());
3054 auto floor = Intrinsic::getDeclaration(F.getParent(), Intrinsic::floor,
3055 Call->getType());
3056 auto fabs = Intrinsic::getDeclaration(F.getParent(), Intrinsic::fabs,
3057 Call->getType());
3058 auto copysign = Intrinsic::getDeclaration(
3059 F.getParent(), Intrinsic::copysign, {Call->getType(), Call->getType()});
3060
3061 IRBuilder<> builder(Call);
3062
3063 auto fabs_call = builder.CreateCall(F.getFunctionType(), fabs, {x});
3064 auto ceil_call = builder.CreateCall(F.getFunctionType(), ceil, {fabs_call});
3065 auto floor_call =
3066 builder.CreateCall(F.getFunctionType(), floor, {fabs_call});
3067 auto fract_call =
3068 builder.CreateCall(F.getFunctionType(), clspv_fract_fn, {fabs_call});
3069 auto cmp = builder.CreateFCmpOGE(fract_call, halfway);
3070 auto sel = builder.CreateSelect(cmp, ceil_call, floor_call);
3071 return builder.CreateCall(copysign->getFunctionType(), copysign, {sel, x});
3072 });
3073}
3074
3075bool ReplaceOpenCLBuiltinPass::replaceTrigPi(Function &F,
3076 Builtins::BuiltinType type) {
3077 return replaceCallsWithValue(F, [&F, type](CallInst *Call) -> Value * {
3078 const auto x = Call->getArgOperand(0);
3079 const double k_pi = 0x1.921fb54442d18p+1;
3080 Constant *pi = ConstantFP::get(x->getType(), k_pi);
3081
3082 IRBuilder<> builder(Call);
3083 auto mul = builder.CreateFMul(x, pi);
3084 switch (type) {
3085 case Builtins::kSinpi: {
3086 auto func = Intrinsic::getDeclaration(F.getParent(), Intrinsic::sin,
3087 x->getType());
3088 return builder.CreateCall(func->getFunctionType(), func, {mul});
3089 }
3090 case Builtins::kCospi: {
3091 auto func = Intrinsic::getDeclaration(F.getParent(), Intrinsic::cos,
3092 x->getType());
3093 return builder.CreateCall(func->getFunctionType(), func, {mul});
3094 }
3095 case Builtins::kTanpi: {
3096 auto sin = Intrinsic::getDeclaration(F.getParent(), Intrinsic::sin,
3097 x->getType());
3098 auto sin_call = builder.CreateCall(sin->getFunctionType(), sin, {mul});
3099 auto cos = Intrinsic::getDeclaration(F.getParent(), Intrinsic::cos,
3100 x->getType());
3101 auto cos_call = builder.CreateCall(cos->getFunctionType(), cos, {mul});
3102 return builder.CreateFDiv(sin_call, cos_call);
3103 }
3104 default:
3105 llvm_unreachable("unexpected builtin");
3106 break;
3107 }
3108 return nullptr;
3109 });
3110}