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