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