FixedPointBuilder.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. //===- llvm/FixedPointBuilder.h - Builder for fixed-point ops ---*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the FixedPointBuilder class, which is used as a convenient
  10. // way to lower fixed-point arithmetic operations to LLVM IR.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_IR_FIXEDPOINTBUILDER_H
  14. #define LLVM_IR_FIXEDPOINTBUILDER_H
  15. #include "llvm/ADT/APFixedPoint.h"
  16. #include "llvm/IR/Constant.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/IRBuilder.h"
  19. #include "llvm/IR/InstrTypes.h"
  20. #include "llvm/IR/Instruction.h"
  21. #include "llvm/IR/IntrinsicInst.h"
  22. #include "llvm/IR/Intrinsics.h"
  23. #include "llvm/IR/Type.h"
  24. #include "llvm/IR/Value.h"
  25. namespace llvm {
  26. template <class IRBuilderTy> class FixedPointBuilder {
  27. IRBuilderTy &B;
  28. Value *Convert(Value *Src, const FixedPointSemantics &SrcSema,
  29. const FixedPointSemantics &DstSema, bool DstIsInteger) {
  30. unsigned SrcWidth = SrcSema.getWidth();
  31. unsigned DstWidth = DstSema.getWidth();
  32. unsigned SrcScale = SrcSema.getScale();
  33. unsigned DstScale = DstSema.getScale();
  34. bool SrcIsSigned = SrcSema.isSigned();
  35. bool DstIsSigned = DstSema.isSigned();
  36. Type *DstIntTy = B.getIntNTy(DstWidth);
  37. Value *Result = Src;
  38. unsigned ResultWidth = SrcWidth;
  39. // Downscale.
  40. if (DstScale < SrcScale) {
  41. // When converting to integers, we round towards zero. For negative
  42. // numbers, right shifting rounds towards negative infinity. In this case,
  43. // we can just round up before shifting.
  44. if (DstIsInteger && SrcIsSigned) {
  45. Value *Zero = Constant::getNullValue(Result->getType());
  46. Value *IsNegative = B.CreateICmpSLT(Result, Zero);
  47. Value *LowBits = ConstantInt::get(
  48. B.getContext(), APInt::getLowBitsSet(ResultWidth, SrcScale));
  49. Value *Rounded = B.CreateAdd(Result, LowBits);
  50. Result = B.CreateSelect(IsNegative, Rounded, Result);
  51. }
  52. Result = SrcIsSigned
  53. ? B.CreateAShr(Result, SrcScale - DstScale, "downscale")
  54. : B.CreateLShr(Result, SrcScale - DstScale, "downscale");
  55. }
  56. if (!DstSema.isSaturated()) {
  57. // Resize.
  58. Result = B.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
  59. // Upscale.
  60. if (DstScale > SrcScale)
  61. Result = B.CreateShl(Result, DstScale - SrcScale, "upscale");
  62. } else {
  63. // Adjust the number of fractional bits.
  64. if (DstScale > SrcScale) {
  65. // Compare to DstWidth to prevent resizing twice.
  66. ResultWidth = std::max(SrcWidth + DstScale - SrcScale, DstWidth);
  67. Type *UpscaledTy = B.getIntNTy(ResultWidth);
  68. Result = B.CreateIntCast(Result, UpscaledTy, SrcIsSigned, "resize");
  69. Result = B.CreateShl(Result, DstScale - SrcScale, "upscale");
  70. }
  71. // Handle saturation.
  72. bool LessIntBits = DstSema.getIntegralBits() < SrcSema.getIntegralBits();
  73. if (LessIntBits) {
  74. Value *Max = ConstantInt::get(
  75. B.getContext(),
  76. APFixedPoint::getMax(DstSema).getValue().extOrTrunc(ResultWidth));
  77. Value *TooHigh = SrcIsSigned ? B.CreateICmpSGT(Result, Max)
  78. : B.CreateICmpUGT(Result, Max);
  79. Result = B.CreateSelect(TooHigh, Max, Result, "satmax");
  80. }
  81. // Cannot overflow min to dest type if src is unsigned since all fixed
  82. // point types can cover the unsigned min of 0.
  83. if (SrcIsSigned && (LessIntBits || !DstIsSigned)) {
  84. Value *Min = ConstantInt::get(
  85. B.getContext(),
  86. APFixedPoint::getMin(DstSema).getValue().extOrTrunc(ResultWidth));
  87. Value *TooLow = B.CreateICmpSLT(Result, Min);
  88. Result = B.CreateSelect(TooLow, Min, Result, "satmin");
  89. }
  90. // Resize the integer part to get the final destination size.
  91. if (ResultWidth != DstWidth)
  92. Result = B.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
  93. }
  94. return Result;
  95. }
  96. /// Get the common semantic for two semantics, with the added imposition that
  97. /// saturated padded types retain the padding bit.
  98. FixedPointSemantics
  99. getCommonBinopSemantic(const FixedPointSemantics &LHSSema,
  100. const FixedPointSemantics &RHSSema) {
  101. auto C = LHSSema.getCommonSemantics(RHSSema);
  102. bool BothPadded =
  103. LHSSema.hasUnsignedPadding() && RHSSema.hasUnsignedPadding();
  104. return FixedPointSemantics(
  105. C.getWidth() + (unsigned)(BothPadded && C.isSaturated()), C.getScale(),
  106. C.isSigned(), C.isSaturated(), BothPadded);
  107. }
  108. /// Given a floating point type and a fixed-point semantic, return a floating
  109. /// point type which can accommodate the fixed-point semantic. This is either
  110. /// \p Ty, or a floating point type with a larger exponent than Ty.
  111. Type *getAccommodatingFloatType(Type *Ty, const FixedPointSemantics &Sema) {
  112. const fltSemantics *FloatSema = &Ty->getFltSemantics();
  113. while (!Sema.fitsInFloatSemantics(*FloatSema))
  114. FloatSema = APFixedPoint::promoteFloatSemantics(FloatSema);
  115. return Type::getFloatingPointTy(Ty->getContext(), *FloatSema);
  116. }
  117. public:
  118. FixedPointBuilder(IRBuilderTy &Builder) : B(Builder) {}
  119. /// Convert an integer value representing a fixed-point number from one
  120. /// fixed-point semantic to another fixed-point semantic.
  121. /// \p Src - The source value
  122. /// \p SrcSema - The fixed-point semantic of the source value
  123. /// \p DstSema - The resulting fixed-point semantic
  124. Value *CreateFixedToFixed(Value *Src, const FixedPointSemantics &SrcSema,
  125. const FixedPointSemantics &DstSema) {
  126. return Convert(Src, SrcSema, DstSema, false);
  127. }
  128. /// Convert an integer value representing a fixed-point number to an integer
  129. /// with the given bit width and signedness.
  130. /// \p Src - The source value
  131. /// \p SrcSema - The fixed-point semantic of the source value
  132. /// \p DstWidth - The bit width of the result value
  133. /// \p DstIsSigned - The signedness of the result value
  134. Value *CreateFixedToInteger(Value *Src, const FixedPointSemantics &SrcSema,
  135. unsigned DstWidth, bool DstIsSigned) {
  136. return Convert(
  137. Src, SrcSema,
  138. FixedPointSemantics::GetIntegerSemantics(DstWidth, DstIsSigned), true);
  139. }
  140. /// Convert an integer value with the given signedness to an integer value
  141. /// representing the given fixed-point semantic.
  142. /// \p Src - The source value
  143. /// \p SrcIsSigned - The signedness of the source value
  144. /// \p DstSema - The resulting fixed-point semantic
  145. Value *CreateIntegerToFixed(Value *Src, unsigned SrcIsSigned,
  146. const FixedPointSemantics &DstSema) {
  147. return Convert(Src,
  148. FixedPointSemantics::GetIntegerSemantics(
  149. Src->getType()->getScalarSizeInBits(), SrcIsSigned),
  150. DstSema, false);
  151. }
  152. Value *CreateFixedToFloating(Value *Src, const FixedPointSemantics &SrcSema,
  153. Type *DstTy) {
  154. Value *Result;
  155. Type *OpTy = getAccommodatingFloatType(DstTy, SrcSema);
  156. // Convert the raw fixed-point value directly to floating point. If the
  157. // value is too large to fit, it will be rounded, not truncated.
  158. Result = SrcSema.isSigned() ? B.CreateSIToFP(Src, OpTy)
  159. : B.CreateUIToFP(Src, OpTy);
  160. // Rescale the integral-in-floating point by the scaling factor. This is
  161. // lossless, except for overflow to infinity which is unlikely.
  162. Result = B.CreateFMul(Result,
  163. ConstantFP::get(OpTy, std::pow(2, -(int)SrcSema.getScale())));
  164. if (OpTy != DstTy)
  165. Result = B.CreateFPTrunc(Result, DstTy);
  166. return Result;
  167. }
  168. Value *CreateFloatingToFixed(Value *Src, const FixedPointSemantics &DstSema) {
  169. bool UseSigned = DstSema.isSigned() || DstSema.hasUnsignedPadding();
  170. Value *Result = Src;
  171. Type *OpTy = getAccommodatingFloatType(Src->getType(), DstSema);
  172. if (OpTy != Src->getType())
  173. Result = B.CreateFPExt(Result, OpTy);
  174. // Rescale the floating point value so that its significant bits (for the
  175. // purposes of the conversion) are in the integral range.
  176. Result = B.CreateFMul(Result,
  177. ConstantFP::get(OpTy, std::pow(2, DstSema.getScale())));
  178. Type *ResultTy = B.getIntNTy(DstSema.getWidth());
  179. if (DstSema.isSaturated()) {
  180. Intrinsic::ID IID =
  181. UseSigned ? Intrinsic::fptosi_sat : Intrinsic::fptoui_sat;
  182. Result = B.CreateIntrinsic(IID, {ResultTy, OpTy}, {Result});
  183. } else {
  184. Result = UseSigned ? B.CreateFPToSI(Result, ResultTy)
  185. : B.CreateFPToUI(Result, ResultTy);
  186. }
  187. // When saturating unsigned-with-padding using signed operations, we may
  188. // get negative values. Emit an extra clamp to zero.
  189. if (DstSema.isSaturated() && DstSema.hasUnsignedPadding()) {
  190. Constant *Zero = Constant::getNullValue(Result->getType());
  191. Result =
  192. B.CreateSelect(B.CreateICmpSLT(Result, Zero), Zero, Result, "satmin");
  193. }
  194. return Result;
  195. }
  196. /// Add two fixed-point values and return the result in their common semantic.
  197. /// \p LHS - The left hand side
  198. /// \p LHSSema - The semantic of the left hand side
  199. /// \p RHS - The right hand side
  200. /// \p RHSSema - The semantic of the right hand side
  201. Value *CreateAdd(Value *LHS, const FixedPointSemantics &LHSSema,
  202. Value *RHS, const FixedPointSemantics &RHSSema) {
  203. auto CommonSema = getCommonBinopSemantic(LHSSema, RHSSema);
  204. bool UseSigned = CommonSema.isSigned() || CommonSema.hasUnsignedPadding();
  205. Value *WideLHS = CreateFixedToFixed(LHS, LHSSema, CommonSema);
  206. Value *WideRHS = CreateFixedToFixed(RHS, RHSSema, CommonSema);
  207. Value *Result;
  208. if (CommonSema.isSaturated()) {
  209. Intrinsic::ID IID = UseSigned ? Intrinsic::sadd_sat : Intrinsic::uadd_sat;
  210. Result = B.CreateBinaryIntrinsic(IID, WideLHS, WideRHS);
  211. } else {
  212. Result = B.CreateAdd(WideLHS, WideRHS);
  213. }
  214. return CreateFixedToFixed(Result, CommonSema,
  215. LHSSema.getCommonSemantics(RHSSema));
  216. }
  217. /// Subtract two fixed-point values and return the result in their common
  218. /// semantic.
  219. /// \p LHS - The left hand side
  220. /// \p LHSSema - The semantic of the left hand side
  221. /// \p RHS - The right hand side
  222. /// \p RHSSema - The semantic of the right hand side
  223. Value *CreateSub(Value *LHS, const FixedPointSemantics &LHSSema,
  224. Value *RHS, const FixedPointSemantics &RHSSema) {
  225. auto CommonSema = getCommonBinopSemantic(LHSSema, RHSSema);
  226. bool UseSigned = CommonSema.isSigned() || CommonSema.hasUnsignedPadding();
  227. Value *WideLHS = CreateFixedToFixed(LHS, LHSSema, CommonSema);
  228. Value *WideRHS = CreateFixedToFixed(RHS, RHSSema, CommonSema);
  229. Value *Result;
  230. if (CommonSema.isSaturated()) {
  231. Intrinsic::ID IID = UseSigned ? Intrinsic::ssub_sat : Intrinsic::usub_sat;
  232. Result = B.CreateBinaryIntrinsic(IID, WideLHS, WideRHS);
  233. } else {
  234. Result = B.CreateSub(WideLHS, WideRHS);
  235. }
  236. // Subtraction can end up below 0 for padded unsigned operations, so emit
  237. // an extra clamp in that case.
  238. if (CommonSema.isSaturated() && CommonSema.hasUnsignedPadding()) {
  239. Constant *Zero = Constant::getNullValue(Result->getType());
  240. Result =
  241. B.CreateSelect(B.CreateICmpSLT(Result, Zero), Zero, Result, "satmin");
  242. }
  243. return CreateFixedToFixed(Result, CommonSema,
  244. LHSSema.getCommonSemantics(RHSSema));
  245. }
  246. /// Multiply two fixed-point values and return the result in their common
  247. /// semantic.
  248. /// \p LHS - The left hand side
  249. /// \p LHSSema - The semantic of the left hand side
  250. /// \p RHS - The right hand side
  251. /// \p RHSSema - The semantic of the right hand side
  252. Value *CreateMul(Value *LHS, const FixedPointSemantics &LHSSema,
  253. Value *RHS, const FixedPointSemantics &RHSSema) {
  254. auto CommonSema = getCommonBinopSemantic(LHSSema, RHSSema);
  255. bool UseSigned = CommonSema.isSigned() || CommonSema.hasUnsignedPadding();
  256. Value *WideLHS = CreateFixedToFixed(LHS, LHSSema, CommonSema);
  257. Value *WideRHS = CreateFixedToFixed(RHS, RHSSema, CommonSema);
  258. Intrinsic::ID IID;
  259. if (CommonSema.isSaturated()) {
  260. IID = UseSigned ? Intrinsic::smul_fix_sat : Intrinsic::umul_fix_sat;
  261. } else {
  262. IID = UseSigned ? Intrinsic::smul_fix : Intrinsic::umul_fix;
  263. }
  264. Value *Result = B.CreateIntrinsic(
  265. IID, {WideLHS->getType()},
  266. {WideLHS, WideRHS, B.getInt32(CommonSema.getScale())});
  267. return CreateFixedToFixed(Result, CommonSema,
  268. LHSSema.getCommonSemantics(RHSSema));
  269. }
  270. /// Divide two fixed-point values and return the result in their common
  271. /// semantic.
  272. /// \p LHS - The left hand side
  273. /// \p LHSSema - The semantic of the left hand side
  274. /// \p RHS - The right hand side
  275. /// \p RHSSema - The semantic of the right hand side
  276. Value *CreateDiv(Value *LHS, const FixedPointSemantics &LHSSema,
  277. Value *RHS, const FixedPointSemantics &RHSSema) {
  278. auto CommonSema = getCommonBinopSemantic(LHSSema, RHSSema);
  279. bool UseSigned = CommonSema.isSigned() || CommonSema.hasUnsignedPadding();
  280. Value *WideLHS = CreateFixedToFixed(LHS, LHSSema, CommonSema);
  281. Value *WideRHS = CreateFixedToFixed(RHS, RHSSema, CommonSema);
  282. Intrinsic::ID IID;
  283. if (CommonSema.isSaturated()) {
  284. IID = UseSigned ? Intrinsic::sdiv_fix_sat : Intrinsic::udiv_fix_sat;
  285. } else {
  286. IID = UseSigned ? Intrinsic::sdiv_fix : Intrinsic::udiv_fix;
  287. }
  288. Value *Result = B.CreateIntrinsic(
  289. IID, {WideLHS->getType()},
  290. {WideLHS, WideRHS, B.getInt32(CommonSema.getScale())});
  291. return CreateFixedToFixed(Result, CommonSema,
  292. LHSSema.getCommonSemantics(RHSSema));
  293. }
  294. /// Left shift a fixed-point value by an unsigned integer value. The integer
  295. /// value can be any bit width.
  296. /// \p LHS - The left hand side
  297. /// \p LHSSema - The semantic of the left hand side
  298. /// \p RHS - The right hand side
  299. Value *CreateShl(Value *LHS, const FixedPointSemantics &LHSSema, Value *RHS) {
  300. bool UseSigned = LHSSema.isSigned() || LHSSema.hasUnsignedPadding();
  301. RHS = B.CreateIntCast(RHS, LHS->getType(), /*IsSigned=*/false);
  302. Value *Result;
  303. if (LHSSema.isSaturated()) {
  304. Intrinsic::ID IID = UseSigned ? Intrinsic::sshl_sat : Intrinsic::ushl_sat;
  305. Result = B.CreateBinaryIntrinsic(IID, LHS, RHS);
  306. } else {
  307. Result = B.CreateShl(LHS, RHS);
  308. }
  309. return Result;
  310. }
  311. /// Right shift a fixed-point value by an unsigned integer value. The integer
  312. /// value can be any bit width.
  313. /// \p LHS - The left hand side
  314. /// \p LHSSema - The semantic of the left hand side
  315. /// \p RHS - The right hand side
  316. Value *CreateShr(Value *LHS, const FixedPointSemantics &LHSSema, Value *RHS) {
  317. RHS = B.CreateIntCast(RHS, LHS->getType(), false);
  318. return LHSSema.isSigned() ? B.CreateAShr(LHS, RHS) : B.CreateLShr(LHS, RHS);
  319. }
  320. /// Compare two fixed-point values for equality.
  321. /// \p LHS - The left hand side
  322. /// \p LHSSema - The semantic of the left hand side
  323. /// \p RHS - The right hand side
  324. /// \p RHSSema - The semantic of the right hand side
  325. Value *CreateEQ(Value *LHS, const FixedPointSemantics &LHSSema,
  326. Value *RHS, const FixedPointSemantics &RHSSema) {
  327. auto CommonSema = getCommonBinopSemantic(LHSSema, RHSSema);
  328. Value *WideLHS = CreateFixedToFixed(LHS, LHSSema, CommonSema);
  329. Value *WideRHS = CreateFixedToFixed(RHS, RHSSema, CommonSema);
  330. return B.CreateICmpEQ(WideLHS, WideRHS);
  331. }
  332. /// Compare two fixed-point values for inequality.
  333. /// \p LHS - The left hand side
  334. /// \p LHSSema - The semantic of the left hand side
  335. /// \p RHS - The right hand side
  336. /// \p RHSSema - The semantic of the right hand side
  337. Value *CreateNE(Value *LHS, const FixedPointSemantics &LHSSema,
  338. Value *RHS, const FixedPointSemantics &RHSSema) {
  339. auto CommonSema = getCommonBinopSemantic(LHSSema, RHSSema);
  340. Value *WideLHS = CreateFixedToFixed(LHS, LHSSema, CommonSema);
  341. Value *WideRHS = CreateFixedToFixed(RHS, RHSSema, CommonSema);
  342. return B.CreateICmpNE(WideLHS, WideRHS);
  343. }
  344. /// Compare two fixed-point values as LHS < RHS.
  345. /// \p LHS - The left hand side
  346. /// \p LHSSema - The semantic of the left hand side
  347. /// \p RHS - The right hand side
  348. /// \p RHSSema - The semantic of the right hand side
  349. Value *CreateLT(Value *LHS, const FixedPointSemantics &LHSSema,
  350. Value *RHS, const FixedPointSemantics &RHSSema) {
  351. auto CommonSema = getCommonBinopSemantic(LHSSema, RHSSema);
  352. Value *WideLHS = CreateFixedToFixed(LHS, LHSSema, CommonSema);
  353. Value *WideRHS = CreateFixedToFixed(RHS, RHSSema, CommonSema);
  354. return CommonSema.isSigned() ? B.CreateICmpSLT(WideLHS, WideRHS)
  355. : B.CreateICmpULT(WideLHS, WideRHS);
  356. }
  357. /// Compare two fixed-point values as LHS <= RHS.
  358. /// \p LHS - The left hand side
  359. /// \p LHSSema - The semantic of the left hand side
  360. /// \p RHS - The right hand side
  361. /// \p RHSSema - The semantic of the right hand side
  362. Value *CreateLE(Value *LHS, const FixedPointSemantics &LHSSema,
  363. Value *RHS, const FixedPointSemantics &RHSSema) {
  364. auto CommonSema = getCommonBinopSemantic(LHSSema, RHSSema);
  365. Value *WideLHS = CreateFixedToFixed(LHS, LHSSema, CommonSema);
  366. Value *WideRHS = CreateFixedToFixed(RHS, RHSSema, CommonSema);
  367. return CommonSema.isSigned() ? B.CreateICmpSLE(WideLHS, WideRHS)
  368. : B.CreateICmpULE(WideLHS, WideRHS);
  369. }
  370. /// Compare two fixed-point values as LHS > RHS.
  371. /// \p LHS - The left hand side
  372. /// \p LHSSema - The semantic of the left hand side
  373. /// \p RHS - The right hand side
  374. /// \p RHSSema - The semantic of the right hand side
  375. Value *CreateGT(Value *LHS, const FixedPointSemantics &LHSSema,
  376. Value *RHS, const FixedPointSemantics &RHSSema) {
  377. auto CommonSema = getCommonBinopSemantic(LHSSema, RHSSema);
  378. Value *WideLHS = CreateFixedToFixed(LHS, LHSSema, CommonSema);
  379. Value *WideRHS = CreateFixedToFixed(RHS, RHSSema, CommonSema);
  380. return CommonSema.isSigned() ? B.CreateICmpSGT(WideLHS, WideRHS)
  381. : B.CreateICmpUGT(WideLHS, WideRHS);
  382. }
  383. /// Compare two fixed-point values as LHS >= RHS.
  384. /// \p LHS - The left hand side
  385. /// \p LHSSema - The semantic of the left hand side
  386. /// \p RHS - The right hand side
  387. /// \p RHSSema - The semantic of the right hand side
  388. Value *CreateGE(Value *LHS, const FixedPointSemantics &LHSSema,
  389. Value *RHS, const FixedPointSemantics &RHSSema) {
  390. auto CommonSema = getCommonBinopSemantic(LHSSema, RHSSema);
  391. Value *WideLHS = CreateFixedToFixed(LHS, LHSSema, CommonSema);
  392. Value *WideRHS = CreateFixedToFixed(RHS, RHSSema, CommonSema);
  393. return CommonSema.isSigned() ? B.CreateICmpSGE(WideLHS, WideRHS)
  394. : B.CreateICmpUGE(WideLHS, WideRHS);
  395. }
  396. };
  397. } // end namespace llvm
  398. #endif // LLVM_IR_FIXEDPOINTBUILDER_H