1=====================
2LLVM Coding Standards
3=====================
4
5.. contents::
6   :local:
7
8Introduction
9============
10
11This document describes coding standards that are used in the LLVM project.
12Although no coding standards should be regarded as absolute requirements to be
13followed in all instances, coding standards are
14particularly important for large-scale code bases that follow a library-based
15design (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 and
25    easy to follow.**
26
27Note that some code bases (e.g. ``libc++``) have special reasons to deviate
28from the coding standards.  For example, in the case of ``libc++``, this is
29because the naming and other conventions are dictated by the C++ standard.
30
31There are some conventions that are not uniformly followed in the code base
32(e.g. the naming convention).  This is because they are relatively new, and a
33lot of code was written before they were put in place.  Our long term goal is
34for the entire codebase to follow the convention, but we explicitly *do not*
35want patches that do large-scale reformatting of existing code.  On the other
36hand, it is reasonable to rename the methods of a class if you're about to
37change it in some other way.  Please commit such changes separately to
38make code review easier.
39
40The ultimate goal of these guidelines is to increase the readability and
41maintainability of our common source base.
42
43Languages, Libraries, and Standards
44===================================
45
46Most source code in LLVM and other LLVM projects using these coding standards
47is C++ code. There are some places where C code is used either due to
48environment restrictions, historical restrictions, or due to third-party source
49code imported into the tree. Generally, our preference is for standards
50conforming, modern, and portable C++ code as the implementation language of
51choice.
52
53C++ Standard Versions
54---------------------
55
56Unless otherwise documented, LLVM subprojects are written using standard C++14
57code and avoid unnecessary vendor-specific extensions.
58
59Nevertheless, we restrict ourselves to features which are available in the
60major toolchains supported as host compilers (see :doc:`GettingStarted` page,
61section `Software`).
62
63Each toolchain provides a good reference for what it accepts:
64
65* Clang: https://clang.llvm.org/cxx_status.html
66* GCC: https://gcc.gnu.org/projects/cxx-status.html#cxx14
67* MSVC: https://msdn.microsoft.com/en-us/library/hh567368.aspx
68
69
70C++ Standard Library
71--------------------
72
73Instead of implementing custom data structures, we encourage the use of C++
74standard library facilities or LLVM support libraries whenever they are
75available for a particular task. LLVM and related projects emphasize and rely
76on the standard library facilities and the LLVM support libraries as much as
77possible.
78
79LLVM support libraries (for example, `ADT
80<https://github.com/llvm/llvm-project/tree/master/llvm/include/llvm/ADT>`_)
81implement specialized data structures or functionality missing in the standard
82library. Such libraries are usually implemented in the ``llvm`` namespace and
83follow the expected standard interface, when there is one.
84
85When both C++ and the LLVM support libraries provide similar functionality, and
86there isn't a specific reason to favor the C++ implementation, it is generally
87preferable to use the LLVM library. For example, ``llvm::DenseMap`` should
88almost always be used instead of ``std::map`` or ``std::unordered_map``, and
89``llvm::SmallVector`` should usually be used instead of ``std::vector``.
90
91We explicitly avoid some standard facilities, like the I/O streams, and instead
92use LLVM's streams library (raw_ostream_). More detailed information on these
93subjects is available in the :doc:`ProgrammersManual`.
94
95For more information about LLVM's data structures and the tradeoffs they make,
96please consult [that section of the programmer's
97manual](https://llvm.org/docs/ProgrammersManual.html#picking-the-right-data-structure-for-a-task).
98
99Guidelines for Go code
100----------------------
101
102Any code written in the Go programming language is not subject to the
103formatting rules below. Instead, we adopt the formatting rules enforced by
104the `gofmt`_ tool.
105
106Go code should strive to be idiomatic. Two good sets of guidelines for what
107this means are `Effective Go`_ and `Go Code Review Comments`_.
108
109.. _gofmt:
110  https://golang.org/cmd/gofmt/
111
112.. _Effective Go:
113  https://golang.org/doc/effective_go.html
114
115.. _Go Code Review Comments:
116  https://github.com/golang/go/wiki/CodeReviewComments
117
118Mechanical Source Issues
119========================
120
121Source Code Formatting
122----------------------
123
124Commenting
125^^^^^^^^^^
126
127Comments are important for readability and maintainability. When writing comments,
128write them as English prose, using proper capitalization, punctuation, etc.
129Aim to describe what the code is trying to do and why, not *how* it does it at
130a micro level. Here are a few important things to document:
131
132.. _header file comment:
133
134File Headers
135""""""""""""
136
137Every source file should have a header on it that describes the basic purpose of
138the file. The standard header looks like this:
139
140.. code-block:: c++
141
142  //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
143  //
144  // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
145  // See https://llvm.org/LICENSE.txt for license information.
146  // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
147  //
148  //===----------------------------------------------------------------------===//
149  ///
150  /// \file
151  /// This file contains the declaration of the Instruction class, which is the
152  /// base class for all of the VM instructions.
153  ///
154  //===----------------------------------------------------------------------===//
155
156A few things to note about this particular format: The "``-*- C++ -*-``" string
157on the first line is there to tell Emacs that the source file is a C++ file, not
158a C file (Emacs assumes ``.h`` files are C files by default).
159
160.. note::
161
162    This tag is not necessary in ``.cpp`` files.  The name of the file is also
163    on the first line, along with a very short description of the purpose of the
164    file.
165
166The next section in the file is a concise note that defines the license that the
167file is released under.  This makes it perfectly clear what terms the source
168code can be distributed under and should not be modified in any way.
169
170The main body is a `Doxygen <http://www.doxygen.nl/>`_ comment (identified by
171the ``///`` comment marker instead of the usual ``//``) describing the purpose
172of the file.  The first sentence (or a passage beginning with ``\brief``) is
173used as an abstract.  Any additional information should be separated by a blank
174line.  If an algorithm is based on a paper or is described in another source,
175provide a reference.
176
177Class overviews
178"""""""""""""""
179
180Classes are a fundamental part of an object-oriented design.  As such, a
181class definition should have a comment block that explains what the class is
182used for and how it works.  Every non-trivial class is expected to have a
183``doxygen`` comment block.
184
185Method information
186""""""""""""""""""
187
188Methods and global functions should also be documented.  A quick note about
189what it does and a description of the edge cases is all that is necessary here.
190The reader should be able to understand how to use interfaces without reading
191the code itself.
192
193Good things to talk about here are what happens when something unexpected
194happens, for instance, does the method return null?
195
196Comment Formatting
197^^^^^^^^^^^^^^^^^^
198
199In general, prefer C++-style comments (``//`` for normal comments, ``///`` for
200``doxygen`` documentation comments).  There are a few cases when it is
201useful to use C-style (``/* */``) comments however:
202
203#. When writing C code to be compatible with C89.
204
205#. When writing a header file that may be ``#include``\d by a C source file.
206
207#. When writing a source file that is used by a tool that only accepts C-style
208   comments.
209
210#. When documenting the significance of constants used as actual parameters in
211   a call. This is most helpful for ``bool`` parameters, or passing ``0`` or
212   ``nullptr``. The comment should contain the parameter name, which ought to be
213   meaningful. For example, it's not clear what the parameter means in this call:
214
215   .. code-block:: c++
216
217     Object.emitName(nullptr);
218
219   An in-line C-style comment makes the intent obvious:
220
221   .. code-block:: c++
222
223     Object.emitName(/*Prefix=*/nullptr);
224
225Commenting out large blocks of code is discouraged, but if you really have to do
226this (for documentation purposes or as a suggestion for debug printing), use
227``#if 0`` and ``#endif``. These nest properly and are better behaved in general
228than C style comments.
229
230Doxygen Use in Documentation Comments
231^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
232
233Use the ``\file`` command to turn the standard file header into a file-level
234comment.
235
236Include descriptive paragraphs for all public interfaces (public classes,
237member and non-member functions).  Avoid restating the information that can
238be inferred from the API name.  The first sentence (or a paragraph beginning
239with ``\brief``) is used as an abstract. Try to use a single sentence as the
240``\brief`` adds visual clutter.  Put detailed discussion into separate
241paragraphs.
242
243To refer to parameter names inside a paragraph, use the ``\p name`` command.
244Don't use the ``\arg name`` command since it starts a new paragraph that
245contains documentation for the parameter.
246
247Wrap non-inline code examples in ``\code ... \endcode``.
248
249To document a function parameter, start a new paragraph with the
250``\param name`` command.  If the parameter is used as an out or an in/out
251parameter, use the ``\param [out] name`` or ``\param [in,out] name`` command,
252respectively.
253
254To describe function return value, start a new paragraph with the ``\returns``
255command.
256
257A minimal documentation comment:
258
259.. code-block:: c++
260
261  /// Sets the xyzzy property to \p Baz.
262  void setXyzzy(bool Baz);
263
264A documentation comment that uses all Doxygen features in a preferred way:
265
266.. code-block:: c++
267
268  /// Does foo and bar.
269  ///
270  /// Does not do foo the usual way if \p Baz is true.
271  ///
272  /// Typical usage:
273  /// \code
274  ///   fooBar(false, "quux", Res);
275  /// \endcode
276  ///
277  /// \param Quux kind of foo to do.
278  /// \param [out] Result filled with bar sequence on foo success.
279  ///
280  /// \returns true on success.
281  bool fooBar(bool Baz, StringRef Quux, std::vector<int> &Result);
282
283Don't duplicate the documentation comment in the header file and in the
284implementation file.  Put the documentation comments for public APIs into the
285header file.  Documentation comments for private APIs can go to the
286implementation file.  In any case, implementation files can include additional
287comments (not necessarily in Doxygen markup) to explain implementation details
288as needed.
289
290Don't duplicate function or class name at the beginning of the comment.
291For humans it is obvious which function or class is being documented;
292automatic documentation processing tools are smart enough to bind the comment
293to the correct declaration.
294
295Avoid:
296
297.. code-block:: c++
298
299  // Example.h:
300
301  // example - Does something important.
302  void example();
303
304  // Example.cpp:
305
306  // example - Does something important.
307  void example() { ... }
308
309Preferred:
310
311.. code-block:: c++
312
313  // Example.h:
314
315  /// Does something important.
316  void example();
317
318  // Example.cpp:
319
320  /// Builds a B-tree in order to do foo.  See paper by...
321  void example() { ... }
322
323``#include`` Style
324^^^^^^^^^^^^^^^^^^
325
326Immediately after the `header file comment`_ (and include guards if working on a
327header file), the `minimal list of #includes`_ required by the file should be
328listed.  We prefer these ``#include``\s to be listed in this order:
329
330.. _Main Module Header:
331.. _Local/Private Headers:
332
333#. Main Module Header
334#. Local/Private Headers
335#. LLVM project/subproject headers (``clang/...``, ``lldb/...``, ``llvm/...``, etc)
336#. System ``#include``\s
337
338and each category should be sorted lexicographically by the full path.
339
340The `Main Module Header`_ file applies to ``.cpp`` files which implement an
341interface defined by a ``.h`` file.  This ``#include`` should always be included
342**first** regardless of where it lives on the file system.  By including a
343header file first in the ``.cpp`` files that implement the interfaces, we ensure
344that the header does not have any hidden dependencies which are not explicitly
345``#include``\d in the header, but should be. It is also a form of documentation
346in the ``.cpp`` file to indicate where the interfaces it implements are defined.
347
348LLVM project and subproject headers should be grouped from most specific to least
349specific, for the same reasons described above.  For example, LLDB depends on
350both clang and LLVM, and clang depends on LLVM.  So an LLDB source file should
351include ``lldb`` headers first, followed by ``clang`` headers, followed by
352``llvm`` headers, to reduce the possibility (for example) of an LLDB header
353accidentally picking up a missing include due to the previous inclusion of that
354header in the main source file or some earlier header file.  clang should
355similarly include its own headers before including llvm headers.  This rule
356applies to all LLVM subprojects.
357
358.. _fit into 80 columns:
359
360Source Code Width
361^^^^^^^^^^^^^^^^^
362
363Write your code to fit within 80 columns.
364
365There must be some limit to the width of the code in
366order to allow developers to have multiple files side-by-side in
367windows on a modest display.  If you are going to pick a width limit, it is
368somewhat arbitrary but you might as well pick something standard.  Going with 90
369columns (for example) instead of 80 columns wouldn't add any significant value
370and would be detrimental to printing out code.  Also many other projects have
371standardized on 80 columns, so some people have already configured their editors
372for it (vs something else, like 90 columns).
373
374Whitespace
375^^^^^^^^^^
376
377In all cases, prefer spaces to tabs in source files.  People have different
378preferred indentation levels, and different styles of indentation that they
379like; this is fine.  What isn't fine is that different editors/viewers expand
380tabs out to different tab stops.  This can cause your code to look completely
381unreadable, and it is not worth dealing with.
382
383As always, follow the `Golden Rule`_ above: follow the style of existing code
384if you are modifying and extending it.
385
386Do not add trailing whitespace.  Some common editors will automatically remove
387trailing whitespace when saving a file which causes unrelated changes to appear
388in diffs and commits.
389
390Format Lambdas Like Blocks Of Code
391""""""""""""""""""""""""""""""""""
392
393When formatting a multi-line lambda, format it like a block of code. If there
394is only one multi-line lambda in a statement, and there are no expressions
395lexically after it in the statement, drop the indent to the standard two space
396indent for a block of code, as if it were an if-block opened by the preceding
397part of the statement:
398
399.. code-block:: c++
400
401  std::sort(foo.begin(), foo.end(), [&](Foo a, Foo b) -> bool {
402    if (a.blah < b.blah)
403      return true;
404    if (a.baz < b.baz)
405      return true;
406    return a.bam < b.bam;
407  });
408
409To take best advantage of this formatting, if you are designing an API which
410accepts a continuation or single callable argument (be it a function object, or
411a ``std::function``), it should be the last argument if at all possible.
412
413If there are multiple multi-line lambdas in a statement, or additional
414parameters after the lambda, indent the block two spaces from the indent of the
415``[]``:
416
417.. code-block:: c++
418
419  dyn_switch(V->stripPointerCasts(),
420             [] (PHINode *PN) {
421               // process phis...
422             },
423             [] (SelectInst *SI) {
424               // process selects...
425             },
426             [] (LoadInst *LI) {
427               // process loads...
428             },
429             [] (AllocaInst *AI) {
430               // process allocas...
431             });
432
433Braced Initializer Lists
434""""""""""""""""""""""""
435
436Starting from C++11, there are significantly more uses of braced lists to
437perform initialization. For example, they can be used to construct aggregate
438temporaries in expressions. They now have a natural way of ending up nested
439within each other and within function calls in order to build up aggregates
440(such as option structs) from local variables.
441
442The historically common formatting of braced initialization of aggregate
443variables does not mix cleanly with deep nesting, general expression contexts,
444function arguments, and lambdas. We suggest new code use a simple rule for
445formatting braced initialization lists: act as-if the braces were parentheses
446in a function call. The formatting rules exactly match those already well
447understood for formatting nested function calls. Examples:
448
449.. code-block:: c++
450
451  foo({a, b, c}, {1, 2, 3});
452
453  llvm::Constant *Mask[] = {
454      llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
455      llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
456      llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)};
457
458This formatting scheme also makes it particularly easy to get predictable,
459consistent, and automatic formatting with tools like `Clang Format`_.
460
461.. _Clang Format: https://clang.llvm.org/docs/ClangFormat.html
462
463Language and Compiler Issues
464----------------------------
465
466Treat Compiler Warnings Like Errors
467^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
468
469Compiler warnings are often useful and help improve the code.  Those that are
470not useful, can be often suppressed with a small code change. For example, an
471assignment in the ``if`` condition is often a typo:
472
473.. code-block:: c++
474
475  if (V = getValue()) {
476    ...
477  }
478
479Several compilers will print a warning for the code above. It can be suppressed
480by adding parentheses:
481
482.. code-block:: c++
483
484  if ((V = getValue())) {
485    ...
486  }
487
488Write Portable Code
489^^^^^^^^^^^^^^^^^^^
490
491In almost all cases, it is possible to write completely portable code.  When
492you need to rely on non-portable code, put it behind a well-defined and
493well-documented interface.
494
495Do not use RTTI or Exceptions
496^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
497
498In an effort to reduce code and executable size, LLVM does not use exceptions
499or RTTI (`runtime type information
500<https://en.wikipedia.org/wiki/Run-time_type_information>`_, for example,
501``dynamic_cast<>``).
502
503That said, LLVM does make extensive use of a hand-rolled form of RTTI that use
504templates like :ref:`isa\<>, cast\<>, and dyn_cast\<> <isa>`.
505This form of RTTI is opt-in and can be
506:doc:`added to any class <HowToSetUpLLVMStyleRTTI>`.
507
508.. _static constructor:
509
510Do not use Static Constructors
511^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
512
513Static constructors and destructors (e.g., global variables whose types have a
514constructor or destructor) should not be added to the code base, and should be
515removed wherever possible.
516
517Globals in different source files are initialized in `arbitrary order
518<https://yosefk.com/c++fqa/ctors.html#fqa-10.12>`, making the code more
519difficult to reason about.
520
521Static constructors have negative impact on launch time of programs that use
522LLVM as a library. We would really like for there to be zero cost for linking
523in an additional LLVM target or other library into an application, but static
524constructors undermine this goal.
525
526Use of ``class`` and ``struct`` Keywords
527^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
528
529In C++, the ``class`` and ``struct`` keywords can be used almost
530interchangeably. The only difference is when they are used to declare a class:
531``class`` makes all members private by default while ``struct`` makes all
532members public by default.
533
534* All declarations and definitions of a given ``class`` or ``struct`` must use
535  the same keyword.  For example:
536
537.. code-block:: c++
538
539  // Avoid if `Example` is defined as a struct.
540  class Example;
541
542  // OK.
543  struct Example;
544
545  struct Example { ... };
546
547* ``struct`` should be used when *all* members are declared public.
548
549.. code-block:: c++
550
551  // Avoid using `struct` here, use `class` instead.
552  struct Foo {
553  private:
554    int Data;
555  public:
556    Foo() : Data(0) { }
557    int getData() const { return Data; }
558    void setData(int D) { Data = D; }
559  };
560
561  // OK to use `struct`: all members are public.
562  struct Bar {
563    int Data;
564    Bar() : Data(0) { }
565  };
566
567Do not use Braced Initializer Lists to Call a Constructor
568^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
569
570Starting from C++11 there is a "generalized initialization syntax" which allows
571calling constructors using braced initializer lists. Do not use these to call
572constructors with non-trivial logic or if you care that you're calling some
573*particular* constructor. Those should look like function calls using
574parentheses rather than like aggregate initialization. Similarly, if you need
575to explicitly name the type and call its constructor to create a temporary,
576don't use a braced initializer list. Instead, use a braced initializer list
577(without any type for temporaries) when doing aggregate initialization or
578something notionally equivalent. Examples:
579
580.. code-block:: c++
581
582  class Foo {
583  public:
584    // Construct a Foo by reading data from the disk in the whizbang format, ...
585    Foo(std::string filename);
586
587    // Construct a Foo by looking up the Nth element of some global data ...
588    Foo(int N);
589
590    // ...
591  };
592
593  // The Foo constructor call is reading a file, don't use braces to call it.
594  std::fill(foo.begin(), foo.end(), Foo("name"));
595
596  // The pair is being constructed like an aggregate, use braces.
597  bar_map.insert({my_key, my_value});
598
599If you use a braced initializer list when initializing a variable, use an equals before the open curly brace:
600
601.. code-block:: c++
602
603  int data[] = {0, 1, 2, 3};
604
605Use ``auto`` Type Deduction to Make Code More Readable
606^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
607
608Some are advocating a policy of "almost always ``auto``" in C++11, however LLVM
609uses a more moderate stance. Use ``auto`` if and only if it makes the code more
610readable or easier to maintain. Don't "almost always" use ``auto``, but do use
611``auto`` with initializers like ``cast<Foo>(...)`` or other places where the
612type is already obvious from the context. Another time when ``auto`` works well
613for these purposes is when the type would have been abstracted away anyways,
614often behind a container's typedef such as ``std::vector<T>::iterator``.
615
616Similarly, C++14 adds generic lambda expressions where parameter types can be
617``auto``. Use these where you would have used a template.
618
619Beware unnecessary copies with ``auto``
620^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
621
622The convenience of ``auto`` makes it easy to forget that its default behavior
623is a copy.  Particularly in range-based ``for`` loops, careless copies are
624expensive.
625
626Use ``auto &`` for values and ``auto *`` for pointers unless you need to make a
627copy.
628
629.. code-block:: c++
630
631  // Typically there's no reason to copy.
632  for (const auto &Val : Container) { observe(Val); }
633  for (auto &Val : Container) { Val.change(); }
634
635  // Remove the reference if you really want a new copy.
636  for (auto Val : Container) { Val.change(); saveSomewhere(Val); }
637
638  // Copy pointers, but make it clear that they're pointers.
639  for (const auto *Ptr : Container) { observe(*Ptr); }
640  for (auto *Ptr : Container) { Ptr->change(); }
641
642Beware of non-determinism due to ordering of pointers
643^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
644
645In general, there is no relative ordering among pointers. As a result,
646when unordered containers like sets and maps are used with pointer keys
647the iteration order is undefined. Hence, iterating such containers may
648result in non-deterministic code generation. While the generated code
649might work correctly, non-determinism can make it harder to reproduce bugs and
650debug the compiler.
651
652In case an ordered result is expected, remember to
653sort an unordered container before iteration. Or use ordered containers
654like ``vector``/``MapVector``/``SetVector`` if you want to iterate pointer
655keys.
656
657Beware of non-deterministic sorting order of equal elements
658^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
659
660``std::sort`` uses a non-stable sorting algorithm in which the order of equal
661elements is not guaranteed to be preserved. Thus using ``std::sort`` for a
662container having equal elements may result in non-deterministic behavior.
663To uncover such instances of non-determinism, LLVM has introduced a new
664llvm::sort wrapper function. For an EXPENSIVE_CHECKS build this will randomly
665shuffle the container before sorting. Default to using ``llvm::sort`` instead
666of ``std::sort``.
667
668Style Issues
669============
670
671The High-Level Issues
672---------------------
673
674Self-contained Headers
675^^^^^^^^^^^^^^^^^^^^^^
676
677Header files should be self-contained (compile on their own) and end in ``.h``.
678Non-header files that are meant for inclusion should end in ``.inc`` and be
679used sparingly.
680
681All header files should be self-contained. Users and refactoring tools should
682not have to adhere to special conditions to include the header. Specifically, a
683header should have header guards and include all other headers it needs.
684
685There are rare cases where a file designed to be included is not
686self-contained. These are typically intended to be included at unusual
687locations, such as the middle of another file. They might not use header
688guards, and might not include their prerequisites. Name such files with the
689.inc extension. Use sparingly, and prefer self-contained headers when possible.
690
691In general, a header should be implemented by one or more ``.cpp`` files.  Each
692of these ``.cpp`` files should include the header that defines their interface
693first.  This ensures that all of the dependences of the header have been
694properly added to the header itself, and are not implicit.  System headers
695should be included after user headers for a translation unit.
696
697Library Layering
698^^^^^^^^^^^^^^^^
699
700A directory of header files (for example ``include/llvm/Foo``) defines a
701library (``Foo``). Dependencies between libraries are defined by the
702``LLVMBuild.txt`` file in their implementation (``lib/Foo``). One library (both
703its headers and implementation) should only use things from the libraries
704listed in its dependencies.
705
706Some of this constraint can be enforced by classic Unix linkers (Mac & Windows
707linkers, as well as lld, do not enforce this constraint). A Unix linker
708searches left to right through the libraries specified on its command line and
709never revisits a library. In this way, no circular dependencies between
710libraries can exist.
711
712This doesn't fully enforce all inter-library dependencies, and importantly
713doesn't enforce header file circular dependencies created by inline functions.
714A good way to answer the "is this layered correctly" would be to consider
715whether a Unix linker would succeed at linking the program if all inline
716functions were defined out-of-line. (& for all valid orderings of dependencies
717- since linking resolution is linear, it's possible that some implicit
718dependencies can sneak through: A depends on B and C, so valid orderings are
719"C B A" or "B C A", in both cases the explicit dependencies come before their
720use. But in the first case, B could still link successfully if it implicitly
721depended on C, or the opposite in the second case)
722
723.. _minimal list of #includes:
724
725``#include`` as Little as Possible
726^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
727
728``#include`` hurts compile time performance.  Don't do it unless you have to,
729especially in header files.
730
731But wait! Sometimes you need to have the definition of a class to use it, or to
732inherit from it.  In these cases go ahead and ``#include`` that header file.  Be
733aware however that there are many cases where you don't need to have the full
734definition of a class.  If you are using a pointer or reference to a class, you
735don't need the header file.  If you are simply returning a class instance from a
736prototyped function or method, you don't need it.  In fact, for most cases, you
737simply don't need the definition of a class. And not ``#include``\ing speeds up
738compilation.
739
740It is easy to try to go too overboard on this recommendation, however.  You
741**must** include all of the header files that you are using --- you can include
742them either directly or indirectly through another header file.  To make sure
743that you don't accidentally forget to include a header file in your module
744header, make sure to include your module header **first** in the implementation
745file (as mentioned above).  This way there won't be any hidden dependencies that
746you'll find out about later.
747
748Keep "Internal" Headers Private
749^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
750
751Many modules have a complex implementation that causes them to use more than one
752implementation (``.cpp``) file.  It is often tempting to put the internal
753communication interface (helper classes, extra functions, etc) in the public
754module header file.  Don't do this!
755
756If you really need to do something like this, put a private header file in the
757same directory as the source files, and include it locally.  This ensures that
758your private interface remains private and undisturbed by outsiders.
759
760.. note::
761
762    It's okay to put extra implementation methods in a public class itself. Just
763    make them private (or protected) and all is well.
764
765.. _early exits:
766
767Use Early Exits and ``continue`` to Simplify Code
768^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
769
770When reading code, keep in mind how much state and how many previous decisions
771have to be remembered by the reader to understand a block of code.  Aim to
772reduce indentation where possible when it doesn't make it more difficult to
773understand the code.  One great way to do this is by making use of early exits
774and the ``continue`` keyword in long loops. Consider this code that does not
775use an early exit:
776
777.. code-block:: c++
778
779  Value *doSomething(Instruction *I) {
780    if (!I->isTerminator() &&
781        I->hasOneUse() && doOtherThing(I)) {
782      ... some long code ....
783    }
784
785    return 0;
786  }
787
788This code has several problems if the body of the ``'if'`` is large.  When
789you're looking at the top of the function, it isn't immediately clear that this
790*only* does interesting things with non-terminator instructions, and only
791applies to things with the other predicates.  Second, it is relatively difficult
792to describe (in comments) why these predicates are important because the ``if``
793statement makes it difficult to lay out the comments.  Third, when you're deep
794within the body of the code, it is indented an extra level.  Finally, when
795reading the top of the function, it isn't clear what the result is if the
796predicate isn't true; you have to read to the end of the function to know that
797it returns null.
798
799It is much preferred to format the code like this:
800
801.. code-block:: c++
802
803  Value *doSomething(Instruction *I) {
804    // Terminators never need 'something' done to them because ...
805    if (I->isTerminator())
806      return 0;
807
808    // We conservatively avoid transforming instructions with multiple uses
809    // because goats like cheese.
810    if (!I->hasOneUse())
811      return 0;
812
813    // This is really just here for example.
814    if (!doOtherThing(I))
815      return 0;
816
817    ... some long code ....
818  }
819
820This fixes these problems.  A similar problem frequently happens in ``for``
821loops.  A silly example is something like this:
822
823.. code-block:: c++
824
825  for (Instruction &I : BB) {
826    if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
827      Value *LHS = BO->getOperand(0);
828      Value *RHS = BO->getOperand(1);
829      if (LHS != RHS) {
830        ...
831      }
832    }
833  }
834
835When you have very, very small loops, this sort of structure is fine. But if it
836exceeds more than 10-15 lines, it becomes difficult for people to read and
837understand at a glance. The problem with this sort of code is that it gets very
838nested very quickly. Meaning that the reader of the code has to keep a lot of
839context in their brain to remember what is going immediately on in the loop,
840because they don't know if/when the ``if`` conditions will have ``else``\s etc.
841It is strongly preferred to structure the loop like this:
842
843.. code-block:: c++
844
845  for (Instruction &I : BB) {
846    auto *BO = dyn_cast<BinaryOperator>(&I);
847    if (!BO) continue;
848
849    Value *LHS = BO->getOperand(0);
850    Value *RHS = BO->getOperand(1);
851    if (LHS == RHS) continue;
852
853    ...
854  }
855
856This has all the benefits of using early exits for functions: it reduces nesting
857of the loop, it makes it easier to describe why the conditions are true, and it
858makes it obvious to the reader that there is no ``else`` coming up that they
859have to push context into their brain for.  If a loop is large, this can be a
860big understandability win.
861
862Don't use ``else`` after a ``return``
863^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
864
865For similar reasons as above (reduction of indentation and easier reading), please
866do not use ``'else'`` or ``'else if'`` after something that interrupts control
867flow --- like ``return``, ``break``, ``continue``, ``goto``, etc. For example:
868
869.. code-block:: c++
870
871  case 'J': {
872    if (Signed) {
873      Type = Context.getsigjmp_bufType();
874      if (Type.isNull()) {
875        Error = ASTContext::GE_Missing_sigjmp_buf;
876        return QualType();
877      } else {
878        break; // Unnecessary.
879      }
880    } else {
881      Type = Context.getjmp_bufType();
882      if (Type.isNull()) {
883        Error = ASTContext::GE_Missing_jmp_buf;
884        return QualType();
885      } else {
886        break; // Unnecessary.
887      }
888    }
889  }
890
891It is better to write it like this:
892
893.. code-block:: c++
894
895  case 'J':
896    if (Signed) {
897      Type = Context.getsigjmp_bufType();
898      if (Type.isNull()) {
899        Error = ASTContext::GE_Missing_sigjmp_buf;
900        return QualType();
901      }
902    } else {
903      Type = Context.getjmp_bufType();
904      if (Type.isNull()) {
905        Error = ASTContext::GE_Missing_jmp_buf;
906        return QualType();
907      }
908    }
909    break;
910
911Or better yet (in this case) as:
912
913.. code-block:: c++
914
915  case 'J':
916    if (Signed)
917      Type = Context.getsigjmp_bufType();
918    else
919      Type = Context.getjmp_bufType();
920
921    if (Type.isNull()) {
922      Error = Signed ? ASTContext::GE_Missing_sigjmp_buf :
923                       ASTContext::GE_Missing_jmp_buf;
924      return QualType();
925    }
926    break;
927
928The idea is to reduce indentation and the amount of code you have to keep track
929of when reading the code.
930
931Turn Predicate Loops into Predicate Functions
932^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
933
934It is very common to write small loops that just compute a boolean value.  There
935are a number of ways that people commonly write these, but an example of this
936sort of thing is:
937
938.. code-block:: c++
939
940  bool FoundFoo = false;
941  for (unsigned I = 0, E = BarList.size(); I != E; ++I)
942    if (BarList[I]->isFoo()) {
943      FoundFoo = true;
944      break;
945    }
946
947  if (FoundFoo) {
948    ...
949  }
950
951Instead of this sort of loop, we prefer to use a predicate function (which may
952be `static`_) that uses `early exits`_:
953
954.. code-block:: c++
955
956  /// \returns true if the specified list has an element that is a foo.
957  static bool containsFoo(const std::vector<Bar*> &List) {
958    for (unsigned I = 0, E = List.size(); I != E; ++I)
959      if (List[I]->isFoo())
960        return true;
961    return false;
962  }
963  ...
964
965  if (containsFoo(BarList)) {
966    ...
967  }
968
969There are many reasons for doing this: it reduces indentation and factors out
970code which can often be shared by other code that checks for the same predicate.
971More importantly, it *forces you to pick a name* for the function, and forces
972you to write a comment for it.  In this silly example, this doesn't add much
973value.  However, if the condition is complex, this can make it a lot easier for
974the reader to understand the code that queries for this predicate.  Instead of
975being faced with the in-line details of how we check to see if the BarList
976contains a foo, we can trust the function name and continue reading with better
977locality.
978
979The Low-Level Issues
980--------------------
981
982Name Types, Functions, Variables, and Enumerators Properly
983^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
984
985Poorly-chosen names can mislead the reader and cause bugs. We cannot stress
986enough how important it is to use *descriptive* names.  Pick names that match
987the semantics and role of the underlying entities, within reason.  Avoid
988abbreviations unless they are well known.  After picking a good name, make sure
989to use consistent capitalization for the name, as inconsistency requires clients
990to either memorize the APIs or to look it up to find the exact spelling.
991
992In general, names should be in camel case (e.g. ``TextFileReader`` and
993``isLValue()``).  Different kinds of declarations have different rules:
994
995* **Type names** (including classes, structs, enums, typedefs, etc) should be
996  nouns and start with an upper-case letter (e.g. ``TextFileReader``).
997
998* **Variable names** should be nouns (as they represent state).  The name should
999  be camel case, and start with an upper case letter (e.g. ``Leader`` or
1000  ``Boats``).
1001
1002* **Function names** should be verb phrases (as they represent actions), and
1003  command-like function should be imperative.  The name should be camel case,
1004  and start with a lower case letter (e.g. ``openFile()`` or ``isFoo()``).
1005
1006* **Enum declarations** (e.g. ``enum Foo {...}``) are types, so they should
1007  follow the naming conventions for types.  A common use for enums is as a
1008  discriminator for a union, or an indicator of a subclass.  When an enum is
1009  used for something like this, it should have a ``Kind`` suffix
1010  (e.g. ``ValueKind``).
1011
1012* **Enumerators** (e.g. ``enum { Foo, Bar }``) and **public member variables**
1013  should start with an upper-case letter, just like types.  Unless the
1014  enumerators are defined in their own small namespace or inside a class,
1015  enumerators should have a prefix corresponding to the enum declaration name.
1016  For example, ``enum ValueKind { ... };`` may contain enumerators like
1017  ``VK_Argument``, ``VK_BasicBlock``, etc.  Enumerators that are just
1018  convenience constants are exempt from the requirement for a prefix.  For
1019  instance:
1020
1021  .. code-block:: c++
1022
1023      enum {
1024        MaxSize = 42,
1025        Density = 12
1026      };
1027
1028As an exception, classes that mimic STL classes can have member names in STL's
1029style of lower-case words separated by underscores (e.g. ``begin()``,
1030``push_back()``, and ``empty()``). Classes that provide multiple
1031iterators should add a singular prefix to ``begin()`` and ``end()``
1032(e.g. ``global_begin()`` and ``use_begin()``).
1033
1034Here are some examples:
1035
1036.. code-block:: c++
1037
1038  class VehicleMaker {
1039    ...
1040    Factory<Tire> F;            // Avoid: a non-descriptive abbreviation.
1041    Factory<Tire> Factory;      // Better: more descriptive.
1042    Factory<Tire> TireFactory;  // Even better: if VehicleMaker has more than one
1043                                // kind of factories.
1044  };
1045
1046  Vehicle makeVehicle(VehicleType Type) {
1047    VehicleMaker M;                         // Might be OK if scope is small.
1048    Tire Tmp1 = M.makeTire();               // Avoid: 'Tmp1' provides no information.
1049    Light Headlight = M.makeLight("head");  // Good: descriptive.
1050    ...
1051  }
1052
1053Assert Liberally
1054^^^^^^^^^^^^^^^^
1055
1056Use the "``assert``" macro to its fullest.  Check all of your preconditions and
1057assumptions, you never know when a bug (not necessarily even yours) might be
1058caught early by an assertion, which reduces debugging time dramatically.  The
1059"``<cassert>``" header file is probably already included by the header files you
1060are using, so it doesn't cost anything to use it.
1061
1062To further assist with debugging, make sure to put some kind of error message in
1063the assertion statement, which is printed if the assertion is tripped. This
1064helps the poor debugger make sense of why an assertion is being made and
1065enforced, and hopefully what to do about it.  Here is one complete example:
1066
1067.. code-block:: c++
1068
1069  inline Value *getOperand(unsigned I) {
1070    assert(I < Operands.size() && "getOperand() out of range!");
1071    return Operands[I];
1072  }
1073
1074Here are more examples:
1075
1076.. code-block:: c++
1077
1078  assert(Ty->isPointerType() && "Can't allocate a non-pointer type!");
1079
1080  assert((Opcode == Shl || Opcode == Shr) && "ShiftInst Opcode invalid!");
1081
1082  assert(idx < getNumSuccessors() && "Successor # out of range!");
1083
1084  assert(V1.getType() == V2.getType() && "Constant types must be identical!");
1085
1086  assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
1087
1088You get the idea.
1089
1090In the past, asserts were used to indicate a piece of code that should not be
1091reached.  These were typically of the form:
1092
1093.. code-block:: c++
1094
1095  assert(0 && "Invalid radix for integer literal");
1096
1097This has a few issues, the main one being that some compilers might not
1098understand the assertion, or warn about a missing return in builds where
1099assertions are compiled out.
1100
1101Today, we have something much better: ``llvm_unreachable``:
1102
1103.. code-block:: c++
1104
1105  llvm_unreachable("Invalid radix for integer literal");
1106
1107When assertions are enabled, this will print the message if it's ever reached
1108and then exit the program. When assertions are disabled (i.e. in release
1109builds), ``llvm_unreachable`` becomes a hint to compilers to skip generating
1110code for this branch. If the compiler does not support this, it will fall back
1111to the "abort" implementation.
1112
1113Neither assertions or ``llvm_unreachable`` will abort the program on a release
1114build. If the error condition can be triggered by user input then the
1115recoverable error mechanism described in :doc:`ProgrammersManual` should be
1116used instead. In cases where this is not practical, ``report_fatal_error`` may
1117be used.
1118
1119Another issue is that values used only by assertions will produce an "unused
1120value" warning when assertions are disabled.  For example, this code will warn:
1121
1122.. code-block:: c++
1123
1124  unsigned Size = V.size();
1125  assert(Size > 42 && "Vector smaller than it should be");
1126
1127  bool NewToSet = Myset.insert(Value);
1128  assert(NewToSet && "The value shouldn't be in the set yet");
1129
1130These are two interesting different cases. In the first case, the call to
1131``V.size()`` is only useful for the assert, and we don't want it executed when
1132assertions are disabled.  Code like this should move the call into the assert
1133itself.  In the second case, the side effects of the call must happen whether
1134the assert is enabled or not.  In this case, the value should be cast to void to
1135disable the warning.  To be specific, it is preferred to write the code like
1136this:
1137
1138.. code-block:: c++
1139
1140  assert(V.size() > 42 && "Vector smaller than it should be");
1141
1142  bool NewToSet = Myset.insert(Value); (void)NewToSet;
1143  assert(NewToSet && "The value shouldn't be in the set yet");
1144
1145Do Not Use ``using namespace std``
1146^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1147
1148In LLVM, we prefer to explicitly prefix all identifiers from the standard
1149namespace with an "``std::``" prefix, rather than rely on "``using namespace
1150std;``".
1151
1152In header files, adding a ``'using namespace XXX'`` directive pollutes the
1153namespace of any source file that ``#include``\s the header, creating
1154maintenance issues.
1155
1156In implementation files (e.g. ``.cpp`` files), the rule is more of a stylistic
1157rule, but is still important.  Basically, using explicit namespace prefixes
1158makes the code **clearer**, because it is immediately obvious what facilities
1159are being used and where they are coming from. And **more portable**, because
1160namespace clashes cannot occur between LLVM code and other namespaces.  The
1161portability rule is important because different standard library implementations
1162expose different symbols (potentially ones they shouldn't), and future revisions
1163to the C++ standard will add more symbols to the ``std`` namespace.  As such, we
1164never use ``'using namespace std;'`` in LLVM.
1165
1166The exception to the general rule (i.e. it's not an exception for the ``std``
1167namespace) is for implementation files.  For example, all of the code in the
1168LLVM project implements code that lives in the 'llvm' namespace.  As such, it is
1169ok, and actually clearer, for the ``.cpp`` files to have a ``'using namespace
1170llvm;'`` directive at the top, after the ``#include``\s.  This reduces
1171indentation in the body of the file for source editors that indent based on
1172braces, and keeps the conceptual context cleaner.  The general form of this rule
1173is that any ``.cpp`` file that implements code in any namespace may use that
1174namespace (and its parents'), but should not use any others.
1175
1176Provide a Virtual Method Anchor for Classes in Headers
1177^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1178
1179If a class is defined in a header file and has a vtable (either it has virtual
1180methods or it derives from classes with virtual methods), it must always have at
1181least one out-of-line virtual method in the class.  Without this, the compiler
1182will copy the vtable and RTTI into every ``.o`` file that ``#include``\s the
1183header, bloating ``.o`` file sizes and increasing link times.
1184
1185Don't use default labels in fully covered switches over enumerations
1186^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1187
1188``-Wswitch`` warns if a switch, without a default label, over an enumeration
1189does not cover every enumeration value. If you write a default label on a fully
1190covered switch over an enumeration then the ``-Wswitch`` warning won't fire
1191when new elements are added to that enumeration. To help avoid adding these
1192kinds of defaults, Clang has the warning ``-Wcovered-switch-default`` which is
1193off by default but turned on when building LLVM with a version of Clang that
1194supports the warning.
1195
1196A knock-on effect of this stylistic requirement is that when building LLVM with
1197GCC you may get warnings related to "control may reach end of non-void function"
1198if you return from each case of a covered switch-over-enum because GCC assumes
1199that the enum expression may take any representable value, not just those of
1200individual enumerators. To suppress this warning, use ``llvm_unreachable`` after
1201the switch.
1202
1203Use range-based ``for`` loops wherever possible
1204^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1205
1206The introduction of range-based ``for`` loops in C++11 means that explicit
1207manipulation of iterators is rarely necessary. We use range-based ``for``
1208loops wherever possible for all newly added code. For example:
1209
1210.. code-block:: c++
1211
1212  BasicBlock *BB = ...
1213  for (Instruction &I : *BB)
1214    ... use I ...
1215
1216Don't evaluate ``end()`` every time through a loop
1217^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1218
1219In cases where range-based ``for`` loops can't be used and it is necessary
1220to write an explicit iterator-based loop, pay close attention to whether
1221``end()`` is re-evaluated on each loop iteration. One common mistake is to
1222write a loop in this style:
1223
1224.. code-block:: c++
1225
1226  BasicBlock *BB = ...
1227  for (auto I = BB->begin(); I != BB->end(); ++I)
1228    ... use I ...
1229
1230The problem with this construct is that it evaluates "``BB->end()``" every time
1231through the loop.  Instead of writing the loop like this, we strongly prefer
1232loops to be written so that they evaluate it once before the loop starts.  A
1233convenient way to do this is like so:
1234
1235.. code-block:: c++
1236
1237  BasicBlock *BB = ...
1238  for (auto I = BB->begin(), E = BB->end(); I != E; ++I)
1239    ... use I ...
1240
1241The observant may quickly point out that these two loops may have different
1242semantics: if the container (a basic block in this case) is being mutated, then
1243"``BB->end()``" may change its value every time through the loop and the second
1244loop may not in fact be correct.  If you actually do depend on this behavior,
1245please write the loop in the first form and add a comment indicating that you
1246did it intentionally.
1247
1248Why do we prefer the second form (when correct)?  Writing the loop in the first
1249form has two problems. First it may be less efficient than evaluating it at the
1250start of the loop.  In this case, the cost is probably minor --- a few extra
1251loads every time through the loop.  However, if the base expression is more
1252complex, then the cost can rise quickly.  I've seen loops where the end
1253expression was actually something like: "``SomeMap[X]->end()``" and map lookups
1254really aren't cheap.  By writing it in the second form consistently, you
1255eliminate the issue entirely and don't even have to think about it.
1256
1257The second (even bigger) issue is that writing the loop in the first form hints
1258to the reader that the loop is mutating the container (a fact that a comment
1259would handily confirm!).  If you write the loop in the second form, it is
1260immediately obvious without even looking at the body of the loop that the
1261container isn't being modified, which makes it easier to read the code and
1262understand what it does.
1263
1264While the second form of the loop is a few extra keystrokes, we do strongly
1265prefer it.
1266
1267``#include <iostream>`` is Forbidden
1268^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1269
1270The use of ``#include <iostream>`` in library files is hereby **forbidden**,
1271because many common implementations transparently inject a `static constructor`_
1272into every translation unit that includes it.
1273
1274Note that using the other stream headers (``<sstream>`` for example) is not
1275problematic in this regard --- just ``<iostream>``. However, ``raw_ostream``
1276provides various APIs that are better performing for almost every use than
1277``std::ostream`` style APIs.
1278
1279.. note::
1280
1281  New code should always use `raw_ostream`_ for writing, or the
1282  ``llvm::MemoryBuffer`` API for reading files.
1283
1284.. _raw_ostream:
1285
1286Use ``raw_ostream``
1287^^^^^^^^^^^^^^^^^^^
1288
1289LLVM includes a lightweight, simple, and efficient stream implementation in
1290``llvm/Support/raw_ostream.h``, which provides all of the common features of
1291``std::ostream``.  All new code should use ``raw_ostream`` instead of
1292``ostream``.
1293
1294Unlike ``std::ostream``, ``raw_ostream`` is not a template and can be forward
1295declared as ``class raw_ostream``.  Public headers should generally not include
1296the ``raw_ostream`` header, but use forward declarations and constant references
1297to ``raw_ostream`` instances.
1298
1299Avoid ``std::endl``
1300^^^^^^^^^^^^^^^^^^^
1301
1302The ``std::endl`` modifier, when used with ``iostreams`` outputs a newline to
1303the output stream specified.  In addition to doing this, however, it also
1304flushes the output stream.  In other words, these are equivalent:
1305
1306.. code-block:: c++
1307
1308  std::cout << std::endl;
1309  std::cout << '\n' << std::flush;
1310
1311Most of the time, you probably have no reason to flush the output stream, so
1312it's better to use a literal ``'\n'``.
1313
1314Don't use ``inline`` when defining a function in a class definition
1315^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1316
1317A member function defined in a class definition is implicitly inline, so don't
1318put the ``inline`` keyword in this case.
1319
1320Don't:
1321
1322.. code-block:: c++
1323
1324  class Foo {
1325  public:
1326    inline void bar() {
1327      // ...
1328    }
1329  };
1330
1331Do:
1332
1333.. code-block:: c++
1334
1335  class Foo {
1336  public:
1337    void bar() {
1338      // ...
1339    }
1340  };
1341
1342Microscopic Details
1343-------------------
1344
1345This section describes preferred low-level formatting guidelines along with
1346reasoning on why we prefer them.
1347
1348Spaces Before Parentheses
1349^^^^^^^^^^^^^^^^^^^^^^^^^
1350
1351Put a space before an open parenthesis only in control flow statements, but not
1352in normal function call expressions and function-like macros.  For example:
1353
1354.. code-block:: c++
1355
1356  if (X) ...
1357  for (I = 0; I != 100; ++I) ...
1358  while (LLVMRocks) ...
1359
1360  somefunc(42);
1361  assert(3 != 4 && "laws of math are failing me");
1362
1363  A = foo(42, 92) + bar(X);
1364
1365The reason for doing this is not completely arbitrary.  This style makes control
1366flow operators stand out more, and makes expressions flow better.
1367
1368Prefer Preincrement
1369^^^^^^^^^^^^^^^^^^^
1370
1371Hard fast rule: Preincrement (``++X``) may be no slower than postincrement
1372(``X++``) and could very well be a lot faster than it.  Use preincrementation
1373whenever possible.
1374
1375The semantics of postincrement include making a copy of the value being
1376incremented, returning it, and then preincrementing the "work value".  For
1377primitive types, this isn't a big deal. But for iterators, it can be a huge
1378issue (for example, some iterators contains stack and set objects in them...
1379copying an iterator could invoke the copy ctor's of these as well).  In general,
1380get in the habit of always using preincrement, and you won't have a problem.
1381
1382
1383Namespace Indentation
1384^^^^^^^^^^^^^^^^^^^^^
1385
1386In general, we strive to reduce indentation wherever possible.  This is useful
1387because we want code to `fit into 80 columns`_ without excessive wrapping, but
1388also because it makes it easier to understand the code. To facilitate this and
1389avoid some insanely deep nesting on occasion, don't indent namespaces. If it
1390helps readability, feel free to add a comment indicating what namespace is
1391being closed by a ``}``.  For example:
1392
1393.. code-block:: c++
1394
1395  namespace llvm {
1396  namespace knowledge {
1397
1398  /// This class represents things that Smith can have an intimate
1399  /// understanding of and contains the data associated with it.
1400  class Grokable {
1401  ...
1402  public:
1403    explicit Grokable() { ... }
1404    virtual ~Grokable() = 0;
1405
1406    ...
1407
1408  };
1409
1410  } // end namespace knowledge
1411  } // end namespace llvm
1412
1413
1414Feel free to skip the closing comment when the namespace being closed is
1415obvious for any reason. For example, the outer-most namespace in a header file
1416is rarely a source of confusion. But namespaces both anonymous and named in
1417source files that are being closed half way through the file probably could use
1418clarification.
1419
1420.. _static:
1421
1422Anonymous Namespaces
1423^^^^^^^^^^^^^^^^^^^^
1424
1425After talking about namespaces in general, you may be wondering about anonymous
1426namespaces in particular.  Anonymous namespaces are a great language feature
1427that tells the C++ compiler that the contents of the namespace are only visible
1428within the current translation unit, allowing more aggressive optimization and
1429eliminating the possibility of symbol name collisions.  Anonymous namespaces are
1430to C++ as "static" is to C functions and global variables.  While "``static``"
1431is available in C++, anonymous namespaces are more general: they can make entire
1432classes private to a file.
1433
1434The problem with anonymous namespaces is that they naturally want to encourage
1435indentation of their body, and they reduce locality of reference: if you see a
1436random function definition in a C++ file, it is easy to see if it is marked
1437static, but seeing if it is in an anonymous namespace requires scanning a big
1438chunk of the file.
1439
1440Because of this, we have a simple guideline: make anonymous namespaces as small
1441as possible, and only use them for class declarations.  For example:
1442
1443.. code-block:: c++
1444
1445  namespace {
1446  class StringSort {
1447  ...
1448  public:
1449    StringSort(...)
1450    bool operator<(const char *RHS) const;
1451  };
1452  } // end anonymous namespace
1453
1454  static void runHelper() {
1455    ...
1456  }
1457
1458  bool StringSort::operator<(const char *RHS) const {
1459    ...
1460  }
1461
1462Avoid putting declarations other than classes into anonymous namespaces:
1463
1464.. code-block:: c++
1465
1466  namespace {
1467
1468  // ... many declarations ...
1469
1470  void runHelper() {
1471    ...
1472  }
1473
1474  // ... many declarations ...
1475
1476  } // end anonymous namespace
1477
1478When you are looking at "``runHelper``" in the middle of a large C++ file,
1479you have no immediate way to tell if this function is local to the file.  In
1480contrast, when the function is marked static, you don't need to cross-reference
1481faraway places in the file to tell that the function is local.
1482
1483See Also
1484========
1485
1486A lot of these comments and recommendations have been culled from other sources.
1487Two particularly important books for our work are:
1488
1489#. `Effective C++
1490   <https://www.amazon.com/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0321334876>`_
1491   by Scott Meyers.  Also interesting and useful are "More Effective C++" and
1492   "Effective STL" by the same author.
1493
1494#. `Large-Scale C++ Software Design
1495   <https://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620>`_
1496   by John Lakos
1497
1498If you get some free time, and you haven't read them: do so, you might learn
1499something.
1500