DragonOS/kernel/common/compiler.h

128 lines
4.3 KiB
C
Raw Normal View History

2022-07-17 09:23:56 +00:00
#pragma once
2022-08-15 09:57:05 +00:00
#define __force __attribute__((force))
2022-07-17 09:23:56 +00:00
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#ifndef barrier
// 内存屏障
#define barrier() __asm__ __volatile__("" :: \
: "memory");
#endif
// 编译器属性
// 当函数的返回值未被使用时,编译器抛出警告信息
2022-10-04 11:04:45 +00:00
#define __must_check __attribute__((__warn_unused_result__))
typedef uint8_t __attribute__((__may_alias__)) __u8_alias_t;
typedef uint16_t __attribute__((__may_alias__)) __u16_alias_t;
typedef uint32_t __attribute__((__may_alias__)) __u32_alias_t;
typedef uint64_t __attribute__((__may_alias__)) __u64_alias_t;
/**
* @brief src读取数据到dst
*
* @param dst
* @param src
* @param size 1248memcpy读取
*/
static __always_inline void __read_once_size(void *dst, const volatile void *src, int size)
{
switch (size)
{
case 1:
*(__u8_alias_t *)dst = *(volatile __u8_alias_t *)src;
break;
case 2:
*(__u16_alias_t *)dst = *(volatile __u16_alias_t *)src;
break;
case 4:
*(__u32_alias_t *)dst = *(volatile __u32_alias_t *)src;
break;
case 8:
*(__u64_alias_t *)dst = *(volatile __u64_alias_t *)src;
break;
default:
barrier();
__builtin_memcpy((void *)dst, (const void *)src, size);
barrier();
break;
}
}
/**
* @brief src处的数据到dst
*
* @param dst
* @param src
* @param size 1248memcpy传输
*/
static __always_inline void __write_once_size(volatile void *dst, void *src, int size)
{
switch (size)
{
case 1:
*(volatile __u8_alias_t *)dst = *(__u8_alias_t *)src;
break;
case 2:
*(volatile __u16_alias_t *)dst = *(__u16_alias_t *)src;
break;
case 4:
*(volatile __u32_alias_t *)dst = *(__u32_alias_t *)src;
break;
case 8:
*(volatile __u64_alias_t *)dst = *(__u64_alias_t *)src;
break;
default:
barrier();
__builtin_memcpy((void *)dst, (const void *)src, size);
barrier();
break;
}
}
/**
* 线
* /READ_ONCE()WRITE_ONCE()
*
* Union或struct访1248使memcpy来处理
*
* 使
* 1.
* 2.访
*
* union __u内的__c用作这个union的地址的指针
*
* READ_ONCE和WRITE_ONCE的简单说明https://bbs.dragonos.org/forum.php?mod=viewthread&tid=24
*/
/**
* @brief x ()
*/
#define READ_ONCE(x) \
({ \
union \
{ \
typeof(x) __val; \
char __c[1]; \
} __u = {.__c = {0}}; \
__read_once_size(__u.__c, &(x), sizeof(x)); \
__u.__val; \
})
/**
* @brief val写入变量x ()
*/
#define WRITE_ONCE(x, val) \
({ \
union \
{ \
typeof(x) __val; \
char __c[1]; \
} __u = {.val = (val)}; \
__write_once_size(&(x), __u.__c, sizeof(x)); \
__u.__val; \
})