Stream: project-inline-asm

Topic: Interaction with const evaluation


Amanieu (Mar 15 2020 at 15:19, on Zulip):

Is the following code valid?

unsafe fn read_from_port<const port: u16>() -> u8 {
    let value: u8;
    if port <= 255 {
        asm!("in al, {}", const port, out("al") value);
    } else {
        asm!("in al, dx", in("dx") port, out("al") value);
    }
    value
}
Amanieu (Mar 15 2020 at 15:21, on Zulip):

The issue here is that the in instruction only accepts immediates in the range 0 - 255. However because of the way we currently perform codegen, the invalid asm (first branch of the if) will never reach LLVM.

Amanieu (Mar 15 2020 at 15:21, on Zulip):

(Assuming that port > 255)

bjorn3 (Mar 15 2020 at 15:22, on Zulip):

I don't believe dead code elimination is guaranteed. At least with -Zmir-opt-level=0 it shouldn't be performed.

Amanieu (Mar 15 2020 at 15:23, on Zulip):

Even then, LLVM may still eliminate it before it reaches the assembler.

Amanieu (Mar 15 2020 at 15:23, on Zulip):

Hmm, actually I know a way of fixing this particular example: just use port & 255.

Josh Triplett (Mar 17 2020 at 04:12, on Zulip):

@Amanieu Or port as u8.

XAMPPRocky (Mar 17 2020 at 08:10, on Zulip):

In 1.43.0, you'll be able to write port & u8::MAX with no imports, which helps avoid magic numbers and as. :smiley:

Last update: Jul 02 2020 at 19:55UTC