# \[Pre-RFC #2\]: Inline assembly

**URL:** <https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310>\
**Category:** language design\
**Created:** [November 17, 2019, 11:17pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310 "2019-11-17T23:17:59Z")\
**Posts on this page:** 20\
**Page:** 2

<div class="post-metadata">

**Author:** ![comex](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/comex/32/2587_2.png) [@comex](https://internals.rust-lang.org/u/comex)\
**Post date:** [November 18, 2019, 6:47am UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/21 "2019-11-18T06:47:48Z")

</div>

> [@mcy](#):
>
> > Just because you don't return doesn't mean you can trash any objects that are currently on the stack.
> 
> Fine, but on single-threaded boot loader I'm working in, I don't _have_ other threads (not to speak of OS infrastructure for Rayon...), so this _should_ be safe. I think we need to have a discussion as to when it is acceptable to trash your stack, unfortunately. =(

Yep. It's a question of whether you're certain what the code in your call stack is doing. Normally, all code is allowed to assume that stack variables won't be trashed before their destructors are run. In theory, even the `core` crate could randomly decide to start taking advantage of that assumption. Any function that takes a callback, like `Option::map`, could be changed to start maintaining a global linked list of all currently running instances of that function... for some reason:

```rust
fn map(f: impl FnOnce(whatever) -> whatever) -> whatever {
    let mut link: LinkedListEntry;
    add_to_global_linked_list(&mut link);
    f(); // call user's callback
    remove_from_global_linked_list(&mut link);
}

```

Is that likely to happen? No. But I don't think there's currently any _guarantee_ that it won't happen.

---

<div class="post-metadata">

**Author:** ![josh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/josh/32/5934_2.png) [@josh](https://internals.rust-lang.org/u/josh)\
**Post date:** [November 18, 2019, 6:48am UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/22 "2019-11-18T06:48:39Z")

</div>

> [@Amanieu](#):
>
> Unless you're on a "fun" architecture like Itanium where a register can contain NaT (not-a-thing) that faults if you try to write it to memory. If you want to use `asm!` to freeze some undefined bytes, use memory instead of a register.

Sounds like the semantics will have to be architecture-specific then, which doesn't seem surprising.

> [@Amanieu](#):
>
> If you are compiling a shared library, there is no way to access a symbol outside the current shared library except through the GOT.

A symbol outside the current crate but visible to the current crate isn't necessarily outside the current shared library.

Also, it should be possible to pass in and call through pointers to functions in the GOT, with well-defined semantics.

---

<div class="post-metadata">

**Author:** ![spunit262](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/spunit262/32/5677_2.png) [@spunit262](https://internals.rust-lang.org/u/spunit262)\
**Post date:** [November 18, 2019, 6:51am UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/23 "2019-11-18T06:51:07Z")

</div>

> [@Amanieu](#):
>
> `lateout` must be used instead of `out` if you are specifying the same explicit register as an `in` .

We should avoid implicit tying completely. If we want tying we should have proper syntax for it.

> [@Amanieu](#):
>
> **in** `out(<reg>) <expr>`
> 
> - `<expr>` must be a **(possibly uninitialized)** place expression, to which the contents of the allocated register is written to at the end of the asm code.

[emphasis mine]

I assume this is a copy paste error?

> [@Amanieu](#):
>
> Should we allow passing a value expression (rvalue) as an `inout` operand? The semantics would be that of an input which is allowed to be clobbered (i.e. the output is simply discarded).

I think requiring tying to an explicit `out _` would be more readable.

> [@Amanieu](#):
>
> Do we need to add support for tied operands? Most use cases for those should already be covered by `inout` .

Tying is more economic and readable than forcing the use of a temporary.

I'm not sure what the syntax should be, but I think they should be specified next to each other without a comma between. Maybe some thing like `in(reg) expr => out place`.

> [@Amanieu](#):
>
> GCC supports `%=` which generates a unique identifier per instance of an asm block. This is guaranteed to be unique even if the asm block is duplicated (e.g. because of inlining).
> 
> We can support this in the future with a special input operand type.

I think just `sym _` should work for this.

---

<div class="post-metadata">

**Author:** ![comex](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/comex/32/2587_2.png) [@comex](https://internals.rust-lang.org/u/comex)\
**Post date:** [November 18, 2019, 6:52am UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/24 "2019-11-18T06:52:26Z")

</div>

> [@josh](#):
>
> Also, it should be possible to pass in and call through pointers to functions in the GOT, with well-defined semantics.

If you pass in the function pointer with `in(reg)`, sure. But if you want to reference it by name, the code sequence required does depend on the linking style / platform.

---

<div class="post-metadata">

**Author:** ![comex](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/comex/32/2587_2.png) [@comex](https://internals.rust-lang.org/u/comex)\
**Post date:** [November 18, 2019, 6:56am UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/25 "2019-11-18T06:56:18Z")

</div>

> [@spunit262](#):
>
> Tying is more economic and readable than forcing the use of a temporary.
> 
> I'm not sure what the syntax should be, but I think they should be specified next to each other without a comma between. Maybe some thing like `in(reg) expr => out place` .

For what it's worth, I'd rather force a temporary. Inline assembly is complicated enough as it is; if you can omit a feature with no performance loss and not too much ergonomic loss, I'd rather omit it. YMMV.

---

<div class="post-metadata">

**Author:** ![bjorn3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bjorn3/32/2736_2.png) [@bjorn3](https://internals.rust-lang.org/u/bjorn3)\
**Post date:** [November 18, 2019, 10:28am UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/26 "2019-11-18T10:28:46Z")

</div>

Can we have a `#[cfg]` feature to detect the presence of `llvm_asm!`?

---

<div class="post-metadata">

**Author:** ![bill\_myers](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bill_myers/32/4085_2.png) [@bill\_myers](https://internals.rust-lang.org/u/bill_myers)\
**Post date:** [November 18, 2019, 1:05pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/27 "2019-11-18T13:05:46Z")

</div>

How about stabilizing llvm\_asm!("\<arch\>", \<current\_syntax\>) as a function that returns true if the arch is correct and the backend supports this particular syntax (as specified by LLVM) and false otherwise? (as well as check\_llvm\_asm! that only checks but does nothing)

This requires almost no effort to implement in rustc, and allows Cranelift to implement any subset of the LLVM assembly syntax, returning false for anything else and letting the generic fallback code (that is already needed to support unknown architectures) handle it.

---

<div class="post-metadata">

**Author:** ![bjorn3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bjorn3/32/2736_2.png) [@bjorn3](https://internals.rust-lang.org/u/bjorn3)\
**Post date:** [November 18, 2019, 1:10pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/28 "2019-11-18T13:10:18Z")

</div>

People will probably forget to check the return value, likely causing wrong results or UB on unknown archs instead of the current compile error.

---

<div class="post-metadata">

**Author:** ![bill\_myers](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bill_myers/32/4085_2.png) [@bill\_myers](https://internals.rust-lang.org/u/bill_myers)\
**Post date:** [November 18, 2019, 1:31pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/29 "2019-11-18T13:31:51Z")

</div>

#[must\_use] equivalent solves that

---

<div class="post-metadata">

**Author:** ![bjorn3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bjorn3/32/2736_2.png) [@bjorn3](https://internals.rust-lang.org/u/bjorn3)\
**Post date:** [November 18, 2019, 1:45pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/30 "2019-11-18T13:45:26Z")

</div>

1. that is just a lint. people will ignore it I think
2. returning a bool will be confusing for people who havent read the docs.

What about something like:

```rust
match_asm! {
    x86 | x86_64 => "cli";
    arm | aarch64 => "cpsid i";
    _ => {
        // arbitrary rust code
        panic!("cant disable interrupts");
    }
}

```

---

<div class="post-metadata">

**Author:** ![Amanieu](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/amanieu/32/4095_2.png) [@Amanieu](https://internals.rust-lang.org/u/Amanieu)\
**Post date:** [November 18, 2019, 1:57pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/31 "2019-11-18T13:57:18Z")

</div>

Honestly I feel that this sort of additional functionality can be left to [crates.io](http://crates.io). I would prefer focusing on the core asm functionality in this RFC.

---

<div class="post-metadata">

**Author:** ![bjorn3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/bjorn3/32/2736_2.png) [@bjorn3](https://internals.rust-lang.org/u/bjorn3)\
**Post date:** [November 18, 2019, 2:07pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/32 "2019-11-18T14:07:54Z")

</div>

For matching on target arch I agree. We already have cfg\_if and `cfg(target_arch)`. For the support of inline asm, it can't be part of a crate. It has to be part of rustc.

---

<div class="post-metadata">

**Author:** ![ckaran](https://avatars.discourse-cdn.com/v4/letter/c/f475e1/32.png) [@ckaran](https://internals.rust-lang.org/u/ckaran)\
**Post date:** [November 18, 2019, 4:26pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/33 "2019-11-18T16:26:33Z")

</div>

How about extending `asm!()` to include the architecture that the block is for? If the compiler is asked to compile for the wrong architecture, it will then be able to detect that there is a problem. Similar to what @bill_myers [said earlier](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/27):

```rust
asm!(x86_64, "foo", ...);

```

Alternatively, the first argument could be some kind of struct that is defined at compile time. e.g.

```rust
#[derive(Debug, Copy, Clone)]
enum Architecture {
    x86_64,
    ARM,
    RISCV,
    WASM_1_0,
    // etc., etc., etc
}

#[derive(Debug)]
struct AsmParameters {
    architecture: Architecture,
    formal_equivalent: &'static str,
}

impl AsmParameters {
    const fn new() -> AsmParameters {
        AsmParameters {
            architecture: Architecture::x86_64,
            formal_equivalent: "",
        }
    }

    const fn architecture(&self, architecture: Architecture) -> AsmParameters {
        AsmParameters {
            architecture,
            formal_equivalent: self.formal_equivalent,
        }
    }

    const fn formal_equivalent(&self, formal_equivalent: &'static str) -> AsmParameters {
        AsmParameters {
            architecture: self.architecture,
            formal_equivalent: formal_equivalent,
        }
    }
}

fn main() {
    const ASM_PARAMETERS: AsmParameters = AsmParameters::new()
        .architecture(Architecture::ARM)
        .formal_equivalent("Something and SMT solver can ingest.");

    unsafe {
        asm!(ASM_PARAMETERS, "Everything in the RFC so far.")
    }
}

```

The advantage of this method is that we can add in new parameters in the future as needed. This will handle many of the problems that were brought up in the earlier conversation about how to stabilize `asm!()`

---

<div class="post-metadata">

**Author:** ![mcy](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mcy/32/6512_2.png) [@mcy](https://internals.rust-lang.org/u/mcy)\
**Post date:** [November 18, 2019, 4:30pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/34 "2019-11-18T16:30:37Z")

</div>

This is... kind of a rabbit hole. Do you distinguish things like SSE? AVX? NEON? The litany of RISC-V extensions? If such a feature exists, and I write RISC-V code that has `mul; mulh`, it would be nice to require the `M` extension. in addition to _just_ RISC-V.

(There's also some muttering about thumb to be made here but I'm not an ARM person.)

---

<div class="post-metadata">

**Author:** ![CAD97](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cad97/32/3460_2.png) [@CAD97](https://internals.rust-lang.org/u/CAD97)\
**Post date:** [November 18, 2019, 4:31pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/35 "2019-11-18T16:31:35Z")

</div>

Personally, I'm in favor of somehow specifying the expected architecture/assembler pair in the `asm!` invocation. That would explicitly handle Intel vs AT&T vs whatever assembly language as well.

This is a very minor concern, though. I just want the default to be uniformly "system assembler" or "specified assembler". (Plus, spitting asm to an assembler it isn't targeting is just asking for arcane issues.)

---

<div class="post-metadata">

**Author:** ![josh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/josh/32/5934_2.png) [@josh](https://internals.rust-lang.org/u/josh)\
**Post date:** [November 18, 2019, 4:45pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/36 "2019-11-18T16:45:44Z")

</div>

Having to manually specify the architecture or similar in an asm directive makes every such directive more verbose, and I don't think it provides commensurate benefit.

---

<div class="post-metadata">

**Author:** ![Tom-Phinney](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tom-phinney/32/3299_2.png) [@Tom-Phinney](https://internals.rust-lang.org/u/Tom-Phinney)\
**Post date:** [November 18, 2019, 4:51pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/37 "2019-11-18T16:51:07Z")

</div>

> [@mcy](#):
>
> Do you distinguish things like SSE? AVX? NEON? The litany of RISC-V extensions? If such a feature exists, and I write RISC-V code that has `mul; mulh` , it would be nice to require the `M` extension. in addition to _just_ RISC-V.

I was about to post a similar concern. When writing assembly code for RISC-V I would like to write the efficient variant for systems where the `M` extension is present, and a less-efficient but performant variant for systems where that extension is absent. The syntax for this needs to identify the base architecture, as well as indicate the presence of absence of specific variants while omitting all the irrelevant variants. RISC-V is the poster-child for this problem, as it has many mostly-disjoint standard, proposed standard, and user-defined variants, as well as the group variant `G` (which is short for `I`+`M`+`A`+`F`+`D`) that probably should not be permitted in the list.)

---

<div class="post-metadata">

**Author:** ![ckaran](https://avatars.discourse-cdn.com/v4/letter/c/f475e1/32.png) [@ckaran](https://internals.rust-lang.org/u/ckaran)\
**Post date:** [November 18, 2019, 5:09pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/38 "2019-11-18T17:09:07Z")

</div>

Not as much a rabbit hole as you'd think though; as @Amanieu stated in the RFC:

> [@Amanieu](#):
>
> The initial implementation of this feature will focus on the ARM and x86 architectures. Support for more architectures will be added based on user demand.

which suggests that there will be a limited set of architectures supported at any one time. As for variants, etc., you could have something like a set of nested enums, or something more esoteric.

That said, I _do_ see your point about how this can lead to a combinatorial explosion. I don't really see a good way around it while at the same time giving the compiler some extra information so that it can do bounds checking on assembly.

In addition, this makes it possible to decide on what _new_ parameters we want to add to the `asm!()` macro in the future. Even if you don't like my `Architecture` example, what about some kind of `rust equivalent` key, or something that an SMT solver can ingest? That will make it possible for the compiler to check the borrow rules even on assembly that it doesn't understand. This would take some work, and I'm not suggesting that it be done now, but it could be added later, if it looks like it's needed.

---

<div class="post-metadata">

**Author:** ![mcy](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mcy/32/6512_2.png) [@mcy](https://internals.rust-lang.org/u/mcy)\
**Post date:** [November 18, 2019, 5:26pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/39 "2019-11-18T17:26:25Z")

</div>

> [@ckaran](#):
>
> which suggests that there will be a limited set of architectures supported at any one time.

Right, but the concern here is that ISAs can vary wildly in shape and size (some examples from this thread, Itanium's hilarious same-core ambi-endianess, NaT values, and RISC-V's O(infinity) extension combinations). If we choose to specify "ISA checking" of assembly, we need to be extremely careful that we do not accidentally exclude useful predicates for non-mainstream ISAs.

I think this RFC should include some variant of "here is a complete list of the boxes you need to tick to implement support for a new ISA". This should involve, at a minimum, mapping register constraint classes, but I suspect there are a lot more constraints too, like "implementation defined behavior" definitions (e.g., I think further up someone muttered something about how Itanium's NaT values might result in problems with "freezing").

---

<div class="post-metadata">

**Author:** ![Amanieu](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/amanieu/32/4095_2.png) [@Amanieu](https://internals.rust-lang.org/u/Amanieu)\
**Post date:** [November 18, 2019, 5:34pm UTC](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310/40 "2019-11-18T17:34:34Z")

</div>

Or just use `#[cfg(target_feature = "...")]` to select different asm implementations depending on the target features.

I don't see a very strong need for additional feature/architecture checking in the asm macro when this can already be done with existing Rust features.

Similarly with AT&T syntax: unless someone can come up with a strong case for supporting it, I would prefer restricting `asm!` to only supporting Intel syntax.

[Previous page](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310.md?page=1)

[Next page](https://internals.rust-lang.org/t/pre-rfc-2-inline-assembly/11310.md?page=3)
