Debian Codegraph @

clang/docs/StandardCPlusPlusModules.rst

raw
1 ====================
2 Standard C++ Modules
3 ====================
4
5 .. contents::
6 :local:
7
8 Introduction
9 ============
10
11 The term ``module`` is ambiguous, as it is used to mean multiple things in
12 Clang. For Clang users, a module may refer to an ``Objective-C Module``,
13 `Clang Module <Modules.html>`_ (also called a ``Clang Header Module``) or a
14 ``C++20 Module`` (or a ``Standard C++ Module``). The implementation of all
15 these kinds of modules in Clang shares a lot of code, but from the perspective
16 of users their semantics and command line interfaces are very different. This
17 document is an introduction to the use of C++20 modules in Clang. In the
18 remainder of this document, the term ``module`` will refer to Standard C++20
19 modules and the term ``Clang module`` will refer to the Clang Modules
20 extension.
21
22 In terms of the C++ Standard, modules consist of two components: "Named
23 Modules" or "Header Units". This document covers both.
24
25 Standard C++ Named modules
26 ==========================
27
28 In order to better understand the compiler's behavior, it is helpful to
29 understand some terms and definitions for readers who are not familiar with the
30 C++ feature. This document is not a tutorial on C++; it only introduces
31 necessary concepts to better understand use of modules in a project.
32
33 Background and terminology
34 --------------------------
35
36 Module and module unit
37 ~~~~~~~~~~~~~~~~~~~~~~
38
39 A module consists of one or more module units. A module unit is a special kind
40 of translation unit. A module unit should almost always start with a module
41 declaration. The syntax of the module declaration is:
42
43 .. code-block:: c++
44
45 [export] module module_name[:partition_name];
46
47 Terms enclosed in ``[]`` are optional. ``module_name`` and ``partition_name``
48 follow the rules for a C++ identifier, except that they may contain one or more
49 period (``.``) characters. Note that a ``.`` in the name has no semantic
50 meaning and does not imply any hierarchy.
51
52 In this document, module units are classified as:
53
54 * Primary module interface unit
55 * Module implementation unit
56 * Module partition interface unit
57 * Internal module partition unit
58
59 A primary module interface unit is a module unit whose module declaration is
60 ``export module module_name;`` where ``module_name`` denotes the name of the
61 module. A module should have one and only one primary module interface unit.
62
63 A module implementation unit is a module unit whose module declaration is
64 ``module module_name;``. Multiple module implementation units can be declared
65 in the same module.
66
67 A module partition interface unit is a module unit whose module declaration is
68 ``export module module_name:partition_name;``. The ``partition_name`` should be
69 unique within any given module.
70
71 An internal module partition unit is a module unit whose module
72 declaration is ``module module_name:partition_name;``. The ``partition_name``
73 should be unique within any given module.
74
75 In this document, we use the following terms:
76
77 * A ``module interface unit`` refers to either a ``primary module interface unit``
78 or a ``module partition interface unit``.
79
80 * An ``importable module unit`` refers to either a ``module interface unit`` or
81 an ``internal module partition unit``.
82
83 * A ``module partition unit`` refers to either a ``module partition interface unit``
84 or an ``internal module partition unit``.
85
86 Built Module Interface
87 ~~~~~~~~~~~~~~~~~~~~~~
88
89 A ``Built Module Interface`` (or ``BMI``) is the precompiled result of an
90 importable module unit.
91
92 Global module fragment
93 ~~~~~~~~~~~~~~~~~~~~~~
94
95 The ``global module fragment`` (or ``GMF``) is the code between the ``module;``
96 and the module declaration within a module unit.
97
98
99 How to build projects using modules
100 -----------------------------------
101
102 Quick Start
103 ~~~~~~~~~~~
104
105 Let's see a "hello world" example that uses modules.
106
107 .. code-block:: c++
108
109 // Hello.cppm
110 module;
111 #include <iostream>
112 export module Hello;
113 export void hello() {
114 std::cout << "Hello World!\n";
115 }
116
117 // use.cpp
118 import Hello;
119 int main() {
120 hello();
121 return 0;
122 }
123
124 Then, on the command line, invoke Clang like:
125
126 .. code-block:: console
127
128 $ clang++ -std=c++20 Hello.cppm --precompile -o Hello.pcm
129 $ clang++ -std=c++20 use.cpp -fmodule-file=Hello=Hello.pcm Hello.pcm -o Hello.out
130 $ ./Hello.out
131 Hello World!
132
133 In this example, we make and use a simple module ``Hello`` which contains only a
134 primary module interface unit named ``Hello.cppm``.
135
136 A more complex "hello world" example which uses the 4 kinds of module units is:
137
138 .. code-block:: c++
139
140 // M.cppm
141 export module M;
142 export import :interface_part;
143 import :impl_part;
144 export void Hello();
145
146 // interface_part.cppm
147 export module M:interface_part;
148 export void World();
149
150 // impl_part.cppm
151 module;
152 #include <iostream>
153 #include <string>
154 module M:impl_part;
155 import :interface_part;
156
157 std::string W = "World.";
158 void World() {
159 std::cout << W << std::endl;
160 }
161
162 // Impl.cpp
163 module;
164 #include <iostream>
165 module M;
166 void Hello() {
167 std::cout << "Hello ";
168 }
169
170 // User.cpp
171 import M;
172 int main() {
173 Hello();
174 World();
175 return 0;
176 }
177
178 Then, back on the command line, invoke Clang with:
179
180 .. code-block:: console
181
182 # Precompiling the module
183 $ clang++ -std=c++20 interface_part.cppm --precompile -o M-interface_part.pcm
184 $ clang++ -std=c++20 impl_part.cppm --precompile -fprebuilt-module-path=. -o M-impl_part.pcm
185 $ clang++ -std=c++20 M.cppm --precompile -fprebuilt-module-path=. -o M.pcm
186 $ clang++ -std=c++20 Impl.cpp -fprebuilt-module-path=. -c -o Impl.o
187
188 # Compiling the user
189 $ clang++ -std=c++20 User.cpp -fprebuilt-module-path=. -c -o User.o
190
191 # Compiling the module and linking it together
192 $ clang++ -std=c++20 M-interface_part.pcm -fprebuilt-module-path=. -c -o M-interface_part.o
193 $ clang++ -std=c++20 M-impl_part.pcm -fprebuilt-module-path=. -c -o M-impl_part.o
194 $ clang++ -std=c++20 M.pcm -fprebuilt-module-path=. -c -o M.o
195 $ clang++ User.o M-interface_part.o M-impl_part.o M.o Impl.o -o a.out
196
197 We explain the options in the following sections.
198
199 How to enable standard C++ modules
200 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
201
202 Standard C++ modules are enabled automatically when the language standard mode
203 is ``-std=c++20`` or newer.
204
205 How to produce a BMI
206 ~~~~~~~~~~~~~~~~~~~~
207
208 To generate a BMI for an importable module unit, use either the ``--precompile``
209 or ``-fmodule-output`` command line options.
210
211 The ``--precompile`` option generates the BMI as the output of the compilation
212 with the output path specified using the ``-o`` option.
213
214 The ``-fmodule-output`` option generates the BMI as a by-product of the
215 compilation. If ``-fmodule-output=`` is specified, the BMI will be emitted to
216 the specified location. If ``-fmodule-output`` and ``-c`` are specified, the
217 BMI will be emitted in the directory of the output file with the name of the
218 input file with the extension ``.pcm``. Otherwise, the BMI will be emitted in
219 the working directory with the name of the input file with the extension
220 ``.pcm``.
221
222 Generating BMIs with ``--precompile`` is referred to as two-phase compilation
223 because it takes two steps to compile a source file to an object file.
224 Generating BMIs with ``-fmodule-output`` is called one-phase compilation. The
225 one-phase compilation model is simpler for build systems to implement while the
226 two-phase compilation has the potential to compile faster due to higher
227 parallelism. As an example, if there are two module units ``A`` and ``B``, and
228 ``B`` depends on ``A``, the one-phase compilation model needs to compile them
229 serially, whereas the two-phase compilation model is able to be compiled as
230 soon as ``A.pcm`` is available, and thus can be compiled simultaneously as the
231 ``A.pcm`` to ``A.o`` compilation step.
232
233 File name requirements
234 ~~~~~~~~~~~~~~~~~~~~~~
235
236 By convention, ``importable module unit`` files should use ``.cppm`` (or
237 ``.ccm``, ``.cxxm``, or ``.c++m``) as a file extension.
238 ``Module implementation unit`` files should use ``.cpp`` (or ``.cc``, ``.cxx``,
239 or ``.c++``) as a file extension.
240
241 A BMI should use ``.pcm`` as a file extension. The file name of the BMI for a
242 ``primary module interface unit`` should be ``module_name.pcm``. The file name
243 of a BMI for a ``module partition unit`` should be
244 ``module_name-partition_name.pcm``.
245
246 Clang may fail to build the module if different extensions are used. For
247 example, if the filename of an ``importable module unit`` ends with ``.cpp``
248 instead of ``.cppm``, then Clang cannot generate a BMI for the
249 ``importable module unit`` with the ``--precompile`` option because the
250 ``--precompile`` option would only run the preprocessor (``-E``). If using a
251 different extension than the conventional one for an ``importable module unit``
252 you can specify ``-x c++-module`` before the file. For example,
253
254 .. code-block:: c++
255
256 // Hello.cpp
257 module;
258 #include <iostream>
259 export module Hello;
260 export void hello() {
261 std::cout << "Hello World!\n";
262 }
263
264 // use.cpp
265 import Hello;
266 int main() {
267 hello();
268 return 0;
269 }
270
271 In this example, the extension used by the ``module interface`` is ``.cpp``
272 instead of ``.cppm``, so it cannot be compiled like the previous example, but
273 it can be compiled with:
274
275 .. code-block:: console
276
277 $ clang++ -std=c++20 -x c++-module Hello.cpp --precompile -o Hello.pcm
278 $ clang++ -std=c++20 use.cpp -fprebuilt-module-path=. Hello.pcm -o Hello.out
279 $ ./Hello.out
280 Hello World!
281
282 Module name requirements
283 ~~~~~~~~~~~~~~~~~~~~~~~~
284
285 ..
286
287 [module.unit]p1:
288
289 All module-names either beginning with an identifier consisting of std followed by zero
290 or more digits or containing a reserved identifier ([lex.name]) are reserved and shall not
291 be specified in a module-declaration; no diagnostic is required. If any identifier in a reserved
292 module-name is a reserved identifier, the module name is reserved for use by C++ implementations;
293 otherwise it is reserved for future standardization.
294
295 Therefore, none of the following names are valid by default:
296
297 .. code-block:: text
298
299 std
300 std1
301 std.foo
302 __test
303 // and so on ...
304
305 Using a reserved module name is strongly discouraged, but
306 ``-Wno-reserved-module-identifier`` can be used to suppress the warning.
307
308 Specifying dependent BMIs
309 ~~~~~~~~~~~~~~~~~~~~~~~~~
310
311 There are 3 ways to specify a dependent BMI:
312
313 1. ``-fprebuilt-module-path=<path/to/directory>``.
314 2. ``-fmodule-file=<path/to/BMI>`` (Deprecated).
315 3. ``-fmodule-file=<module-name>=<path/to/BMI>``.
316
317 The ``-fprebuilt-module-path`` option specifies the path to search for
318 dependent BMIs. Multiple paths may be specified, similar to using ``-I`` to
319 specify a search path for header files. When importing a module ``M``, the
320 compiler looks for ``M.pcm`` in the directories specified by
321 ``-fprebuilt-module-path``. Similarly, when importing a partition module unit
322 ``M:P``, the compiler looks for ``M-P.pcm`` in the directories specified by
323 ``-fprebuilt-module-path``.
324
325 The ``-fmodule-file=<path/to/BMI>`` option causes the compiler to load the
326 specified BMI directly. The ``-fmodule-file=<module-name>=<path/to/BMI>``
327 option causes the compiler to load the specified BMI for the module specified
328 by ``<module-name>`` when necessary. The main difference is that
329 ``-fmodule-file=<path/to/BMI>`` will load the BMI eagerly, whereas
330 ``-fmodule-file=<module-name>=<path/to/BMI>`` will only load the BMI lazily,
331 as will ``-fprebuilt-module-path``. The ``-fmodule-file=<path/to/BMI>`` option
332 for named modules is deprecated and will be removed in a future version of
333 Clang.
334
335 When these options are specified in the same invocation of the compiler, the
336 ``-fmodule-file=<path/to/BMI>`` option takes precedence over
337 ``-fmodule-file=<module-name>=<path/to/BMI>``, which takes precedence over
338 ``-fprebuilt-module-path=<path/to/directory>``.
339
340 Note: all dependant BMIs must be specified explicitly, either directly or
341 indirectly dependent BMIs explicitly. See
342 https://github.com/llvm/llvm-project/issues/62707 for details.
343
344 When compiling a ``module implementation unit``, the BMI of the corresponding
345 ``primary module interface unit`` must be specified because a module
346 implementation unit implicitly imports the primary module interface unit.
347
348 [module.unit]p8
349
350 A module-declaration that contains neither an export-keyword nor a module-partition implicitly
351 imports the primary module interface unit of the module as if by a module-import-declaration.
352
353 The ``-fprebuilt-module-path=<path/to/directory>``, ``-fmodule-file=<path/to/BMI>``,
354 and ``-fmodule-file=<module-name>=<path/to/BMI>`` options may be specified
355 multiple times. For example, the command line to compile ``M.cppm`` in
356 the previous example could be rewritten as:
357
358 .. code-block:: console
359
360 $ clang++ -std=c++20 M.cppm --precompile -fmodule-file=M:interface_part=M-interface_part.pcm -fmodule-file=M:impl_part=M-impl_part.pcm -o M.pcm
361
362 When there are multiple ``-fmodule-file=<module-name>=`` options for the same
363 ``<module-name>``, the last ``-fmodule-file=<module-name>=`` overrides the
364 previous ``-fmodule-file=<module-name>=`` option.
365
366 Remember that module units still have an object counterpart to the BMI
367 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
368
369 While module interfaces resemble traditional header files, they still require
370 compilation. Module units are translation units, and need to be compiled to
371 object files, which then need to be linked together as the following examples
372 show.
373
374 For example, the traditional compilation processes for headers are like:
375
376 .. code-block:: text
377
378 src1.cpp -+> clang++ src1.cpp --> src1.o ---,
379 hdr1.h --' +-> clang++ src1.o src2.o -> executable
380 hdr2.h --, |
381 src2.cpp -+> clang++ src2.cpp --> src2.o ---'
382
383 And the compilation process for module units are like:
384
385 .. code-block:: text
386
387 src1.cpp ----------------------------------------+> clang++ src1.cpp -------> src1.o -,
388 (header unit) hdr1.h -> clang++ hdr1.h ... -> hdr1.pcm --' +-> clang++ src1.o mod1.o src2.o -> executable
389 mod1.cppm -> clang++ mod1.cppm ... -> mod1.pcm --,--> clang++ mod1.pcm ... -> mod1.o -+
390 src2.cpp ----------------------------------------+> clang++ src2.cpp -------> src2.o -'
391
392 As the diagrams show, we need to compile the BMI from module units to object
393 files and then link the object files. (However, this cannot be done for the BMI
394 from header units. See the section on :ref:`header units <header-units>` for
395 more details.
396
397 BMIs cannot be shipped in an archive to create a module library. Instead, the
398 BMIs(``*.pcm``) are compiled into object files(``*.o``) and those object files
399 are added to the archive instead.
400
401 clang-cl
402 ~~~~~~~~
403
404 ``clang-cl`` supports the same options as ``clang++`` for modules as detailed above;
405 there is no need to prefix these options with ``/clang:``. Note that ``cl.exe``
406 `options to emit/consume IFC files <https://devblogs.microsoft.com/cppblog/using-cpp-modules-in-msvc-from-the-command-line-part-1/>` are *not* supported.
407 The resultant precompiled modules are also not compatible for use with ``cl.exe``.
408
409 We recommend that build system authors use the above-mentioned ``clang++`` options with ``clang-cl`` to build modules.
410
411 Consistency Requirements
412 ~~~~~~~~~~~~~~~~~~~~~~~~
413
414 Modules can be viewed as a kind of cache to speed up compilation. Thus, like
415 other caching techniques, it is important to maintain cache consistency which
416 is why Clang does very strict checking for consistency.
417
418 Options consistency
419 ^^^^^^^^^^^^^^^^^^^
420
421 Compiler options related to the language dialect for a module unit and its
422 non-module-unit uses need to be consistent. Consider the following example:
423
424 .. code-block:: c++
425
426 // M.cppm
427 export module M;
428
429 // Use.cpp
430 import M;
431
432 .. code-block:: console
433
434 $ clang++ -std=c++20 M.cppm --precompile -o M.pcm
435 $ clang++ -std=c++23 Use.cpp -fprebuilt-module-path=.
436
437 Clang rejects the example due to the inconsistent language standard modes. Not
438 all compiler options are language dialect options, though. For example:
439
440 .. code-block:: console
441
442 $ clang++ -std=c++20 M.cppm --precompile -o M.pcm
443 # Inconsistent optimization level.
444 $ clang++ -std=c++20 -O3 Use.cpp -fprebuilt-module-path=.
445 # Inconsistent debugging level.
446 $ clang++ -std=c++20 -g Use.cpp -fprebuilt-module-path=.
447
448 Although the optimization and debugging levels are inconsistent, these
449 compilations are accepted because the compiler options do not impact the
450 language dialect.
451
452 Note that the compiler **currently** doesn't reject inconsistent macro
453 definitions (this may change in the future). For example:
454
455 .. code-block:: console
456
457 $ clang++ -std=c++20 M.cppm --precompile -o M.pcm
458 # Inconsistent optimization level.
459 $ clang++ -std=c++20 -O3 -DNDEBUG Use.cpp -fprebuilt-module-path=.
460
461 Currently, Clang accepts the above example, though it may produce surprising
462 results if the debugging code depends on consistent use of ``NDEBUG`` in other
463 translation units.
464
465 Object definition consistency
466 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
467
468 The C++ language requires that declarations of the same entity in different
469 translation units have the same definition, which is known as the One
470 Definition Rule (ODR). Without modules, the compiler cannot perform strong ODR
471 violation checking because it only sees one translation unit at a time. With
472 the use of modules, the compiler can perform checks for ODR violations across
473 translation units.
474
475 However, the current ODR checking mechanisms are not perfect. There are a
476 significant number of false positive ODR violation diagnostics, where the
477 compiler incorrectly diagnoses two identical declarations as having different
478 definitions. Further, true positive ODR violations are not always reported.
479
480 To give a better user experience, improve compilation performance, and for
481 consistency with MSVC, ODR checking of declarations in the global module
482 fragment is disabled by default. These checks can be enabled by specifying
483 ``-Xclang -fno-skip-odr-check-in-gmf`` when compiling. If the check is enabled
484 and you encounter incorrect or missing diagnostics, please report them via the
485 `community issue tracker <https://github.com/llvm/llvm-project/issues/>`_.
486
487 ABI Impacts
488 -----------
489
490 This section describes the new ABI changes brought by modules. Only changes to
491 the Itanium C++ ABI are covered.
492
493 Name Mangling
494 ~~~~~~~~~~~~~
495
496 The declarations in a module unit which are not in the global module fragment
497 have new linkage names.
498
499 For example,
500
501 .. code-block:: c++
502
503 export module M;
504 namespace NS {
505 export int foo();
506 }
507
508 The linkage name of ``NS::foo()`` is ``_ZN2NSW1M3fooEv``. This couldn't be
509 demangled by previous versions of the debugger or demangler. As of LLVM 15.x,
510 ``llvm-cxxfilt`` can be used to demangle this:
511
512 .. code-block:: console
513
514 $ llvm-cxxfilt _ZN2NSW1M3fooEv
515 NS::foo@M()
516
517 The result should be read as ``NS::foo()`` in module ``M``.
518
519 The ABI implies that something cannot be declared in a module unit and defined
520 in a non-module unit (or vice-versa), as this would result in linking errors.
521
522 Despite this, it is possible to implement declarations with a compatible ABI in
523 a module unit by using a language linkage specifier because the declarations in
524 the language linkage specifier are attached to the global module fragment. For
525 example:
526
527 .. code-block:: c++
528
529 export module M;
530 namespace NS {
531 export extern "C++" int foo();
532 }
533
534 Now the linkage name of ``NS::foo()`` will be ``_ZN2NS3fooEv``.
535
536 Module Initializers
537 ~~~~~~~~~~~~~~~~~~~
538
539 All importable module units are required to emit an initializer function to
540 handle the dynamic initialization of non-inline variables in the module unit.
541 The importable module unit has to emit the initializer even if there is no
542 dynamic initialization; otherwise, the importer may call a nonexistent
543 function. The initializer function emits calls to imported modules first
544 followed by calls to all to of the dynamic initializers in the current module
545 unit.
546
547 Translation units that explicitly or implicitly import a named module must call
548 the initializer functions of the imported named module within the sequence of
549 the dynamic initializers in the translation unit. Initializations of entities
550 at namespace scope are appearance-ordered. This (recursively) extends to
551 imported modules at the point of appearance of the import declaration.
552
553 If the imported module is known to be empty, the call to its initializer may be
554 omitted. Additionally, if the imported module is known to have already been
555 imported, the call to its initializer may be omitted.
556
557 Reduced BMI
558 -----------
559
560 To support the two-phase compilation model, Clang puts everything needed to
561 produce an object into the BMI. However, other consumers of the BMI generally
562 don't need that information. This makes the BMI larger and may introduce
563 unnecessary dependencies for the BMI. To mitigate the problem, Clang has a
564 compiler option to reduce the information contained in the BMI. These two
565 formats are known as Full BMI and Reduced BMI, respectively.
566
567 Users can use the ``-fexperimental-modules-reduced-bmi`` option to produce a
568 Reduced BMI.
569
570 For the one-phase compilation model (CMake implements this model), with
571 ``-fexperimental-modules-reduced-bmi``, the generated BMI will be a Reduced
572 BMI automatically. (The output path of the BMI is specified by
573 ``-fmodule-output=`` as usual with the one-phase compilation model).
574
575 It is also possible to produce a Reduced BMI with the two-phase compilation
576 model. When ``-fexperimental-modules-reduced-bmi``, ``--precompile``, and
577 ``-fmodule-output=`` are specified, the generated BMI specified by ``-o`` will
578 be a full BMI and the BMI specified by ``-fmodule-output=`` will be a Reduced
579 BMI. The dependency graph in this case would look like:
580
581 .. code-block:: none
582
583 module-unit.cppm --> module-unit.full.pcm -> module-unit.o
584 |
585 -> module-unit.reduced.pcm -> consumer1.cpp
586 -> consumer2.cpp
587 -> ...
588 -> consumer_n.cpp
589
590 Clang does not emit diagnostics when ``-fexperimental-modules-reduced-bmi`` is
591 used with a non-module unit. This design permits users of the one-phase
592 compilation model to try using reduced BMIs without needing to modify the build
593 system. The two-phase compilation module requires build system support.
594
595 In a Reduced BMI, Clang does not emit unreachable entities from the global
596 module fragment, or definitions of non-inline functions and non-inline
597 variables. This may not be a transparent change.
598
599 Consider the following example:
600
601 .. code-block:: c++
602
603 // foo.h
604 namespace N {
605 struct X {};
606 int d();
607 int e();
608 inline int f(X, int = d()) { return e(); }
609 int g(X);
610 int h(X);
611 }
612
613 // M.cppm
614 module;
615 #include "foo.h"
616 export module M;
617 template<typename T> int use_f() {
618 N::X x; // N::X, N, and :: are decl-reachable from use_f
619 return f(x, 123); // N::f is decl-reachable from use_f,
620 // N::e is indirectly decl-reachable from use_f
621 // because it is decl-reachable from N::f, and
622 // N::d is decl-reachable from use_f
623 // because it is decl-reachable from N::f
624 // even though it is not used in this call
625 }
626 template<typename T> int use_g() {
627 N::X x; // N::X, N, and :: are decl-reachable from use_g
628 return g((T(), x)); // N::g is not decl-reachable from use_g
629 }
630 template<typename T> int use_h() {
631 N::X x; // N::X, N, and :: are decl-reachable from use_h
632 return h((T(), x)); // N::h is not decl-reachable from use_h, but
633 // N::h is decl-reachable from use_h<int>
634 }
635 int k = use_h<int>();
636 // use_h<int> is decl-reachable from k, so
637 // N::h is decl-reachable from k
638
639 // M-impl.cpp
640 module M;
641 int a = use_f<int>(); // OK
642 int b = use_g<int>(); // error: no viable function for call to g;
643 // g is not decl-reachable from purview of
644 // module M's interface, so is discarded
645 int c = use_h<int>(); // OK
646
647 In the above example, the function definition of ``N::g`` is elided from the
648 Reduced BMI of ``M.cppm``. Then the use of ``use_g<int>`` in ``M-impl.cpp``
649 fails to instantiate. For such issues, users can add references to ``N::g`` in
650 the `module purview <https://eel.is/c++draft/module.unit#5>`_ of ``M.cppm`` to
651 ensure it is reachable, e.g. ``using N::g;``.
652
653 Support for Reduced BMIs is still experimental, but it may become the default
654 in the future. The expected roadmap for Reduced BMIs as of Clang 19.x is:
655
656 1. ``-fexperimental-modules-reduced-bmi`` is opt-in for 1~2 releases. The period depends
657 on user feedback and may be extended.
658 2. Announce that Reduced BMIs are no longer experimental and introduce
659 ``-fmodules-reduced-bmi`` as a new option, and recommend use of the new
660 option. This transition is expected to take 1~2 additional releases as well.
661 3. Finally, ``-fmodules-reduced-bmi`` will be the default. When that time
662 comes, the term BMI will refer to the Reduced BMI and the Full BMI will only
663 be meaningful to build systems which elect to support two-phase compilation.
664
665 Experimental Non-Cascading Changes
666 ----------------------------------
667
668 This section is primarily for build system vendors. For end compiler users,
669 if you don't want to read it all, this is helpful to reduce recompilations.
670 We encourage build system vendors and end users try this out and bring feedback.
671
672 Before Clang 19, a change in BMI of any (transitive) dependency would cause the
673 outputs of the BMI to change. Starting with Clang 19, changes to non-direct
674 dependencies should not directly affect the output BMI, unless they affect the
675 results of the compilations. We expect that there are many more opportunities
676 for this optimization than we currently have realized and would appreaciate
677 feedback about missed optimization opportunities. For example,
678
679 .. code-block:: c++
680
681 // m-partA.cppm
682 export module m:partA;
683
684 // m-partB.cppm
685 export module m:partB;
686 export int getB() { return 44; }
687
688 // m.cppm
689 export module m;
690 export import :partA;
691 export import :partB;
692
693 // useBOnly.cppm
694 export module useBOnly;
695 import m;
696 export int B() {
697 return getB();
698 }
699
700 // Use.cc
701 import useBOnly;
702 int get() {
703 return B();
704 }
705
706 To compile the project (for brevity, some commands are omitted.):
707
708 .. code-block:: console
709
710 $ clang++ -std=c++20 m-partA.cppm --precompile -o m-partA.pcm
711 $ clang++ -std=c++20 m-partB.cppm --precompile -o m-partB.pcm
712 $ clang++ -std=c++20 m.cppm --precompile -o m.pcm -fprebuilt-module-path=.
713 $ clang++ -std=c++20 useBOnly.cppm --precompile -o useBOnly.pcm -fprebuilt-module-path=.
714 $ md5sum useBOnly.pcm
715 07656bf4a6908626795729295f9608da useBOnly.pcm
716
717 If the interface of ``m-partA.cppm`` is changed to:
718
719 .. code-block:: c++
720
721 // m-partA.v1.cppm
722 export module m:partA;
723 export int getA() { return 43; }
724
725 and the BMI for ``useBOnly`` is recompiled as in:
726
727 .. code-block:: console
728
729 $ clang++ -std=c++20 m-partA.cppm --precompile -o m-partA.pcm
730 $ clang++ -std=c++20 m-partB.cppm --precompile -o m-partB.pcm
731 $ clang++ -std=c++20 m.cppm --precompile -o m.pcm -fprebuilt-module-path=.
732 $ clang++ -std=c++20 useBOnly.cppm --precompile -o useBOnly.pcm -fprebuilt-module-path=.
733 $ md5sum useBOnly.pcm
734 07656bf4a6908626795729295f9608da useBOnly.pcm
735
736 then the contents of ``useBOnly.pcm`` remain unchanged.
737 Consequently, if the build system only bases recompilation decisions on directly imported modules,
738 it becomes possible to skip the recompilation of ``Use.cc``.
739 It should be fine because the altered interfaces do not affect ``Use.cc`` in any way;
740 the changes do not cascade.
741
742 When ``Clang`` generates a BMI, it records the hash values of all potentially contributory BMIs
743 for the BMI being produced. This ensures that build systems are not required to consider
744 transitively imported modules when deciding whether to recompile.
745
746 What is considered to be a potential contributory BMIs is currently unspecified.
747 However, it is a severe bug for a BMI to remain unchanged following an observable change
748 that affects its consumers.
749
750 Build systems may utilize this optimization by doing an update-if-changed operation to the BMI
751 that is consumed from the BMI that is output by the compiler.
752
753 We encourage build systems to add an experimental mode that
754 reuses the cached BMI when **direct** dependencies did not change,
755 even if **transitive** dependencies did change.
756
757 Given there are potential compiler bugs, we recommend that build systems
758 support this feature as a configurable option so that users
759 can go back to the transitive change mode safely at any time.
760
761 Interactions with Reduced BMI
762 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
763
764 With reduced BMI, non-cascading changes can be more powerful. For example,
765
766 .. code-block:: c++
767
768 // A.cppm
769 export module A;
770 export int a() { return 44; }
771
772 // B.cppm
773 export module B;
774 import A;
775 export int b() { return a(); }
776
777 .. code-block:: console
778
779 $ clang++ -std=c++20 A.cppm -c -fmodule-output=A.pcm -fexperimental-modules-reduced-bmi -o A.o
780 $ clang++ -std=c++20 B.cppm -c -fmodule-output=B.pcm -fexperimental-modules-reduced-bmi -o B.o -fmodule-file=A=A.pcm
781 $ md5sum B.pcm
782 6c2bd452ca32ab418bf35cd141b060b9 B.pcm
783
784 And let's change the implementation for ``A.cppm`` into:
785
786 .. code-block:: c++
787
788 export module A;
789 int a_impl() { return 99; }
790 export int a() { return a_impl(); }
791
792 and recompile the example:
793
794 .. code-block:: console
795
796 $ clang++ -std=c++20 A.cppm -c -fmodule-output=A.pcm -fexperimental-modules-reduced-bmi -o A.o
797 $ clang++ -std=c++20 B.cppm -c -fmodule-output=B.pcm -fexperimental-modules-reduced-bmi -o B.o -fmodule-file=A=A.pcm
798 $ md5sum B.pcm
799 6c2bd452ca32ab418bf35cd141b060b9 B.pcm
800
801 We should find the contents of ``B.pcm`` remains the same. In this case, the build system is
802 allowed to skip recompilations of TUs which solely and directly depend on module ``B``.
803
804 This only happens with a reduced BMI. With reduced BMIs, we won't record the function body
805 of ``int b()`` in the BMI for ``B`` so that the module ``A`` doesn't contribute to the BMI of ``B``
806 and we have less dependencies.
807
808 Performance Tips
809 ----------------
810
811 Reduce duplications
812 ~~~~~~~~~~~~~~~~~~~
813
814 While it is valid to have duplicated declarations in the global module fragments
815 of different module units, it is not free for Clang to deal with the duplicated
816 declarations. A translation unit will compile more slowly if there is a lot of
817 duplicated declarations between the translation unit and modules it imports.
818 For example:
819
820 .. code-block:: c++
821
822 // M-partA.cppm
823 module;
824 #include "big.header.h"
825 export module M:partA;
826 ...
827
828 // M-partB.cppm
829 module;
830 #include "big.header.h"
831 export module M:partB;
832 ...
833
834 // other partitions
835 ...
836
837 // M-partZ.cppm
838 module;
839 #include "big.header.h"
840 export module M:partZ;
841 ...
842
843 // M.cppm
844 export module M;
845 export import :partA;
846 export import :partB;
847 ...
848 export import :partZ;
849
850 // use.cpp
851 import M;
852 ... // use declarations from module M.
853
854 When ``big.header.h`` is big enough and there are a lot of partitions, the
855 compilation of ``use.cpp`` may be significantly slower than the following
856 approach:
857
858 .. code-block:: c++
859
860 module;
861 #include "big.header.h"
862 export module m:big.header.wrapper;
863 export ... // export the needed declarations
864
865 // M-partA.cppm
866 export module M:partA;
867 import :big.header.wrapper;
868 ...
869
870 // M-partB.cppm
871 export module M:partB;
872 import :big.header.wrapper;
873 ...
874
875 // other partitions
876 ...
877
878 // M-partZ.cppm
879 export module M:partZ;
880 import :big.header.wrapper;
881 ...
882
883 // M.cppm
884 export module M;
885 export import :partA;
886 export import :partB;
887 ...
888 export import :partZ;
889
890 // use.cpp
891 import M;
892 ... // use declarations from module M.
893
894 Reducing the duplication from textual includes is what improves compile-time
895 performance.
896
897 Transitioning to modules
898 ------------------------
899
900 It is best for new code and libraries to use modules from the start if
901 possible. However, it may be a breaking change for existing code or libraries
902 to switch to modules. As a result, many existing libraries need to provide
903 both headers and module interfaces for a while to not break existing users.
904
905 This section suggests some suggestions on how to ease the transition process
906 for existing libraries. **Note that this information is only intended as
907 guidance, rather than as requirements to use modules in Clang.** It presumes
908 the project is starting with no module-based dependencies.
909
910 ABI non-breaking styles
911 ~~~~~~~~~~~~~~~~~~~~~~~
912
913 export-using style
914 ^^^^^^^^^^^^^^^^^^
915
916 .. code-block:: c++
917
918 module;
919 #include "header_1.h"
920 #include "header_2.h"
921 ...
922 #include "header_n.h"
923 export module your_library;
924 export namespace your_namespace {
925 using decl_1;
926 using decl_2;
927 ...
928 using decl_n;
929 }
930
931 This example shows how to include all the headers containing declarations which
932 need to be exported, and uses `using` declarations in an `export` block to
933 produce the module interface.
934
935 export extern-C++ style
936 ^^^^^^^^^^^^^^^^^^^^^^^
937
938 .. code-block:: c++
939
940 module;
941 #include "third_party/A/headers.h"
942 #include "third_party/B/headers.h"
943 ...
944 #include "third_party/Z/headers.h"
945 export module your_library;
946 #define IN_MODULE_INTERFACE
947 extern "C++" {
948 #include "header_1.h"
949 #include "header_2.h"
950 ...
951 #include "header_n.h"
952 }
953
954 Headers (from ``header_1.h`` to ``header_n.h``) need to define the macro:
955
956 .. code-block:: c++
957
958 #ifdef IN_MODULE_INTERFACE
959 #define EXPORT export
960 #else
961 #define EXPORT
962 #endif
963
964 and put ``EXPORT`` on the declarations you want to export.
965
966 Also, it is recommended to refactor headers to include third-party headers
967 conditionally:
968
969 .. code-block:: c++
970
971 #ifndef IN_MODULE_INTERFACE
972 #include "third_party/A/headers.h"
973 #endif
974
975 #include "header_x.h"
976
977 ...
978
979 This can be helpful because it gives better diagnostic messages if the module
980 interface unit is not properly updated when modifying code.
981
982 This approach works because the declarations with language linkage are attached
983 to the global module. Thus, the ABI of the modular form of the library does not
984 change.
985
986 While this style is more involved than the export-using style, it makes it
987 easier to further refactor the library to other styles.
988
989 ABI breaking style
990 ~~~~~~~~~~~~~~~~~~
991
992 The term ``ABI breaking`` may sound like a bad approach. However, this style
993 forces consumers of the library use it in a consistent way. e.g., either always
994 include headers for the library or always import modules. The style prevents
995 the ability to mix includes and imports for the library.
996
997 The pattern for ABI breaking style is similar to the export extern-C++ style.
998
999 .. code-block:: c++
1000
1001 module;
1002 #include "third_party/A/headers.h"
1003 #include "third_party/B/headers.h"
1004 ...
1005 #include "third_party/Z/headers.h"
1006 export module your_library;
1007 #define IN_MODULE_INTERFACE
1008 #include "header_1.h"
1009 #include "header_2.h"
1010 ...
1011 #include "header_n.h"
1012
1013 #if the number of .cpp files in your project are small
1014 module :private;
1015 #include "source_1.cpp"
1016 #include "source_2.cpp"
1017 ...
1018 #include "source_n.cpp"
1019 #else // the number of .cpp files in your project are a lot
1020 // Using all the declarations from third-party libraries which are
1021 // used in the .cpp files.
1022 namespace third_party_namespace {
1023 using third_party_decl_used_in_cpp_1;
1024 using third_party_decl_used_in_cpp_2;
1025 ...
1026 using third_party_decl_used_in_cpp_n;
1027 }
1028 #endif
1029
1030 (And add `EXPORT` and conditional include to the headers as suggested in the
1031 export extern-C++ style section.)
1032
1033 The ABI with modules is different and thus we need to compile the source files
1034 into the new ABI. This is done by an additional part of the interface unit:
1035
1036 .. code-block:: c++
1037
1038 #if the number of .cpp files in your project are small
1039 module :private;
1040 #include "source_1.cpp"
1041 #include "source_2.cpp"
1042 ...
1043 #include "source_n.cpp"
1044 #else // the number of .cpp files in your project are a lot
1045 // Using all the declarations from third-party libraries which are
1046 // used in the .cpp files.
1047 namespace third_party_namespace {
1048 using third_party_decl_used_in_cpp_1;
1049 using third_party_decl_used_in_cpp_2;
1050 ...
1051 using third_party_decl_used_in_cpp_n;
1052 }
1053 #endif
1054
1055 If the number of source files is small, everything can be put in the private
1056 module fragment directly (it is recommended to add conditional includes to the
1057 source files as well). However, compile time performance will be bad if there
1058 are a lot of source files to compile.
1059
1060 **Note that the private module fragment can only be in the primary module
1061 interface unit and the primary module interface unit containing the private
1062 module fragment should be the only module unit of the corresponding module.**
1063
1064 In this case, source files (.cpp files) must be converted to module
1065 implementation units:
1066
1067 .. code-block:: c++
1068
1069 #ifndef IN_MODULE_INTERFACE
1070 // List all the includes here.
1071 #include "third_party/A/headers.h"
1072 ...
1073 #include "header.h"
1074 #endif
1075
1076 module your_library;
1077
1078 // Following off should be unchanged.
1079 ...
1080
1081 The module implementation unit will import the primary module implicitly. Do
1082 not include any headers in the module implementation units as it avoids
1083 duplicated declarations between translation units. This is why non-exported
1084 using declarations should be added from third-party libraries in the primary
1085 module interface unit.
1086
1087 If the library is provided as ``libyour_library.so``, a modular library (e.g.,
1088 ``libyour_library_modules.so``) may also need to be provided for ABI
1089 compatibility.
1090
1091 What if there are headers only included by the source files
1092 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1093
1094 The above practice may be problematic if there are headers only included by the
1095 source files. When using a private module fragment, this issue may be solved by
1096 including those headers in the private module fragment. While it is OK to solve
1097 it by including the implementation headers in the module purview when using
1098 implementation module units, it may be suboptimal because the primary module
1099 interface units now contain entities that do not belong to the interface.
1100
1101 This can potentially be improved by introducing a module partition
1102 implementation unit. An internal module partition unit is an importable
1103 module unit which is internal to the module itself.
1104
1105 Providing a header to skip parsing redundant headers
1106 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1107
1108 Many redeclarations shared between translation units causes Clang to have
1109 slower compile-time performance. Further, there are known issues with
1110 `include after import <https://github.com/llvm/llvm-project/issues/61465>`_.
1111 Even when that issue is resolved, users may still get slower compilation speed
1112 and larger BMIs. For these reasons, it is recommended to not include headers
1113 after importing the corresponding module. However, it is not always easy if the
1114 library is included by other dependencies, as in:
1115
1116 .. code-block:: c++
1117
1118 #include "third_party/A.h" // #include "your_library/a_header.h"
1119 import your_library;
1120
1121 or
1122
1123 .. code-block:: c++
1124
1125 import your_library;
1126 #include "third_party/A.h" // #include "your_library/a_header.h"
1127
1128 For such cases, it is best if the library providing both module and header
1129 interfaces also provides a header which skips parsing so that the library can
1130 be imported with the following approach that skips redundant redeclarations:
1131
1132 .. code-block:: c++
1133
1134 import your_library;
1135 #include "your_library_imported.h"
1136 #include "third_party/A.h" // #include "your_library/a_header.h" but got skipped
1137
1138 The implementation of ``your_library_imported.h`` can be a set of controlling
1139 macros or an overall controlling macro if using `#pragma once`. Then headers
1140 can be refactored to:
1141
1142 .. code-block:: c++
1143
1144 #pragma once
1145 #ifndef YOUR_LIBRARY_IMPORTED
1146 ...
1147 #endif
1148
1149 If the modules imported by the library provide such headers, remember to add
1150 them to ``your_library_imported.h`` too.
1151
1152 Importing modules
1153 ~~~~~~~~~~~~~~~~~
1154
1155 When there are dependent libraries providing modules, they should be imported
1156 in your module as well. Many existing libraries will fall into this category
1157 once the ``std`` module is more widely available.
1158
1159 All dependent libraries providing modules
1160 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1161
1162 Of course, most of the complexity disappears if all the dependent libraries
1163 provide modules.
1164
1165 Headers need to be converted to include third-party headers conditionally. Then,
1166 for the export-using style:
1167
1168 .. code-block:: c++
1169
1170 module;
1171 import modules_from_third_party;
1172 #define IN_MODULE_INTERFACE
1173 #include "header_1.h"
1174 #include "header_2.h"
1175 ...
1176 #include "header_n.h"
1177 export module your_library;
1178 export namespace your_namespace {
1179 using decl_1;
1180 using decl_2;
1181 ...
1182 using decl_n;
1183 }
1184
1185 or, for the export extern-C++ style:
1186
1187 .. code-block:: c++
1188
1189 export module your_library;
1190 import modules_from_third_party;
1191 #define IN_MODULE_INTERFACE
1192 extern "C++" {
1193 #include "header_1.h"
1194 #include "header_2.h"
1195 ...
1196 #include "header_n.h"
1197 }
1198
1199 or, for the ABI-breaking style,
1200
1201 .. code-block:: c++
1202
1203 export module your_library;
1204 import modules_from_third_party;
1205 #define IN_MODULE_INTERFACE
1206 #include "header_1.h"
1207 #include "header_2.h"
1208 ...
1209 #include "header_n.h"
1210
1211 #if the number of .cpp files in your project are small
1212 module :private;
1213 #include "source_1.cpp"
1214 #include "source_2.cpp"
1215 ...
1216 #include "source_n.cpp"
1217 #endif
1218
1219 Non-exported ``using`` declarations are unnecessary if using implementation
1220 module units. Instead, third-party modules can be imported directly in
1221 implementation module units.
1222
1223 Partial dependent libraries providing modules
1224 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1225
1226 If the library has to mix the use of ``include`` and ``import`` in its module,
1227 the primary goal is still the removal of duplicated declarations in translation
1228 units as much as possible. If the imported modules provide headers to skip
1229 parsing their headers, those should be included after the import. If the
1230 imported modules don't provide such a header, one can be made manually for
1231 improved compile time performance.
1232
1233 Known Issues
1234 ------------
1235
1236 The following describes issues in the current implementation of modules. Please
1237 see
1238 `the issues list for modules <https://github.com/llvm/llvm-project/labels/clang%3Amodules>`_
1239 for a list of issues or to file a new issue if you don't find an existing one.
1240 When creating a new issue for standard C++ modules, please start the title with
1241 ``[C++20] [Modules]`` (or ``[C++23] [Modules]``, etc) and add the label
1242 ``clang:modules`` if possible.
1243
1244 A high-level overview of support for standards features, including modules, can
1245 be found on the `C++ Feature Status <https://clang.llvm.org/cxx_status.html>`_
1246 page.
1247
1248 Missing VTables for classes attached to modules
1249 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1250
1251 Now the compiler may miss emitting the definition of vtables
1252 for classes attached to modules, if the definition of the class
1253 doesn't contain any key function in that module units
1254 (The key function is the first non-pure virtual function that is
1255 not inline at the point of class definition.)
1256
1257 (Note: technically, the key function is not a thing for modules.
1258 We use the concept here for convinient.)
1259
1260 For example,
1261
1262 .. code-block:: c++
1263
1264 // layer1.cppm
1265 export module foo:layer1;
1266 struct Fruit {
1267 virtual ~Fruit() = default;
1268 virtual void eval() = 0;
1269 };
1270 struct Banana : public Fruit {
1271 Banana() {}
1272 void eval() override;
1273 };
1274
1275 // layer2.cppm
1276 export module foo:layer2;
1277 import :layer1;
1278 export void layer2_fun() {
1279 Banana *b = new Banana();
1280 b->eval();
1281 }
1282 void Banana::eval() {
1283 }
1284
1285 For the above example, we can't find the definition for the vtable of
1286 class ``Banana`` in any object files.
1287
1288 The expected behavior is, for dynamic classes attached to named modules,
1289 the vtable should always be emitted to the module units the class attaches
1290 to.
1291
1292 To workaround the problem, users can add the key function manually in the
1293 corresponding module units. e.g.,
1294
1295 .. code-block:: c++
1296
1297 // layer1.cppm
1298 export module foo:layer1;
1299 struct Fruit {
1300 virtual ~Fruit() = default;
1301 virtual void eval() = 0;
1302 };
1303 struct Banana : public Fruit {
1304 // Hack a key function to hint the compiler to emit the virtual table.
1305 virtual void anchor();
1306
1307 Banana() {}
1308 void eval() override;
1309 };
1310
1311 void Banana::anchor() {}
1312
1313 This is tracked by
1314 `#70585 <https://github.com/llvm/llvm-project/issues/70585>`_.
1315
1316 Including headers after import is not well-supported
1317 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1318
1319 The following example is accepted:
1320
1321 .. code-block:: c++
1322
1323 #include <iostream>
1324 import foo; // assume module 'foo' contain the declarations from `<iostream>`
1325
1326 int main(int argc, char *argv[])
1327 {
1328 std::cout << "Test\n";
1329 return 0;
1330 }
1331
1332 but if the order of ``#include <iostream>`` and ``import foo;`` is reversed,
1333 then the code is currently rejected:
1334
1335 .. code-block:: c++
1336
1337 import foo; // assume module 'foo' contain the declarations from `<iostream>`
1338 #include <iostream>
1339
1340 int main(int argc, char *argv[])
1341 {
1342 std::cout << "Test\n";
1343 return 0;
1344 }
1345
1346 Both of the above examples should be accepted.
1347
1348 This is a limitation of the implementation. In the first example, the compiler
1349 will see and parse ``<iostream>`` first then it will see the ``import``. In
1350 this case, ODR checking and declaration merging will happen in the
1351 deserializer. In the second example, the compiler will see the ``import`` first
1352 and the ``#include`` second which results in ODR checking and declarations
1353 merging happening in the semantic analyzer. This is due to a divergence in the
1354 implementation path. This is tracked by
1355 `#61465 <https://github.com/llvm/llvm-project/issues/61465>`_.
1356
1357 Ignored ``preferred_name`` Attribute
1358 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1359
1360 When Clang writes BMIs, it will ignore the ``preferred_name`` attribute on
1361 declarations which use it. Thus, the preferred name will not be displayed in
1362 the debugger as expected. This is tracked by
1363 `#56490 <https://github.com/llvm/llvm-project/issues/56490>`_.
1364
1365 Don't emit macros about module declaration
1366 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1367
1368 This is covered by `P1857R3 <https://wg21.link/P1857R3>`_. It is mentioned here
1369 because we want users to be aware that we don't yet implement it.
1370
1371 A direct approach to write code that can be compiled by both modules and
1372 non-module builds may look like:
1373
1374 .. code-block:: c++
1375
1376 MODULE
1377 IMPORT header_name
1378 EXPORT_MODULE MODULE_NAME;
1379 IMPORT header_name
1380 EXPORT ...
1381
1382 The intent of this is that this file can be compiled like a module unit or a
1383 non-module unit depending on the definition of some macros. However, this usage
1384 is forbidden by P1857R3 which is not yet implemented in Clang. This means that
1385 is possible to write invalid modules which will no longer be accepted once
1386 P1857R3 is implemented. This is tracked by
1387 `#56917 <https://github.com/llvm/llvm-project/issues/56917>`_.
1388
1389 Until then, it is recommended not to mix macros with module declarations.
1390
1391
1392 In consistent filename suffix requirement for importable module units
1393 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1394
1395 Currently, Clang requires the file name of an ``importable module unit`` to
1396 have ``.cppm`` (or ``.ccm``, ``.cxxm``, ``.c++m``) as the file extension.
1397 However, the behavior is inconsistent with other compilers. This is tracked by
1398 `#57416 <https://github.com/llvm/llvm-project/issues/57416>`_.
1399
1400 Incorrect ODR violation diagnostics
1401 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1402
1403 ODR violations are a common issue when using modules. Clang sometimes produces
1404 false-positive diagnostics or fails to produce true-positive diagnostics of the
1405 One Definition Rule. One often-reported example is:
1406
1407 .. code-block:: c++
1408
1409 // part.cc
1410 module;
1411 typedef long T;
1412 namespace ns {
1413 inline void fun() {
1414 (void)(T)0;
1415 }
1416 }
1417 export module repro:part;
1418
1419 // repro.cc
1420 module;
1421 typedef long T;
1422 namespace ns {
1423 using ::T;
1424 }
1425 namespace ns {
1426 inline void fun() {
1427 (void)(T)0;
1428 }
1429 }
1430 export module repro;
1431 export import :part;
1432
1433 Currently the compiler incorrectly diagnoses the inconsistent definition of
1434 ``fun()`` in two module units. Because both definitions of ``fun()`` have the
1435 same spelling and ``T`` refers to the same type entity, there is no ODR
1436 violation. This is tracked by
1437 `#78850 <https://github.com/llvm/llvm-project/issues/78850>`_.
1438
1439 Using TU-local entity in other units
1440 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1441
1442 Module units are translation units, so the entities which should be local to
1443 the module unit itself should never be used by other units.
1444
1445 The C++ standard defines the concept of ``TU-local`` and ``exposure`` in
1446 `basic.link/p14 <https://eel.is/c++draft/basic.link#14>`_,
1447 `basic.link/p15 <https://eel.is/c++draft/basic.link#15>`_,
1448 `basic.link/p16 <https://eel.is/c++draft/basic.link#16>`_,
1449 `basic.link/p17 <https://eel.is/c++draft/basic.link#17>`_, and
1450 `basic.link/p18 <https://eel.is/c++draft/basic.link#18>`_.
1451
1452 However, Clang doesn't formally support these two concepts. This results in
1453 unclear or confusing diagnostic messages. Further, Clang may import
1454 ``TU-local`` entities to other units without any diagnostics. This is tracked
1455 by `#78173 <https://github.com/llvm/llvm-project/issues/78173>`_.
1456
1457 .. _header-units:
1458
1459 Header Units
1460 ============
1461
1462 How to build projects using header units
1463 ----------------------------------------
1464
1465 .. warning::
1466
1467 The support for header units, including related command line options, is
1468 experimental. There are still many unanswered question about how tools
1469 should interact with header units. The details described here may change in
1470 the future.
1471
1472 Quick Start
1473 ~~~~~~~~~~~
1474
1475 The following example:
1476
1477 .. code-block:: c++
1478
1479 import <iostream>;
1480 int main() {
1481 std::cout << "Hello World.\n";
1482 }
1483
1484 could be compiled with:
1485
1486 .. code-block:: console
1487
1488 $ clang++ -std=c++20 -xc++-system-header --precompile iostream -o iostream.pcm
1489 $ clang++ -std=c++20 -fmodule-file=iostream.pcm main.cpp
1490
1491 How to produce BMIs
1492 ~~~~~~~~~~~~~~~~~~~
1493
1494 Similar to named modules, ``--precompile`` can be used to produce a BMI.
1495 However, that requires specifying that the input file is a header by using
1496 ``-xc++-system-header`` or ``-xc++-user-header``.
1497
1498 The ``-fmodule-header={user,system}`` option can also be used to produce a BMI
1499 for header units which have a file extension like `.h` or `.hh`. The argument to
1500 ``-fmodule-header`` specifies either the user search path or the system search
1501 path. The default value for ``-fmodule-header`` is ``user``. For example:
1502
1503 .. code-block:: c++
1504
1505 // foo.h
1506 #include <iostream>
1507 void Hello() {
1508 std::cout << "Hello World.\n";
1509 }
1510
1511 // use.cpp
1512 import "foo.h";
1513 int main() {
1514 Hello();
1515 }
1516
1517 could be compiled with:
1518
1519 .. code-block:: console
1520
1521 $ clang++ -std=c++20 -fmodule-header foo.h -o foo.pcm
1522 $ clang++ -std=c++20 -fmodule-file=foo.pcm use.cpp
1523
1524 For headers which do not have a file extension, ``-xc++-header`` (or
1525 ``-xc++-system-header``, ``-xc++-user-header``) must be used to specify the
1526 file as a header. For example:
1527
1528 .. code-block:: c++
1529
1530 // use.cpp
1531 import "foo.h";
1532 int main() {
1533 Hello();
1534 }
1535
1536 .. code-block:: console
1537
1538 $ clang++ -std=c++20 -fmodule-header=system -xc++-header iostream -o iostream.pcm
1539 $ clang++ -std=c++20 -fmodule-file=iostream.pcm use.cpp
1540
1541 How to specify dependent BMIs
1542 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1543
1544 ``-fmodule-file`` can be used to specify a dependent BMI (or multiple times for
1545 more than one dependent BMI).
1546
1547 With the existing implementation, ``-fprebuilt-module-path`` cannot be used for
1548 header units (because they are nominally anonymous). For header units, use
1549 ``-fmodule-file`` to include the relevant PCM file for each header unit.
1550
1551 This is expect to be solved in a future version of Clang either by the compiler
1552 finding and specifying ``-fmodule-file`` automatically, or by the use of a
1553 module-mapper that understands how to map the header name to their PCMs.
1554
1555 Compiling a header unit to an object file
1556 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1557
1558 A header unit cannot be compiled to an object file due to the semantics of
1559 header units. For example:
1560
1561 .. code-block:: console
1562
1563 $ clang++ -std=c++20 -xc++-system-header --precompile iostream -o iostream.pcm
1564 # This is not allowed!
1565 $ clang++ iostream.pcm -c -o iostream.o
1566
1567 Include translation
1568 ~~~~~~~~~~~~~~~~~~~
1569
1570 The C++ standard allows vendors to convert ``#include header-name`` to
1571 ``import header-name;`` when possible. Currently, Clang does this translation
1572 for the ``#include`` in the global module fragment. For example, the following
1573 example:
1574
1575 .. code-block:: c++
1576
1577 module;
1578 import <iostream>;
1579 export module M;
1580 export void Hello() {
1581 std::cout << "Hello.\n";
1582 }
1583
1584 is the same as this example:
1585
1586 .. code-block:: c++
1587
1588 module;
1589 #include <iostream>
1590 export module M;
1591 export void Hello() {
1592 std::cout << "Hello.\n";
1593 }
1594
1595 .. code-block:: console
1596
1597 $ clang++ -std=c++20 -xc++-system-header --precompile iostream -o iostream.pcm
1598 $ clang++ -std=c++20 -fmodule-file=iostream.pcm --precompile M.cppm -o M.cpp
1599
1600 In the latter example, Clang can find the BMI for ``<iostream>`` and so it
1601 tries to replace the ``#include <iostream>`` with ``import <iostream>;``
1602 automatically.
1603
1604
1605 Differences between Clang modules and header units
1606 --------------------------------------------------
1607
1608 Header units have similar semantics to Clang modules. The semantics of both are
1609 like headers. Therefore, header units can be mimicked by Clang modules as in
1610 the following example:
1611
1612 .. code-block:: c++
1613
1614 module "iostream" {
1615 export *
1616 header "/path/to/libstdcxx/iostream"
1617 }
1618
1619 .. code-block:: console
1620
1621 $ clang++ -std=c++20 -fimplicit-modules -fmodule-map-file=.modulemap main.cpp
1622
1623 This example is simplified when using libc++:
1624
1625 .. code-block:: console
1626
1627 $ clang++ -std=c++20 main.cpp -fimplicit-modules -fimplicit-module-maps
1628
1629 because libc++ already supplies a
1630 `module map <https://github.com/llvm/llvm-project/blob/main/libcxx/include/module.modulemap.in>`_.
1631
1632 This raises the question: why are header units not implemented through Clang
1633 modules?
1634
1635 This is primarily because Clang modules have more hierarchical semantics when
1636 wrapping multiple headers together as one module, which is not supported by
1637 Standard C++ Header units. We want to avoid the impression that these
1638 additional semantics get interpreted as Standard C++ behavior.
1639
1640 Another reason is that there are proposals to introduce module mappers to the
1641 C++ standard (for example, https://wg21.link/p1184r2). Reusing Clang's
1642 ``modulemap`` may be more difficult if we need to introduce another module
1643 mapper.
1644
1645 Discovering Dependencies
1646 ========================
1647
1648 Without use of modules, all the translation units in a project can be compiled
1649 in parallel. However, the presence of module units requires compiling the
1650 translation units in a topological order.
1651
1652 The ``clang-scan-deps`` tool can extract dependency information and produce a
1653 JSON file conforming to the specification described in
1654 `P1689 <https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p1689r5.html>`_.
1655 Only named modules are supported currently.
1656
1657 A compilation database is needed when using ``clang-scan-deps``. See
1658 `JSON Compilation Database Format Specification <JSONCompilationDatabase.html>`_
1659 for more information about compilation databases. Note that the ``output``
1660 JSON attribute is necessary for ``clang-scan-deps`` to scan using the P1689
1661 format. For example:
1662
1663 .. code-block:: c++
1664
1665 //--- M.cppm
1666 export module M;
1667 export import :interface_part;
1668 import :impl_part;
1669 export int Hello();
1670
1671 //--- interface_part.cppm
1672 export module M:interface_part;
1673 export void World();
1674
1675 //--- Impl.cpp
1676 module;
1677 #include <iostream>
1678 module M;
1679 void Hello() {
1680 std::cout << "Hello ";
1681 }
1682
1683 //--- impl_part.cppm
1684 module;
1685 #include <string>
1686 #include <iostream>
1687 module M:impl_part;
1688 import :interface_part;
1689
1690 std::string W = "World.";
1691 void World() {
1692 std::cout << W << std::endl;
1693 }
1694
1695 //--- User.cpp
1696 import M;
1697 import third_party_module;
1698 int main() {
1699 Hello();
1700 World();
1701 return 0;
1702 }
1703
1704 And here is the compilation database:
1705
1706 .. code-block:: text
1707
1708 [
1709 {
1710 "directory": ".",
1711 "command": "<path-to-compiler-executable>/clang++ -std=c++20 M.cppm -c -o M.o",
1712 "file": "M.cppm",
1713 "output": "M.o"
1714 },
1715 {
1716 "directory": ".",
1717 "command": "<path-to-compiler-executable>/clang++ -std=c++20 Impl.cpp -c -o Impl.o",
1718 "file": "Impl.cpp",
1719 "output": "Impl.o"
1720 },
1721 {
1722 "directory": ".",
1723 "command": "<path-to-compiler-executable>/clang++ -std=c++20 impl_part.cppm -c -o impl_part.o",
1724 "file": "impl_part.cppm",
1725 "output": "impl_part.o"
1726 },
1727 {
1728 "directory": ".",
1729 "command": "<path-to-compiler-executable>/clang++ -std=c++20 interface_part.cppm -c -o interface_part.o",
1730 "file": "interface_part.cppm",
1731 "output": "interface_part.o"
1732 },
1733 {
1734 "directory": ".",
1735 "command": "<path-to-compiler-executable>/clang++ -std=c++20 User.cpp -c -o User.o",
1736 "file": "User.cpp",
1737 "output": "User.o"
1738 }
1739 ]
1740
1741 To get the dependency information in P1689 format, use:
1742
1743 .. code-block:: console
1744
1745 $ clang-scan-deps -format=p1689 -compilation-database P1689.json
1746
1747 to get:
1748
1749 .. code-block:: text
1750
1751 {
1752 "revision": 0,
1753 "rules": [
1754 {
1755 "primary-output": "Impl.o",
1756 "requires": [
1757 {
1758 "logical-name": "M",
1759 "source-path": "M.cppm"
1760 }
1761 ]
1762 },
1763 {
1764 "primary-output": "M.o",
1765 "provides": [
1766 {
1767 "is-interface": true,
1768 "logical-name": "M",
1769 "source-path": "M.cppm"
1770 }
1771 ],
1772 "requires": [
1773 {
1774 "logical-name": "M:interface_part",
1775 "source-path": "interface_part.cppm"
1776 },
1777 {
1778 "logical-name": "M:impl_part",
1779 "source-path": "impl_part.cppm"
1780 }
1781 ]
1782 },
1783 {
1784 "primary-output": "User.o",
1785 "requires": [
1786 {
1787 "logical-name": "M",
1788 "source-path": "M.cppm"
1789 },
1790 {
1791 "logical-name": "third_party_module"
1792 }
1793 ]
1794 },
1795 {
1796 "primary-output": "impl_part.o",
1797 "provides": [
1798 {
1799 "is-interface": false,
1800 "logical-name": "M:impl_part",
1801 "source-path": "impl_part.cppm"
1802 }
1803 ],
1804 "requires": [
1805 {
1806 "logical-name": "M:interface_part",
1807 "source-path": "interface_part.cppm"
1808 }
1809 ]
1810 },
1811 {
1812 "primary-output": "interface_part.o",
1813 "provides": [
1814 {
1815 "is-interface": true,
1816 "logical-name": "M:interface_part",
1817 "source-path": "interface_part.cppm"
1818 }
1819 ]
1820 }
1821 ],
1822 "version": 1
1823 }
1824
1825 See the P1689 paper for the meaning of the fields.
1826
1827 Getting dependency information per file with finer-grained control (such as
1828 scanning generated source files) is possible. For example:
1829
1830 .. code-block:: console
1831
1832 $ clang-scan-deps -format=p1689 -- <path-to-compiler-executable>/clang++ -std=c++20 impl_part.cppm -c -o impl_part.o
1833
1834 will produce:
1835
1836 .. code-block:: text
1837
1838 {
1839 "revision": 0,
1840 "rules": [
1841 {
1842 "primary-output": "impl_part.o",
1843 "provides": [
1844 {
1845 "is-interface": false,
1846 "logical-name": "M:impl_part",
1847 "source-path": "impl_part.cppm"
1848 }
1849 ],
1850 "requires": [
1851 {
1852 "logical-name": "M:interface_part"
1853 }
1854 ]
1855 }
1856 ],
1857 "version": 1
1858 }
1859
1860 Individual command line options can be specified after ``--``.
1861 ``clang-scan-deps`` will extract the necessary information from the specified
1862 options. Note that the path to the compiler executable needs to be specified
1863 explicitly instead of using ``clang++`` directly.
1864
1865 Users may want the scanner to get the transitional dependency information for
1866 headers. Otherwise, the project has to be scanned twice, once for headers and
1867 once for modules. To address this, ``clang-scan-deps`` will recognize the
1868 specified preprocessor options in the given command line and generate the
1869 corresponding dependency information. For example:
1870
1871 .. code-block:: console
1872
1873 $ clang-scan-deps -format=p1689 -- ../bin/clang++ -std=c++20 impl_part.cppm -c -o impl_part.o -MD -MT impl_part.ddi -MF impl_part.dep
1874 $ cat impl_part.dep
1875
1876 will produce:
1877
1878 .. code-block:: text
1879
1880 impl_part.ddi: \
1881 /usr/include/bits/wchar.h /usr/include/bits/types/wint_t.h \
1882 /usr/include/bits/types/mbstate_t.h \
1883 /usr/include/bits/types/__mbstate_t.h /usr/include/bits/types/__FILE.h \
1884 /usr/include/bits/types/FILE.h /usr/include/bits/types/locale_t.h \
1885 /usr/include/bits/types/__locale_t.h \
1886 ...
1887
1888 When ``clang-scan-deps`` detects the ``-MF`` option, it will try to write the
1889 dependency information for headers to the file specified by ``-MF``.
1890
1891 Possible Issues: Failed to find system headers
1892 ----------------------------------------------
1893
1894 If encountering an error like ``fatal error: 'stddef.h' file not found``,
1895 the specified ``<path-to-compiler-executable>/clang++`` probably refers to a
1896 symlink instead a real binary. There are four potential solutions to the
1897 problem:
1898
1899 1. Point the specified compiler executable to the real binary instead of the
1900 symlink.
1901 2. Invoke ``<path-to-compiler-executable>/clang++ -print-resource-dir`` to get
1902 the corresponding resource directory for your compiler and add that
1903 directory to the include search paths manually in the build scripts.
1904 3. For build systems that use a compilation database as the input for
1905 ``clang-scan-deps``, the build system can add the
1906 ``--resource-dir-recipe invoke-compiler`` option when executing
1907 ``clang-scan-deps`` to calculate the resource directory dynamically.
1908 The calculation happens only once for a unique ``<path-to-compiler-executable>/clang++``.
1909 4. For build systems that invoke ``clang-scan-deps`` per file, repeatedly
1910 calculating the resource directory may be inefficient. In such cases, the
1911 build system can cache the resource directory and specify
1912 ``-resource-dir <resource-dir>`` explicitly, as in:
1913
1914 .. code-block:: console
1915
1916 $ clang-scan-deps -format=p1689 -- <path-to-compiler-executable>/clang++ -std=c++20 -resource-dir <resource-dir> mod.cppm -c -o mod.o
1917
1918
1919 Import modules with clang-repl
1920 ==============================
1921
1922 ``clang-repl`` supports importing C++20 named modules. For example:
1923
1924 .. code-block:: c++
1925
1926 // M.cppm
1927 export module M;
1928 export const char* Hello() {
1929 return "Hello Interpreter for Modules!";
1930 }
1931
1932 The named module still needs to be compiled ahead of time.
1933
1934 .. code-block:: console
1935
1936 $ clang++ -std=c++20 M.cppm --precompile -o M.pcm
1937 $ clang++ M.pcm -c -o M.o
1938 $ clang++ -shared M.o -o libM.so
1939
1940 Note that the module unit needs to be compiled as a dynamic library so that
1941 ``clang-repl`` can load the object files of the module units. Then it is
1942 possible to import module ``M`` in clang-repl.
1943
1944 .. code-block:: console
1945
1946 $ clang-repl -Xcc=-std=c++20 -Xcc=-fprebuilt-module-path=.
1947 # We need to load the dynamic library first before importing the modules.
1948 clang-repl> %lib libM.so
1949 clang-repl> import M;
1950 clang-repl> extern "C" int printf(const char *, ...);
1951 clang-repl> printf("%s\n", Hello());
1952 Hello Interpreter for Modules!
1953 clang-repl> %quit
1954
1955 Possible Questions
1956 ==================
1957
1958 How modules speed up compilation
1959 --------------------------------
1960
1961 A classic theory for the reason why modules speed up the compilation is: if
1962 there are ``n`` headers and ``m`` source files and each header is included by
1963 each source file, then the complexity of the compilation is ``O(n*m)``.
1964 However, if there are ``n`` module interfaces and ``m`` source files, the
1965 complexity of the compilation is ``O(n+m)``. Therefore, using modules would be
1966 a significant improvement at scale. More simply, use of modules causes many of
1967 the redundant compilations to no longer be necessary.
1968
1969 While this is accurate at a high level, this depends greatly on the
1970 optimization level, as illustrated below.
1971
1972 First is ``-O0``. The compilation process is described in the following graph.
1973
1974 .. code-block:: none
1975
1976 ├-------------frontend----------┼-------------middle end----------------┼----backend----┤
1977 │ │ │ │
1978 └---parsing----sema----codegen--┴----- transformations ---- codegen ----┴---- codegen --┘
1979
1980 ├---------------------------------------------------------------------------------------┐
1981 | │
1982 | source file │
1983 | │
1984 └---------------------------------------------------------------------------------------┘
1985
1986 ├--------┐
1987 │ │
1988 │imported│
1989 │ │
1990 │ code │
1991 │ │
1992 └--------┘
1993
1994 In this case, the source file (which could be a non-module unit or a module
1995 unit) would get processed by the entire pipeline. However, the imported code
1996 would only get involved in semantic analysis, which, for the most part, is name
1997 lookup, overload resolution, and template instantiation. All of these processes
1998 are fast relative to the whole compilation process. More importantly, the
1999 imported code only needs to be processed once during frontend code generation,
2000 as well as the whole middle end and backend. So we could get a big win for the
2001 compilation time in ``-O0``.
2002
2003 But with optimizations, things are different (the ``code generation`` part for
2004 each end is omitted due to limited space):
2005
2006 .. code-block:: none
2007
2008 ├-------- frontend ---------┼--------------- middle end --------------------┼------ backend ----┤
2009 │ │ │ │
2010 └--- parsing ---- sema -----┴--- optimizations --- IPO ---- optimizations---┴--- optimizations -┘
2011
2012 ├-----------------------------------------------------------------------------------------------┐
2013 │ │
2014 │ source file │
2015 │ │
2016 └-----------------------------------------------------------------------------------------------┘
2017 ├---------------------------------------┐
2018 │ │
2019 │ │
2020 │ imported code │
2021 │ │
2022 │ │
2023 └---------------------------------------┘
2024
2025 It would be very unfortunate if we end up with worse performance when using
2026 modules. The main concern is that when a source file is compiled, the compiler
2027 needs to see the body of imported module units so that it can perform IPO
2028 (InterProcedural Optimization, primarily inlining in practice) to optimize
2029 functions in the current source file with the help of the information provided
2030 by the imported module units. In other words, the imported code would be
2031 processed again and again in importee units by optimizations (including IPO
2032 itself). The optimizations before IPO and IPO itself are the most time-consuming
2033 part in whole compilation process. So from this perspective, it might not be
2034 possible to get the compile time improvements described, but there could be
2035 time savings for optimizations after IPO and the whole backend.
2036
2037 Overall, at ``-O0`` the implementations of functions defined in a module will
2038 not impact module users, but at higher optimization levels the definitions of
2039 such functions are provided to user compilations for the purposes of
2040 optimization (but definitions of these functions are still not included in the
2041 use's object file). This means the build speedup at higher optimization levels
2042 may be lower than expected given ``-O0`` experience, but does provide more
2043 optimization opportunities.
2044
2045 Interoperability with Clang Modules
2046 -----------------------------------
2047
2048 We **wish** to support Clang modules and standard C++ modules at the same time,
2049 but the mixing them together is not well used/tested yet. Please file new
2050 GitHub issues as you find interoperability problems.