假装 64 位整数具有无限范围
我正在为一种专有语言实现一个编译器。
该语言有一种内置的整数类型,范围不受限制。有时变量使用较小的类型表示,例如,如果 a
和 b
是整型变量,但 b
仅分配表达式<的值代码>a % 100000 或a & 0xFFFFFF
,则 b
可以表示为 Int32
。
我正在考虑实施以下优化。假设它看到与此 C# 方法等效的内容:
public static void Main(string[] args)
{
BigInt i = 0;
while (true)
{
DoStuff(i++);
}
}
从数学上来说,转换为以下内容无效有效:
public static void Main(string[] args)
{
Int64 i = 0;
while (true)
{
DoStuff(i++);
}
}
因为我已将 BigInt
替换为 Int64
>,如果循环永远运行,最终会溢出。不过我怀疑我可以忽略这种可能性,因为:
i
被初始化为 0,并且只能通过重复添加 1 来修改,这意味着将需要 263 迭代 。- 如果
DoStuff
做了任何有用的工作,那么i
需要几个世纪的时间(根据我非常粗略的测试推断)才能溢出 运行该程序的机器不会持续那么久。不仅如此,它的架构可能也不会持续那么久,所以我也不需要担心它在迁移到新硬件的虚拟机上运行。 - 如果
DoStuff
没有做任何有用的工作,操作员最终会注意到它正在浪费 CPU 周期并终止进程
那么我需要担心什么情况?
有编译器已经使用这个 hack 了吗?
I am implementing a compiler for a proprietary language.
The language has one built-in integer type, with unlimited range. Sometimes variables are represented using smaller types, for example if a
and b
are integer variables but b
is only ever assigned the value of the expression a % 100000
or a & 0xFFFFFF
, then b
can be represented as an Int32
instead.
I am considering implementing the following optimization. Suppose it sees the equivalent of this C# method:
public static void Main(string[] args)
{
BigInt i = 0;
while (true)
{
DoStuff(i++);
}
}
Mathematically speaking, transforming into the following is not valid:
public static void Main(string[] args)
{
Int64 i = 0;
while (true)
{
DoStuff(i++);
}
}
Because I have replaced a BigInt
with an Int64
, which will eventually overflow if the loop runs forever. However I suspect I can ignore this possibility because:
i
is initialized to 0 and is modified only by repeatedly adding 1 to it, which means that will take 263 iterations of the loop to make it overflow- If
DoStuff
does any useful work, it will take centuries (extrapolated from my very crude tests) fori
to overflow. The machine the program runs on will not last that long. Not only that but its architecture probably won't last that long either, so I also don't need to worry about it running on a VM that is migrated to new hardware. - If
DoStuff
does not do any useful work, an operator will eventually notice that it is wasting CPU cycles and kill the process
So what scenarios do I need to worry about?
Do any compilers already use this hack?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯..在我看来你已经回答了你的问题。
但我怀疑这个问题是否真的有任何有用的结果。
如果默认情况下唯一的内置整数具有无限范围,那么对于循环计数器等典型用法来说,它的效率应该不会低下。
我认为仅在实际溢出发生后扩展值范围(并为变量分配更多内存)对于这种语言来说并不困难。
Well.. It seems to me you already answered your question.
But I doubt the question really has any useful outcome.
If the only built-in integer has unlimited range by default it should not inefficient for typical usage such as a loop counter.
I think expanding value range (and allocate more memory to the variable) only after actual overflow occur won't that hard for such language.