HotSpot Coding Style

Introduction

This is a collection of rules, guidelines, and suggestions for writing HotSpot code. Following these will help new code fit in with existing HotSpot code, making it easier to read and maintain. Failure to follow these guidelines may lead to discussion during code reviews, if not outright rejection of a change.

Changing this Document

Proposed changes should be discussed on the HotSpot Developers mailing list. Changes are likely to be cautious and incremental, since HotSpot coders have been using these guidelines for years.

Substantive changes are approved by rough consensus of the HotSpot Group Members. The Group Lead determines whether consensus has been reached.

Editorial changes (changes that only affect the description of HotSpot style, not its substance) do not require the full consensus gathering process. The normal HotSpot pull request process may be used for editorial changes, with the additional requirement that the requisite reviewers are also HotSpot Group Members.

Why Care About Style?

Some programmers seem to have lexers and even C preprocessors installed directly behind their eyeballs. The rest of us require code that is not only functionally correct but also easy to read. More than that, since there is no one style for easy-to-read code, and since a mashup of many styles is just as confusing as no style at all, it is important for coders to be conscious of the many implicit stylistic choices that historically have gone into the HotSpot code base.

Some of these guidelines are driven by the cross-platform requirements for HotSpot. Shared code must work on a variety of platforms, and may encounter deficiencies in some. Using platform conditionalization in shared code is usually avoided, while shared code is strongly preferred to multiple platform-dependent implementations, so some language features may be recommended against.

Some of the guidelines here are relatively arbitrary choices among equally plausible alternatives. The purpose of stating and enforcing these rules is largely to provide a consistent look to the code. That consistency makes the code more readable by avoiding non-functional distractions from the interesting functionality.

When changing pre-existing code, it is reasonable to adjust it to match these conventions. Exception: If the pre-existing code clearly conforms locally to its own peculiar conventions, it is not worth reformatting the whole thing. Also consider separating changes that make extensive stylistic updates from those which make functional changes.

Counterexamples

Many of the guidelines mentioned here have (sometimes widespread) counterexamples in the HotSpot code base. Finding a counterexample is not sufficient justification for new code to follow the counterexample as a precedent, since readers of your code will rightfully expect your code to follow the greater bulk of precedents documented here.

Occasionally a guideline mentioned here may be just out of synch with the actual HotSpot code base. If you find that a guideline is consistently contradicted by a large number of counterexamples, please bring it up for discussion and possible change. The architectural rule, of course, is "When in Rome do as the Romans". Sometimes in the suburbs of Rome the rules are a little different; these differences can be pointed out here.

Structure and Formatting

Factoring and Class Design

Conventions for Lock-free Code

Sometimes variables are accessed concurrently without appropriate synchronization context, such as a held mutex or at a safepoint. In such cases the variable should be declared volatile and it should NOT be accessed as a normal C++ lvalue. Rather, access should be performed via functions from Atomic, such as Atomic::load, Atomic::store, etc.

This special formulation makes it more clear to maintainers that the variable is accessed concurrently in a lock-free manner.

Source Files

JTReg Tests

Naming

Commenting

Macros

Whitespace

Avoid implicit conversions to bool

Miscellaneous

Use of C++ Features

HotSpot was originally written in a subset of the C++98/03 language. More recently, support for C++17 is provided, though again, HotSpot only uses a subset. (Backports to JDK versions lacking support for more recent Standards must of course stick with the original C++98/03 subset.)

This section describes that subset. Features from the C++98/03 language may be used unless explicitly excluded here. Features from C++11, C++14, and C++17 may be explicitly permitted or explicitly excluded, and discussed accordingly here. There is a third category, undecided features, about which HotSpot developers have not yet reached a consensus, or perhaps have not discussed at all. Use of these features is also excluded.

(The use of some features may not be immediately obvious and may slip in anyway, since the compiler will accept them. The code review process is the main defense against this.)

Some features are discussed in their own subsection, typically to provide more extensive discussion or rationale for limitations. Features that don't have their own subsection are listed in omnibus feature sections for permitted, excluded, and undecided features.

Lists of new features for C++11, C++14, and C++17, along with links to their descriptions, can be found in the online documentation for some of the compilers and libraries. The C++17 Standard is the definitive description.

As a rule of thumb, permitting features which simplify writing code and, especially, reading code, is encouraged.

Similar discussions for some other projects:

Error Handling

Do not use exceptions. Exceptions are disabled by the build configuration for some platforms.

Rationale: There is significant concern over the performance cost of exceptions and their usage model and implications for maintainable code. That's not just a matter of history that has been fixed; there remain questions and problems even today (2019). See, for example, Zero cost deterministic exceptions. Because of this, HotSpot has always used a build configuration that disables exceptions where that is available. As a result, HotSpot code uses error handling mechanisms such as two-phase construction, factory functions, returning error codes, and immediate termination. Even if the cost of exceptions were not a concern, the existing body of code was not written with exception safety in mind. Making HotSpot exception safe would be a very large undertaking.

In addition to the usual alternatives to exceptions, HotSpot provides its own exception mechanism. This is based on a set of macros defined in utilities/exceptions.hpp.

RTTI (Runtime Type Information)

Do not use Runtime Type Information (RTTI). RTTI is disabled by the build configuration for some platforms. Among other things, this means dynamic_cast cannot be used.

Rationale: Other than to implement exceptions (which HotSpot doesn't use), most potential uses of RTTI are better done via virtual functions. Some of the remainder can be replaced by bespoke mechanisms. The cost of the additional runtime data structures needed to support RTTI are deemed not worthwhile, given the alternatives.

Memory Allocation

Do not use the standard global allocation and deallocation functions (operator new and related functions). Use of these functions by HotSpot code is disabled for some platforms.

Rationale: HotSpot often uses "resource" or "arena" allocation. Even where heap allocation is used, the standard global functions are avoided in favor of wrappers around malloc and free that support the VM's Native Memory Tracking (NMT) feature. Typically, uses of the global operator new are inadvertent and therefore often associated with memory leaks.

Native memory allocation failures are often treated as non-recoverable. The place where "out of memory" is (first) detected may be an innocent bystander, unrelated to the actual culprit.

Class Inheritance

Use public single inheritance.

Prefer composition rather than non-public inheritance.

Restrict inheritance to the "is-a" case; use composition rather than non-is-a related inheritance.

Avoid multiple inheritance. Never use virtual inheritance.

Namespaces

Avoid using namespaces. HotSpot code normally uses "all static" classes rather than namespaces for grouping. An "all static" class is not instantiable, has only static members, and is normally derived (possibly indirectly) from the helper class AllStatic.

Benefits of using such classes include:

Namespaces should be used only in cases where one of those "benefits" is actually a hindrance.

In particular, don't use anonymous namespaces. They seem like they should be useful, and indeed have some real benefits for naming and generated code size on some platforms. Unfortunately, debuggers don't seem to like them at all.

https://groups.google.com/forum/#!topic/mozilla.dev.platform/KsaG3lEEaRM
Suggests Visual Studio debugger might not be able to refer to anonymous namespace symbols, so can't set breakpoints in them. Though the discussion seems to go back and forth on that.

https://firefox-source-docs.mozilla.org/code-quality/coding-style/coding_style_cpp.html
Search for "Anonymous namespaces" Suggests preferring "static" to anonymous namespaces where applicable, because of poor debugger support for anonymous namespaces.

https://sourceware.org/bugzilla/show_bug.cgi?id=16874
Bug for similar gdb problems.

C++ Standard Library

Avoid using the C++ Standard Library.

Historically, HotSpot has mostly avoided use of the Standard Library.

(It used to be impossible to use most of it in shared code, because the build configuration for Solaris with Solaris Studio made all but a couple of pieces inaccessible. Support for header-only parts was added in mid-2017. Support for Solaris was removed in 2020.)

Some reasons for this include

There are a few exceptions to this rule.

Certain restrictions apply to the declarations provided by <type_traits>.

TODO: Rather than directly #including (permitted) Standard Library headers, use a convention of #including wrapper headers (in some location like hotspot/shared/stdcpp). This provides a single place for dealing with issues we might have for any given header, esp. platform-specific issues.

Type Deduction

Use type deduction only if it makes the code clearer or safer. Do not use it merely to avoid the inconvenience of writing an explicit type, unless that type is itself difficult to write. An example of the latter is a function template return type that depends on template parameters in a non-trivial way.

There are several contexts where types are deduced.

* Function return type deduction (n3638)
Only use if the function body has a very small number of return statements, and generally relatively little other code.

  ScopeGuard guard{[&]{ ... cleanup code ... }};

Expression SFINAE

Substitution Failure Is Not An Error (SFINAE) is a template metaprogramming technique that makes use of template parameter substitution failures to make compile-time decisions.

C++11 relaxed the rules for what constitutes a hard-error when attempting to substitute template parameters with template arguments, making most deduction errors be substitution errors; see (n2634). This makes SFINAE more powerful and easier to use. However, the implementation complexity for this change is significant, and this seems to be a place where obscure corner-case bugs in various compilers can be found. So while this feature can (and indeed should) be used (and would be difficult to avoid), caution should be used when pushing to extremes.

Here are a few closely related example bugs:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95468
https://developercommunity.visualstudio.com/content/problem/396562/sizeof-deduced-type-is-sometimes-not-a-constant-ex.html

Trailing return type syntax for functions

A function's return type may be specified after the parameters and qualifiers (n2541). In such a declaration the normal return type is auto and the return type is indicated by -> followed by the type. Although both use auto in the "normal" leading return type position, this differs from function return type deduction, in that the return type is explicit rather than deduced, but specified in a trailing position.

Use of trailing return types is permitted. However, the normal, leading position for the return type is preferred. A trailing return type should only be used where it provides some benefit. Such benefits usually arise because a trailing return type is in a different scope than a leading return type.

template<typename T, typename U> auto add(T t, U u) -> decltype(t + u);

rather than

template<typename T, typename U> decltype((*(T*)0) + (*(U*)0)) add(T t, U u);

Non-type template parameter values

C++17 extended the arguments permitted for non-type template parameters (n4268). The kinds of values (the parameter types) aren't changed. However, the values can now be the result of arbitrary constant expressions (with a few restrictions on the result), rather than a much more limited and restrictive set of expressions. In particular, the argument for a pointer or reference type parameter can now be the result of a constexpr function.

enum

Where appropriate, scoped-enums should be used. (n2347)

Use of unscoped-enums is permitted, though ordinary constants may be preferable when the automatic initializer feature isn't used.

The underlying type (the enum-base) of an unscoped enum type should always be specified explicitly. When unspecified, the underlying type is dependent on the range of the enumerator values and the platform.

The underlying type of a scoped-enum should also be specified explicitly if conversions may be applied to values of that type.

Due to bugs in certain (very old) compilers, there is widespread use of enums and avoidance of in-class initialization of static integral constant members. Compilers having such bugs are no longer supported. Except where an enum is semantically appropriate, new code should use integral constants.

alignas

Alignment-specifiers (alignas n2341) are permitted, with restrictions.

Alignment-specifiers are permitted when the requested alignment is a fundamental alignment (not greater than alignof(std::max_align_t) C++14 3.11/2).

Alignment-specifiers with an extended alignment (greater than alignof(std::max_align_t) C++14 3.11/3) may only be used to align variables with static or automatic storage duration (C++14 3.7.1, 3.7.3). As a consequence, over-aligned types are forbidden; this may change if HotSpot updates to using C++17 or later (p0035r4).

Large extended alignments should be avoided, particularly for stack allocated objects. What is a large value may depend on the platform and configuration. There may also be hard limits for some platforms.

An alignment-specifier must always be applied to a definition (C++14 10.6.2/6). (C++ allows an alignment-specifier to optionally also be applied to a declaration, so long as the definition has equivalent alignment. There isn't any known benefit from duplicating the alignment in a non-definition declaration, so such duplication should be avoided in HotSpot code.)

Enumerations are forbidden from having alignment-specifiers. Aligned enumerations were originally permitted but insufficiently specified, and were later (C++20) removed (CWG 2354). Permitting such usage in HotSpot now would just cause problems in the future.

Alignment-specifiers are forbidden in typedef and alias-declarations. This may work or may have worked in some versions of some compilers, but was later (C++14) explicitly disallowed (CWG 1437).

The HotSpot macro ATTRIBUTE_ALIGNED provides similar capabilities for platforms that define it. This macro predates the use by HotSpot of C++ versions providing alignas. New code should use alignas.

thread_local

Avoid use of thread_local (n2659); and instead, use the HotSpot macro THREAD_LOCAL, for which the initializer must be a constant expression. When thread_local must be used, use the Hotspot macro APPROVED_CPP_THREAD_LOCAL to indicate that the use has been given appropriate consideration.

As was discussed in the review for JDK-8230877, thread_local allows dynamic initialization and destruction semantics. However, that support requires a run-time penalty for references to non-function-local thread_local variables defined in a different translation unit, even if they don't need dynamic initialization. Dynamic initialization and destruction of non-local thread_local variables also has the same ordering problems as for ordinary non-local variables. So we avoid use of thread_local in general, limiting its use to only those cases where dynamic initialization or destruction are essential. See JDK-8282469 for further discussion.

nullptr

Use nullptr (n2431) rather than NULL. See the paper for reasons to avoid NULL.

Don't use (constant expression or literal) 0 for pointers. Note that C++14 removed non-literal 0 constants from null pointer constants, though some compilers continue to treat them as such. For historical reasons there may be lingering uses of 0 as a pointer.

<atomic>

Do not use facilities provided by the <atomic> header (n2427), (n2752); instead, use the HotSpot Atomic class and related facilities.

Atomic operations in HotSpot code must have semantics which are consistent with those provided by the JDK's compilers for Java. There are platform-specific implementation choices that a C++ compiler might make or change that are outside the scope of the C++ Standard, and might differ from what the Java compilers implement.

In addition, HotSpot Atomic has a concept of "conservative" memory ordering, which may differ from (may be stronger than) sequentially consistent. There are algorithms in HotSpot that are believed to rely on that ordering.

Variable Templates and Inline Variables

The use of variable templates (including static data member templates) (N3651) is permitted. They provide parameterized variables and constants in a simple and direct form, instead of requiring the use of various workarounds.

Variables with static storage duration and variable templates may be declared inline (p0386r2), and this usage is permitted. This has similar effects as for declaring a function inline: it can be defined, identically, in multiple translation units, must be defined in every translation unit in which it is ODR used, and the behavior of the program is as if there is exactly one variable.

Declaring a variable inline allows the complete definition to be in a header file, rather than having a declaration in a header and the definition in a .cpp file. The guidance on initialization of such variables still applies. Inline variables with dynamic initializations can make initialization order problems worse. The few ordering constraints that exist for non-inline variables don't apply, as there isn't a single program-designated translation unit containing the definition.

A constexpr static data member or static data member template is implicitly inline. As a consequence, an ODR use of such a member doesn't require a definition in some .cpp file. (This is a change from pre-C++17. Beginning with C++17, such a definition is considered a duplicate definition, and is deprecated.)

Declaring a thread_local variable template or inline variable is forbidden in HotSpot code. The use of thread_local is already heavily restricted.

Initializing variables with static storage duration

Variables with static storage duration and dynamic initialization C++14 3.6.2). should be avoided, unless an implementation is permitted to perform the initialization as a static initialization. The order in which dynamic initializations occur is incompletely specified. Initialization order problems can be difficult to deal with and lead to surprises.

Variables with static storage duration and non-trivial destructors should be avoided. HotSpot doesn't generally try to cleanup on exit, and running destructors at exit can lead to problems.

Some of the approaches used in HotSpot to avoid dynamic initialization include:

Uniform Initialization

The use of uniform initialization (n2672), also known as brace initialization, is permitted.

Some relevant sections from cppreference.com:

Although related, the use of std::initializer_list remains forbidden, as part of the avoidance of the C++ Standard Library in HotSpot code.

Mandatory Copy Elision

Copy elision (or here) is a compiler optimization used to avoid potentially expensive copies in certain situations. It is critical to making practical the performance of return by value or pass by value. It is also unusual in not following the as-if rule for optimizations - copy elision can be applied even if doing so bypasses side-effects of copying/moving the object. The C++ standard explicitly permits this.

However, because it's an optional optimization, the relevant copy/move constructor must be available and accessible, in case the compiler chooses to not apply the optimization even in a situation where permitted.

C++17 changed some cases of copy elision so that there is never a copy/move in these cases (p0135r1). The interesting cases involve a function that returns an unnamed temporary object, and constructors. In such cases the object being initialized from the temporary is always direct initialized, with no copy/move ever involved; see RVO and more specifically URVO.

Since this is now standard behavior it can't be avoided in the covered situations. This could change the behavior of code that relied on side effects by constructors, but that's both uncommon and was already problematic because of the previous optional copy elision. But HotSpot code can, and should, explicitly take advantage of this newly required behavior where it makes sense to do so.

For example, it may be beneficial to delay construction of the result of a function until the return statement, rather than having a local variable that is modified into the desired state and then returned. (Though NRVO may apply in that case.)

It is also now possible to define a factory function for a class that is neither movable nor copyable, if it can be written in a way that makes use of this feature.

Local Function Objects

Single-use function objects can be defined locally within a function, directly at the point of use. This is an alternative to having a function or function object class defined at class or namespace scope.

This usage was somewhat limited by C++03, which does not permit such a class to be used as a template parameter. That restriction was removed by C++11 (n2657). Use of this feature is permitted.

Many HotSpot protocols involve "function-like" objects that involve some named member function rather than a call operator. For example, a function that performs some action on all threads might be written as

void do_something() {
  struct DoSomething : public ThreadClosure {
    virtual void do_thread(Thread* t) {
      ... do something with t ...
    }
  } closure;
  Threads::threads_do(&closure);
}

HotSpot code has historically usually placed the DoSomething class at namespace (or sometimes class) scope. This separates the function's code from its use, often to the detriment of readability. It requires giving the class a globally unique name (if at namespace scope). It also loses the information that the class is intended for use in exactly one place, and does not have any subclasses. (However, the latter can now be indicated by declaring it final.) Often, for simplicity, a local class will skip things like access control and accessor functions, giving the enclosing function direct access to the implementation and eliminating some boilerplate that might be provided if the class is in some outer (more accessible) scope. On the other hand, if there is a lot of surrounding code in the function body or the local class is of significant size, defining it locally can increase clutter and reduce readability.

C++11 added lambda expressions as a new way to write a function object. Simple lambda expressions can be significantly more concise than a function object, eliminating a lot of boiler-plate. On the other hand, a complex lambda expression may not provide much, if any, readability benefit compared to an ordinary function object. Also, while a lambda can encapsulate a call to a "function-like" object, it cannot be used in place of such.

A common use for local functions is as one-use RAII objects. The amount of boilerplate for a function object class (local or not) makes such usage somewhat clumsy and verbose. But with the help of a small amount of supporting utility code, lambdas work particularly well for this use case.

Another use for local functions is partial application. Again here, lambdas are typically much simpler and less verbose than function object classes.

A lambda is a constexpr function if either the parameter declaration clause is followed by constexpr, or it satisfies the requirements for a constexpr function (p0170r1). Thus, using a lambda to package up some computation doesn't incur unnecessary overhead or prevent use in a context required to be compile-time evaluated (such as an array size).

Because of these benefits, lambda expressions are permitted in HotSpot code, with some restrictions and usage guidance. An anonymous lambda is one which is passed directly as an argument. A named lambda is the value of a variable, which is its name.

Lambda expressions should only be passed downward. In particular, a lambda should not be returned from a function or stored in a global variable, whether directly or as the value of a member of some other object. Lambda capture is syntactically subtle (by design), and propagating a lambda in such ways can easily pass references to captured values to places where they are no longer valid. In particular, members of the enclosing this object are effectively captured by reference, even if the default capture is by-value. For such uses-cases a function object class should be used to make the desired value capturing and propagation explicit.

Limiting the capture list to [&] (implicitly capture by reference) is a simplifying restriction that still provides good support for HotSpot usage, while reducing the cases a reader must recognize and understand.

While it is possible to directly invoke an anonymous lambda expression, that feature should not be used, as such a form can be confusing to readers. Instead, name the lambda and call it by name.

Some reasons to prefer a named lambda instead of an anonymous lambda are

Lambda expressions, and particularly anonymous lambda expressions, should be simple and compact. One-liners are good. Anonymous lambdas should usually be limited to a couple lines of body code. More complex lambdas should be named. A named lambda should not clutter the enclosing function and make it long and complex; do continue to break up large functions via the use of separate helper functions.

An anonymous lambda expression should either be a one-liner in a one-line expression, or isolated in its own set of lines. Don't place part of a lambda expression on the same line as other arguments to a function. The body of a multi-line lambda argument should be indented from the start of the capture list, as if that were the start of an ordinary function definition. The body of a multi-line named lambda should be indented one step from the variable's indentation.

Some examples:

  1. foo([&] { ++counter; });

  2. foo(x, [&] { ++counter; });

  3. foo([&] { if (predicate) ++counter; });

  4. foo([&] { auto tmp = process(x); tmp.f(); return tmp.g(); })

  5. Separate one-line lambda from other arguments:

    foo(c.begin(), c.end(),
        [&] (const X& x) { do_something(x); return x.value(); });
  6. Indentation for multi-line lambda:

    c.do_entries([&] (const X& x) {
                   do_something(x, a);
                   do_something1(x, b);
                   do_something2(x, c);
                 });
  7. Separate multi-line lambda from other arguments:

    foo(c.begin(), c.end(),
        [&] (const X& x) {
          do_something(x, a);
          do_something1(x, b);
          do_something2(x, c);
        });
  8. Multi-line named lambda:

    auto do_entry = [&] (const X& x) {
      do_something(x, a);
      do_something1(x, b);
      do_something2(x, c);
    };

Item 4, and especially items 6 and 7, are pushing the simplicity limits for anonymous lambdas. Item 6 might be better written using a named lambda:

c.do_entries(do_entry);

Note that C++11 also added bind expressions as a way to write a function object for partial application, using std::bind and related facilities from the Standard Library. std::bind generalizes and replaces some of the binders from C++03. Bind expressions are not permitted in HotSpot code. They don't provide enough benefit over lambdas or local function classes in the cases where bind expressions are applicable to warrant the introduction of yet another mechanism in this space into HotSpot code.

References:

References from C++17

References from C++20

References from C++23

Inheriting constructors

Do not use inheriting constructors (n2540).

C++11 provides simple syntax allowing a class to inherit the constructors of a base class. Unfortunately there are a number of problems with the original specification, and C++17 contains significant revisions (p0136r1 opens with a list of 8 Core Issues). Although those issues have been addressed, the benefits from this feature are small compared to the complexity. Because of this, HotSpot code must not use inherited constructors.

p0195r0

Attributes

The use of some attributes (n2761) (listed below) is permitted. (Note that some of the attributes defined in that paper didn't make it into the final specification.)

Attributes are syntactically permitted in a broad set of locations, but specific attributes are only permitted in a subset of those locations. In some cases an attribute that appertains to a given element may be placed in any of several locations with the same meaning. In those cases HotSpot has a preferred location.

p0068r0 is the initial proposal for the attributes added by C++17.)

Only the following attributes are permitted:

The following attributes are expressly forbidden:

Direct use of non-standard (and presumably scoped) attributes in shared code is also forbidden. Using such would depend on the C++17 feature that an attribute not recognized by the implementation is ignored (p0283r2). If such an attribute is needed in shared code, the well-established technique of providing an ATTRIBUTE_XXX macro with per-compiler definitions (sometimes empty) should be used. Compilers may warn about unrecognized attributes (whether by name or by location), in order to report typos or misuse. Disabling such warnings globally would not be desirable.

The use of using directives in attribute lists is also forbidden. (p0028r0) (p0028r4) We don't generally use scoped attributes in attribute lists with other attributes. Rather, uses of scoped attributes (which are implementation defined) are generally hidden behind a portability macro that includes the surrounding brackets.

noexcept

Use of noexcept exception specifications (n3050) are permitted with restrictions described below.

HotSpot is built with exceptions disabled, e.g. compile with -fno-exceptions (gcc, clang) or no /EH option (MSVC++). So why do we need to consider noexcept at all? It's because noexcept exception specifications serve two distinct purposes.

The first is to allow the compiler to avoid generating code or data in support of exceptions being thrown by a function. But this is unnecessary, because exceptions are disabled.

The second is to allow the compiler and library code to choose different algorithms, depending on whether some function may throw exceptions. This is only relevant to a certain set of functions.

HotSpot code can assume no exceptions will ever be thrown, even from functions not declared noexcept. So HotSpot code doesn't ever need to check, either with conditional exception specifications or with noexcept expressions.

The exception specification is part of the type of a function (p0012r1. This likely has little impact on HotSpot code, since the use of noexcept is expected to be rare.

Dynamic exception specifications were deprecated in C++11. C++17 removed all but throw(), with that remaining a deprecated equivalent to noexcept.

Enhanced selection statements

C++17 modified the condition part of if and switch statements, permitting an init-statement to be included (p0305r1).

Use of this feature is permitted. (However, complex uses may interfere with readability.) Limiting the scope of a variable involved in the condition, while also making the value available to the statement's body, can improve readability. The alternative method of scope-limiting by introducing a nested scope isn't very popular and is rarely used.

This new syntax is in addition to the condition being a declaration with a brace-or-equal-initializer. For an if statement this new sytax gains that benefit without violating the long-standing guidance against using implicit conversions to bool, which still stands.

For example, uses of Unified Logging sometimes explicitly check whether a LogTarget is enabled. Instead of

  LogTarget(...) lt;
  if (lt.is_enabled()) {
    LogStream log(lt);
    ... use log ...
  }
  ... lt is accessible but probably not needed here ...

using this feature one could write

  if (LogTarget(...) lt; lt.is_enabled()) {
    LogStream log(lt);
    ... use log ...
  }

C++17 also added compile-time if statements (p0292r2). Use of if constexpr is permitted. This feature can replace and (sometimes vastly) simplify many uses of SFINAE. The same declaration and initialization guidance for the condition part apply here as for ordinary if statements.

Expression Evaluation Order

C++17 tightened up the evaluation order for some kinds of subexpressions (p0138r2). Note, however, that the Alternate Evaluation Order for Function Calls alternative in that paper was adopted, rather than the strict left to right order of evaluation for function call arguments that was proposed in the main body of the paper.

The primary purpose of this change seems to be to make certain kinds of call chaining well defined. That's not a style widely used in HotSpot. In general it is better to continue to avoid questions in this area by isolating operations with side effects from other statements. In particular, continue to avoid modifying a value in an expression where it is also used.

Compatibility with C11

C++17 refers to C11 rather than C99. This means that C11 libraries and functions may be used in HotSpot. There may be limitations because of differing levels of compatibility among various compilers and versions of those compilers.

Note that the C parts of the JDK have been built with C11 selected for some time (JDK-8292008).

Additional Permitted Features

Excluded Features

Structured Bindings

The use of structured bindings p0217r3 is forbidden. Preferred approaches for handling functions with multiple return values include

There is a strong preference for names and explicit types, as opposed to offsets and implicit types. For example, there are folks who strongly dislike that some of the Standard Library functions return std::pair because first and second members don't carry any useful information.

File System Library

The use of the File System library is forbidden. HotSpot doesn't do very much with files, and already has adequate mechanisms for its needs. Rewriting in terms of this new library doesn't provide any obviously significant benefits. Having a mix of the existing usage and uses of this new library would be confusing.

n4100 p0218r0 p0219r1 p0317r1 p0392r0 p0430r2 p0492r2 p1164r1

Aggregate Extensions

Aggregates with base classes are forbidden. C++17 allows aggregate initialization for classes with base classes (p0017r1). HotSpot makes very little use of aggregate classes, preferring explicit constructors even for very simple classes.

Additional Excluded Features

Undecided Features

This list is incomplete; it serves to explicitly call out some features that have not yet been discussed.

Some features are undecided (so implicitly forbidden) because we don't expect to use them at all. This might be reconsidered if someone finds a good use case.

Some Standard Library features are undecided (so implicitly forbidden) because, while this Style Guide forbids the use of such, they may be sufficiently useful that we want to permit them anyway. Doing so may require some idiomatic mechanism for addressing things like assert incompatibility, incompatibility with HotSpot's FORBID_C_FUNCTION mechanism, and the like.

std::optional<>

It is undecided whether to permit the use of std::optional<> (p0220r1). It may be sufficiently useful that it should be permitted despite the usual prohibition against using Standard Library facilities. Use of the value() member function must be forbidden, as it reports an invalid access by throwing an exception.

std::byte

It is undecided whether to permit the use of the std::byte type (p0298r3). It may be sufficiently useful that it should be permitted despite the usual prohibition against using Standard Library facilities.

It has been suggested that changing the HotSpot address type to use std::byte has some benefits. That is, replace

typedef u_char*       address;
typedef const u_char* const_address;
using address       = std::byte*;
using const_address = const std::byte*;

in globalDefinitions.hpp.

A specific benefit that was mentioned is that it might improve the horrible way that gdb handles our current definition of the address type.

#include <cstddef>

typedef unsigned char* address;
typedef std::byte* address_b;

int main() {

  char* mem;

  address addr = (address)mem;
  address_b addr_b = (address_b)mem;

  return 0;
}
(gdb) p addr
$1 = (address) 0x7ffff7fe4fa0 <dl_main> "\363\017\036\372Uf\017\357\300H\211\345AWI\211\377AVAUATSH\201\354\210\002"
(gdb) p addr_b
$2 = (address_b) 0x7ffff7fe4fa0 <dl_main>

This needs to be explored. Some folks have said they will do so.

String Views

It is undecided whether to permit the use of std::string_view (p0220r1).

HotSpot doesn't use std::string, but uses char* strings a lot. Wrapping such in a std::string_view to enable the use of various algorithms could be useful. But since HotSpot also doesn't permit use of <algorithm> and the like, that only gets the limited set of algorithms provided by the view class directly.

There is also the issue of NUL termination; string views are not necessarily NUL terminated. Moreover, if one goes to the work of making one that is NUL terminated, that terminator is included in the size.

There are other caveats. Permitting use of string views would require discussion of those.

Substring and Subsequence Searching

In addition to simple substring searching, the Standard Library now includes Boyer-Moore and Boyer-Moore-Horspool searchers, in case someone wants to search really large texts. That seems an unlikely use-case for HotSpot. See p0220r1.

new and delete with Over-Aligned Data

It is undecided whether to permit the use of dynamic allocation of overaligned types (n3396).

HotSpot currently only has a couple of over-aligned types that are dynamically allocated. These are handled manually, not going through new expressions, as that couldn't work before C++17.

One of the ways an over-aligned type might arise is by aligning a data member. This might be done to avoid destructive interference for concurrent accesses. But HotSpot uses a different approach, using explicit padding. Again, this is in part because new and delete of overaligned types didn't work. But we might prefer to continue this approach.

We would need to add operator new overloads to CHeapObj<> and possibly in other places in order to support this. However, it has been suggested that implementing it (efficiently) on top of NMT might be difficult. Note that posix_memalign / _aligned_malloc don't help here, because of NMT's use of malloc headers.

If we don't support it we may want to add operator new overloads that are deleted, to prevent attempted uses.

Alignment usage in non-HotSpot parts of the OpenJDK:

std::to_chars() and std::from_chars

It is undecided whether to permit the use of std::to_chars() and std::from_chars() (p0067r5).

These functions provide low-level conversions between character sequences and numeric values. This seems like a good candidate for use in HotSpot, potentially replacing various clumsy or less performant alternatives. There is no memory allocation. Parsing failures are indicated via error codes rather than exceptions. Various other nice for HotSpot properties.

Note that the published C++17 Standard puts these in <utility>, but a defect report moved them to <charconv>. This also needs <system_error>.

This would require upgrading the minimum gcc version to 11.1 for floating point conversion support. The minimum Visual Studio version is already sufficient. The minimum clang version requirement hasn't been determined yet.

std::launder()

It is undecided whether to permit the use of std::launder() (p0137r1).

Change to permitted if we discover a place where we need it. Or maybe we should just permit it, but hope we don't need it.

Also, C++20 revised the relevant part of Object Lifetime in a way that seems more permissive and with less need of laundering. We don't know if implementations of prior versions take advantage of the difference.

See Object Lifetime: C++17 6.8/8, C++20 6.7.3/8

Additional Undecided Features