blob: 6eebea2fc3fa92994f7c41f74e3f106248d94f5f [file] [log] [blame]
Sean Callanan9998acd2014-12-05 01:21:59 +00001//===-- ClangModulesDeclVendor.cpp ------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ClangModulesDeclVendor.h"
11
12#include "lldb/Core/StreamString.h"
13#include "lldb/Host/FileSpec.h"
14#include "lldb/Host/Host.h"
15#include "lldb/Host/HostInfo.h"
16#include "lldb/Target/Target.h"
17
18#include "clang/Basic/TargetInfo.h"
19#include "clang/Frontend/CompilerInstance.h"
20#include "clang/Frontend/FrontendActions.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Parse/Parser.h"
23#include "clang/Sema/Lookup.h"
24#include "clang/Serialization/ASTReader.h"
25
26using namespace lldb_private;
27
28namespace {
29 // Any Clang compiler requires a consumer for diagnostics. This one stores them as strings
30 // so we can provide them to the user in case a module failed to load.
31 class StoringDiagnosticConsumer : public clang::DiagnosticConsumer
32 {
33 public:
34 StoringDiagnosticConsumer ();
35 void
36 HandleDiagnostic (clang::DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &info);
37
38 void
39 ClearDiagnostics ();
40
41 void
42 DumpDiagnostics (Stream &error_stream);
43 private:
44 typedef std::pair<clang::DiagnosticsEngine::Level, std::string> IDAndDiagnostic;
45 std::vector<IDAndDiagnostic> m_diagnostics;
46 Log * m_log;
47 };
48
49 // The private implementation of our ClangModulesDeclVendor. Contains all the Clang state required
50 // to load modules.
51 class ClangModulesDeclVendorImpl : public ClangModulesDeclVendor
52 {
53 public:
54 ClangModulesDeclVendorImpl(llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> &diagnostics_engine,
55 llvm::IntrusiveRefCntPtr<clang::CompilerInvocation> &compiler_invocation,
56 std::unique_ptr<clang::CompilerInstance> &&compiler_instance,
57 std::unique_ptr<clang::Parser> &&parser);
58
59 virtual bool
60 AddModule(std::vector<llvm::StringRef> &path,
61 Stream &error_stream);
62
63 virtual uint32_t
64 FindDecls (const ConstString &name,
65 bool append,
66 uint32_t max_matches,
67 std::vector <clang::NamedDecl*> &decls);
68
69 ~ClangModulesDeclVendorImpl();
70
71 private:
72 clang::ModuleLoadResult
73 DoGetModule(clang::ModuleIdPath path, bool make_visible);
74
75 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> m_diagnostics_engine;
76 llvm::IntrusiveRefCntPtr<clang::CompilerInvocation> m_compiler_invocation;
77 std::unique_ptr<clang::CompilerInstance> m_compiler_instance;
78 std::unique_ptr<clang::Parser> m_parser;
79 };
80}
81
82StoringDiagnosticConsumer::StoringDiagnosticConsumer ()
83{
84 m_log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
85}
86
87void
88StoringDiagnosticConsumer::HandleDiagnostic (clang::DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &info)
89{
90 llvm::SmallVector<char, 256> diagnostic_string;
91
92 info.FormatDiagnostic(diagnostic_string);
93
94 m_diagnostics.push_back(IDAndDiagnostic(DiagLevel, std::string(diagnostic_string.data(), diagnostic_string.size())));
95}
96
97void
98StoringDiagnosticConsumer::ClearDiagnostics ()
99{
100 m_diagnostics.clear();
101}
102
103void
104StoringDiagnosticConsumer::DumpDiagnostics (Stream &error_stream)
105{
106 for (IDAndDiagnostic &diag : m_diagnostics)
107 {
108 switch (diag.first)
109 {
110 default:
111 error_stream.PutCString(diag.second.c_str());
112 break;
113 case clang::DiagnosticsEngine::Level::Ignored:
114 break;
115 }
116 }
117}
118
119static FileSpec
120GetResourceDir ()
121{
122 static FileSpec g_cached_resource_dir;
123
124 static std::once_flag g_once_flag;
125
126 std::call_once(g_once_flag, [](){
127 HostInfo::GetLLDBPath (lldb::ePathTypeClangDir, g_cached_resource_dir);
128 });
129
130 return g_cached_resource_dir;
131}
132
133
134ClangModulesDeclVendor::ClangModulesDeclVendor()
135{
136}
137
138ClangModulesDeclVendor::~ClangModulesDeclVendor()
139{
140}
141
142ClangModulesDeclVendorImpl::ClangModulesDeclVendorImpl(llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> &diagnostics_engine,
143 llvm::IntrusiveRefCntPtr<clang::CompilerInvocation> &compiler_invocation,
144 std::unique_ptr<clang::CompilerInstance> &&compiler_instance,
145 std::unique_ptr<clang::Parser> &&parser) :
146 ClangModulesDeclVendor(),
147 m_diagnostics_engine(diagnostics_engine),
148 m_compiler_invocation(compiler_invocation),
149 m_compiler_instance(std::move(compiler_instance)),
150 m_parser(std::move(parser))
151{
152}
153
154bool
155ClangModulesDeclVendorImpl::AddModule(std::vector<llvm::StringRef> &path,
156 Stream &error_stream)
157{
158 // Fail early.
159
160 if (m_compiler_instance->hadModuleLoaderFatalFailure())
161 {
162 error_stream.PutCString("error: Couldn't load a module because the module loader is in a fatal state.\n");
163 return false;
164 }
165
166 if (!m_compiler_instance->getPreprocessor().getHeaderSearchInfo().lookupModule(path[0]))
167 {
168 error_stream.Printf("error: Header search couldn't locate module %s\n", path[0].str().c_str());
169 return false;
170 }
171
172 llvm::SmallVector<std::pair<clang::IdentifierInfo *, clang::SourceLocation>, 4> clang_path;
173
174 {
175 size_t source_loc_counter = 0;
176 clang::SourceManager &source_manager = m_compiler_instance->getASTContext().getSourceManager();
177
178 for (llvm::StringRef &component : path)
179 {
180 clang_path.push_back(std::make_pair(&m_compiler_instance->getASTContext().Idents.get(component),
181 source_manager.getLocForStartOfFile(source_manager.getMainFileID()).getLocWithOffset(source_loc_counter++)));
182 }
183 }
184
185 StoringDiagnosticConsumer *diagnostic_consumer = static_cast<StoringDiagnosticConsumer *>(m_compiler_instance->getDiagnostics().getClient());
186
187 diagnostic_consumer->ClearDiagnostics();
188
189 clang::Module *top_level_module = DoGetModule(clang_path.front(), false);
190
191 if (!top_level_module)
192 {
193 diagnostic_consumer->DumpDiagnostics(error_stream);
194 error_stream.Printf("error: Couldn't load top-level module %s\n", path[0].str().c_str());
195 return false;
196 }
197
198 clang::Module *submodule = top_level_module;
199
200 for (size_t ci = 1; ci < path.size(); ++ci)
201 {
202 llvm::StringRef &component = path[ci];
203 submodule = submodule->findSubmodule(component.str());
204 if (!submodule)
205 {
206 diagnostic_consumer->DumpDiagnostics(error_stream);
207 error_stream.Printf("error: Couldn't load submodule %s\n", component.str().c_str());
208 return false;
209 }
210 }
211
212 clang::Module *requested_module = DoGetModule(clang_path, true);
213
214 return (requested_module != nullptr);
215}
216
217// ClangImporter::lookupValue
218
219uint32_t
220ClangModulesDeclVendorImpl::FindDecls (const ConstString &name,
221 bool append,
222 uint32_t max_matches,
223 std::vector <clang::NamedDecl*> &decls)
224{
225 if (!append)
226 decls.clear();
227
228 clang::IdentifierInfo &ident = m_compiler_instance->getASTContext().Idents.get(name.GetStringRef());
229
230 clang::LookupResult lookup_result(m_compiler_instance->getSema(),
231 clang::DeclarationName(&ident),
232 clang::SourceLocation(),
233 clang::Sema::LookupOrdinaryName);
234
235 m_compiler_instance->getSema().LookupName(lookup_result, m_compiler_instance->getSema().getScopeForContext(m_compiler_instance->getASTContext().getTranslationUnitDecl()));
236
237 uint32_t num_matches = 0;
238
239 for (clang::NamedDecl *named_decl : lookup_result)
240 {
241 if (num_matches >= max_matches)
242 return num_matches;
243
244 decls.push_back(named_decl);
245 ++num_matches;
246 }
247
248 return num_matches;
249}
250
251ClangModulesDeclVendorImpl::~ClangModulesDeclVendorImpl()
252{
253}
254
255clang::ModuleLoadResult
256ClangModulesDeclVendorImpl::DoGetModule(clang::ModuleIdPath path,
257 bool make_visible)
258{
259 clang::Module::NameVisibilityKind visibility = make_visible ? clang::Module::AllVisible : clang::Module::Hidden;
260
261 const bool is_inclusion_directive = false;
262
263 return m_compiler_instance->loadModule(path.front().second, path, visibility, is_inclusion_directive);
264}
265
266static const char *ModuleImportBufferName = "LLDBModulesMemoryBuffer";
267
268lldb_private::ClangModulesDeclVendor *
269ClangModulesDeclVendor::Create(Target &target)
270{
271 // FIXME we should insure programmatically that the expression parser's compiler and the modules runtime's
272 // compiler are both initialized in the same way – preferably by the same code.
273
274 if (!target.GetPlatform()->SupportsModules())
275 return nullptr;
276
277 const ArchSpec &arch = target.GetArchitecture();
278
279 std::vector<std::string> compiler_invocation_arguments =
280 {
281 "-fmodules",
282 "-fcxx-modules",
283 "-fsyntax-only",
284 "-femit-all-decls",
285 "-target", arch.GetTriple().str(),
286 "-fmodules-validate-system-headers",
287 "-Werror=non-modular-include-in-framework-module"
288 };
289
290 target.GetPlatform()->AddClangModuleCompilationOptions(compiler_invocation_arguments);
291
292 compiler_invocation_arguments.push_back(ModuleImportBufferName);
293
294 // Add additional search paths with { "-I", path } or { "-F", path } here.
295
296 {
297 llvm::SmallString<128> DefaultModuleCache;
298 const bool erased_on_reboot = false;
299 llvm::sys::path::system_temp_directory(erased_on_reboot, DefaultModuleCache);
300 llvm::sys::path::append(DefaultModuleCache, "org.llvm.clang");
301 llvm::sys::path::append(DefaultModuleCache, "ModuleCache");
302 std::string module_cache_argument("-fmodules-cache-path=");
303 module_cache_argument.append(DefaultModuleCache.str().str());
304 compiler_invocation_arguments.push_back(module_cache_argument);
305 }
306
307 {
308 FileSpec clang_resource_dir = GetResourceDir();
309
310 if (clang_resource_dir.IsDirectory())
311 {
312 compiler_invocation_arguments.push_back("-resource-dir");
313 compiler_invocation_arguments.push_back(clang_resource_dir.GetPath());
314 }
315 }
316
317 llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diagnostics_engine = clang::CompilerInstance::createDiagnostics(new clang::DiagnosticOptions,
318 new StoringDiagnosticConsumer);
319
320 std::vector<const char *> compiler_invocation_argument_cstrs;
321
322 for (const std::string &arg : compiler_invocation_arguments) {
323 compiler_invocation_argument_cstrs.push_back(arg.c_str());
324 }
325
326 llvm::IntrusiveRefCntPtr<clang::CompilerInvocation> invocation(clang::createInvocationFromCommandLine(compiler_invocation_argument_cstrs, diagnostics_engine));
327
328 if (!invocation)
329 return nullptr;
330
331 std::unique_ptr<llvm::MemoryBuffer> source_buffer = llvm::MemoryBuffer::getMemBuffer("extern int __lldb __attribute__((unavailable));",
332 ModuleImportBufferName);
333
334 invocation->getPreprocessorOpts().addRemappedFile(ModuleImportBufferName, source_buffer.release());
335
336 std::unique_ptr<clang::CompilerInstance> instance(new clang::CompilerInstance);
337
338 instance->setDiagnostics(diagnostics_engine.get());
339 instance->setInvocation(invocation.get());
340
341 std::unique_ptr<clang::FrontendAction> action(new clang::SyntaxOnlyAction);
342
343 instance->setTarget(clang::TargetInfo::CreateTargetInfo(*diagnostics_engine, instance->getInvocation().TargetOpts));
344
345 if (!instance->hasTarget())
346 return nullptr;
347
348 instance->getTarget().adjust(instance->getLangOpts());
349
350 if (!action->BeginSourceFile(*instance, instance->getFrontendOpts().Inputs[0]))
351 return nullptr;
352
353 instance->getPreprocessor().enableIncrementalProcessing();
354
355 instance->createModuleManager();
356
357 instance->createSema(action->getTranslationUnitKind(), nullptr);
358
359 const bool skipFunctionBodies = false;
360 std::unique_ptr<clang::Parser> parser(new clang::Parser(instance->getPreprocessor(), instance->getSema(), skipFunctionBodies));
361
362 instance->getPreprocessor().EnterMainSourceFile();
363 parser->Initialize();
364
365 clang::Parser::DeclGroupPtrTy parsed;
366
367 while (!parser->ParseTopLevelDecl(parsed));
368
369 return new ClangModulesDeclVendorImpl (diagnostics_engine, invocation, std::move(instance), std::move(parser));
370}