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
765Use Namespace Qualifiers to Implement Previously Declared Functions
766^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
767
768When providing an out of line implementation of a function in a source file, do
769not open namespace blocks in the source file. Instead, use namespace qualifiers
770to help ensure that your definition matches an existing declaration. Do this:
771
772.. code-block:: c++
773
774  // Foo.h
775  namespace llvm {
776  int foo(const char *s);
777  }
778
779  // Foo.cpp
780  #include "Foo.h"
781  using namespace llvm;
782  int llvm::foo(const char *s) {
783    // ...
784  }
785
786Doing this helps to avoid bugs where the definition does not match the
787declaration from the header. For example, the following C++ code defines a new
788overload of ``llvm::foo`` instead of providing a definition for the existing
789function declared in the header:
790
791.. code-block:: c++
792
793  // Foo.cpp
794  #include "Foo.h"
795  namespace llvm {
796  int foo(char *s) { // Mismatch between "const char *" and "char *"
797  }
798  } // end namespace llvm
799
800This error will not be caught until the build is nearly complete, when the
801linker fails to find a definition for any uses of the original function.  If the
802function were instead defined with a namespace qualifier, the error would have
803been caught immediately when the definition was compiled.
804
805Class method implementations must already name the class and new overloads
806cannot be introduced out of line, so this recommendation does not apply to them.
807
808.. _early exits:
809
810Use Early Exits and ``continue`` to Simplify Code
811^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
812
813When reading code, keep in mind how much state and how many previous decisions
814have to be remembered by the reader to understand a block of code.  Aim to
815reduce indentation where possible when it doesn't make it more difficult to
816understand the code.  One great way to do this is by making use of early exits
817and the ``continue`` keyword in long loops. Consider this code that does not
818use an early exit:
819
820.. code-block:: c++
821
822  Value *doSomething(Instruction *I) {
823    if (!I->isTerminator() &&
824        I->hasOneUse() && doOtherThing(I)) {
825      ... some long code ....
826    }
827
828    return 0;
829  }
830
831This code has several problems if the body of the ``'if'`` is large.  When
832you're looking at the top of the function, it isn't immediately clear that this
833*only* does interesting things with non-terminator instructions, and only
834applies to things with the other predicates.  Second, it is relatively difficult
835to describe (in comments) why these predicates are important because the ``if``
836statement makes it difficult to lay out the comments.  Third, when you're deep
837within the body of the code, it is indented an extra level.  Finally, when
838reading the top of the function, it isn't clear what the result is if the
839predicate isn't true; you have to read to the end of the function to know that
840it returns null.
841
842It is much preferred to format the code like this:
843
844.. code-block:: c++
845
846  Value *doSomething(Instruction *I) {
847    // Terminators never need 'something' done to them because ...
848    if (I->isTerminator())
849      return 0;
850
851    // We conservatively avoid transforming instructions with multiple uses
852    // because goats like cheese.
853    if (!I->hasOneUse())
854      return 0;
855
856    // This is really just here for example.
857    if (!doOtherThing(I))
858      return 0;
859
860    ... some long code ....
861  }
862
863This fixes these problems.  A similar problem frequently happens in ``for``
864loops.  A silly example is something like this:
865
866.. code-block:: c++
867
868  for (Instruction &I : BB) {
869    if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
870      Value *LHS = BO->getOperand(0);
871      Value *RHS = BO->getOperand(1);
872      if (LHS != RHS) {
873        ...
874      }
875    }
876  }
877
878When you have very, very small loops, this sort of structure is fine. But if it
879exceeds more than 10-15 lines, it becomes difficult for people to read and
880understand at a glance. The problem with this sort of code is that it gets very
881nested very quickly. Meaning that the reader of the code has to keep a lot of
882context in their brain to remember what is going immediately on in the loop,
883because they don't know if/when the ``if`` conditions will have ``else``\s etc.
884It is strongly preferred to structure the loop like this:
885
886.. code-block:: c++
887
888  for (Instruction &I : BB) {
889    auto *BO = dyn_cast<BinaryOperator>(&I);
890    if (!BO) continue;
891
892    Value *LHS = BO->getOperand(0);
893    Value *RHS = BO->getOperand(1);
894    if (LHS == RHS) continue;
895
896    ...
897  }
898
899This has all the benefits of using early exits for functions: it reduces nesting
900of the loop, it makes it easier to describe why the conditions are true, and it
901makes it obvious to the reader that there is no ``else`` coming up that they
902have to push context into their brain for.  If a loop is large, this can be a
903big understandability win.
904
905Don't use ``else`` after a ``return``
906^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
907
908For similar reasons as above (reduction of indentation and easier reading), please
909do not use ``'else'`` or ``'else if'`` after something that interrupts control
910flow --- like ``return``, ``break``, ``continue``, ``goto``, etc. For example:
911
912.. code-block:: c++
913
914  case 'J': {
915    if (Signed) {
916      Type = Context.getsigjmp_bufType();
917      if (Type.isNull()) {
918        Error = ASTContext::GE_Missing_sigjmp_buf;
919        return QualType();
920      } else {
921        break; // Unnecessary.
922      }
923    } else {
924      Type = Context.getjmp_bufType();
925      if (Type.isNull()) {
926        Error = ASTContext::GE_Missing_jmp_buf;
927        return QualType();
928      } else {
929        break; // Unnecessary.
930      }
931    }
932  }
933
934It is better to write it like this:
935
936.. code-block:: c++
937
938  case 'J':
939    if (Signed) {
940      Type = Context.getsigjmp_bufType();
941      if (Type.isNull()) {
942        Error = ASTContext::GE_Missing_sigjmp_buf;
943        return QualType();
944      }
945    } else {
946      Type = Context.getjmp_bufType();
947      if (Type.isNull()) {
948        Error = ASTContext::GE_Missing_jmp_buf;
949        return QualType();
950      }
951    }
952    break;
953
954Or better yet (in this case) as:
955
956.. code-block:: c++
957
958  case 'J':
959    if (Signed)
960      Type = Context.getsigjmp_bufType();
961    else
962      Type = Context.getjmp_bufType();
963
964    if (Type.isNull()) {
965      Error = Signed ? ASTContext::GE_Missing_sigjmp_buf :
966                       ASTContext::GE_Missing_jmp_buf;
967      return QualType();
968    }
969    break;
970
971The idea is to reduce indentation and the amount of code you have to keep track
972of when reading the code.
973
974Turn Predicate Loops into Predicate Functions
975^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
976
977It is very common to write small loops that just compute a boolean value.  There
978are a number of ways that people commonly write these, but an example of this
979sort of thing is:
980
981.. code-block:: c++
982
983  bool FoundFoo = false;
984  for (unsigned I = 0, E = BarList.size(); I != E; ++I)
985    if (BarList[I]->isFoo()) {
986      FoundFoo = true;
987      break;
988    }
989
990  if (FoundFoo) {
991    ...
992  }
993
994Instead of this sort of loop, we prefer to use a predicate function (which may
995be `static`_) that uses `early exits`_:
996
997.. code-block:: c++
998
999  /// \returns true if the specified list has an element that is a foo.
1000  static bool containsFoo(const std::vector<Bar*> &List) {
1001    for (unsigned I = 0, E = List.size(); I != E; ++I)
1002      if (List[I]->isFoo())
1003        return true;
1004    return false;
1005  }
1006  ...
1007
1008  if (containsFoo(BarList)) {
1009    ...
1010  }
1011
1012There are many reasons for doing this: it reduces indentation and factors out
1013code which can often be shared by other code that checks for the same predicate.
1014More importantly, it *forces you to pick a name* for the function, and forces
1015you to write a comment for it.  In this silly example, this doesn't add much
1016value.  However, if the condition is complex, this can make it a lot easier for
1017the reader to understand the code that queries for this predicate.  Instead of
1018being faced with the in-line details of how we check to see if the BarList
1019contains a foo, we can trust the function name and continue reading with better
1020locality.
1021
1022The Low-Level Issues
1023--------------------
1024
1025Name Types, Functions, Variables, and Enumerators Properly
1026^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1027
1028Poorly-chosen names can mislead the reader and cause bugs. We cannot stress
1029enough how important it is to use *descriptive* names.  Pick names that match
1030the semantics and role of the underlying entities, within reason.  Avoid
1031abbreviations unless they are well known.  After picking a good name, make sure
1032to use consistent capitalization for the name, as inconsistency requires clients
1033to either memorize the APIs or to look it up to find the exact spelling.
1034
1035In general, names should be in camel case (e.g. ``TextFileReader`` and
1036``isLValue()``).  Different kinds of declarations have different rules:
1037
1038* **Type names** (including classes, structs, enums, typedefs, etc) should be
1039  nouns and start with an upper-case letter (e.g. ``TextFileReader``).
1040
1041* **Variable names** should be nouns (as they represent state).  The name should
1042  be camel case, and start with an upper case letter (e.g. ``Leader`` or
1043  ``Boats``).
1044
1045* **Function names** should be verb phrases (as they represent actions), and
1046  command-like function should be imperative.  The name should be camel case,
1047  and start with a lower case letter (e.g. ``openFile()`` or ``isFoo()``).
1048
1049* **Enum declarations** (e.g. ``enum Foo {...}``) are types, so they should
1050  follow the naming conventions for types.  A common use for enums is as a
1051  discriminator for a union, or an indicator of a subclass.  When an enum is
1052  used for something like this, it should have a ``Kind`` suffix
1053  (e.g. ``ValueKind``).
1054
1055* **Enumerators** (e.g. ``enum { Foo, Bar }``) and **public member variables**
1056  should start with an upper-case letter, just like types.  Unless the
1057  enumerators are defined in their own small namespace or inside a class,
1058  enumerators should have a prefix corresponding to the enum declaration name.
1059  For example, ``enum ValueKind { ... };`` may contain enumerators like
1060  ``VK_Argument``, ``VK_BasicBlock``, etc.  Enumerators that are just
1061  convenience constants are exempt from the requirement for a prefix.  For
1062  instance:
1063
1064  .. code-block:: c++
1065
1066      enum {
1067        MaxSize = 42,
1068        Density = 12
1069      };
1070
1071As an exception, classes that mimic STL classes can have member names in STL's
1072style of lower-case words separated by underscores (e.g. ``begin()``,
1073``push_back()``, and ``empty()``). Classes that provide multiple
1074iterators should add a singular prefix to ``begin()`` and ``end()``
1075(e.g. ``global_begin()`` and ``use_begin()``).
1076
1077Here are some examples:
1078
1079.. code-block:: c++
1080
1081  class VehicleMaker {
1082    ...
1083    Factory<Tire> F;            // Avoid: a non-descriptive abbreviation.
1084    Factory<Tire> Factory;      // Better: more descriptive.
1085    Factory<Tire> TireFactory;  // Even better: if VehicleMaker has more than one
1086                                // kind of factories.
1087  };
1088
1089  Vehicle makeVehicle(VehicleType Type) {
1090    VehicleMaker M;                         // Might be OK if scope is small.
1091    Tire Tmp1 = M.makeTire();               // Avoid: 'Tmp1' provides no information.
1092    Light Headlight = M.makeLight("head");  // Good: descriptive.
1093    ...
1094  }
1095
1096Assert Liberally
1097^^^^^^^^^^^^^^^^
1098
1099Use the "``assert``" macro to its fullest.  Check all of your preconditions and
1100assumptions, you never know when a bug (not necessarily even yours) might be
1101caught early by an assertion, which reduces debugging time dramatically.  The
1102"``<cassert>``" header file is probably already included by the header files you
1103are using, so it doesn't cost anything to use it.
1104
1105To further assist with debugging, make sure to put some kind of error message in
1106the assertion statement, which is printed if the assertion is tripped. This
1107helps the poor debugger make sense of why an assertion is being made and
1108enforced, and hopefully what to do about it.  Here is one complete example:
1109
1110.. code-block:: c++
1111
1112  inline Value *getOperand(unsigned I) {
1113    assert(I < Operands.size() && "getOperand() out of range!");
1114    return Operands[I];
1115  }
1116
1117Here are more examples:
1118
1119.. code-block:: c++
1120
1121  assert(Ty->isPointerType() && "Can't allocate a non-pointer type!");
1122
1123  assert((Opcode == Shl || Opcode == Shr) && "ShiftInst Opcode invalid!");
1124
1125  assert(idx < getNumSuccessors() && "Successor # out of range!");
1126
1127  assert(V1.getType() == V2.getType() && "Constant types must be identical!");
1128
1129  assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
1130
1131You get the idea.
1132
1133In the past, asserts were used to indicate a piece of code that should not be
1134reached.  These were typically of the form:
1135
1136.. code-block:: c++
1137
1138  assert(0 && "Invalid radix for integer literal");
1139
1140This has a few issues, the main one being that some compilers might not
1141understand the assertion, or warn about a missing return in builds where
1142assertions are compiled out.
1143
1144Today, we have something much better: ``llvm_unreachable``:
1145
1146.. code-block:: c++
1147
1148  llvm_unreachable("Invalid radix for integer literal");
1149
1150When assertions are enabled, this will print the message if it's ever reached
1151and then exit the program. When assertions are disabled (i.e. in release
1152builds), ``llvm_unreachable`` becomes a hint to compilers to skip generating
1153code for this branch. If the compiler does not support this, it will fall back
1154to the "abort" implementation.
1155
1156Use ``llvm_unreachable`` to mark a specific point in code that should never be
1157reached. This is especially desirable for addressing warnings about unreachable
1158branches, etc., but can be used whenever reaching a particular code path is
1159unconditionally a bug (not originating from user input; see below) of some kind.
1160Use of ``assert`` should always include a testable predicate (as opposed to
1161``assert(false)``).
1162
1163Neither assertions or ``llvm_unreachable`` will abort the program on a release
1164build. If the error condition can be triggered by user input then the
1165recoverable error mechanism described in :doc:`ProgrammersManual` should be
1166used instead. In cases where this is not practical, ``report_fatal_error`` may
1167be used.
1168
1169Another issue is that values used only by assertions will produce an "unused
1170value" warning when assertions are disabled.  For example, this code will warn:
1171
1172.. code-block:: c++
1173
1174  unsigned Size = V.size();
1175  assert(Size > 42 && "Vector smaller than it should be");
1176
1177  bool NewToSet = Myset.insert(Value);
1178  assert(NewToSet && "The value shouldn't be in the set yet");
1179
1180These are two interesting different cases. In the first case, the call to
1181``V.size()`` is only useful for the assert, and we don't want it executed when
1182assertions are disabled.  Code like this should move the call into the assert
1183itself.  In the second case, the side effects of the call must happen whether
1184the assert is enabled or not.  In this case, the value should be cast to void to
1185disable the warning.  To be specific, it is preferred to write the code like
1186this:
1187
1188.. code-block:: c++
1189
1190  assert(V.size() > 42 && "Vector smaller than it should be");
1191
1192  bool NewToSet = Myset.insert(Value); (void)NewToSet;
1193  assert(NewToSet && "The value shouldn't be in the set yet");
1194
1195Do Not Use ``using namespace std``
1196^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1197
1198In LLVM, we prefer to explicitly prefix all identifiers from the standard
1199namespace with an "``std::``" prefix, rather than rely on "``using namespace
1200std;``".
1201
1202In header files, adding a ``'using namespace XXX'`` directive pollutes the
1203namespace of any source file that ``#include``\s the header, creating
1204maintenance issues.
1205
1206In implementation files (e.g. ``.cpp`` files), the rule is more of a stylistic
1207rule, but is still important.  Basically, using explicit namespace prefixes
1208makes the code **clearer**, because it is immediately obvious what facilities
1209are being used and where they are coming from. And **more portable**, because
1210namespace clashes cannot occur between LLVM code and other namespaces.  The
1211portability rule is important because different standard library implementations
1212expose different symbols (potentially ones they shouldn't), and future revisions
1213to the C++ standard will add more symbols to the ``std`` namespace.  As such, we
1214never use ``'using namespace std;'`` in LLVM.
1215
1216The exception to the general rule (i.e. it's not an exception for the ``std``
1217namespace) is for implementation files.  For example, all of the code in the
1218LLVM project implements code that lives in the 'llvm' namespace.  As such, it is
1219ok, and actually clearer, for the ``.cpp`` files to have a ``'using namespace
1220llvm;'`` directive at the top, after the ``#include``\s.  This reduces
1221indentation in the body of the file for source editors that indent based on
1222braces, and keeps the conceptual context cleaner.  The general form of this rule
1223is that any ``.cpp`` file that implements code in any namespace may use that
1224namespace (and its parents'), but should not use any others.
1225
1226Provide a Virtual Method Anchor for Classes in Headers
1227^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1228
1229If a class is defined in a header file and has a vtable (either it has virtual
1230methods or it derives from classes with virtual methods), it must always have at
1231least one out-of-line virtual method in the class.  Without this, the compiler
1232will copy the vtable and RTTI into every ``.o`` file that ``#include``\s the
1233header, bloating ``.o`` file sizes and increasing link times.
1234
1235Don't use default labels in fully covered switches over enumerations
1236^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1237
1238``-Wswitch`` warns if a switch, without a default label, over an enumeration
1239does not cover every enumeration value. If you write a default label on a fully
1240covered switch over an enumeration then the ``-Wswitch`` warning won't fire
1241when new elements are added to that enumeration. To help avoid adding these
1242kinds of defaults, Clang has the warning ``-Wcovered-switch-default`` which is
1243off by default but turned on when building LLVM with a version of Clang that
1244supports the warning.
1245
1246A knock-on effect of this stylistic requirement is that when building LLVM with
1247GCC you may get warnings related to "control may reach end of non-void function"
1248if you return from each case of a covered switch-over-enum because GCC assumes
1249that the enum expression may take any representable value, not just those of
1250individual enumerators. To suppress this warning, use ``llvm_unreachable`` after
1251the switch.
1252
1253Use range-based ``for`` loops wherever possible
1254^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1255
1256The introduction of range-based ``for`` loops in C++11 means that explicit
1257manipulation of iterators is rarely necessary. We use range-based ``for``
1258loops wherever possible for all newly added code. For example:
1259
1260.. code-block:: c++
1261
1262  BasicBlock *BB = ...
1263  for (Instruction &I : *BB)
1264    ... use I ...
1265
1266Don't evaluate ``end()`` every time through a loop
1267^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1268
1269In cases where range-based ``for`` loops can't be used and it is necessary
1270to write an explicit iterator-based loop, pay close attention to whether
1271``end()`` is re-evaluated on each loop iteration. One common mistake is to
1272write a loop in this style:
1273
1274.. code-block:: c++
1275
1276  BasicBlock *BB = ...
1277  for (auto I = BB->begin(); I != BB->end(); ++I)
1278    ... use I ...
1279
1280The problem with this construct is that it evaluates "``BB->end()``" every time
1281through the loop.  Instead of writing the loop like this, we strongly prefer
1282loops to be written so that they evaluate it once before the loop starts.  A
1283convenient way to do this is like so:
1284
1285.. code-block:: c++
1286
1287  BasicBlock *BB = ...
1288  for (auto I = BB->begin(), E = BB->end(); I != E; ++I)
1289    ... use I ...
1290
1291The observant may quickly point out that these two loops may have different
1292semantics: if the container (a basic block in this case) is being mutated, then
1293"``BB->end()``" may change its value every time through the loop and the second
1294loop may not in fact be correct.  If you actually do depend on this behavior,
1295please write the loop in the first form and add a comment indicating that you
1296did it intentionally.
1297
1298Why do we prefer the second form (when correct)?  Writing the loop in the first
1299form has two problems. First it may be less efficient than evaluating it at the
1300start of the loop.  In this case, the cost is probably minor --- a few extra
1301loads every time through the loop.  However, if the base expression is more
1302complex, then the cost can rise quickly.  I've seen loops where the end
1303expression was actually something like: "``SomeMap[X]->end()``" and map lookups
1304really aren't cheap.  By writing it in the second form consistently, you
1305eliminate the issue entirely and don't even have to think about it.
1306
1307The second (even bigger) issue is that writing the loop in the first form hints
1308to the reader that the loop is mutating the container (a fact that a comment
1309would handily confirm!).  If you write the loop in the second form, it is
1310immediately obvious without even looking at the body of the loop that the
1311container isn't being modified, which makes it easier to read the code and
1312understand what it does.
1313
1314While the second form of the loop is a few extra keystrokes, we do strongly
1315prefer it.
1316
1317``#include <iostream>`` is Forbidden
1318^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1319
1320The use of ``#include <iostream>`` in library files is hereby **forbidden**,
1321because many common implementations transparently inject a `static constructor`_
1322into every translation unit that includes it.
1323
1324Note that using the other stream headers (``<sstream>`` for example) is not
1325problematic in this regard --- just ``<iostream>``. However, ``raw_ostream``
1326provides various APIs that are better performing for almost every use than
1327``std::ostream`` style APIs.
1328
1329.. note::
1330
1331  New code should always use `raw_ostream`_ for writing, or the
1332  ``llvm::MemoryBuffer`` API for reading files.
1333
1334.. _raw_ostream:
1335
1336Use ``raw_ostream``
1337^^^^^^^^^^^^^^^^^^^
1338
1339LLVM includes a lightweight, simple, and efficient stream implementation in
1340``llvm/Support/raw_ostream.h``, which provides all of the common features of
1341``std::ostream``.  All new code should use ``raw_ostream`` instead of
1342``ostream``.
1343
1344Unlike ``std::ostream``, ``raw_ostream`` is not a template and can be forward
1345declared as ``class raw_ostream``.  Public headers should generally not include
1346the ``raw_ostream`` header, but use forward declarations and constant references
1347to ``raw_ostream`` instances.
1348
1349Avoid ``std::endl``
1350^^^^^^^^^^^^^^^^^^^
1351
1352The ``std::endl`` modifier, when used with ``iostreams`` outputs a newline to
1353the output stream specified.  In addition to doing this, however, it also
1354flushes the output stream.  In other words, these are equivalent:
1355
1356.. code-block:: c++
1357
1358  std::cout << std::endl;
1359  std::cout << '\n' << std::flush;
1360
1361Most of the time, you probably have no reason to flush the output stream, so
1362it's better to use a literal ``'\n'``.
1363
1364Don't use ``inline`` when defining a function in a class definition
1365^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1366
1367A member function defined in a class definition is implicitly inline, so don't
1368put the ``inline`` keyword in this case.
1369
1370Don't:
1371
1372.. code-block:: c++
1373
1374  class Foo {
1375  public:
1376    inline void bar() {
1377      // ...
1378    }
1379  };
1380
1381Do:
1382
1383.. code-block:: c++
1384
1385  class Foo {
1386  public:
1387    void bar() {
1388      // ...
1389    }
1390  };
1391
1392Microscopic Details
1393-------------------
1394
1395This section describes preferred low-level formatting guidelines along with
1396reasoning on why we prefer them.
1397
1398Spaces Before Parentheses
1399^^^^^^^^^^^^^^^^^^^^^^^^^
1400
1401Put a space before an open parenthesis only in control flow statements, but not
1402in normal function call expressions and function-like macros.  For example:
1403
1404.. code-block:: c++
1405
1406  if (X) ...
1407  for (I = 0; I != 100; ++I) ...
1408  while (LLVMRocks) ...
1409
1410  somefunc(42);
1411  assert(3 != 4 && "laws of math are failing me");
1412
1413  A = foo(42, 92) + bar(X);
1414
1415The reason for doing this is not completely arbitrary.  This style makes control
1416flow operators stand out more, and makes expressions flow better.
1417
1418Prefer Preincrement
1419^^^^^^^^^^^^^^^^^^^
1420
1421Hard fast rule: Preincrement (``++X``) may be no slower than postincrement
1422(``X++``) and could very well be a lot faster than it.  Use preincrementation
1423whenever possible.
1424
1425The semantics of postincrement include making a copy of the value being
1426incremented, returning it, and then preincrementing the "work value".  For
1427primitive types, this isn't a big deal. But for iterators, it can be a huge
1428issue (for example, some iterators contains stack and set objects in them...
1429copying an iterator could invoke the copy ctor's of these as well).  In general,
1430get in the habit of always using preincrement, and you won't have a problem.
1431
1432
1433Namespace Indentation
1434^^^^^^^^^^^^^^^^^^^^^
1435
1436In general, we strive to reduce indentation wherever possible.  This is useful
1437because we want code to `fit into 80 columns`_ without excessive wrapping, but
1438also because it makes it easier to understand the code. To facilitate this and
1439avoid some insanely deep nesting on occasion, don't indent namespaces. If it
1440helps readability, feel free to add a comment indicating what namespace is
1441being closed by a ``}``.  For example:
1442
1443.. code-block:: c++
1444
1445  namespace llvm {
1446  namespace knowledge {
1447
1448  /// This class represents things that Smith can have an intimate
1449  /// understanding of and contains the data associated with it.
1450  class Grokable {
1451  ...
1452  public:
1453    explicit Grokable() { ... }
1454    virtual ~Grokable() = 0;
1455
1456    ...
1457
1458  };
1459
1460  } // end namespace knowledge
1461  } // end namespace llvm
1462
1463
1464Feel free to skip the closing comment when the namespace being closed is
1465obvious for any reason. For example, the outer-most namespace in a header file
1466is rarely a source of confusion. But namespaces both anonymous and named in
1467source files that are being closed half way through the file probably could use
1468clarification.
1469
1470.. _static:
1471
1472Anonymous Namespaces
1473^^^^^^^^^^^^^^^^^^^^
1474
1475After talking about namespaces in general, you may be wondering about anonymous
1476namespaces in particular.  Anonymous namespaces are a great language feature
1477that tells the C++ compiler that the contents of the namespace are only visible
1478within the current translation unit, allowing more aggressive optimization and
1479eliminating the possibility of symbol name collisions.  Anonymous namespaces are
1480to C++ as "static" is to C functions and global variables.  While "``static``"
1481is available in C++, anonymous namespaces are more general: they can make entire
1482classes private to a file.
1483
1484The problem with anonymous namespaces is that they naturally want to encourage
1485indentation of their body, and they reduce locality of reference: if you see a
1486random function definition in a C++ file, it is easy to see if it is marked
1487static, but seeing if it is in an anonymous namespace requires scanning a big
1488chunk of the file.
1489
1490Because of this, we have a simple guideline: make anonymous namespaces as small
1491as possible, and only use them for class declarations.  For example:
1492
1493.. code-block:: c++
1494
1495  namespace {
1496  class StringSort {
1497  ...
1498  public:
1499    StringSort(...)
1500    bool operator<(const char *RHS) const;
1501  };
1502  } // end anonymous namespace
1503
1504  static void runHelper() {
1505    ...
1506  }
1507
1508  bool StringSort::operator<(const char *RHS) const {
1509    ...
1510  }
1511
1512Avoid putting declarations other than classes into anonymous namespaces:
1513
1514.. code-block:: c++
1515
1516  namespace {
1517
1518  // ... many declarations ...
1519
1520  void runHelper() {
1521    ...
1522  }
1523
1524  // ... many declarations ...
1525
1526  } // end anonymous namespace
1527
1528When you are looking at "``runHelper``" in the middle of a large C++ file,
1529you have no immediate way to tell if this function is local to the file.  In
1530contrast, when the function is marked static, you don't need to cross-reference
1531faraway places in the file to tell that the function is local.
1532
1533See Also
1534========
1535
1536A lot of these comments and recommendations have been culled from other sources.
1537Two particularly important books for our work are:
1538
1539#. `Effective C++
1540   <https://www.amazon.com/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0321334876>`_
1541   by Scott Meyers.  Also interesting and useful are "More Effective C++" and
1542   "Effective STL" by the same author.
1543
1544#. `Large-Scale C++ Software Design
1545   <https://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620>`_
1546   by John Lakos
1547
1548If you get some free time, and you haven't read them: do so, you might learn
1549something.
1550