9#include "clang/Basic/Diagnostic.h"
10#include "clang/Basic/DiagnosticFrontend.h"
11#include "clang/Basic/IdentifierTable.h"
12#include "clang/Basic/TargetInfo.h"
13#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Frontend/FrontendActions.h"
15#include "clang/Frontend/TextDiagnosticPrinter.h"
16#include "clang/Lex/Preprocessor.h"
17#include "clang/Lex/PreprocessorOptions.h"
18#include "clang/Parse/Parser.h"
19#include "clang/Sema/Lookup.h"
20#include "clang/Serialization/ASTReader.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Support/Path.h"
23#include "llvm/Support/Threading.h"
47class StoringDiagnosticConsumer :
public clang::DiagnosticConsumer {
49 StoringDiagnosticConsumer();
51 void HandleDiagnostic(clang::DiagnosticsEngine::Level DiagLevel,
52 const clang::Diagnostic &info)
override;
54 void ClearDiagnostics();
58 void BeginSourceFile(
const clang::LangOptions &LangOpts,
59 const clang::Preprocessor *PP =
nullptr)
override;
60 void EndSourceFile()
override;
63 bool HandleModuleRemark(
const clang::Diagnostic &info);
64 void SetCurrentModuleProgress(std::string module_name);
66 typedef std::pair<clang::DiagnosticsEngine::Level, std::string>
68 std::vector<IDAndDiagnostic> m_diagnostics;
69 std::unique_ptr<clang::DiagnosticOptions> m_diag_opts;
72 std::unique_ptr<clang::TextDiagnosticPrinter> m_diag_printer;
74 std::unique_ptr<llvm::raw_string_ostream> m_os;
78 std::unique_ptr<Progress> m_current_progress_up;
79 std::vector<std::string> m_module_build_stack;
86 ClangModulesDeclVendorImpl(
87 std::unique_ptr<clang::DiagnosticOptions> diagnostic_options,
88 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine,
89 std::shared_ptr<clang::CompilerInvocation> compiler_invocation,
90 std::unique_ptr<clang::CompilerInstance> compiler_instance,
91 std::unique_ptr<clang::Parser> parser);
93 ~ClangModulesDeclVendorImpl()
override =
default;
95 bool AddModule(
const SourceModule &module, ModuleVector *exported_modules,
96 Stream &error_stream)
override;
98 bool AddModulesForCompileUnit(CompileUnit &cu, ModuleVector &exported_modules,
99 Stream &error_stream)
override;
101 uint32_t FindDecls(ConstString name,
bool append, uint32_t max_matches,
102 std::vector<CompilerDecl> &decls)
override;
105 const ModuleVector &modules,
106 std::function<
bool(llvm::StringRef, llvm::StringRef)> handler)
override;
109 typedef llvm::DenseSet<ModuleID> ExportedModuleSet;
110 void ReportModuleExportsHelper(ExportedModuleSet &exports,
111 clang::Module *module);
113 void ReportModuleExports(ModuleVector &exports, clang::Module *module);
115 clang::ModuleLoadResult DoGetModule(clang::ModuleIdPath path,
118 bool m_enabled =
false;
120 std::unique_ptr<clang::DiagnosticOptions> m_diagnostic_options;
121 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> m_diagnostics_engine;
122 std::shared_ptr<clang::CompilerInvocation> m_compiler_invocation;
123 std::unique_ptr<clang::CompilerInstance> m_compiler_instance;
124 std::unique_ptr<clang::Parser> m_parser;
125 size_t m_source_location_index =
128 typedef std::vector<ConstString> ImportedModule;
129 typedef std::map<ImportedModule, clang::Module *> ImportedModuleMap;
130 typedef llvm::DenseSet<ModuleID> ImportedModuleSet;
131 ImportedModuleMap m_imported_modules;
132 ImportedModuleSet m_user_imported_modules;
135 std::shared_ptr<TypeSystemClang> m_ast_context;
139StoringDiagnosticConsumer::StoringDiagnosticConsumer() {
140 m_diag_opts = std::make_unique<clang::DiagnosticOptions>();
141 m_os = std::make_unique<llvm::raw_string_ostream>(m_output);
143 std::make_unique<clang::TextDiagnosticPrinter>(*m_os, *m_diag_opts);
146void StoringDiagnosticConsumer::HandleDiagnostic(
147 clang::DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic &info) {
148 if (HandleModuleRemark(info))
153 m_diag_printer->HandleDiagnostic(DiagLevel, info);
156 m_diagnostics.push_back(IDAndDiagnostic(DiagLevel, m_output));
159void StoringDiagnosticConsumer::ClearDiagnostics() { m_diagnostics.clear(); }
161void StoringDiagnosticConsumer::DumpDiagnostics(Stream &error_stream) {
162 for (IDAndDiagnostic &diag : m_diagnostics) {
163 switch (diag.first) {
168 case clang::DiagnosticsEngine::Level::Ignored:
174void StoringDiagnosticConsumer::BeginSourceFile(
175 const clang::LangOptions &LangOpts,
const clang::Preprocessor *PP) {
176 m_diag_printer->BeginSourceFile(LangOpts, PP);
179void StoringDiagnosticConsumer::EndSourceFile() {
180 m_current_progress_up =
nullptr;
181 m_diag_printer->EndSourceFile();
184bool StoringDiagnosticConsumer::HandleModuleRemark(
185 const clang::Diagnostic &info) {
186 Log *log =
GetLog(LLDBLog::Types | LLDBLog::Expressions);
187 switch (info.getID()) {
188 case clang::diag::remark_module_build: {
189 const auto &module_name = info.getArgStdStr(0);
190 SetCurrentModuleProgress(module_name);
191 m_module_build_stack.push_back(module_name);
193 const auto &module_path = info.getArgStdStr(1);
194 LLDB_LOG(log,
"Building Clang module {0} as {1}", module_name, module_path);
197 case clang::diag::remark_module_build_done: {
199 m_module_build_stack.pop_back();
200 if (m_module_build_stack.empty()) {
201 m_current_progress_up =
nullptr;
206 const auto &resumed_module_name = m_module_build_stack.back();
207 SetCurrentModuleProgress(resumed_module_name);
210 const auto &module_name = info.getArgStdStr(0);
211 LLDB_LOG(log,
"Finished building Clang module {0}", module_name);
219void StoringDiagnosticConsumer::SetCurrentModuleProgress(
220 std::string module_name) {
221 if (!m_current_progress_up)
222 m_current_progress_up =
223 std::make_unique<Progress>(
"Building Clang modules");
225 m_current_progress_up->Increment(1, std::move(module_name));
233ClangModulesDeclVendorImpl::ClangModulesDeclVendorImpl(
234 std::unique_ptr<clang::DiagnosticOptions> diagnostic_options,
235 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine,
236 std::shared_ptr<clang::CompilerInvocation> compiler_invocation,
237 std::unique_ptr<clang::CompilerInstance> compiler_instance,
238 std::unique_ptr<clang::Parser> parser)
239 : m_diagnostic_options(std::move(diagnostic_options)),
240 m_diagnostics_engine(std::move(diagnostics_engine)),
241 m_compiler_invocation(std::move(compiler_invocation)),
242 m_compiler_instance(std::move(compiler_instance)),
243 m_parser(std::move(parser)) {
247 std::make_shared<TypeSystemClang>(
"ClangModulesDeclVendor ASTContext",
248 m_compiler_instance->getASTContext());
251void ClangModulesDeclVendorImpl::ReportModuleExportsHelper(
252 ExportedModuleSet &exports, clang::Module *module) {
258 llvm::SmallVector<clang::Module *, 2> sub_exports;
260 module->getExportedModules(sub_exports);
262 for (clang::Module *module : sub_exports)
263 ReportModuleExportsHelper(exports, module);
266void ClangModulesDeclVendorImpl::ReportModuleExports(
268 ExportedModuleSet exports_set;
270 ReportModuleExportsHelper(exports_set, module);
272 for (ModuleID module : exports_set)
273 exports.push_back(module);
276bool ClangModulesDeclVendorImpl::AddModule(
const SourceModule &module,
277 ModuleVector *exported_modules,
281 if (m_compiler_instance->hadModuleLoaderFatalFailure()) {
282 error_stream.
PutCString(
"error: Couldn't load a module because the module "
283 "loader is in a fatal state.\n");
289 std::vector<ConstString> imported_module;
292 imported_module.push_back(path_component);
295 ImportedModuleMap::iterator mi = m_imported_modules.find(imported_module);
297 if (mi != m_imported_modules.end()) {
298 if (exported_modules)
299 ReportModuleExports(*exported_modules, mi->second);
304 clang::HeaderSearch &HS =
305 m_compiler_instance->getPreprocessor().getHeaderSearchInfo();
313 bool is_system_module = (std::distance(path_begin, path_end) >=
314 std::distance(sysroot_begin, sysroot_end)) &&
315 std::equal(sysroot_begin, sysroot_end, path_begin);
317 if (!is_system_module) {
319 error_stream.
Printf(
"error: No module map file in %s\n",
324 bool is_system =
true;
325 bool is_framework =
false;
326 auto dir = HS.getFileMgr().getOptionalDirectoryRef(
330 auto file = HS.lookupModuleMapFile(*dir, is_framework);
333 if (HS.parseAndLoadModuleMapFile(*file, is_system))
337 if (!HS.lookupModule(module.
path.front().GetStringRef())) {
338 error_stream.
Printf(
"error: Header search couldn't locate module '%s'\n",
339 module.
path.front().AsCString());
343 llvm::SmallVector<clang::IdentifierLoc, 4> clang_path;
346 clang::SourceManager &source_manager =
347 m_compiler_instance->getASTContext().getSourceManager();
350 clang_path.emplace_back(
351 source_manager.getLocForStartOfFile(source_manager.getMainFileID())
352 .getLocWithOffset(m_source_location_index++),
353 &m_compiler_instance->getASTContext().Idents.get(
358 StoringDiagnosticConsumer *diagnostic_consumer =
359 static_cast<StoringDiagnosticConsumer *
>(
360 m_compiler_instance->getDiagnostics().getClient());
362 diagnostic_consumer->ClearDiagnostics();
364 clang::Module *top_level_module = DoGetModule(clang_path.front(),
false);
366 if (!top_level_module) {
367 diagnostic_consumer->DumpDiagnostics(error_stream);
368 error_stream.
Printf(
"error: Couldn't load top-level module %s\n",
369 module.
path.front().AsCString());
373 clang::Module *submodule = top_level_module;
375 for (
auto &component : llvm::ArrayRef<ConstString>(module.
path).drop_front()) {
376 submodule = submodule->findSubmodule(component.GetStringRef());
378 diagnostic_consumer->DumpDiagnostics(error_stream);
379 error_stream.
Printf(
"error: Couldn't load submodule %s\n",
380 component.GetCString());
388 m_compiler_instance->makeModuleVisible(
389 submodule, clang::Module::NameVisibilityKind::AllVisible,
392 clang::Module *requested_module = DoGetModule(clang_path,
true);
394 if (requested_module !=
nullptr) {
395 if (exported_modules)
396 ReportModuleExports(*exported_modules, requested_module);
398 m_imported_modules[imported_module] = requested_module;
427bool ClangModulesDeclVendorImpl::AddModulesForCompileUnit(
430 if (LanguageSupportsClangModules(cu.
GetLanguage())) {
432 if (!AddModule(imported_module, &exported_modules, error_stream))
441ClangModulesDeclVendorImpl::FindDecls(
ConstString name,
bool append,
442 uint32_t max_matches,
443 std::vector<CompilerDecl> &decls) {
450 clang::IdentifierInfo &ident =
451 m_compiler_instance->getASTContext().Idents.get(name.
GetStringRef());
453 clang::LookupResult lookup_result(
454 m_compiler_instance->getSema(), clang::DeclarationName(&ident),
455 clang::SourceLocation(), clang::Sema::LookupOrdinaryName);
457 m_compiler_instance->getSema().LookupName(
459 m_compiler_instance->getSema().getScopeForContext(
460 m_compiler_instance->getASTContext().getTranslationUnitDecl()));
462 uint32_t num_matches = 0;
464 for (clang::NamedDecl *named_decl : lookup_result) {
465 if (num_matches >= max_matches)
468 decls.push_back(m_ast_context->GetCompilerDecl(named_decl));
475void ClangModulesDeclVendorImpl::ForEachMacro(
477 std::function<
bool(llvm::StringRef, llvm::StringRef)> handler) {
481 typedef std::map<ModuleID, ssize_t> ModulePriorityMap;
482 ModulePriorityMap module_priorities;
484 ssize_t priority = 0;
486 for (ModuleID module : modules)
487 module_priorities[module] = priority++;
489 if (m_compiler_instance->getPreprocessor().getExternalSource()) {
490 m_compiler_instance->getPreprocessor()
492 ->ReadDefinedMacros();
495 for (clang::Preprocessor::macro_iterator
496 mi = m_compiler_instance->getPreprocessor().macro_begin(),
497 me = m_compiler_instance->getPreprocessor().macro_end();
499 const clang::IdentifierInfo *ii =
nullptr;
502 if (clang::IdentifierInfoLookup *lookup =
503 m_compiler_instance->getPreprocessor()
504 .getIdentifierTable()
505 .getExternalIdentifierLookup()) {
506 lookup->get(mi->first->getName());
512 ssize_t found_priority = -1;
513 clang::MacroInfo *macro_info =
nullptr;
515 for (clang::ModuleMacro *module_macro :
516 m_compiler_instance->getPreprocessor().getLeafModuleMacros(ii)) {
517 clang::Module *module = module_macro->getOwningModule();
520 ModulePriorityMap::iterator pi =
521 module_priorities.find(
reinterpret_cast<ModuleID
>(module));
523 if (pi != module_priorities.end() && pi->second > found_priority) {
524 macro_info = module_macro->getMacroInfo();
525 found_priority = pi->second;
529 clang::Module *top_level_module =
module->getTopLevelModule();
531 if (top_level_module != module) {
532 ModulePriorityMap::iterator pi = module_priorities.find(
533 reinterpret_cast<ModuleID
>(top_level_module));
535 if ((pi != module_priorities.end()) && pi->second > found_priority) {
536 macro_info = module_macro->getMacroInfo();
537 found_priority = pi->second;
543 std::string macro_expansion =
"#define ";
544 llvm::StringRef macro_identifier = mi->first->getName();
545 macro_expansion.append(macro_identifier.str());
548 if (macro_info->isFunctionLike()) {
549 macro_expansion.append(
"(");
551 bool first_arg =
true;
553 for (
auto pi = macro_info->param_begin(),
554 pe = macro_info->param_end();
557 macro_expansion.append(
", ");
561 macro_expansion.append((*pi)->getName().str());
564 if (macro_info->isC99Varargs()) {
566 macro_expansion.append(
"...");
568 macro_expansion.append(
", ...");
569 }
else if (macro_info->isGNUVarargs())
570 macro_expansion.append(
"...");
572 macro_expansion.append(
")");
575 macro_expansion.append(
" ");
577 bool first_token =
true;
579 for (clang::MacroInfo::const_tokens_iterator
580 ti = macro_info->tokens_begin(),
581 te = macro_info->tokens_end();
584 macro_expansion.append(
" ");
588 if (ti->isLiteral()) {
589 if (
const char *literal_data = ti->getLiteralData()) {
590 std::string token_str(literal_data, ti->getLength());
591 macro_expansion.append(token_str);
593 bool invalid =
false;
594 const char *literal_source =
595 m_compiler_instance->getSourceManager().getCharacterData(
596 ti->getLocation(), &invalid);
600 macro_expansion.append(
"<unknown literal value>");
602 macro_expansion.append(
603 std::string(literal_source, ti->getLength()));
606 }
else if (
const char *punctuator_spelling =
607 clang::tok::getPunctuatorSpelling(ti->getKind())) {
608 macro_expansion.append(punctuator_spelling);
609 }
else if (
const char *keyword_spelling =
610 clang::tok::getKeywordSpelling(ti->getKind())) {
611 macro_expansion.append(keyword_spelling);
613 switch (ti->getKind()) {
614 case clang::tok::TokenKind::identifier:
615 macro_expansion.append(ti->getIdentifierInfo()->getName().str());
617 case clang::tok::TokenKind::raw_identifier:
618 macro_expansion.append(ti->getRawIdentifier().str());
621 macro_expansion.append(ti->getName());
627 if (handler(macro_identifier, macro_expansion)) {
635clang::ModuleLoadResult
636ClangModulesDeclVendorImpl::DoGetModule(clang::ModuleIdPath path,
638 clang::Module::NameVisibilityKind visibility =
639 make_visible ? clang::Module::AllVisible : clang::Module::Hidden;
641 const bool is_inclusion_directive =
false;
643 return m_compiler_instance->loadModule(path.front().getLoc(), path,
644 visibility, is_inclusion_directive);
661 std::vector<std::string> compiler_invocation_arguments = {
664 "-fimplicit-module-maps",
670 "-fmodules-validate-system-headers",
671 "-Werror=non-modular-include-in-framework-module",
672 "-Xclang=-fincremental-extensions",
675 target.
GetPlatform()->AddClangModuleCompilationOptions(
676 &target, compiler_invocation_arguments);
683 llvm::SmallString<128> path;
685 props.GetClangModulesCachePath().GetPath(path);
686 std::string module_cache_argument(
"-fmodules-cache-path=");
687 module_cache_argument.append(std::string(path.str()));
688 compiler_invocation_arguments.push_back(module_cache_argument);
693 for (
size_t spi = 0, spe = module_search_paths.
GetSize(); spi < spe; ++spi) {
696 std::string search_path_argument =
"-I";
697 search_path_argument.append(search_path.
GetPath());
699 compiler_invocation_arguments.push_back(search_path_argument);
706 compiler_invocation_arguments.push_back(
"-resource-dir");
707 compiler_invocation_arguments.push_back(clang_resource_dir.
GetPath());
711 std::vector<const char *> compiler_invocation_argument_cstrs;
712 compiler_invocation_argument_cstrs.reserve(
713 compiler_invocation_arguments.size());
714 for (
const std::string &arg : compiler_invocation_arguments)
715 compiler_invocation_argument_cstrs.push_back(arg.c_str());
717 auto diag_options_up =
718 clang::CreateAndPopulateDiagOpts(compiler_invocation_argument_cstrs);
719 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine =
720 clang::CompilerInstance::createDiagnostics(
722 new StoringDiagnosticConsumer);
725 LLDB_LOG(log,
"ClangModulesDeclVendor's compiler flags {0:$[ ]}",
726 llvm::make_range(compiler_invocation_arguments.begin(),
727 compiler_invocation_arguments.end()));
729 clang::CreateInvocationOptions CIOpts;
730 CIOpts.Diags = diagnostics_engine;
731 std::shared_ptr<clang::CompilerInvocation> invocation =
732 clang::createInvocation(compiler_invocation_argument_cstrs,
738 std::unique_ptr<llvm::MemoryBuffer> source_buffer =
739 llvm::MemoryBuffer::getMemBuffer(
740 "extern int __lldb __attribute__((unavailable));",
744 source_buffer.release());
746 auto instance = std::make_unique<clang::CompilerInstance>(invocation);
750 instance->createFileManager();
751 instance->setDiagnostics(diagnostics_engine);
753 std::unique_ptr<clang::FrontendAction> action(
new clang::SyntaxOnlyAction);
755 instance->setTarget(clang::TargetInfo::CreateTargetInfo(
756 *diagnostics_engine, instance->getInvocation().getTargetOpts()));
758 if (!instance->hasTarget())
761 instance->getTarget().adjust(*diagnostics_engine, instance->getLangOpts(),
764 if (!action->BeginSourceFile(*instance,
765 instance->getFrontendOpts().Inputs[0]))
768 instance->createASTReader();
770 instance->createSema(action->getTranslationUnitKind(),
nullptr);
772 const bool skipFunctionBodies =
false;
773 std::unique_ptr<clang::Parser> parser(
new clang::Parser(
774 instance->getPreprocessor(), instance->getSema(), skipFunctionBodies));
776 instance->getPreprocessor().EnterMainSourceFile();
777 parser->Initialize();
779 clang::Parser::DeclGroupPtrTy parsed;
780 auto ImportState = clang::Sema::ModuleImportState::NotACXX20Module;
781 while (!parser->ParseTopLevelDecl(parsed, ImportState))
784 return new ClangModulesDeclVendorImpl(
785 std::move(diag_options_up), std::move(diagnostics_engine),
786 std::move(invocation), std::move(instance), std::move(parser));
static const char * ModuleImportBufferName
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
static void DumpDiagnostics(void *cookie)
An architecture specification class.
llvm::Triple & GetTriple()
Architecture triple accessor.
ClangDeclVendor(DeclVendorKind kind)
static ClangModulesDeclVendor * Create(Target &target)
std::vector< ModuleID > ModuleVector
static bool LanguageSupportsClangModules(lldb::LanguageType language)
Query whether Clang supports modules for a particular language.
~ClangModulesDeclVendor() override
A class that describes a compilation unit.
const std::vector< SourceModule > & GetImportedModules()
Get the compile unit's imported module list.
lldb::LanguageType GetLanguage()
A uniqued constant string class.
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
Get file at index.
size_t GetSize() const
Get the number of files in the file list.
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
static FileSystem & Instance()
static ModuleListProperties & GetGlobalModuleListProperties()
A stream class that can stream formatted output to a file.
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
FileSpecList GetClangModuleSearchPaths()
lldb::PlatformSP GetPlatform()
const ArchSpec & GetArchitecture() const
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
FileSpec GetClangResourceDir()
LanguageType
Programming language type.
@ eLanguageTypeC_plus_plus_14
ISO C++:2014.
@ eLanguageTypeC11
ISO C:2011.
@ eLanguageTypeC99
ISO C:1999.
@ eLanguageTypeC_plus_plus_03
ISO C++:2003.
@ eLanguageTypeObjC_plus_plus
Objective-C++.
@ eLanguageTypeC_plus_plus_11
ISO C++:2011.
@ eLanguageTypeC89
ISO C:1989.
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eLanguageTypeObjC
Objective-C.
@ eLanguageTypeC_plus_plus
ISO C++:1998.
Information needed to import a source-language module.
std::vector< ConstString > path
Something like "Module.Submodule".