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