1 //===-- ClangModulesDeclVendor.cpp ------------------------------*- C++ -*-===// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include <mutex> 10 11 #include "clang/Basic/TargetInfo.h" 12 #include "clang/Frontend/CompilerInstance.h" 13 #include "clang/Frontend/FrontendActions.h" 14 #include "clang/Lex/Preprocessor.h" 15 #include "clang/Lex/PreprocessorOptions.h" 16 #include "clang/Parse/Parser.h" 17 #include "clang/Sema/Lookup.h" 18 #include "clang/Serialization/ASTReader.h" 19 #include "llvm/Support/FileSystem.h" 20 #include "llvm/Support/Path.h" 21 #include "llvm/Support/Threading.h" 22 23 #include "ClangHost.h" 24 #include "ClangModulesDeclVendor.h" 25 #include "ModuleDependencyCollector.h" 26 27 #include "lldb/Core/ModuleList.h" 28 #include "lldb/Host/Host.h" 29 #include "lldb/Host/HostInfo.h" 30 #include "lldb/Symbol/ClangASTContext.h" 31 #include "lldb/Symbol/CompileUnit.h" 32 #include "lldb/Symbol/SourceModule.h" 33 #include "lldb/Target/Target.h" 34 #include "lldb/Utility/FileSpec.h" 35 #include "lldb/Utility/LLDBAssert.h" 36 #include "lldb/Utility/Log.h" 37 #include "lldb/Utility/Reproducer.h" 38 #include "lldb/Utility/StreamString.h" 39 40 using namespace lldb_private; 41 42 namespace { 43 // Any Clang compiler requires a consumer for diagnostics. This one stores 44 // them as strings so we can provide them to the user in case a module failed 45 // to load. 46 class StoringDiagnosticConsumer : public clang::DiagnosticConsumer { 47 public: 48 StoringDiagnosticConsumer(); 49 50 void HandleDiagnostic(clang::DiagnosticsEngine::Level DiagLevel, 51 const clang::Diagnostic &info) override; 52 53 void ClearDiagnostics(); 54 55 void DumpDiagnostics(Stream &error_stream); 56 57 private: 58 typedef std::pair<clang::DiagnosticsEngine::Level, std::string> 59 IDAndDiagnostic; 60 std::vector<IDAndDiagnostic> m_diagnostics; 61 Log *m_log; 62 }; 63 64 // The private implementation of our ClangModulesDeclVendor. Contains all the 65 // Clang state required to load modules. 66 class ClangModulesDeclVendorImpl : public ClangModulesDeclVendor { 67 public: 68 ClangModulesDeclVendorImpl( 69 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine, 70 std::shared_ptr<clang::CompilerInvocation> compiler_invocation, 71 std::unique_ptr<clang::CompilerInstance> compiler_instance, 72 std::unique_ptr<clang::Parser> parser); 73 74 ~ClangModulesDeclVendorImpl() override = default; 75 76 bool AddModule(const SourceModule &module, ModuleVector *exported_modules, 77 Stream &error_stream) override; 78 79 bool AddModulesForCompileUnit(CompileUnit &cu, ModuleVector &exported_modules, 80 Stream &error_stream) override; 81 82 uint32_t FindDecls(ConstString name, bool append, uint32_t max_matches, 83 std::vector<clang::NamedDecl *> &decls) override; 84 85 void ForEachMacro(const ModuleVector &modules, 86 std::function<bool(const std::string &)> handler) override; 87 88 clang::ExternalASTMerger::ImporterSource GetImporterSource() override; 89 private: 90 void 91 ReportModuleExportsHelper(std::set<ClangModulesDeclVendor::ModuleID> &exports, 92 clang::Module *module); 93 94 void ReportModuleExports(ModuleVector &exports, clang::Module *module); 95 96 clang::ModuleLoadResult DoGetModule(clang::ModuleIdPath path, 97 bool make_visible); 98 99 bool m_enabled = false; 100 101 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> m_diagnostics_engine; 102 std::shared_ptr<clang::CompilerInvocation> m_compiler_invocation; 103 std::unique_ptr<clang::CompilerInstance> m_compiler_instance; 104 std::unique_ptr<clang::Parser> m_parser; 105 size_t m_source_location_index = 106 0; // used to give name components fake SourceLocations 107 108 typedef std::vector<ConstString> ImportedModule; 109 typedef std::map<ImportedModule, clang::Module *> ImportedModuleMap; 110 typedef std::set<ModuleID> ImportedModuleSet; 111 ImportedModuleMap m_imported_modules; 112 ImportedModuleSet m_user_imported_modules; 113 const clang::ExternalASTMerger::OriginMap m_origin_map; 114 // We assume that every ASTContext has an ClangASTContext, so we also store 115 // a custom ClangASTContext for our internal ASTContext. 116 std::unique_ptr<ClangASTContext> m_ast_context; 117 }; 118 } // anonymous namespace 119 120 StoringDiagnosticConsumer::StoringDiagnosticConsumer() { 121 m_log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); 122 } 123 124 void StoringDiagnosticConsumer::HandleDiagnostic( 125 clang::DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &info) { 126 llvm::SmallVector<char, 256> diagnostic_string; 127 128 info.FormatDiagnostic(diagnostic_string); 129 130 m_diagnostics.push_back( 131 IDAndDiagnostic(DiagLevel, std::string(diagnostic_string.data(), 132 diagnostic_string.size()))); 133 } 134 135 void StoringDiagnosticConsumer::ClearDiagnostics() { m_diagnostics.clear(); } 136 137 void StoringDiagnosticConsumer::DumpDiagnostics(Stream &error_stream) { 138 for (IDAndDiagnostic &diag : m_diagnostics) { 139 switch (diag.first) { 140 default: 141 error_stream.PutCString(diag.second); 142 error_stream.PutChar('\n'); 143 break; 144 case clang::DiagnosticsEngine::Level::Ignored: 145 break; 146 } 147 } 148 } 149 150 ClangModulesDeclVendor::ClangModulesDeclVendor() {} 151 152 ClangModulesDeclVendor::~ClangModulesDeclVendor() {} 153 154 ClangModulesDeclVendorImpl::ClangModulesDeclVendorImpl( 155 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine, 156 std::shared_ptr<clang::CompilerInvocation> compiler_invocation, 157 std::unique_ptr<clang::CompilerInstance> compiler_instance, 158 std::unique_ptr<clang::Parser> parser) 159 : m_diagnostics_engine(std::move(diagnostics_engine)), 160 m_compiler_invocation(std::move(compiler_invocation)), 161 m_compiler_instance(std::move(compiler_instance)), 162 m_parser(std::move(parser)), m_origin_map() { 163 164 // Initialize our ClangASTContext. 165 auto target_opts = m_compiler_invocation->getTargetOpts(); 166 m_ast_context.reset(new ClangASTContext(target_opts.Triple.c_str())); 167 m_ast_context->setASTContext(&m_compiler_instance->getASTContext()); 168 } 169 170 void ClangModulesDeclVendorImpl::ReportModuleExportsHelper( 171 std::set<ClangModulesDeclVendor::ModuleID> &exports, 172 clang::Module *module) { 173 if (exports.count(reinterpret_cast<ClangModulesDeclVendor::ModuleID>(module))) 174 return; 175 176 exports.insert(reinterpret_cast<ClangModulesDeclVendor::ModuleID>(module)); 177 178 llvm::SmallVector<clang::Module *, 2> sub_exports; 179 180 module->getExportedModules(sub_exports); 181 182 for (clang::Module *module : sub_exports) { 183 ReportModuleExportsHelper(exports, module); 184 } 185 } 186 187 void ClangModulesDeclVendorImpl::ReportModuleExports( 188 ClangModulesDeclVendor::ModuleVector &exports, clang::Module *module) { 189 std::set<ClangModulesDeclVendor::ModuleID> exports_set; 190 191 ReportModuleExportsHelper(exports_set, module); 192 193 for (ModuleID module : exports_set) { 194 exports.push_back(module); 195 } 196 } 197 198 bool ClangModulesDeclVendorImpl::AddModule(const SourceModule &module, 199 ModuleVector *exported_modules, 200 Stream &error_stream) { 201 // Fail early. 202 203 if (m_compiler_instance->hadModuleLoaderFatalFailure()) { 204 error_stream.PutCString("error: Couldn't load a module because the module " 205 "loader is in a fatal state.\n"); 206 return false; 207 } 208 209 // Check if we've already imported this module. 210 211 std::vector<ConstString> imported_module; 212 213 for (ConstString path_component : module.path) { 214 imported_module.push_back(path_component); 215 } 216 217 { 218 ImportedModuleMap::iterator mi = m_imported_modules.find(imported_module); 219 220 if (mi != m_imported_modules.end()) { 221 if (exported_modules) { 222 ReportModuleExports(*exported_modules, mi->second); 223 } 224 return true; 225 } 226 } 227 228 clang::HeaderSearch &HS = 229 m_compiler_instance->getPreprocessor().getHeaderSearchInfo(); 230 231 if (module.search_path) { 232 auto path_begin = llvm::sys::path::begin(module.search_path.GetStringRef()); 233 auto path_end = llvm::sys::path::end(module.search_path.GetStringRef()); 234 auto sysroot_begin = llvm::sys::path::begin(module.sysroot.GetStringRef()); 235 auto sysroot_end = llvm::sys::path::end(module.sysroot.GetStringRef()); 236 // FIXME: Use C++14 std::equal(it, it, it, it) variant once it's available. 237 bool is_system_module = (std::distance(path_begin, path_end) >= 238 std::distance(sysroot_begin, sysroot_end)) && 239 std::equal(sysroot_begin, sysroot_end, path_begin); 240 // No need to inject search paths to modules in the sysroot. 241 if (!is_system_module) { 242 auto error = [&]() { 243 error_stream.Printf("error: No module map file in %s\n", 244 module.search_path.AsCString()); 245 return false; 246 }; 247 248 bool is_system = true; 249 bool is_framework = false; 250 auto dir = 251 HS.getFileMgr().getDirectory(module.search_path.GetStringRef()); 252 if (!dir) 253 return error(); 254 auto *file = HS.lookupModuleMapFile(*dir, is_framework); 255 if (!file) 256 return error(); 257 if (!HS.loadModuleMapFile(file, is_system)) 258 return error(); 259 } 260 } 261 if (!HS.lookupModule(module.path.front().GetStringRef())) { 262 error_stream.Printf("error: Header search couldn't locate module %s\n", 263 module.path.front().AsCString()); 264 return false; 265 } 266 267 llvm::SmallVector<std::pair<clang::IdentifierInfo *, clang::SourceLocation>, 268 4> 269 clang_path; 270 271 { 272 clang::SourceManager &source_manager = 273 m_compiler_instance->getASTContext().getSourceManager(); 274 275 for (ConstString path_component : module.path) { 276 clang_path.push_back(std::make_pair( 277 &m_compiler_instance->getASTContext().Idents.get( 278 path_component.GetStringRef()), 279 source_manager.getLocForStartOfFile(source_manager.getMainFileID()) 280 .getLocWithOffset(m_source_location_index++))); 281 } 282 } 283 284 StoringDiagnosticConsumer *diagnostic_consumer = 285 static_cast<StoringDiagnosticConsumer *>( 286 m_compiler_instance->getDiagnostics().getClient()); 287 288 diagnostic_consumer->ClearDiagnostics(); 289 290 clang::Module *top_level_module = DoGetModule(clang_path.front(), false); 291 292 if (!top_level_module) { 293 diagnostic_consumer->DumpDiagnostics(error_stream); 294 error_stream.Printf("error: Couldn't load top-level module %s\n", 295 module.path.front().AsCString()); 296 return false; 297 } 298 299 clang::Module *submodule = top_level_module; 300 301 for (auto &component : llvm::ArrayRef<ConstString>(module.path).drop_front()) { 302 submodule = submodule->findSubmodule(component.GetStringRef()); 303 if (!submodule) { 304 diagnostic_consumer->DumpDiagnostics(error_stream); 305 error_stream.Printf("error: Couldn't load submodule %s\n", 306 component.GetCString()); 307 return false; 308 } 309 } 310 311 clang::Module *requested_module = DoGetModule(clang_path, true); 312 313 if (requested_module != nullptr) { 314 if (exported_modules) { 315 ReportModuleExports(*exported_modules, requested_module); 316 } 317 318 m_imported_modules[imported_module] = requested_module; 319 320 m_enabled = true; 321 322 return true; 323 } 324 325 return false; 326 } 327 328 bool ClangModulesDeclVendor::LanguageSupportsClangModules( 329 lldb::LanguageType language) { 330 switch (language) { 331 default: 332 return false; 333 case lldb::LanguageType::eLanguageTypeC: 334 case lldb::LanguageType::eLanguageTypeC11: 335 case lldb::LanguageType::eLanguageTypeC89: 336 case lldb::LanguageType::eLanguageTypeC99: 337 case lldb::LanguageType::eLanguageTypeC_plus_plus: 338 case lldb::LanguageType::eLanguageTypeC_plus_plus_03: 339 case lldb::LanguageType::eLanguageTypeC_plus_plus_11: 340 case lldb::LanguageType::eLanguageTypeC_plus_plus_14: 341 case lldb::LanguageType::eLanguageTypeObjC: 342 case lldb::LanguageType::eLanguageTypeObjC_plus_plus: 343 return true; 344 } 345 } 346 347 bool ClangModulesDeclVendorImpl::AddModulesForCompileUnit( 348 CompileUnit &cu, ClangModulesDeclVendor::ModuleVector &exported_modules, 349 Stream &error_stream) { 350 if (LanguageSupportsClangModules(cu.GetLanguage())) { 351 for (auto &imported_module : cu.GetImportedModules()) 352 if (!AddModule(imported_module, &exported_modules, error_stream)) 353 return false; 354 } 355 return true; 356 } 357 358 // ClangImporter::lookupValue 359 360 uint32_t 361 ClangModulesDeclVendorImpl::FindDecls(ConstString name, bool append, 362 uint32_t max_matches, 363 std::vector<clang::NamedDecl *> &decls) { 364 if (!m_enabled) { 365 return 0; 366 } 367 368 if (!append) 369 decls.clear(); 370 371 clang::IdentifierInfo &ident = 372 m_compiler_instance->getASTContext().Idents.get(name.GetStringRef()); 373 374 clang::LookupResult lookup_result( 375 m_compiler_instance->getSema(), clang::DeclarationName(&ident), 376 clang::SourceLocation(), clang::Sema::LookupOrdinaryName); 377 378 m_compiler_instance->getSema().LookupName( 379 lookup_result, 380 m_compiler_instance->getSema().getScopeForContext( 381 m_compiler_instance->getASTContext().getTranslationUnitDecl())); 382 383 uint32_t num_matches = 0; 384 385 for (clang::NamedDecl *named_decl : lookup_result) { 386 if (num_matches >= max_matches) 387 return num_matches; 388 389 decls.push_back(named_decl); 390 ++num_matches; 391 } 392 393 return num_matches; 394 } 395 396 void ClangModulesDeclVendorImpl::ForEachMacro( 397 const ClangModulesDeclVendor::ModuleVector &modules, 398 std::function<bool(const std::string &)> handler) { 399 if (!m_enabled) { 400 return; 401 } 402 403 typedef std::map<ModuleID, ssize_t> ModulePriorityMap; 404 ModulePriorityMap module_priorities; 405 406 ssize_t priority = 0; 407 408 for (ModuleID module : modules) { 409 module_priorities[module] = priority++; 410 } 411 412 if (m_compiler_instance->getPreprocessor().getExternalSource()) { 413 m_compiler_instance->getPreprocessor() 414 .getExternalSource() 415 ->ReadDefinedMacros(); 416 } 417 418 for (clang::Preprocessor::macro_iterator 419 mi = m_compiler_instance->getPreprocessor().macro_begin(), 420 me = m_compiler_instance->getPreprocessor().macro_end(); 421 mi != me; ++mi) { 422 const clang::IdentifierInfo *ii = nullptr; 423 424 { 425 if (clang::IdentifierInfoLookup *lookup = 426 m_compiler_instance->getPreprocessor() 427 .getIdentifierTable() 428 .getExternalIdentifierLookup()) { 429 lookup->get(mi->first->getName()); 430 } 431 if (!ii) { 432 ii = mi->first; 433 } 434 } 435 436 ssize_t found_priority = -1; 437 clang::MacroInfo *macro_info = nullptr; 438 439 for (clang::ModuleMacro *module_macro : 440 m_compiler_instance->getPreprocessor().getLeafModuleMacros(ii)) { 441 clang::Module *module = module_macro->getOwningModule(); 442 443 { 444 ModulePriorityMap::iterator pi = 445 module_priorities.find(reinterpret_cast<ModuleID>(module)); 446 447 if (pi != module_priorities.end() && pi->second > found_priority) { 448 macro_info = module_macro->getMacroInfo(); 449 found_priority = pi->second; 450 } 451 } 452 453 clang::Module *top_level_module = module->getTopLevelModule(); 454 455 if (top_level_module != module) { 456 ModulePriorityMap::iterator pi = module_priorities.find( 457 reinterpret_cast<ModuleID>(top_level_module)); 458 459 if ((pi != module_priorities.end()) && pi->second > found_priority) { 460 macro_info = module_macro->getMacroInfo(); 461 found_priority = pi->second; 462 } 463 } 464 } 465 466 if (macro_info) { 467 std::string macro_expansion = "#define "; 468 macro_expansion.append(mi->first->getName().str()); 469 470 { 471 if (macro_info->isFunctionLike()) { 472 macro_expansion.append("("); 473 474 bool first_arg = true; 475 476 for (auto pi = macro_info->param_begin(), 477 pe = macro_info->param_end(); 478 pi != pe; ++pi) { 479 if (!first_arg) { 480 macro_expansion.append(", "); 481 } else { 482 first_arg = false; 483 } 484 485 macro_expansion.append((*pi)->getName().str()); 486 } 487 488 if (macro_info->isC99Varargs()) { 489 if (first_arg) { 490 macro_expansion.append("..."); 491 } else { 492 macro_expansion.append(", ..."); 493 } 494 } else if (macro_info->isGNUVarargs()) { 495 macro_expansion.append("..."); 496 } 497 498 macro_expansion.append(")"); 499 } 500 501 macro_expansion.append(" "); 502 503 bool first_token = true; 504 505 for (clang::MacroInfo::tokens_iterator ti = macro_info->tokens_begin(), 506 te = macro_info->tokens_end(); 507 ti != te; ++ti) { 508 if (!first_token) { 509 macro_expansion.append(" "); 510 } else { 511 first_token = false; 512 } 513 514 if (ti->isLiteral()) { 515 if (const char *literal_data = ti->getLiteralData()) { 516 std::string token_str(literal_data, ti->getLength()); 517 macro_expansion.append(token_str); 518 } else { 519 bool invalid = false; 520 const char *literal_source = 521 m_compiler_instance->getSourceManager().getCharacterData( 522 ti->getLocation(), &invalid); 523 524 if (invalid) { 525 lldbassert(0 && "Unhandled token kind"); 526 macro_expansion.append("<unknown literal value>"); 527 } else { 528 macro_expansion.append( 529 std::string(literal_source, ti->getLength())); 530 } 531 } 532 } else if (const char *punctuator_spelling = 533 clang::tok::getPunctuatorSpelling(ti->getKind())) { 534 macro_expansion.append(punctuator_spelling); 535 } else if (const char *keyword_spelling = 536 clang::tok::getKeywordSpelling(ti->getKind())) { 537 macro_expansion.append(keyword_spelling); 538 } else { 539 switch (ti->getKind()) { 540 case clang::tok::TokenKind::identifier: 541 macro_expansion.append(ti->getIdentifierInfo()->getName().str()); 542 break; 543 case clang::tok::TokenKind::raw_identifier: 544 macro_expansion.append(ti->getRawIdentifier().str()); 545 break; 546 default: 547 macro_expansion.append(ti->getName()); 548 break; 549 } 550 } 551 } 552 553 if (handler(macro_expansion)) { 554 return; 555 } 556 } 557 } 558 } 559 } 560 561 clang::ModuleLoadResult 562 ClangModulesDeclVendorImpl::DoGetModule(clang::ModuleIdPath path, 563 bool make_visible) { 564 clang::Module::NameVisibilityKind visibility = 565 make_visible ? clang::Module::AllVisible : clang::Module::Hidden; 566 567 const bool is_inclusion_directive = false; 568 569 return m_compiler_instance->loadModule(path.front().second, path, visibility, 570 is_inclusion_directive); 571 } 572 573 clang::ExternalASTMerger::ImporterSource 574 ClangModulesDeclVendorImpl::GetImporterSource() { 575 return {m_compiler_instance->getASTContext(), 576 m_compiler_instance->getFileManager(), m_origin_map}; 577 } 578 579 static const char *ModuleImportBufferName = "LLDBModulesMemoryBuffer"; 580 581 lldb_private::ClangModulesDeclVendor * 582 ClangModulesDeclVendor::Create(Target &target) { 583 // FIXME we should insure programmatically that the expression parser's 584 // compiler and the modules runtime's 585 // compiler are both initialized in the same way – preferably by the same 586 // code. 587 588 if (!target.GetPlatform()->SupportsModules()) 589 return nullptr; 590 591 const ArchSpec &arch = target.GetArchitecture(); 592 593 std::vector<std::string> compiler_invocation_arguments = { 594 "clang", 595 "-fmodules", 596 "-fimplicit-module-maps", 597 "-fcxx-modules", 598 "-fsyntax-only", 599 "-femit-all-decls", 600 "-target", 601 arch.GetTriple().str(), 602 "-fmodules-validate-system-headers", 603 "-Werror=non-modular-include-in-framework-module"}; 604 605 target.GetPlatform()->AddClangModuleCompilationOptions( 606 &target, compiler_invocation_arguments); 607 608 compiler_invocation_arguments.push_back(ModuleImportBufferName); 609 610 // Add additional search paths with { "-I", path } or { "-F", path } here. 611 612 { 613 llvm::SmallString<128> path; 614 auto props = ModuleList::GetGlobalModuleListProperties(); 615 props.GetClangModulesCachePath().GetPath(path); 616 std::string module_cache_argument("-fmodules-cache-path="); 617 module_cache_argument.append(path.str()); 618 compiler_invocation_arguments.push_back(module_cache_argument); 619 } 620 621 FileSpecList module_search_paths = target.GetClangModuleSearchPaths(); 622 623 for (size_t spi = 0, spe = module_search_paths.GetSize(); spi < spe; ++spi) { 624 const FileSpec &search_path = module_search_paths.GetFileSpecAtIndex(spi); 625 626 std::string search_path_argument = "-I"; 627 search_path_argument.append(search_path.GetPath()); 628 629 compiler_invocation_arguments.push_back(search_path_argument); 630 } 631 632 { 633 FileSpec clang_resource_dir = GetClangResourceDir(); 634 635 if (FileSystem::Instance().IsDirectory(clang_resource_dir.GetPath())) { 636 compiler_invocation_arguments.push_back("-resource-dir"); 637 compiler_invocation_arguments.push_back(clang_resource_dir.GetPath()); 638 } 639 } 640 641 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine = 642 clang::CompilerInstance::createDiagnostics(new clang::DiagnosticOptions, 643 new StoringDiagnosticConsumer); 644 645 std::vector<const char *> compiler_invocation_argument_cstrs; 646 compiler_invocation_argument_cstrs.reserve( 647 compiler_invocation_arguments.size()); 648 for (const std::string &arg : compiler_invocation_arguments) 649 compiler_invocation_argument_cstrs.push_back(arg.c_str()); 650 651 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)); 652 LLDB_LOG(log, "ClangModulesDeclVendor's compiler flags {0:$[ ]}", 653 llvm::make_range(compiler_invocation_arguments.begin(), 654 compiler_invocation_arguments.end())); 655 656 std::shared_ptr<clang::CompilerInvocation> invocation = 657 clang::createInvocationFromCommandLine(compiler_invocation_argument_cstrs, 658 diagnostics_engine); 659 660 if (!invocation) 661 return nullptr; 662 663 std::unique_ptr<llvm::MemoryBuffer> source_buffer = 664 llvm::MemoryBuffer::getMemBuffer( 665 "extern int __lldb __attribute__((unavailable));", 666 ModuleImportBufferName); 667 668 invocation->getPreprocessorOpts().addRemappedFile(ModuleImportBufferName, 669 source_buffer.release()); 670 671 std::unique_ptr<clang::CompilerInstance> instance( 672 new clang::CompilerInstance); 673 674 // When capturing a reproducer, hook up the file collector with clang to 675 // collector modules and headers. 676 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) { 677 repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>(); 678 instance->setModuleDepCollector( 679 std::make_shared<ModuleDependencyCollectorAdaptor>( 680 fp.GetFileCollector())); 681 clang::DependencyOutputOptions &opts = instance->getDependencyOutputOpts(); 682 opts.IncludeSystemHeaders = true; 683 opts.IncludeModuleFiles = true; 684 } 685 686 // Make sure clang uses the same VFS as LLDB. 687 instance->createFileManager(FileSystem::Instance().GetVirtualFileSystem()); 688 instance->setDiagnostics(diagnostics_engine.get()); 689 instance->setInvocation(invocation); 690 691 std::unique_ptr<clang::FrontendAction> action(new clang::SyntaxOnlyAction); 692 693 instance->setTarget(clang::TargetInfo::CreateTargetInfo( 694 *diagnostics_engine, instance->getInvocation().TargetOpts)); 695 696 if (!instance->hasTarget()) 697 return nullptr; 698 699 instance->getTarget().adjust(instance->getLangOpts()); 700 701 if (!action->BeginSourceFile(*instance, 702 instance->getFrontendOpts().Inputs[0])) 703 return nullptr; 704 705 instance->getPreprocessor().enableIncrementalProcessing(); 706 707 instance->createModuleManager(); 708 709 instance->createSema(action->getTranslationUnitKind(), nullptr); 710 711 const bool skipFunctionBodies = false; 712 std::unique_ptr<clang::Parser> parser(new clang::Parser( 713 instance->getPreprocessor(), instance->getSema(), skipFunctionBodies)); 714 715 instance->getPreprocessor().EnterMainSourceFile(); 716 parser->Initialize(); 717 718 clang::Parser::DeclGroupPtrTy parsed; 719 720 while (!parser->ParseTopLevelDecl(parsed)) 721 ; 722 723 return new ClangModulesDeclVendorImpl(std::move(diagnostics_engine), 724 std::move(invocation), 725 std::move(instance), std::move(parser)); 726 } 727