Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Go optimize out unreachable if-statements?

Go has a very unfortunate lack of built-in assertions. I want to implement them this way:

const ASSERT = true

func SomeFunction() {
        if ASSERT && !some_condition_that_should_always_be_true() {
                panic("Error message or object.")
        }
}

My question is will the if-statement be optimized out if I define const ASSERT = false?

like image 289
Matt Avatar asked Apr 15 '15 15:04

Matt


People also ask

When unreachable code?

Unreachable code is an atom or sequence of atoms which cannot be executed because there is no way for the flow of control to reach that sequence of atoms. For example, in the following atom sequence the MUL, SUB, and ADD atoms will never be executed because of the unconditional jump preceding them.

What does unreachable code mean in Java?

Unreachable code error occurs when the code can't be compiled due to a variety of reasons, some of which include: infinite loop, return statement before the unreachable line of code.

Which tool should be used to detect unreachable code?

GNATprove detects and issues warnings about both the dead code and the unreachable code.


1 Answers

As noted by the people in the comments to your question, it's implementation-specific.

gc does remove it. You can build your program with -gcflags '-S' and see that the ASSERT part is not in the binary.

E.g. compile the following code with -gcflags '-S', and you'll see that the code on lines 8 and 9 is included, but change Assert to be false, and they won't be there in the asm listing.

package main

const Assert = true

var cond = true

func main() {
    if Assert && !cond {
        panic("failed")
    }
}

EDIT:

As for gccgo, it removes this code at -O1 and above. You can see it by compiling the same code with

go build -compiler gccgo -gccgoflags '-O1' main.go

and then doing

objdump -S main

to see the annotated assembly.

like image 129
Ainar-G Avatar answered Nov 10 '22 22:11

Ainar-G