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/intrinsics6502.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.

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
              .extern _Zp           ; pseudo zero page registers
myFunction:   clc
              adc     zp:_Zp
              rts

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

#include <stdint.h>

extern int8_t myFunction(int8_t a, int8_t b);

int caller(int8_t param) {
  return myFunction(5, param);
}

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;
}
$ cc6502 skeleton.c --assembly-source=skeleton.s
; Generated by Calypsi ISO C compiler for 6502

            .rtmodel version,"1"
            .rtmodel codeModel,"plain"
            .rtmodel core,"6502"
            .rtmodel target,"none-specified"
            .extern _AllocStack
            .extern _DeallocStack
            .extern _Vfp
            .extern _Vsp
            .extern _Zp
            .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
myFunction: ldx     #254
            jsr     _AllocStack
            sta     zp:_Zp+2
;    int local = i;
            ldy     #0
            lda     zp:_Zp
            sta     (_Vsp),y
            iny
            lda     zp:_Zp+1
            sta     (_Vsp),y
;    intvar = i;
            lda     zp:_Zp
            sta     intvar
            lda     zp:_Zp+1
            sta     intvar+1
;    charvar = c;
            lda     zp:_Zp+2
            sta     charvar
;    externalFunction(&local);
            lda     zp:_Vsp
            sta     zp:_Zp
            lda     zp:_Vsp+1
            sta     zp:_Zp+1
            jsr     externalFunction
;    return local;
            ldy     #0
            lda     (_Vsp),y
            sta     zp:_Zp
            iny
            lda     (_Vsp),y
            sta     zp:_Zp+1
;  }
            ldx     #2
            jmp     _DeallocStack
;
;  int main() {
            .section code,text
            .public main
main:
;    myFunction(intvar, charvar);
            lda     intvar
            sta     zp:_Zp
            lda     intvar+1
            sta     zp:_Zp+1
            lda     charvar
            jsr     myFunction
;    return 0;
            lda     #0
            sta     zp:_Zp
            lda     #0
            sta     zp:_Zp+1
;  }
            rts

20.3. Calling convention

The default calling convention is complex in detail, but straightforward in most common scenarios.

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.

Parameters are passed in register A and pseudo-registers _Zp[0-7]. Registers X, Y, and pseudo-registers 0–23 are destroyed by a function call, while pseudo-registers 24–47 must be preserved.

Table 20.1 Parameter registers

Register

Size

Types

A

8

char, zero page pointer

_Zp[0]

8

char, zero page pointer

_Zp[1]

8

char, zero page pointer

_Zp[2]

8

char, zero page pointer

_Zp[3]

8

char, zero page pointer

_Zp[4]

8

char, zero page pointer

_Zp[5]

8

char, zero page pointer

_Zp[6]

8

char, zero page pointer

_Zp[7]

8

char, zero page pointer

_Zp[0-1]

16

int, short, pointer

_Zp[2-3]

16

int, short, pointer

_Zp[4-5]

16

int, short, pointer

_Zp[6-7]

16

int, short, pointer

_Zp[0-3]

32

long, float

_Zp[4-7]

32

long, float

_Zp[0-3]

32

far and huge pointers (MEGA65 target)

_Zp[4-7]

32

far and huge pointers (MEGA65 target)

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

Table 20.2 Return values

Register

Size

Types

A

8

char, zero page pointer

_Zp[0-1]

16

int, short, pointer

_Zp[0-3]

32

long, float

_Zp[0-3]

32

far and huge pointers (MEGA65 target)

64 bit values

The above tables do not mention 64 bit values. A 64 bit value such as long long and long double is passed by reference, that is, as a 16 bits pointer to the value.

If a function returns a 64 bit value, the caller is responsible for allocating space. An extra ‘invisible’ parameter, a pointer to this space, is added to the function. The called function is expected to return this pointer.

Structure passing

Structure parameters are passed on the stack. Structure return values are handled like 64 bit values. 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(" sei\n"
        " inc counter\n"
        " bne skip\n"
        " inc counter+1\n"
        "skip: cli\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.3 Register classes

Register class

Description

a

A accumulator

x

X index register

y

Y index register

index

X or Y index register

zp8

An 8-bit zero page pseudo register

zp16

A 16-bit zero page pseudo register

zp32

A 32-bit zero page pseudo register

z

Z index register (45GS02 only)

q

32-bit Q register (45GS02 only)

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:

char foo(char xx) {
  char out;
  __asm(" inx\n"
        " inx\n"
        " inx\n"
        " inx\n"
        " txa\n"
        : "=Ka" (out)
        : "Kx"  (xx)
        : "a", "x"
      );
  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(char xx, char yy) {
  int out;
  __asm(" ldy %1\n"
        " iny\n"
        " tya\n"
        " clc\n"
        " adc %2\n"
        " sta %0\n"
        " lda #0\n"
	" adc #0\n"
        " sta %0+1\n"
        : "=Kzp16"(out)
        : "Kzp8"(xx), "Kzp8"(yy)
        : "a", "y"
      );
  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(char xx, char yy) {
  int out;
  __asm(" ldy %[xx]\n"
        " iny\n"
        " tya\n"
        " clc\n"
        " adc %[second]\n"
        " sta %[result]\n"
        " lda #0\n"
	" adc #0\n"
        " sta %[result]+1\n"
        : [result] "=Kzp16"(out)
        : [xx] "Kzp8"(xx), [second] "Kzp8"(yy)
        : "a", "y"
      );
  return out;
}