#pragma inside #define - c

I'm working in a micro-controller using the C language. In this specific micro, the interrupts have to be defined using #pragma in following way:
static void func();
#pragma INTERRUPT func <interrupt_address> <interrupt_category>
static void func() { /* function body */ }
The <interrupt_address> is address of the interrupt in vector table. The <interrupt_category> is either 1 or 2. For example, to define an interrupt in Port 0 pin 0:
static void _int_p00();
#pragma INTERRUPT _int_p00 0x10 1
static void _int_p00() { (*isr_p00)(); }
We define actual interrupt service routine elsewhere and use function pointer (like isr_p00 in the example) to execute them.
It would be convenient if the interrupts could be defined using a macro. I want do define a macro in following way:
#define DECLARE_INTERRUPT(INT_NAME, INT_CAT) \
static void _int_##INT_NAME(); \
#pragma INTERRUPT _int_##INT_NAME INT_NAME##_ADDR INT_CAT \
static void _int_##INT_NAME() { (*isr_##INT_NAME)(); }
The compiler throwing the following error:
Formal parameter missing after '#'
indicating following line:
static void _int_##INT_NAME() { (*isr_##INT_NAME)(); }
I guess preprocessor directives cannot be used in #defines? Is there any work around?

C99 has the new _Pragma keyword that lets you place #pragma inside macros. Basically it expects a string as an argument that corresponds to the text that you would have give to the #pragma directive.
If your compiler doesn't support this (gcc does) and you'd go for an external implementation of what you need (as said, m4 could be a choice) the best would probably be to stay as close as possible to that not-so-new _Pragma. Then once your compiler builder catches up with the standard you could just stop using your script.

A workround is to use code generation or another macro language to preprocess your code.
ie write the code with a different extension.
Have your makefile or similar call the macro language (e.g. m4) or a script of some form to generate a .c file
Then compile that.

As far as I'm aware, what you are specifically asking is impossible. I'm presuming a preprocessor that works the same as the GNU C Preprocessor. In the manual for that, it states:
The compiler does not re-tokenize the preprocessor's output. Each preprocessing token becomes one compiler token.

Related

Symbol "#" in C language

I would like to ask you about assign specific memory adress for variable in C language.
I need to setup Understand SciTool software, and I have some issues about it.
Please have a look:
#define dPU1 0xF0031
__SFR_EXTERN__ __near __no_init volatile union
{
TByte ioPU1;
TBitfieldByte ioPU1_Bits;
} #dPU1;
dPU1 is a register adress (Renesas RL78).
Understand SciTool cant process it. I recived those messages:
[E] pasting formed '#dSMR02', an invalid preprocessing token;
[E] expected ';' after union
[E] expected identifier or '('
I can't find any information about "#" in C language.
Any idea?
Thanks!
Many compilers for embedded control accept certain extensions to place objects at absolute addresses.
Apparently your compiler allows to specify it via this notation.
In contrast, code analyzers are generic tools. They rarely know such extensions and so you receive this error message.
This is a good reason to wrap such an extension in a macro. This macro will be differently defined depending on the tool that parses the source. If your compiler reads the source, it provides the absolute address. If the analyzer reads the source, it expands to nothing.
This suggestion is untested:
#if defined(/* some macro that is automatically set by your compiler */)
#define AT(x) #x
#else
#define AT(x)
#endif
#define dPU1 0xF0031
__SFR_EXTERN__ __near __no_init volatile union
{
TByte ioPU1;
TBitfieldByte ioPU1_Bits;
} AT(dPU1);
The # operator is not standard C; you should find it documented as an extension in the manual for whatever compiler you are using.
The problem here is that static analysis tools need not be aware of such extensions.
Your compiler may offer an alternative method of locating objects that will not trouble the static analysis parser. For example the IAR compiler supports this extension, but has an alternative #pragma location directive:
#pragma location = 0xF0031
__SFR_EXTERN__ __near __no_init volatile union
{
TByte ioPU1;
TBitfieldByte ioPU1_Bits;
} dPU1;
Since the required behaviour when encountering an unrecognised pragma is to ignore it, your analyser should accept this code.

Is there a possibility to tell the gcc compiler to ignore function attributes? Or to speed up compilation time?

I don't have much experience with C and am now working on a HPC project which very often uses __attribute__ ((always_inline)) void foo() function definitions.
I see the point of doing it for performance runs, but for debugging, testing, and developing, the compilation time is way to long. Just earlier I wanted to add a simple printf in a function to see when the function is called, and had to wait 5min for it to compile.
Is there a possibility to pass gcc a flag to ignore the attribute requests? I already am compiling with the lowest level of optimization.
A hackish way of disabling the attribute might be to define it away in the preprocessor:
#define always_inline noinline
A better approach, however, would be to apply those attributes in a macro so that they can be configured globally, e.g.
#ifndef DEBUG
# define HOT_FUNCTION __attribute__ ((always_inline))
#else
# define HOT_FUNCTION /* nothing */
#endif
…
HOT_FUNCTION void foo() { … }

Retaining Compatibility To Assembly With inline Functions

I'm writing some header files, which are to be accessed by both C code and assembly. Assembly code is preprocessed with the C preprocessor for this sake.
The problem is I have plenty of inline functions in those header files. The assembler cannot process functions, which are not symbols in an object file (as with static inline functions), so I cannot use those. I've read this and this invaluable posts and have grasped how to use extern and static in conjunction with inline by now but I am unsure about how to make inline function accessible to both C code and assembly.
My current approach is to write inline functions (with >= GNU99, -O3 inlines the function, anything else calls an external definition of that function, which I need to define explicitly) in a header file and write external definitions in an implementation file. The C code includes the header file (the inline functions) compiles with -O3, thus using the inlined versions. The assembly code uses the external definitions.
Questions:
The assembly code can only call the functions, inlining is currently impossible. Can assembly code, by any means, make use of inlining? I mean as in an .S file, not inline assembly.
extern inline would be similarly good as my current method but it boils down to just one definition (the external definition is emitted automatically), so it cannot be divided into header and source file, which is crucial to make it accessible to C code (header) and assembly (source).
Is there any better method to achieve what I've been trying to do?
The overhead of a call forcing you to assume most registers are clobbered is pretty high. For high performance you need to manually inline your functions into asm so you can fully optimize everything.
Getting the compiler to emit a stand-alone definition and calling it should only be considered for code that's not performance-critical. You didn't say what you're writing in asm, or why, but I'm assuming that it is performance critical. Otherwise you'd just write it in C (with inline asm for any special instructions, I guess?).
If you don't want to manually inline, and you want to use these small inline C functions inside a loop, you'll probably get better performance from writing the whole thing in C. That would let the compiler optimize across a lot more code.
The register-arg calling conventions used for x86-64 are nice, but there are a lot of registers that are call-clobbered, so calls in the middle of computing stuff stop you from keeping as much data live in registers.
Can assembly code, by any means, make use of inlining? I mean as in an
.S file, not inline assembly.
No, there's no syntax for the reverse of inline-asm. If there was, it would be something like: you tell the compiler what registers the inputs are in, what registers you want outputs in, and which registers it's allowed to clobber.
Common-subexpression-elimination and other significant optimizations between the hand-written asm and the compiler output wouldn't be possible without a compiler that really understood the hand-written asm, or treated it as source code and then emitted an optimized version of the whole thing.
Optimal inlining of compiler output into asm will typically require adjustments to the asm, which is why there aren't any programs to do it.
Is there any better method to achieve what I've been trying to do?
Now that you've explained in comments what your goals are: make small wrappers in C for the special instructions you want to use, instead of the other way around.
#include <stdint.h>
struct __attribute__((packed)) lgdt_arg {
uint16_t limit;
void * base; // FIXME: always 64bit in long mode, including the x32 ABI where pointers and uintptr_t are 32bit.
// In 16bit mode, base is 24bit (not 32), so I guess be careful with that too
// you could just make this a uint64_t, since x86 is little-endian.
// The trailing bytes don't matter since the instruction just uses a pointer to the struct.
};
inline void lgdt (const struct lgdt_arg *p) {
asm volatile ("lgdt %0" : : "m"(*p) : "memory");
}
// Or this kind of construct sometimes gets used to make doubly sure compile-time reordering doesn't happen:
inline void lgdt_v2 (struct lgdt_arg *p) {
asm volatile ("lgdt %0" : "+m"(*(volatile struct lgdt_arg *)p) :: "memory");
}
// that puts the asm statement into the dependency chain of things affecting the contents of the pointed-to struct, so the compiler is forced to order it correctly.
void set_gdt(unsigned size, char *table) {
struct lgdt_arg tmp = { size, table };
lgdt (&tmp);
}
set_gdt compiles to (gcc 5.3 -O3 on godbolt):
movw %di, -24(%rsp)
movq %rsi, -22(%rsp)
lgdt -24(%rsp)
ret
I've never written code involving lgdt. It's probably a good idea to use a "memory" clobber like I did to make sure any loads/stores aren't reordered across it at compile time. That will make sure the GDT it points to might is fully initialized before running LGDT. (Same for LIDT). Compilers might notice the that base gives the inline asm a reference to the GDT, and make sure its contents are in sync, but I'm not sure. There should be little to no downside to just using a "memory" clobber here.
Linux (the kernel) uses this sort of wrapper around an instruction or two all over the place, writing as little code as possible in asm. Look there for inspiration if you want.
re: your comments: yes you'll want to write your boot sector in asm, and maybe some other 16bit code since gcc's -m16 code is silly (still basically 32bit code).
No, there's no way to inline C compiler output into asm other than manually. That's normal and expected, for the same reason there aren't programs that optimize assembly. (i.e. read asm source, optimize, write different asm source).
Think about what such a program would have to do: it would have to understand the hand-written asm to be able to know what it could change without breaking the hand-written asm. Asm as a source language doesn't give an optimizer much to work with.
The answer you linked to explains how C99 inline functions work but don't explain why the definition is that quirky. The relevant standard paragraph is ISO 9899:2011 §6.7.4 ¶6–7 (ISO 9899:1999 ibid.):
6 A function declared with an inline function specifier is an inline function. Making a function an inline function suggests that calls to the function be as fast as possible.138) The extent to which such suggestions are effective is implementation-defined. 139)
7 Any function with internal linkage can be an inline function. For a function with external linkage, the following restrictions apply: If a function is declared with an inline function specifier, then it shall also be defined in the same translation unit. If all of the file scope declarations for a function in a translation unit include the inline function specifier without extern, then the definition in that translation unit is an inline
definition. An inline definition does not provide an external definition for the function, and does not forbid an external definition in another translation unit. An inline definition provides an alternative to an external definition, which a translator may use to implement any call to the function in the same translation unit. It is unspecified whether a call to the function uses the inline definition or the external definition.140)
138) By using, for example, an alternative to the usual function call mechanism, such as ”inline substitution”. Inline substitution is not textual substitution, nor does it create a new function. Therefore, for example, the expansion of a macro used within the body of the function uses the definition it had at the point the function body appears, and not where the function is called; and identifiers refer to the declarations in scope where the body occurs. Likewise, the function has a single address, regardless of the number of inline definitions that occur in addition to the external definition.
139) For example, an implementation might never perform inline substitution, or might only perform inline substitutions to calls in the scope of an inline declaration.
140) Since an inline definition is distinct from the corresponding external definition and from any other corresponding inline definitions in other translation units, all corresponding objects with static storage duration are also distinct in each of the definitions.
How does the definition of inline come into play? Well, if only inline declarations (without extern or static) of a function exist in a translation unit, no code for the funcion is emitted. But if a single declaration without inline or with extern exists, then code for the function is emitted, even if it is defined as an inline function. This design aspect allows you to describe the module that contains the machine code for an inline function without having to duplicate the implementation:
In your header file, place inline definitions:
fast_things.h
/* TODO: add assembly implementation */
inline int fast_add(int a, int b)
{
return (a + b);
}
inline int fast_mul(int a, int b)
{
return (a * b);
}
This header can be included in every translation module and provides inline definitions for fast_add and fast_mul. To generate the machine code for these two, add this file:
fast_things.c
#include "fast_things.h"
extern inline int fast_add(int, int);
extern inline int fast_mul(int, int);
You can avoid typing all of this out using some macro magic. Change fast_things.h like this:
#ifndef EXTERN_INLINE
#define EXTERN_INLINE_UNDEFINED
#define EXTERN_INLINE inline
#endif
EXTERN_INLINE int fast_add(int a, int b)
{
return (a + b);
}
EXTERN_INLINE int fast_mul(int a, int b)
{
return (a * b);
}
#ifdef EXTERN_INLINE_UNDEFINED
#undef EXTERN_INLINE
#undef EXTERN_INLINE_UNDEFINED
#endif
Then fast_things.c simply becomes:
#define EXTERN_INLINE extern inline
#include "fast_things.h"
Since code is emitted for the inline functions, you can call them from assembly just fine. You cannot however inline them in assembly as the assembler doesn't speak C.
There are also static inline functions which might be more suitable for your purpose (i.e. tiny helper functions) when you can make reasonably sure that they are always inlined.
The GNU assembler supports macros in its custom macro language. One possibility is to write a custom preprocessor that takes your inline assembly and emits both gcc-style inline assembly for C and gas macros. This should be possible with sed, m4, or awk (in descending order of difficulty). It might also be possible to abuse the C preprocessors stringify (#) operator for this; if you can give me a concrete example, I could try to throw something together.

C - Generate warning when loosely defined function is called

I'd like to generate a compiler warning for a specific situation. I'm building a sort of universal code that will be built based on several pre-compiler definitions. For instance I might have something like the following.
sdcard.h
#ifdef PART_BOARD1
#include "port/board1.h"
#elif PART_BOARD2
#include "port/board2.h"
#endif
extern void sdcardConfigure(void);
sdcard.c
#ifndef FLAG_SDCARD
#warning "No SD Card available for this board, or this board has not been defined"
#define sdcardConfigure(...) void(0)
#endif
port/board1.h (similar for port/board2)
#define FLAG_SDCARD
void sdcardConfigure(void);
port/board1.c
void sdcardConfigure(void) {
// sd card is configured here
}
Essentially what I'd like to do is modify the #define sdcardConfigure(...) statement in sdcard.c so that I'm only seeing the warning message if sdcardConfigure() is actually called. Making it act like:
void sdcardConfigure(void) {
#warning "sdcardConfigure() not available on this board"
}
The idea being that this gives me the flexibility to create a universal (I know many fear universal) program that adapts to the parts that it's using. I.E. if there is an SD Card use it, otherwise generate a warning saying "you're calling a function that doesn't exist for this part" and let the developer decide if the function is needed.
The answer to this will most-likely be compiler-dependent.
For gcc et al you can use __attribute__ ((deprecated)) (see gcc manual).
For Visual Studio you can use __declspec(deprecated).

How can I tell gcc not to inline a function?

Say I have this small function in a source file
static void foo() {}
and I build an optimized version of my binary yet I don't want this function inlined (for optimization purposes). is there a macro I can add in a source code to prevent the inlining?
You want the gcc-specific noinline attribute.
This function attribute prevents a
function from being considered for
inlining. If the function does not
have side-effects, there are
optimizations other than inlining that
causes function calls to be optimized
away, although the function call is
live. To keep such calls from being
optimized away, put
asm ("");
Use it like this:
void __attribute__ ((noinline)) foo()
{
...
}
GCC has a switch called
-fno-inline-small-functions
So use that when invoking gcc. But the side effect is that all other small functions are also non-inlined.
I know the question is about GCC, but I thought it might be useful to
have some information about compilers other compilers as well.
GCC's
noinline
function attribute is pretty popular with other compilers as well. It
is supported by at least:
Clang (check with __has_attribute(noinline))
Intel C/C++ Compiler (their documentation is terrible, but I'm
certain it works on 16.0+)
Oracle Solaris Studio back to at least 12.2
ARM C/C++ Compiler back to at least 4.1
IBM XL C/C++ back to at least 10.1
TI 8.0+ (or 7.3+ with --gcc, which will define __TI_GNU_ATTRIBUTE_SUPPORT__)
Additionally, MSVC supports
__declspec(noinline)
back to Visual Studio 7.1. Intel probably supports it too (they try to
be compatible with both GCC and MSVC), but I haven't bothered to
verify that. The syntax is basically the same:
__declspec(noinline)
static void foo(void) { }
PGI 10.2+ (and probably older) supports a noinline pragma which
applies to the next function:
#pragma noinline
static void foo(void) { }
TI 6.0+ supports a
FUNC_CANNOT_INLINE
pragma which (annoyingly) works differently in C and C++. In C++, it's similar to PGI's:
#pragma FUNC_CANNOT_INLINE;
static void foo(void) { }
In C, however, the function name is required:
#pragma FUNC_CANNOT_INLINE(foo);
static void foo(void) { }
Cray 6.4+ (and possibly earlier) takes a similar approach, requiring
the function name:
#pragma _CRI inline_never foo
static void foo(void) { }
Oracle Developer Studio also supports a pragma which takes the
function name, going back to at least Forte Developer
6,
but note that it needs to come after the declaration, even in recent
versions:
static void foo(void);
#pragma no_inline(foo)
Depending on how dedicated you are, you could create a macro that
would work everywhere, but you would need to have the function name as
well as the declaration as arguments.
If, OTOH, you're okay with something that just works for most people,
you can get away with something which is a little more aesthetically
pleasing and doesn't require repeating yourself. That's the approach
I've taken for Hedley, where the
current version of
HEDLEY_NEVER_INLINE
looks like:
#if \
HEDLEY_GNUC_HAS_ATTRIBUTE(noinline,4,0,0) || \
HEDLEY_INTEL_VERSION_CHECK(16,0,0) || \
HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
HEDLEY_TI_VERSION_CHECK(8,0,0) || \
(HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
# define HEDLEY_NEVER_INLINE __attribute__((__noinline__))
#elif HEDLEY_MSVC_VERSION_CHECK(13,10,0)
# define HEDLEY_NEVER_INLINE __declspec(noinline)
#elif HEDLEY_PGI_VERSION_CHECK(10,2,0)
# define HEDLEY_NEVER_INLINE _Pragma("noinline")
#elif HEDLEY_TI_VERSION_CHECK(6,0,0)
# define HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
#else
# define HEDLEY_NEVER_INLINE HEDLEY_INLINE
#endif
If you don't want to use Hedley (it's a single public domain / CC0
header) you can convert the version checking macros without too much
effort, but more than I'm willing to put in ☺.
A portable way to do this is to call the function through a pointer:
void (*foo_ptr)() = foo;
foo_ptr();
Though this produces different instructions to branch, which may not be your goal. Which brings up a good point: what is your goal here?
In case you get a compiler error for __attribute__((noinline)), you can just try:
noinline int func(int arg)
{
....
}
static __attribute__ ((noinline)) void foo()
{
}
This is what worked for me.
Use the noinline attribute:
int func(int arg) __attribute__((noinline))
{
}
You should probably use it both when you declare the function for external use and when you write the function.
I work with gcc 7.2. I specifically needed a function to be non-inlined, because it had to be instantiated in a library. I tried the __attribute__((noinline)) answer, as well as the asm("") answer. Neither one solved the problem.
Finally, I figured that defining a static variable inside the function will force the compiler to allocate space for it in the static variable block, and to issue an initialization for it when the function is first called.
This is sort of a dirty trick, but it works.
I couldn't get __attribute__((noinline)) to work, but this works on clang and GCC.
The Linux kernel defines noinline.
include/linux/compiler_attributes.h:#define noinline __attribute__((__noinline__))
#include <linux/kernel.h>
static noinline void foo(void);

Resources