Skip to content

clang: macro expansion error of simple function #158263

@tttturtle-russ

Description

@tttturtle-russ

When I was trying to compile the Linux kernel with clang, a strange error occurred. It's about the macro in Linux Kernel BUILD_BUG_ON. I extracted the minimal C code to reproduce this.

bug.c

#include "bug.h"

void test(){
    BUILD_BUG_ON(TEST != 16);
    BUILD_BUG_ON(!is_power_of_2(TEST));
}

bug.h

#ifndef _BUG_H
#define _BUG_H
#include <stdbool.h>

#define TEST 16

static inline __attribute__((const))
bool is_power_of_2(unsigned long n)
{
	return (n != 0 && ((n & (n - 1)) == 0));
}

#define __noreturn __attribute__((__noreturn__))

#if __has_attribute(__error__)
# define __compiletime_error(msg)       __attribute__((__error__(msg)))
#else
# define __compiletime_error(msg)
#endif

# define __compiletime_assert(condition, msg, prefix, suffix)		\
	do {								\
		/*							\
		 * __noreturn is needed to give the compiler enough	\
		 * information to avoid certain possibly-uninitialized	\
		 * warnings (regardless of the build failing).		\
		 */							\
		__noreturn extern void prefix ## suffix(void)		\
			__compiletime_error(msg);			\
		if (!(condition))					\
			prefix ## suffix();				\
	} while (0)

#define _compiletime_assert(condition, msg, prefix, suffix) \
	__compiletime_assert(condition, msg, prefix, suffix)


#define compiletime_assert(condition, msg) \
	_compiletime_assert(condition, msg, __compiletime_assert_, __COUNTER__)

#define BUILD_BUG_ON_MSG(cond, msg) compiletime_assert(!(cond), msg)

#define BUILD_BUG_ON(condition) \
	BUILD_BUG_ON_MSG(condition, "BUILD_BUG_ON failed: " #condition)


#define BUILD_BUG() BUILD_BUG_ON_MSG(1, "BUILD_BUG failed")

#endif

Compile Command:

clang bug.c

Clang Version & Arch

I've tested this on both macOS and Linux.

Homebrew clang version 16.0.6
Target: arm64-apple-darwin24.6.0
Thread model: posix
InstalledDir: /Users/russ/KernelAnalysis/SVF/llvm-16.0.0.obj/bin

clang version 16.0.4 (https://github.com/llvm/llvm-project ae42196bc493ffe877a7e3dff8be32035dea4d07)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /root/KernelAnalysis-dev/SVF/llvm-16.0.0.obj/bin

Metadata

Metadata

Assignees

No one assigned

    Labels

    llvm:optimizationsquestionA question, not bug report. Check out https://llvm.org/docs/GettingInvolved.html instead!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions