如何为浮点异常生成陷阱?

How are traps generated for floating point exceptions?

我想知道 glibc 库中的哪些代码和文件负责在启用陷阱时为浮点异常生成陷阱。

目前,RISC-V 的 GCC 不捕获浮点异常。我有兴趣添加此功能。因此,我正在研究如何在 GCC for x86 中实现此功能。

我知道我们可以按照这个[问题]中的描述捕获信号 (Trapping floating-point overflow in C) 但我想了解有关其工作原理的更多详细信息。

我查看了 glibc/math 中的文件,根据我的说法,这些文件以某种形式负责生成像

这样的陷阱
fenv.h
feenablxcpt.c
fegetexpect.c
feupdateenv.c

和许多其他以 fe 开头的文件。

所有这些文件也存在于 RISC-V 的 glibc 中。我不能 找出 glibc for x86 如何生成陷阱。

这些 traps are usually generated by the hardware itself, at the instruction set architecture (ISA) 级别。特别是在 x86-64 上。

I want to know which code and files in the glibc library are responsible for generating traps for floating point exceptions when traps are enabled.

所以没有这样的文件。但是,Linux...上的 operating system kernel (notably with signal(7)-s) 正在将陷阱转换为其他内容。

请详细阅读Operating Systems: Three Easy Pieces for more. And study the x86-64指令集。

一个更熟悉的例子是整数除以零。在大多数硬件上,这会产生机器陷阱(或机器 exception), handled by the kernel. On some hardware (IIRC, PowerPC), its gives -1 as a result and sets some bit in a status register. Further machine code could test that bit. I believe that the GCC compiler would, in some cases and with some optimizations 禁用,在每次除法后生成这样的测试。但不需要这样做。

C语言(阅读n1570, which practically is the C11 standard) has defined the notion of undefined behavior to handle such situations the most quickly and simply possible. Read Lattner's What every C programmer should know about undefined behavior博客。

既然你提到 RISC-V, read about the RISC philosophy of the previous century, and be aware that designing out-of-order and super-scalar 处理器需要大量的工程工作。我的猜测是,如果你在 x86-64 上投入的研发(这意味着数百亿美元或欧元)与英特尔一样多,或者在较小程度上,AMD 在 RISC-V 芯片上投入的资金,你可以获得与当前 x86-64 处理器相当的性能。请注意,SPARC 或 PowerPC(或者可能是 ARM)芯片是 RISC-like,它们最好的处理器在性能上几乎与英特尔芯片相当,但其研发投资可能比英特尔在其微处理器上的投入少十倍。