Help us understand the problem. What is going on with this article?

LDCで無限ループが動かなくて困ったとき

みなさんもLDCで無限ループを含む関数を使っている場合、最適化フラグを渡していると予期しない挙動となることがよくあるんじゃないかと思います。

ubyte infiniteLoop()
{
    for (;;) {  }
}

void main()
{
    auto x = infiniteLoop();
}
$ ldc2 -version| head -1
LDC - the LLVM D compiler (1.18.0):
$ ldc2 -O3 -run infiniteloop.d  # 本来は無限ループなので返ってこないことを期待
Error: /tmp/infiniteloop-b2ee371-8ab556 failed with status: 1

これはLLVMが最適化を行った結果として空のループを未定義動作にしてしまうのが問題なのですが、ときには困ることもあるわけです。

じゃあどうすればいいかというと、まさにその状態を回避するためにあるllvm.sideeffectを使うことで回避できます。

pragma(LDC_intrinsic, "llvm.sideeffect")
void llvm_sideeffect();

ubyte infiniteLoop()
{
    for (;;) {
        llvm_sideeffect();
    }
}

void main()
{
    auto x = infiniteLoop();
}

ちゃんとループが動いてますね。

$ ldc2 -O3 -run infiniteloop.d
(...) # 諸君らの環境でも無限ループが実行されているはずだ
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away