Welcome, guest ( Login )

WikiHome » Inline Assembler in C Files

Inline Assembler in C Files

Version 8, changed by kerry. 10/03/2006.   Show version history

Under Construction
nios2-elf-gcc supports inline assembly language.  You can mix C and Nios II assembly language statements in a C file using a special syntax.  In addition, nios2-elf-gcc will let you use C expressions for assembly language operands.
The following sections show how to use an asm() statement to enter in-line assembly language in your C file.

Assembly Statements Without Operands

Simple assembly-language opcodes that have no operands can be inserted in-line like this.

nios2-elf-gcc Source Resulting Assembly Language
int test(void)
{
    modify_code();
asm("flushp");
execute_modified_code();
return 0;
}
test:
        addi    sp, sp, -4
        stw     ra, 0(sp)
        call    modify_code
#APP
        flushp
#NO_APP
        call    execute_modified_code
        mov     r2, zero
        ldw     ra, 0(sp)
        addi    sp, sp, 4
        ret

This same technique works with any in-line assembly language that references fixed registers.

nios2-elf-gcc Source Resulting Assembly Language
void test2(void)
{
    asm(


"\n rdctl r8, ienable"
"\n ori r8, r8, 2"
"\n wrctl r8, ienable"



);
}
test2:
#APP
        rdctl r8, ienable
        ori r8, r8, 2
        wrctl r8, ienable
#NO_APP
        ret

nios2-elf-gcc recognizes that this opcode must have some kind of side effect, since it references no registers, and so it will not move the instruction significantly during optimization.

Assembly Statements With C int Operands

Assembly-language opcodes with C int operands can be inserted in-line. 

Source-Register Operands

Here is an example that writes control register ctl3 (ienable) with the value of integer parameter x.  You can see that the first parameter of the asm statement "wrctl ienable, %0" contains a "%0" where the source operand needs to be.  This "%0" is similar to a "%s" in a printf format string.  In this usage, it is replaced with the register that holds the int variable x.

void wrctl_ienable(int x)
{
    asm volatile ("wrctl ienable, %0" :: "r" (x));
}

The resulting assembly langauge is below.  The compiler has stored x in register r4.

wrctl_7:
#APP
        wrctl ienable, r4
#NO_APP
        ret

Destination-Register Operands

Using #define with asm()

#define wrctl(register_number, value) 
  ({ int __x = (value);
     asm("wrctl ctl" #register_number ", %0" :
         /* no output parameters */ :
         "r" (__x));
  })
void test(int argc, char **argv)
{
    wrctl(7, 123);
}

Custom Instructions

Custom Instructions and Built-in Functions

Attachments (0)

  File By Size Attached Ver.