[llvm] revisions to LLVM_ABI export macro definitions (#144598)

## Purpose

Simplify the logic used to define `LLVM_ABI` and related macros,
eliminate the `LLVM_ABI_FRIEND` macro, and update the `LLVM_ABI` macro
to always resolve to `__attribute__((visibility("default")))` when
building LLVM as a shared library for ELF or Mach-O targets.

## Background

Previously, `LLVM_ABI` was defined to the C++ style attribute
`[[gnu::visibility("default")]]` when compiling with gcc, which has more
restrictions on its placement. Of note, the C++ style attributes cannot
decorate `friend` functions and must not appear after `extern` on
variable declarations.

Documentation for `LLVM_ABI` and related annotations is found in the
LLVM repo
[here](https://github.com/llvm/llvm-project/blob/main/llvm/docs/InterfaceExportAnnotations.rst).

## Overview
- Define a new CMake config value,
`LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS`, which is implicitly set whenever
`LLVM_BUILD_LLVM_DYLIB`, `LLVM_BUILD_SHARED_LIBS`, or
`LLVM_ENABLE_PLUGINS` is set. Add it as a `#cmakedefine` to
llvm-config.h so its definition is available to projects building
against LLVM as required so clients see `__declspec(dllimport)` on
Windows.
- Gate the `LLVM_ABI` macro definitions in Compiler.h behind the new
`LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS` definition. This is
simpler/cleaner, but should be equivalent to the previous logic.
- Maintain `LLVM_BUILD_STATIC` as an override to be used by specific
targets that don't want to build against the DLL/shared library, such as
tablegen.
- For ELF and Mach-O targets, directly define `LLVM_ABI` as
`__attribute__((visibility("default")))` instead of
`LLVM_ATTRIBUTE_VISIBILITY_DEFAULT`, which resolves to C++ style
`[[gnu::visibility("default")]]` when compiling with gcc.
- Remove the `LLVM_ABI_FRIEND` macro and replace all usages of it with
`LLVM_ABI`.
- Update the documentation for exporting friend functions to no longer
reference `LLVM_ABI_FRIEND`.

## Validation
- Built as static lib with clang and gcc on Linux.
- Built as static with clang-cl and MSVC on Windows.
- Built as shared lib with clang and gcc on Linux (+ additional local
changes not yet merged).
- Built as DLL with clang-cl and MSVC on Windows (+ additional local
changes not yet merged).

---------

Co-authored-by: SquallATF <squallatf@gmail.com>
This commit is contained in:
Andrew Rogers
2025-06-24 09:18:34 -07:00
committed by GitHub
parent 6a8899cee7
commit e175ecff93
21 changed files with 70 additions and 80 deletions

View File

@@ -942,6 +942,13 @@ if (LLVM_LINK_LLVM_DYLIB AND BUILD_SHARED_LIBS)
message(FATAL_ERROR "Cannot enable BUILD_SHARED_LIBS with LLVM_LINK_LLVM_DYLIB. We recommend disabling BUILD_SHARED_LIBS.")
endif()
set(LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS OFF)
if (LLVM_BUILD_LLVM_DYLIB OR LLVM_BUILD_SHARED_LIBS OR LLVM_ENABLE_PLUGINS)
# Export annotations for LLVM must be enabled if building as a shared lib or
# enabling plugins.
set(LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS ON)
endif()
option(LLVM_OPTIMIZED_TABLEGEN "Force TableGen to be built with optimization" OFF)
if(CMAKE_CROSSCOMPILING OR (LLVM_OPTIMIZED_TABLEGEN AND (LLVM_ENABLE_ASSERTIONS OR CMAKE_CONFIGURATION_TYPES)))
set(LLVM_USE_HOST_TOOLS ON)

View File

@@ -222,7 +222,7 @@ method in a C++ class, it may be annotated for export.
Friend Functions
~~~~~~~~~~~~~~~~
Friend functions declared in a class, struct or union must be annotated with
``LLVM_ABI_FRIEND`` if the corresponding function declaration is annotated with
``LLVM_ABI`` if the corresponding function declaration is annotated with
``LLVM_ABI``. This requirement applies even when the class containing the friend
declaration is annotated with ``LLVM_ABI``.
@@ -236,14 +236,13 @@ declaration is annotated with ``LLVM_ABI``.
class ExampleClass {
// Friend declaration of a function must be annotated the same as the actual
// function declaration.
LLVM_ABI_FRIEND friend int friend_function(ExampleClass &obj);
LLVM_ABI friend int friend_function(ExampleClass &obj);
};
.. note::
Annotating the friend declaration avoids an “inconsistent dll linkage”
compiler error when building a DLL for Windows. The ``LLVM_ABI_FRIEND``
annotation is a no-op when building ELF or Mach-O shared libraries.
compiler error when building a DLL for Windows.
Virtual Table and Type Info
~~~~~~~~~~~~~~~~~~~~~~~~~~~

View File

@@ -572,7 +572,7 @@ public:
/// emphasizes producing different codes for different inputs in order to
/// be used in canonicalization and memoization. As such, equality is
/// bitwiseIsEqual, and 0 != -0.
LLVM_ABI_FRIEND friend hash_code hash_value(const IEEEFloat &Arg);
LLVM_ABI friend hash_code hash_value(const IEEEFloat &Arg);
/// Converts this value into a decimal string.
///
@@ -629,13 +629,12 @@ public:
/// 0 -> \c IEK_Zero
/// Inf -> \c IEK_Inf
///
LLVM_ABI_FRIEND friend int ilogb(const IEEEFloat &Arg);
LLVM_ABI friend int ilogb(const IEEEFloat &Arg);
/// Returns: X * 2^Exp for integral exponents.
LLVM_ABI_FRIEND friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode);
LLVM_ABI friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode);
LLVM_ABI_FRIEND friend IEEEFloat frexp(const IEEEFloat &X, int &Exp,
roundingMode);
LLVM_ABI friend IEEEFloat frexp(const IEEEFloat &X, int &Exp, roundingMode);
/// \name Special value setters.
/// @{
@@ -906,11 +905,11 @@ public:
LLVM_ABI LLVM_READONLY int getExactLog2() const;
LLVM_ABI LLVM_READONLY int getExactLog2Abs() const;
LLVM_ABI_FRIEND friend DoubleAPFloat scalbn(const DoubleAPFloat &X, int Exp,
LLVM_ABI friend DoubleAPFloat scalbn(const DoubleAPFloat &X, int Exp,
roundingMode);
LLVM_ABI_FRIEND friend DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp,
LLVM_ABI friend DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp,
roundingMode);
LLVM_ABI_FRIEND friend hash_code hash_value(const DoubleAPFloat &Arg);
LLVM_ABI friend hash_code hash_value(const DoubleAPFloat &Arg);
};
LLVM_ABI hash_code hash_value(const DoubleAPFloat &Arg);
@@ -1518,7 +1517,7 @@ public:
APFLOAT_DISPATCH_ON_SEMANTICS(getExactLog2());
}
LLVM_ABI_FRIEND friend hash_code hash_value(const APFloat &Arg);
LLVM_ABI friend hash_code hash_value(const APFloat &Arg);
friend int ilogb(const APFloat &Arg) { return ilogb(Arg.getIEEE()); }
friend APFloat scalbn(APFloat X, int Exp, roundingMode RM);
friend APFloat frexp(const APFloat &X, int &Exp, roundingMode RM);

View File

@@ -62,18 +62,17 @@ public:
LLVM_ABI SlowDynamicAPInt &operator++();
LLVM_ABI SlowDynamicAPInt &operator--();
LLVM_ABI_FRIEND friend SlowDynamicAPInt abs(const SlowDynamicAPInt &X);
LLVM_ABI_FRIEND friend SlowDynamicAPInt ceilDiv(const SlowDynamicAPInt &LHS,
LLVM_ABI friend SlowDynamicAPInt abs(const SlowDynamicAPInt &X);
LLVM_ABI friend SlowDynamicAPInt ceilDiv(const SlowDynamicAPInt &LHS,
const SlowDynamicAPInt &RHS);
LLVM_ABI_FRIEND friend SlowDynamicAPInt floorDiv(const SlowDynamicAPInt &LHS,
LLVM_ABI friend SlowDynamicAPInt floorDiv(const SlowDynamicAPInt &LHS,
const SlowDynamicAPInt &RHS);
/// The operands must be non-negative for gcd.
LLVM_ABI_FRIEND friend SlowDynamicAPInt gcd(const SlowDynamicAPInt &A,
LLVM_ABI friend SlowDynamicAPInt gcd(const SlowDynamicAPInt &A,
const SlowDynamicAPInt &B);
/// Overload to compute a hash_code for a SlowDynamicAPInt value.
LLVM_ABI_FRIEND friend hash_code
hash_value(const SlowDynamicAPInt &X); // NOLINT
LLVM_ABI friend hash_code hash_value(const SlowDynamicAPInt &X); // NOLINT
// Make DynamicAPInt a friend so it can access Val directly.
friend DynamicAPInt;

View File

@@ -120,7 +120,7 @@ struct ParserCallbacks {
IdentificationBit(IdentificationBit), ModuleBit(ModuleBit) {}
// Calls the ctor.
LLVM_ABI_FRIEND friend Expected<BitcodeFileContents>
LLVM_ABI friend Expected<BitcodeFileContents>
getBitcodeFileContents(MemoryBufferRef Buffer);
Expected<std::unique_ptr<Module>>

View File

@@ -764,7 +764,7 @@ public:
/// isIdenticalTo uses for comparison. It is thus suited for use in hash
/// tables which use that function for equality comparisons only. This must
/// stay exactly in sync with isIdenticalTo above.
LLVM_ABI_FRIEND friend hash_code hash_value(const MachineOperand &MO);
LLVM_ABI friend hash_code hash_value(const MachineOperand &MO);
/// ChangeToImmediate - Replace this operand with a new immediate operand of
/// the specified value. If an operand is known to be an immediate already,

View File

@@ -46,8 +46,8 @@ public:
private:
unsigned Kind;
unsigned AddressSpace;
LLVM_ABI_FRIEND friend raw_ostream &
llvm::operator<<(raw_ostream &OS, const PseudoSourceValue *PSV);
LLVM_ABI friend raw_ostream &llvm::operator<<(raw_ostream &OS,
const PseudoSourceValue *PSV);
friend class MachineMemOperand; // For printCustom().
friend class MIRFormatter; // For printCustom().

View File

@@ -110,6 +110,9 @@
/* Define if building LLVM with BUILD_SHARED_LIBS */
#cmakedefine LLVM_BUILD_SHARED_LIBS
/* Define if exporting LLVM public interface for shared library */
#cmakedefine LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS
/* Define if building LLVM with LLVM_FORCE_USE_OLD_TOOLCHAIN_LIBS */
#cmakedefine LLVM_FORCE_USE_OLD_TOOLCHAIN ${LLVM_FORCE_USE_OLD_TOOLCHAIN}

View File

@@ -42,8 +42,7 @@ class ExecutorProcessControl;
class LLVM_ABI LLJIT {
template <typename, typename, typename> friend class LLJITBuilderSetters;
LLVM_ABI_FRIEND friend Expected<JITDylibSP>
setUpGenericLLVMIRPlatform(LLJIT &J);
LLVM_ABI friend Expected<JITDylibSP> setUpGenericLLVMIRPlatform(LLJIT &J);
public:
/// Initializer support for LLJIT.

View File

@@ -36,7 +36,7 @@ class SymbolStringPool {
friend class SymbolStringPoolEntryUnsafe;
// Implemented in DebugUtils.h.
LLVM_ABI_FRIEND friend raw_ostream &operator<<(raw_ostream &OS,
LLVM_ABI friend raw_ostream &operator<<(raw_ostream &OS,
const SymbolStringPool &SSP);
public:
@@ -94,8 +94,8 @@ public:
return LHS.S < RHS.S;
}
LLVM_ABI_FRIEND friend raw_ostream &
operator<<(raw_ostream &OS, const SymbolStringPtrBase &Sym);
LLVM_ABI friend raw_ostream &operator<<(raw_ostream &OS,
const SymbolStringPtrBase &Sym);
#ifndef NDEBUG
// Returns true if the pool entry's ref count is above zero (or if the entry

View File

@@ -287,7 +287,7 @@ public:
LLVM_ABI void finalizeWithMemoryManagerLocking();
private:
LLVM_ABI_FRIEND friend void jitLinkForORC(
LLVM_ABI friend void jitLinkForORC(
object::OwningBinary<object::ObjectFile> O,
RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver,
bool ProcessAllSections,

View File

@@ -783,9 +783,8 @@ public:
private:
// These need access to the underlying BB list.
LLVM_ABI_FRIEND friend void BasicBlock::removeFromParent();
LLVM_ABI_FRIEND friend iplist<BasicBlock>::iterator
BasicBlock::eraseFromParent();
LLVM_ABI friend void BasicBlock::removeFromParent();
LLVM_ABI friend iplist<BasicBlock>::iterator BasicBlock::eraseFromParent();
template <class BB_t, class BB_i_t, class BI_t, class II_t>
friend class InstIterator;
friend class llvm::SymbolTableListTraits<llvm::BasicBlock>;

View File

@@ -193,7 +193,7 @@ private:
/// cannot be skipped.
bool MarkFlatProfiles = false;
LLVM_ABI_FRIEND friend ErrorOr<std::unique_ptr<SampleProfileWriter>>
LLVM_ABI friend ErrorOr<std::unique_ptr<SampleProfileWriter>>
SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
SampleProfileFormat Format);
};
@@ -225,7 +225,7 @@ protected:
void addNames(const FunctionSamples &S);
private:
LLVM_ABI_FRIEND friend ErrorOr<std::unique_ptr<SampleProfileWriter>>
LLVM_ABI friend ErrorOr<std::unique_ptr<SampleProfileWriter>>
SampleProfileWriter::create(std::unique_ptr<raw_ostream> &OS,
SampleProfileFormat Format);
};

View File

@@ -171,11 +171,6 @@
/// for both functions and classes. On windows its turned in to dllimport for
/// library consumers, for other platforms its a default visibility attribute.
///
/// LLVM_ABI_FRIEND is for annotating friend function declarations when the
/// target function's original declaration is annotated with LLVM_ABI. This
/// macro matches the LLVM_ABI macro on Windows, on other platforms it does
/// nothing.
///
/// LLVM_C_ABI is used to annotated functions and data that need to be exported
/// for the libllvm-c API. This used both for the llvm-c headers and for the
/// functions declared in the different Target's c++ source files that don't
@@ -184,19 +179,10 @@
// Marker to add to classes or functions in public headers that should not have
// export macros added to them by the clang tool
#define LLVM_ABI_NOT_EXPORTED
#if defined(LLVM_BUILD_LLVM_DYLIB) || defined(LLVM_BUILD_SHARED_LIBS) || \
defined(LLVM_ENABLE_PLUGINS)
// Some libraries like those for tablegen are linked in to tools that used
// in the build so can't depend on the llvm shared library. If export macros
// were left enabled when building these we would get duplicate or
// missing symbol linker errors on windows.
#if defined(LLVM_BUILD_STATIC)
#define LLVM_ABI
#define LLVM_ABI_FRIEND
#define LLVM_TEMPLATE_ABI
#define LLVM_EXPORT_TEMPLATE
#define LLVM_ABI_EXPORT
#elif defined(_WIN32) && !defined(__MINGW32__)
// TODO(https://github.com/llvm/llvm-project/issues/145406): eliminate need for
// two preprocessor definitions to gate LLVM_ABI macro definitions.
#if defined(LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS) && !defined(LLVM_BUILD_STATIC)
#if defined(_WIN32) && !defined(__MINGW32__)
#if defined(LLVM_EXPORTS)
#define LLVM_ABI __declspec(dllexport)
#define LLVM_TEMPLATE_ABI
@@ -206,25 +192,24 @@
#define LLVM_TEMPLATE_ABI __declspec(dllimport)
#define LLVM_EXPORT_TEMPLATE
#endif
#define LLVM_ABI_FRIEND LLVM_ABI
#define LLVM_ABI_EXPORT __declspec(dllexport)
#elif defined(__ELF__) || defined(__MINGW32__) || defined(_AIX) || \
#elif __has_attribute(visibility)
#if defined(__ELF__) || defined(__MINGW32__) || defined(_AIX) || \
defined(__MVS__) || defined(__CYGWIN__)
#define LLVM_ABI LLVM_ATTRIBUTE_VISIBILITY_DEFAULT
#define LLVM_ABI_FRIEND
#define LLVM_TEMPLATE_ABI LLVM_ATTRIBUTE_VISIBILITY_DEFAULT
#define LLVM_ABI __attribute__((visibility("default")))
#define LLVM_TEMPLATE_ABI LLVM_ABI
#define LLVM_EXPORT_TEMPLATE
#define LLVM_ABI_EXPORT LLVM_ATTRIBUTE_VISIBILITY_DEFAULT
#define LLVM_ABI_EXPORT LLVM_ABI
#elif defined(__MACH__) || defined(__WASM__) || defined(__EMSCRIPTEN__)
#define LLVM_ABI LLVM_ATTRIBUTE_VISIBILITY_DEFAULT
#define LLVM_ABI_FRIEND
#define LLVM_ABI __attribute__((visibility("default")))
#define LLVM_TEMPLATE_ABI
#define LLVM_EXPORT_TEMPLATE
#define LLVM_ABI_EXPORT LLVM_ATTRIBUTE_VISIBILITY_DEFAULT
#define LLVM_ABI_EXPORT LLVM_ABI
#endif
#else
#endif
#endif
#if !defined(LLVM_ABI)
#define LLVM_ABI
#define LLVM_ABI_FRIEND
#define LLVM_TEMPLATE_ABI
#define LLVM_EXPORT_TEMPLATE
#define LLVM_ABI_EXPORT

View File

@@ -1191,7 +1191,7 @@ private:
/// (or Expected) and you want to call code that still returns
/// std::error_codes.
class LLVM_ABI ECError : public ErrorInfo<ECError> {
LLVM_ABI_FRIEND friend Error errorCodeToError(std::error_code);
LLVM_ABI friend Error errorCodeToError(std::error_code);
void anchor() override;

View File

@@ -220,7 +220,7 @@ public:
/// Represents the result of a call to sys::fs::status().
class file_status : public basic_file_status {
LLVM_ABI_FRIEND friend bool equivalent(file_status A, file_status B);
LLVM_ABI friend bool equivalent(file_status A, file_status B);
#if defined(LLVM_ON_UNIX)
dev_t fs_st_dev = 0;

View File

@@ -531,7 +531,7 @@ private:
llvm::StringRef, std::string, json::Array,
json::Object>
Union;
LLVM_ABI_FRIEND friend bool operator==(const Value &, const Value &);
LLVM_ABI friend bool operator==(const Value &, const Value &);
};
LLVM_ABI bool operator==(const Value &, const Value &);
@@ -713,7 +713,7 @@ class Path::Root {
llvm::StringLiteral ErrorMessage;
std::vector<Path::Segment> ErrorPath; // Only valid in error state. Reversed.
LLVM_ABI_FRIEND friend void Path::report(llvm::StringLiteral Message);
LLVM_ABI friend void Path::report(llvm::StringLiteral Message);
public:
Root(llvm::StringRef Name = "") : Name(Name), ErrorMessage("") {}

View File

@@ -80,8 +80,8 @@ class const_iterator
Style S = Style::native; ///< The path style to use.
// An end iterator has Position = Path.size() + 1.
LLVM_ABI_FRIEND friend const_iterator begin(StringRef path, Style style);
LLVM_ABI_FRIEND friend const_iterator end(StringRef path);
LLVM_ABI friend const_iterator begin(StringRef path, Style style);
LLVM_ABI friend const_iterator end(StringRef path);
public:
reference operator*() const { return Component; }
@@ -105,8 +105,8 @@ class reverse_iterator
size_t Position = 0; ///< The iterators current position within Path.
Style S = Style::native; ///< The path style to use.
LLVM_ABI_FRIEND friend reverse_iterator rbegin(StringRef path, Style style);
LLVM_ABI_FRIEND friend reverse_iterator rend(StringRef path);
LLVM_ABI friend reverse_iterator rbegin(StringRef path, Style style);
LLVM_ABI friend reverse_iterator rend(StringRef path);
public:
reference operator*() const { return Component; }

View File

@@ -51,7 +51,7 @@ namespace llvm {
/// constructed and destructed, they will add their symbolic frames to a
/// virtual stack trace. This gets dumped out if the program crashes.
class LLVM_ABI PrettyStackTraceEntry {
LLVM_ABI_FRIEND friend PrettyStackTraceEntry *
LLVM_ABI friend PrettyStackTraceEntry *
ReverseStackTrace(PrettyStackTraceEntry *);
PrettyStackTraceEntry *NextEntry;

View File

@@ -85,7 +85,7 @@ private:
FunctionAddressMap FunctionAddresses;
FunctionAddressReverseMap FunctionIds;
LLVM_ABI_FRIEND friend Expected<InstrumentationMap>
LLVM_ABI friend Expected<InstrumentationMap>
loadInstrumentationMap(StringRef);
public:

View File

@@ -51,7 +51,7 @@ class Trace {
typedef std::vector<XRayRecord>::const_iterator citerator;
LLVM_ABI_FRIEND friend Expected<Trace> loadTrace(const DataExtractor &, bool);
LLVM_ABI friend Expected<Trace> loadTrace(const DataExtractor &, bool);
public:
using size_type = RecordVector::size_type;