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