Writing asm Macros

Here are some guidelines for writing asm macros.

  1. Know the implementation. You must be familiar with the C compiler and assembly language with which you are working. You can consult the Application Binary Interface for your machine for the details of function calling and register usage conventions.
  2. Observe register conventions. You should be aware of which registers the C compiler normally uses for scratch registers or register variables. An asm macro may alter scratch registers at will, but the values in register variables must be preserved. You must know in which register(s) the compiler returns function results.
  3. Handle return values. asm macros may "return" values. That means they behave as if they were actually functions that had been called via the usual function call mechanism. asm macros must therefore mimic C's behavior in that respect, passing return values in the same place as normal C functions. Float and double results sometimes get returned in different registers from integer-type results. On some machine architectures, C functions return pointers in different registers from those used for scalars. Finally, structs may be returned in a variety of implementation-dependent ways.
  4. Cover all cases. The asm macro patterns should cover all combinations of storage modes of the parameters. The compiler attempts to match patterns in the order of their appearance in the asm macro definition.

If the compiler encounters a storage mode of error while attempting to find a matching pattern, it generates a compile time error for that particular asm macro call.

  1. Beware of argument handling. asm macro arguments are used for macro substitution. Thus, unlike normal C functions, asm macros can alter the underlying values that their arguments refer to. Altering argument values is discouraged, however, because doing so would make it impossible to substitute an equivalent C function call for the asm macro call.
  2. asm macros are inherently non-portable and implementation-dependent. Although they make it easier to introduce assembly code reliably into C code, the process cannot be made foolproof. You will always need to verify correct behavior by inspection and testing.
  3. Debuggers will generally have difficulty with asm macros. It may be impossible to set breakpoints within the inline code that the compiler generates.
  4. Because the optimizers are highly tuned to the normal code generation sequences of the compiler, using asm macros may cause optimizers to produce incorrect code. Generally speaking, any asm macro that can be directly replaced by a comparable C function may be optimized safely. However, the sensitivity of an optimizer to asm macros varies among implementations and may change with new software releases.

Previous

Next



Copyright © 1999, Green Hills Software. All rights reserved.