295 lines · plain
1.. _code_style:2 3===================4The libc code style5===================6 7Naming style8============9 10For the large part, the libc project follows the general `coding standards of11the LLVM project <https://llvm.org/docs/CodingStandards.html>`_. The libc12project differs from that standard with respect to the naming style. The13differences are as follows:14 15#. **Non-const variables** - This includes function arguments, struct and16 class data members, non-const globals and local variables. They all use the17 ``snake_case`` style.18#. **const and constexpr variables** - They use the capitalized19 ``SNAKE_CASE`` irrespective of whether they are local or global.20#. **Function and methods** - They use the ``snake_case`` style like the21 non-const variables.22#. **Internal type names** - These are types which are internal to the libc23 implementation. They use the ``CaptilizedCamelCase`` style.24#. **Public names** - These are the names as prescribed by the standards and25 will follow the style as prescribed by the standards.26 27Macro style28===========29 30We define two kinds of macros:31 32#. **Build defined** macros are generated by `CMake` or `Bazel` and are passed33 down to the compiler with the ``-D`` command line flag. They start with the34 ``LIBC_COPT_`` prefix. They are used to tune the behavior of the libc.35 They either denote an action or define a constant.36 37#. **Code defined** macros are defined within the ``src/__support/macros``38 folder. They all start with the ``LIBC_`` prefix.39 40 * ``src/__support/macros/properties/`` - Build related properties like41 target architecture or enabled CPU features defined by introspecting42 compiler defined preprocessor definitions.43 44 * ``architectures.h`` - Target architecture properties.45 e.g., ``LIBC_TARGET_ARCH_IS_ARM``.46 * ``compiler.h`` - Host compiler properties.47 e.g., ``LIBC_COMPILER_IS_CLANG``.48 * ``cpu_features.h`` - Target cpu feature availability.49 e.g., ``LIBC_TARGET_CPU_HAS_AVX2``.50 * ``types.h`` - Type properties and availability.51 e.g., ``LIBC_TYPES_HAS_FLOAT128``.52 * ``os.h`` - Target os properties.53 e.g., ``LIBC_TARGET_OS_IS_LINUX``.54 55 * ``src/__support/macros/config.h`` - Important compiler and platform56 features. Such macros can be used to produce portable code by57 parameterizing compilation based on the presence or lack of a given58 feature. e.g., ``LIBC_HAS_FEATURE``59 * ``src/__support/macros/attributes.h`` - Attributes for functions, types,60 and variables. e.g., ``LIBC_UNUSED``61 * ``src/__support/macros/optimization.h`` - Portable macros for performance62 optimization. e.g., ``LIBC_LIKELY``, ``LIBC_LOOP_NOUNROLL``63 64Inline functions and variables defined in header files65======================================================66 67When defining functions and variables inline in header files, we follow certain68rules:69 70#. The functions should not be given file-static linkage. There can be class71 static methods defined inline however.72#. Instead of using the ``inline`` keyword, functions should be tagged with the73 ``LIBC_INLINE`` macro and variables should be tagged with the74 ``LIBC_INLINE_VAR`` macro defined in ``src/__support/macros/attributes.h``.75 For example:76 77 .. code-block:: c++78 79 LIBC_INLINE_VAR constexpr bool foo = true;80 81 LIBC_INLINE ReturnType function_defined_inline(ArgType arg) {82 ...83 }84 85#. The ``LIBC_INLINE`` tag should also be added to functions which have86 definitions that are implicitly inline. Examples of such functions are87 class methods (static and non-static) defined inline and ``constexpr``88 functions.89 90Setting ``errno`` from runtime code91===================================92 93Many libc functions set ``errno`` to indicate an error condition. If LLVM's libc94is being used as the only libc, then the ``errno`` from LLVM's libc is affected.95If LLVM's libc is being used in the :ref:`overlay_mode`, then the ``errno`` from96the system libc is affected. When a libc function, which can potentially affect97the ``errno``, is called from a unit test, we do not want the global ``errno``98(as in, the ``errno`` of the process thread running the unit test) to be99affected. If the global ``errno`` is affected, then the operation of the unit100test infrastructure itself can be affected. To avoid perturbing the unit test101infrastructure around the setting of ``errno``, the following rules are to be102followed:103 104#. A special macro named ``libc_errno`` defined in ``src/__support/libc_errno.h``105 should be used when setting ``errno`` from libc runtime code. For example,106 code to set ``errno`` to ``EINVAL`` should be:107 108 .. code-block:: c++109 110 libc_errno = EINVAL;111 112#. ``errno`` should be set just before returning from the implementation of the113 public function. It should not be set from within helper functions. Helper114 functions should use idiomatic C++ constructs like115 `cpp::optional <https://github.com/llvm/llvm-project/blob/main/libc/src/__support/CPP/optional.h>`_116 and117 `ErrorOr <https://github.com/llvm/llvm-project/blob/main/libc/src/__support/error_or.h>`_118 to return error values.119 120#. The header file ``src/__support/libc_errno.h`` is shipped as part of the target121 corresponding to the ``errno`` entrypoint ``libc.src.errno.errno``. We do122 not in general allow dependencies between entrypoints. However, the ``errno``123 entrypoint is the only exceptional entrypoint on which other entrypoints124 should explicitly depend on if they set ``errno`` to indicate error125 conditions.126 127Assertions in libc runtime code128===============================129 130The libc developers should, and are encouraged to, use assertions freely in131the libc runtime code. However, the assertion should be listed via the macro132``LIBC_ASSERT`` defined in ``src/__support/libc_assert.h``. This macro can be133used from anywhere in the libc runtime code. Internally, all it does is to134print the assertion expression and exit. It does not implement the semantics135of the standard ``assert`` macro. Hence, it can be used from any where in the136libc runtime code without causing any recursive calls or chicken-and-egg137situations.138 139Allocations in the libc runtime code140====================================141 142Some libc functions allocate memory. For example, the ``strdup`` function143allocates new memory into which the input string is duplicated. Allocations144are typically done by calling a function from the ``malloc`` family of145functions. Such functions can fail and return an error value to indicate146allocation failure. To conform to standards, the libc should handle147allocation failures gracefully and surface the error conditions to the user148code as appropriate. Since LLVM's libc is implemented in C++, we want149allocations and deallocations to employ C++ operators ``new`` and ``delete``150as they implicitly invoke constructors and destructors respectively. However,151if we use the default ``new`` and ``delete`` operators, the libc will end up152depending on the C++ runtime. To avoid such a dependence, and to handle153allocation failures gracefully, we use special ``new`` and ``delete`` operators154defined in155`src/__support/CPP/new.h <https://github.com/llvm/llvm-project/blob/main/libc/src/__support/CPP/new.h>`_.156Allocations and deallocations using these operators employ a pattern like157this:158 159.. code-block:: c++160 161 #include "src/__support/CPP/new.h"162 163 ...164 165 LIBC_NAMESPACE::AllocChecker ac;166 auto *obj = new (ac) Type(...);167 if (!ac) {168 // handle allocator failure.169 }170 ...171 delete obj;172 173The only exception to using the above pattern is if allocating using the174``realloc`` function is of value. In such cases, prefer to use only the175``malloc`` family of functions for allocations and deallocations. Allocation176failures will still need to be handled gracefully. Further, keep in mind that177these functions do not call the constructors and destructors of the178allocated/deallocated objects. So, use these functions carefully and only179when it is absolutely clear that constructor and destructor invocation is180not required.181 182Warnings in sources183===================184 185We expect contributions to be free of warnings from the `minimum supported186compiler versions`__ (and newer).187 188.. __: https://libc.llvm.org/compiler_support.html#minimum-supported-versions189 190Header Inclusion Policy191=======================192 193Because llvm-libc supports194`Overlay Mode <https://libc.llvm.org/overlay_mode.html>`__,195`Full Host Build Mode <https://libc.llvm.org/full_host_build.html>`__ and196`Full Cross Build Mode <https://libc.llvm.org/full_cross_build.html>`__ care197must be taken when ``#include``'ing certain headers.198 199The ``include/`` directory contains public facing headers that users must200consume for fullbuild mode. As such, types defined here will have ABI201implications as these definitions may differ from the underlying system for202overlay mode and are NEVER appropriate to include in ``libc/src/`` without203preprocessor guards for ``LLVM_LIBC_FULL_BUILD``.204 205Consider the case where an implementation in ``libc/src/`` may wish to refer to206a ``sigset_t``, what header should be included? ``<signal.h>``, ``<spawn.h>``,207``<sys/select.h>``?208 209None of the above. Instead, code under ``src/`` should ``#include210"hdr/types/sigset_t.h"`` which contains preprocessor guards on211``LLVM_LIBC_FULL_BUILD`` to either include the public type (fullbuild mode) or212the underlying system header (overlay mode).213 214Implementations in ``libc/src/`` should NOT be ``#include``'ing using ``<>`` or215``"include/*``, except for these "proxy" headers that first check for216``LLVM_LIBC_FULL_BUILD``.217 218These "proxy" headers are similarly used when referring to preprocessor219defines. Code under ``libc/src/`` should ``#include`` a proxy header from220``hdr/``, which contains a guard on ``LLVM_LIBC_FULL_BUILD`` to either include221our header from ``libc/include/`` (fullbuild) or the corresponding underlying222system header (overlay).223 224Policy on Assembly sources225==========================226 227Coding in high level languages such as C++ provides benefits relative to low228level languages like Assembly, such as:229 230* Improved safety231* Compile time diagnostics232* Instrumentation233 234 * Code coverage235 * Profile collection236* Sanitization237* Automatic generation of debug info238 239While it's not impossible to have Assembly code that correctly provides all of240the above, we do not wish to maintain such Assembly sources in llvm-libc.241 242That said, there are a few functions provided by llvm-libc that are impossible243to reliably implement in C++ for all compilers supported for building244llvm-libc.245 246We do use inline or out-of-line Assembly in an intentionally minimal set of247places; typically places where the stack or individual register state must be248manipulated very carefully for correctness, or instances where a specific249instruction sequence does not have a corresponding compiler builtin function250today.251 252Contributions adding functions implemented purely in Assembly for performance253are not welcome.254 255Contributors should strive to stick with C++ for as long as it remains256reasonable to do so. Ideally, bugs should be filed against compiler vendors,257and links to those bug reports should appear in commit messages or comments258that seek to add Assembly to llvm-libc.259 260Patches containing any amount of Assembly ideally should be approved by 2261maintainers. llvm-libc maintainers reserve the right to reject Assembly262contributions that they feel could be better maintained if rewritten in C++,263and to revisit this policy in the future.264 265LIBC_NAMESPACE_DECL266===================267 268llvm-libc provides a macro `LIBC_NAMESPACE` which contains internal implementations of269libc functions and globals. This macro should only be used as an270identifier for accessing such symbols within the namespace (like `LIBC_NAMESPACE::cpp::max`).271Any usage of this namespace for declaring or defining internal symbols should272instead use `LIBC_NAMESPACE_DECL` which declares `LIBC_NAMESPACE` with hidden visibility.273 274Example usage:275 276.. code-block:: c++277 278 #include "src/__support/macros/config.h" // The macro is defined here.279 280 namespace LIBC_NAMESPACE_DECL {281 282 void new_function() {283 ...284 }285 286 } // LIBC_NAMESPACE_DECL287 288Having hidden visibility on the namespace ensures extern declarations in a given TU289have known visibility and never generate GOT indirections. The attribute guarantees290this independently of global compile options and build systems.291 292..293 TODO(97655): We should have a clang-tidy check to enforce this and a294 fixit implementation.295