blob: c1a94e83c7feea3c5cedf1de8b9be8de8884831d [file] [log] [blame]
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001=====================
2LLVM Coding Standards
3=====================
4
5.. contents::
6 :local:
7
8Introduction
9============
10
11This document attempts to describe a few coding standards that are being used in
12the LLVM source tree. Although no coding standards should be regarded as
13absolute requirements to be followed in all instances, coding standards are
14particularly important for large-scale code bases that follow a library-based
15design (like LLVM).
16
Chandler Carruthc8ce0652014-02-28 12:24:18 +000017While 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:
Bill Wendling1c5e94a2012-06-20 02:57:56 +000020
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 really good reasons to deviate
28from the coding standards. In the case of ``libc++``, this is because the
29naming and other conventions are dictated by the C++ standard. If you think
30there is a specific good reason to deviate from the standards here, please bring
Tanya Lattner0d28f802015-08-05 03:51:17 +000031it up on the LLVM-dev mailing list.
Bill Wendling1c5e94a2012-06-20 02:57:56 +000032
33There are some conventions that are not uniformly followed in the code base
34(e.g. the naming convention). This is because they are relatively new, and a
35lot of code was written before they were put in place. Our long term goal is
36for the entire codebase to follow the convention, but we explicitly *do not*
37want patches that do large-scale reformating of existing code. On the other
38hand, it is reasonable to rename the methods of a class if you're about to
39change it in some other way. Just do the reformating as a separate commit from
40the functionality change.
41
Vedant Kumarcb236392015-08-19 18:19:12 +000042The ultimate goal of these guidelines is to increase the readability and
Bill Wendling1c5e94a2012-06-20 02:57:56 +000043maintainability of our common source base. If you have suggestions for topics to
44be included, please mail them to `Chris <mailto:sabre@nondot.org>`_.
45
Chandler Carruthe8c97892014-02-28 13:35:54 +000046Languages, Libraries, and Standards
47===================================
48
49Most source code in LLVM and other LLVM projects using these coding standards
50is C++ code. There are some places where C code is used either due to
51environment restrictions, historical restrictions, or due to third-party source
52code imported into the tree. Generally, our preference is for standards
53conforming, modern, and portable C++ code as the implementation language of
54choice.
55
56C++ Standard Versions
57---------------------
58
Chandler Carruth25353ac2014-03-01 02:48:03 +000059LLVM, Clang, and LLD are currently written using C++11 conforming code,
60although we restrict ourselves to features which are available in the major
61toolchains supported as host compilers. The LLDB project is even more
62aggressive in the set of host compilers supported and thus uses still more
63features. Regardless of the supported features, code is expected to (when
64reasonable) be standard, portable, and modern C++11 code. We avoid unnecessary
65vendor-specific extensions, etc.
Chandler Carruthe8c97892014-02-28 13:35:54 +000066
67C++ Standard Library
68--------------------
69
70Use the C++ standard library facilities whenever they are available for
71a particular task. LLVM and related projects emphasize and rely on the standard
72library facilities for as much as possible. Common support libraries providing
73functionality missing from the standard library for which there are standard
74interfaces or active work on adding standard interfaces will often be
75implemented in the LLVM namespace following the expected standard interface.
76
77There are some exceptions such as the standard I/O streams library which are
78avoided. Also, there is much more detailed information on these subjects in the
Sean Silva1703e702014-04-08 21:06:22 +000079:doc:`ProgrammersManual`.
Chandler Carruthe8c97892014-02-28 13:35:54 +000080
81Supported C++11 Language and Library Features
Sean Silva216f1ee2014-03-02 00:21:42 +000082---------------------------------------------
Chandler Carruthe8c97892014-02-28 13:35:54 +000083
Chandler Carruthe8c97892014-02-28 13:35:54 +000084While LLVM, Clang, and LLD use C++11, not all features are available in all of
85the toolchains which we support. The set of features supported for use in LLVM
Renato Golinecbcd7c2016-10-17 12:29:00 +000086is the intersection of those supported in the minimum requirements described
87in the :doc:`GettingStarted` page, section `Software`.
Chandler Carruthe8c97892014-02-28 13:35:54 +000088The ultimate definition of this set is what build bots with those respective
Chandler Carruth25353ac2014-03-01 02:48:03 +000089toolchains accept. Don't argue with the build bots. However, we have some
90guidance below to help you know what to expect.
Chandler Carruthe8c97892014-02-28 13:35:54 +000091
92Each toolchain provides a good reference for what it accepts:
Richard Smithf30ed8f2014-02-28 21:11:28 +000093
Chandler Carruthe8c97892014-02-28 13:35:54 +000094* Clang: http://clang.llvm.org/cxx_status.html
95* GCC: http://gcc.gnu.org/projects/cxx0x.html
96* MSVC: http://msdn.microsoft.com/en-us/library/hh567368.aspx
97
98In most cases, the MSVC list will be the dominating factor. Here is a summary
99of the features that are expected to work. Features not on this list are
100unlikely to be supported by our host compilers.
101
102* Rvalue references: N2118_
Richard Smitha98d4002014-02-28 21:14:25 +0000103
Chandler Carruthe8c97892014-02-28 13:35:54 +0000104 * But *not* Rvalue references for ``*this`` or member qualifiers (N2439_)
Richard Smitha98d4002014-02-28 21:14:25 +0000105
Chandler Carruthe8c97892014-02-28 13:35:54 +0000106* Static assert: N1720_
107* ``auto`` type deduction: N1984_, N1737_
108* Trailing return types: N2541_
109* Lambdas: N2927_
Reid Kleckner38dcdb72014-03-03 21:12:13 +0000110
Reid Kleckner6a8fada2014-07-02 00:42:07 +0000111 * But *not* lambdas with default arguments.
Reid Kleckner38dcdb72014-03-03 21:12:13 +0000112
Chandler Carruthe8c97892014-02-28 13:35:54 +0000113* ``decltype``: N2343_
114* Nested closing right angle brackets: N1757_
115* Extern templates: N1987_
116* ``nullptr``: N2431_
117* Strongly-typed and forward declarable enums: N2347_, N2764_
118* Local and unnamed types as template arguments: N2657_
119* Range-based for-loop: N2930_
Duncan P. N. Exon Smith8443d582014-04-17 18:02:34 +0000120
121 * But ``{}`` are required around inner ``do {} while()`` loops. As a result,
122 ``{}`` are required around function-like macros inside range-based for
123 loops.
124
Chandler Carruthe8c97892014-02-28 13:35:54 +0000125* ``override`` and ``final``: N2928_, N3206_, N3272_
126* Atomic operations and the C++11 memory model: N2429_
Benjamin Kramerbec02cc2015-02-15 19:34:28 +0000127* Variadic templates: N2242_
Benjamin Kramer499473c2015-02-16 10:28:41 +0000128* Explicit conversion operators: N2437_
129* Defaulted and deleted functions: N2346_
130
131 * But not defaulted move constructors or move assignment operators, MSVC 2013
132 cannot synthesize them.
Aaron Ballman6ab16142015-03-04 23:17:31 +0000133* Initializer lists: N2627_
Benjamin Kramer6409a3c2015-03-06 13:46:50 +0000134* Delegating constructors: N1986_
Reid Kleckner582786b2015-04-30 18:17:12 +0000135* Default member initializers (non-static data member initializers): N2756_
136
137 * Only use these for scalar members that would otherwise be left
138 uninitialized. Non-scalar members generally have appropriate default
139 constructors, and MSVC 2013 has problems when braced initializer lists are
140 involved.
Chandler Carruthe8c97892014-02-28 13:35:54 +0000141
142.. _N2118: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2118.html
Ben Langmuir3b0a8662014-02-28 19:37:20 +0000143.. _N2439: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2439.htm
144.. _N1720: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1720.html
Chandler Carruthe8c97892014-02-28 13:35:54 +0000145.. _N1984: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1984.pdf
Ben Langmuir3b0a8662014-02-28 19:37:20 +0000146.. _N1737: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1737.pdf
147.. _N2541: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2541.htm
148.. _N2927: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2927.pdf
149.. _N2343: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2343.pdf
150.. _N1757: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1757.html
Chandler Carruthe8c97892014-02-28 13:35:54 +0000151.. _N1987: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1987.htm
Ben Langmuir3b0a8662014-02-28 19:37:20 +0000152.. _N2431: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2431.pdf
153.. _N2347: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2347.pdf
154.. _N2764: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2764.pdf
155.. _N2657: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2657.htm
156.. _N2930: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2930.html
157.. _N2928: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2928.htm
158.. _N3206: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3206.htm
159.. _N3272: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3272.htm
160.. _N2429: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2429.htm
Benjamin Kramerbec02cc2015-02-15 19:34:28 +0000161.. _N2242: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2242.pdf
Benjamin Kramer499473c2015-02-16 10:28:41 +0000162.. _N2437: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2437.pdf
163.. _N2346: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2346.htm
Aaron Ballman6ab16142015-03-04 23:17:31 +0000164.. _N2627: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2672.htm
Benjamin Kramer6409a3c2015-03-06 13:46:50 +0000165.. _N1986: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1986.pdf
Reid Kleckner582786b2015-04-30 18:17:12 +0000166.. _N2756: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2756.htm
Chandler Carruthe8c97892014-02-28 13:35:54 +0000167
168The supported features in the C++11 standard libraries are less well tracked,
169but also much greater. Most of the standard libraries implement most of C++11's
170library. The most likely lowest common denominator is Linux support. For
171libc++, the support is just poorly tested and undocumented but expected to be
172largely complete. YMMV. For libstdc++, the support is documented in detail in
173`the libstdc++ manual`_. There are some very minor missing facilities that are
174unlikely to be common problems, and there are a few larger gaps that are worth
175being aware of:
176
177* Not all of the type traits are implemented
178* No regular expression library.
179* While most of the atomics library is well implemented, the fences are
180 missing. Fortunately, they are rarely needed.
181* The locale support is incomplete.
182
Chandler Carruth25353ac2014-03-01 02:48:03 +0000183Other than these areas you should assume the standard library is available and
184working as expected until some build bot tells you otherwise. If you're in an
185uncertain area of one of the above points, but you cannot test on a Linux
186system, your best approach is to minimize your use of these features, and watch
187the Linux build bots to find out if your usage triggered a bug. For example, if
188you hit a type trait which doesn't work we can then add support to LLVM's
189traits header to emulate it.
Chandler Carruth6e390fa2014-02-28 21:59:51 +0000190
Chandler Carruthe8c97892014-02-28 13:35:54 +0000191.. _the libstdc++ manual:
Teresa Johnsonf7f02fa2016-10-18 17:17:37 +0000192 http://gcc.gnu.org/onlinedocs/gcc-4.8.0/libstdc++/manual/manual/status.html#status.iso.2011
Chandler Carruthe8c97892014-02-28 13:35:54 +0000193
Peter Collingbournee0461992014-10-14 00:40:53 +0000194Other Languages
195---------------
196
197Any code written in the Go programming language is not subject to the
198formatting rules below. Instead, we adopt the formatting rules enforced by
199the `gofmt`_ tool.
200
201Go code should strive to be idiomatic. Two good sets of guidelines for what
202this means are `Effective Go`_ and `Go Code Review Comments`_.
203
204.. _gofmt:
205 https://golang.org/cmd/gofmt/
206
207.. _Effective Go:
208 https://golang.org/doc/effective_go.html
209
210.. _Go Code Review Comments:
211 https://code.google.com/p/go-wiki/wiki/CodeReviewComments
212
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000213Mechanical Source Issues
214========================
215
216Source Code Formatting
217----------------------
218
219Commenting
220^^^^^^^^^^
221
222Comments are one critical part of readability and maintainability. Everyone
223knows they should comment their code, and so should you. When writing comments,
224write them as English prose, which means they should use proper capitalization,
225punctuation, etc. Aim to describe what the code is trying to do and why, not
226*how* it does it at a micro level. Here are a few critical things to document:
227
228.. _header file comment:
229
230File Headers
231""""""""""""
232
233Every source file should have a header on it that describes the basic purpose of
234the file. If a file does not have a header, it should not be checked into the
235tree. The standard header looks like this:
236
237.. code-block:: c++
238
239 //===-- llvm/Instruction.h - Instruction class definition -------*- C++ -*-===//
240 //
241 // The LLVM Compiler Infrastructure
242 //
243 // This file is distributed under the University of Illinois Open Source
244 // License. See LICENSE.TXT for details.
245 //
246 //===----------------------------------------------------------------------===//
Michael J. Spencer99a241f2012-10-01 19:59:21 +0000247 ///
248 /// \file
Matthias Braun95a2a7e2015-05-15 03:34:01 +0000249 /// This file contains the declaration of the Instruction class, which is the
250 /// base class for all of the VM instructions.
Michael J. Spencer99a241f2012-10-01 19:59:21 +0000251 ///
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000252 //===----------------------------------------------------------------------===//
253
254A few things to note about this particular format: The "``-*- C++ -*-``" string
255on the first line is there to tell Emacs that the source file is a C++ file, not
256a C file (Emacs assumes ``.h`` files are C files by default).
257
258.. note::
259
260 This tag is not necessary in ``.cpp`` files. The name of the file is also
261 on the first line, along with a very short description of the purpose of the
262 file. This is important when printing out code and flipping though lots of
263 pages.
264
265The next section in the file is a concise note that defines the license that the
266file is released under. This makes it perfectly clear what terms the source
267code can be distributed under and should not be modified in any way.
268
Paul Robinson343e4962015-01-22 00:19:56 +0000269The main body is a ``doxygen`` comment (identified by the ``///`` comment
Matthias Braun95a2a7e2015-05-15 03:34:01 +0000270marker instead of the usual ``//``) describing the purpose of the file. The
Chandler Carruth67473522016-09-01 22:18:25 +0000271first sentence (or a passage beginning with ``\brief``) is used as an abstract.
Matthias Braun95a2a7e2015-05-15 03:34:01 +0000272Any additional information should be separated by a blank line. If an
273algorithm is being implemented or something tricky is going on, a reference
Michael J. Spencer99a241f2012-10-01 19:59:21 +0000274to the paper where it is published should be included, as well as any notes or
275*gotchas* in the code to watch out for.
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000276
277Class overviews
278"""""""""""""""
279
280Classes are one fundamental part of a good object oriented design. As such, a
281class definition should have a comment block that explains what the class is
282used for and how it works. Every non-trivial class is expected to have a
283``doxygen`` comment block.
284
285Method information
286""""""""""""""""""
287
288Methods defined in a class (as well as any global functions) should also be
289documented properly. A quick note about what it does and a description of the
290borderline behaviour is all that is necessary here (unless something
291particularly tricky or insidious is going on). The hope is that people can
292figure out how to use your interfaces without reading the code itself.
293
294Good things to talk about here are what happens when something unexpected
295happens: does the method return null? Abort? Format your hard disk?
296
297Comment Formatting
298^^^^^^^^^^^^^^^^^^
299
Paul Robinson343e4962015-01-22 00:19:56 +0000300In general, prefer C++ style comments (``//`` for normal comments, ``///`` for
301``doxygen`` documentation comments). They take less space, require
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000302less typing, don't have nesting problems, etc. There are a few cases when it is
303useful to use C style (``/* */``) comments however:
304
305#. When writing C code: Obviously if you are writing C code, use C style
306 comments.
307
308#. When writing a header file that may be ``#include``\d by a C source file.
309
310#. When writing a source file that is used by a tool that only accepts C style
311 comments.
312
Andrey Bokhanko7d7bacb2016-08-17 14:53:18 +0000313Commenting out large blocks of code is discouraged, but if you really have to do
314this (for documentation purposes or as a suggestion for debug printing), use
315``#if 0`` and ``#endif``. These nest properly and are better behaved in general
316than C style comments.
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000317
Dmitri Gribenko9fb49d22012-10-20 13:27:43 +0000318Doxygen Use in Documentation Comments
319^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
320
321Use the ``\file`` command to turn the standard file header into a file-level
322comment.
323
Matthias Braun95a2a7e2015-05-15 03:34:01 +0000324Include descriptive paragraphs for all public interfaces (public classes,
325member and non-member functions). Don't just restate the information that can
Chandler Carruth67473522016-09-01 22:18:25 +0000326be inferred from the API name. The first sentence (or a paragraph beginning
327with ``\brief``) is used as an abstract. Try to use a single sentence as the
328``\brief`` adds visual clutter. Put detailed discussion into separate
Matthias Braun95a2a7e2015-05-15 03:34:01 +0000329paragraphs.
Dmitri Gribenko9fb49d22012-10-20 13:27:43 +0000330
331To refer to parameter names inside a paragraph, use the ``\p name`` command.
332Don't use the ``\arg name`` command since it starts a new paragraph that
333contains documentation for the parameter.
334
335Wrap non-inline code examples in ``\code ... \endcode``.
336
337To document a function parameter, start a new paragraph with the
338``\param name`` command. If the parameter is used as an out or an in/out
339parameter, use the ``\param [out] name`` or ``\param [in,out] name`` command,
340respectively.
341
342To describe function return value, start a new paragraph with the ``\returns``
343command.
344
345A minimal documentation comment:
346
347.. code-block:: c++
348
Matthias Braun95a2a7e2015-05-15 03:34:01 +0000349 /// Sets the xyzzy property to \p Baz.
350 void setXyzzy(bool Baz);
Dmitri Gribenko9fb49d22012-10-20 13:27:43 +0000351
352A documentation comment that uses all Doxygen features in a preferred way:
353
354.. code-block:: c++
355
Chandler Carruth67473522016-09-01 22:18:25 +0000356 /// Does foo and bar.
Dmitri Gribenko9fb49d22012-10-20 13:27:43 +0000357 ///
358 /// Does not do foo the usual way if \p Baz is true.
359 ///
360 /// Typical usage:
361 /// \code
362 /// fooBar(false, "quux", Res);
363 /// \endcode
364 ///
365 /// \param Quux kind of foo to do.
366 /// \param [out] Result filled with bar sequence on foo success.
367 ///
368 /// \returns true on success.
369 bool fooBar(bool Baz, StringRef Quux, std::vector<int> &Result);
370
Chris Lattner4fe27462013-09-01 15:48:08 +0000371Don't duplicate the documentation comment in the header file and in the
372implementation file. Put the documentation comments for public APIs into the
373header file. Documentation comments for private APIs can go to the
374implementation file. In any case, implementation files can include additional
375comments (not necessarily in Doxygen markup) to explain implementation details
376as needed.
377
Dmitri Gribenko9fb49d22012-10-20 13:27:43 +0000378Don't duplicate function or class name at the beginning of the comment.
379For humans it is obvious which function or class is being documented;
380automatic documentation processing tools are smart enough to bind the comment
381to the correct declaration.
382
383Wrong:
384
385.. code-block:: c++
386
387 // In Something.h:
388
389 /// Something - An abstraction for some complicated thing.
390 class Something {
391 public:
392 /// fooBar - Does foo and bar.
393 void fooBar();
394 };
395
396 // In Something.cpp:
397
398 /// fooBar - Does foo and bar.
399 void Something::fooBar() { ... }
400
401Correct:
402
403.. code-block:: c++
404
405 // In Something.h:
406
Matthias Braun95a2a7e2015-05-15 03:34:01 +0000407 /// An abstraction for some complicated thing.
Dmitri Gribenko9fb49d22012-10-20 13:27:43 +0000408 class Something {
409 public:
Matthias Braun95a2a7e2015-05-15 03:34:01 +0000410 /// Does foo and bar.
Dmitri Gribenko9fb49d22012-10-20 13:27:43 +0000411 void fooBar();
412 };
413
414 // In Something.cpp:
415
416 // Builds a B-tree in order to do foo. See paper by...
417 void Something::fooBar() { ... }
418
419It is not required to use additional Doxygen features, but sometimes it might
420be a good idea to do so.
421
422Consider:
423
424* adding comments to any narrow namespace containing a collection of
425 related functions or types;
426
427* using top-level groups to organize a collection of related functions at
428 namespace scope where the grouping is smaller than the namespace;
429
430* using member groups and additional comments attached to member
431 groups to organize within a class.
432
433For example:
434
435.. code-block:: c++
436
437 class Something {
438 /// \name Functions that do Foo.
439 /// @{
440 void fooBar();
441 void fooBaz();
442 /// @}
443 ...
444 };
445
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000446``#include`` Style
447^^^^^^^^^^^^^^^^^^
448
449Immediately after the `header file comment`_ (and include guards if working on a
450header file), the `minimal list of #includes`_ required by the file should be
451listed. We prefer these ``#include``\s to be listed in this order:
452
453.. _Main Module Header:
454.. _Local/Private Headers:
455
456#. Main Module Header
457#. Local/Private Headers
Zachary Turner068d1f82016-08-23 20:07:32 +0000458#. LLVM project/subproject headers (``clang/...``, ``lldb/...``, ``llvm/...``, etc)
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000459#. System ``#include``\s
460
Chandler Carruth494cfc02012-12-02 11:53:27 +0000461and each category should be sorted lexicographically by the full path.
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000462
463The `Main Module Header`_ file applies to ``.cpp`` files which implement an
464interface defined by a ``.h`` file. This ``#include`` should always be included
465**first** regardless of where it lives on the file system. By including a
466header file first in the ``.cpp`` files that implement the interfaces, we ensure
467that the header does not have any hidden dependencies which are not explicitly
468``#include``\d in the header, but should be. It is also a form of documentation
469in the ``.cpp`` file to indicate where the interfaces it implements are defined.
470
Zachary Turner068d1f82016-08-23 20:07:32 +0000471LLVM project and subproject headers should be grouped from most specific to least
472specific, for the same reasons described above. For example, LLDB depends on
473both clang and LLVM, and clang depends on LLVM. So an LLDB source file should
474include ``lldb`` headers first, followed by ``clang`` headers, followed by
475``llvm`` headers, to reduce the possibility (for example) of an LLDB header
476accidentally picking up a missing include due to the previous inclusion of that
477header in the main source file or some earlier header file. clang should
478similarly include its own headers before including llvm headers. This rule
479applies to all LLVM subprojects.
480
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000481.. _fit into 80 columns:
482
483Source Code Width
484^^^^^^^^^^^^^^^^^
485
486Write your code to fit within 80 columns of text. This helps those of us who
487like to print out code and look at your code in an ``xterm`` without resizing
488it.
489
490The longer answer is that there must be some limit to the width of the code in
491order to reasonably allow developers to have multiple files side-by-side in
492windows on a modest display. If you are going to pick a width limit, it is
493somewhat arbitrary but you might as well pick something standard. Going with 90
494columns (for example) instead of 80 columns wouldn't add any significant value
495and would be detrimental to printing out code. Also many other projects have
496standardized on 80 columns, so some people have already configured their editors
497for it (vs something else, like 90 columns).
498
499This is one of many contentious issues in coding standards, but it is not up for
500debate.
501
502Use Spaces Instead of Tabs
503^^^^^^^^^^^^^^^^^^^^^^^^^^
504
505In all cases, prefer spaces to tabs in source files. People have different
506preferred indentation levels, and different styles of indentation that they
507like; this is fine. What isn't fine is that different editors/viewers expand
508tabs out to different tab stops. This can cause your code to look completely
509unreadable, and it is not worth dealing with.
510
511As always, follow the `Golden Rule`_ above: follow the style of
512existing code if you are modifying and extending it. If you like four spaces of
513indentation, **DO NOT** do that in the middle of a chunk of code with two spaces
514of indentation. Also, do not reindent a whole source file: it makes for
515incredible diffs that are absolutely worthless.
516
517Indent Code Consistently
518^^^^^^^^^^^^^^^^^^^^^^^^
519
520Okay, in your first year of programming you were told that indentation is
Chandler Carruthe55d9bf2014-03-02 08:38:35 +0000521important. If you didn't believe and internalize this then, now is the time.
522Just do it. With the introduction of C++11, there are some new formatting
523challenges that merit some suggestions to help have consistent, maintainable,
524and tool-friendly formatting and indentation.
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000525
Chandler Carruthe55d9bf2014-03-02 08:38:35 +0000526Format Lambdas Like Blocks Of Code
527""""""""""""""""""""""""""""""""""
528
529When formatting a multi-line lambda, format it like a block of code, that's
530what it is. If there is only one multi-line lambda in a statement, and there
531are no expressions lexically after it in the statement, drop the indent to the
532standard two space indent for a block of code, as if it were an if-block opened
533by the preceding part of the statement:
534
535.. code-block:: c++
536
537 std::sort(foo.begin(), foo.end(), [&](Foo a, Foo b) -> bool {
538 if (a.blah < b.blah)
539 return true;
540 if (a.baz < b.baz)
541 return true;
542 return a.bam < b.bam;
543 });
544
Chandler Carruthd9ff35f2014-03-02 09:13:39 +0000545To take best advantage of this formatting, if you are designing an API which
546accepts a continuation or single callable argument (be it a functor, or
547a ``std::function``), it should be the last argument if at all possible.
548
Chandler Carruthe55d9bf2014-03-02 08:38:35 +0000549If there are multiple multi-line lambdas in a statement, or there is anything
550interesting after the lambda in the statement, indent the block two spaces from
551the indent of the ``[]``:
552
553.. code-block:: c++
554
555 dyn_switch(V->stripPointerCasts(),
556 [] (PHINode *PN) {
557 // process phis...
558 },
559 [] (SelectInst *SI) {
560 // process selects...
561 },
562 [] (LoadInst *LI) {
563 // process loads...
564 },
565 [] (AllocaInst *AI) {
566 // process allocas...
567 });
568
569Braced Initializer Lists
570""""""""""""""""""""""""
571
572With C++11, there are significantly more uses of braced lists to perform
573initialization. These allow you to easily construct aggregate temporaries in
574expressions among other niceness. They now have a natural way of ending up
575nested within each other and within function calls in order to build up
576aggregates (such as option structs) from local variables. To make matters
577worse, we also have many more uses of braces in an expression context that are
578*not* performing initialization.
579
580The historically common formatting of braced initialization of aggregate
581variables does not mix cleanly with deep nesting, general expression contexts,
582function arguments, and lambdas. We suggest new code use a simple rule for
583formatting braced initialization lists: act as-if the braces were parentheses
584in a function call. The formatting rules exactly match those already well
585understood for formatting nested function calls. Examples:
586
587.. code-block:: c++
588
589 foo({a, b, c}, {1, 2, 3});
590
591 llvm::Constant *Mask[] = {
592 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
593 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
594 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)};
595
596This formatting scheme also makes it particularly easy to get predictable,
597consistent, and automatic formatting with tools like `Clang Format`_.
598
599.. _Clang Format: http://clang.llvm.org/docs/ClangFormat.html
600
601Language and Compiler Issues
602----------------------------
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000603
604Treat Compiler Warnings Like Errors
605^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
606
607If your code has compiler warnings in it, something is wrong --- you aren't
608casting values correctly, you have "questionable" constructs in your code, or
609you are doing something legitimately wrong. Compiler warnings can cover up
610legitimate errors in output and make dealing with a translation unit difficult.
611
612It is not possible to prevent all warnings from all compilers, nor is it
613desirable. Instead, pick a standard compiler (like ``gcc``) that provides a
614good thorough set of warnings, and stick to it. At least in the case of
615``gcc``, it is possible to work around any spurious errors by changing the
616syntax of the code slightly. For example, a warning that annoys me occurs when
617I write code like this:
618
619.. code-block:: c++
620
621 if (V = getValue()) {
622 ...
623 }
624
625``gcc`` will warn me that I probably want to use the ``==`` operator, and that I
626probably mistyped it. In most cases, I haven't, and I really don't want the
627spurious errors. To fix this particular problem, I rewrite the code like
628this:
629
630.. code-block:: c++
631
632 if ((V = getValue())) {
633 ...
634 }
635
636which shuts ``gcc`` up. Any ``gcc`` warning that annoys you can be fixed by
637massaging the code appropriately.
638
639Write Portable Code
640^^^^^^^^^^^^^^^^^^^
641
642In almost all cases, it is possible and within reason to write completely
643portable code. If there are cases where it isn't possible to write portable
644code, isolate it behind a well defined (and well documented) interface.
645
646In practice, this means that you shouldn't assume much about the host compiler
647(and Visual Studio tends to be the lowest common denominator). If advanced
648features are used, they should only be an implementation detail of a library
649which has a simple exposed API, and preferably be buried in ``libSystem``.
650
651Do not use RTTI or Exceptions
652^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
653
654In an effort to reduce code and executable size, LLVM does not use RTTI
655(e.g. ``dynamic_cast<>;``) or exceptions. These two language features violate
656the general C++ principle of *"you only pay for what you use"*, causing
657executable bloat even if exceptions are never used in the code base, or if RTTI
658is never used for a class. Because of this, we turn them off globally in the
659code.
660
661That said, LLVM does make extensive use of a hand-rolled form of RTTI that use
Sean Silva1703e702014-04-08 21:06:22 +0000662templates like :ref:`isa\<>, cast\<>, and dyn_cast\<> <isa>`.
Sean Silva0fc33ec2012-11-17 21:01:44 +0000663This form of RTTI is opt-in and can be
664:doc:`added to any class <HowToSetUpLLVMStyleRTTI>`. It is also
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000665substantially more efficient than ``dynamic_cast<>``.
666
667.. _static constructor:
668
669Do not use Static Constructors
670^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
671
672Static constructors and destructors (e.g. global variables whose types have a
673constructor or destructor) should not be added to the code base, and should be
674removed wherever possible. Besides `well known problems
675<http://yosefk.com/c++fqa/ctors.html#fqa-10.12>`_ where the order of
676initialization is undefined between globals in different source files, the
677entire concept of static constructors is at odds with the common use case of
678LLVM as a library linked into a larger application.
679
680Consider the use of LLVM as a JIT linked into another application (perhaps for
681`OpenGL, custom languages <http://llvm.org/Users.html>`_, `shaders in movies
682<http://llvm.org/devmtg/2010-11/Gritz-OpenShadingLang.pdf>`_, etc). Due to the
683design of static constructors, they must be executed at startup time of the
684entire application, regardless of whether or how LLVM is used in that larger
685application. There are two problems with this:
686
687* The time to run the static constructors impacts startup time of applications
688 --- a critical time for GUI apps, among others.
689
690* The static constructors cause the app to pull many extra pages of memory off
691 the disk: both the code for the constructor in each ``.o`` file and the small
692 amount of data that gets touched. In addition, touched/dirty pages put more
693 pressure on the VM system on low-memory machines.
694
695We would really like for there to be zero cost for linking in an additional LLVM
696target or other library into an application, but static constructors violate
697this goal.
698
699That said, LLVM unfortunately does contain static constructors. It would be a
700`great project <http://llvm.org/PR11944>`_ for someone to purge all static
701constructors from LLVM, and then enable the ``-Wglobal-constructors`` warning
702flag (when building with Clang) to ensure we do not regress in the future.
703
704Use of ``class`` and ``struct`` Keywords
705^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
706
707In C++, the ``class`` and ``struct`` keywords can be used almost
708interchangeably. The only difference is when they are used to declare a class:
709``class`` makes all members private by default while ``struct`` makes all
710members public by default.
711
712Unfortunately, not all compilers follow the rules and some will generate
713different symbols based on whether ``class`` or ``struct`` was used to declare
Duncan P. N. Exon Smith9724e832014-03-03 16:48:44 +0000714the symbol (e.g., MSVC). This can lead to problems at link time.
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000715
Duncan P. N. Exon Smith9724e832014-03-03 16:48:44 +0000716* All declarations and definitions of a given ``class`` or ``struct`` must use
717 the same keyword. For example:
718
719.. code-block:: c++
720
721 class Foo;
722
723 // Breaks mangling in MSVC.
724 struct Foo { int Data; };
725
726* As a rule of thumb, ``struct`` should be kept to structures where *all*
727 members are declared public.
728
729.. code-block:: c++
730
731 // Foo feels like a class... this is strange.
732 struct Foo {
733 private:
734 int Data;
735 public:
736 Foo() : Data(0) { }
737 int getData() const { return Data; }
738 void setData(int D) { Data = D; }
739 };
740
741 // Bar isn't POD, but it does look like a struct.
742 struct Bar {
743 int Data;
Chris Lattner6cd04ac2015-02-25 17:28:41 +0000744 Bar() : Data(0) { }
Duncan P. N. Exon Smith9724e832014-03-03 16:48:44 +0000745 };
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000746
Chandler Carruthe55d9bf2014-03-02 08:38:35 +0000747Do not use Braced Initializer Lists to Call a Constructor
748^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
749
750In C++11 there is a "generalized initialization syntax" which allows calling
751constructors using braced initializer lists. Do not use these to call
752constructors with any interesting logic or if you care that you're calling some
753*particular* constructor. Those should look like function calls using
754parentheses rather than like aggregate initialization. Similarly, if you need
755to explicitly name the type and call its constructor to create a temporary,
756don't use a braced initializer list. Instead, use a braced initializer list
757(without any type for temporaries) when doing aggregate initialization or
758something notionally equivalent. Examples:
759
760.. code-block:: c++
761
762 class Foo {
763 public:
764 // Construct a Foo by reading data from the disk in the whizbang format, ...
765 Foo(std::string filename);
766
767 // Construct a Foo by looking up the Nth element of some global data ...
768 Foo(int N);
769
770 // ...
771 };
772
773 // The Foo constructor call is very deliberate, no braces.
774 std::fill(foo.begin(), foo.end(), Foo("name"));
775
776 // The pair is just being constructed like an aggregate, use braces.
777 bar_map.insert({my_key, my_value});
778
779If you use a braced initializer list when initializing a variable, use an equals before the open curly brace:
780
781.. code-block:: c++
782
783 int data[] = {0, 1, 2, 3};
784
785Use ``auto`` Type Deduction to Make Code More Readable
786^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
787
788Some are advocating a policy of "almost always ``auto``" in C++11, however LLVM
789uses a more moderate stance. Use ``auto`` if and only if it makes the code more
790readable or easier to maintain. Don't "almost always" use ``auto``, but do use
791``auto`` with initializers like ``cast<Foo>(...)`` or other places where the
792type is already obvious from the context. Another time when ``auto`` works well
793for these purposes is when the type would have been abstracted away anyways,
794often behind a container's typedef such as ``std::vector<T>::iterator``.
795
Duncan P. N. Exon Smith99486372014-03-03 16:48:47 +0000796Beware unnecessary copies with ``auto``
797^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
798
799The convenience of ``auto`` makes it easy to forget that its default behavior
800is a copy. Particularly in range-based ``for`` loops, careless copies are
801expensive.
802
Duncan P. N. Exon Smithfdbb44a2014-03-07 18:06:15 +0000803As a rule of thumb, use ``auto &`` unless you need to copy the result, and use
804``auto *`` when copying pointers.
Duncan P. N. Exon Smith99486372014-03-03 16:48:47 +0000805
806.. code-block:: c++
807
Duncan P. N. Exon Smithfdbb44a2014-03-07 18:06:15 +0000808 // Typically there's no reason to copy.
Duncan P. N. Exon Smith99486372014-03-03 16:48:47 +0000809 for (const auto &Val : Container) { observe(Val); }
Duncan P. N. Exon Smith99486372014-03-03 16:48:47 +0000810 for (auto &Val : Container) { Val.change(); }
811
812 // Remove the reference if you really want a new copy.
813 for (auto Val : Container) { Val.change(); saveSomewhere(Val); }
814
Duncan P. N. Exon Smith6b3d6a42014-03-07 17:23:29 +0000815 // Copy pointers, but make it clear that they're pointers.
Duncan P. N. Exon Smithfdbb44a2014-03-07 18:06:15 +0000816 for (const auto *Ptr : Container) { observe(*Ptr); }
817 for (auto *Ptr : Container) { Ptr->change(); }
Duncan P. N. Exon Smith6b3d6a42014-03-07 17:23:29 +0000818
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000819Style Issues
820============
821
822The High-Level Issues
823---------------------
824
825A Public Header File **is** a Module
826^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
827
828C++ doesn't do too well in the modularity department. There is no real
829encapsulation or data hiding (unless you use expensive protocol classes), but it
830is what we have to work with. When you write a public header file (in the LLVM
831source tree, they live in the top level "``include``" directory), you are
832defining a module of functionality.
833
834Ideally, modules should be completely independent of each other, and their
835header files should only ``#include`` the absolute minimum number of headers
836possible. A module is not just a class, a function, or a namespace: it's a
837collection of these that defines an interface. This interface may be several
838functions, classes, or data structures, but the important issue is how they work
839together.
840
841In general, a module should be implemented by one or more ``.cpp`` files. Each
842of these ``.cpp`` files should include the header that defines their interface
843first. This ensures that all of the dependences of the module header have been
844properly added to the module header itself, and are not implicit. System
845headers should be included after user headers for a translation unit.
846
847.. _minimal list of #includes:
848
849``#include`` as Little as Possible
850^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
851
852``#include`` hurts compile time performance. Don't do it unless you have to,
853especially in header files.
854
855But wait! Sometimes you need to have the definition of a class to use it, or to
856inherit from it. In these cases go ahead and ``#include`` that header file. Be
857aware however that there are many cases where you don't need to have the full
858definition of a class. If you are using a pointer or reference to a class, you
859don't need the header file. If you are simply returning a class instance from a
860prototyped function or method, you don't need it. In fact, for most cases, you
861simply don't need the definition of a class. And not ``#include``\ing speeds up
862compilation.
863
864It is easy to try to go too overboard on this recommendation, however. You
865**must** include all of the header files that you are using --- you can include
866them either directly or indirectly through another header file. To make sure
867that you don't accidentally forget to include a header file in your module
868header, make sure to include your module header **first** in the implementation
869file (as mentioned above). This way there won't be any hidden dependencies that
870you'll find out about later.
871
872Keep "Internal" Headers Private
873^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
874
875Many modules have a complex implementation that causes them to use more than one
876implementation (``.cpp``) file. It is often tempting to put the internal
877communication interface (helper classes, extra functions, etc) in the public
878module header file. Don't do this!
879
880If you really need to do something like this, put a private header file in the
881same directory as the source files, and include it locally. This ensures that
882your private interface remains private and undisturbed by outsiders.
883
884.. note::
885
886 It's okay to put extra implementation methods in a public class itself. Just
887 make them private (or protected) and all is well.
888
889.. _early exits:
890
891Use Early Exits and ``continue`` to Simplify Code
892^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
893
894When reading code, keep in mind how much state and how many previous decisions
895have to be remembered by the reader to understand a block of code. Aim to
896reduce indentation where possible when it doesn't make it more difficult to
897understand the code. One great way to do this is by making use of early exits
898and the ``continue`` keyword in long loops. As an example of using an early
899exit from a function, consider this "bad" code:
900
901.. code-block:: c++
902
Andrew Tricke6af4b92012-09-20 17:02:04 +0000903 Value *doSomething(Instruction *I) {
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000904 if (!isa<TerminatorInst>(I) &&
Andrew Tricke6af4b92012-09-20 17:02:04 +0000905 I->hasOneUse() && doOtherThing(I)) {
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000906 ... some long code ....
907 }
908
909 return 0;
910 }
911
912This code has several problems if the body of the ``'if'`` is large. When
913you're looking at the top of the function, it isn't immediately clear that this
914*only* does interesting things with non-terminator instructions, and only
915applies to things with the other predicates. Second, it is relatively difficult
916to describe (in comments) why these predicates are important because the ``if``
917statement makes it difficult to lay out the comments. Third, when you're deep
918within the body of the code, it is indented an extra level. Finally, when
919reading the top of the function, it isn't clear what the result is if the
920predicate isn't true; you have to read to the end of the function to know that
921it returns null.
922
923It is much preferred to format the code like this:
924
925.. code-block:: c++
926
Andrew Tricke6af4b92012-09-20 17:02:04 +0000927 Value *doSomething(Instruction *I) {
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000928 // Terminators never need 'something' done to them because ...
929 if (isa<TerminatorInst>(I))
930 return 0;
931
932 // We conservatively avoid transforming instructions with multiple uses
933 // because goats like cheese.
934 if (!I->hasOneUse())
935 return 0;
936
937 // This is really just here for example.
Andrew Tricke6af4b92012-09-20 17:02:04 +0000938 if (!doOtherThing(I))
Bill Wendling1c5e94a2012-06-20 02:57:56 +0000939 return 0;
940
941 ... some long code ....
942 }
943
944This fixes these problems. A similar problem frequently happens in ``for``
945loops. A silly example is something like this:
946
947.. code-block:: c++
948
949 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
950 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(II)) {
951 Value *LHS = BO->getOperand(0);
952 Value *RHS = BO->getOperand(1);
953 if (LHS != RHS) {
954 ...
955 }
956 }
957 }
958
959When you have very, very small loops, this sort of structure is fine. But if it
960exceeds more than 10-15 lines, it becomes difficult for people to read and
961understand at a glance. The problem with this sort of code is that it gets very
962nested very quickly. Meaning that the reader of the code has to keep a lot of
963context in their brain to remember what is going immediately on in the loop,
964because they don't know if/when the ``if`` conditions will have ``else``\s etc.
965It is strongly preferred to structure the loop like this:
966
967.. code-block:: c++
968
969 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
970 BinaryOperator *BO = dyn_cast<BinaryOperator>(II);
971 if (!BO) continue;
972
973 Value *LHS = BO->getOperand(0);
974 Value *RHS = BO->getOperand(1);
975 if (LHS == RHS) continue;
976
977 ...
978 }
979
980This has all the benefits of using early exits for functions: it reduces nesting
981of the loop, it makes it easier to describe why the conditions are true, and it
982makes it obvious to the reader that there is no ``else`` coming up that they
983have to push context into their brain for. If a loop is large, this can be a
984big understandability win.
985
986Don't use ``else`` after a ``return``
987^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
988
989For similar reasons above (reduction of indentation and easier reading), please
990do not use ``'else'`` or ``'else if'`` after something that interrupts control
991flow --- like ``return``, ``break``, ``continue``, ``goto``, etc. For
992example, this is *bad*:
993
994.. code-block:: c++
995
996 case 'J': {
997 if (Signed) {
998 Type = Context.getsigjmp_bufType();
999 if (Type.isNull()) {
1000 Error = ASTContext::GE_Missing_sigjmp_buf;
1001 return QualType();
1002 } else {
1003 break;
1004 }
1005 } else {
1006 Type = Context.getjmp_bufType();
1007 if (Type.isNull()) {
1008 Error = ASTContext::GE_Missing_jmp_buf;
1009 return QualType();
Meador Inge46137da2012-06-20 23:48:01 +00001010 } else {
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001011 break;
Meador Inge46137da2012-06-20 23:48:01 +00001012 }
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001013 }
1014 }
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001015
1016It is better to write it like this:
1017
1018.. code-block:: c++
1019
1020 case 'J':
1021 if (Signed) {
1022 Type = Context.getsigjmp_bufType();
1023 if (Type.isNull()) {
1024 Error = ASTContext::GE_Missing_sigjmp_buf;
1025 return QualType();
1026 }
1027 } else {
1028 Type = Context.getjmp_bufType();
1029 if (Type.isNull()) {
1030 Error = ASTContext::GE_Missing_jmp_buf;
1031 return QualType();
1032 }
1033 }
1034 break;
1035
1036Or better yet (in this case) as:
1037
1038.. code-block:: c++
1039
1040 case 'J':
1041 if (Signed)
1042 Type = Context.getsigjmp_bufType();
1043 else
1044 Type = Context.getjmp_bufType();
1045
1046 if (Type.isNull()) {
1047 Error = Signed ? ASTContext::GE_Missing_sigjmp_buf :
1048 ASTContext::GE_Missing_jmp_buf;
1049 return QualType();
1050 }
1051 break;
1052
1053The idea is to reduce indentation and the amount of code you have to keep track
1054of when reading the code.
1055
1056Turn Predicate Loops into Predicate Functions
1057^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1058
1059It is very common to write small loops that just compute a boolean value. There
1060are a number of ways that people commonly write these, but an example of this
1061sort of thing is:
1062
1063.. code-block:: c++
1064
1065 bool FoundFoo = false;
Sean Silva7333a842012-11-17 23:25:33 +00001066 for (unsigned I = 0, E = BarList.size(); I != E; ++I)
1067 if (BarList[I]->isFoo()) {
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001068 FoundFoo = true;
1069 break;
1070 }
1071
1072 if (FoundFoo) {
1073 ...
1074 }
1075
1076This sort of code is awkward to write, and is almost always a bad sign. Instead
1077of this sort of loop, we strongly prefer to use a predicate function (which may
1078be `static`_) that uses `early exits`_ to compute the predicate. We prefer the
1079code to be structured like this:
1080
1081.. code-block:: c++
1082
Dmitri Gribenko9fb49d22012-10-20 13:27:43 +00001083 /// \returns true if the specified list has an element that is a foo.
Andrew Trickfc9420c2012-09-20 02:01:06 +00001084 static bool containsFoo(const std::vector<Bar*> &List) {
Sean Silva7333a842012-11-17 23:25:33 +00001085 for (unsigned I = 0, E = List.size(); I != E; ++I)
1086 if (List[I]->isFoo())
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001087 return true;
1088 return false;
1089 }
1090 ...
1091
Andrew Trickfc9420c2012-09-20 02:01:06 +00001092 if (containsFoo(BarList)) {
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001093 ...
1094 }
1095
1096There are many reasons for doing this: it reduces indentation and factors out
1097code which can often be shared by other code that checks for the same predicate.
1098More importantly, it *forces you to pick a name* for the function, and forces
1099you to write a comment for it. In this silly example, this doesn't add much
1100value. However, if the condition is complex, this can make it a lot easier for
1101the reader to understand the code that queries for this predicate. Instead of
1102being faced with the in-line details of how we check to see if the BarList
1103contains a foo, we can trust the function name and continue reading with better
1104locality.
1105
1106The Low-Level Issues
1107--------------------
1108
1109Name Types, Functions, Variables, and Enumerators Properly
1110^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1111
1112Poorly-chosen names can mislead the reader and cause bugs. We cannot stress
1113enough how important it is to use *descriptive* names. Pick names that match
1114the semantics and role of the underlying entities, within reason. Avoid
1115abbreviations unless they are well known. After picking a good name, make sure
1116to use consistent capitalization for the name, as inconsistency requires clients
1117to either memorize the APIs or to look it up to find the exact spelling.
1118
1119In general, names should be in camel case (e.g. ``TextFileReader`` and
1120``isLValue()``). Different kinds of declarations have different rules:
1121
1122* **Type names** (including classes, structs, enums, typedefs, etc) should be
1123 nouns and start with an upper-case letter (e.g. ``TextFileReader``).
1124
1125* **Variable names** should be nouns (as they represent state). The name should
1126 be camel case, and start with an upper case letter (e.g. ``Leader`` or
1127 ``Boats``).
1128
1129* **Function names** should be verb phrases (as they represent actions), and
1130 command-like function should be imperative. The name should be camel case,
1131 and start with a lower case letter (e.g. ``openFile()`` or ``isFoo()``).
1132
1133* **Enum declarations** (e.g. ``enum Foo {...}``) are types, so they should
1134 follow the naming conventions for types. A common use for enums is as a
1135 discriminator for a union, or an indicator of a subclass. When an enum is
1136 used for something like this, it should have a ``Kind`` suffix
1137 (e.g. ``ValueKind``).
1138
1139* **Enumerators** (e.g. ``enum { Foo, Bar }``) and **public member variables**
1140 should start with an upper-case letter, just like types. Unless the
1141 enumerators are defined in their own small namespace or inside a class,
1142 enumerators should have a prefix corresponding to the enum declaration name.
1143 For example, ``enum ValueKind { ... };`` may contain enumerators like
1144 ``VK_Argument``, ``VK_BasicBlock``, etc. Enumerators that are just
1145 convenience constants are exempt from the requirement for a prefix. For
1146 instance:
1147
1148 .. code-block:: c++
1149
1150 enum {
1151 MaxSize = 42,
1152 Density = 12
1153 };
1154
1155As an exception, classes that mimic STL classes can have member names in STL's
1156style of lower-case words separated by underscores (e.g. ``begin()``,
Rafael Espindolab0b16222013-08-07 19:34:37 +00001157``push_back()``, and ``empty()``). Classes that provide multiple
1158iterators should add a singular prefix to ``begin()`` and ``end()``
1159(e.g. ``global_begin()`` and ``use_begin()``).
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001160
1161Here are some examples of good and bad names:
1162
Meador Inge6a706af2012-06-20 23:57:00 +00001163.. code-block:: c++
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001164
1165 class VehicleMaker {
1166 ...
1167 Factory<Tire> F; // Bad -- abbreviation and non-descriptive.
1168 Factory<Tire> Factory; // Better.
1169 Factory<Tire> TireFactory; // Even better -- if VehicleMaker has more than one
1170 // kind of factories.
1171 };
1172
Alexander Kornienkof1e68ff2016-09-27 14:49:45 +00001173 Vehicle makeVehicle(VehicleType Type) {
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001174 VehicleMaker M; // Might be OK if having a short life-span.
Sean Silva7333a842012-11-17 23:25:33 +00001175 Tire Tmp1 = M.makeTire(); // Bad -- 'Tmp1' provides no information.
1176 Light Headlight = M.makeLight("head"); // Good -- descriptive.
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001177 ...
1178 }
1179
1180Assert Liberally
1181^^^^^^^^^^^^^^^^
1182
1183Use the "``assert``" macro to its fullest. Check all of your preconditions and
1184assumptions, you never know when a bug (not necessarily even yours) might be
1185caught early by an assertion, which reduces debugging time dramatically. The
1186"``<cassert>``" header file is probably already included by the header files you
1187are using, so it doesn't cost anything to use it.
1188
1189To further assist with debugging, make sure to put some kind of error message in
1190the assertion statement, which is printed if the assertion is tripped. This
1191helps the poor debugger make sense of why an assertion is being made and
1192enforced, and hopefully what to do about it. Here is one complete example:
1193
1194.. code-block:: c++
1195
Sean Silva7333a842012-11-17 23:25:33 +00001196 inline Value *getOperand(unsigned I) {
1197 assert(I < Operands.size() && "getOperand() out of range!");
1198 return Operands[I];
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001199 }
1200
1201Here are more examples:
1202
1203.. code-block:: c++
1204
Alp Tokerf907b892013-12-05 05:44:44 +00001205 assert(Ty->isPointerType() && "Can't allocate a non-pointer type!");
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001206
1207 assert((Opcode == Shl || Opcode == Shr) && "ShiftInst Opcode invalid!");
1208
1209 assert(idx < getNumSuccessors() && "Successor # out of range!");
1210
1211 assert(V1.getType() == V2.getType() && "Constant types must be identical!");
1212
1213 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
1214
1215You get the idea.
1216
Jordan Rose2962d952012-10-26 22:08:46 +00001217In the past, asserts were used to indicate a piece of code that should not be
1218reached. These were typically of the form:
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001219
1220.. code-block:: c++
1221
Jordan Rose2962d952012-10-26 22:08:46 +00001222 assert(0 && "Invalid radix for integer literal");
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001223
Jordan Rose2962d952012-10-26 22:08:46 +00001224This has a few issues, the main one being that some compilers might not
1225understand the assertion, or warn about a missing return in builds where
1226assertions are compiled out.
1227
1228Today, we have something much better: ``llvm_unreachable``:
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001229
1230.. code-block:: c++
1231
Jordan Rose2962d952012-10-26 22:08:46 +00001232 llvm_unreachable("Invalid radix for integer literal");
1233
1234When assertions are enabled, this will print the message if it's ever reached
1235and then exit the program. When assertions are disabled (i.e. in release
1236builds), ``llvm_unreachable`` becomes a hint to compilers to skip generating
1237code for this branch. If the compiler does not support this, it will fall back
1238to the "abort" implementation.
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001239
1240Another issue is that values used only by assertions will produce an "unused
1241value" warning when assertions are disabled. For example, this code will warn:
1242
1243.. code-block:: c++
1244
1245 unsigned Size = V.size();
1246 assert(Size > 42 && "Vector smaller than it should be");
1247
1248 bool NewToSet = Myset.insert(Value);
1249 assert(NewToSet && "The value shouldn't be in the set yet");
1250
1251These are two interesting different cases. In the first case, the call to
1252``V.size()`` is only useful for the assert, and we don't want it executed when
1253assertions are disabled. Code like this should move the call into the assert
1254itself. In the second case, the side effects of the call must happen whether
1255the assert is enabled or not. In this case, the value should be cast to void to
1256disable the warning. To be specific, it is preferred to write the code like
1257this:
1258
1259.. code-block:: c++
1260
1261 assert(V.size() > 42 && "Vector smaller than it should be");
1262
1263 bool NewToSet = Myset.insert(Value); (void)NewToSet;
1264 assert(NewToSet && "The value shouldn't be in the set yet");
1265
1266Do Not Use ``using namespace std``
1267^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1268
1269In LLVM, we prefer to explicitly prefix all identifiers from the standard
1270namespace with an "``std::``" prefix, rather than rely on "``using namespace
1271std;``".
1272
1273In header files, adding a ``'using namespace XXX'`` directive pollutes the
1274namespace of any source file that ``#include``\s the header. This is clearly a
1275bad thing.
1276
1277In implementation files (e.g. ``.cpp`` files), the rule is more of a stylistic
1278rule, but is still important. Basically, using explicit namespace prefixes
1279makes the code **clearer**, because it is immediately obvious what facilities
1280are being used and where they are coming from. And **more portable**, because
1281namespace clashes cannot occur between LLVM code and other namespaces. The
1282portability rule is important because different standard library implementations
1283expose different symbols (potentially ones they shouldn't), and future revisions
1284to the C++ standard will add more symbols to the ``std`` namespace. As such, we
1285never use ``'using namespace std;'`` in LLVM.
1286
1287The exception to the general rule (i.e. it's not an exception for the ``std``
1288namespace) is for implementation files. For example, all of the code in the
1289LLVM project implements code that lives in the 'llvm' namespace. As such, it is
1290ok, and actually clearer, for the ``.cpp`` files to have a ``'using namespace
1291llvm;'`` directive at the top, after the ``#include``\s. This reduces
1292indentation in the body of the file for source editors that indent based on
1293braces, and keeps the conceptual context cleaner. The general form of this rule
1294is that any ``.cpp`` file that implements code in any namespace may use that
1295namespace (and its parents'), but should not use any others.
1296
1297Provide a Virtual Method Anchor for Classes in Headers
1298^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1299
1300If a class is defined in a header file and has a vtable (either it has virtual
1301methods or it derives from classes with virtual methods), it must always have at
1302least one out-of-line virtual method in the class. Without this, the compiler
1303will copy the vtable and RTTI into every ``.o`` file that ``#include``\s the
1304header, bloating ``.o`` file sizes and increasing link times.
1305
David Blaikie00bec9a2012-09-21 17:47:36 +00001306Don't use default labels in fully covered switches over enumerations
1307^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1308
1309``-Wswitch`` warns if a switch, without a default label, over an enumeration
1310does not cover every enumeration value. If you write a default label on a fully
1311covered switch over an enumeration then the ``-Wswitch`` warning won't fire
1312when new elements are added to that enumeration. To help avoid adding these
1313kinds of defaults, Clang has the warning ``-Wcovered-switch-default`` which is
1314off by default but turned on when building LLVM with a version of Clang that
1315supports the warning.
1316
1317A knock-on effect of this stylistic requirement is that when building LLVM with
David Blaikief787f172012-09-21 18:03:02 +00001318GCC you may get warnings related to "control may reach end of non-void function"
David Blaikie00bec9a2012-09-21 17:47:36 +00001319if you return from each case of a covered switch-over-enum because GCC assumes
David Blaikief787f172012-09-21 18:03:02 +00001320that the enum expression may take any representable value, not just those of
1321individual enumerators. To suppress this warning, use ``llvm_unreachable`` after
1322the switch.
David Blaikie00bec9a2012-09-21 17:47:36 +00001323
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001324Don't evaluate ``end()`` every time through a loop
1325^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1326
1327Because C++ doesn't have a standard "``foreach``" loop (though it can be
1328emulated with macros and may be coming in C++'0x) we end up writing a lot of
1329loops that manually iterate from begin to end on a variety of containers or
1330through other data structures. One common mistake is to write a loop in this
1331style:
1332
1333.. code-block:: c++
1334
1335 BasicBlock *BB = ...
1336 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
1337 ... use I ...
1338
1339The problem with this construct is that it evaluates "``BB->end()``" every time
1340through the loop. Instead of writing the loop like this, we strongly prefer
1341loops to be written so that they evaluate it once before the loop starts. A
1342convenient way to do this is like so:
1343
1344.. code-block:: c++
1345
1346 BasicBlock *BB = ...
1347 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1348 ... use I ...
1349
1350The observant may quickly point out that these two loops may have different
1351semantics: if the container (a basic block in this case) is being mutated, then
1352"``BB->end()``" may change its value every time through the loop and the second
1353loop may not in fact be correct. If you actually do depend on this behavior,
1354please write the loop in the first form and add a comment indicating that you
1355did it intentionally.
1356
1357Why do we prefer the second form (when correct)? Writing the loop in the first
1358form has two problems. First it may be less efficient than evaluating it at the
1359start of the loop. In this case, the cost is probably minor --- a few extra
1360loads every time through the loop. However, if the base expression is more
1361complex, then the cost can rise quickly. I've seen loops where the end
Sean Silva7333a842012-11-17 23:25:33 +00001362expression was actually something like: "``SomeMap[X]->end()``" and map lookups
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001363really aren't cheap. By writing it in the second form consistently, you
1364eliminate the issue entirely and don't even have to think about it.
1365
1366The second (even bigger) issue is that writing the loop in the first form hints
1367to the reader that the loop is mutating the container (a fact that a comment
1368would handily confirm!). If you write the loop in the second form, it is
1369immediately obvious without even looking at the body of the loop that the
1370container isn't being modified, which makes it easier to read the code and
1371understand what it does.
1372
1373While the second form of the loop is a few extra keystrokes, we do strongly
1374prefer it.
1375
1376``#include <iostream>`` is Forbidden
1377^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1378
1379The use of ``#include <iostream>`` in library files is hereby **forbidden**,
1380because many common implementations transparently inject a `static constructor`_
1381into every translation unit that includes it.
1382
1383Note that using the other stream headers (``<sstream>`` for example) is not
1384problematic in this regard --- just ``<iostream>``. However, ``raw_ostream``
1385provides various APIs that are better performing for almost every use than
1386``std::ostream`` style APIs.
1387
1388.. note::
1389
1390 New code should always use `raw_ostream`_ for writing, or the
1391 ``llvm::MemoryBuffer`` API for reading files.
1392
1393.. _raw_ostream:
1394
1395Use ``raw_ostream``
1396^^^^^^^^^^^^^^^^^^^
1397
1398LLVM includes a lightweight, simple, and efficient stream implementation in
1399``llvm/Support/raw_ostream.h``, which provides all of the common features of
1400``std::ostream``. All new code should use ``raw_ostream`` instead of
1401``ostream``.
1402
1403Unlike ``std::ostream``, ``raw_ostream`` is not a template and can be forward
1404declared as ``class raw_ostream``. Public headers should generally not include
1405the ``raw_ostream`` header, but use forward declarations and constant references
1406to ``raw_ostream`` instances.
1407
1408Avoid ``std::endl``
1409^^^^^^^^^^^^^^^^^^^
1410
1411The ``std::endl`` modifier, when used with ``iostreams`` outputs a newline to
1412the output stream specified. In addition to doing this, however, it also
1413flushes the output stream. In other words, these are equivalent:
1414
1415.. code-block:: c++
1416
1417 std::cout << std::endl;
1418 std::cout << '\n' << std::flush;
1419
1420Most of the time, you probably have no reason to flush the output stream, so
1421it's better to use a literal ``'\n'``.
1422
Dmitri Gribenkoa84c59c2013-02-04 10:24:58 +00001423Don't use ``inline`` when defining a function in a class definition
1424^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1425
1426A member function defined in a class definition is implicitly inline, so don't
1427put the ``inline`` keyword in this case.
1428
1429Don't:
1430
1431.. code-block:: c++
1432
1433 class Foo {
1434 public:
1435 inline void bar() {
1436 // ...
1437 }
1438 };
1439
1440Do:
1441
1442.. code-block:: c++
1443
1444 class Foo {
1445 public:
1446 void bar() {
1447 // ...
1448 }
1449 };
1450
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001451Microscopic Details
1452-------------------
1453
1454This section describes preferred low-level formatting guidelines along with
1455reasoning on why we prefer them.
1456
1457Spaces Before Parentheses
1458^^^^^^^^^^^^^^^^^^^^^^^^^
1459
1460We prefer to put a space before an open parenthesis only in control flow
1461statements, but not in normal function call expressions and function-like
1462macros. For example, this is good:
1463
1464.. code-block:: c++
1465
Sean Silva7333a842012-11-17 23:25:33 +00001466 if (X) ...
1467 for (I = 0; I != 100; ++I) ...
1468 while (LLVMRocks) ...
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001469
1470 somefunc(42);
1471 assert(3 != 4 && "laws of math are failing me");
1472
Sean Silva7333a842012-11-17 23:25:33 +00001473 A = foo(42, 92) + bar(X);
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001474
1475and this is bad:
1476
1477.. code-block:: c++
1478
Sean Silva7333a842012-11-17 23:25:33 +00001479 if(X) ...
1480 for(I = 0; I != 100; ++I) ...
1481 while(LLVMRocks) ...
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001482
1483 somefunc (42);
1484 assert (3 != 4 && "laws of math are failing me");
1485
Sean Silva7333a842012-11-17 23:25:33 +00001486 A = foo (42, 92) + bar (X);
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001487
1488The reason for doing this is not completely arbitrary. This style makes control
1489flow operators stand out more, and makes expressions flow better. The function
1490call operator binds very tightly as a postfix operator. Putting a space after a
1491function name (as in the last example) makes it appear that the code might bind
1492the arguments of the left-hand-side of a binary operator with the argument list
1493of a function and the name of the right side. More specifically, it is easy to
Sean Silva7333a842012-11-17 23:25:33 +00001494misread the "``A``" example as:
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001495
1496.. code-block:: c++
1497
Sean Silva7333a842012-11-17 23:25:33 +00001498 A = foo ((42, 92) + bar) (X);
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001499
1500when skimming through the code. By avoiding a space in a function, we avoid
1501this misinterpretation.
1502
1503Prefer Preincrement
1504^^^^^^^^^^^^^^^^^^^
1505
1506Hard fast rule: Preincrement (``++X``) may be no slower than postincrement
1507(``X++``) and could very well be a lot faster than it. Use preincrementation
1508whenever possible.
1509
1510The semantics of postincrement include making a copy of the value being
1511incremented, returning it, and then preincrementing the "work value". For
1512primitive types, this isn't a big deal. But for iterators, it can be a huge
1513issue (for example, some iterators contains stack and set objects in them...
1514copying an iterator could invoke the copy ctor's of these as well). In general,
1515get in the habit of always using preincrement, and you won't have a problem.
1516
1517
1518Namespace Indentation
1519^^^^^^^^^^^^^^^^^^^^^
1520
1521In general, we strive to reduce indentation wherever possible. This is useful
1522because we want code to `fit into 80 columns`_ without wrapping horribly, but
Chandler Carruth36dc5192014-01-20 10:15:32 +00001523also because it makes it easier to understand the code. To facilitate this and
1524avoid some insanely deep nesting on occasion, don't indent namespaces. If it
1525helps readability, feel free to add a comment indicating what namespace is
1526being closed by a ``}``. For example:
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001527
1528.. code-block:: c++
1529
1530 namespace llvm {
1531 namespace knowledge {
1532
Dmitri Gribenko9fb49d22012-10-20 13:27:43 +00001533 /// This class represents things that Smith can have an intimate
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001534 /// understanding of and contains the data associated with it.
1535 class Grokable {
1536 ...
1537 public:
1538 explicit Grokable() { ... }
1539 virtual ~Grokable() = 0;
1540
1541 ...
1542
1543 };
1544
1545 } // end namespace knowledge
1546 } // end namespace llvm
1547
Chandler Carruth36dc5192014-01-20 10:15:32 +00001548
1549Feel free to skip the closing comment when the namespace being closed is
1550obvious for any reason. For example, the outer-most namespace in a header file
1551is rarely a source of confusion. But namespaces both anonymous and named in
1552source files that are being closed half way through the file probably could use
1553clarification.
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001554
1555.. _static:
1556
1557Anonymous Namespaces
1558^^^^^^^^^^^^^^^^^^^^
1559
1560After talking about namespaces in general, you may be wondering about anonymous
1561namespaces in particular. Anonymous namespaces are a great language feature
1562that tells the C++ compiler that the contents of the namespace are only visible
1563within the current translation unit, allowing more aggressive optimization and
1564eliminating the possibility of symbol name collisions. Anonymous namespaces are
1565to C++ as "static" is to C functions and global variables. While "``static``"
1566is available in C++, anonymous namespaces are more general: they can make entire
1567classes private to a file.
1568
1569The problem with anonymous namespaces is that they naturally want to encourage
1570indentation of their body, and they reduce locality of reference: if you see a
1571random function definition in a C++ file, it is easy to see if it is marked
1572static, but seeing if it is in an anonymous namespace requires scanning a big
1573chunk of the file.
1574
1575Because of this, we have a simple guideline: make anonymous namespaces as small
1576as possible, and only use them for class declarations. For example, this is
1577good:
1578
1579.. code-block:: c++
1580
1581 namespace {
Chandler Carruth36dc5192014-01-20 10:15:32 +00001582 class StringSort {
1583 ...
1584 public:
1585 StringSort(...)
1586 bool operator<(const char *RHS) const;
1587 };
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001588 } // end anonymous namespace
1589
Andrew Trickfc9420c2012-09-20 02:01:06 +00001590 static void runHelper() {
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001591 ...
1592 }
1593
1594 bool StringSort::operator<(const char *RHS) const {
1595 ...
1596 }
1597
1598This is bad:
1599
1600.. code-block:: c++
1601
1602 namespace {
Chandler Carruth36dc5192014-01-20 10:15:32 +00001603
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001604 class StringSort {
1605 ...
1606 public:
1607 StringSort(...)
1608 bool operator<(const char *RHS) const;
1609 };
1610
Andrew Trickfc9420c2012-09-20 02:01:06 +00001611 void runHelper() {
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001612 ...
1613 }
1614
1615 bool StringSort::operator<(const char *RHS) const {
1616 ...
1617 }
1618
1619 } // end anonymous namespace
1620
Andrew Trickfc9420c2012-09-20 02:01:06 +00001621This is bad specifically because if you're looking at "``runHelper``" in the middle
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001622of a large C++ file, that you have no immediate way to tell if it is local to
1623the file. When it is marked static explicitly, this is immediately obvious.
1624Also, there is no reason to enclose the definition of "``operator<``" in the
1625namespace just because it was declared there.
1626
1627See Also
1628========
1629
Joel Jones7818be42013-01-21 23:20:47 +00001630A lot of these comments and recommendations have been culled from other sources.
Bill Wendling1c5e94a2012-06-20 02:57:56 +00001631Two particularly important books for our work are:
1632
1633#. `Effective C++
1634 <http://www.amazon.com/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0321334876>`_
1635 by Scott Meyers. Also interesting and useful are "More Effective C++" and
1636 "Effective STL" by the same author.
1637
1638#. `Large-Scale C++ Software Design
1639 <http://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620/ref=sr_1_1>`_
1640 by John Lakos
1641
1642If you get some free time, and you haven't read them: do so, you might learn
1643something.