Inline assembler

Short description: Embedding assembly in a high-level language

In computer programming, an inline assembler is a feature of some compilers that allows low-level code written in assembly language to be embedded within a program, among code that otherwise has been compiled from a higher-level language such as C or Ada.

## Contents

* 1 Motivation and alternatives
* 2 Syntax
* 2.1 In language standards
* 2.2 In actual compilers
* 3 Examples
* 3.1 A system call in GCC
* 3.2 Processor-specific instruction in D
* 3.3 Rust
* 4 References
* 5 External links

## Motivation and alternatives

The embedding of assembly language code is usually done for one of these reasons:[1]

* Optimization: Programmers can use assembly language code to implement the most performance-sensitive parts of their program's algorithms, code that is apt to be more efficient than what might otherwise be generated by the compiler.
* Access to processor-specific instructions: Most processors offer special instructions, such as Compare and Swap and Test and Set instructions which may be used to construct semaphores or other synchronization and locking primitives. Nearly every modern processor has these or similar instructions, as they are necessary to implement multitasking. Examples of specialized instructions are found in the SPARC VIS, Intel MMX and SSE, and Motorola Altivec instruction sets.
* Access to special calling conventions not yet supported by the compiler.
* System calls and interrupts: High-level languages rarely have a direct facility to make arbitrary system calls, so assembly code is used. Direct interrupts are even more rarely supplied.
* To emit special directives for the linker or assembler, for example to change sectioning, macros, or to make symbol aliases.

On the other hand, inline assembler poses a direct problem for the compiler itself as it complicates the analysis of what is done to each variable, a key part of register allocation. This means the performance might actually decrease. Inline assembler also complicates future porting and maintenance of a program.[1]

Alternative facilities are often provided as a way to simplify the work for both the compiler and the programmer. Intrinsic functions for special instructions are provided by most compilers and C-function wrappers for arbitrary system calls are available on every Unix platform.

## Syntax

### In language standards

The ISO C++ standard and ISO C standards (annex J) specify a conditionally supported syntax for inline assembler:

> An asm declaration has the form
>  asm-declaration:
>  asm ( string-literal ) ;
>  The asm declaration is conditionally-supported; its meaning is implementation-defined.[2]

This definition, however, is rarely used in actual C, as it is simultaneously too liberal (in the interpretation) and too restricted (in the use of one string literal only).

### In actual compilers

In practical use, inline assembly operating on values is rarely standalone as free-floating code. Since the programmer cannot predict what register a variable is assigned to, compilers typically provide a way to substitute them in as an extension.

There are, in general, two types of inline assembly supported by C/C++ compilers:

* asm (or __asm__) in GCC. GCC uses a direct extension of the ISO rules: assembly code template is written in strings, with inputs, outputs, and clobbered registers specified after the strings in colons. C variables are used directly while register names are quoted as string literals.[3]
* __asm in Microsoft Visual C++ (MSVC), Borland/Embarcadero C compiler, and descendants. This syntax is not based on ISO rules at all; programmers simply write ASM inside a block without needing to conform to C syntax. Variables are available as if they are registers and some C expressions are allowed.[4] ARM Compiler used to have a similar facility.[5]

The two families of extensions represent different understandings of division of labor in processing inline assembly. The GCC form preserves the overall syntax of the language and compartmentizes what the compiler needs to know: what is needed and what is changed. It does not explicitly require the compiler to understand instruction names, as the compiler is only needed to substitute its register assignments, plus a few mov operations, to handle the input requirements. However, the user is prone to specifying clobbered registers incorrectly. The MSVC form of an embedded domain-specific language provides ease of writing, but it requires the compiler itself to know about opcode names and their clobbering properties, demanding extra attention in maintenance and porting.[6] It is still possible to check GCC-style assembly for clobber mistakes with knowledge of the instruction set.[7]

GNAT (Ada language frontend of the GCC suite), and LLVM uses the GCC syntax.[8][9] The D programming language uses a DSL similar to the MSVC extension officially for x86_64,[10] but the LLVM-based LDC also provides the GCC-style syntax on every architecture.[11] MSVC only supports inline assembler on 32-bit x86.[4]

The Rust language has since migrated to a syntax abstracting away inline assembly options further than the LLVM (GCC-style) version. It provides enough information to allow transforming the block into an externally-assembled function if the backend could not handle embedded assembly.[6]

## Examples

### A system call in GCC

Calling an operating system directly is generally not possible under a system using protected memory. The OS runs at a more privileged level (kernel mode) than the user (user mode); a (software) interrupt is used to make requests to the operating system. This is rarely a feature in a higher-level language, and so wrapper functions for system calls are written using inline assembler.

The following C code example shows an x86 system call wrapper in AT&T assembler syntax, using the GNU Assembler. Such calls are normally written with the aid of macros; the full code is included for clarity. In this particular case, the wrapper performs a system call of a number given by the caller with three operands, returning the result.[12]

To recap, GCC supports both basic and extended assembly. The former simply passes text verbatim to the assembler, while the latter performs some substitutions for register locations.[3]

#include <errno.h>

int syscall3(int num, int arg1, int arg2, int arg3) {
int res = 0;
asm (
"int $0x80" // make the request to the OS
: "=a" (res), // return result in eax ("a")
"+b" (arg1), // pass arg1 in ebx ("b") [as a "+" output because the syscall may change it]
"+c" (arg2), // pass arg2 in ecx ("c") [ditto]
"+d" (arg3) // pass arg3 in edx ("d") [ditto]
: "a"  (num) // pass system call number in eax ("a")
: "memory", "cc", // announce to the compiler that the memory and condition codes have been modified
"esi", "edi", "ebp" // these registers are clobbered [changed by the syscall] too

// The operating system will return a negative value on error;
// wrappers return -1 on error and set the errno global variable
if (-125 <= res && res < 0) {
errno = -res;
res = -1;

return res;

### Processor-specific instruction in D

This example of inline assembly from the D programming language shows code that computes the tangent of x using the x86's FPU (x87) instructions.

// Compute the tangent of x
real tan(real x) {
asm {
fld     x[EBP]                  ; // load x
fxam                            ; // test for oddball values
fstsw   AX                      ;
sahf                            ;
jc      trigerr                 ; // C0 = 1: x is NAN, infinity, or empty
// 387's can handle denormals
SC18:   fptan                           ;
fstp    ST(0)                   ; // dump X, which is always 1
fstsw   AX                      ;
sahf                            ; // if (!(fp_status & 0x20)) goto Lret
jnp     Lret                    ; // C2 = 1: x is out of range, do argument reduction
fldpi                           ; // load pi
fxch                            ;
SC17:   fprem1                          ; // reminder (partial)
fstsw   AX                      ;
sahf                            ;
jp      SC17                    ; // C2 = 1: partial reminder, need to loop
fstp    ST(1)                   ; // remove pi from stack
jmp     SC18                    ;

trigerr:
return real.nan;
Lret:                                     // No need to manually return anything as the value is already on FP stack

The fstsw-sahf followed by conditional jump idiom is used to access the x87 FPU status word bits C0 and C2. fstsw stores the status in a general-purpose register; sahf sets the FLAGS register to the higher 8 bits of the register; and the jump is used to judge on whatever flag bit that happens to correspond to the FPU status bit.[13]

### Rust

In Rust, one can use the `std::arch::asm` macro. It must be inside an `unsafe` context.[14]

use std::arch::asm;

fn read_timestamp_counter() -> u64 {
let high: u32;
let low: u32;

unsafe {
asm!(
"rdtsc",
out("edx") high,
out("eax") low,
options(nomem, nostack, preserves_flags),

((high as u64) << 32) | (low as u64)

## References

1. ↑ 1.0 1.1 "DontUseInlineAsm". https://gcc.gnu.org/wiki/DontUseInlineAsm.
2. ↑ C++, [dcl.asm]
3. ↑ 3.0 3.1 "Extended Asm - Assembler Instructions with C Expression Operands". https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html.
4. ↑ 4.0 4.1 "Inline Assembler" (in en-us). 3 August 2021. https://docs.microsoft.com/en-us/cpp/assembler/inline/inline-assembler.
5. ↑ "Migration and Compatibility Guide: Inline assembly with Arm Compiler 6". https://www.keil.com/support/man/docs/armclang_mig/armclang_mig_ioz1485879652178.htm.
6. ↑ 6.0 6.1 d'Antras, Amanieu (13 December 2019). "Rust RFC-2873: stable inline asm". https://rust-lang.github.io/rfcs/2873-inline-asm.html. "However it is possible to implement support for inline assembly without support from the compiler backend by using an external assembler instead." Pull Request for status tracking
7. ↑ "⚙ D54891 [RFC Checking inline assembly for validity"]. https://reviews.llvm.org/D54891.
8. ↑ "LLVM Language Reference: Inline assembly expressions". http://llvm.org/docs/LangRef.html#inline-assembler-expressions.
9. ↑ "Inline Assembly". https://doc.rust-lang.org/1.0.0/book/inline-assembly.html.
10. ↑ "Inline Assembler". https://dlang.org/spec/iasm.html.
11. ↑ "LDC inline assembly expressions". https://wiki.dlang.org/LDC_inline_assembly_expressions.
12. ↑ `syscall(2)` – Linux Programmer's Manual – System Calls
13. ↑ "FSTSW/FNSTSW — Store x87 FPU Status Word". https://www.felixcloutier.com/x86/fstsw:fnstsw. "The FNSTSW AX form of the instruction is used primarily in conditional branching..."
14. ↑ The Rust Reference. "Inline assembly". The Rust Reference. https://doc.rust-lang.org/reference/inline-assembly.html.

## External links

* GCC-Inline-Assembly-HOWTO
* Clang Inline assembly
* GNAT Inline Assembler
* GCC Inline Assembler Reference
* Compiler Explorer

0.00

(0 votes)

Original source: https://en.wikipedia.org/wiki/Inline assembler. Read more

|

Retrieved from "https://handwiki.org/wiki/index.php?title=Inline_assembler&oldid=4296711"