20. Assembly language interface

Assembly language provides symbolic access to target machine instructions. You might need this control for specific instructions unrepresentable in C, precise hardware interaction, exception stack frame manipulation, exact timing sequences, or performance-critical routines.

20.1. Intrinsic functions

The compiler provides intrinsic functions (declared in the calypsi/intrinsics68000.h file) that resemble ordinary functions. Instead of a function call, an intrinsic generates a specific instruction sequence. For example, __disable_interrupts() emits machine instructions to disable normal interrupts. See Intrinsic functions for details.

20.2. Assembly functions

You can implement functions in assembly language and call them from C like any other function. An assembly function must adhere to the C calling convention, which dictates how values are passed to the called function and where the return value is placed.

Note

To simplify your assembly routine interface, consider using the simple_call calling convention.

You can choose between a separate assembly source file or inline assembly; each has pros and cons. Assembly functions offer better separation between C and assembly, aiding portability. However, function call overhead and adherence to calling conventions may be undesirable.

Minimal boilerplate assembly code is required to place the routine in a suitable section and declare public symbols. This assembly code resides in a separate file, which must be added to the build system.

Assembly language files typically use the .s or .asm extension; however, this varies due to the lack of standardization in assembly language itself.

The assembler provided by the Calypsi C compiler tool chain, similar to UNIX assemblers, uses directives starting with a dot. This avoids name clashes with instructions, whose naming conventions vary widely across targets, ensuring consistent directive names.

As a minimum, you must declare the section and export your function name using the .public directive:

              .section code
              .public myFunction    ; export myFunction
myFunction:   add.l   d1,d0         ; just add the inputs
              rts

To call this function correctly, you must provide a prototype in C:

extern int myFunction(int a, int b);

int caller(int x) {
  return myFunction(5, x);
}

Generate skeleton code

The easiest way to generate an assembly source file is to have the compiler create it using the --assembly-source command-line option. A simplified C source file containing the desired functions and declarations can be used for this purpose.

You can provide desired function definitions with simple parameter uses to study how they are passed:

extern int intvar;
extern char charvar;

extern void externalFunction(int*);

int myFunction(int i, char c) {
  int local = i;
  intvar = i;
  charvar = c;
  externalFunction(&local);
  return local;
}

int main() {
  myFunction(intvar, charvar);
  return 0;
}
$ cc68k skeleton.c --assembly-source=skeleton.s
; Generated by Calypsi ISO C compiler for Motorola 68000

            .rtmodel version,"1"
            .rtmodel nearDataBase,"A4"
            .rtmodel core,"68000"
            .rtmodel codeModel,"large"
            .rtmodel target,"none-specified"
            .extern charvar
            .extern externalFunction
            .extern intvar
;  extern int intvar;
;  extern char charvar;
;
;  extern void externalFunction(int*);
;
;  int myFunction(int i, char c) {
            .section code,text
            .public myFunction
            .align  2
myFunction: subq.l  #4,sp
;    int local = i;
            move.l  d0,(sp)
;    intvar = i;
            move.l  d0,(.near intvar,a4)
;    charvar = c;
            move.b  d1,(.near charvar,a4)
;    externalFunction(&local);
            lea.l   (sp),a0
            jsr     externalFunction.l

;    return local;
            move.l  (sp),d0
;  }
            addq.l  #4,sp
            rts
;
;  int main() {
            .section code,text
            .public main
            .align  2
main:
;    myFunction(intvar, charvar);
            move.b  (.near charvar,a4),d1
            move.l  (.near intvar,a4),d0
            jsr     myFunction.l

;    return 0;
            moveq.l #0,d0
;  }
            rts

20.3. Calling convention

The default calling convention is complex in detail, but straightforward in most common scenarios. An alternative calling convention simple_call is also provided.

If parameters are passed on the stack, the caller is responsible for cleanup. The called function may use any register resource but must preserve certain registers, saving and restoring them before returning.

Simple calling convention

Use __attribute__((simple_call)) or __simple_call on a function declaration to enable the simple calling convention.

In this calling convention all parameters are pushed on the stack. Registers D0, D1, A0 and A1 are destroyed by a call and the return value are passed as follows:

Table 20.1 Return values

Register

Size

Types

D0.B

8

char

D0.W

16

short

D0.L

32

int, long, float, data and function pointers

D0:D1

64

long long, long double

Normal calling convention

Parameters are passed in the D0, D1, A0 and A1 registers. These registers are clobbered by a function call. All other registers must be preserved by a function call.

Table 20.2 Parameter registers

Register

Size

Types

D0.B

8

char

D1.B

8

char

D0.W

16

short

D1.W

16

short

D0.L

32

int, long, float

D1.L

32

int, long, float

A0

32

data and function pointers

A1

32

data and function pointers

D0:D1

64

long long, long double

Parameters are bound to register left to right on a first fit basis. If a parameter register has to be skipped over, it will considered again for later parameters. Parameters that cannot be fit into registers are passed on the stack.

Table 20.3 Return values

Register

Size

Types

D0.B

8

char

D0.W

16

short

D0.L

32

int, long, float, data and function pointers

D0:D1

64

long long, long double

Structure passing

Structure parameters are passed on the stack. If a function returns a structure, the caller allocates space and adds an extra ‘invisible’ parameter (a pointer to that space) to the function call. The called function is expected to return this pointer.

20.4. Inline assembler

The inline assembler allows you to insert and interface assembly code slices within a C function. This avoids call overhead and can improve parameter adaptation. However, the optimizer must be more cautious, which may affect the performance of the surrounding C code.

Basic inline assembly

You can insert a slice of assembly code using an __asm block:

int counter;

void foo(char xx) {
  __asm(" bcc skip\n"
        " trapv\n"
        "skip: \n"
        );
}

Each line without a label requires at least one leading space and must be terminated by a newline character (\n).

The inline assembler supports the full assembly instruction set, including literal bytes, volatile operations, local labels, and register allocation for parameters and return values.

Goto labels and most assembler directives are currently not supported by the inline assembler. If you need better control with placement, use a separate assembly source file instead.

When inline assembly is inserted, the compiler adapts it to fit the generated C code. Variables can be passed as parameters, and a single result variable is supported. The compiler reasonably understands the inserted assembly, mixing it with C-generated code. Inline assembly is subject to low-level optimizations when the optimizer is enabled.

Volatile

An assembly block can be marked as volatile:

__asm volatile { ... }

This has the effect that all memory accesses in the assembly slice are treated as side effects. Otherwise the optimizer may remove reads from memory when the value read is not used.

Local labels

Local labels can be used and their names will not clash with C identifiers. When an inline assembly slice is inserted, local labels are converted to internal C labels, preventing name clashes with C identifiers.

External symbols

Inline assembly can refer to symbols defined outside its code slice, provided such symbols are visible at the C level within the same compilation unit.

Constraints

An inline assembly code slice can refer to C variables and return a value. The inline assembly construct optionally accepts three lists:

  1. Output variable: Specifies a C variable to represent the returned value and a register class where the assembly code block places it. The result is prefixed by = in its single-value list.

  2. Input expressions: Typically variables. The compiler evaluates the expression and places it in the specified register class.

  3. Clobbered registers: Any register resource clobbered by the inline assembly must be specified here.

Multiple entries in a list are comma-separated.

Register classes

A register class is a register resource that can represent either a single register or a set of equivalent registers. They are used for allocating parameters and determining the return value location.

The following register classes are defined:

Table 20.4 Register classes

Register class

Description

d0b

D0 as 8-bit register

d0w

D0 as 16-bit register

d0

D0 as 32-bit register

a0w

A0 as 16-bit register

a0

A0 as 32-bit register

dreg8

8-bit data register

areg16

16-bit address register

dreg16

16-bit data register

xreg16

16-bit address or data register

areg32

32-bit address register

dreg32

32-bit data register

xreg32

32-bit address or data register

Note

Register classes are used internally during code generation. Internal code generator rules ensure safe register allocation by adhering to specific rules and invariants. Rather than attempting to diagnose inline assembly constraints or impose conservative limitations, the compiler trusts you. Overusing resources or violating internal invariants may lead to a register allocation error. In such cases, ease the register resources to find a working allocation.

Registers and constraints

The following code shows how constraints for an inline assembly code slice are defined:

int foo(short xx, int *p) {
  int out;
  __asm(" move.w (a0)+,d0\n"
        " ext.l d0\n"
        : "=Kd0" (out)
        : "Kd0w"  (xx), "Ka0" (p)
        : "d0", "a0"
      );
  return out;
}

Currently, the only supported constraint is ‘K’, followed by a register class.

An empty list can be entered by using a colon character followed by nothing.

The first list is the optional output parameter, describing the C variable where the output is visible after the inline assembly slice executes. The inline assembly slice must leave the result in the specified register class; the compiler will automatically insert code to store this value in the C variable.

The second constraint specifies input variables and their register classes. The compiler ensures these variables are available in the specified register classes before passing control to the inline assembly code slice.

The third list specifies the actual registers clobbered by the inline assembly code slice. These must be register classes describing a single register.

Substitutions

A register class may specify a register resource with multiple alternatives. The register allocator selects the actual register used. You can refer to the register resource using substitutions, given by the %N syntax, where N is 0 for the result (if present), 1 for the first input, 2 for the second, and so on:

int foo(int xx, int yy, char *p) {
  int out;
  __asm(" move.l %1,d0\n"
        " add.l %2,d0\n"
	" add.l (%3)+,%0\n"
        : "=Kd0" (out)
        : "Kdreg32" (xx), "Kdreg32" (yy), "Ka0" (p)
        : "d0", "a0"
      );
  return out;
}

Note

If the output is empty then the input list starts with %0.

If you find substitutions using numbers to be unreadable, you can specify a symbol for each substitution:

int foo(int xx, int yy, char *p) {
  int out;
  __asm(" move.l %[xx],d0\n"
        " add.l %[second],d0\n"
	" add.l (%[pointer])+,%[result]\n"
        : [result] "=Kd0" (out)
        : [xx] "Kdreg32" (xx), [second] "Kdreg32" (yy), [pointer] "Ka0" (p)
        : "d0", "a0"
      );
  return out;
}