1 /****************************************************************************
2 * Copyright (C) 2014-2015 Intel Corporation. All Rights Reserved.
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23 * @file builder_misc.cpp
25 * @brief Implementation for miscellaneous builder functions
29 ******************************************************************************/
31 #include "common/rdtsc_buckets.h"
33 #include "llvm/Support/DynamicLibrary.h"
35 void __cdecl
CallPrint(const char* fmt
, ...);
37 //////////////////////////////////////////////////////////////////////////
38 /// @brief Convert an IEEE 754 32-bit single precision float to an
39 /// 16 bit float with 5 exponent bits and a variable
40 /// number of mantissa bits.
41 /// @param val - 32-bit float
42 /// @todo Maybe move this outside of this file into a header?
43 static uint16_t Convert32To16Float(float val
)
45 uint32_t sign
, exp
, mant
;
48 // Extract the sign, exponent, and mantissa
49 uint32_t uf
= *(uint32_t*)&val
;
50 sign
= (uf
& 0x80000000) >> 31;
51 exp
= (uf
& 0x7F800000) >> 23;
52 mant
= uf
& 0x007FFFFF;
54 // Check for out of range
59 sign
= 1; // set the sign bit for NANs
61 else if (std::isinf(val
))
66 else if (exp
> (0x70 + 0x1E)) // Too big to represent -> max representable value
71 else if ((exp
<= 0x70) && (exp
>= 0x66)) // It's a denorm
74 for (; exp
<= 0x70; mant
>>= 1, exp
++)
79 else if (exp
< 0x66) // Too small to represent -> Zero
86 // Saves bits that will be shifted off for rounding
87 roundBits
= mant
& 0x1FFFu
;
88 // convert exponent and mantissa to 16 bit format
92 // Essentially RTZ, but round up if off by only 1 lsb
93 if (roundBits
== 0x1FFFu
)
97 if ((mant
& 0xC00u
) != 0)
99 // make sure only the needed bits are used
104 uint32_t tmpVal
= (sign
<< 15) | (exp
<< 10) | mant
;
105 return (uint16_t)tmpVal
;
108 //////////////////////////////////////////////////////////////////////////
109 /// @brief Convert an IEEE 754 16-bit float to an 32-bit single precision
111 /// @param val - 16-bit float
112 /// @todo Maybe move this outside of this file into a header?
113 static float ConvertSmallFloatTo32(UINT val
)
116 if ((val
& 0x7fff) == 0)
118 result
= ((uint32_t)(val
& 0x8000)) << 16;
120 else if ((val
& 0x7c00) == 0x7c00)
122 result
= ((val
& 0x3ff) == 0) ? 0x7f800000 : 0x7fc00000;
123 result
|= ((uint32_t)val
& 0x8000) << 16;
127 uint32_t sign
= (val
& 0x8000) << 16;
128 uint32_t mant
= (val
& 0x3ff) << 13;
129 uint32_t exp
= (val
>> 10) & 0x1f;
130 if ((exp
== 0) && (mant
!= 0)) // Adjust exponent and mantissa for denormals
133 while (mant
< (0x400 << 13))
138 mant
&= (0x3ff << 13);
140 exp
= ((exp
- 15 + 127) & 0xff) << 23;
141 result
= sign
| exp
| mant
;
144 return *(float*)&result
;
147 Constant
*Builder::C(bool i
)
149 return ConstantInt::get(IRB()->getInt1Ty(), (i
? 1 : 0));
152 Constant
*Builder::C(char i
)
154 return ConstantInt::get(IRB()->getInt8Ty(), i
);
157 Constant
*Builder::C(uint8_t i
)
159 return ConstantInt::get(IRB()->getInt8Ty(), i
);
162 Constant
*Builder::C(int i
)
164 return ConstantInt::get(IRB()->getInt32Ty(), i
);
167 Constant
*Builder::C(int64_t i
)
169 return ConstantInt::get(IRB()->getInt64Ty(), i
);
172 Constant
*Builder::C(uint16_t i
)
174 return ConstantInt::get(mInt16Ty
,i
);
177 Constant
*Builder::C(uint32_t i
)
179 return ConstantInt::get(IRB()->getInt32Ty(), i
);
182 Constant
*Builder::C(float i
)
184 return ConstantFP::get(IRB()->getFloatTy(), i
);
187 Constant
*Builder::PRED(bool pred
)
189 return ConstantInt::get(IRB()->getInt1Ty(), (pred
? 1 : 0));
192 Value
*Builder::VIMMED1(int i
)
194 return ConstantVector::getSplat(mVWidth
, cast
<ConstantInt
>(C(i
)));
197 Value
*Builder::VIMMED1(uint32_t i
)
199 return ConstantVector::getSplat(mVWidth
, cast
<ConstantInt
>(C(i
)));
202 Value
*Builder::VIMMED1(float i
)
204 return ConstantVector::getSplat(mVWidth
, cast
<ConstantFP
>(C(i
)));
207 Value
*Builder::VIMMED1(bool i
)
209 return ConstantVector::getSplat(mVWidth
, cast
<ConstantInt
>(C(i
)));
212 Value
*Builder::VUNDEF_IPTR()
214 return UndefValue::get(VectorType::get(mInt32PtrTy
,mVWidth
));
217 Value
*Builder::VUNDEF_I()
219 return UndefValue::get(VectorType::get(mInt32Ty
, mVWidth
));
222 Value
*Builder::VUNDEF(Type
*ty
, uint32_t size
)
224 return UndefValue::get(VectorType::get(ty
, size
));
227 Value
*Builder::VUNDEF_F()
229 return UndefValue::get(VectorType::get(mFP32Ty
, mVWidth
));
232 Value
*Builder::VUNDEF(Type
* t
)
234 return UndefValue::get(VectorType::get(t
, mVWidth
));
237 #if HAVE_LLVM == 0x306
238 Value
*Builder::VINSERT(Value
*vec
, Value
*val
, uint64_t index
)
240 return VINSERT(vec
, val
, C((int64_t)index
));
244 Value
*Builder::VBROADCAST(Value
*src
)
246 // check if src is already a vector
247 if (src
->getType()->isVectorTy())
252 return VECTOR_SPLAT(mVWidth
, src
);
255 uint32_t Builder::IMMED(Value
* v
)
257 SWR_ASSERT(isa
<ConstantInt
>(v
));
258 ConstantInt
*pValConst
= cast
<ConstantInt
>(v
);
259 return pValConst
->getZExtValue();
262 int32_t Builder::S_IMMED(Value
* v
)
264 SWR_ASSERT(isa
<ConstantInt
>(v
));
265 ConstantInt
*pValConst
= cast
<ConstantInt
>(v
);
266 return pValConst
->getSExtValue();
269 Value
*Builder::GEP(Value
* ptr
, const std::initializer_list
<Value
*> &indexList
)
271 std::vector
<Value
*> indices
;
272 for (auto i
: indexList
)
273 indices
.push_back(i
);
274 return GEPA(ptr
, indices
);
277 Value
*Builder::GEP(Value
* ptr
, const std::initializer_list
<uint32_t> &indexList
)
279 std::vector
<Value
*> indices
;
280 for (auto i
: indexList
)
281 indices
.push_back(C(i
));
282 return GEPA(ptr
, indices
);
285 LoadInst
*Builder::LOAD(Value
*basePtr
, const std::initializer_list
<uint32_t> &indices
, const llvm::Twine
& name
)
287 std::vector
<Value
*> valIndices
;
288 for (auto i
: indices
)
289 valIndices
.push_back(C(i
));
290 return LOAD(GEPA(basePtr
, valIndices
), name
);
293 LoadInst
*Builder::LOADV(Value
*basePtr
, const std::initializer_list
<Value
*> &indices
, const llvm::Twine
& name
)
295 std::vector
<Value
*> valIndices
;
296 for (auto i
: indices
)
297 valIndices
.push_back(i
);
298 return LOAD(GEPA(basePtr
, valIndices
), name
);
301 StoreInst
*Builder::STORE(Value
*val
, Value
*basePtr
, const std::initializer_list
<uint32_t> &indices
)
303 std::vector
<Value
*> valIndices
;
304 for (auto i
: indices
)
305 valIndices
.push_back(C(i
));
306 return STORE(val
, GEPA(basePtr
, valIndices
));
309 StoreInst
*Builder::STOREV(Value
*val
, Value
*basePtr
, const std::initializer_list
<Value
*> &indices
)
311 std::vector
<Value
*> valIndices
;
312 for (auto i
: indices
)
313 valIndices
.push_back(i
);
314 return STORE(val
, GEPA(basePtr
, valIndices
));
317 CallInst
*Builder::CALL(Value
*Callee
, const std::initializer_list
<Value
*> &argsList
)
319 std::vector
<Value
*> args
;
320 for (auto arg
: argsList
)
322 return CALLA(Callee
, args
);
325 Value
*Builder::VRCP(Value
*va
)
327 return FDIV(VIMMED1(1.0f
), va
); // 1 / a
330 Value
*Builder::VPLANEPS(Value
* vA
, Value
* vB
, Value
* vC
, Value
* &vX
, Value
* &vY
)
332 Value
* vOut
= FMADDPS(vA
, vX
, vC
);
333 vOut
= FMADDPS(vB
, vY
, vOut
);
337 //////////////////////////////////////////////////////////////////////////
338 /// @brief Generate an i32 masked load operation in LLVM IR. If not
339 /// supported on the underlying platform, emulate it with float masked load
340 /// @param src - base address pointer for the load
341 /// @param vMask - SIMD wide mask that controls whether to access memory load 0
342 Value
*Builder::MASKLOADD(Value
* src
,Value
* mask
)
345 // use avx2 gather instruction is available
346 if(JM()->mArch
.AVX2())
348 Function
*func
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::x86_avx2_maskload_d_256
);
349 vResult
= CALL(func
,{src
,mask
});
353 // maskload intrinsic expects integer mask operand in llvm >= 3.8
354 #if (LLVM_VERSION_MAJOR > 3) || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 8)
355 mask
= BITCAST(mask
,VectorType::get(mInt32Ty
,mVWidth
));
357 mask
= BITCAST(mask
,VectorType::get(mFP32Ty
,mVWidth
));
359 Function
*func
= Intrinsic::getDeclaration(JM()->mpCurrentModule
,Intrinsic::x86_avx_maskload_ps_256
);
360 vResult
= BITCAST(CALL(func
,{src
,mask
}), VectorType::get(mInt32Ty
,mVWidth
));
365 //////////////////////////////////////////////////////////////////////////
366 /// @brief insert a JIT call to CallPrint
367 /// - outputs formatted string to both stdout and VS output window
368 /// - DEBUG builds only
370 /// PRINT("index %d = 0x%p\n",{C(lane), pIndex});
371 /// where C(lane) creates a constant value to print, and pIndex is the Value*
372 /// result from a GEP, printing out the pointer to memory
373 /// @param printStr - constant string to print, which includes format specifiers
374 /// @param printArgs - initializer list of Value*'s to print to std out
375 CallInst
*Builder::PRINT(const std::string
&printStr
,const std::initializer_list
<Value
*> &printArgs
)
377 // push the arguments to CallPrint into a vector
378 std::vector
<Value
*> printCallArgs
;
379 // save room for the format string. we still need to modify it for vectors
380 printCallArgs
.resize(1);
382 // search through the format string for special processing
384 std::string
tempStr(printStr
);
385 pos
= tempStr
.find('%', pos
);
386 auto v
= printArgs
.begin();
388 while ((pos
!= std::string::npos
) && (v
!= printArgs
.end()))
391 Type
* pType
= pArg
->getType();
393 if (pType
->isVectorTy())
395 Type
* pContainedType
= pType
->getContainedType(0);
397 if (toupper(tempStr
[pos
+ 1]) == 'X')
400 tempStr
[pos
+ 1] = 'x';
401 tempStr
.insert(pos
+ 2, "%08X ");
404 printCallArgs
.push_back(VEXTRACT(pArg
, C(0)));
406 std::string vectorFormatStr
;
407 for (uint32_t i
= 1; i
< pType
->getVectorNumElements(); ++i
)
409 vectorFormatStr
+= "0x%08X ";
410 printCallArgs
.push_back(VEXTRACT(pArg
, C(i
)));
413 tempStr
.insert(pos
, vectorFormatStr
);
414 pos
+= vectorFormatStr
.size();
416 else if ((tempStr
[pos
+ 1] == 'f') && (pContainedType
->isFloatTy()))
419 for (; i
< (pArg
->getType()->getVectorNumElements()) - 1; i
++)
421 tempStr
.insert(pos
, std::string("%f "));
423 printCallArgs
.push_back(FP_EXT(VEXTRACT(pArg
, C(i
)), Type::getDoubleTy(JM()->mContext
)));
425 printCallArgs
.push_back(FP_EXT(VEXTRACT(pArg
, C(i
)), Type::getDoubleTy(JM()->mContext
)));
427 else if ((tempStr
[pos
+ 1] == 'd') && (pContainedType
->isIntegerTy()))
430 for (; i
< (pArg
->getType()->getVectorNumElements()) - 1; i
++)
432 tempStr
.insert(pos
, std::string("%d "));
434 printCallArgs
.push_back(VEXTRACT(pArg
, C(i
)));
436 printCallArgs
.push_back(VEXTRACT(pArg
, C(i
)));
441 if (toupper(tempStr
[pos
+ 1]) == 'X')
444 tempStr
.insert(pos
+ 1, "x%08");
445 printCallArgs
.push_back(pArg
);
448 // for %f we need to cast float Values to doubles so that they print out correctly
449 else if ((tempStr
[pos
+ 1] == 'f') && (pType
->isFloatTy()))
451 printCallArgs
.push_back(FP_EXT(pArg
, Type::getDoubleTy(JM()->mContext
)));
456 printCallArgs
.push_back(pArg
);
460 // advance to the next arguement
462 pos
= tempStr
.find('%', ++pos
);
465 // create global variable constant string
466 Constant
*constString
= ConstantDataArray::getString(JM()->mContext
,tempStr
,true);
467 GlobalVariable
*gvPtr
= new GlobalVariable(constString
->getType(),true,GlobalValue::InternalLinkage
,constString
,"printStr");
468 JM()->mpCurrentModule
->getGlobalList().push_back(gvPtr
);
470 // get a pointer to the first character in the constant string array
471 std::vector
<Constant
*> geplist
{C(0),C(0)};
472 #if HAVE_LLVM == 0x306
473 Constant
*strGEP
= ConstantExpr::getGetElementPtr(gvPtr
,geplist
,false);
475 Constant
*strGEP
= ConstantExpr::getGetElementPtr(nullptr, gvPtr
,geplist
,false);
478 // insert the pointer to the format string in the argument vector
479 printCallArgs
[0] = strGEP
;
481 // get pointer to CallPrint function and insert decl into the module if needed
482 std::vector
<Type
*> args
;
483 args
.push_back(PointerType::get(mInt8Ty
,0));
484 FunctionType
* callPrintTy
= FunctionType::get(Type::getVoidTy(JM()->mContext
),args
,true);
485 Function
*callPrintFn
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("CallPrint", callPrintTy
));
487 // if we haven't yet added the symbol to the symbol table
488 if((sys::DynamicLibrary::SearchForAddressOfSymbol("CallPrint")) == nullptr)
490 sys::DynamicLibrary::AddSymbol("CallPrint", (void *)&CallPrint
);
493 // insert a call to CallPrint
494 return CALLA(callPrintFn
,printCallArgs
);
497 //////////////////////////////////////////////////////////////////////////
498 /// @brief Wrapper around PRINT with initializer list.
499 CallInst
* Builder::PRINT(const std::string
&printStr
)
501 return PRINT(printStr
, {});
504 //////////////////////////////////////////////////////////////////////////
505 /// @brief Generate a masked gather operation in LLVM IR. If not
506 /// supported on the underlying platform, emulate it with loads
507 /// @param vSrc - SIMD wide value that will be loaded if mask is invalid
508 /// @param pBase - Int8* base VB address pointer value
509 /// @param vIndices - SIMD wide value of VB byte offsets
510 /// @param vMask - SIMD wide mask that controls whether to access memory or the src values
511 /// @param scale - value to scale indices by
512 Value
*Builder::GATHERPS(Value
* vSrc
, Value
* pBase
, Value
* vIndices
, Value
* vMask
, Value
* scale
)
516 // use avx2 gather instruction if available
517 if(JM()->mArch
.AVX2())
519 // force mask to <N x float>, required by vgather
520 vMask
= BITCAST(vMask
, mSimdFP32Ty
);
521 vGather
= VGATHERPS(vSrc
,pBase
,vIndices
,vMask
,scale
);
525 Value
* pStack
= STACKSAVE();
527 // store vSrc on the stack. this way we can select between a valid load address and the vSrc address
528 Value
* vSrcPtr
= ALLOCA(vSrc
->getType());
529 STORE(vSrc
, vSrcPtr
);
531 vGather
= VUNDEF_F();
532 Value
*vScaleVec
= VBROADCAST(Z_EXT(scale
,mInt32Ty
));
533 Value
*vOffsets
= MUL(vIndices
,vScaleVec
);
534 Value
*mask
= MASK(vMask
);
535 for(uint32_t i
= 0; i
< mVWidth
; ++i
)
537 // single component byte index
538 Value
*offset
= VEXTRACT(vOffsets
,C(i
));
539 // byte pointer to component
540 Value
*loadAddress
= GEP(pBase
,offset
);
541 loadAddress
= BITCAST(loadAddress
,PointerType::get(mFP32Ty
,0));
542 // pointer to the value to load if we're masking off a component
543 Value
*maskLoadAddress
= GEP(vSrcPtr
,{C(0), C(i
)});
544 Value
*selMask
= VEXTRACT(mask
,C(i
));
545 // switch in a safe address to load if we're trying to access a vertex
546 Value
*validAddress
= SELECT(selMask
, loadAddress
, maskLoadAddress
);
547 Value
*val
= LOAD(validAddress
);
548 vGather
= VINSERT(vGather
,val
,C(i
));
550 STACKRESTORE(pStack
);
556 //////////////////////////////////////////////////////////////////////////
557 /// @brief Generate a masked gather operation in LLVM IR. If not
558 /// supported on the underlying platform, emulate it with loads
559 /// @param vSrc - SIMD wide value that will be loaded if mask is invalid
560 /// @param pBase - Int8* base VB address pointer value
561 /// @param vIndices - SIMD wide value of VB byte offsets
562 /// @param vMask - SIMD wide mask that controls whether to access memory or the src values
563 /// @param scale - value to scale indices by
564 Value
*Builder::GATHERDD(Value
* vSrc
, Value
* pBase
, Value
* vIndices
, Value
* vMask
, Value
* scale
)
568 // use avx2 gather instruction if available
569 if(JM()->mArch
.AVX2())
571 vGather
= VGATHERDD(vSrc
, pBase
, vIndices
, vMask
, scale
);
575 Value
* pStack
= STACKSAVE();
577 // store vSrc on the stack. this way we can select between a valid load address and the vSrc address
578 Value
* vSrcPtr
= ALLOCA(vSrc
->getType());
579 STORE(vSrc
, vSrcPtr
);
581 vGather
= VUNDEF_I();
582 Value
*vScaleVec
= VBROADCAST(Z_EXT(scale
, mInt32Ty
));
583 Value
*vOffsets
= MUL(vIndices
, vScaleVec
);
584 Value
*mask
= MASK(vMask
);
585 for(uint32_t i
= 0; i
< mVWidth
; ++i
)
587 // single component byte index
588 Value
*offset
= VEXTRACT(vOffsets
, C(i
));
589 // byte pointer to component
590 Value
*loadAddress
= GEP(pBase
, offset
);
591 loadAddress
= BITCAST(loadAddress
, PointerType::get(mInt32Ty
, 0));
592 // pointer to the value to load if we're masking off a component
593 Value
*maskLoadAddress
= GEP(vSrcPtr
, {C(0), C(i
)});
594 Value
*selMask
= VEXTRACT(mask
, C(i
));
595 // switch in a safe address to load if we're trying to access a vertex
596 Value
*validAddress
= SELECT(selMask
, loadAddress
, maskLoadAddress
);
597 Value
*val
= LOAD(validAddress
, C(0));
598 vGather
= VINSERT(vGather
, val
, C(i
));
601 STACKRESTORE(pStack
);
606 //////////////////////////////////////////////////////////////////////////
607 /// @brief convert x86 <N x float> mask to llvm <N x i1> mask
608 Value
* Builder::MASK(Value
* vmask
)
610 Value
* src
= BITCAST(vmask
, mSimdInt32Ty
);
611 return ICMP_SLT(src
, VIMMED1(0));
614 //////////////////////////////////////////////////////////////////////////
615 /// @brief convert llvm <N x i1> mask to x86 <N x i32> mask
616 Value
* Builder::VMASK(Value
* mask
)
618 return S_EXT(mask
, mSimdInt32Ty
);
621 //////////////////////////////////////////////////////////////////////////
622 /// @brief Generate a VPSHUFB operation in LLVM IR. If not
623 /// supported on the underlying platform, emulate it
624 /// @param a - 256bit SIMD(32x8bit) of 8bit integer values
625 /// @param b - 256bit SIMD(32x8bit) of 8bit integer mask values
626 /// Byte masks in lower 128 lane of b selects 8 bit values from lower
627 /// 128bits of a, and vice versa for the upper lanes. If the mask
628 /// value is negative, '0' is inserted.
629 Value
*Builder::PSHUFB(Value
* a
, Value
* b
)
632 // use avx2 pshufb instruction if available
633 if(JM()->mArch
.AVX2())
639 Constant
* cB
= dyn_cast
<Constant
>(b
);
640 // number of 8 bit elements in b
641 uint32_t numElms
= cast
<VectorType
>(cB
->getType())->getNumElements();
643 Value
* vShuf
= UndefValue::get(VectorType::get(mInt8Ty
, numElms
));
645 // insert an 8 bit value from the high and low lanes of a per loop iteration
647 for(uint32_t i
= 0; i
< numElms
; i
++)
649 ConstantInt
* cLow128b
= cast
<ConstantInt
>(cB
->getAggregateElement(i
));
650 ConstantInt
* cHigh128b
= cast
<ConstantInt
>(cB
->getAggregateElement(i
+ numElms
));
652 // extract values from constant mask
653 char valLow128bLane
= (char)(cLow128b
->getSExtValue());
654 char valHigh128bLane
= (char)(cHigh128b
->getSExtValue());
656 Value
* insertValLow128b
;
657 Value
* insertValHigh128b
;
659 // if the mask value is negative, insert a '0' in the respective output position
660 // otherwise, lookup the value at mask position (bits 3..0 of the respective mask byte) in a and insert in output vector
661 insertValLow128b
= (valLow128bLane
< 0) ? C((char)0) : VEXTRACT(a
, C((valLow128bLane
& 0xF)));
662 insertValHigh128b
= (valHigh128bLane
< 0) ? C((char)0) : VEXTRACT(a
, C((valHigh128bLane
& 0xF) + numElms
));
664 vShuf
= VINSERT(vShuf
, insertValLow128b
, i
);
665 vShuf
= VINSERT(vShuf
, insertValHigh128b
, (i
+ numElms
));
672 //////////////////////////////////////////////////////////////////////////
673 /// @brief Generate a VPSHUFB operation (sign extend 8 8bit values to 32
674 /// bits)in LLVM IR. If not supported on the underlying platform, emulate it
675 /// @param a - 128bit SIMD lane(16x8bit) of 8bit integer values. Only
676 /// lower 8 values are used.
677 Value
*Builder::PMOVSXBD(Value
* a
)
680 // use avx2 byte sign extend instruction if available
681 if(JM()->mArch
.AVX2())
687 // VPMOVSXBD output type
688 Type
* v8x32Ty
= VectorType::get(mInt32Ty
, 8);
689 // Extract 8 values from 128bit lane and sign extend
690 res
= S_EXT(VSHUFFLE(a
, a
, C
<int>({0, 1, 2, 3, 4, 5, 6, 7})), v8x32Ty
);
695 //////////////////////////////////////////////////////////////////////////
696 /// @brief Generate a VPSHUFB operation (sign extend 8 16bit values to 32
697 /// bits)in LLVM IR. If not supported on the underlying platform, emulate it
698 /// @param a - 128bit SIMD lane(8x16bit) of 16bit integer values.
699 Value
*Builder::PMOVSXWD(Value
* a
)
702 // use avx2 word sign extend if available
703 if(JM()->mArch
.AVX2())
709 // VPMOVSXWD output type
710 Type
* v8x32Ty
= VectorType::get(mInt32Ty
, 8);
711 // Extract 8 values from 128bit lane and sign extend
712 res
= S_EXT(VSHUFFLE(a
, a
, C
<int>({0, 1, 2, 3, 4, 5, 6, 7})), v8x32Ty
);
717 //////////////////////////////////////////////////////////////////////////
718 /// @brief Generate a VPERMD operation (shuffle 32 bit integer values
719 /// across 128 bit lanes) in LLVM IR. If not supported on the underlying
720 /// platform, emulate it
721 /// @param a - 256bit SIMD lane(8x32bit) of integer values.
722 /// @param idx - 256bit SIMD lane(8x32bit) of 3 bit lane index values
723 Value
*Builder::PERMD(Value
* a
, Value
* idx
)
726 // use avx2 permute instruction if available
727 if(JM()->mArch
.AVX2())
729 // llvm 3.6.0 swapped the order of the args to vpermd
730 res
= VPERMD(idx
, a
);
734 if (isa
<Constant
>(idx
))
736 res
= VSHUFFLE(a
, a
, idx
);
741 for (uint32_t l
= 0; l
< JM()->mVWidth
; ++l
)
743 Value
* pIndex
= VEXTRACT(idx
, C(l
));
744 Value
* pVal
= VEXTRACT(a
, pIndex
);
745 res
= VINSERT(res
, pVal
, C(l
));
752 //////////////////////////////////////////////////////////////////////////
753 /// @brief Generate a VPERMPS operation (shuffle 32 bit float values
754 /// across 128 bit lanes) in LLVM IR. If not supported on the underlying
755 /// platform, emulate it
756 /// @param a - 256bit SIMD lane(8x32bit) of float values.
757 /// @param idx - 256bit SIMD lane(8x32bit) of 3 bit lane index values
758 Value
*Builder::PERMPS(Value
* a
, Value
* idx
)
761 // use avx2 permute instruction if available
762 if (JM()->mArch
.AVX2())
764 // llvm 3.6.0 swapped the order of the args to vpermd
765 res
= VPERMPS(idx
, a
);
769 if (isa
<Constant
>(idx
))
771 res
= VSHUFFLE(a
, a
, idx
);
776 for (uint32_t l
= 0; l
< JM()->mVWidth
; ++l
)
778 Value
* pIndex
= VEXTRACT(idx
, C(l
));
779 Value
* pVal
= VEXTRACT(a
, pIndex
);
780 res
= VINSERT(res
, pVal
, C(l
));
788 //////////////////////////////////////////////////////////////////////////
789 /// @brief Generate a VCVTPH2PS operation (float16->float32 conversion)
790 /// in LLVM IR. If not supported on the underlying platform, emulate it
791 /// @param a - 128bit SIMD lane(8x16bit) of float16 in int16 format.
792 Value
*Builder::CVTPH2PS(Value
* a
)
794 if (JM()->mArch
.F16C())
800 FunctionType
* pFuncTy
= FunctionType::get(mFP32Ty
, mInt16Ty
);
801 Function
* pCvtPh2Ps
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("ConvertSmallFloatTo32", pFuncTy
));
803 if (sys::DynamicLibrary::SearchForAddressOfSymbol("ConvertSmallFloatTo32") == nullptr)
805 sys::DynamicLibrary::AddSymbol("ConvertSmallFloatTo32", (void *)&ConvertSmallFloatTo32
);
808 Value
* pResult
= UndefValue::get(mSimdFP32Ty
);
809 for (uint32_t i
= 0; i
< mVWidth
; ++i
)
811 Value
* pSrc
= VEXTRACT(a
, C(i
));
812 Value
* pConv
= CALL(pCvtPh2Ps
, std::initializer_list
<Value
*>{pSrc
});
813 pResult
= VINSERT(pResult
, pConv
, C(i
));
820 //////////////////////////////////////////////////////////////////////////
821 /// @brief Generate a VCVTPS2PH operation (float32->float16 conversion)
822 /// in LLVM IR. If not supported on the underlying platform, emulate it
823 /// @param a - 128bit SIMD lane(8x16bit) of float16 in int16 format.
824 Value
*Builder::CVTPS2PH(Value
* a
, Value
* rounding
)
826 if (JM()->mArch
.F16C())
828 return VCVTPS2PH(a
, rounding
);
832 // call scalar C function for now
833 FunctionType
* pFuncTy
= FunctionType::get(mInt16Ty
, mFP32Ty
);
834 Function
* pCvtPs2Ph
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("Convert32To16Float", pFuncTy
));
836 if (sys::DynamicLibrary::SearchForAddressOfSymbol("Convert32To16Float") == nullptr)
838 sys::DynamicLibrary::AddSymbol("Convert32To16Float", (void *)&Convert32To16Float
);
841 Value
* pResult
= UndefValue::get(mSimdInt16Ty
);
842 for (uint32_t i
= 0; i
< mVWidth
; ++i
)
844 Value
* pSrc
= VEXTRACT(a
, C(i
));
845 Value
* pConv
= CALL(pCvtPs2Ph
, std::initializer_list
<Value
*>{pSrc
});
846 pResult
= VINSERT(pResult
, pConv
, C(i
));
853 Value
*Builder::PMAXSD(Value
* a
, Value
* b
)
855 if (JM()->mArch
.AVX2())
857 return VPMAXSD(a
, b
);
861 // use 4-wide sse max intrinsic on lower/upper halves of 8-wide sources
862 Function
* pmaxsd
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::x86_sse41_pmaxsd
);
865 Value
* aLo
= VEXTRACTI128(a
, C((uint8_t)0));
866 Value
* bLo
= VEXTRACTI128(b
, C((uint8_t)0));
867 Value
* resLo
= CALL(pmaxsd
, {aLo
, bLo
});
870 Value
* aHi
= VEXTRACTI128(a
, C((uint8_t)1));
871 Value
* bHi
= VEXTRACTI128(b
, C((uint8_t)1));
872 Value
* resHi
= CALL(pmaxsd
, {aHi
, bHi
});
875 Value
* result
= VINSERTI128(VUNDEF_I(), resLo
, C((uint8_t)0));
876 result
= VINSERTI128(result
, resHi
, C((uint8_t)1));
882 Value
*Builder::PMINSD(Value
* a
, Value
* b
)
884 if (JM()->mArch
.AVX2())
886 return VPMINSD(a
, b
);
890 // use 4-wide sse max intrinsic on lower/upper halves of 8-wide sources
891 Function
* pminsd
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::x86_sse41_pminsd
);
894 Value
* aLo
= VEXTRACTI128(a
, C((uint8_t)0));
895 Value
* bLo
= VEXTRACTI128(b
, C((uint8_t)0));
896 Value
* resLo
= CALL(pminsd
, {aLo
, bLo
});
899 Value
* aHi
= VEXTRACTI128(a
, C((uint8_t)1));
900 Value
* bHi
= VEXTRACTI128(b
, C((uint8_t)1));
901 Value
* resHi
= CALL(pminsd
, {aHi
, bHi
});
904 Value
* result
= VINSERTI128(VUNDEF_I(), resLo
, C((uint8_t)0));
905 result
= VINSERTI128(result
, resHi
, C((uint8_t)1));
911 void Builder::Gather4(const SWR_FORMAT format
, Value
* pSrcBase
, Value
* byteOffsets
,
912 Value
* mask
, Value
* vGatherComponents
[], bool bPackedOutput
)
914 const SWR_FORMAT_INFO
&info
= GetFormatInfo(format
);
915 if(info
.type
[0] == SWR_TYPE_FLOAT
&& info
.bpc
[0] == 32)
917 // ensure our mask is the correct type
918 mask
= BITCAST(mask
, mSimdFP32Ty
);
919 GATHER4PS(info
, pSrcBase
, byteOffsets
, mask
, vGatherComponents
, bPackedOutput
);
923 // ensure our mask is the correct type
924 mask
= BITCAST(mask
, mSimdInt32Ty
);
925 GATHER4DD(info
, pSrcBase
, byteOffsets
, mask
, vGatherComponents
, bPackedOutput
);
929 void Builder::GATHER4PS(const SWR_FORMAT_INFO
&info
, Value
* pSrcBase
, Value
* byteOffsets
,
930 Value
* mask
, Value
* vGatherComponents
[], bool bPackedOutput
)
932 switch(info
.bpp
/ info
.numComps
)
936 Value
* vGatherResult
[2];
939 // TODO: vGatherMaskedVal
940 Value
* vGatherMaskedVal
= VIMMED1((float)0);
942 // always have at least one component out of x or y to fetch
944 // save mask as it is zero'd out after each gather
947 vGatherResult
[0] = GATHERPS(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
, C((char)1));
948 // e.g. result of first 8x32bit integer gather for 16bit components
949 // 256i - 0 1 2 3 4 5 6 7
950 // xyxy xyxy xyxy xyxy xyxy xyxy xyxy xyxy
953 // if we have at least one component out of x or y to fetch
954 if(info
.numComps
> 2)
956 // offset base to the next components(zw) in the vertex to gather
957 pSrcBase
= GEP(pSrcBase
, C((char)4));
960 vGatherResult
[1] = GATHERPS(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
, C((char)1));
961 // e.g. result of second 8x32bit integer gather for 16bit components
962 // 256i - 0 1 2 3 4 5 6 7
963 // zwzw zwzw zwzw zwzw zwzw zwzw zwzw zwzw
968 vGatherResult
[1] = vGatherMaskedVal
;
971 // Shuffle gathered components into place, each row is a component
972 Shuffle16bpcGather4(info
, vGatherResult
, vGatherComponents
, bPackedOutput
);
978 for (uint32_t i
= 0; i
< 4; ++i
)
980 vGatherComponents
[i
] = VIMMED1(*(float*)&info
.defaults
[i
]);
983 for(uint32_t i
= 0; i
< info
.numComps
; i
++)
985 uint32_t swizzleIndex
= info
.swizzle
[i
];
987 // save mask as it is zero'd out after each gather
990 // Gather a SIMD of components
991 vGatherComponents
[swizzleIndex
] = GATHERPS(vGatherComponents
[swizzleIndex
], pSrcBase
, byteOffsets
, vMask
, C((char)1));
993 // offset base to the next component to gather
994 pSrcBase
= GEP(pSrcBase
, C((char)4));
999 SWR_ASSERT(0, "Invalid float format");
1004 void Builder::GATHER4DD(const SWR_FORMAT_INFO
&info
, Value
* pSrcBase
, Value
* byteOffsets
,
1005 Value
* mask
, Value
* vGatherComponents
[], bool bPackedOutput
)
1007 switch (info
.bpp
/ info
.numComps
)
1011 Value
* vGatherMaskedVal
= VIMMED1((int32_t)0);
1012 Value
* vGatherResult
= GATHERDD(vGatherMaskedVal
, pSrcBase
, byteOffsets
, mask
, C((char)1));
1013 // e.g. result of an 8x32bit integer gather for 8bit components
1014 // 256i - 0 1 2 3 4 5 6 7
1015 // xyzw xyzw xyzw xyzw xyzw xyzw xyzw xyzw
1017 Shuffle8bpcGather4(info
, vGatherResult
, vGatherComponents
, bPackedOutput
);
1022 Value
* vGatherResult
[2];
1025 // TODO: vGatherMaskedVal
1026 Value
* vGatherMaskedVal
= VIMMED1((int32_t)0);
1028 // always have at least one component out of x or y to fetch
1030 // save mask as it is zero'd out after each gather
1033 vGatherResult
[0] = GATHERDD(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
, C((char)1));
1034 // e.g. result of first 8x32bit integer gather for 16bit components
1035 // 256i - 0 1 2 3 4 5 6 7
1036 // xyxy xyxy xyxy xyxy xyxy xyxy xyxy xyxy
1039 // if we have at least one component out of x or y to fetch
1040 if(info
.numComps
> 2)
1042 // offset base to the next components(zw) in the vertex to gather
1043 pSrcBase
= GEP(pSrcBase
, C((char)4));
1046 vGatherResult
[1] = GATHERDD(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
, C((char)1));
1047 // e.g. result of second 8x32bit integer gather for 16bit components
1048 // 256i - 0 1 2 3 4 5 6 7
1049 // zwzw zwzw zwzw zwzw zwzw zwzw zwzw zwzw
1054 vGatherResult
[1] = vGatherMaskedVal
;
1057 // Shuffle gathered components into place, each row is a component
1058 Shuffle16bpcGather4(info
, vGatherResult
, vGatherComponents
, bPackedOutput
);
1065 for (uint32_t i
= 0; i
< 4; ++i
)
1067 vGatherComponents
[i
] = VIMMED1((int)info
.defaults
[i
]);
1070 for(uint32_t i
= 0; i
< info
.numComps
; i
++)
1072 uint32_t swizzleIndex
= info
.swizzle
[i
];
1074 // save mask as it is zero'd out after each gather
1075 Value
*vMask
= mask
;
1077 // Gather a SIMD of components
1078 vGatherComponents
[swizzleIndex
] = GATHERDD(vGatherComponents
[swizzleIndex
], pSrcBase
, byteOffsets
, vMask
, C((char)1));
1080 // offset base to the next component to gather
1081 pSrcBase
= GEP(pSrcBase
, C((char)4));
1086 SWR_ASSERT(0, "unsupported format");
1091 void Builder::Shuffle16bpcGather4(const SWR_FORMAT_INFO
&info
, Value
* vGatherInput
[2], Value
* vGatherOutput
[4], bool bPackedOutput
)
1094 Type
* vGatherTy
= VectorType::get(IntegerType::getInt32Ty(JM()->mContext
), mVWidth
);
1095 Type
* v32x8Ty
= VectorType::get(mInt8Ty
, mVWidth
* 4); // vwidth is units of 32 bits
1097 // input could either be float or int vector; do shuffle work in int
1098 vGatherInput
[0] = BITCAST(vGatherInput
[0], mSimdInt32Ty
);
1099 vGatherInput
[1] = BITCAST(vGatherInput
[1], mSimdInt32Ty
);
1103 Type
* v128bitTy
= VectorType::get(IntegerType::getIntNTy(JM()->mContext
, 128), mVWidth
/ 4); // vwidth is units of 32 bits
1106 Value
* vConstMask
= C
<char>({0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15,
1107 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15});
1108 Value
* vShufResult
= BITCAST(PSHUFB(BITCAST(vGatherInput
[0], v32x8Ty
), vConstMask
), vGatherTy
);
1109 // after pshufb: group components together in each 128bit lane
1110 // 256i - 0 1 2 3 4 5 6 7
1111 // xxxx xxxx yyyy yyyy xxxx xxxx yyyy yyyy
1113 Value
* vi128XY
= BITCAST(PERMD(vShufResult
, C
<int32_t>({0, 1, 4, 5, 2, 3, 6, 7})), v128bitTy
);
1114 // after PERMD: move and pack xy components into each 128bit lane
1115 // 256i - 0 1 2 3 4 5 6 7
1116 // xxxx xxxx xxxx xxxx yyyy yyyy yyyy yyyy
1118 // do the same for zw components
1119 Value
* vi128ZW
= nullptr;
1120 if(info
.numComps
> 2)
1122 Value
* vShufResult
= BITCAST(PSHUFB(BITCAST(vGatherInput
[1], v32x8Ty
), vConstMask
), vGatherTy
);
1123 vi128ZW
= BITCAST(PERMD(vShufResult
, C
<int32_t>({0, 1, 4, 5, 2, 3, 6, 7})), v128bitTy
);
1126 for(uint32_t i
= 0; i
< 4; i
++)
1128 uint32_t swizzleIndex
= info
.swizzle
[i
];
1129 // todo: fixed for packed
1130 Value
* vGatherMaskedVal
= VIMMED1((int32_t)(info
.defaults
[i
]));
1131 if(i
>= info
.numComps
)
1133 // set the default component val
1134 vGatherOutput
[swizzleIndex
] = vGatherMaskedVal
;
1138 // if x or z, extract 128bits from lane 0, else for y or w, extract from lane 1
1139 uint32_t lane
= ((i
== 0) || (i
== 2)) ? 0 : 1;
1140 // if x or y, use vi128XY permute result, else use vi128ZW
1141 Value
* selectedPermute
= (i
< 2) ? vi128XY
: vi128ZW
;
1143 // extract packed component 128 bit lanes
1144 vGatherOutput
[swizzleIndex
] = VEXTRACT(selectedPermute
, C(lane
));
1150 // pshufb masks for each component
1151 Value
* vConstMask
[2];
1153 vConstMask
[0] = C
<char>({0, 1, -1, -1, 4, 5, -1, -1, 8, 9, -1, -1, 12, 13, -1, -1,
1154 0, 1, -1, -1, 4, 5, -1, -1, 8, 9, -1, -1, 12, 13, -1, -1, });
1157 vConstMask
[1] = C
<char>({2, 3, -1, -1, 6, 7, -1, -1, 10, 11, -1, -1, 14, 15, -1, -1,
1158 2, 3, -1, -1, 6, 7, -1, -1, 10, 11, -1, -1, 14, 15, -1, -1});
1161 // shuffle enabled components into lower word of each 32bit lane, 0 extending to 32 bits
1163 for (uint32_t i
= 0; i
< 4; ++i
)
1165 vGatherOutput
[i
] = VIMMED1((int32_t)info
.defaults
[i
]);
1168 for(uint32_t i
= 0; i
< info
.numComps
; i
++)
1170 uint32_t swizzleIndex
= info
.swizzle
[i
];
1172 // select correct constMask for x/z or y/w pshufb
1173 uint32_t selectedMask
= ((i
== 0) || (i
== 2)) ? 0 : 1;
1174 // if x or y, use vi128XY permute result, else use vi128ZW
1175 uint32_t selectedGather
= (i
< 2) ? 0 : 1;
1177 vGatherOutput
[swizzleIndex
] = BITCAST(PSHUFB(BITCAST(vGatherInput
[selectedGather
], v32x8Ty
), vConstMask
[selectedMask
]), vGatherTy
);
1178 // after pshufb mask for x channel; z uses the same shuffle from the second gather
1179 // 256i - 0 1 2 3 4 5 6 7
1180 // xx00 xx00 xx00 xx00 xx00 xx00 xx00 xx00
1185 void Builder::Shuffle8bpcGather4(const SWR_FORMAT_INFO
&info
, Value
* vGatherInput
, Value
* vGatherOutput
[], bool bPackedOutput
)
1188 Type
* vGatherTy
= VectorType::get(IntegerType::getInt32Ty(JM()->mContext
), mVWidth
);
1189 Type
* v32x8Ty
= VectorType::get(mInt8Ty
, mVWidth
* 4 ); // vwidth is units of 32 bits
1193 Type
* v128Ty
= VectorType::get(IntegerType::getIntNTy(JM()->mContext
, 128), mVWidth
/ 4); // vwidth is units of 32 bits
1195 Value
* vConstMask
= C
<char>({0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15,
1196 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15});
1197 Value
* vShufResult
= BITCAST(PSHUFB(BITCAST(vGatherInput
, v32x8Ty
), vConstMask
), vGatherTy
);
1198 // after pshufb: group components together in each 128bit lane
1199 // 256i - 0 1 2 3 4 5 6 7
1200 // xxxx yyyy zzzz wwww xxxx yyyy zzzz wwww
1202 Value
* vi128XY
= BITCAST(PERMD(vShufResult
, C
<int32_t>({0, 4, 0, 0, 1, 5, 0, 0})), v128Ty
);
1203 // after PERMD: move and pack xy and zw components in low 64 bits of each 128bit lane
1204 // 256i - 0 1 2 3 4 5 6 7
1205 // xxxx xxxx dcdc dcdc yyyy yyyy dcdc dcdc (dc - don't care)
1207 // do the same for zw components
1208 Value
* vi128ZW
= nullptr;
1209 if(info
.numComps
> 2)
1211 vi128ZW
= BITCAST(PERMD(vShufResult
, C
<int32_t>({2, 6, 0, 0, 3, 7, 0, 0})), v128Ty
);
1214 // sign extend all enabled components. If we have a fill vVertexElements, output to current simdvertex
1215 for(uint32_t i
= 0; i
< 4; i
++)
1217 uint32_t swizzleIndex
= info
.swizzle
[i
];
1218 // todo: fix for packed
1219 Value
* vGatherMaskedVal
= VIMMED1((int32_t)(info
.defaults
[i
]));
1220 if(i
>= info
.numComps
)
1222 // set the default component val
1223 vGatherOutput
[swizzleIndex
] = vGatherMaskedVal
;
1227 // if x or z, extract 128bits from lane 0, else for y or w, extract from lane 1
1228 uint32_t lane
= ((i
== 0) || (i
== 2)) ? 0 : 1;
1229 // if x or y, use vi128XY permute result, else use vi128ZW
1230 Value
* selectedPermute
= (i
< 2) ? vi128XY
: vi128ZW
;
1233 vGatherOutput
[swizzleIndex
] = VEXTRACT(selectedPermute
, C(lane
));
1238 // shuffle enabled components into lower byte of each 32bit lane, 0 extending to 32 bits
1240 for (uint32_t i
= 0; i
< 4; ++i
)
1242 vGatherOutput
[i
] = VIMMED1((int32_t)info
.defaults
[i
]);
1245 for(uint32_t i
= 0; i
< info
.numComps
; i
++){
1246 uint32_t swizzleIndex
= info
.swizzle
[i
];
1248 // pshufb masks for each component
1254 vConstMask
= C
<char>({0, -1, -1, -1, 4, -1, -1, -1, 8, -1, -1, -1, 12, -1, -1, -1,
1255 0, -1, -1, -1, 4, -1, -1, -1, 8, -1, -1, -1, 12, -1, -1, -1});
1259 vConstMask
= C
<char>({1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1,
1260 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1});
1264 vConstMask
= C
<char>({2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1,
1265 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1});
1269 vConstMask
= C
<char>({3, -1, -1, -1, 7, -1, -1, -1, 11, -1, -1, -1, 15, -1, -1, -1,
1270 3, -1, -1, -1, 7, -1, -1, -1, 11, -1, -1, -1, 15, -1, -1, -1});
1273 vConstMask
= nullptr;
1277 vGatherOutput
[swizzleIndex
] = BITCAST(PSHUFB(BITCAST(vGatherInput
, v32x8Ty
), vConstMask
), vGatherTy
);
1278 // after pshufb for x channel
1279 // 256i - 0 1 2 3 4 5 6 7
1280 // x000 x000 x000 x000 x000 x000 x000 x000
1285 //////////////////////////////////////////////////////////////////////////
1286 /// @brief emulates a scatter operation.
1287 /// @param pDst - pointer to destination
1288 /// @param vSrc - vector of src data to scatter
1289 /// @param vOffsets - vector of byte offsets from pDst
1290 /// @param vMask - mask of valid lanes
1291 void Builder::SCATTERPS(Value
* pDst
, Value
* vSrc
, Value
* vOffsets
, Value
* vMask
)
1293 Value
* pStack
= STACKSAVE();
1295 Type
* pSrcTy
= vSrc
->getType()->getVectorElementType();
1297 // allocate tmp stack for masked off lanes
1298 Value
* vTmpPtr
= ALLOCA(pSrcTy
);
1300 Value
*mask
= MASK(vMask
);
1301 for (uint32_t i
= 0; i
< mVWidth
; ++i
)
1303 Value
*offset
= VEXTRACT(vOffsets
, C(i
));
1304 // byte pointer to component
1305 Value
*storeAddress
= GEP(pDst
, offset
);
1306 storeAddress
= BITCAST(storeAddress
, PointerType::get(pSrcTy
, 0));
1307 Value
*selMask
= VEXTRACT(mask
, C(i
));
1308 Value
*srcElem
= VEXTRACT(vSrc
, C(i
));
1309 // switch in a safe address to load if we're trying to access a vertex
1310 Value
*validAddress
= SELECT(selMask
, storeAddress
, vTmpPtr
);
1311 STORE(srcElem
, validAddress
);
1314 STACKRESTORE(pStack
);
1317 Value
* Builder::VABSPS(Value
* a
)
1319 Value
* asInt
= BITCAST(a
, mSimdInt32Ty
);
1320 Value
* result
= BITCAST(AND(asInt
, VIMMED1(0x7fffffff)), mSimdFP32Ty
);
1324 Value
*Builder::ICLAMP(Value
* src
, Value
* low
, Value
* high
)
1326 Value
*lowCmp
= ICMP_SLT(src
, low
);
1327 Value
*ret
= SELECT(lowCmp
, low
, src
);
1329 Value
*highCmp
= ICMP_SGT(ret
, high
);
1330 ret
= SELECT(highCmp
, high
, ret
);
1335 Value
*Builder::FCLAMP(Value
* src
, Value
* low
, Value
* high
)
1337 Value
*lowCmp
= FCMP_OLT(src
, low
);
1338 Value
*ret
= SELECT(lowCmp
, low
, src
);
1340 Value
*highCmp
= FCMP_OGT(ret
, high
);
1341 ret
= SELECT(highCmp
, high
, ret
);
1346 Value
*Builder::FCLAMP(Value
* src
, float low
, float high
)
1348 Value
* result
= VMAXPS(src
, VIMMED1(low
));
1349 result
= VMINPS(result
, VIMMED1(high
));
1354 //////////////////////////////////////////////////////////////////////////
1355 /// @brief save/restore stack, providing ability to push/pop the stack and
1356 /// reduce overall stack requirements for temporary stack use
1357 Value
* Builder::STACKSAVE()
1359 Function
* pfnStackSave
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::stacksave
);
1360 #if HAVE_LLVM == 0x306
1361 return CALL(pfnStackSave
);
1363 return CALLA(pfnStackSave
);
1367 void Builder::STACKRESTORE(Value
* pSaved
)
1369 Function
* pfnStackRestore
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::stackrestore
);
1370 CALL(pfnStackRestore
, std::initializer_list
<Value
*>{pSaved
});
1373 Value
*Builder::FMADDPS(Value
* a
, Value
* b
, Value
* c
)
1376 // use FMADs if available
1377 if(JM()->mArch
.AVX2())
1379 vOut
= VFMADDPS(a
, b
, c
);
1383 vOut
= FADD(FMUL(a
, b
), c
);
1388 Value
* Builder::POPCNT(Value
* a
)
1390 Function
* pCtPop
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::ctpop
, { a
->getType() });
1391 return CALL(pCtPop
, std::initializer_list
<Value
*>{a
});
1394 //////////////////////////////////////////////////////////////////////////
1395 /// @brief C functions called by LLVM IR
1396 //////////////////////////////////////////////////////////////////////////
1398 //////////////////////////////////////////////////////////////////////////
1399 /// @brief called in JIT code, inserted by PRINT
1400 /// output to both stdout and visual studio debug console
1401 void __cdecl
CallPrint(const char* fmt
, ...)
1404 va_start(args
, fmt
);
1407 #if defined( _WIN32 )
1409 vsnprintf_s(strBuf
, _TRUNCATE
, fmt
, args
);
1410 OutputDebugString(strBuf
);
1416 Value
*Builder::VEXTRACTI128(Value
* a
, Constant
* imm8
)
1418 #if HAVE_LLVM == 0x306
1420 Intrinsic::getDeclaration(JM()->mpCurrentModule
,
1421 Intrinsic::x86_avx_vextractf128_si_256
);
1422 return CALL(func
, {a
, imm8
});
1424 bool flag
= !imm8
->isZeroValue();
1425 SmallVector
<Constant
*,8> idx
;
1426 for (unsigned i
= 0; i
< mVWidth
/ 2; i
++) {
1427 idx
.push_back(C(flag
? i
+ mVWidth
/ 2 : i
));
1429 return VSHUFFLE(a
, VUNDEF_I(), ConstantVector::get(idx
));
1433 Value
*Builder::VINSERTI128(Value
* a
, Value
* b
, Constant
* imm8
)
1435 #if HAVE_LLVM == 0x306
1437 Intrinsic::getDeclaration(JM()->mpCurrentModule
,
1438 Intrinsic::x86_avx_vinsertf128_si_256
);
1439 return CALL(func
, {a
, b
, imm8
});
1441 bool flag
= !imm8
->isZeroValue();
1442 SmallVector
<Constant
*,8> idx
;
1443 for (unsigned i
= 0; i
< mVWidth
; i
++) {
1444 idx
.push_back(C(i
));
1446 Value
*inter
= VSHUFFLE(b
, VUNDEF_I(), ConstantVector::get(idx
));
1448 SmallVector
<Constant
*,8> idx2
;
1449 for (unsigned i
= 0; i
< mVWidth
/ 2; i
++) {
1450 idx2
.push_back(C(flag
? i
: i
+ mVWidth
));
1452 for (unsigned i
= mVWidth
/ 2; i
< mVWidth
; i
++) {
1453 idx2
.push_back(C(flag
? i
+ mVWidth
/ 2 : i
));
1455 return VSHUFFLE(a
, inter
, ConstantVector::get(idx2
));
1459 // rdtsc buckets macros
1460 void Builder::RDTSC_START(Value
* pBucketMgr
, Value
* pId
)
1462 std::vector
<Type
*> args
{
1463 PointerType::get(mInt32Ty
, 0), // pBucketMgr
1467 FunctionType
* pFuncTy
= FunctionType::get(Type::getVoidTy(JM()->mContext
), args
, false);
1468 Function
* pFunc
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("BucketManager_StartBucket", pFuncTy
));
1469 if (sys::DynamicLibrary::SearchForAddressOfSymbol("BucketManager_StartBucket") == nullptr)
1471 sys::DynamicLibrary::AddSymbol("BucketManager_StartBucket", (void*)&BucketManager_StartBucket
);
1474 CALL(pFunc
, { pBucketMgr
, pId
});
1477 void Builder::RDTSC_STOP(Value
* pBucketMgr
, Value
* pId
)
1479 std::vector
<Type
*> args
{
1480 PointerType::get(mInt32Ty
, 0), // pBucketMgr
1484 FunctionType
* pFuncTy
= FunctionType::get(Type::getVoidTy(JM()->mContext
), args
, false);
1485 Function
* pFunc
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("BucketManager_StopBucket", pFuncTy
));
1486 if (sys::DynamicLibrary::SearchForAddressOfSymbol("BucketManager_StopBucket") == nullptr)
1488 sys::DynamicLibrary::AddSymbol("BucketManager_StopBucket", (void*)&BucketManager_StopBucket
);
1491 CALL(pFunc
, { pBucketMgr
, pId
});