1830 lines · plain
1=====================2LLVM Coding Standards3=====================4 5.. contents::6 :local:7 8Introduction9============10 11This document describes coding standards that are used in the LLVM project.12Although no coding standards should be regarded as absolute requirements to be13followed in all instances, coding standards are14particularly important for large-scale code bases that follow a library-based15design (like LLVM).16 17While this document may provide guidance for some mechanical formatting issues,18whitespace, or other "microscopic details", these are not fixed standards.19Always follow the golden rule:20 21.. _Golden Rule:22 23 **If you are extending, enhancing, or bug fixing already implemented code,24 use the style that is already being used so that the source is uniform and25 easy to follow.**26 27Note that some code bases (e.g. ``libc++``) have special reasons to deviate28from the coding standards. For example, in the case of ``libc++``, this is29because the naming and other conventions are dictated by the C++ standard.30 31There are some conventions that are not uniformly followed in the code base32(e.g. the naming convention). This is because they are relatively new, and a33lot of code was written before they were put in place. Our long-term goal is34for the entire codebase to follow the convention, but we explicitly *do not*35want patches that do large-scale reformatting of existing code. On the other36hand, it is reasonable to rename the methods of a class if you're about to37change it in some other way. Please commit such changes separately to38make code review easier.39 40The ultimate goal of these guidelines is to increase the readability and41maintainability of our common source base.42 43Languages, Libraries, and Standards44===================================45 46Most source code in LLVM and other LLVM projects using these coding standards47is C++ code. There are some places where C code is used either due to48environment restrictions, historical restrictions, or due to third-party source49code imported into the tree. Generally, our preference is for50standards-conforming, modern, and portable C++ code as the implementation language of51choice.52 53For automation, build systems, and utility scripts, Python is preferred and54is widely used in the LLVM repository already.55 56C++ Standard Versions57---------------------58 59Unless otherwise documented, LLVM subprojects are written using standard C++1760code and avoid unnecessary vendor-specific extensions.61 62Nevertheless, we restrict ourselves to features which are available in the63major toolchains supported as host compilers (see :doc:`GettingStarted` page,64section `Software`).65 66Each toolchain provides a good reference for what it accepts:67 68* Clang: https://clang.llvm.org/cxx_status.html69 70 * libc++: https://libcxx.llvm.org/Status/Cxx17.html71 72* GCC: https://gcc.gnu.org/projects/cxx-status.html#cxx1773 74 * libstdc++: https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.201775 76* MSVC: https://learn.microsoft.com/cpp/overview/visual-cpp-language-conformance77 78Additionally, there are compiler comparison tables of supported C++ features on79`cppreference.com <https://en.cppreference.com/w/cpp/compiler_support/17>`_.80 81To keep track with the evolution of the standard, newer C++ versions can be used82to build LLVM. However, our support focuses on the minimum supported C++83version and a very recent standard may not yet be supported, or only using the84latest version of the supported toolchains and possibly not across all the85subprojects.86 87 88C++ Standard Library89--------------------90 91Instead of implementing custom data structures, we encourage the use of C++92standard library facilities or LLVM support libraries whenever they are93available for a particular task. LLVM and related projects emphasize and rely94on the standard library facilities and the LLVM support libraries as much as95possible.96 97LLVM support libraries (for example, `ADT98<https://github.com/llvm/llvm-project/tree/main/llvm/include/llvm/ADT>`_)99implement specialized data structures or functionality missing in the standard100library. Such libraries are usually implemented in the ``llvm`` namespace and101follow the expected standard interface when there is one.102 103When both C++ and the LLVM support libraries provide similar functionality, and104there isn't a specific reason to favor the C++ implementation, it is generally105preferable to use the LLVM library. For example, ``llvm::DenseMap`` should106almost always be used instead of ``std::map`` or ``std::unordered_map``, and107``llvm::SmallVector`` should usually be used instead of ``std::vector``.108 109We explicitly avoid some standard facilities, like the I/O streams, and instead110use LLVM's streams library (raw_ostream_). More detailed information on these111subjects is available in the :doc:`ProgrammersManual`.112 113For more information about LLVM's data structures and the tradeoffs they make,114please consult `that section of the programmer's manual115<https://llvm.org/docs/ProgrammersManual.html#picking-the-right-data-structure-for-a-task>`_.116 117Python version and Source Code Formatting118-----------------------------------------119 120The current minimum version of Python required is documented in the :doc:`GettingStarted`121section. Python code in the LLVM repository should only use language features122available in this version of Python.123 124The Python code within the LLVM repository should adhere to the formatting guidelines125outlined in `PEP 8 <https://peps.python.org/pep-0008/>`_.126 127For consistency and to limit churn, code should be automatically formatted with128the `black <https://github.com/psf/black>`_ utility, which is PEP 8 compliant.129Use its default rules. For example, avoid specifying ``--line-length`` even130though it does not default to 80. The default rules can change between major131versions of black. In order to avoid unnecessary churn in the formatting rules,132we currently use black version 23.x in LLVM.133 134When contributing a patch unrelated to formatting, you should format only the135Python code that the patch modifies. For this purpose, use the `darker136<https://pypi.org/project/darker/>`_ utility, which runs default black rules137over only the modified Python code. Doing so should ensure the patch will pass138the Python format checks in LLVM's pre-commit CI, which also uses darker. When139contributing a patch specifically for reformatting Python files, use black,140which currently only supports formatting entire files.141 142Here are some quick examples, but see the black and darker documentation for143details:144 145.. code-block:: bash146 147 $ pip install black=='23.*' darker # install black 23.x and darker148 $ darker test.py # format uncommitted changes149 $ darker -r HEAD^ test.py # also format changes from last commit150 $ black test.py # format entire file151 152Instead of individual file names, you can specify directories to153darker, and it will find the changed files. However, if a directory is154large, like a clone of the LLVM repository, darker can be painfully155slow. In that case, you might wish to use git to list changed files.156For example:157 158.. code-block:: bash159 160 $ darker -r HEAD^ $(git diff --name-only --diff-filter=d HEAD^)161 162Mechanical Source Issues163========================164 165Source Code Formatting166----------------------167 168Commenting169^^^^^^^^^^170 171Comments are important for readability and maintainability. When writing comments,172write them as English prose, using proper capitalization, punctuation, etc.173Aim to describe what the code is trying to do and why, not *how* it does it at174a micro level. Here are a few important things to document:175 176.. _header file comment:177 178File Headers179""""""""""""180 181Every source file should have a header on it that describes the basic purpose of182the file. The standard header looks like this:183 184.. code-block:: c++185 186 //===----------------------------------------------------------------------===//187 //188 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.189 // See https://llvm.org/LICENSE.txt for license information.190 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception191 //192 //===----------------------------------------------------------------------===//193 ///194 /// \file195 /// This file contains the declaration of the Instruction class, which is the196 /// base class for all of the VM instructions.197 ///198 //===----------------------------------------------------------------------===//199 200The first section in the file is a concise note that defines the license that the201file is released under. This makes it perfectly clear what terms the source202code can be distributed under and should not be modified in any way.203 204The main body is a `Doxygen <http://www.doxygen.nl/>`_ comment (identified by205the ``///`` comment marker instead of the usual ``//``) describing the purpose206of the file. The first sentence (or a passage beginning with ``\brief``) is207used as an abstract. Any additional information should be separated by a blank208line. If an algorithm is based on a paper or is described in another source,209provide a reference.210 211Header Guard212""""""""""""213 214The header file's guard should be the all-caps path that a user of this header215would #include, using '_' instead of path separator and extension marker.216For example, the header file217``llvm/include/llvm/Analysis/Utils/Local.h`` would be ``#include``-ed as218``#include "llvm/Analysis/Utils/Local.h"``, so its guard is219``LLVM_ANALYSIS_UTILS_LOCAL_H``.220 221Class overviews222"""""""""""""""223 224Classes are a fundamental part of an object-oriented design. As such, a225class definition should have a comment block that explains what the class is226used for and how it works. Every non-trivial class is expected to have a227``doxygen`` comment block.228 229Method information230""""""""""""""""""231 232Methods and global functions should also be documented. A quick note about233what it does and a description of the edge cases is all that is necessary here.234The reader should be able to understand how to use interfaces without reading235the code itself.236 237Good things to talk about here are what happens when something unexpected238happens, for instance, does the method return null?239 240Comment Formatting241^^^^^^^^^^^^^^^^^^242 243In general, prefer C++-style comments (``//`` for normal comments, ``///`` for244``doxygen`` documentation comments). There are a few cases when it is245useful to use C-style (``/* */``) comments, however:246 247#. When writing C code to be compatible with C89.248 249#. When writing a header file that may be ``#include``\d by a C source file.250 251#. When writing a source file that is used by a tool that only accepts C-style252 comments.253 254#. When documenting the significance of constants used as actual parameters in255 a call. This is most helpful for ``bool`` parameters, or passing ``0`` or256 ``nullptr``. The comment should contain the parameter name, which ought to be257 meaningful. For example, it's not clear what the parameter means in this call:258 259 .. code-block:: c++260 261 Object.emitName(nullptr);262 263 An in-line C-style comment makes the intent obvious:264 265 .. code-block:: c++266 267 Object.emitName(/*Prefix=*/nullptr);268 269Commenting out large blocks of code is discouraged, but if you really have to do270this (for documentation purposes or as a suggestion for debug printing), use271``#if 0`` and ``#endif``. These nest properly and are better behaved in general272than C-style comments.273 274Doxygen Use in Documentation Comments275^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^276 277Use the ``\file`` command to turn the standard file header into a file-level278comment.279 280Include descriptive paragraphs for all public interfaces (public classes,281member and non-member functions). Avoid restating the information that can282be inferred from the API name. The first sentence (or a paragraph beginning283with ``\brief``) is used as an abstract. Try to use a single sentence as the284``\brief`` adds visual clutter. Put detailed discussion into separate285paragraphs.286 287To refer to parameter names inside a paragraph, use the ``\p name`` command.288Don't use the ``\arg name`` command since it starts a new paragraph that289contains documentation for the parameter.290 291Wrap non-inline code examples in ``\code ... \endcode``.292 293To document a function parameter, start a new paragraph with the294``\param name`` command. If the parameter is used as an out or an in/out295parameter, use the ``\param [out] name`` or ``\param [in,out] name`` command,296respectively.297 298To describe function return value, start a new paragraph with the ``\returns``299command.300 301A minimal documentation comment:302 303.. code-block:: c++304 305 /// Sets the xyzzy property to \p Baz.306 void setXyzzy(bool Baz);307 308A documentation comment that uses all Doxygen features in a preferred way:309 310.. code-block:: c++311 312 /// Does foo and bar.313 ///314 /// Does not do foo the usual way if \p Baz is true.315 ///316 /// Typical usage:317 /// \code318 /// fooBar(false, "quux", Res);319 /// \endcode320 ///321 /// \param Quux kind of foo to do.322 /// \param [out] Result filled with bar sequence on foo success.323 ///324 /// \returns true on success.325 bool fooBar(bool Baz, StringRef Quux, std::vector<int> &Result);326 327Don't duplicate the documentation comment in the header file and in the328implementation file. Put the documentation comments for public APIs into the329header file. Documentation comments for private APIs can go to the330implementation file. In any case, implementation files can include additional331comments (not necessarily in Doxygen markup) to explain implementation details332as needed.333 334Don't duplicate the function or class name at the beginning of the comment.335For humans, it is obvious which function or class is being documented;336automatic documentation processing tools are smart enough to bind the comment337to the correct declaration.338 339Avoid:340 341.. code-block:: c++342 343 // Example.h:344 345 // example - Does something important.346 void example();347 348 // Example.cpp:349 350 // example - Does something important.351 void example() { ... }352 353Preferred:354 355.. code-block:: c++356 357 // Example.h:358 359 /// Does something important.360 void example();361 362 // Example.cpp:363 364 /// Builds a B-tree in order to do foo. See paper by...365 void example() { ... }366 367Error and Warning Messages368^^^^^^^^^^^^^^^^^^^^^^^^^^369 370Clear diagnostic messages are important to help users identify and fix issues in371their inputs. Use succinct but correct English prose that gives the user the372context needed to understand what went wrong. Also, to match error message373styles commonly produced by other tools, start the first sentence with a374lowercase letter, and finish the last sentence without a period, if it would375end in one otherwise. Sentences which end with different punctuation, such as376"did you forget ';'?", should still do so.377 378For example, this is a good error message:379 380.. code-block:: none381 382 error: file.o: section header 3 is corrupt. Size is 10 when it should be 20383 384This is a bad message, since it does not provide useful information and uses the385wrong style:386 387.. code-block:: none388 389 error: file.o: Corrupt section header.390 391As with other coding standards, individual projects, such as the Clang Static392Analyzer, may have preexisting styles that do not conform to this. If a393different formatting scheme is used consistently throughout the project, use394that style instead. Otherwise, this standard applies to all LLVM tools,395including clang, clang-tidy, and so on.396 397If the tool or project does not have existing functions to emit warnings or398errors, use the error and warning handlers provided in ``Support/WithColor.h``399to ensure they are printed in the appropriate style, rather than printing to400stderr directly.401 402When using ``report_fatal_error``, follow the same standards for the message as403regular error messages. Assertion messages and ``llvm_unreachable`` calls do not404necessarily need to follow these same styles as they are automatically405formatted, and thus these guidelines may not be suitable.406 407``#include`` Style408^^^^^^^^^^^^^^^^^^409 410Immediately after the `header file comment`_ (and include guards if working on a411header file), the `minimal list of #includes`_ required by the file should be412listed. We prefer these ``#include``\s to be listed in this order:413 414.. _Main Module Header:415.. _Local/Private Headers:416 417#. Main Module Header418#. Local/Private Headers419#. LLVM project/subproject headers (``clang/...``, ``lldb/...``, ``llvm/...``, etc)420#. System ``#include``\s421 422and each category should be sorted lexicographically by the full path.423 424The `Main Module Header`_ file applies to ``.cpp`` files which implement an425interface defined by a ``.h`` file. This ``#include`` should always be included426**first** regardless of where it lives on the file system. By including a427header file first in the ``.cpp`` files that implement the interfaces, we ensure428that the header does not have any hidden dependencies which are not explicitly429``#include``\d in the header, but should be. It is also a form of documentation430in the ``.cpp`` file to indicate where the interfaces it implements are defined.431 432LLVM project and subproject headers should be grouped from most specific to least433specific, for the same reasons described above. For example, LLDB depends on434both clang and LLVM, and clang depends on LLVM. So an LLDB source file should435include ``lldb`` headers first, followed by ``clang`` headers, followed by436``llvm`` headers, to reduce the possibility (for example) of an LLDB header437accidentally picking up a missing include due to the previous inclusion of that438header in the main source file or some earlier header file. clang should439similarly include its own headers before including llvm headers. This rule440applies to all LLVM subprojects.441 442.. _fit into 80 columns:443 444Source Code Width445^^^^^^^^^^^^^^^^^446 447Write your code to fit within 80 columns.448 449There must be some limit to the width of the code in450order to allow developers to have multiple files side-by-side in451windows on a modest display. If you are going to pick a width limit, it is452somewhat arbitrary, but you might as well pick something standard. Going with 90453columns (for example) instead of 80 columns wouldn't add any significant value454and would be detrimental to printing out code. Also many other projects have455standardized on 80 columns, so some people have already configured their editors456for it (vs something else, like 90 columns).457 458Whitespace459^^^^^^^^^^460 461In all cases, prefer spaces to tabs in source files. People have different462preferred indentation levels, and different styles of indentation that they463like; this is fine. What isn't fine is that different editors/viewers expand464tabs out to different tab stops. This can cause your code to look completely465unreadable, and it is not worth dealing with.466 467As always, follow the `Golden Rule`_ above: follow the style of existing code468if you are modifying and extending it.469 470Do not add trailing whitespace. Some common editors will automatically remove471trailing whitespace when saving a file which causes unrelated changes to appear472in diffs and commits.473 474Format Lambdas Like Blocks Of Code475""""""""""""""""""""""""""""""""""476 477When formatting a multi-line lambda, format it like a block of code. If there478is only one multi-line lambda in a statement, and there are no expressions479lexically after it in the statement, drop the indent to the standard two space480indent for a block of code, as if it were an if-block opened by the preceding481part of the statement:482 483.. code-block:: c++484 485 std::sort(foo.begin(), foo.end(), [&](Foo a, Foo b) -> bool {486 if (a.blah < b.blah)487 return true;488 if (a.baz < b.baz)489 return true;490 return a.bam < b.bam;491 });492 493To take best advantage of this formatting, if you are designing an API which494accepts a continuation or single callable argument (be it a function object, or495a ``std::function``), it should be the last argument if at all possible.496 497If there are multiple multi-line lambdas in a statement, or additional498parameters after the lambda, indent the block two spaces from the indent of the499``[]``:500 501.. code-block:: c++502 503 dyn_switch(V->stripPointerCasts(),504 [] (PHINode *PN) {505 // process phis...506 },507 [] (SelectInst *SI) {508 // process selects...509 },510 [] (LoadInst *LI) {511 // process loads...512 },513 [] (AllocaInst *AI) {514 // process allocas...515 });516 517Braced Initializer Lists518""""""""""""""""""""""""519 520Starting from C++11, there are significantly more uses of braced lists to521perform initialization. For example, they can be used to construct aggregate522temporaries in expressions. They now have a natural way of ending up nested523within each other and within function calls in order to build up aggregates524(such as option structs) from local variables.525 526The historically common formatting of braced initialization of aggregate527variables does not mix cleanly with deep nesting, general expression contexts,528function arguments, and lambdas. We suggest new code use a simple rule for529formatting braced initialization lists: act as if the braces were parentheses530in a function call. The formatting rules exactly match those already well531understood for formatting nested function calls. Examples:532 533.. code-block:: c++534 535 foo({a, b, c}, {1, 2, 3});536 537 llvm::Constant *Mask[] = {538 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),539 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),540 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)};541 542This formatting scheme also makes it particularly easy to get predictable,543consistent, and automatic formatting with tools like `Clang Format`_.544 545.. _Clang Format: https://clang.llvm.org/docs/ClangFormat.html546 547Language and Compiler Issues548----------------------------549 550Treat Compiler Warnings Like Errors551^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^552 553Compiler warnings are often useful and help improve the code. Those that are554not useful, can be often suppressed with a small code change. For example, an555assignment in the ``if`` condition is often a typo:556 557.. code-block:: c++558 559 if (V = getValue()) {560 ...561 }562 563Several compilers will print a warning for the code above. It can be suppressed564by adding parentheses:565 566.. code-block:: c++567 568 if ((V = getValue())) {569 ...570 }571 572Write Portable Code573^^^^^^^^^^^^^^^^^^^574 575In almost all cases, it is possible to write completely portable code. When576you need to rely on non-portable code, put it behind a well-defined and577well-documented interface.578 579Do not use RTTI or Exceptions580^^^^^^^^^^^^^^^^^^^^^^^^^^^^^581 582In an effort to reduce code and executable size, LLVM does not use exceptions583or RTTI (`runtime type information584<https://en.wikipedia.org/wiki/Run-time_type_information>`_, for example,585``dynamic_cast<>``).586 587That said, LLVM does make extensive use of a hand-rolled form of RTTI that use588templates like :ref:`isa\<>, cast\<>, and dyn_cast\<> <isa>`.589This form of RTTI is opt-in and can be590:doc:`added to any class <HowToSetUpLLVMStyleRTTI>`.591 592Prefer C++-style casts593^^^^^^^^^^^^^^^^^^^^^^594 595When casting, use ``static_cast``, ``reinterpret_cast``, and ``const_cast``,596rather than C-style casts. There are two exceptions to this:597 598* When casting to ``void`` to suppress warnings about unused variables (as an599 alternative to ``[[maybe_unused]]``). Prefer C-style casts in this instance.600 Note that if the variable is unused because it's used only in ``assert``, use601 ``[[maybe_unused]]`` instead of a C-style void cast.602 603* When casting between integral types (including enums that are not strongly-604 typed), functional-style casts are permitted as an alternative to605 ``static_cast``.606 607.. _static constructor:608 609Do not use Static Constructors610^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^611 612Static constructors and destructors (e.g., global variables whose types have a613constructor or destructor) should not be added to the code base, and should be614removed wherever possible.615 616Globals in different source files are initialized in an `arbitrary order617<https://yosefk.com/c++fqa/ctors.html#fqa-10.12>`_, making the code more618difficult to reason about.619 620Static constructors have a negative impact on the launch time of programs that use621LLVM as a library. We would really like for there to be zero cost for linking622in an additional LLVM target or other library into an application, but static623constructors undermine this goal.624 625Use of ``class`` and ``struct`` Keywords626^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^627 628In C++, the ``class`` and ``struct`` keywords can be used almost629interchangeably. The only difference is when they are used to declare a class:630``class`` makes all members private by default while ``struct`` makes all631members public by default.632 633* All declarations and definitions of a given ``class`` or ``struct`` must use634 the same keyword. For example:635 636.. code-block:: c++637 638 // Avoid if `Example` is defined as a struct.639 class Example;640 641 // OK.642 struct Example;643 644 struct Example { ... };645 646* ``struct`` should be used when *all* members are declared public.647 648.. code-block:: c++649 650 // Avoid using `struct` here, use `class` instead.651 struct Foo {652 private:653 int Data;654 public:655 Foo() : Data(0) { }656 int getData() const { return Data; }657 void setData(int D) { Data = D; }658 };659 660 // OK to use `struct`: all members are public.661 struct Bar {662 int Data;663 Bar() : Data(0) { }664 };665 666Do not use Braced Initializer Lists to Call a Constructor667^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^668 669Starting from C++11 there is a "generalized initialization syntax" which allows670calling constructors using braced initializer lists. Do not use these to call671constructors with non-trivial logic or if you care that you're calling some672*particular* constructor. Those should look like function calls using673parentheses rather than like aggregate initialization. Similarly, if you need674to explicitly name the type and call its constructor to create a temporary,675don't use a braced initializer list. Instead, use a braced initializer list676(without any type for temporaries) when doing aggregate initialization or677something notionally equivalent. Examples:678 679.. code-block:: c++680 681 class Foo {682 public:683 // Construct a Foo by reading data from the disk in the whizbang format, ...684 Foo(std::string filename);685 686 // Construct a Foo by looking up the Nth element of some global data ...687 Foo(int N);688 689 // ...690 };691 692 // The Foo constructor call is reading a file, don't use braces to call it.693 llvm::fill(foo, Foo("name"));694 695 // The pair is being constructed like an aggregate, use braces.696 bar_map.insert({my_key, my_value});697 698If you use a braced initializer list when initializing a variable, use an equals before the open curly brace:699 700.. code-block:: c++701 702 int data[] = {0, 1, 2, 3};703 704Use ``auto`` Type Deduction to Make Code More Readable705^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^706 707Some are advocating a policy of "almost always ``auto``" in C++11; however, LLVM708uses a more moderate stance. Use ``auto`` if and only if it makes the code more709readable or easier to maintain. Don't "almost always" use ``auto``, but do use710``auto`` with initializers like ``cast<Foo>(...)`` or other places where the711type is already obvious from the context. Another time when ``auto`` works well712for these purposes is when the type would have been abstracted away anyway,713often behind a container's typedef such as ``std::vector<T>::iterator``.714 715Similarly, C++14 adds generic lambda expressions where parameter types can be716``auto``. Use these where you would have used a template.717 718Beware unnecessary copies with ``auto``719^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^720 721The convenience of ``auto`` makes it easy to forget that its default behavior722is a copy. Particularly in range-based ``for`` loops, careless copies are723expensive.724 725Use ``auto &`` for values and ``auto *`` for pointers unless you need to make a726copy.727 728.. code-block:: c++729 730 // Typically there's no reason to copy.731 for (const auto &Val : Container) observe(Val);732 for (auto &Val : Container) Val.change();733 734 // Remove the reference if you really want a new copy.735 for (auto Val : Container) { Val.change(); saveSomewhere(Val); }736 737 // Copy pointers, but make it clear that they're pointers.738 for (const auto *Ptr : Container) observe(*Ptr);739 for (auto *Ptr : Container) Ptr->change();740 741Beware of non-determinism due to ordering of pointers742^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^743 744In general, there is no relative ordering among pointers. As a result,745when unordered containers like sets and maps are used with pointer keys746the iteration order is undefined. Hence, iterating such containers may747result in non-deterministic code generation. While the generated code748might work correctly, non-determinism can make it harder to reproduce bugs and749debug the compiler.750 751In case an ordered result is expected, remember to752sort an unordered container before iteration. Or use ordered containers753like ``vector``/``MapVector``/``SetVector`` if you want to iterate pointer754keys.755 756Beware of non-deterministic sorting order of equal elements757^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^758 759``std::sort`` uses a non-stable sorting algorithm in which the order of equal760elements is not guaranteed to be preserved. Thus using ``std::sort`` for a761container having equal elements may result in non-deterministic behavior.762To uncover such instances of non-determinism, LLVM has introduced a new763``llvm::sort`` wrapper function. For an ``EXPENSIVE_CHECKS`` build this will randomly764shuffle the container before sorting. Default to using ``llvm::sort`` instead765of ``std::sort``.766 767Style Issues768============769 770The High-Level Issues771---------------------772 773Self-contained Headers774^^^^^^^^^^^^^^^^^^^^^^775 776Header files should be self-contained (compile on their own) and end in ``.h``.777Non-header files that are meant for inclusion should end in ``.inc`` and be778used sparingly.779 780All header files should be self-contained. Users and refactoring tools should781not have to adhere to special conditions to include the header. Specifically, a782header should have header guards and include all other headers it needs.783 784There are rare cases where a file designed to be included is not785self-contained. These are typically intended to be included at unusual786locations, such as the middle of another file. They might not use header787guards, and might not include their prerequisites. Name such files with the788.inc extension. Use sparingly, and prefer self-contained headers when possible.789 790In general, a header should be implemented by one or more ``.cpp`` files. Each791of these ``.cpp`` files should include the header that defines their interface792first. This ensures that all of the dependencies of the header have been793properly added to the header itself, and are not implicit. System headers794should be included after user headers for a translation unit.795 796Library Layering797^^^^^^^^^^^^^^^^798 799A directory of header files (for example, ``include/llvm/Foo``) defines a800library (``Foo``). One library (both801its headers and implementation) should only use things from the libraries802listed in its dependencies.803 804Some of this constraint can be enforced by classic Unix linkers (Mac & Windows805linkers, as well as lld, do not enforce this constraint). A Unix linker806searches left to right through the libraries specified on its command line and807never revisits a library. In this way, no circular dependencies between808libraries can exist.809 810This doesn't fully enforce all inter-library dependencies, and importantly811doesn't enforce header file circular dependencies created by inline functions.812A good way to answer the "is this layered correctly" would be to consider813whether a Unix linker would succeed at linking the program if all inline814functions were defined out-of-line. (& for all valid orderings of dependencies815- since linking resolution is linear, it's possible that some implicit816dependencies can sneak through: A depends on B and C, so valid orderings are817"C B A" or "B C A", in both cases the explicit dependencies come before their818use. But in the first case, B could still link successfully if it implicitly819depended on C, or the opposite in the second case)820 821.. _minimal list of #includes:822 823``#include`` as Little as Possible824^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^825 826``#include`` hurts compile time performance. Don't do it unless you have to,827especially in header files.828 829But wait! Sometimes you need to have the definition of a class to use it, or to830inherit from it. In these cases go ahead and ``#include`` that header file. Be831aware, however, that there are many cases where you don't need to have the full832definition of a class. If you are using a pointer or reference to a class, you833don't need the header file. If you are simply returning a class instance from a834prototyped function or method, you don't need it. In fact, for most cases, you835simply don't need the definition of a class. And not ``#include``\ing speeds up836compilation.837 838It is easy to try to go overboard on this recommendation, however. You839**must** include all of the header files that you are using --- you can include840them either directly or indirectly through another header file. To make sure841that you don't accidentally forget to include a header file in your module842header, make sure to include your module header **first** in the implementation843file (as mentioned above). This way there won't be any hidden dependencies that844you'll find out about later.845 846Keep "Internal" Headers Private847^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^848 849Many modules have a complex implementation that causes them to use more than one850implementation (``.cpp``) file. It is often tempting to put the internal851communication interface (helper classes, extra functions, etc) in the public852module header file. Don't do this!853 854If you really need to do something like this, put a private header file in the855same directory as the source files, and include it locally. This ensures that856your private interface remains private and undisturbed by outsiders.857 858.. note::859 860 It's okay to put extra implementation methods in a public class itself. Just861 make them private (or protected) and all is well.862 863Use Namespace Qualifiers to Define Previously Declared Symbols864^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^865 866When providing an out-of-line definition for various symbols (variables,867functions, opaque classes) in a source file, do not open namespace blocks in the868source file. Instead, use namespace qualifiers to help ensure that your869definition matches an existing declaration. Do this:870 871.. code-block:: c++872 873 // Foo.h874 namespace llvm {875 extern int FooVal;876 int foo(const char *s);877 878 namespace detail {879 class FooImpl;880 } // namespace detail881 } // namespace llvm882 883 // Foo.cpp884 #include "Foo.h"885 using namespace llvm;886 887 int llvm::FooVal;888 889 int llvm::foo(const char *s) {890 // ...891 }892 893 class detail::FooImpl {894 // ...895 }896 897Doing this helps to avoid bugs where the definition does not match the898declaration from the header. For example, the following C++ code defines a new899overload of ``llvm::foo`` instead of providing a definition for the existing900function declared in the header:901 902.. code-block:: c++903 904 // Foo.cpp905 #include "Foo.h"906 namespace llvm {907 int foo(char *s) { // Mismatch between "const char *" and "char *"908 }909 } // namespace llvm910 911This error will not be caught until the build is nearly complete, when the912linker fails to find a definition for any uses of the original function. If the913function were instead defined with a namespace qualifier, the error would have914been caught immediately when the definition was compiled.915 916Class method implementations must already name the class and new overloads917cannot be introduced out of line, so this recommendation does not apply to them.918 919.. _early exits:920 921Use Early Exits and ``continue`` to Simplify Code922^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^923 924When reading code, keep in mind how much state and how many previous decisions925have to be remembered by the reader to understand a block of code. Aim to926reduce indentation where possible when it doesn't make it more difficult to927understand the code. One great way to do this is by making use of early exits928and the ``continue`` keyword in long loops. Consider this code that does not929use an early exit:930 931.. code-block:: c++932 933 Value *doSomething(Instruction *I) {934 if (!I->isTerminator() &&935 I->hasOneUse() && doOtherThing(I)) {936 ... some long code ....937 }938 939 return 0;940 }941 942This code has several problems if the body of the ``'if'`` is large. When943you're looking at the top of the function, it isn't immediately clear that this944*only* does interesting things with non-terminator instructions, and only945applies to things with the other predicates. Second, it is relatively difficult946to describe (in comments) why these predicates are important because the ``if``947statement makes it difficult to lay out the comments. Third, when you're deep948within the body of the code, it is indented an extra level. Finally, when949reading the top of the function, it isn't clear what the result is if the950predicate isn't true; you have to read to the end of the function to know that951it returns null.952 953It is much preferred to format the code like this:954 955.. code-block:: c++956 957 Value *doSomething(Instruction *I) {958 // Terminators never need 'something' done to them because ...959 if (I->isTerminator())960 return 0;961 962 // We conservatively avoid transforming instructions with multiple uses963 // because goats like cheese.964 if (!I->hasOneUse())965 return 0;966 967 // This is really just here for example.968 if (!doOtherThing(I))969 return 0;970 971 ... some long code ....972 }973 974This fixes these problems. A similar problem frequently happens in ``for``975loops. A silly example is something like this:976 977.. code-block:: c++978 979 for (Instruction &I : BB) {980 if (auto *BO = dyn_cast<BinaryOperator>(&I)) {981 Value *LHS = BO->getOperand(0);982 Value *RHS = BO->getOperand(1);983 if (LHS != RHS) {984 ...985 }986 }987 }988 989When you have very, very small loops, this sort of structure is fine. But if it990exceeds more than 10-15 lines, it becomes difficult for people to read and991understand at a glance. The problem with this sort of code is that it gets very992nested very quickly. This means that the reader of the code has to keep a lot of993context in their brain to remember what is going immediately on in the loop,994because they don't know if/when the ``if`` conditions will have ``else``\s etc.995It is strongly preferred to structure the loop like this:996 997.. code-block:: c++998 999 for (Instruction &I : BB) {1000 auto *BO = dyn_cast<BinaryOperator>(&I);1001 if (!BO) continue;1002 1003 Value *LHS = BO->getOperand(0);1004 Value *RHS = BO->getOperand(1);1005 if (LHS == RHS) continue;1006 1007 ...1008 }1009 1010This has all the benefits of using early exits for functions: it reduces the nesting1011of the loop, it makes it easier to describe why the conditions are true, and it1012makes it obvious to the reader that there is no ``else`` coming up that they1013have to push context into their brain for. If a loop is large, this can be a1014big understandability win.1015 1016Don't use ``else`` after a ``return``1017^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1018 1019For similar reasons as above (reduction of indentation and easier reading), please1020do not use ``'else'`` or ``'else if'`` after something that interrupts control1021flow --- like ``return``, ``break``, ``continue``, ``goto``, etc. For example:1022 1023.. code-block:: c++1024 1025 case 'J': {1026 if (Signed) {1027 Type = Context.getsigjmp_bufType();1028 if (Type.isNull()) {1029 Error = ASTContext::GE_Missing_sigjmp_buf;1030 return QualType();1031 } else {1032 break; // Unnecessary.1033 }1034 } else {1035 Type = Context.getjmp_bufType();1036 if (Type.isNull()) {1037 Error = ASTContext::GE_Missing_jmp_buf;1038 return QualType();1039 } else {1040 break; // Unnecessary.1041 }1042 }1043 }1044 1045It is better to write it like this:1046 1047.. code-block:: c++1048 1049 case 'J':1050 if (Signed) {1051 Type = Context.getsigjmp_bufType();1052 if (Type.isNull()) {1053 Error = ASTContext::GE_Missing_sigjmp_buf;1054 return QualType();1055 }1056 } else {1057 Type = Context.getjmp_bufType();1058 if (Type.isNull()) {1059 Error = ASTContext::GE_Missing_jmp_buf;1060 return QualType();1061 }1062 }1063 break;1064 1065Or better yet (in this case) as:1066 1067.. code-block:: c++1068 1069 case 'J':1070 if (Signed)1071 Type = Context.getsigjmp_bufType();1072 else1073 Type = Context.getjmp_bufType();1074 1075 if (Type.isNull()) {1076 Error = Signed ? ASTContext::GE_Missing_sigjmp_buf :1077 ASTContext::GE_Missing_jmp_buf;1078 return QualType();1079 }1080 break;1081 1082The idea is to reduce indentation and the amount of code you have to keep track1083of when reading the code.1084 1085Note: this advice does not apply to a ``constexpr if`` statement. The1086substatement of the ``else`` clause may be a discarded statement, so removing1087the ``else`` can cause unexpected template instantiations. Thus, the following1088example is correct:1089 1090.. code-block:: c++1091 1092 template<typename T>1093 static constexpr bool VarTempl = true;1094 1095 template<typename T>1096 int func() {1097 if constexpr (VarTempl<T>)1098 return 1;1099 else1100 static_assert(!VarTempl<T>);1101 }1102 1103Turn Predicate Loops into Predicate Functions1104^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1105 1106It is very common to write small loops that just compute a boolean value. There1107are a number of ways that people commonly write these, but an example of this1108sort of thing is:1109 1110.. code-block:: c++1111 1112 bool FoundFoo = false;1113 for (unsigned I = 0, E = BarList.size(); I != E; ++I)1114 if (BarList[I]->isFoo()) {1115 FoundFoo = true;1116 break;1117 }1118 1119 if (FoundFoo) {1120 ...1121 }1122 1123Instead of this sort of loop, we prefer to use a predicate function (which may1124be `static`_) that uses `early exits`_:1125 1126.. code-block:: c++1127 1128 /// \returns true if the specified list has an element that is a foo.1129 static bool containsFoo(const std::vector<Bar*> &List) {1130 for (unsigned I = 0, E = List.size(); I != E; ++I)1131 if (List[I]->isFoo())1132 return true;1133 return false;1134 }1135 ...1136 1137 if (containsFoo(BarList)) {1138 ...1139 }1140 1141There are many reasons for doing this: it reduces indentation and factors out1142code which can often be shared by other code that checks for the same predicate.1143More importantly, it *forces you to pick a name* for the function, and forces1144you to write a comment for it. In this silly example, this doesn't add much1145value. However, if the condition is complex, this can make it a lot easier for1146the reader to understand the code that queries for this predicate. Instead of1147being faced with the in-line details of how we check to see if the BarList1148contains a foo, we can trust the function name and continue reading with better1149locality.1150 1151The Low-Level Issues1152--------------------1153 1154Name Types, Functions, Variables, and Enumerators Properly1155^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1156 1157Poorly-chosen names can mislead the reader and cause bugs. We cannot stress1158enough how important it is to use *descriptive* names. Pick names that match1159the semantics and role of the underlying entities, within reason. Avoid1160abbreviations unless they are well known. After picking a good name, make sure1161to use consistent capitalization for the name, as inconsistency requires clients1162to either memorize the APIs or to look it up to find the exact spelling.1163 1164In general, names should be in camel case (e.g. ``TextFileReader`` and1165``isLValue()``). Different kinds of declarations have different rules:1166 1167* **Type names** (including classes, structs, enums, typedefs, etc) should be1168 nouns and start with an upper-case letter (e.g. ``TextFileReader``).1169 1170* **Variable names** should be nouns (as they represent state). The name should1171 be camel case, and start with an upper-case letter (e.g. ``Leader`` or1172 ``Boats``).1173 1174* **Function names** should be verb phrases (as they represent actions), and1175 command-like function should be imperative. The name should be camel case,1176 and start with a lowercase letter (e.g. ``openFile()`` or ``isFoo()``).1177 1178* **Enum declarations** (e.g. ``enum Foo {...}``) are types, so they should1179 follow the naming conventions for types. A common use for enums is as a1180 discriminator for a union, or an indicator of a subclass. When an enum is1181 used for something like this, it should have a ``Kind`` suffix1182 (e.g. ``ValueKind``).1183 1184* **Enumerators** (e.g. ``enum { Foo, Bar }``) and **public member variables**1185 should start with an upper-case letter, just like types. Unless the1186 enumerators are defined in their own small namespace or inside a class,1187 enumerators should have a prefix corresponding to the enum declaration name.1188 For example, ``enum ValueKind { ... };`` may contain enumerators like1189 ``VK_Argument``, ``VK_BasicBlock``, etc. Enumerators that are just1190 convenience constants are exempt from the requirement for a prefix. For1191 instance:1192 1193 .. code-block:: c++1194 1195 enum {1196 MaxSize = 42,1197 Density = 121198 };1199 1200As an exception, classes that mimic STL classes can have member names in STL's1201style of lowercase words separated by underscores (e.g. ``begin()``,1202``push_back()``, and ``empty()``). Classes that provide multiple1203iterators should add a singular prefix to ``begin()`` and ``end()``1204(e.g. ``global_begin()`` and ``use_begin()``).1205 1206Here are some examples:1207 1208.. code-block:: c++1209 1210 class VehicleMaker {1211 ...1212 Factory<Tire> F; // Avoid: a non-descriptive abbreviation.1213 Factory<Tire> Factory; // Better: more descriptive.1214 Factory<Tire> TireFactory; // Even better: if VehicleMaker has more than one1215 // kind of factories.1216 };1217 1218 Vehicle makeVehicle(VehicleType Type) {1219 VehicleMaker M; // Might be OK if scope is small.1220 Tire Tmp1 = M.makeTire(); // Avoid: 'Tmp1' provides no information.1221 Light Headlight = M.makeLight("head"); // Good: descriptive.1222 ...1223 }1224 1225Assert Liberally1226^^^^^^^^^^^^^^^^1227 1228Use the "``assert``" macro to its fullest. Check all of your preconditions and1229assumptions. You never know when a bug (not necessarily even yours) might be1230caught early by an assertion, which reduces debugging time dramatically. The1231"``<cassert>``" header file is probably already included by the header files you1232are using, so it doesn't cost anything to use it.1233 1234To further assist with debugging, make sure to put some kind of error message in1235the assertion statement, which is printed if the assertion is tripped. This1236helps the poor debugger make sense of why an assertion is being made and1237enforced, and hopefully what to do about it. Here is one complete example:1238 1239.. code-block:: c++1240 1241 inline Value *getOperand(unsigned I) {1242 assert(I < Operands.size() && "getOperand() out of range!");1243 return Operands[I];1244 }1245 1246Here are more examples:1247 1248.. code-block:: c++1249 1250 assert(Ty->isPointerType() && "Can't allocate a non-pointer type!");1251 1252 assert((Opcode == Shl || Opcode == Shr) && "ShiftInst Opcode invalid!");1253 1254 assert(idx < getNumSuccessors() && "Successor # out of range!");1255 1256 assert(V1.getType() == V2.getType() && "Constant types must be identical!");1257 1258 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");1259 1260You get the idea.1261 1262In the past, asserts were used to indicate a piece of code that should not be1263reached. These were typically of the form:1264 1265.. code-block:: c++1266 1267 assert(0 && "Invalid radix for integer literal");1268 1269This has a few issues, the main one being that some compilers might not1270understand the assertion, or warn about a missing return in builds where1271assertions are compiled out.1272 1273Today, we have something much better: ``llvm_unreachable``:1274 1275.. code-block:: c++1276 1277 llvm_unreachable("Invalid radix for integer literal");1278 1279When assertions are enabled, this will print the message if it's ever reached1280and then exit the program. When assertions are disabled (i.e. in release1281builds), ``llvm_unreachable`` becomes a hint to compilers to skip generating1282code for this branch. If the compiler does not support this, it will fall back1283to the "abort" implementation.1284 1285Use ``llvm_unreachable`` to mark a specific point in code that should never be1286reached. This is especially desirable for addressing warnings about unreachable1287branches, etc., but can be used whenever reaching a particular code path is1288unconditionally a bug (not originating from user input; see below) of some kind.1289Use of ``assert`` should always include a testable predicate (as opposed to1290``assert(false)``).1291 1292If the error condition can be triggered by user input then the1293recoverable error mechanism described in :doc:`ProgrammersManual` should be1294used instead. In cases where this is not practical, ``report_fatal_error`` may1295be used.1296 1297Another issue is that values used only by assertions will produce an "unused1298value" warning when assertions are disabled. For example, this code will warn:1299 1300.. code-block:: c++1301 1302 unsigned Size = V.size();1303 assert(Size > 42 && "Vector smaller than it should be");1304 1305 bool NewToSet = Myset.insert(Value);1306 assert(NewToSet && "The value shouldn't be in the set yet");1307 1308These are two interesting different cases. In the first case, the call to1309``V.size()`` is only useful for the assert, and we don't want it executed when1310assertions are disabled. Code like this should move the call into the assert1311itself. In the second case, the side effects of the call must happen whether1312the assert is enabled or not. In this case, the value should be defined using1313the ``[[maybe_unused]]`` attribute to suppress the warning. To be specific, it is1314preferred to write the code like this:1315 1316.. code-block:: c++1317 1318 assert(V.size() > 42 && "Vector smaller than it should be");1319 1320 [[maybe_unused]] bool NewToSet = Myset.insert(Value);1321 assert(NewToSet && "The value shouldn't be in the set yet");1322 1323In C code where ``[[maybe_unused]]`` is not supported, use ``void`` cast to1324suppress an unused variable warning as follows:1325 1326.. code-block:: c1327 1328 LLVMValueRef Value = LLVMMetadataAsValue(Context, NodeMD);1329 assert(LLVMIsAValueAsMetadata(Value) != NULL);1330 (void)Value;1331 1332Do Not Use ``using namespace std``1333^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1334 1335In LLVM, we prefer to explicitly prefix all identifiers from the standard1336namespace with an "``std::``" prefix, rather than rely on "``using namespace1337std;``".1338 1339In header files, adding a ``'using namespace XXX'`` directive pollutes the1340namespace of any source file that ``#include``\s the header, creating1341maintenance issues.1342 1343In implementation files (e.g. ``.cpp`` files), the rule is more of a stylistic1344rule, but is still important. Basically, using explicit namespace prefixes1345makes the code **clearer**, because it is immediately obvious what facilities1346are being used and where they are coming from. And **more portable**, because1347namespace clashes cannot occur between LLVM code and other namespaces. The1348portability rule is important because different standard library implementations1349expose different symbols (potentially ones they shouldn't), and future revisions1350to the C++ standard will add more symbols to the ``std`` namespace. As such, we1351never use ``'using namespace std;'`` in LLVM.1352 1353The exception to the general rule (i.e. it's not an exception for the ``std``1354namespace) is for implementation files. For example, all of the code in the1355LLVM project implements code that lives in the 'llvm' namespace. As such, it is1356ok, and actually clearer, for the ``.cpp`` files to have a ``'using namespace1357llvm;'`` directive at the top, after the ``#include``\s. This reduces1358indentation in the body of the file for source editors that indent based on1359braces, and keeps the conceptual context cleaner. The general form of this rule1360is that any ``.cpp`` file that implements code in any namespace may use that1361namespace (and its parents'), but should not use any others.1362 1363Provide a Virtual Method Anchor for Classes in Headers1364^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1365 1366If a class is defined in a header file and has a vtable (either it has virtual1367methods or it derives from classes with virtual methods), it must always have at1368least one out-of-line virtual method in the class. Without this, the compiler1369will copy the vtable and RTTI into every ``.o`` file that ``#include``\s the1370header, bloating ``.o`` file sizes and increasing link times.1371 1372Don't use default labels in fully covered switches over enumerations1373^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1374 1375``-Wswitch`` warns if a switch, without a default label, over an enumeration1376does not cover every enumeration value. If you write a default label on a fully1377covered switch over an enumeration then the ``-Wswitch`` warning won't fire1378when new elements are added to that enumeration. To help avoid adding these1379kinds of defaults, Clang has the warning ``-Wcovered-switch-default`` which is1380off by default but turned on when building LLVM with a version of Clang that1381supports the warning.1382 1383A knock-on effect of this stylistic requirement is that when building LLVM with1384GCC you may get warnings related to "control may reach end of non-void function"1385if you return from each case of a covered switch-over-enum because GCC assumes1386that the enum expression may take any representable value, not just those of1387individual enumerators. To suppress this warning, use ``llvm_unreachable`` after1388the switch.1389 1390Use range-based ``for`` loops wherever possible1391^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1392 1393The introduction of range-based ``for`` loops in C++11 means that explicit1394manipulation of iterators is rarely necessary. We use range-based ``for``1395loops wherever possible for all newly added code. For example:1396 1397.. code-block:: c++1398 1399 BasicBlock *BB = ...1400 for (Instruction &I : *BB)1401 ... use I ...1402 1403Usage of ``std::for_each()``/``llvm::for_each()`` functions is discouraged,1404unless the callable object already exists.1405 1406Don't evaluate ``end()`` every time through a loop1407^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1408 1409In cases where range-based ``for`` loops can't be used and it is necessary1410to write an explicit iterator-based loop, pay close attention to whether1411``end()`` is re-evaluated on each loop iteration. One common mistake is to1412write a loop in this style:1413 1414.. code-block:: c++1415 1416 BasicBlock *BB = ...1417 for (auto I = BB->begin(); I != BB->end(); ++I)1418 ... use I ...1419 1420The problem with this construct is that it evaluates "``BB->end()``" every time1421through the loop. Instead of writing the loop like this, we strongly prefer1422loops to be written so that they evaluate it once before the loop starts. A1423convenient way to do this is like so:1424 1425.. code-block:: c++1426 1427 BasicBlock *BB = ...1428 for (auto I = BB->begin(), E = BB->end(); I != E; ++I)1429 ... use I ...1430 1431The observant may quickly point out that these two loops may have different1432semantics: if the container (a basic block in this case) is being mutated, then1433"``BB->end()``" may change its value every time through the loop and the second1434loop may not in fact be correct. If you actually do depend on this behavior,1435please write the loop in the first form and add a comment indicating that you1436did it intentionally.1437 1438Why do we prefer the second form (when correct)? Writing the loop in the first1439form has two problems. First, it may be less efficient than evaluating it at the1440start of the loop. In this case, the cost is probably minor --- a few extra1441loads every time through the loop. However, if the base expression is more1442complex, then the cost can rise quickly. I've seen loops where the end1443expression was actually something like: "``SomeMap[X]->end()``" and map lookups1444really aren't cheap. By writing it in the second form consistently, you1445eliminate the issue entirely and don't even have to think about it.1446 1447The second (even bigger) issue is that writing the loop in the first form hints1448to the reader that the loop is mutating the container (a fact that a comment1449would handily confirm!). If you write the loop in the second form, it is1450immediately obvious without even looking at the body of the loop that the1451container isn't being modified, which makes it easier to read the code and1452understand what it does.1453 1454While the second form of the loop is a few extra keystrokes, we do strongly1455prefer it.1456 1457``#include <iostream>`` is Forbidden1458^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1459 1460The use of ``#include <iostream>`` in library files is hereby **forbidden**,1461because many common implementations transparently inject a `static constructor`_1462into every translation unit that includes it.1463 1464Note that using the other stream headers (``<sstream>`` for example) is not1465problematic in this regard --- just ``<iostream>``. However, ``raw_ostream``1466provides various APIs that are better performing for almost every use than1467``std::ostream`` style APIs.1468 1469.. note::1470 1471 New code should always use `raw_ostream`_ for writing, or the1472 ``llvm::MemoryBuffer`` API for reading files.1473 1474.. _raw_ostream:1475 1476Use ``raw_ostream``1477^^^^^^^^^^^^^^^^^^^1478 1479LLVM includes a lightweight, simple, and efficient stream implementation in1480``llvm/Support/raw_ostream.h``, which provides all of the common features of1481``std::ostream``. All new code should use ``raw_ostream`` instead of1482``ostream``.1483 1484Unlike ``std::ostream``, ``raw_ostream`` is not a template and can be forward1485declared as ``class raw_ostream``. Public headers should generally not include1486the ``raw_ostream`` header, but use forward declarations and constant references1487to ``raw_ostream`` instances.1488 1489Avoid ``std::endl``1490^^^^^^^^^^^^^^^^^^^1491 1492The ``std::endl`` modifier, when used with ``iostreams`` outputs a newline to1493the output stream specified. In addition to doing this, however, it also1494flushes the output stream. In other words, these are equivalent:1495 1496.. code-block:: c++1497 1498 std::cout << std::endl;1499 std::cout << '\n' << std::flush;1500 1501Most of the time, you probably have no reason to flush the output stream, so1502it's better to use a literal ``'\n'``.1503 1504Don't use ``inline`` when defining a function in a class definition1505^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1506 1507A member function defined in a class definition is implicitly inline, so don't1508put the ``inline`` keyword in this case.1509 1510Don't:1511 1512.. code-block:: c++1513 1514 class Foo {1515 public:1516 inline void bar() {1517 // ...1518 }1519 };1520 1521Do:1522 1523.. code-block:: c++1524 1525 class Foo {1526 public:1527 void bar() {1528 // ...1529 }1530 };1531 1532Microscopic Details1533-------------------1534 1535This section describes preferred low-level formatting guidelines along with1536reasoning on why we prefer them.1537 1538Spaces Before Parentheses1539^^^^^^^^^^^^^^^^^^^^^^^^^1540 1541Put a space before an open parenthesis only in control flow statements, but not1542in normal function call expressions and function-like macros. For example:1543 1544.. code-block:: c++1545 1546 if (X) ...1547 for (I = 0; I != 100; ++I) ...1548 while (LLVMRocks) ...1549 1550 somefunc(42);1551 assert(3 != 4 && "laws of math are failing me");1552 1553 A = foo(42, 92) + bar(X);1554 1555The reason for doing this is not completely arbitrary. This style makes control1556flow operators stand out more, and makes expressions flow better.1557 1558Prefer Preincrement1559^^^^^^^^^^^^^^^^^^^1560 1561Hard fast rule: Preincrement (``++X``) may be no slower than postincrement1562(``X++``) and could very well be a lot faster than it. Use preincrementation1563whenever possible.1564 1565The semantics of postincrement include making a copy of the value being1566incremented, returning it, and then preincrementing the "work value". For1567primitive types, this isn't a big deal. But for iterators, it can be a huge1568issue (for example, some iterators contain stack and set objects in them...1569copying an iterator could invoke the copy ctor's of these as well). In general,1570get in the habit of always using preincrement, and you won't have a problem.1571 1572 1573Namespace Indentation1574^^^^^^^^^^^^^^^^^^^^^1575 1576In general, we strive to reduce indentation wherever possible. This is useful1577because we want code to `fit into 80 columns`_ without excessive wrapping, but1578also because it makes it easier to understand the code. To facilitate this and1579avoid some insanely deep nesting on occasion, don't indent namespaces. If it1580helps readability, feel free to add a comment indicating what namespace is1581being closed by a ``}``. For example:1582 1583.. code-block:: c++1584 1585 namespace llvm {1586 namespace knowledge {1587 1588 /// This class represents things that Smith can have an intimate1589 /// understanding of and contains the data associated with it.1590 class Grokable {1591 ...1592 public:1593 explicit Grokable() { ... }1594 virtual ~Grokable() = 0;1595 1596 ...1597 1598 };1599 1600 } // namespace knowledge1601 } // namespace llvm1602 1603 1604Feel free to skip the closing comment when the namespace being closed is1605obvious for any reason. For example, the outer-most namespace in a header file1606is rarely a source of confusion. But namespaces both anonymous and named in1607source files that are being closed half way through the file probably could use1608clarification.1609 1610.. _static:1611 1612Restrict Visibility1613^^^^^^^^^^^^^^^^^^^1614 1615Functions and variables should have the most restricted visibility possible.1616 1617For class members, that means using appropriate ``private``, ``protected``, or1618``public`` keyword to restrict their access.1619 1620For non-member functions, variables, and classes, that means restricting1621visibility to a single ``.cpp`` file if it is not referenced outside that file.1622 1623Visibility of file-scope non-member variables and functions can be restricted to1624the current translation unit by using either the ``static`` keyword or an anonymous1625namespace.1626 1627Anonymous namespaces are a great language feature that tells the C++1628compiler that the contents of the namespace are only visible within the current1629translation unit, allowing more aggressive optimization and eliminating the1630possibility of symbol name collisions.1631 1632Anonymous namespaces are to C++ as ``static`` is to C functions and global1633variables. While ``static`` is available in C++, anonymous namespaces are more1634general: they can make entire classes private to a file.1635 1636The problem with anonymous namespaces is that they naturally want to encourage1637indentation of their body, and they reduce locality of reference: if you see a1638random function definition in a C++ file, it is easy to see if it is marked1639static, but seeing if it is in an anonymous namespace requires scanning a big1640chunk of the file.1641 1642Because of this, we have a simple guideline: make anonymous namespaces as small1643as possible, and only use them for class declarations. For example:1644 1645.. code-block:: c++1646 1647 namespace {1648 class StringSort {1649 ...1650 public:1651 StringSort(...)1652 bool operator<(const char *RHS) const;1653 };1654 } // namespace1655 1656 static void runHelper() {1657 ...1658 }1659 1660 bool StringSort::operator<(const char *RHS) const {1661 ...1662 }1663 1664Avoid putting declarations other than classes into anonymous namespaces:1665 1666.. code-block:: c++1667 1668 namespace {1669 1670 // ... many declarations ...1671 1672 void runHelper() {1673 ...1674 }1675 1676 // ... many declarations ...1677 1678 } // namespace1679 1680When you are looking at ``runHelper`` in the middle of a large C++ file,1681you have no immediate way to tell if this function is local to the file.1682 1683In contrast, when the function is marked static, you don't need to cross-reference1684faraway places in the file to tell that the function is local:1685 1686.. code-block:: c++1687 1688 static void runHelper() {1689 ...1690 }1691 1692Don't Use Braces on Simple Single-Statement Bodies of if/else/loop Statements1693^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1694 1695When writing the body of an ``if``, ``else``, or ``for``/``while`` loop1696statement, we aim to reduce unnecessary line noise.1697 1698**Omit braces when:**1699 1700* The body consists of a single **simple** statement.1701* The single statement is not preceded by a comment.1702 (Hoist comments above the control statement if you can.)1703* An ``else`` clause, if present, also meets the above criteria (single1704 simple statement, no associated comments).1705 1706**Use braces in all other cases, including:**1707 1708* Multi-statement bodies1709* Single-statement bodies with non-hoistable comments1710* Complex single-statement bodies (e.g., deep nesting, complex nested1711 loops)1712* Inconsistent bracing within ``if``/``else if``/``else`` chains (if one1713 block requires braces, all must)1714* ``if`` statements ending with a nested ``if`` lacking an ``else`` (to1715 prevent "dangling else")1716 1717The examples below provide guidelines for these cases:1718 1719.. code-block:: c++1720 1721 // Omit the braces since the body is simple and clearly associated with the1722 // `if`.1723 if (isa<FunctionDecl>(D))1724 handleFunctionDecl(D);1725 else if (isa<VarDecl>(D))1726 handleVarDecl(D);1727 1728 // Here we document the condition itself and not the body.1729 if (isa<VarDecl>(D)) {1730 // It is necessary that we explain the situation with this surprisingly long1731 // comment, so it would be unclear without the braces whether the following1732 // statement is in the scope of the `if`.1733 // Because the condition is documented, we can't really hoist this1734 // comment that applies to the body above the `if`.1735 handleOtherDecl(D);1736 }1737 1738 // Use braces on the outer `if` to avoid a potential dangling `else`1739 // situation.1740 if (isa<VarDecl>(D)) {1741 if (shouldProcessAttr(A))1742 handleAttr(A);1743 }1744 1745 // Use braces for the `if` block to keep it uniform with the `else` block.1746 if (isa<FunctionDecl>(D)) {1747 handleFunctionDecl(D);1748 } else {1749 // In this `else` case, it is necessary that we explain the situation with1750 // this surprisingly long comment, so it would be unclear without the braces1751 // whether the following statement is in the scope of the `if`.1752 handleOtherDecl(D);1753 }1754 1755 // Use braces for the `else if` and `else` block to keep it uniform with the1756 // `if` block.1757 if (isa<FunctionDecl>(D)) {1758 verifyFunctionDecl(D);1759 handleFunctionDecl(D);1760 } else if (isa<GlobalVarDecl>(D)) {1761 handleGlobalVarDecl(D);1762 } else {1763 handleOtherDecl(D);1764 }1765 1766 // This should also omit braces. The `for` loop contains only a single1767 // statement, so it shouldn't have braces. The `if` also only contains a1768 // single simple statement (the `for` loop), so it also should omit braces.1769 if (isa<FunctionDecl>(D))1770 for (auto *A : D.attrs())1771 handleAttr(A);1772 1773 // Use braces for a `do-while` loop and its enclosing statement.1774 if (Tok->is(tok::l_brace)) {1775 do {1776 Tok = Tok->Next;1777 } while (Tok);1778 }1779 1780 // Use braces for the outer `if` since the nested `for` is braced.1781 if (isa<FunctionDecl>(D)) {1782 for (auto *A : D.attrs()) {1783 // In this `for` loop body, it is necessary that we explain the situation1784 // with this surprisingly long comment, forcing braces on the `for` block.1785 handleAttr(A);1786 }1787 }1788 1789 // Use braces on the outer block because there are more than two levels of1790 // nesting.1791 if (isa<FunctionDecl>(D)) {1792 for (auto *A : D.attrs())1793 for (ssize_t i : llvm::seq<ssize_t>(count))1794 handleAttrOnDecl(D, A, i);1795 }1796 1797 // Use braces on the outer block because of a nested `if`; otherwise, the1798 // compiler would warn: `add explicit braces to avoid dangling else`1799 if (auto *D = dyn_cast<FunctionDecl>(D)) {1800 if (shouldProcess(D))1801 handleVarDecl(D);1802 else1803 markAsIgnored(D);1804 }1805 1806Use Unix line endings for files1807^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1808 1809Use Unix line endings for all files. CRLF line endings are allowed as an1810exception for test files that intend to test CRLF handling or when the file1811format requires it (like ``.bat`` or ``.rc`` files).1812 1813See Also1814========1815 1816A lot of these comments and recommendations have been culled from other sources.1817Two particularly important books for our work are:1818 1819#. `Effective C++1820 <https://www.amazon.com/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0321334876>`_1821 by Scott Meyers. Also interesting and useful are "More Effective C++" and1822 "Effective STL" by the same author.1823 1824#. `Large-Scale C++ Software Design1825 <https://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620>`_1826 by John Lakos1827 1828If you get some free time, and you haven't read them: do so, you might learn1829something.1830