1 //===- Module.cpp - Describe a module -------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the Module class, which describes a module in the source
12 //===----------------------------------------------------------------------===//
14 #include "clang/Basic/Module.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
35 using namespace clang
;
37 Module::Module(StringRef Name
, SourceLocation DefinitionLoc
, Module
*Parent
,
38 bool IsFramework
, bool IsExplicit
, unsigned VisibilityID
)
39 : Name(Name
), DefinitionLoc(DefinitionLoc
), Parent(Parent
),
40 VisibilityID(VisibilityID
), IsUnimportable(false),
41 HasIncompatibleModuleFile(false), IsAvailable(true),
42 IsFromModuleFile(false), IsFramework(IsFramework
), IsExplicit(IsExplicit
),
43 IsSystem(false), IsExternC(false), IsInferred(false),
44 InferSubmodules(false), InferExplicitSubmodules(false),
45 InferExportWildcard(false), ConfigMacrosExhaustive(false),
46 NoUndeclaredIncludes(false), ModuleMapIsPrivate(false),
47 NameVisibility(Hidden
) {
49 IsAvailable
= Parent
->isAvailable();
50 IsUnimportable
= Parent
->isUnimportable();
51 IsSystem
= Parent
->IsSystem
;
52 IsExternC
= Parent
->IsExternC
;
53 NoUndeclaredIncludes
= Parent
->NoUndeclaredIncludes
;
54 ModuleMapIsPrivate
= Parent
->ModuleMapIsPrivate
;
56 Parent
->SubModuleIndex
[Name
] = Parent
->SubModules
.size();
57 Parent
->SubModules
.push_back(this);
62 for (auto *Submodule
: SubModules
) {
67 static bool isPlatformEnvironment(const TargetInfo
&Target
, StringRef Feature
) {
68 StringRef Platform
= Target
.getPlatformName();
69 StringRef Env
= Target
.getTriple().getEnvironmentName();
71 // Attempt to match platform and environment.
72 if (Platform
== Feature
|| Target
.getTriple().getOSName() == Feature
||
76 auto CmpPlatformEnv
= [](StringRef LHS
, StringRef RHS
) {
77 auto Pos
= LHS
.find('-');
78 if (Pos
== StringRef::npos
)
80 SmallString
<128> NewLHS
= LHS
.slice(0, Pos
);
81 NewLHS
+= LHS
.slice(Pos
+1, LHS
.size());
85 SmallString
<128> PlatformEnv
= Target
.getTriple().getOSAndEnvironmentName();
86 // Darwin has different but equivalent variants for simulators, example:
87 // 1. x86_64-apple-ios-simulator
88 // 2. x86_64-apple-iossimulator
89 // where both are valid examples of the same platform+environment but in the
90 // variant (2) the simulator is hardcoded as part of the platform name. Both
91 // forms above should match for "iossimulator" requirement.
92 if (Target
.getTriple().isOSDarwin() && PlatformEnv
.endswith("simulator"))
93 return PlatformEnv
== Feature
|| CmpPlatformEnv(PlatformEnv
, Feature
);
95 return PlatformEnv
== Feature
;
98 /// Determine whether a translation unit built using the current
99 /// language options has the given feature.
100 static bool hasFeature(StringRef Feature
, const LangOptions
&LangOpts
,
101 const TargetInfo
&Target
) {
102 bool HasFeature
= llvm::StringSwitch
<bool>(Feature
)
103 .Case("altivec", LangOpts
.AltiVec
)
104 .Case("blocks", LangOpts
.Blocks
)
105 .Case("coroutines", LangOpts
.Coroutines
)
106 .Case("cplusplus", LangOpts
.CPlusPlus
)
107 .Case("cplusplus11", LangOpts
.CPlusPlus11
)
108 .Case("cplusplus14", LangOpts
.CPlusPlus14
)
109 .Case("cplusplus17", LangOpts
.CPlusPlus17
)
110 .Case("cplusplus20", LangOpts
.CPlusPlus20
)
111 .Case("cplusplus23", LangOpts
.CPlusPlus23
)
112 .Case("cplusplus26", LangOpts
.CPlusPlus26
)
113 .Case("c99", LangOpts
.C99
)
114 .Case("c11", LangOpts
.C11
)
115 .Case("c17", LangOpts
.C17
)
116 .Case("freestanding", LangOpts
.Freestanding
)
117 .Case("gnuinlineasm", LangOpts
.GNUAsm
)
118 .Case("objc", LangOpts
.ObjC
)
119 .Case("objc_arc", LangOpts
.ObjCAutoRefCount
)
120 .Case("opencl", LangOpts
.OpenCL
)
121 .Case("tls", Target
.isTLSSupported())
122 .Case("zvector", LangOpts
.ZVector
)
123 .Default(Target
.hasFeature(Feature
) ||
124 isPlatformEnvironment(Target
, Feature
));
126 HasFeature
= llvm::is_contained(LangOpts
.ModuleFeatures
, Feature
);
130 bool Module::isUnimportable(const LangOptions
&LangOpts
,
131 const TargetInfo
&Target
, Requirement
&Req
,
132 Module
*&ShadowingModule
) const {
136 for (const Module
*Current
= this; Current
; Current
= Current
->Parent
) {
137 if (Current
->ShadowingModule
) {
138 ShadowingModule
= Current
->ShadowingModule
;
141 for (unsigned I
= 0, N
= Current
->Requirements
.size(); I
!= N
; ++I
) {
142 if (hasFeature(Current
->Requirements
[I
].first
, LangOpts
, Target
) !=
143 Current
->Requirements
[I
].second
) {
144 Req
= Current
->Requirements
[I
];
150 llvm_unreachable("could not find a reason why module is unimportable");
153 // The -fmodule-name option tells the compiler to textually include headers in
154 // the specified module, meaning Clang won't build the specified module. This
155 // is useful in a number of situations, for instance, when building a library
156 // that vends a module map, one might want to avoid hitting intermediate build
157 // products containing the module map or avoid finding the system installed
158 // modulemap for that library.
159 bool Module::isForBuilding(const LangOptions
&LangOpts
) const {
160 StringRef TopLevelName
= getTopLevelModuleName();
161 StringRef CurrentModule
= LangOpts
.CurrentModule
;
163 // When building framework Foo, we want to make sure that Foo *and*
164 // Foo_Private are textually included and no modules are built for both.
165 if (getTopLevelModule()->IsFramework
&&
166 CurrentModule
== LangOpts
.ModuleName
&&
167 !CurrentModule
.endswith("_Private") && TopLevelName
.endswith("_Private"))
168 TopLevelName
= TopLevelName
.drop_back(8);
170 return TopLevelName
== CurrentModule
;
173 bool Module::isAvailable(const LangOptions
&LangOpts
, const TargetInfo
&Target
,
175 UnresolvedHeaderDirective
&MissingHeader
,
176 Module
*&ShadowingModule
) const {
180 if (isUnimportable(LangOpts
, Target
, Req
, ShadowingModule
))
183 // FIXME: All missing headers are listed on the top-level module. Should we
185 for (const Module
*Current
= this; Current
; Current
= Current
->Parent
) {
186 if (!Current
->MissingHeaders
.empty()) {
187 MissingHeader
= Current
->MissingHeaders
.front();
192 llvm_unreachable("could not find a reason why module is unavailable");
195 bool Module::isSubModuleOf(const Module
*Other
) const {
196 for (auto *Parent
= this; Parent
; Parent
= Parent
->Parent
) {
203 const Module
*Module::getTopLevelModule() const {
204 const Module
*Result
= this;
205 while (Result
->Parent
)
206 Result
= Result
->Parent
;
211 static StringRef
getModuleNameFromComponent(
212 const std::pair
<std::string
, SourceLocation
> &IdComponent
) {
213 return IdComponent
.first
;
216 static StringRef
getModuleNameFromComponent(StringRef R
) { return R
; }
218 template<typename InputIter
>
219 static void printModuleId(raw_ostream
&OS
, InputIter Begin
, InputIter End
,
220 bool AllowStringLiterals
= true) {
221 for (InputIter It
= Begin
; It
!= End
; ++It
) {
225 StringRef Name
= getModuleNameFromComponent(*It
);
226 if (!AllowStringLiterals
|| isValidAsciiIdentifier(Name
))
230 OS
.write_escaped(Name
);
236 template<typename Container
>
237 static void printModuleId(raw_ostream
&OS
, const Container
&C
) {
238 return printModuleId(OS
, C
.begin(), C
.end());
241 std::string
Module::getFullModuleName(bool AllowStringLiterals
) const {
242 SmallVector
<StringRef
, 2> Names
;
244 // Build up the set of module names (from innermost to outermost).
245 for (const Module
*M
= this; M
; M
= M
->Parent
)
246 Names
.push_back(M
->Name
);
250 llvm::raw_string_ostream
Out(Result
);
251 printModuleId(Out
, Names
.rbegin(), Names
.rend(), AllowStringLiterals
);
257 bool Module::fullModuleNameIs(ArrayRef
<StringRef
> nameParts
) const {
258 for (const Module
*M
= this; M
; M
= M
->Parent
) {
259 if (nameParts
.empty() || M
->Name
!= nameParts
.back())
261 nameParts
= nameParts
.drop_back();
263 return nameParts
.empty();
266 OptionalDirectoryEntryRef
Module::getEffectiveUmbrellaDir() const {
267 if (const auto *ME
= Umbrella
.dyn_cast
<const FileEntryRef::MapEntry
*>())
268 return FileEntryRef(*ME
).getDir();
269 if (const auto *ME
= Umbrella
.dyn_cast
<const DirectoryEntryRef::MapEntry
*>())
270 return DirectoryEntryRef(*ME
);
274 void Module::addTopHeader(const FileEntry
*File
) {
276 TopHeaders
.insert(File
);
279 ArrayRef
<const FileEntry
*> Module::getTopHeaders(FileManager
&FileMgr
) {
280 if (!TopHeaderNames
.empty()) {
281 for (std::vector
<std::string
>::iterator
282 I
= TopHeaderNames
.begin(), E
= TopHeaderNames
.end(); I
!= E
; ++I
) {
283 if (auto FE
= FileMgr
.getFile(*I
))
284 TopHeaders
.insert(*FE
);
286 TopHeaderNames
.clear();
289 return llvm::ArrayRef(TopHeaders
.begin(), TopHeaders
.end());
292 bool Module::directlyUses(const Module
*Requested
) {
293 auto *Top
= getTopLevelModule();
295 // A top-level module implicitly uses itself.
296 if (Requested
->isSubModuleOf(Top
))
299 for (auto *Use
: Top
->DirectUses
)
300 if (Requested
->isSubModuleOf(Use
))
303 // Anyone is allowed to use our builtin stddef.h and its accompanying module.
304 if (!Requested
->Parent
&& Requested
->Name
== "_Builtin_stddef_max_align_t")
307 if (NoUndeclaredIncludes
)
308 UndeclaredUses
.insert(Requested
);
313 void Module::addRequirement(StringRef Feature
, bool RequiredState
,
314 const LangOptions
&LangOpts
,
315 const TargetInfo
&Target
) {
316 Requirements
.push_back(Requirement(std::string(Feature
), RequiredState
));
318 // If this feature is currently available, we're done.
319 if (hasFeature(Feature
, LangOpts
, Target
) == RequiredState
)
322 markUnavailable(/*Unimportable*/true);
325 void Module::markUnavailable(bool Unimportable
) {
326 auto needUpdate
= [Unimportable
](Module
*M
) {
327 return M
->IsAvailable
|| (!M
->IsUnimportable
&& Unimportable
);
330 if (!needUpdate(this))
333 SmallVector
<Module
*, 2> Stack
;
334 Stack
.push_back(this);
335 while (!Stack
.empty()) {
336 Module
*Current
= Stack
.back();
339 if (!needUpdate(Current
))
342 Current
->IsAvailable
= false;
343 Current
->IsUnimportable
|= Unimportable
;
344 for (auto *Submodule
: Current
->submodules()) {
345 if (needUpdate(Submodule
))
346 Stack
.push_back(Submodule
);
351 Module
*Module::findSubmodule(StringRef Name
) const {
352 llvm::StringMap
<unsigned>::const_iterator Pos
= SubModuleIndex
.find(Name
);
353 if (Pos
== SubModuleIndex
.end())
356 return SubModules
[Pos
->getValue()];
359 Module
*Module::findOrInferSubmodule(StringRef Name
) {
360 llvm::StringMap
<unsigned>::const_iterator Pos
= SubModuleIndex
.find(Name
);
361 if (Pos
!= SubModuleIndex
.end())
362 return SubModules
[Pos
->getValue()];
363 if (!InferSubmodules
)
365 Module
*Result
= new Module(Name
, SourceLocation(), this, false, InferExplicitSubmodules
, 0);
366 Result
->InferExplicitSubmodules
= InferExplicitSubmodules
;
367 Result
->InferSubmodules
= InferSubmodules
;
368 Result
->InferExportWildcard
= InferExportWildcard
;
369 if (Result
->InferExportWildcard
)
370 Result
->Exports
.push_back(Module::ExportDecl(nullptr, true));
374 void Module::getExportedModules(SmallVectorImpl
<Module
*> &Exported
) const {
375 // All non-explicit submodules are exported.
376 for (std::vector
<Module
*>::const_iterator I
= SubModules
.begin(),
377 E
= SubModules
.end();
380 if (!Mod
->IsExplicit
)
381 Exported
.push_back(Mod
);
384 // Find re-exported modules by filtering the list of imported modules.
385 bool AnyWildcard
= false;
386 bool UnrestrictedWildcard
= false;
387 SmallVector
<Module
*, 4> WildcardRestrictions
;
388 for (unsigned I
= 0, N
= Exports
.size(); I
!= N
; ++I
) {
389 Module
*Mod
= Exports
[I
].getPointer();
390 if (!Exports
[I
].getInt()) {
391 // Export a named module directly; no wildcards involved.
392 Exported
.push_back(Mod
);
397 // Wildcard export: export all of the imported modules that match
398 // the given pattern.
400 if (UnrestrictedWildcard
)
403 if (Module
*Restriction
= Exports
[I
].getPointer())
404 WildcardRestrictions
.push_back(Restriction
);
406 WildcardRestrictions
.clear();
407 UnrestrictedWildcard
= true;
411 // If there were any wildcards, push any imported modules that were
412 // re-exported by the wildcard restriction.
416 for (unsigned I
= 0, N
= Imports
.size(); I
!= N
; ++I
) {
417 Module
*Mod
= Imports
[I
];
418 bool Acceptable
= UnrestrictedWildcard
;
420 // Check whether this module meets one of the restrictions.
421 for (unsigned R
= 0, NR
= WildcardRestrictions
.size(); R
!= NR
; ++R
) {
422 Module
*Restriction
= WildcardRestrictions
[R
];
423 if (Mod
== Restriction
|| Mod
->isSubModuleOf(Restriction
)) {
433 Exported
.push_back(Mod
);
437 void Module::buildVisibleModulesCache() const {
438 assert(VisibleModulesCache
.empty() && "cache does not need building");
440 // This module is visible to itself.
441 VisibleModulesCache
.insert(this);
443 // Every imported module is visible.
444 SmallVector
<Module
*, 16> Stack(Imports
.begin(), Imports
.end());
445 while (!Stack
.empty()) {
446 Module
*CurrModule
= Stack
.pop_back_val();
448 // Every module transitively exported by an imported module is visible.
449 if (VisibleModulesCache
.insert(CurrModule
).second
)
450 CurrModule
->getExportedModules(Stack
);
454 void Module::print(raw_ostream
&OS
, unsigned Indent
, bool Dump
) const {
461 printModuleId(OS
, &Name
, &Name
+ 1);
463 if (IsSystem
|| IsExternC
) {
464 OS
.indent(Indent
+ 2);
473 if (!Requirements
.empty()) {
474 OS
.indent(Indent
+ 2);
476 for (unsigned I
= 0, N
= Requirements
.size(); I
!= N
; ++I
) {
479 if (!Requirements
[I
].second
)
481 OS
<< Requirements
[I
].first
;
486 if (std::optional
<Header
> H
= getUmbrellaHeaderAsWritten()) {
487 OS
.indent(Indent
+ 2);
488 OS
<< "umbrella header \"";
489 OS
.write_escaped(H
->NameAsWritten
);
491 } else if (std::optional
<DirectoryName
> D
= getUmbrellaDirAsWritten()) {
492 OS
.indent(Indent
+ 2);
494 OS
.write_escaped(D
->NameAsWritten
);
498 if (!ConfigMacros
.empty() || ConfigMacrosExhaustive
) {
499 OS
.indent(Indent
+ 2);
500 OS
<< "config_macros ";
501 if (ConfigMacrosExhaustive
)
502 OS
<< "[exhaustive]";
503 for (unsigned I
= 0, N
= ConfigMacros
.size(); I
!= N
; ++I
) {
506 OS
<< ConfigMacros
[I
];
514 } Kinds
[] = {{"", HK_Normal
},
515 {"textual ", HK_Textual
},
516 {"private ", HK_Private
},
517 {"private textual ", HK_PrivateTextual
},
518 {"exclude ", HK_Excluded
}};
520 for (auto &K
: Kinds
) {
521 assert(&K
== &Kinds
[K
.Kind
] && "kinds in wrong order");
522 for (auto &H
: Headers
[K
.Kind
]) {
523 OS
.indent(Indent
+ 2);
524 OS
<< K
.Prefix
<< "header \"";
525 OS
.write_escaped(H
.NameAsWritten
);
526 OS
<< "\" { size " << H
.Entry
.getSize()
527 << " mtime " << H
.Entry
.getModificationTime() << " }\n";
530 for (auto *Unresolved
: {&UnresolvedHeaders
, &MissingHeaders
}) {
531 for (auto &U
: *Unresolved
) {
532 OS
.indent(Indent
+ 2);
533 OS
<< Kinds
[U
.Kind
].Prefix
<< "header \"";
534 OS
.write_escaped(U
.FileName
);
536 if (U
.Size
|| U
.ModTime
) {
539 OS
<< " size " << *U
.Size
;
541 OS
<< " mtime " << *U
.ModTime
;
548 if (!ExportAsModule
.empty()) {
549 OS
.indent(Indent
+ 2);
550 OS
<< "export_as" << ExportAsModule
<< "\n";
553 for (auto *Submodule
: submodules())
554 // Print inferred subframework modules so that we don't need to re-infer
555 // them (requires expensive directory iteration + stat calls) when we build
556 // the module. Regular inferred submodules are OK, as we need to look at all
557 // those header files anyway.
558 if (!Submodule
->IsInferred
|| Submodule
->IsFramework
)
559 Submodule
->print(OS
, Indent
+ 2, Dump
);
561 for (unsigned I
= 0, N
= Exports
.size(); I
!= N
; ++I
) {
562 OS
.indent(Indent
+ 2);
564 if (Module
*Restriction
= Exports
[I
].getPointer()) {
565 OS
<< Restriction
->getFullModuleName(true);
566 if (Exports
[I
].getInt())
574 for (unsigned I
= 0, N
= UnresolvedExports
.size(); I
!= N
; ++I
) {
575 OS
.indent(Indent
+ 2);
577 printModuleId(OS
, UnresolvedExports
[I
].Id
);
578 if (UnresolvedExports
[I
].Wildcard
)
579 OS
<< (UnresolvedExports
[I
].Id
.empty() ? "*" : ".*");
584 for (Module
*M
: Imports
) {
585 OS
.indent(Indent
+ 2);
586 llvm::errs() << "import " << M
->getFullModuleName() << "\n";
590 for (unsigned I
= 0, N
= DirectUses
.size(); I
!= N
; ++I
) {
591 OS
.indent(Indent
+ 2);
593 OS
<< DirectUses
[I
]->getFullModuleName(true);
597 for (unsigned I
= 0, N
= UnresolvedDirectUses
.size(); I
!= N
; ++I
) {
598 OS
.indent(Indent
+ 2);
600 printModuleId(OS
, UnresolvedDirectUses
[I
]);
604 for (unsigned I
= 0, N
= LinkLibraries
.size(); I
!= N
; ++I
) {
605 OS
.indent(Indent
+ 2);
607 if (LinkLibraries
[I
].IsFramework
)
610 OS
.write_escaped(LinkLibraries
[I
].Library
);
614 for (unsigned I
= 0, N
= UnresolvedConflicts
.size(); I
!= N
; ++I
) {
615 OS
.indent(Indent
+ 2);
617 printModuleId(OS
, UnresolvedConflicts
[I
].Id
);
619 OS
.write_escaped(UnresolvedConflicts
[I
].Message
);
623 for (unsigned I
= 0, N
= Conflicts
.size(); I
!= N
; ++I
) {
624 OS
.indent(Indent
+ 2);
626 OS
<< Conflicts
[I
].Other
->getFullModuleName(true);
628 OS
.write_escaped(Conflicts
[I
].Message
);
632 if (InferSubmodules
) {
633 OS
.indent(Indent
+ 2);
634 if (InferExplicitSubmodules
)
636 OS
<< "module * {\n";
637 if (InferExportWildcard
) {
638 OS
.indent(Indent
+ 4);
641 OS
.indent(Indent
+ 2);
649 LLVM_DUMP_METHOD
void Module::dump() const {
650 print(llvm::errs(), 0, true);
653 void VisibleModuleSet::setVisible(Module
*M
, SourceLocation Loc
,
654 VisibleCallback Vis
, ConflictCallback Cb
) {
655 // We can't import a global module fragment so the location can be invalid.
656 assert((M
->isGlobalModule() || Loc
.isValid()) &&
657 "setVisible expects a valid import location");
665 Visiting
*ExportedBy
;
668 std::function
<void(Visiting
)> VisitModule
= [&](Visiting V
) {
669 // Nothing to do for a module that's already visible.
670 unsigned ID
= V
.M
->getVisibilityID();
671 if (ImportLocs
.size() <= ID
)
672 ImportLocs
.resize(ID
+ 1);
673 else if (ImportLocs
[ID
].isValid())
676 ImportLocs
[ID
] = Loc
;
679 // Make any exported modules visible.
680 SmallVector
<Module
*, 16> Exports
;
681 V
.M
->getExportedModules(Exports
);
682 for (Module
*E
: Exports
) {
683 // Don't import non-importable modules.
684 if (!E
->isUnimportable())
685 VisitModule({E
, &V
});
688 for (auto &C
: V
.M
->Conflicts
) {
689 if (isVisible(C
.Other
)) {
690 llvm::SmallVector
<Module
*, 8> Path
;
691 for (Visiting
*I
= &V
; I
; I
= I
->ExportedBy
)
692 Path
.push_back(I
->M
);
693 Cb(Path
, C
.Other
, C
.Message
);
697 VisitModule({M
, nullptr});
700 ASTSourceDescriptor::ASTSourceDescriptor(Module
&M
)
701 : Signature(M
.Signature
), ClangModule(&M
) {
703 Path
= M
.Directory
->getName();
704 if (auto File
= M
.getASTFile())
705 ASTFile
= File
->getName();
708 std::string
ASTSourceDescriptor::getModuleName() const {
710 return ClangModule
->Name
;
712 return std::string(PCHModuleName
);