11 The term ``modules`` has a lot of meanings. For the users of Clang, modules may
12 refer to ``Objective-C Modules``, ``Clang C++ Modules`` (or ``Clang Header Modules``,
13 etc.) or ``Standard C++ Modules``. The implementation of all these kinds of modules in Clang
14 has a lot of shared code, but from the perspective of users, their semantics and
15 command line interfaces are very different. This document focuses on
16 an introduction of how to use standard C++ modules in Clang.
18 There is already a detailed document about `Clang modules <Modules.html>`_, it
19 should be helpful to read `Clang modules <Modules.html>`_ if you want to know
20 more about the general idea of modules. Since standard C++ modules have different semantics
21 (and work flows) from `Clang modules`, this page describes the background and use of
22 Clang with standard C++ modules.
24 Modules exist in two forms in the C++ Language Specification. They can refer to
25 either "Named Modules" or to "Header Units". This document covers both forms.
27 Standard C++ Named modules
28 ==========================
30 This document was intended to be a manual first and foremost, however, we consider it helpful to
31 introduce some language background here for readers who are not familiar with
32 the new language feature. This document is not intended to be a language
33 tutorial; it will only introduce necessary concepts about the
34 structure and building of the project.
36 Background and terminology
37 --------------------------
42 In this document, the term ``Modules``/``modules`` refers to standard C++ modules
43 feature if it is not decorated by ``Clang``.
48 In this document, the term ``Clang Modules``/``Clang modules`` refer to Clang
49 c++ modules extension. These are also known as ``Clang header modules``,
50 ``Clang module map modules`` or ``Clang c++ modules``.
52 Module and module unit
53 ~~~~~~~~~~~~~~~~~~~~~~
55 A module consists of one or more module units. A module unit is a special
56 translation unit. Every module unit must have a module declaration. The syntax
57 of the module declaration is:
61 [export] module module_name[:partition_name];
63 Terms enclosed in ``[]`` are optional. The syntax of ``module_name`` and ``partition_name``
64 in regex form corresponds to ``[a-zA-Z_][a-zA-Z_0-9\.]*``. In particular, a literal dot ``.``
65 in the name has no semantic meaning (e.g. implying a hierarchy).
67 In this document, module units are classified into:
69 * Primary module interface unit.
71 * Module implementation unit.
73 * Module interface partition unit.
75 * Internal module partition unit.
77 A primary module interface unit is a module unit whose module declaration is
78 ``export module module_name;``. The ``module_name`` here denotes the name of the
79 module. A module should have one and only one primary module interface unit.
81 A module implementation unit is a module unit whose module declaration is
82 ``module module_name;``. A module could have multiple module implementation
83 units with the same declaration.
85 A module interface partition unit is a module unit whose module declaration is
86 ``export module module_name:partition_name;``. The ``partition_name`` should be
87 unique within any given module.
89 An internal module partition unit is a module unit whose module declaration
90 is ``module module_name:partition_name;``. The ``partition_name`` should be
91 unique within any given module.
93 In this document, we use the following umbrella terms:
95 * A ``module interface unit`` refers to either a ``primary module interface unit``
96 or a ``module interface partition unit``.
98 * An ``importable module unit`` refers to either a ``module interface unit``
99 or a ``internal module partition unit``.
101 * A ``module partition unit`` refers to either a ``module interface partition unit``
102 or a ``internal module partition unit``.
104 Built Module Interface file
105 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
107 A ``Built Module Interface file`` stands for the precompiled result of an importable module unit.
108 It is also called the acronym ``BMI`` generally.
110 Global module fragment
111 ~~~~~~~~~~~~~~~~~~~~~~
113 In a module unit, the section from ``module;`` to the module declaration is called the global module fragment.
116 How to build projects using modules
117 -----------------------------------
122 Let's see a "hello world" example that uses modules.
130 export void hello() {
131 std::cout << "Hello World!\n";
143 .. code-block:: console
145 $ clang++ -std=c++20 Hello.cppm --precompile -o Hello.pcm
146 $ clang++ -std=c++20 use.cpp -fmodule-file=Hello=Hello.pcm Hello.pcm -o Hello.out
150 In this example, we make and use a simple module ``Hello`` which contains only a
151 primary module interface unit ``Hello.cppm``.
153 Then let's see a little bit more complex "hello world" example which uses the 4 kinds of module units.
159 export import :interface_part;
163 // interface_part.cppm
164 export module M:interface_part;
172 import :interface_part;
174 std::string W = "World.";
176 std::cout << W << std::endl;
184 std::cout << "Hello ";
195 Then we are able to compile the example by the following command:
197 .. code-block:: console
199 # Precompiling the module
200 $ clang++ -std=c++20 interface_part.cppm --precompile -o M-interface_part.pcm
201 $ clang++ -std=c++20 impl_part.cppm --precompile -fprebuilt-module-path=. -o M-impl_part.pcm
202 $ clang++ -std=c++20 M.cppm --precompile -fprebuilt-module-path=. -o M.pcm
203 $ clang++ -std=c++20 Impl.cpp -fprebuilt-module-path=. -c -o Impl.o
206 $ clang++ -std=c++20 User.cpp -fprebuilt-module-path=. -c -o User.o
208 # Compiling the module and linking it together
209 $ clang++ -std=c++20 M-interface_part.pcm -fprebuilt-module-path=. -c -o M-interface_part.o
210 $ clang++ -std=c++20 M-impl_part.pcm -fprebuilt-module-path=. -c -o M-impl_part.o
211 $ clang++ -std=c++20 M.pcm -fprebuilt-module-path=. -c -o M.o
212 $ clang++ User.o M-interface_part.o M-impl_part.o M.o Impl.o -o a.out
214 We explain the options in the following sections.
216 How to enable standard C++ modules
217 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
219 Currently, standard C++ modules are enabled automatically
220 if the language standard is ``-std=c++20`` or newer.
225 We can generate a BMI for an importable module unit by either ``--precompile``
226 or ``-fmodule-output`` flags.
228 The ``--precompile`` option generates the BMI as the output of the compilation and the output path
229 can be specified using the ``-o`` option.
231 The ``-fmodule-output`` option generates the BMI as a by-product of the compilation.
232 If ``-fmodule-output=`` is specified, the BMI will be emitted the specified location. Then if
233 ``-fmodule-output`` and ``-c`` are specified, the BMI will be emitted in the directory of the
234 output file with the name of the input file with the new extension ``.pcm``. Otherwise, the BMI
235 will be emitted in the working directory with the name of the input file with the new extension
238 The style to generate BMIs by ``--precompile`` is called two-phase compilation since it takes
239 2 steps to compile a source file to an object file. The style to generate BMIs by ``-fmodule-output``
240 is called one-phase compilation respectively. The one-phase compilation model is simpler
241 for build systems to implement and the two-phase compilation has the potential to compile faster due
242 to higher parallelism. As an example, if there are two module units A and B, and B depends on A, the
243 one-phase compilation model would need to compile them serially, whereas the two-phase compilation
244 model may be able to compile them simultaneously if the compilation from A.pcm to A.o takes a long
247 File name requirement
248 ~~~~~~~~~~~~~~~~~~~~~
250 The file name of an ``importable module unit`` should end with ``.cppm``
251 (or ``.ccm``, ``.cxxm``, ``.c++m``). The file name of a ``module implementation unit``
252 should end with ``.cpp`` (or ``.cc``, ``.cxx``, ``.c++``).
254 The file name of BMIs should end with ``.pcm``.
255 The file name of the BMI of a ``primary module interface unit`` should be ``module_name.pcm``.
256 The file name of BMIs of ``module partition unit`` should be ``module_name-partition_name.pcm``.
258 If the file names use different extensions, Clang may fail to build the module.
259 For example, if the filename of an ``importable module unit`` ends with ``.cpp`` instead of ``.cppm``,
260 then we can't generate a BMI for the ``importable module unit`` by ``--precompile`` option
261 since ``--precompile`` option now would only run preprocessor, which is equal to `-E` now.
262 If we want the filename of an ``importable module unit`` ends with other suffixes instead of ``.cppm``,
263 we could put ``-x c++-module`` in front of the file. For example,
271 export void hello() {
272 std::cout << "Hello World!\n";
282 Now the filename of the ``module interface`` ends with ``.cpp`` instead of ``.cppm``,
283 we can't compile them by the original command lines. But we are still able to do it by:
285 .. code-block:: console
287 $ clang++ -std=c++20 -x c++-module Hello.cpp --precompile -o Hello.pcm
288 $ clang++ -std=c++20 use.cpp -fprebuilt-module-path=. Hello.pcm -o Hello.out
292 Module name requirement
293 ~~~~~~~~~~~~~~~~~~~~~~~
295 [module.unit]p1 says:
299 All module-names either beginning with an identifier consisting of std followed by zero
300 or more digits or containing a reserved identifier ([lex.name]) are reserved and shall not
301 be specified in a module-declaration; no diagnostic is required. If any identifier in a reserved
302 module-name is a reserved identifier, the module name is reserved for use by C++ implementations;
303 otherwise it is reserved for future standardization.
305 So all of the following name is not valid by default:
315 If you still want to use the reserved module names for any reason, use
316 ``-Wno-reserved-module-identifier`` to suppress the warning.
318 How to specify the dependent BMIs
319 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
321 There are 3 methods to specify the dependent BMIs:
323 * (1) ``-fprebuilt-module-path=<path/to/directory>``.
324 * (2) ``-fmodule-file=<path/to/BMI>`` (Deprecated).
325 * (3) ``-fmodule-file=<module-name>=<path/to/BMI>``.
327 The option ``-fprebuilt-module-path`` tells the compiler the path where to search for dependent BMIs.
328 It may be used multiple times just like ``-I`` for specifying paths for header files. The look up rule here is:
330 * (1) When we import module M. The compiler would look up M.pcm in the directories specified
331 by ``-fprebuilt-module-path``.
332 * (2) When we import partition module unit M:P. The compiler would look up M-P.pcm in the
333 directories specified by ``-fprebuilt-module-path``.
335 The option ``-fmodule-file=<path/to/BMI>`` tells the compiler to load the specified BMI directly.
336 The option ``-fmodule-file=<module-name>=<path/to/BMI>`` tells the compiler to load the specified BMI
337 for the module specified by ``<module-name>`` when necessary. The main difference is that
338 ``-fmodule-file=<path/to/BMI>`` will load the BMI eagerly, whereas
339 ``-fmodule-file=<module-name>=<path/to/BMI>`` will only load the BMI lazily, which is similar
340 with ``-fprebuilt-module-path``. The option ``-fmodule-file=<path/to/BMI>`` for named modules is deprecated
341 and is planning to be removed in future versions.
343 In case all ``-fprebuilt-module-path=<path/to/directory>``, ``-fmodule-file=<path/to/BMI>`` and
344 ``-fmodule-file=<module-name>=<path/to/BMI>`` exist, the ``-fmodule-file=<path/to/BMI>`` option
345 takes highest precedence and ``-fmodule-file=<module-name>=<path/to/BMI>`` will take the second
348 When we compile a ``module implementation unit``, we must specify the BMI of the corresponding
349 ``primary module interface unit``.
350 Since the language specification says a module implementation unit implicitly imports
351 the primary module interface unit.
355 A module-declaration that contains neither an export-keyword nor a module-partition implicitly
356 imports the primary module interface unit of the module as if by a module-import-declaration.
358 All of the 3 options ``-fprebuilt-module-path=<path/to/directory>``, ``-fmodule-file=<path/to/BMI>``
359 and ``-fmodule-file=<module-name>=<path/to/BMI>`` may occur multiple times.
360 For example, the command line to compile ``M.cppm`` in
361 the above example could be rewritten into:
363 .. code-block:: console
365 $ 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
367 When there are multiple ``-fmodule-file=<module-name>=`` options for the same
368 ``<module-name>``, the last ``-fmodule-file=<module-name>=`` will override the previous
369 ``-fmodule-file=<module-name>=`` options.
371 ``-fprebuilt-module-path`` is more convenient and ``-fmodule-file`` is faster since
372 it saves time for file lookup.
374 Remember that module units still have an object counterpart to the BMI
375 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
377 It is easy to forget to compile BMIs at first since we may envision module interfaces like headers.
378 However, this is not true.
379 Module units are translation units. We need to compile them to object files
380 and link the object files like the example shows.
382 For example, the traditional compilation processes for headers are like:
386 src1.cpp -+> clang++ src1.cpp --> src1.o ---,
387 hdr1.h --' +-> clang++ src1.o src2.o -> executable
389 src2.cpp -+> clang++ src2.cpp --> src2.o ---'
391 And the compilation process for module units are like:
395 src1.cpp ----------------------------------------+> clang++ src1.cpp -------> src1.o -,
396 (header unit) hdr1.h -> clang++ hdr1.h ... -> hdr1.pcm --' +-> clang++ src1.o mod1.o src2.o -> executable
397 mod1.cppm -> clang++ mod1.cppm ... -> mod1.pcm --,--> clang++ mod1.pcm ... -> mod1.o -+
398 src2.cpp ----------------------------------------+> clang++ src2.cpp -------> src2.o -'
400 As the diagrams show, we need to compile the BMI from module units to object files and link the object files.
401 (But we can't do this for the BMI from header units. See the later section for the definition of header units)
403 If we want to create a module library, we can't just ship the BMIs in an archive.
404 We must compile these BMIs(``*.pcm``) into object files(``*.o``) and add those object files to the archive instead.
406 Consistency Requirement
407 ~~~~~~~~~~~~~~~~~~~~~~~
409 If we envision modules as a cache to speed up compilation, then - as with other caching techniques -
410 it is important to keep cache consistency.
411 So **currently** Clang will do very strict check for consistency.
416 The language option of module units and their non-module-unit users should be consistent.
417 The following example is not allowed:
427 .. code-block:: console
429 $ clang++ -std=c++20 M.cppm --precompile -o M.pcm
430 $ clang++ -std=c++23 Use.cpp -fprebuilt-module-path=.
432 The compiler would reject the example due to the inconsistent language options.
433 Not all options are language options.
434 For example, the following example is allowed:
436 .. code-block:: console
438 $ clang++ -std=c++20 M.cppm --precompile -o M.pcm
439 # Inconsistent optimization level.
440 $ clang++ -std=c++20 -O3 Use.cpp -fprebuilt-module-path=.
441 # Inconsistent debugging level.
442 $ clang++ -std=c++20 -g Use.cpp -fprebuilt-module-path=.
444 Although the two examples have inconsistent optimization and debugging level, both of them are accepted.
446 Note that **currently** the compiler doesn't consider inconsistent macro definition a problem. For example:
448 .. code-block:: console
450 $ clang++ -std=c++20 M.cppm --precompile -o M.pcm
451 # Inconsistent optimization level.
452 $ clang++ -std=c++20 -O3 -DNDEBUG Use.cpp -fprebuilt-module-path=.
454 Currently Clang would accept the above example. But it may produce surprising results if the
455 debugging code depends on consistent use of ``NDEBUG`` also in other translation units.
460 The declarations in a module unit which are not in the global module fragment have new linkage names.
471 The linkage name of ``NS::foo()`` would be ``_ZN2NSW1M3fooEv``.
472 This couldn't be demangled by previous versions of the debugger or demangler.
473 As of LLVM 15.x, users can utilize ``llvm-cxxfilt`` to demangle this:
475 .. code-block:: console
477 $ llvm-cxxfilt _ZN2NSW1M3fooEv
479 The result would be ``NS::foo@M()``, which reads as ``NS::foo()`` in module ``M``.
481 The ABI implies that we can't declare something in a module unit and define it in a non-module unit (or vice-versa),
482 as this would result in linking errors.
484 If we still want to implement declarations within the compatible ABI in module unit,
485 we can use the language-linkage specifier. Since the declarations in the language-linkage specifier
486 is attached to the global module fragments. For example:
492 export extern "C++" int foo();
495 Now the linkage name of ``NS::foo()`` will be ``_ZN2NS3fooEv``.
503 While it is legal to have duplicated declarations in the global module fragments
504 of different module units, it is not free for clang to deal with the duplicated
505 declarations. In other word, for a translation unit, it will compile slower if the
506 translation unit itself and its importing module units contains a lot duplicated
515 #include "big.header.h"
516 export module M:partA;
521 #include "big.header.h"
522 export module M:partB;
530 #include "big.header.h"
531 export module M:partZ;
536 export import :partA;
537 export import :partB;
539 export import :partZ;
543 ... // use declarations from module M.
545 When ``big.header.h`` is big enough and there are a lot of partitions,
546 the compilation of ``use.cpp`` may be slower than
547 the following style significantly:
552 #include "big.header.h"
553 export module m:big.header.wrapper;
554 export ... // export the needed declarations
557 export module M:partA;
558 import :big.header.wrapper;
562 export module M:partB;
563 import :big.header.wrapper;
570 export module M:partZ;
571 import :big.header.wrapper;
576 export import :partA;
577 export import :partB;
579 export import :partZ;
583 ... // use declarations from module M.
585 The key part of the tip is to reduce the duplications from the text includes.
590 The following describes issues in the current implementation of modules.
591 Please see https://github.com/llvm/llvm-project/labels/clang%3Amodules for more issues
592 or file a new issue if you don't find an existing one.
593 If you're going to create a new issue for standard C++ modules,
594 please start the title with ``[C++20] [Modules]`` (or ``[C++23] [Modules]``, etc)
595 and add the label ``clang:modules`` (if you have permissions for that).
597 For higher level support for proposals, you could visit https://clang.llvm.org/cxx_status.html.
599 Including headers after import is problematic
600 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
602 For example, the following example can be accept:
607 import foo; // assume module 'foo' contain the declarations from `<iostream>`
609 int main(int argc, char *argv[])
611 std::cout << "Test\n";
615 but it will get rejected if we reverse the order of ``#include <iostream>`` and
620 import foo; // assume module 'foo' contain the declarations from `<iostream>`
623 int main(int argc, char *argv[])
625 std::cout << "Test\n";
629 Both of the above examples should be accepted.
631 This is a limitation in the implementation. In the first example,
632 the compiler will see and parse <iostream> first then the compiler will see the import.
633 So the ODR Checking and declarations merging will happen in the deserializer.
634 In the second example, the compiler will see the import first and the include second.
635 As a result, the ODR Checking and declarations merging will happen in the semantic analyzer.
637 So there is divergence in the implementation path. It might be understandable that why
638 the orders matter here in the case.
639 (Note that "understandable" is different from "makes sense").
641 This is tracked in: https://github.com/llvm/llvm-project/issues/61465
643 Ignored PreferredName Attribute
644 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
646 Due to a tricky problem, when Clang writes BMIs, Clang will ignore the ``preferred_name`` attribute, if any.
647 This implies that the ``preferred_name`` wouldn't show in debugger or dumping.
649 This is tracked in: https://github.com/llvm/llvm-project/issues/56490
651 Don't emit macros about module declaration
652 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
654 This is covered by P1857R3. We mention it again here since users may abuse it before we implement it.
656 Someone may want to write code which could be compiled both by modules or non-modules.
657 A direct idea would be use macros like:
663 EXPORT_MODULE MODULE_NAME;
667 So this file could be triggered like a module unit or a non-module unit depending on the definition
669 However, this kind of usage is forbidden by P1857R3 but we haven't implemented P1857R3 yet.
670 This means that is possible to write illegal modules code now, and obviously this will stop working
671 once P1857R3 is implemented.
672 A simple suggestion would be "Don't play macro tricks with module declarations".
674 This is tracked in: https://github.com/llvm/llvm-project/issues/56917
676 In consistent filename suffix requirement for importable module units
677 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
679 Currently, clang requires the file name of an ``importable module unit`` should end with ``.cppm``
680 (or ``.ccm``, ``.cxxm``, ``.c++m``). However, the behavior is inconsistent with other compilers.
682 This is tracked in: https://github.com/llvm/llvm-project/issues/57416
684 clang-cl is not compatible with the standard C++ modules
685 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
687 Now we can't use the `/clang:-fmodule-file` or `/clang:-fprebuilt-module-path` to specify
688 the BMI within ``clang-cl.exe``.
690 This is tracked in: https://github.com/llvm/llvm-project/issues/64118
692 delayed template parsing is not supported/broken with C++ modules
693 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
695 The feature `-fdelayed-template-parsing` can't work well with C++ modules now.
696 Note that this is significant on Windows since the option will be enabled by default
699 This is tracked in: https://github.com/llvm/llvm-project/issues/61068
704 How to build projects using header unit
705 ---------------------------------------
709 The user interfaces of header units is highly experimental. There are still
710 many unanswered question about how tools should interact with header units.
711 The user interfaces described here may change after we have progress on how
712 tools should support for header units.
717 For the following example,
723 std::cout << "Hello World.\n";
726 we could compile it as
728 .. code-block:: console
730 $ clang++ -std=c++20 -xc++-system-header --precompile iostream -o iostream.pcm
731 $ clang++ -std=c++20 -fmodule-file=iostream.pcm main.cpp
736 Similar to named modules, we could use ``--precompile`` to produce the BMI.
737 But we need to specify that the input file is a header by ``-xc++-system-header`` or ``-xc++-user-header``.
739 Also we could use `-fmodule-header={user,system}` option to produce the BMI for header units
740 which has suffix like `.h` or `.hh`.
741 The value of `-fmodule-header` means the user search path or the system search path.
742 The default value for `-fmodule-header` is `user`.
750 std::cout << "Hello World.\n";
759 We could compile it as:
761 .. code-block:: console
763 $ clang++ -std=c++20 -fmodule-header foo.h -o foo.pcm
764 $ clang++ -std=c++20 -fmodule-file=foo.pcm use.cpp
766 For headers which don't have a suffix, we need to pass ``-xc++-header``
767 (or ``-xc++-system-header`` or ``-xc++-user-header``) to mark it as a header.
778 .. code-block:: console
780 $ clang++ -std=c++20 -fmodule-header=system -xc++-header iostream -o iostream.pcm
781 $ clang++ -std=c++20 -fmodule-file=iostream.pcm use.cpp
783 How to specify the dependent BMIs
784 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
786 We could use ``-fmodule-file`` to specify the BMIs, and this option may occur multiple times as well.
788 With the existing implementation ``-fprebuilt-module-path`` cannot be used for header units
789 (since they are nominally anonymous).
790 For header units, use ``-fmodule-file`` to include the relevant PCM file for each header unit.
792 This is expect to be solved in future editions of the compiler either by the tooling finding and specifying
793 the -fmodule-file or by the use of a module-mapper that understands how to map the header name to their PCMs.
795 Don't compile the BMI
796 ~~~~~~~~~~~~~~~~~~~~~
798 Another difference with modules is that we can't compile the BMI from a header unit.
801 .. code-block:: console
803 $ clang++ -std=c++20 -xc++-system-header --precompile iostream -o iostream.pcm
804 # This is not allowed!
805 $ clang++ iostream.pcm -c -o iostream.o
807 It makes sense due to the semantics of header units, which are just like headers.
812 The C++ spec allows the vendors to convert ``#include header-name`` to ``import header-name;`` when possible.
813 Currently, Clang would do this translation for the ``#include`` in the global module fragment.
815 For example, the following two examples are the same:
822 export void Hello() {
823 std::cout << "Hello.\n";
826 with the following one:
833 export void Hello() {
834 std::cout << "Hello.\n";
837 .. code-block:: console
839 $ clang++ -std=c++20 -xc++-system-header --precompile iostream -o iostream.pcm
840 $ clang++ -std=c++20 -fmodule-file=iostream.pcm --precompile M.cppm -o M.cpp
842 In the latter example, the Clang could find the BMI for the ``<iostream>``
843 so it would try to replace the ``#include <iostream>`` to ``import <iostream>;`` automatically.
846 Relationships between Clang modules
847 -----------------------------------
849 Header units have pretty similar semantics with Clang modules.
850 The semantics of both of them are like headers.
852 In fact, we could even "mimic" the sytle of header units by Clang modules:
858 header "/path/to/libstdcxx/iostream"
861 .. code-block:: console
863 $ clang++ -std=c++20 -fimplicit-modules -fmodule-map-file=.modulemap main.cpp
865 It would be simpler if we are using libcxx:
867 .. code-block:: console
869 $ clang++ -std=c++20 main.cpp -fimplicit-modules -fimplicit-module-maps
871 Since there is already one
872 `module map <https://github.com/llvm/llvm-project/blob/main/libcxx/include/module.modulemap.in>`_
873 in the source of libcxx.
875 Then immediately leads to the question: why don't we implement header units through Clang header modules?
877 The main reason for this is that Clang modules have more semantics like hierarchy or
878 wrapping multiple headers together as a big module.
879 However, these things are not part of Standard C++ Header units,
880 and we want to avoid the impression that these additional semantics get interpreted as Standard C++ behavior.
882 Another reason is that there are proposals to introduce module mappers to the C++ standard
883 (for example, https://wg21.link/p1184r2).
884 If we decide to reuse Clang's modulemap, we may get in trouble once we need to introduce another module mapper.
886 So the final answer for why we don't reuse the interface of Clang modules for header units is that
887 there are some differences between header units and Clang modules and that ignoring those
888 differences now would likely become a problem in the future.
890 Discover Dependencies
891 =====================
893 Prior to modules, all the translation units can be compiled parallelly.
894 But it is not true for the module units. The presence of module units requires
895 us to compile the translation units in a (topological) order.
897 The clang-scan-deps scanner implemented
898 `P1689 paper <https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p1689r5.html>`_
899 to describe the order. Only named modules are supported now.
901 We need a compilation database to use clang-scan-deps. See
902 `JSON Compilation Database Format Specification <JSONCompilationDatabase.html>`_
903 for example. Note that the ``output`` entry is necessary for clang-scan-deps
904 to scan P1689 format. Here is an example:
910 export import :interface_part;
914 //--- interface_part.cppm
915 export module M:interface_part;
923 std::cout << "Hello ";
931 import :interface_part;
933 std::string W = "World.";
935 std::cout << W << std::endl;
940 import third_party_module;
947 And here is the compilation database:
954 "command": "<path-to-compiler-executable>/clang++ -std=c++20 M.cppm -c -o M.o",
960 "command": "<path-to-compiler-executable>/clang++ -std=c++20 Impl.cpp -c -o Impl.o",
966 "command": "<path-to-compiler-executable>/clang++ -std=c++20 impl_part.cppm -c -o impl_part.o",
967 "file": "impl_part.cppm",
968 "output": "impl_part.o"
972 "command": "<path-to-compiler-executable>/clang++ -std=c++20 interface_part.cppm -c -o interface_part.o",
973 "file": "interface_part.cppm",
974 "output": "interface_part.o"
978 "command": "<path-to-compiler-executable>/clang++ -std=c++20 User.cpp -c -o User.o",
984 And we can get the dependency information in P1689 format by:
986 .. code-block:: console
988 $ clang-scan-deps -format=p1689 -compilation-database P1689.json
998 "primary-output": "Impl.o",
1001 "logical-name": "M",
1002 "source-path": "M.cppm"
1007 "primary-output": "M.o",
1010 "is-interface": true,
1011 "logical-name": "M",
1012 "source-path": "M.cppm"
1017 "logical-name": "M:interface_part",
1018 "source-path": "interface_part.cppm"
1021 "logical-name": "M:impl_part",
1022 "source-path": "impl_part.cppm"
1027 "primary-output": "User.o",
1030 "logical-name": "M",
1031 "source-path": "M.cppm"
1034 "logical-name": "third_party_module"
1039 "primary-output": "impl_part.o",
1042 "is-interface": false,
1043 "logical-name": "M:impl_part",
1044 "source-path": "impl_part.cppm"
1049 "logical-name": "M:interface_part",
1050 "source-path": "interface_part.cppm"
1055 "primary-output": "interface_part.o",
1058 "is-interface": true,
1059 "logical-name": "M:interface_part",
1060 "source-path": "interface_part.cppm"
1068 See the P1689 paper for the meaning of the fields.
1070 And if the user want a finer-grained control for any reason, e.g., to scan the generated source files,
1071 the user can choose to get the dependency information per file. For example:
1073 .. code-block:: console
1075 $ clang-scan-deps -format=p1689 -- <path-to-compiler-executable>/clang++ -std=c++20 impl_part.cppm -c -o impl_part.o
1079 .. code-block:: text
1085 "primary-output": "impl_part.o",
1088 "is-interface": false,
1089 "logical-name": "M:impl_part",
1090 "source-path": "impl_part.cppm"
1095 "logical-name": "M:interface_part"
1103 In this way, we can pass the single command line options after the ``--``.
1104 Then clang-scan-deps will extract the necessary information from the options.
1105 Note that we need to specify the path to the compiler executable instead of saying
1108 The users may want the scanner to get the transitional dependency information for headers.
1109 Otherwise, the users have to scan twice for the project, once for headers and once for modules.
1110 To address the requirement, clang-scan-deps will recognize the specified preprocessor options
1111 in the given command line and generate the corresponding dependency information. For example,
1113 .. code-block:: console
1115 $ 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
1120 .. code-block:: text
1123 /usr/include/bits/wchar.h /usr/include/bits/types/wint_t.h \
1124 /usr/include/bits/types/mbstate_t.h \
1125 /usr/include/bits/types/__mbstate_t.h /usr/include/bits/types/__FILE.h \
1126 /usr/include/bits/types/FILE.h /usr/include/bits/types/locale_t.h \
1127 /usr/include/bits/types/__locale_t.h \
1130 When clang-scan-deps detects ``-MF`` option, clang-scan-deps will try to write the
1131 dependency information for headers to the file specified by ``-MF``.
1133 Possible Issues: Failed to find system headers
1134 ----------------------------------------------
1136 In case the users encounter errors like ``fatal error: 'stddef.h' file not found``,
1137 probably the specified ``<path-to-compiler-executable>/clang++`` refers to a symlink
1138 instead a real binary. There are 4 potential solutions to the problem:
1140 * (1) End users can resolve the issue by pointing the specified compiler executable to
1141 the real binary instead of the symlink.
1142 * (2) End users can invoke ``<path-to-compiler-executable>/clang++ -print-resource-dir``
1143 to get the corresponding resource directory for your compiler and add that directory
1144 to the include search paths manually in the build scripts.
1145 * (3) Build systems that use a compilation database as the input for clang-scan-deps
1146 scanner, the build system can add the flag ``--resource-dir-recipe invoke-compiler`` to
1147 the clang-scan-deps scanner to calculate the resources directory dynamically.
1148 The calculation happens only once for a unique ``<path-to-compiler-executable>/clang++``.
1149 * (4) For build systems that invokes the clang-scan-deps scanner per file, repeatedly
1150 calculating the resource directory may be inefficient. In such cases, the build
1151 system can cache the resource directory by itself and pass ``-resource-dir <resource-dir>``
1152 explicitly in the command line options:
1154 .. code-block:: console
1156 $ clang-scan-deps -format=p1689 -- <path-to-compiler-executable>/clang++ -std=c++20 -resource-dir <resource-dir> mod.cppm -c -o mod.o
1162 How modules speed up compilation
1163 --------------------------------
1165 A classic theory for the reason why modules speed up the compilation is:
1166 if there are ``n`` headers and ``m`` source files and each header is included by each source file,
1167 then the complexity of the compilation is ``O(n*m)``;
1168 But if there are ``n`` module interfaces and ``m`` source files, the complexity of the compilation is
1169 ``O(n+m)``. So, using modules would be a big win when scaling.
1170 In a simpler word, we could get rid of many redundant compilations by using modules.
1172 Roughly, this theory is correct. But the problem is that it is too rough.
1173 The behavior depends on the optimization level, as we will illustrate below.
1175 First is ``O0``. The compilation process is described in the following graph.
1177 .. code-block:: none
1179 ├-------------frontend----------┼-------------middle end----------------┼----backend----┤
1181 └---parsing----sema----codegen--┴----- transformations ---- codegen ----┴---- codegen --┘
1183 ┌---------------------------------------------------------------------------------------┐
1187 └---------------------------------------------------------------------------------------┘
1197 Here we can see that the source file (could be a non-module unit or a module unit) would get processed by the
1199 But the imported code would only get involved in semantic analysis, which is mainly about name lookup,
1200 overload resolution and template instantiation.
1201 All of these processes are fast relative to the whole compilation process.
1202 More importantly, the imported code only needs to be processed once in frontend code generation,
1203 as well as the whole middle end and backend.
1204 So we could get a big win for the compilation time in O0.
1206 But with optimizations, things are different:
1208 (we omit ``code generation`` part for each end due to the limited space)
1210 .. code-block:: none
1212 ├-------- frontend ---------┼--------------- middle end --------------------┼------ backend ----┤
1214 └--- parsing ---- sema -----┴--- optimizations --- IPO ---- optimizations---┴--- optimizations -┘
1216 ┌-----------------------------------------------------------------------------------------------┐
1220 └-----------------------------------------------------------------------------------------------┘
1221 ┌---------------------------------------┐
1227 └---------------------------------------┘
1229 It would be very unfortunate if we end up with worse performance after using modules.
1230 The main concern is that when we compile a source file, the compiler needs to see the function body
1231 of imported module units so that it can perform IPO (InterProcedural Optimization, primarily inlining
1232 in practice) to optimize functions in current source file with the help of the information provided by
1233 the imported module units.
1234 In other words, the imported code would be processed again and again in importee units
1235 by optimizations (including IPO itself).
1236 The optimizations before IPO and the IPO itself are the most time-consuming part in whole compilation process.
1237 So from this perspective, we might not be able to get the improvements described in the theory.
1238 But we could still save the time for optimizations after IPO and the whole backend.
1240 Overall, at ``O0`` the implementations of functions defined in a module will not impact module users,
1241 but at higher optimization levels the definitions of such functions are provided to user compilations for the
1242 purposes of optimization (but definitions of these functions are still not included in the use's object file)-
1243 this means the build speedup at higher optimization levels may be lower than expected given ``O0`` experience,
1244 but does provide by more optimization opportunities.
1246 Interoperability with Clang Modules
1247 -----------------------------------
1249 We **wish** to support clang modules and standard c++ modules at the same time,
1250 but the mixed using form is not well used/tested yet.
1252 Please file new github issues as you find interoperability problems.