【问题标题】:Get the original parsed number from FloatingLiteral/APFloat从 FloatingLiteral/APFloat 获取原始解析数字
【发布时间】:2015-12-01 14:38:25
【问题描述】:

我开始使用 clang 作为我目前正在研究的有界模型检查器的前端,我需要一些关于从 AST 获得的浮点数的帮助。

例如,对于这个程序:

int main()
{
  float a = 1.0f;
  long double b = 5567.765434376l;
}

生成的 AST 是:

FunctionDecl 0x1dea160 </home/mramalho/main.c:3:1, line:7:1> line:3:5 main 'int ()'
`-CompoundStmt 0x1dea368 <line:4:1, line:7:1>
  |-DeclStmt 0x1dea298 <line:5:3, col:17>
  | `-VarDecl 0x1dea218 <col:3, col:13> col:9 a 'float' cinit
  |   `-FloatingLiteral 0x1dea278 <col:13> 'float' 1.000000e+00
  `-DeclStmt 0x1dea350 <line:6:3, col:34>
    `-VarDecl 0x1dea2c0 <col:3, col:19> col:15 b 'long double' cinit
      `-FloatingLiteral 0x1dea320 <col:19> 'long double' 5.567765e+03

我从 .getValue() 获得的 APFLoat 数字没有多大帮助,因为它存储为已转换的数字。

特别想知道是否有可能获得原始数字(在上面的示例中,1.0f 和 5567.765434376l)。如果可能,在适用时使用 (+/-)Inf 和/或 NaN 的字符串会很好,但不是必需的。

我尝试了几种方法,但最终总是得到原始数字的修剪版本。

我最好的选择是方法 convertFromString 和 struct DecimalInfo(都在 APFloat 上),但我找不到找到它们的方法,因为在我获得 FloatingLiteral 时已经创建了数字。

谢谢。

【问题讨论】:

    标签: c++ clang llvm llvm-clang llvm-ir


    【解决方案1】:

    不知道是否可以回答您自己的问题,但我是这样解决的:

    llvm::SmallVector<char, 32> string;
    val.toString(string, 32, 0);
    

    其中 val 是 APFloat。来自文档:

    /// Converts this value into a decimal string.
    ///
    /// \param FormatPrecision The maximum number of digits of
    ///   precision to output.  If there are fewer digits available,
    ///   zero padding will not be used unless the value is
    ///   integral and small enough to be expressed in
    ///   FormatPrecision digits.  0 means to use the natural
    ///   precision of the number.
    /// \param FormatMaxPadding The maximum number of zeros to
    ///   consider inserting before falling back to scientific
    ///   notation.  0 means to always use scientific notation.
    ///
    /// Number       Precision    MaxPadding      Result
    /// ------       ---------    ----------      ------
    /// 1.01E+4              5             2       10100
    /// 1.01E+4              4             2       1.01E+4
    /// 1.01E+4              5             1       1.01E+4
    /// 1.01E-2              5             2       0.0101
    /// 1.01E-2              4             2       0.0101
    /// 1.01E-2              4             1       1.01E-2
    

    然后就是简单的迭代来获取值。

    它还为无穷大值提供“Inf”字符串。

    【讨论】:

    • 不仅可以,而且值得鼓励。很高兴你最终到达那里。
    猜你喜欢
    • 2022-06-30
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多