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/Driver/CreateInvocationFromArgs.h"
14#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Frontend/FrontendActions.h"
16#include "clang/Frontend/TextDiagnosticPrinter.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Lex/PreprocessorOptions.h"
19#include "clang/Parse/Parser.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Serialization/ASTReader.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Support/Threading.h"
48class StoringDiagnosticConsumer :
public clang::DiagnosticConsumer {
50 StoringDiagnosticConsumer();
52 void HandleDiagnostic(clang::DiagnosticsEngine::Level DiagLevel,
53 const clang::Diagnostic &info)
override;
55 void ClearDiagnostics();
59 void BeginSourceFile(
const clang::LangOptions &LangOpts,
60 const clang::Preprocessor *PP =
nullptr)
override;
61 void EndSourceFile()
override;
64 bool HandleModuleRemark(
const clang::Diagnostic &info);
65 void SetCurrentModuleProgress(std::string module_name);
67 typedef std::pair<clang::DiagnosticsEngine::Level, std::string>
69 std::vector<IDAndDiagnostic> m_diagnostics;
70 std::unique_ptr<clang::DiagnosticOptions> m_diag_opts;
74 std::unique_ptr<llvm::raw_string_ostream> m_os;
77 std::unique_ptr<clang::TextDiagnosticPrinter> m_diag_printer;
79 std::unique_ptr<Progress> m_current_progress_up;
80 std::vector<std::string> m_module_build_stack;
87 ClangModulesDeclVendorImpl(
88 std::unique_ptr<clang::DiagnosticOptions> diagnostic_options,
89 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine,
90 std::shared_ptr<clang::CompilerInvocation> compiler_invocation,
91 std::unique_ptr<clang::CompilerInstance> compiler_instance,
92 std::unique_ptr<clang::Parser> parser);
94 ~ClangModulesDeclVendorImpl()
override =
default;
96 llvm::Error AddModule(
const SourceModule &module,
97 ModuleVector *exported_modules)
override;
99 llvm::Error AddModulesForCompileUnit(CompileUnit &cu,
100 ModuleVector &exported_modules)
override;
102 uint32_t FindDecls(ConstString name,
bool append, uint32_t max_matches,
103 std::vector<CompilerDecl> &decls)
override;
106 const ModuleVector &modules,
107 std::function<
bool(llvm::StringRef, llvm::StringRef)> handler)
override;
110 typedef llvm::DenseSet<ModuleID> ExportedModuleSet;
111 void ReportModuleExportsHelper(ExportedModuleSet &exports,
112 clang::Module *module);
114 void ReportModuleExports(ModuleVector &exports, clang::Module *module);
116 clang::ModuleLoadResult DoGetModule(clang::ModuleIdPath path,
119 bool m_enabled =
false;
121 std::unique_ptr<clang::DiagnosticOptions> m_diagnostic_options;
122 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> m_diagnostics_engine;
123 std::shared_ptr<clang::CompilerInvocation> m_compiler_invocation;
124 std::unique_ptr<clang::CompilerInstance> m_compiler_instance;
125 std::unique_ptr<clang::Parser> m_parser;
126 size_t m_source_location_index =
129 typedef std::vector<ConstString> ImportedModule;
130 typedef std::map<ImportedModule, clang::Module *> ImportedModuleMap;
131 typedef llvm::DenseSet<ModuleID> ImportedModuleSet;
132 ImportedModuleMap m_imported_modules;
133 ImportedModuleSet m_user_imported_modules;
136 std::shared_ptr<TypeSystemClang> m_ast_context;
140StoringDiagnosticConsumer::StoringDiagnosticConsumer() {
141 m_diag_opts = std::make_unique<clang::DiagnosticOptions>();
142 m_os = std::make_unique<llvm::raw_string_ostream>(m_output);
144 std::make_unique<clang::TextDiagnosticPrinter>(*m_os, *m_diag_opts);
147void StoringDiagnosticConsumer::HandleDiagnostic(
148 clang::DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic &info) {
149 if (HandleModuleRemark(info))
154 m_diag_printer->HandleDiagnostic(DiagLevel, info);
157 m_diagnostics.push_back(IDAndDiagnostic(DiagLevel, m_output));
160void StoringDiagnosticConsumer::ClearDiagnostics() { m_diagnostics.clear(); }
162void StoringDiagnosticConsumer::DumpDiagnostics(Stream &error_stream) {
163 for (IDAndDiagnostic &diag : m_diagnostics) {
164 switch (diag.first) {
169 case clang::DiagnosticsEngine::Level::Ignored:
175void StoringDiagnosticConsumer::BeginSourceFile(
176 const clang::LangOptions &LangOpts,
const clang::Preprocessor *PP) {
177 m_diag_printer->BeginSourceFile(LangOpts, PP);
180void StoringDiagnosticConsumer::EndSourceFile() {
181 m_current_progress_up =
nullptr;
182 m_diag_printer->EndSourceFile();
185bool StoringDiagnosticConsumer::HandleModuleRemark(
186 const clang::Diagnostic &info) {
187 Log *log =
GetLog(LLDBLog::Types | LLDBLog::Expressions);
188 switch (info.getID()) {
189 case clang::diag::remark_module_build: {
190 const auto &module_name = info.getArgStdStr(0);
191 SetCurrentModuleProgress(module_name);
192 m_module_build_stack.push_back(module_name);
194 const auto &module_path = info.getArgStdStr(1);
195 LLDB_LOG(log,
"Building Clang module {0} as {1}", module_name, module_path);
198 case clang::diag::remark_module_build_done: {
200 m_module_build_stack.pop_back();
201 if (m_module_build_stack.empty()) {
202 m_current_progress_up =
nullptr;
207 const auto &resumed_module_name = m_module_build_stack.back();
208 SetCurrentModuleProgress(resumed_module_name);
211 const auto &module_name = info.getArgStdStr(0);
212 LLDB_LOG(log,
"Finished building Clang module {0}", module_name);
220void StoringDiagnosticConsumer::SetCurrentModuleProgress(
221 std::string module_name) {
222 if (!m_current_progress_up)
223 m_current_progress_up =
224 std::make_unique<Progress>(
"Building Clang modules");
226 m_current_progress_up->Increment(1, std::move(module_name));
234ClangModulesDeclVendorImpl::ClangModulesDeclVendorImpl(
235 std::unique_ptr<clang::DiagnosticOptions> diagnostic_options,
236 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine,
237 std::shared_ptr<clang::CompilerInvocation> compiler_invocation,
238 std::unique_ptr<clang::CompilerInstance> compiler_instance,
239 std::unique_ptr<clang::Parser> parser)
240 : m_diagnostic_options(std::move(diagnostic_options)),
241 m_diagnostics_engine(std::move(diagnostics_engine)),
242 m_compiler_invocation(std::move(compiler_invocation)),
243 m_compiler_instance(std::move(compiler_instance)),
244 m_parser(std::move(parser)) {
248 std::make_shared<TypeSystemClang>(
"ClangModulesDeclVendor ASTContext",
249 m_compiler_instance->getASTContext());
252void ClangModulesDeclVendorImpl::ReportModuleExportsHelper(
253 ExportedModuleSet &exports, clang::Module *module) {
259 llvm::SmallVector<clang::Module *, 2> sub_exports;
261 module->getExportedModules(sub_exports);
263 for (clang::Module *module : sub_exports)
264 ReportModuleExportsHelper(exports, module);
267void ClangModulesDeclVendorImpl::ReportModuleExports(
269 ExportedModuleSet exports_set;
271 ReportModuleExportsHelper(exports_set, module);
273 for (ModuleID module : exports_set)
274 exports.push_back(module);
278ClangModulesDeclVendorImpl::AddModule(
const SourceModule &module,
279 ModuleVector *exported_modules) {
282 if (m_compiler_instance->hadModuleLoaderFatalFailure())
283 return llvm::createStringError(
284 "couldn't load a module because the module loader is in a fatal state");
288 std::vector<ConstString> imported_module;
291 imported_module.push_back(path_component);
294 ImportedModuleMap::iterator mi = m_imported_modules.find(imported_module);
296 if (mi != m_imported_modules.end()) {
297 if (exported_modules)
298 ReportModuleExports(*exported_modules, mi->second);
299 return llvm::Error::success();
303 clang::HeaderSearch &HS =
304 m_compiler_instance->getPreprocessor().getHeaderSearchInfo();
312 bool is_system_module = (std::distance(path_begin, path_end) >=
313 std::distance(sysroot_begin, sysroot_end)) &&
314 std::equal(sysroot_begin, sysroot_end, path_begin);
316 if (!is_system_module) {
317 bool is_system =
true;
318 bool is_framework =
false;
319 auto dir = HS.getFileMgr().getOptionalDirectoryRef(
322 return llvm::createStringError(
323 "couldn't find module search path directory %s",
326 auto file = HS.lookupModuleMapFile(*dir, is_framework);
328 return llvm::createStringError(
"couldn't find modulemap file in %s",
331 if (HS.parseAndLoadModuleMapFile(*file, is_system))
332 return llvm::createStringError(
333 "failed to parse and load modulemap file in %s",
338 if (!HS.lookupModule(module.
path.front().GetStringRef()))
339 return llvm::createStringError(
"header search couldn't locate module '%s'",
340 module.
path.front().AsCString());
342 llvm::SmallVector<clang::IdentifierLoc, 4> clang_path;
345 clang::SourceManager &source_manager =
346 m_compiler_instance->getASTContext().getSourceManager();
349 clang_path.emplace_back(
350 source_manager.getLocForStartOfFile(source_manager.getMainFileID())
351 .getLocWithOffset(m_source_location_index++),
352 &m_compiler_instance->getASTContext().Idents.get(
357 StoringDiagnosticConsumer *diagnostic_consumer =
358 static_cast<StoringDiagnosticConsumer *
>(
359 m_compiler_instance->getDiagnostics().getClient());
361 diagnostic_consumer->ClearDiagnostics();
363 clang::Module *top_level_module = DoGetModule(clang_path.front(),
false);
365 if (!top_level_module) {
366 lldb_private::StreamString error_stream;
367 diagnostic_consumer->DumpDiagnostics(error_stream);
369 return llvm::createStringError(llvm::formatv(
370 "couldn't load top-level module {0}:\n{1}",
371 module.
path.front().GetStringRef(), error_stream.
GetString()));
374 clang::Module *submodule = top_level_module;
376 for (
auto &component : llvm::ArrayRef<ConstString>(module.
path).drop_front()) {
377 clang::Module *found = submodule->findSubmodule(component.GetStringRef());
379 lldb_private::StreamString error_stream;
380 diagnostic_consumer->DumpDiagnostics(error_stream);
382 return llvm::createStringError(llvm::formatv(
383 "couldn't load submodule '{0}' of module '{1}':\n{2}",
384 component.GetStringRef(), submodule->getFullModuleName(),
394 m_compiler_instance->makeModuleVisible(
395 submodule, clang::Module::NameVisibilityKind::AllVisible,
398 clang::Module *requested_module = DoGetModule(clang_path,
true);
400 if (requested_module !=
nullptr) {
401 if (exported_modules)
402 ReportModuleExports(*exported_modules, requested_module);
404 m_imported_modules[imported_module] = requested_module;
408 return llvm::Error::success();
411 return llvm::createStringError(
412 llvm::formatv(
"unknown error while loading module {0}\n",
413 module.
path.front().GetStringRef()));
435llvm::Error ClangModulesDeclVendorImpl::AddModulesForCompileUnit(
437 if (!LanguageSupportsClangModules(cu.
GetLanguage()))
438 return llvm::Error::success();
440 llvm::Error errors = llvm::Error::success();
443 if (
auto err = AddModule(imported_module, &exported_modules))
444 errors = llvm::joinErrors(std::move(errors), std::move(err));
452ClangModulesDeclVendorImpl::FindDecls(
ConstString name,
bool append,
453 uint32_t max_matches,
454 std::vector<CompilerDecl> &decls) {
461 clang::IdentifierInfo &ident =
462 m_compiler_instance->getASTContext().Idents.get(name.
GetStringRef());
464 clang::LookupResult lookup_result(
465 m_compiler_instance->getSema(), clang::DeclarationName(&ident),
466 clang::SourceLocation(), clang::Sema::LookupOrdinaryName);
468 m_compiler_instance->getSema().LookupName(
470 m_compiler_instance->getSema().getScopeForContext(
471 m_compiler_instance->getASTContext().getTranslationUnitDecl()));
473 uint32_t num_matches = 0;
475 for (clang::NamedDecl *named_decl : lookup_result) {
476 if (num_matches >= max_matches)
479 decls.push_back(m_ast_context->GetCompilerDecl(named_decl));
486void ClangModulesDeclVendorImpl::ForEachMacro(
488 std::function<
bool(llvm::StringRef, llvm::StringRef)> handler) {
492 typedef std::map<ModuleID, ssize_t> ModulePriorityMap;
493 ModulePriorityMap module_priorities;
495 ssize_t priority = 0;
497 for (ModuleID module : modules)
498 module_priorities[module] = priority++;
500 if (m_compiler_instance->getPreprocessor().getExternalSource()) {
501 m_compiler_instance->getPreprocessor()
503 ->ReadDefinedMacros();
506 for (clang::Preprocessor::macro_iterator
507 mi = m_compiler_instance->getPreprocessor().macro_begin(),
508 me = m_compiler_instance->getPreprocessor().macro_end();
510 const clang::IdentifierInfo *ii =
nullptr;
513 if (clang::IdentifierInfoLookup *lookup =
514 m_compiler_instance->getPreprocessor()
515 .getIdentifierTable()
516 .getExternalIdentifierLookup()) {
517 lookup->get(mi->first->getName());
523 ssize_t found_priority = -1;
524 clang::MacroInfo *macro_info =
nullptr;
526 for (clang::ModuleMacro *module_macro :
527 m_compiler_instance->getPreprocessor().getLeafModuleMacros(ii)) {
528 clang::Module *module = module_macro->getOwningModule();
531 ModulePriorityMap::iterator pi =
532 module_priorities.find(
reinterpret_cast<ModuleID
>(module));
534 if (pi != module_priorities.end() && pi->second > found_priority) {
535 macro_info = module_macro->getMacroInfo();
536 found_priority = pi->second;
540 clang::Module *top_level_module =
module->getTopLevelModule();
542 if (top_level_module != module) {
543 ModulePriorityMap::iterator pi = module_priorities.find(
544 reinterpret_cast<ModuleID
>(top_level_module));
546 if ((pi != module_priorities.end()) && pi->second > found_priority) {
547 macro_info = module_macro->getMacroInfo();
548 found_priority = pi->second;
554 std::string macro_expansion =
"#define ";
555 llvm::StringRef macro_identifier = mi->first->getName();
556 macro_expansion.append(macro_identifier.str());
559 if (macro_info->isFunctionLike()) {
560 macro_expansion.append(
"(");
562 bool first_arg =
true;
564 for (
auto pi = macro_info->param_begin(),
565 pe = macro_info->param_end();
568 macro_expansion.append(
", ");
572 macro_expansion.append((*pi)->getName().str());
575 if (macro_info->isC99Varargs()) {
577 macro_expansion.append(
"...");
579 macro_expansion.append(
", ...");
580 }
else if (macro_info->isGNUVarargs())
581 macro_expansion.append(
"...");
583 macro_expansion.append(
")");
586 macro_expansion.append(
" ");
588 bool first_token =
true;
590 for (clang::MacroInfo::const_tokens_iterator
591 ti = macro_info->tokens_begin(),
592 te = macro_info->tokens_end();
595 macro_expansion.append(
" ");
599 if (ti->isLiteral()) {
600 if (
const char *literal_data = ti->getLiteralData()) {
601 std::string token_str(literal_data, ti->getLength());
602 macro_expansion.append(token_str);
604 bool invalid =
false;
605 const char *literal_source =
606 m_compiler_instance->getSourceManager().getCharacterData(
607 ti->getLocation(), &invalid);
611 macro_expansion.append(
"<unknown literal value>");
613 macro_expansion.append(
614 std::string(literal_source, ti->getLength()));
617 }
else if (
const char *punctuator_spelling =
618 clang::tok::getPunctuatorSpelling(ti->getKind())) {
619 macro_expansion.append(punctuator_spelling);
620 }
else if (
const char *keyword_spelling =
621 clang::tok::getKeywordSpelling(ti->getKind())) {
622 macro_expansion.append(keyword_spelling);
624 switch (ti->getKind()) {
625 case clang::tok::TokenKind::identifier:
626 macro_expansion.append(ti->getIdentifierInfo()->getName().str());
628 case clang::tok::TokenKind::raw_identifier:
629 macro_expansion.append(ti->getRawIdentifier().str());
632 macro_expansion.append(ti->getName());
638 if (handler(macro_identifier, macro_expansion)) {
646clang::ModuleLoadResult
647ClangModulesDeclVendorImpl::DoGetModule(clang::ModuleIdPath path,
649 clang::Module::NameVisibilityKind visibility =
650 make_visible ? clang::Module::AllVisible : clang::Module::Hidden;
652 const bool is_inclusion_directive =
false;
654 return m_compiler_instance->loadModule(path.front().getLoc(), path,
655 visibility, is_inclusion_directive);
672 std::vector<std::string> compiler_invocation_arguments = {
675 "-fimplicit-module-maps",
681 "-fmodules-validate-system-headers",
682 "-Werror=non-modular-include-in-framework-module",
683 "-Xclang=-fincremental-extensions",
686 target.
GetPlatform()->AddClangModuleCompilationOptions(
687 &target, compiler_invocation_arguments);
694 llvm::SmallString<128> path;
696 props.GetClangModulesCachePath().GetPath(path);
697 std::string module_cache_argument(
"-fmodules-cache-path=");
698 module_cache_argument.append(std::string(path.str()));
699 compiler_invocation_arguments.push_back(module_cache_argument);
704 for (
size_t spi = 0, spe = module_search_paths.
GetSize(); spi < spe; ++spi) {
707 std::string search_path_argument =
"-I";
708 search_path_argument.append(search_path.
GetPath());
710 compiler_invocation_arguments.push_back(search_path_argument);
717 compiler_invocation_arguments.push_back(
"-resource-dir");
718 compiler_invocation_arguments.push_back(clang_resource_dir.
GetPath());
722 std::vector<const char *> compiler_invocation_argument_cstrs;
723 compiler_invocation_argument_cstrs.reserve(
724 compiler_invocation_arguments.size());
725 for (
const std::string &arg : compiler_invocation_arguments)
726 compiler_invocation_argument_cstrs.push_back(arg.c_str());
728 auto diag_options_up =
729 clang::CreateAndPopulateDiagOpts(compiler_invocation_argument_cstrs);
730 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine =
731 clang::CompilerInstance::createDiagnostics(
733 new StoringDiagnosticConsumer);
736 LLDB_LOG(log,
"ClangModulesDeclVendor's compiler flags {0:$[ ]}",
737 llvm::make_range(compiler_invocation_arguments.begin(),
738 compiler_invocation_arguments.end()));
740 clang::CreateInvocationOptions CIOpts;
741 CIOpts.Diags = diagnostics_engine;
742 std::shared_ptr<clang::CompilerInvocation> invocation =
743 clang::createInvocation(compiler_invocation_argument_cstrs,
749 std::unique_ptr<llvm::MemoryBuffer> source_buffer =
750 llvm::MemoryBuffer::getMemBuffer(
751 "extern int __lldb __attribute__((unavailable));",
755 source_buffer.release());
757 auto instance = std::make_unique<clang::CompilerInstance>(invocation);
761 instance->createFileManager();
762 instance->setDiagnostics(diagnostics_engine);
764 std::unique_ptr<clang::FrontendAction> action(
new clang::SyntaxOnlyAction);
766 instance->setTarget(clang::TargetInfo::CreateTargetInfo(
767 *diagnostics_engine, instance->getInvocation().getTargetOpts()));
769 if (!instance->hasTarget())
772 instance->getTarget().adjust(*diagnostics_engine, instance->getLangOpts(),
775 if (!action->BeginSourceFile(*instance,
776 instance->getFrontendOpts().Inputs[0]))
779 instance->createASTReader();
781 instance->createSema(action->getTranslationUnitKind(),
nullptr);
783 const bool skipFunctionBodies =
false;
784 std::unique_ptr<clang::Parser> parser(
new clang::Parser(
785 instance->getPreprocessor(), instance->getSema(), skipFunctionBodies));
787 instance->getPreprocessor().EnterMainSourceFile();
788 parser->Initialize();
790 clang::Parser::DeclGroupPtrTy parsed;
791 auto ImportState = clang::Sema::ModuleImportState::NotACXX20Module;
792 while (!parser->ParseTopLevelDecl(parsed, ImportState))
795 return new ClangModulesDeclVendorImpl(
796 std::move(diag_options_up), std::move(diagnostics_engine),
797 std::move(invocation), std::move(instance), std::move(parser));
static const char * ModuleImportBufferName
#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.
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.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * GetCString() const
Get the string value as a C string.
DeclVendor(DeclVendorKind kind)
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()
llvm::StringRef GetString() const
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".