| 1 |
//===- SPIRVRegularizeLLVM.cpp - Regularize LLVM for SPIR-V ------- C++ -*-===// |
| 2 |
// |
| 3 |
// The LLVM/SPIRV Translator |
| 4 |
// |
| 5 |
// This file is distributed under the University of Illinois Open Source |
| 6 |
// License. See LICENSE.TXT for details. |
| 7 |
// |
| 8 |
// Copyright (c) 2014 Advanced Micro Devices, Inc. All rights reserved. |
| 9 |
// |
| 10 |
// Permission is hereby granted, free of charge, to any person obtaining a |
| 11 |
// copy of this software and associated documentation files (the "Software"), |
| 12 |
// to deal with the Software without restriction, including without limitation |
| 13 |
// the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| 14 |
// and/or sell copies of the Software, and to permit persons to whom the |
| 15 |
// Software is furnished to do so, subject to the following conditions: |
| 16 |
// |
| 17 |
// Redistributions of source code must retain the above copyright notice, |
| 18 |
// this list of conditions and the following disclaimers. |
| 19 |
// Redistributions in binary form must reproduce the above copyright notice, |
| 20 |
// this list of conditions and the following disclaimers in the documentation |
| 21 |
// and/or other materials provided with the distribution. |
| 22 |
// Neither the names of Advanced Micro Devices, Inc., nor the names of its |
| 23 |
// contributors may be used to endorse or promote products derived from this |
| 24 |
// Software without specific prior written permission. |
| 25 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 26 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 27 |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 28 |
// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 29 |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 30 |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH |
| 31 |
// THE SOFTWARE. |
| 32 |
// |
| 33 |
//===----------------------------------------------------------------------===// |
| 34 |
// |
| 35 |
// This file implements regularization of LLVM module for SPIR-V. |
| 36 |
// |
| 37 |
//===----------------------------------------------------------------------===// |
| 38 |
#define DEBUG_TYPE "spvregular" |
| 39 |
|
| 40 |
#include "SPIRVRegularizeLLVM.h" |
| 41 |
#include "OCLUtil.h" |
| 42 |
#include "SPIRVInternal.h" |
| 43 |
#include "SPIRVMDWalker.h" |
| 44 |
#include "libSPIRV/SPIRVDebug.h" |
| 45 |
|
| 46 |
#include "llvm/ADT/StringExtras.h" // llvm::isDigit |
| 47 |
#include "llvm/CodeGen/IntrinsicLowering.h" |
| 48 |
#include "llvm/Demangle/Demangle.h" |
| 49 |
#include "llvm/IR/IntrinsicInst.h" |
| 50 |
#include "llvm/IR/Module.h" |
| 51 |
#include "llvm/IR/Operator.h" |
| 52 |
#include "llvm/Support/Debug.h" |
| 53 |
#include "llvm/Transforms/Utils/LowerMemIntrinsics.h" // expandMemSetAsLoop() |
| 54 |
|
| 55 |
#include <set> |
| 56 |
#include <vector> |
| 57 |
|
| 58 |
using namespace llvm; |
| 59 |
using namespace SPIRV; |
| 60 |
using namespace OCLUtil; |
| 61 |
|
| 62 |
namespace SPIRV { |
| 63 |
|
| 64 |
static bool SPIRVDbgSaveRegularizedModule = false; |
| 65 |
static std::string RegularizedModuleTmpFile = "regularized.bc"; |
| 66 |
|
| 67 |
char SPIRVRegularizeLLVMLegacy::ID = 0; |
| 68 |
|
| 69 |
bool SPIRVRegularizeLLVMLegacy::runOnModule(Module &Module) { |
| 70 |
return runRegularizeLLVM(Module); |
| 71 |
} |
| 72 |
|
| 73 |
std::string SPIRVRegularizeLLVMBase::lowerLLVMIntrinsicName(IntrinsicInst *II) { |
| 74 |
Function *IntrinsicFunc = II->getCalledFunction(); |
| 75 |
assert(IntrinsicFunc && "Missing function"); |
| 76 |
std::string FuncName = IntrinsicFunc->getName().str(); |
| 77 |
std::replace(FuncName.begin(), FuncName.end(), '.', '_'); |
| 78 |
FuncName = "spirv." + FuncName; |
| 79 |
return FuncName; |
| 80 |
} |
| 81 |
|
| 82 |
void SPIRVRegularizeLLVMBase::lowerIntrinsicToFunction( |
| 83 |
IntrinsicInst *Intrinsic) { |
| 84 |
// For @llvm.memset.* intrinsic cases with constant value and length arguments |
| 85 |
// are emulated via "storing" a constant array to the destination. For other |
| 86 |
// cases we wrap the intrinsic in @spirv.llvm_memset_* function and expand the |
| 87 |
// intrinsic to a loop via expandMemSetAsLoop() from |
| 88 |
// llvm/Transforms/Utils/LowerMemIntrinsics.h |
| 89 |
if (auto *MSI = dyn_cast<MemSetInst>(Intrinsic)) |
| 90 |
if (isa<Constant>(MSI->getValue()) && isa<ConstantInt>(MSI->getLength())) |
| 91 |
return; // To be handled in LLVMToSPIRV::transIntrinsicInst |
| 92 |
|
| 93 |
std::string FuncName = lowerLLVMIntrinsicName(Intrinsic); |
| 94 |
if (Intrinsic->isVolatile()) |
| 95 |
FuncName += ".volatile"; |
| 96 |
// Redirect @llvm.intrinsic.* call to @spirv.llvm_intrinsic_* |
| 97 |
Function *F = M->getFunction(FuncName); |
| 98 |
if (F) { |
| 99 |
// This function is already linked in. |
| 100 |
Intrinsic->setCalledFunction(F); |
| 101 |
return; |
| 102 |
} |
| 103 |
// TODO copy arguments attributes: nocapture writeonly. |
| 104 |
FunctionCallee FC = |
| 105 |
M->getOrInsertFunction(FuncName, Intrinsic->getFunctionType()); |
| 106 |
auto IntrinsicID = Intrinsic->getIntrinsicID(); |
| 107 |
Intrinsic->setCalledFunction(FC); |
| 108 |
|
| 109 |
F = dyn_cast<Function>(FC.getCallee()); |
| 110 |
assert(F && "must be a function!"); |
| 111 |
|
| 112 |
switch (IntrinsicID) { |
| 113 |
case Intrinsic::memset: { |
| 114 |
auto *MSI = static_cast<MemSetInst *>(Intrinsic); |
| 115 |
Argument *Dest = F->getArg(0); |
| 116 |
Argument *Val = F->getArg(1); |
| 117 |
Argument *Len = F->getArg(2); |
| 118 |
Argument *IsVolatile = F->getArg(3); |
| 119 |
Dest->setName("dest"); |
| 120 |
Val->setName("val"); |
| 121 |
Len->setName("len"); |
| 122 |
IsVolatile->setName("isvolatile"); |
| 123 |
IsVolatile->addAttr(Attribute::ImmArg); |
| 124 |
BasicBlock *EntryBB = BasicBlock::Create(M->getContext(), "entry", F); |
| 125 |
IRBuilder<> IRB(EntryBB); |
| 126 |
auto *MemSet = IRB.CreateMemSet(Dest, Val, Len, MSI->getDestAlign(), |
| 127 |
MSI->isVolatile()); |
| 128 |
IRB.CreateRetVoid(); |
| 129 |
expandMemSetAsLoop(cast<MemSetInst>(MemSet)); |
| 130 |
MemSet->eraseFromParent(); |
| 131 |
break; |
| 132 |
} |
| 133 |
case Intrinsic::bswap: { |
| 134 |
BasicBlock *EntryBB = BasicBlock::Create(M->getContext(), "entry", F); |
| 135 |
IRBuilder<> IRB(EntryBB); |
| 136 |
auto *BSwap = IRB.CreateIntrinsic(Intrinsic::bswap, Intrinsic->getType(), |
| 137 |
F->getArg(0)); |
| 138 |
IRB.CreateRet(BSwap); |
| 139 |
IntrinsicLowering IL(M->getDataLayout()); |
| 140 |
IL.LowerIntrinsicCall(BSwap); |
| 141 |
break; |
| 142 |
} |
| 143 |
default: |
| 144 |
break; // do nothing |
| 145 |
} |
| 146 |
|
| 147 |
return; |
| 148 |
} |
| 149 |
|
| 150 |
void SPIRVRegularizeLLVMBase::lowerFunnelShift(IntrinsicInst *FSHIntrinsic) { |
| 151 |
// Get a separate function - otherwise, we'd have to rework the CFG of the |
| 152 |
// current one. Then simply replace the intrinsic uses with a call to the new |
| 153 |
// function. |
| 154 |
// Expected LLVM IR for the function: i* @spirv.llvm_fsh?_i* (i* %a, i* %b, i* |
| 155 |
// %c) |
| 156 |
FunctionType *FSHFuncTy = FSHIntrinsic->getFunctionType(); |
| 157 |
Type *FSHRetTy = FSHFuncTy->getReturnType(); |
| 158 |
const std::string FuncName = lowerLLVMIntrinsicName(FSHIntrinsic); |
| 159 |
Function *FSHFunc = |
| 160 |
getOrCreateFunction(M, FSHRetTy, FSHFuncTy->params(), FuncName); |
| 161 |
|
| 162 |
if (!FSHFunc->empty()) { |
| 163 |
FSHIntrinsic->setCalledFunction(FSHFunc); |
| 164 |
return; |
| 165 |
} |
| 166 |
auto *RotateBB = BasicBlock::Create(M->getContext(), "rotate", FSHFunc); |
| 167 |
IRBuilder<> Builder(RotateBB); |
| 168 |
Type *Ty = FSHFunc->getReturnType(); |
| 169 |
// Build the actual funnel shift rotate logic. |
| 170 |
// In the comments, "int" is used interchangeably with "vector of int |
| 171 |
// elements". |
| 172 |
FixedVectorType *VectorTy = dyn_cast<FixedVectorType>(Ty); |
| 173 |
Type *IntTy = VectorTy ? VectorTy->getElementType() : Ty; |
| 174 |
unsigned BitWidth = IntTy->getIntegerBitWidth(); |
| 175 |
ConstantInt *BitWidthConstant = Builder.getInt({BitWidth, BitWidth}); |
| 176 |
Value *BitWidthForInsts = |
| 177 |
VectorTy ? Builder.CreateVectorSplat(VectorTy->getNumElements(), |
| 178 |
BitWidthConstant) |
| 179 |
: BitWidthConstant; |
| 180 |
auto *RotateModVal = |
| 181 |
Builder.CreateURem(/*Rotate*/ FSHFunc->getArg(2), BitWidthForInsts); |
| 182 |
Value *FirstShift = nullptr, *SecShift = nullptr; |
| 183 |
if (FSHIntrinsic->getIntrinsicID() == Intrinsic::fshr) |
| 184 |
// Shift the less significant number right, the "rotate" number of bits |
| 185 |
// will be 0-filled on the left as a result of this regular shift. |
| 186 |
FirstShift = Builder.CreateLShr(FSHFunc->getArg(1), RotateModVal); |
| 187 |
else |
| 188 |
// Shift the more significant number left, the "rotate" number of bits |
| 189 |
// will be 0-filled on the right as a result of this regular shift. |
| 190 |
FirstShift = Builder.CreateShl(FSHFunc->getArg(0), RotateModVal); |
| 191 |
|
| 192 |
// We want the "rotate" number of the more significant int's LSBs (MSBs) to |
| 193 |
// occupy the leftmost (rightmost) "0 space" left by the previous operation. |
| 194 |
// Therefore, subtract the "rotate" number from the integer bitsize... |
| 195 |
auto *SubRotateVal = Builder.CreateSub(BitWidthForInsts, RotateModVal); |
| 196 |
if (FSHIntrinsic->getIntrinsicID() == Intrinsic::fshr) |
| 197 |
// ...and left-shift the more significant int by this number, zero-filling |
| 198 |
// the LSBs. |
| 199 |
SecShift = Builder.CreateShl(FSHFunc->getArg(0), SubRotateVal); |
| 200 |
else |
| 201 |
// ...and right-shift the less significant int by this number, zero-filling |
| 202 |
// the MSBs. |
| 203 |
SecShift = Builder.CreateLShr(FSHFunc->getArg(1), SubRotateVal); |
| 204 |
|
| 205 |
// A simple binary addition of the shifted ints yields the final result. |
| 206 |
auto *FunnelShiftRes = Builder.CreateOr(FirstShift, SecShift); |
| 207 |
Builder.CreateRet(FunnelShiftRes); |
| 208 |
|
| 209 |
FSHIntrinsic->setCalledFunction(FSHFunc); |
| 210 |
} |
| 211 |
|
| 212 |
void SPIRVRegularizeLLVMBase::buildUMulWithOverflowFunc(Function *UMulFunc) { |
| 213 |
if (!UMulFunc->empty()) |
| 214 |
return; |
| 215 |
|
| 216 |
BasicBlock *EntryBB = BasicBlock::Create(M->getContext(), "entry", UMulFunc); |
| 217 |
IRBuilder<> Builder(EntryBB); |
| 218 |
// Build the actual unsigned multiplication logic with the overflow |
| 219 |
// indication. |
| 220 |
auto *FirstArg = UMulFunc->getArg(0); |
| 221 |
auto *SecondArg = UMulFunc->getArg(1); |
| 222 |
|
| 223 |
// Do unsigned multiplication Mul = A * B. |
| 224 |
// Then check if unsigned division Div = Mul / A is not equal to B. |
| 225 |
// If so, then overflow has happened. |
| 226 |
auto *Mul = Builder.CreateNUWMul(FirstArg, SecondArg); |
| 227 |
auto *Div = Builder.CreateUDiv(Mul, FirstArg); |
| 228 |
auto *Overflow = Builder.CreateICmpNE(FirstArg, Div); |
| 229 |
|
| 230 |
// umul.with.overflow intrinsic return a structure, where the first element |
| 231 |
// is the multiplication result, and the second is an overflow bit. |
| 232 |
auto *StructTy = UMulFunc->getReturnType(); |
| 233 |
auto *Agg = Builder.CreateInsertValue(UndefValue::get(StructTy), Mul, {0}); |
| 234 |
auto *Res = Builder.CreateInsertValue(Agg, Overflow, {1}); |
| 235 |
Builder.CreateRet(Res); |
| 236 |
} |
| 237 |
|
| 238 |
void SPIRVRegularizeLLVMBase::lowerUMulWithOverflow( |
| 239 |
IntrinsicInst *UMulIntrinsic) { |
| 240 |
// Get a separate function - otherwise, we'd have to rework the CFG of the |
| 241 |
// current one. Then simply replace the intrinsic uses with a call to the new |
| 242 |
// function. |
| 243 |
FunctionType *UMulFuncTy = UMulIntrinsic->getFunctionType(); |
| 244 |
Type *FSHLRetTy = UMulFuncTy->getReturnType(); |
| 245 |
const std::string FuncName = lowerLLVMIntrinsicName(UMulIntrinsic); |
| 246 |
Function *UMulFunc = |
| 247 |
getOrCreateFunction(M, FSHLRetTy, UMulFuncTy->params(), FuncName); |
| 248 |
buildUMulWithOverflowFunc(UMulFunc); |
| 249 |
UMulIntrinsic->setCalledFunction(UMulFunc); |
| 250 |
} |
| 251 |
|
| 252 |
void SPIRVRegularizeLLVMBase::expandVEDWithSYCLTypeSRetArg(Function *F) { |
| 253 |
auto Attrs = F->getAttributes(); |
| 254 |
StructType *SRetTy = cast<StructType>(Attrs.getParamStructRetType(0)); |
| 255 |
Attrs = Attrs.removeParamAttribute(F->getContext(), 0, Attribute::StructRet); |
| 256 |
std::string Name = F->getName().str(); |
| 257 |
CallInst *OldCall = nullptr; |
| 258 |
mutateFunction( |
| 259 |
F, |
| 260 |
[=, &OldCall](CallInst *CI, std::vector<Value *> &Args, Type *&RetTy) { |
| 261 |
Args.erase(Args.begin()); |
| 262 |
RetTy = SRetTy->getElementType(0); |
| 263 |
OldCall = CI; |
| 264 |
return Name; |
| 265 |
}, |
| 266 |
[=, &OldCall](CallInst *NewCI) { |
| 267 |
IRBuilder<> Builder(OldCall); |
| 268 |
Value *Target = |
| 269 |
Builder.CreateStructGEP(SRetTy, OldCall->getOperand(0), 0); |
| 270 |
return Builder.CreateStore(NewCI, Target); |
| 271 |
}, |
| 272 |
nullptr, &Attrs, true); |
| 273 |
} |
| 274 |
|
| 275 |
void SPIRVRegularizeLLVMBase::expandVIDWithSYCLTypeByValComp(Function *F) { |
| 276 |
auto Attrs = F->getAttributes(); |
| 277 |
auto *CompPtrTy = cast<StructType>(Attrs.getParamByValType(1)); |
| 278 |
Attrs = Attrs.removeParamAttribute(F->getContext(), 1, Attribute::ByVal); |
| 279 |
std::string Name = F->getName().str(); |
| 280 |
mutateFunction( |
| 281 |
F, |
| 282 |
[=](CallInst *CI, std::vector<Value *> &Args) { |
| 283 |
Type *HalfTy = CompPtrTy->getElementType(0); |
| 284 |
IRBuilder<> Builder(CI); |
| 285 |
auto *Target = Builder.CreateStructGEP(CompPtrTy, CI->getOperand(1), 0); |
| 286 |
Args[1] = Builder.CreateLoad(HalfTy, Target); |
| 287 |
return Name; |
| 288 |
}, |
| 289 |
nullptr, &Attrs, true); |
| 290 |
} |
| 291 |
|
| 292 |
void SPIRVRegularizeLLVMBase::expandSYCLTypeUsing(Module *M) { |
| 293 |
std::vector<Function *> ToExpandVEDWithSYCLTypeSRetArg; |
| 294 |
std::vector<Function *> ToExpandVIDWithSYCLTypeByValComp; |
| 295 |
|
| 296 |
for (auto &F : *M) { |
| 297 |
if (F.getName().startswith("_Z28__spirv_VectorExtractDynamic") && |
| 298 |
F.hasStructRetAttr()) { |
| 299 |
auto *SRetTy = F.getParamStructRetType(0); |
| 300 |
if (isSYCLHalfType(SRetTy) || isSYCLBfloat16Type(SRetTy)) |
| 301 |
ToExpandVEDWithSYCLTypeSRetArg.push_back(&F); |
| 302 |
else |
| 303 |
llvm_unreachable("The return type of the VectorExtractDynamic " |
| 304 |
"instruction cannot be a structure other than SYCL " |
| 305 |
"half."); |
| 306 |
} |
| 307 |
if (F.getName().startswith("_Z27__spirv_VectorInsertDynamic") && |
| 308 |
F.getArg(1)->getType()->isPointerTy()) { |
| 309 |
auto *ET = F.getParamByValType(1); |
| 310 |
if (isSYCLHalfType(ET) || isSYCLBfloat16Type(ET)) |
| 311 |
ToExpandVIDWithSYCLTypeByValComp.push_back(&F); |
| 312 |
else |
| 313 |
llvm_unreachable("The component argument type of an " |
| 314 |
"VectorInsertDynamic instruction can't be a " |
| 315 |
"structure other than SYCL half."); |
| 316 |
} |
| 317 |
} |
| 318 |
|
| 319 |
for (auto *F : ToExpandVEDWithSYCLTypeSRetArg) |
| 320 |
expandVEDWithSYCLTypeSRetArg(F); |
| 321 |
for (auto *F : ToExpandVIDWithSYCLTypeByValComp) |
| 322 |
expandVIDWithSYCLTypeByValComp(F); |
| 323 |
} |
| 324 |
|
| 325 |
Value *SPIRVRegularizeLLVMBase::extendBitInstBoolArg(Instruction *II) { |
| 326 |
IRBuilder<> Builder(II); |
| 327 |
auto *ArgTy = II->getOperand(0)->getType(); |
| 328 |
Type *NewArgType = nullptr; |
| 329 |
if (ArgTy->isIntegerTy()) { |
| 330 |
NewArgType = Builder.getInt32Ty(); |
| 331 |
} else if (ArgTy->isVectorTy() && |
| 332 |
cast<VectorType>(ArgTy)->getElementType()->isIntegerTy()) { |
| 333 |
unsigned NumElements = cast<FixedVectorType>(ArgTy)->getNumElements(); |
| 334 |
NewArgType = VectorType::get(Builder.getInt32Ty(), NumElements, false); |
| 335 |
} else { |
| 336 |
llvm_unreachable("Unexpected type"); |
| 337 |
} |
| 338 |
auto *NewBase = Builder.CreateZExt(II->getOperand(0), NewArgType); |
| 339 |
auto *NewShift = Builder.CreateZExt(II->getOperand(1), NewArgType); |
| 340 |
switch (II->getOpcode()) { |
| 341 |
case Instruction::LShr: |
| 342 |
return Builder.CreateLShr(NewBase, NewShift); |
| 343 |
case Instruction::Shl: |
| 344 |
return Builder.CreateShl(NewBase, NewShift); |
| 345 |
default: |
| 346 |
return II; |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
bool SPIRVRegularizeLLVMBase::runRegularizeLLVM(Module &Module) { |
| 351 |
M = &Module; |
| 352 |
Ctx = &M->getContext(); |
| 353 |
|
| 354 |
LLVM_DEBUG(dbgs() << "Enter SPIRVRegularizeLLVM:\n"); |
| 355 |
regularize(); |
| 356 |
LLVM_DEBUG(dbgs() << "After SPIRVRegularizeLLVM:\n" << *M); |
| 357 |
|
| 358 |
verifyRegularizationPass(*M, "SPIRVRegularizeLLVM"); |
| 359 |
|
| 360 |
return true; |
| 361 |
} |
| 362 |
|
| 363 |
/// Remove entities not representable by SPIR-V |
| 364 |
bool SPIRVRegularizeLLVMBase::regularize() { |
| 365 |
eraseUselessFunctions(M); |
| 366 |
addKernelEntryPoint(M); |
| 367 |
expandSYCLTypeUsing(M); |
| 368 |
|
| 369 |
for (auto I = M->begin(), E = M->end(); I != E;) { |
| 370 |
Function *F = &(*I++); |
| 371 |
if (F->isDeclaration() && F->use_empty()) { |
| 372 |
F->eraseFromParent(); |
| 373 |
continue; |
| 374 |
} |
| 375 |
|
| 376 |
std::vector<Instruction *> ToErase; |
| 377 |
for (BasicBlock &BB : *F) { |
| 378 |
for (Instruction &II : BB) { |
| 379 |
if (auto Call = dyn_cast<CallInst>(&II)) { |
| 380 |
Call->setTailCall(false); |
| 381 |
Function *CF = Call->getCalledFunction(); |
| 382 |
if (CF && CF->isIntrinsic()) { |
| 383 |
removeFnAttr(Call, Attribute::NoUnwind); |
| 384 |
auto *II = cast<IntrinsicInst>(Call); |
| 385 |
if (II->getIntrinsicID() == Intrinsic::memset || |
| 386 |
II->getIntrinsicID() == Intrinsic::bswap) |
| 387 |
lowerIntrinsicToFunction(II); |
| 388 |
else if (II->getIntrinsicID() == Intrinsic::fshl || |
| 389 |
II->getIntrinsicID() == Intrinsic::fshr) |
| 390 |
lowerFunnelShift(II); |
| 391 |
else if (II->getIntrinsicID() == Intrinsic::umul_with_overflow) |
| 392 |
lowerUMulWithOverflow(II); |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
// Translator treats i1 as boolean, but bit instructions take |
| 397 |
// a scalar/vector integers, so we have to extend such arguments |
| 398 |
if (II.isLogicalShift() && |
| 399 |
II.getOperand(0)->getType()->isIntOrIntVectorTy(1)) { |
| 400 |
auto *NewInst = extendBitInstBoolArg(&II); |
| 401 |
for (auto *U : II.users()) { |
| 402 |
if (cast<Instruction>(U)->getOpcode() == Instruction::ZExt) { |
| 403 |
U->dropAllReferences(); |
| 404 |
U->replaceAllUsesWith(NewInst); |
| 405 |
ToErase.push_back(cast<Instruction>(U)); |
| 406 |
} |
| 407 |
} |
| 408 |
ToErase.push_back(&II); |
| 409 |
} |
| 410 |
|
| 411 |
// Remove optimization info not supported by SPIRV |
| 412 |
if (auto BO = dyn_cast<BinaryOperator>(&II)) { |
| 413 |
if (isa<PossiblyExactOperator>(BO) && BO->isExact()) |
| 414 |
BO->setIsExact(false); |
| 415 |
} |
| 416 |
|
| 417 |
// FIXME: This is not valid handling for freeze instruction |
| 418 |
if (auto *FI = dyn_cast<FreezeInst>(&II)) { |
| 419 |
auto *V = FI->getOperand(0); |
| 420 |
if (isa<UndefValue>(V)) |
| 421 |
V = Constant::getNullValue(V->getType()); |
| 422 |
FI->replaceAllUsesWith(V); |
| 423 |
FI->dropAllReferences(); |
| 424 |
ToErase.push_back(FI); |
| 425 |
} |
| 426 |
|
| 427 |
// Remove metadata not supported by SPIRV |
| 428 |
static const char *MDs[] = { |
| 429 |
"fpmath", |
| 430 |
"tbaa", |
| 431 |
"range", |
| 432 |
}; |
| 433 |
for (auto &MDName : MDs) { |
| 434 |
if (II.getMetadata(MDName)) { |
| 435 |
II.setMetadata(MDName, nullptr); |
| 436 |
} |
| 437 |
} |
| 438 |
// Add an additional bitcast in case address space cast also changes |
| 439 |
// pointer element type. |
| 440 |
if (auto *ASCast = dyn_cast<AddrSpaceCastInst>(&II)) { |
| 441 |
Type *DestTy = ASCast->getDestTy(); |
| 442 |
Type *SrcTy = ASCast->getSrcTy(); |
| 443 |
if (!II.getContext().supportsTypedPointers()) |
| 444 |
continue; |
| 445 |
if (DestTy->getScalarType()->getNonOpaquePointerElementType() != |
| 446 |
SrcTy->getScalarType()->getNonOpaquePointerElementType()) { |
| 447 |
Type *InterTy = PointerType::getWithSamePointeeType( |
| 448 |
cast<PointerType>(DestTy->getScalarType()), |
| 449 |
cast<PointerType>(SrcTy->getScalarType()) |
| 450 |
->getPointerAddressSpace()); |
| 451 |
if (DestTy->isVectorTy()) |
| 452 |
InterTy = VectorType::get( |
| 453 |
InterTy, cast<VectorType>(DestTy)->getElementCount()); |
| 454 |
BitCastInst *NewBCast = new BitCastInst( |
| 455 |
ASCast->getPointerOperand(), InterTy, /*NameStr=*/"", ASCast); |
| 456 |
AddrSpaceCastInst *NewASCast = |
| 457 |
new AddrSpaceCastInst(NewBCast, DestTy, /*NameStr=*/"", ASCast); |
| 458 |
ToErase.push_back(ASCast); |
| 459 |
ASCast->dropAllReferences(); |
| 460 |
ASCast->replaceAllUsesWith(NewASCast); |
| 461 |
} |
| 462 |
} |
| 463 |
if (auto Cmpxchg = dyn_cast<AtomicCmpXchgInst>(&II)) { |
| 464 |
// Transform: |
| 465 |
// %1 = cmpxchg i32* %ptr, i32 %comparator, i32 %0 seq_cst acquire |
| 466 |
// To: |
| 467 |
// %cmpxchg.res = call spir_func |
| 468 |
// i32 @_Z29__spirv_AtomicCompareExchangePiiiiii( |
| 469 |
// i32* %ptr, i32 1, i32 16, i32 2, i32 %0, i32 %comparator) |
| 470 |
// %cmpxchg.success = icmp eq i32 %cmpxchg.res, %comparator |
| 471 |
// %1 = insertvalue { i32, i1 } undef, i32 %cmpxchg.res, 0 |
| 472 |
// %2 = insertvalue { i32, i1 } %1, i1 %cmpxchg.success, 1 |
| 473 |
|
| 474 |
// To get memory scope argument we might use Cmpxchg->getSyncScopeID() |
| 475 |
// but LLVM's cmpxchg instruction is not aware of OpenCL(or SPIR-V) |
| 476 |
// memory scope enumeration. And assuming the produced SPIR-V module |
| 477 |
// will be consumed in an OpenCL environment, we can use the same |
| 478 |
// memory scope as OpenCL atomic functions that do not have |
| 479 |
// memory_scope argument, i.e. memory_scope_device. See the OpenCL C |
| 480 |
// specification p6.13.11. Atomic Functions |
| 481 |
|
| 482 |
// cmpxchg LLVM instruction returns a pair {i32, i1}: the original |
| 483 |
// value and a flag indicating success (true) or failure (false). |
| 484 |
// OpAtomicCompareExchange SPIR-V instruction returns only the |
| 485 |
// original value. To keep the return type({i32, i1}) we construct |
| 486 |
// a composite. The first element of the composite holds result of |
| 487 |
// OpAtomicCompareExchange, i.e. the original value. The second |
| 488 |
// element holds result of comparison of the returned value and the |
| 489 |
// comparator, which matches with semantics of the flag returned by |
| 490 |
// cmpxchg. |
| 491 |
Value *Ptr = Cmpxchg->getPointerOperand(); |
| 492 |
Value *MemoryScope = getInt32(M, spv::ScopeDevice); |
| 493 |
auto SuccessOrder = static_cast<OCLMemOrderKind>( |
| 494 |
llvm::toCABI(Cmpxchg->getSuccessOrdering())); |
| 495 |
auto FailureOrder = static_cast<OCLMemOrderKind>( |
| 496 |
llvm::toCABI(Cmpxchg->getFailureOrdering())); |
| 497 |
Value *EqualSem = getInt32(M, OCLMemOrderMap::map(SuccessOrder)); |
| 498 |
Value *UnequalSem = getInt32(M, OCLMemOrderMap::map(FailureOrder)); |
| 499 |
Value *Val = Cmpxchg->getNewValOperand(); |
| 500 |
Value *Comparator = Cmpxchg->getCompareOperand(); |
| 501 |
|
| 502 |
Type *MemType = Cmpxchg->getCompareOperand()->getType(); |
| 503 |
|
| 504 |
llvm::Value *Args[] = {Ptr, MemoryScope, EqualSem, |
| 505 |
UnequalSem, Val, Comparator}; |
| 506 |
auto *Res = |
| 507 |
addCallInstSPIRV(M, "__spirv_AtomicCompareExchange", MemType, |
| 508 |
Args, nullptr, {MemType}, &II, "cmpxchg.res"); |
| 509 |
IRBuilder<> Builder(Cmpxchg); |
| 510 |
auto *Cmp = Builder.CreateICmpEQ(Res, Comparator, "cmpxchg.success"); |
| 511 |
auto *V1 = Builder.CreateInsertValue( |
| 512 |
UndefValue::get(Cmpxchg->getType()), Res, 0); |
| 513 |
auto *V2 = Builder.CreateInsertValue(V1, Cmp, 1, Cmpxchg->getName()); |
| 514 |
Cmpxchg->replaceAllUsesWith(V2); |
| 515 |
ToErase.push_back(Cmpxchg); |
| 516 |
} |
| 517 |
} |
| 518 |
} |
| 519 |
for (Instruction *V : ToErase) { |
| 520 |
assert(V->user_empty()); |
| 521 |
V->eraseFromParent(); |
| 522 |
} |
| 523 |
} |
| 524 |
|
| 525 |
if (SPIRVDbgSaveRegularizedModule) |
| 526 |
saveLLVMModule(M, RegularizedModuleTmpFile); |
| 527 |
return true; |
| 528 |
} |
| 529 |
|
| 530 |
void SPIRVRegularizeLLVMBase::addKernelEntryPoint(Module *M) { |
| 531 |
std::vector<Function *> Work; |
| 532 |
|
| 533 |
// Get a list of all functions that have SPIR kernel calling conv |
| 534 |
for (auto &F : *M) { |
| 535 |
if (F.getCallingConv() == CallingConv::SPIR_KERNEL) |
| 536 |
Work.push_back(&F); |
| 537 |
} |
| 538 |
for (auto &F : Work) { |
| 539 |
// for declarations just make them into SPIR functions. |
| 540 |
F->setCallingConv(CallingConv::SPIR_FUNC); |
| 541 |
if (F->isDeclaration()) |
| 542 |
continue; |
| 543 |
|
| 544 |
// Otherwise add a wrapper around the function to act as an entry point. |
| 545 |
FunctionType *FType = F->getFunctionType(); |
| 546 |
std::string WrapName = |
| 547 |
kSPIRVName::EntrypointPrefix + static_cast<std::string>(F->getName()); |
| 548 |
Function *WrapFn = |
| 549 |
getOrCreateFunction(M, F->getReturnType(), FType->params(), WrapName); |
| 550 |
|
| 551 |
auto *CallBB = BasicBlock::Create(M->getContext(), "", WrapFn); |
| 552 |
IRBuilder<> Builder(CallBB); |
| 553 |
|
| 554 |
Function::arg_iterator DestI = WrapFn->arg_begin(); |
| 555 |
for (const Argument &I : F->args()) { |
| 556 |
DestI->setName(I.getName()); |
| 557 |
DestI++; |
| 558 |
} |
| 559 |
SmallVector<Value *, 1> Args; |
| 560 |
for (Argument &I : WrapFn->args()) { |
| 561 |
Args.emplace_back(&I); |
| 562 |
} |
| 563 |
auto *CI = CallInst::Create(F, ArrayRef<Value *>(Args), "", CallBB); |
| 564 |
CI->setCallingConv(F->getCallingConv()); |
| 565 |
CI->setAttributes(F->getAttributes()); |
| 566 |
|
| 567 |
// copy over all the metadata (should it be removed from F?) |
| 568 |
SmallVector<std::pair<unsigned, MDNode *>> MDs; |
| 569 |
F->getAllMetadata(MDs); |
| 570 |
WrapFn->setAttributes(F->getAttributes()); |
| 571 |
for (auto MD = MDs.begin(), End = MDs.end(); MD != End; ++MD) { |
| 572 |
WrapFn->addMetadata(MD->first, *MD->second); |
| 573 |
} |
| 574 |
WrapFn->setCallingConv(CallingConv::SPIR_KERNEL); |
| 575 |
WrapFn->setLinkage(llvm::GlobalValue::InternalLinkage); |
| 576 |
|
| 577 |
Builder.CreateRet(F->getReturnType()->isVoidTy() ? nullptr : CI); |
| 578 |
|
| 579 |
// Have to find the spir-v metadata for execution mode and transfer it to |
| 580 |
// the wrapper. |
| 581 |
if (auto NMD = SPIRVMDWalker(*M).getNamedMD(kSPIRVMD::ExecutionMode)) { |
| 582 |
while (!NMD.atEnd()) { |
| 583 |
Function *MDF = nullptr; |
| 584 |
auto N = NMD.nextOp(); /* execution mode MDNode */ |
| 585 |
N.get(MDF); |
| 586 |
if (MDF == F) |
| 587 |
N.M->replaceOperandWith(0, ValueAsMetadata::get(WrapFn)); |
| 588 |
} |
| 589 |
} |
| 590 |
} |
| 591 |
} |
| 592 |
|
| 593 |
} // namespace SPIRV |
| 594 |
|
| 595 |
INITIALIZE_PASS(SPIRVRegularizeLLVMLegacy, "spvregular", |
| 596 |
"Regularize LLVM for SPIR-V", false, false) |
| 597 |
|
| 598 |
ModulePass *llvm::createSPIRVRegularizeLLVMLegacy() { |
| 599 |
return new SPIRVRegularizeLLVMLegacy(); |
| 600 |
} |