1 //===-- ClangExpressionParser.cpp -----------------------------------------===//
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 "clang/AST/ASTContext.h"
10 #include "clang/AST/ASTDiagnostic.h"
11 #include "clang/AST/ExternalASTSource.h"
12 #include "clang/AST/PrettyPrinter.h"
13 #include "clang/Basic/Builtins.h"
14 #include "clang/Basic/DiagnosticIDs.h"
15 #include "clang/Basic/SourceLocation.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Basic/Version.h"
18 #include "clang/CodeGen/CodeGenAction.h"
19 #include "clang/CodeGen/ModuleBuilder.h"
20 #include "clang/Edit/Commit.h"
21 #include "clang/Edit/EditedSource.h"
22 #include "clang/Edit/EditsReceiver.h"
23 #include "clang/Frontend/CompilerInstance.h"
24 #include "clang/Frontend/CompilerInvocation.h"
25 #include "clang/Frontend/FrontendActions.h"
26 #include "clang/Frontend/FrontendDiagnostic.h"
27 #include "clang/Frontend/FrontendPluginRegistry.h"
28 #include "clang/Frontend/TextDiagnosticBuffer.h"
29 #include "clang/Frontend/TextDiagnosticPrinter.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Parse/ParseAST.h"
32 #include "clang/Rewrite/Core/Rewriter.h"
33 #include "clang/Rewrite/Frontend/FrontendActions.h"
34 #include "clang/Sema/CodeCompleteConsumer.h"
35 #include "clang/Sema/Sema.h"
36 #include "clang/Sema/SemaConsumer.h"
37 
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/ExecutionEngine/ExecutionEngine.h"
40 #include "llvm/Support/CrashRecoveryContext.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/TargetSelect.h"
44 
45 #include "llvm/IR/LLVMContext.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/Support/DynamicLibrary.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/Host.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/Signals.h"
52 
53 #include "ClangDiagnostic.h"
54 #include "ClangExpressionParser.h"
55 #include "ClangUserExpression.h"
56 
57 #include "ASTUtils.h"
58 #include "ClangASTSource.h"
59 #include "ClangDiagnostic.h"
60 #include "ClangExpressionDeclMap.h"
61 #include "ClangExpressionHelper.h"
62 #include "ClangExpressionParser.h"
63 #include "ClangHost.h"
64 #include "ClangModulesDeclVendor.h"
65 #include "ClangPersistentVariables.h"
66 #include "IRDynamicChecks.h"
67 #include "IRForTarget.h"
68 #include "ModuleDependencyCollector.h"
69 
70 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
71 #include "lldb/Core/Debugger.h"
72 #include "lldb/Core/Disassembler.h"
73 #include "lldb/Core/Module.h"
74 #include "lldb/Core/StreamFile.h"
75 #include "lldb/Expression/IRExecutionUnit.h"
76 #include "lldb/Expression/IRInterpreter.h"
77 #include "lldb/Host/File.h"
78 #include "lldb/Host/HostInfo.h"
79 #include "lldb/Symbol/SymbolVendor.h"
80 #include "lldb/Target/ExecutionContext.h"
81 #include "lldb/Target/Language.h"
82 #include "lldb/Target/Process.h"
83 #include "lldb/Target/Target.h"
84 #include "lldb/Target/ThreadPlanCallFunction.h"
85 #include "lldb/Utility/DataBufferHeap.h"
86 #include "lldb/Utility/LLDBAssert.h"
87 #include "lldb/Utility/Log.h"
88 #include "lldb/Utility/ReproducerProvider.h"
89 #include "lldb/Utility/Stream.h"
90 #include "lldb/Utility/StreamString.h"
91 #include "lldb/Utility/StringList.h"
92 
93 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
94 #include "Plugins/LanguageRuntime/RenderScript/RenderScriptRuntime/RenderScriptRuntime.h"
95 
96 #include <cctype>
97 #include <memory>
98 
99 using namespace clang;
100 using namespace llvm;
101 using namespace lldb_private;
102 
103 //===----------------------------------------------------------------------===//
104 // Utility Methods for Clang
105 //===----------------------------------------------------------------------===//
106 
107 class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
108   ClangModulesDeclVendor &m_decl_vendor;
109   ClangPersistentVariables &m_persistent_vars;
110   clang::SourceManager &m_source_mgr;
111   StreamString m_error_stream;
112   bool m_has_errors = false;
113 
114 public:
115   LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
116                             ClangPersistentVariables &persistent_vars,
117                             clang::SourceManager &source_mgr)
118       : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars),
119         m_source_mgr(source_mgr) {}
120 
121   void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
122                     const clang::Module * /*null*/) override {
123     // Ignore modules that are imported in the wrapper code as these are not
124     // loaded by the user.
125     llvm::StringRef filename =
126         m_source_mgr.getPresumedLoc(import_location).getFilename();
127     if (filename == ClangExpressionSourceCode::g_prefix_file_name)
128       return;
129 
130     SourceModule module;
131 
132     for (const std::pair<IdentifierInfo *, SourceLocation> &component : path)
133       module.path.push_back(ConstString(component.first->getName()));
134 
135     StreamString error_stream;
136 
137     ClangModulesDeclVendor::ModuleVector exported_modules;
138     if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream))
139       m_has_errors = true;
140 
141     for (ClangModulesDeclVendor::ModuleID module : exported_modules)
142       m_persistent_vars.AddHandLoadedClangModule(module);
143   }
144 
145   bool hasErrors() { return m_has_errors; }
146 
147   llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
148 };
149 
150 static void AddAllFixIts(ClangDiagnostic *diag, const clang::Diagnostic &Info) {
151   for (auto &fix_it : Info.getFixItHints()) {
152     if (fix_it.isNull())
153       continue;
154     diag->AddFixitHint(fix_it);
155   }
156 }
157 
158 class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
159 public:
160   ClangDiagnosticManagerAdapter(DiagnosticOptions &opts) {
161     DiagnosticOptions *options = new DiagnosticOptions(opts);
162     options->ShowPresumedLoc = true;
163     options->ShowLevel = false;
164     m_os = std::make_shared<llvm::raw_string_ostream>(m_output);
165     m_passthrough =
166         std::make_shared<clang::TextDiagnosticPrinter>(*m_os, options);
167   }
168 
169   void ResetManager(DiagnosticManager *manager = nullptr) {
170     m_manager = manager;
171   }
172 
173   /// Returns the last ClangDiagnostic message that the DiagnosticManager
174   /// received or a nullptr if the DiagnosticMangager hasn't seen any
175   /// Clang diagnostics yet.
176   ClangDiagnostic *MaybeGetLastClangDiag() const {
177     if (m_manager->Diagnostics().empty())
178       return nullptr;
179     lldb_private::Diagnostic *diag = m_manager->Diagnostics().back().get();
180     ClangDiagnostic *clang_diag = dyn_cast<ClangDiagnostic>(diag);
181     return clang_diag;
182   }
183 
184   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
185                         const clang::Diagnostic &Info) override {
186     if (!m_manager) {
187       // We have no DiagnosticManager before/after parsing but we still could
188       // receive diagnostics (e.g., by the ASTImporter failing to copy decls
189       // when we move the expression result ot the ScratchASTContext). Let's at
190       // least log these diagnostics until we find a way to properly render
191       // them and display them to the user.
192       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
193       if (log) {
194         llvm::SmallVector<char, 32> diag_str;
195         Info.FormatDiagnostic(diag_str);
196         diag_str.push_back('\0');
197         const char *plain_diag = diag_str.data();
198         LLDB_LOG(log, "Received diagnostic outside parsing: {0}", plain_diag);
199       }
200       return;
201     }
202 
203     // Update error/warning counters.
204     DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
205 
206     // Render diagnostic message to m_output.
207     m_output.clear();
208     m_passthrough->HandleDiagnostic(DiagLevel, Info);
209     m_os->flush();
210 
211     lldb_private::DiagnosticSeverity severity;
212     bool make_new_diagnostic = true;
213 
214     switch (DiagLevel) {
215     case DiagnosticsEngine::Level::Fatal:
216     case DiagnosticsEngine::Level::Error:
217       severity = eDiagnosticSeverityError;
218       break;
219     case DiagnosticsEngine::Level::Warning:
220       severity = eDiagnosticSeverityWarning;
221       break;
222     case DiagnosticsEngine::Level::Remark:
223     case DiagnosticsEngine::Level::Ignored:
224       severity = eDiagnosticSeverityRemark;
225       break;
226     case DiagnosticsEngine::Level::Note:
227       m_manager->AppendMessageToDiagnostic(m_output);
228       make_new_diagnostic = false;
229 
230       // 'note:' diagnostics for errors and warnings can also contain Fix-Its.
231       // We add these Fix-Its to the last error diagnostic to make sure
232       // that we later have all Fix-Its related to an 'error' diagnostic when
233       // we apply them to the user expression.
234       auto *clang_diag = MaybeGetLastClangDiag();
235       // If we don't have a previous diagnostic there is nothing to do.
236       // If the previous diagnostic already has its own Fix-Its, assume that
237       // the 'note:' Fix-It is just an alternative way to solve the issue and
238       // ignore these Fix-Its.
239       if (!clang_diag || clang_diag->HasFixIts())
240         break;
241       // Ignore all Fix-Its that are not associated with an error.
242       if (clang_diag->GetSeverity() != eDiagnosticSeverityError)
243         break;
244       AddAllFixIts(clang_diag, Info);
245       break;
246     }
247     if (make_new_diagnostic) {
248       // ClangDiagnostic messages are expected to have no whitespace/newlines
249       // around them.
250       std::string stripped_output =
251           std::string(llvm::StringRef(m_output).trim());
252 
253       auto new_diagnostic = std::make_unique<ClangDiagnostic>(
254           stripped_output, severity, Info.getID());
255 
256       // Don't store away warning fixits, since the compiler doesn't have
257       // enough context in an expression for the warning to be useful.
258       // FIXME: Should we try to filter out FixIts that apply to our generated
259       // code, and not the user's expression?
260       if (severity == eDiagnosticSeverityError)
261         AddAllFixIts(new_diagnostic.get(), Info);
262 
263       m_manager->AddDiagnostic(std::move(new_diagnostic));
264     }
265   }
266 
267   void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override {
268     m_passthrough->BeginSourceFile(LO, PP);
269   }
270 
271   void EndSourceFile() override { m_passthrough->EndSourceFile(); }
272 
273 private:
274   DiagnosticManager *m_manager = nullptr;
275   std::shared_ptr<clang::TextDiagnosticPrinter> m_passthrough;
276   /// Output stream of m_passthrough.
277   std::shared_ptr<llvm::raw_string_ostream> m_os;
278   /// Output string filled by m_os.
279   std::string m_output;
280 };
281 
282 static void SetupModuleHeaderPaths(CompilerInstance *compiler,
283                                    std::vector<std::string> include_directories,
284                                    lldb::TargetSP target_sp) {
285   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
286 
287   HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();
288 
289   for (const std::string &dir : include_directories) {
290     search_opts.AddPath(dir, frontend::System, false, true);
291     LLDB_LOG(log, "Added user include dir: {0}", dir);
292   }
293 
294   llvm::SmallString<128> module_cache;
295   const auto &props = ModuleList::GetGlobalModuleListProperties();
296   props.GetClangModulesCachePath().GetPath(module_cache);
297   search_opts.ModuleCachePath = std::string(module_cache.str());
298   LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str());
299 
300   search_opts.ResourceDir = GetClangResourceDir().GetPath();
301 
302   search_opts.ImplicitModuleMaps = true;
303 }
304 
305 //===----------------------------------------------------------------------===//
306 // Implementation of ClangExpressionParser
307 //===----------------------------------------------------------------------===//
308 
309 ClangExpressionParser::ClangExpressionParser(
310     ExecutionContextScope *exe_scope, Expression &expr,
311     bool generate_debug_info, std::vector<std::string> include_directories,
312     std::string filename)
313     : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
314       m_pp_callbacks(nullptr),
315       m_include_directories(std::move(include_directories)),
316       m_filename(std::move(filename)) {
317   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
318 
319   // We can't compile expressions without a target.  So if the exe_scope is
320   // null or doesn't have a target, then we just need to get out of here.  I'll
321   // lldbassert and not make any of the compiler objects since
322   // I can't return errors directly from the constructor.  Further calls will
323   // check if the compiler was made and
324   // bag out if it wasn't.
325 
326   if (!exe_scope) {
327     lldbassert(exe_scope &&
328                "Can't make an expression parser with a null scope.");
329     return;
330   }
331 
332   lldb::TargetSP target_sp;
333   target_sp = exe_scope->CalculateTarget();
334   if (!target_sp) {
335     lldbassert(target_sp.get() &&
336                "Can't make an expression parser with a null target.");
337     return;
338   }
339 
340   // 1. Create a new compiler instance.
341   m_compiler = std::make_unique<CompilerInstance>();
342 
343   // When capturing a reproducer, hook up the file collector with clang to
344   // collector modules and headers.
345   if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
346     repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>();
347     m_compiler->setModuleDepCollector(
348         std::make_shared<ModuleDependencyCollectorAdaptor>(
349             fp.GetFileCollector()));
350     DependencyOutputOptions &opts = m_compiler->getDependencyOutputOpts();
351     opts.IncludeSystemHeaders = true;
352     opts.IncludeModuleFiles = true;
353   }
354 
355   // Make sure clang uses the same VFS as LLDB.
356   m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
357 
358   lldb::LanguageType frame_lang =
359       expr.Language(); // defaults to lldb::eLanguageTypeUnknown
360   bool overridden_target_opts = false;
361   lldb_private::LanguageRuntime *lang_rt = nullptr;
362 
363   std::string abi;
364   ArchSpec target_arch;
365   target_arch = target_sp->GetArchitecture();
366 
367   const auto target_machine = target_arch.GetMachine();
368 
369   // If the expression is being evaluated in the context of an existing stack
370   // frame, we introspect to see if the language runtime is available.
371 
372   lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
373   lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
374 
375   // Make sure the user hasn't provided a preferred execution language with
376   // `expression --language X -- ...`
377   if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
378     frame_lang = frame_sp->GetLanguage();
379 
380   if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
381     lang_rt = process_sp->GetLanguageRuntime(frame_lang);
382     LLDB_LOGF(log, "Frame has language of type %s",
383               Language::GetNameForLanguageType(frame_lang));
384   }
385 
386   // 2. Configure the compiler with a set of default options that are
387   // appropriate for most situations.
388   if (target_arch.IsValid()) {
389     std::string triple = target_arch.GetTriple().str();
390     m_compiler->getTargetOpts().Triple = triple;
391     LLDB_LOGF(log, "Using %s as the target triple",
392               m_compiler->getTargetOpts().Triple.c_str());
393   } else {
394     // If we get here we don't have a valid target and just have to guess.
395     // Sometimes this will be ok to just use the host target triple (when we
396     // evaluate say "2+3", but other expressions like breakpoint conditions and
397     // other things that _are_ target specific really shouldn't just be using
398     // the host triple. In such a case the language runtime should expose an
399     // overridden options set (3), below.
400     m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
401     LLDB_LOGF(log, "Using default target triple of %s",
402               m_compiler->getTargetOpts().Triple.c_str());
403   }
404   // Now add some special fixes for known architectures: Any arm32 iOS
405   // environment, but not on arm64
406   if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
407       m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
408       m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
409     m_compiler->getTargetOpts().ABI = "apcs-gnu";
410   }
411   // Supported subsets of x86
412   if (target_machine == llvm::Triple::x86 ||
413       target_machine == llvm::Triple::x86_64) {
414     m_compiler->getTargetOpts().Features.push_back("+sse");
415     m_compiler->getTargetOpts().Features.push_back("+sse2");
416   }
417 
418   // Set the target CPU to generate code for. This will be empty for any CPU
419   // that doesn't really need to make a special
420   // CPU string.
421   m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
422 
423   // Set the target ABI
424   abi = GetClangTargetABI(target_arch);
425   if (!abi.empty())
426     m_compiler->getTargetOpts().ABI = abi;
427 
428   // 3. Now allow the runtime to provide custom configuration options for the
429   // target. In this case, a specialized language runtime is available and we
430   // can query it for extra options. For 99% of use cases, this will not be
431   // needed and should be provided when basic platform detection is not enough.
432   // FIXME: Generalize this. Only RenderScriptRuntime currently supports this
433   // currently. Hardcoding this isn't ideal but it's better than LanguageRuntime
434   // having knowledge of clang::TargetOpts.
435   if (auto *renderscript_rt =
436           llvm::dyn_cast_or_null<RenderScriptRuntime>(lang_rt))
437     overridden_target_opts =
438         renderscript_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
439 
440   if (overridden_target_opts)
441     if (log && log->GetVerbose()) {
442       LLDB_LOGV(
443           log, "Using overridden target options for the expression evaluation");
444 
445       auto opts = m_compiler->getTargetOpts();
446       LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
447       LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
448       LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
449       LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
450       LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
451       StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
452       StringList::LogDump(log, opts.Features, "Features");
453     }
454 
455   // 4. Create and install the target on the compiler.
456   m_compiler->createDiagnostics();
457   // Limit the number of error diagnostics we emit.
458   // A value of 0 means no limit for both LLDB and Clang.
459   m_compiler->getDiagnostics().setErrorLimit(target_sp->GetExprErrorLimit());
460 
461   auto target_info = TargetInfo::CreateTargetInfo(
462       m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
463   if (log) {
464     LLDB_LOGF(log, "Using SIMD alignment: %d",
465               target_info->getSimdDefaultAlign());
466     LLDB_LOGF(log, "Target datalayout string: '%s'",
467               target_info->getDataLayout().getStringRepresentation().c_str());
468     LLDB_LOGF(log, "Target ABI: '%s'", target_info->getABI().str().c_str());
469     LLDB_LOGF(log, "Target vector alignment: %d",
470               target_info->getMaxVectorAlign());
471   }
472   m_compiler->setTarget(target_info);
473 
474   assert(m_compiler->hasTarget());
475 
476   // 5. Set language options.
477   lldb::LanguageType language = expr.Language();
478   LangOptions &lang_opts = m_compiler->getLangOpts();
479 
480   switch (language) {
481   case lldb::eLanguageTypeC:
482   case lldb::eLanguageTypeC89:
483   case lldb::eLanguageTypeC99:
484   case lldb::eLanguageTypeC11:
485     // FIXME: the following language option is a temporary workaround,
486     // to "ask for C, get C++."
487     // For now, the expression parser must use C++ anytime the language is a C
488     // family language, because the expression parser uses features of C++ to
489     // capture values.
490     lang_opts.CPlusPlus = true;
491     break;
492   case lldb::eLanguageTypeObjC:
493     lang_opts.ObjC = true;
494     // FIXME: the following language option is a temporary workaround,
495     // to "ask for ObjC, get ObjC++" (see comment above).
496     lang_opts.CPlusPlus = true;
497 
498     // Clang now sets as default C++14 as the default standard (with
499     // GNU extensions), so we do the same here to avoid mismatches that
500     // cause compiler error when evaluating expressions (e.g. nullptr not found
501     // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
502     // two lines below) so we decide to be consistent with that, but this could
503     // be re-evaluated in the future.
504     lang_opts.CPlusPlus11 = true;
505     break;
506   case lldb::eLanguageTypeC_plus_plus:
507   case lldb::eLanguageTypeC_plus_plus_11:
508   case lldb::eLanguageTypeC_plus_plus_14:
509     lang_opts.CPlusPlus11 = true;
510     m_compiler->getHeaderSearchOpts().UseLibcxx = true;
511     LLVM_FALLTHROUGH;
512   case lldb::eLanguageTypeC_plus_plus_03:
513     lang_opts.CPlusPlus = true;
514     if (process_sp)
515       lang_opts.ObjC =
516           process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
517     break;
518   case lldb::eLanguageTypeObjC_plus_plus:
519   case lldb::eLanguageTypeUnknown:
520   default:
521     lang_opts.ObjC = true;
522     lang_opts.CPlusPlus = true;
523     lang_opts.CPlusPlus11 = true;
524     m_compiler->getHeaderSearchOpts().UseLibcxx = true;
525     break;
526   }
527 
528   lang_opts.Bool = true;
529   lang_opts.WChar = true;
530   lang_opts.Blocks = true;
531   lang_opts.DebuggerSupport =
532       true; // Features specifically for debugger clients
533   if (expr.DesiredResultType() == Expression::eResultTypeId)
534     lang_opts.DebuggerCastResultToId = true;
535 
536   lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
537                                .CharIsSignedByDefault();
538 
539   // Spell checking is a nice feature, but it ends up completing a lot of types
540   // that we didn't strictly speaking need to complete. As a result, we spend a
541   // long time parsing and importing debug information.
542   lang_opts.SpellChecking = false;
543 
544   auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr);
545   if (clang_expr && clang_expr->DidImportCxxModules()) {
546     LLDB_LOG(log, "Adding lang options for importing C++ modules");
547 
548     lang_opts.Modules = true;
549     // We want to implicitly build modules.
550     lang_opts.ImplicitModules = true;
551     // To automatically import all submodules when we import 'std'.
552     lang_opts.ModulesLocalVisibility = false;
553 
554     // We use the @import statements, so we need this:
555     // FIXME: We could use the modules-ts, but that currently doesn't work.
556     lang_opts.ObjC = true;
557 
558     // Options we need to parse libc++ code successfully.
559     // FIXME: We should ask the driver for the appropriate default flags.
560     lang_opts.GNUMode = true;
561     lang_opts.GNUKeywords = true;
562     lang_opts.DoubleSquareBracketAttributes = true;
563     lang_opts.CPlusPlus11 = true;
564 
565     // The Darwin libc expects this macro to be set.
566     lang_opts.GNUCVersion = 40201;
567 
568     SetupModuleHeaderPaths(m_compiler.get(), m_include_directories,
569                            target_sp);
570   }
571 
572   if (process_sp && lang_opts.ObjC) {
573     if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) {
574       if (runtime->GetRuntimeVersion() ==
575           ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
576         lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
577       else
578         lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
579                                   VersionTuple(10, 7));
580 
581       if (runtime->HasNewLiteralsAndIndexing())
582         lang_opts.DebuggerObjCLiteral = true;
583     }
584   }
585 
586   lang_opts.ThreadsafeStatics = false;
587   lang_opts.AccessControl = false; // Debuggers get universal access
588   lang_opts.DollarIdents = true;   // $ indicates a persistent variable name
589   // We enable all builtin functions beside the builtins from libc/libm (e.g.
590   // 'fopen'). Those libc functions are already correctly handled by LLDB, and
591   // additionally enabling them as expandable builtins is breaking Clang.
592   lang_opts.NoBuiltin = true;
593 
594   // Set CodeGen options
595   m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
596   m_compiler->getCodeGenOpts().InstrumentFunctions = false;
597   m_compiler->getCodeGenOpts().setFramePointer(
598                                     CodeGenOptions::FramePointerKind::All);
599   if (generate_debug_info)
600     m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
601   else
602     m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
603 
604   // Disable some warnings.
605   m_compiler->getDiagnostics().setSeverityForGroup(
606       clang::diag::Flavor::WarningOrError, "unused-value",
607       clang::diag::Severity::Ignored, SourceLocation());
608   m_compiler->getDiagnostics().setSeverityForGroup(
609       clang::diag::Flavor::WarningOrError, "odr",
610       clang::diag::Severity::Ignored, SourceLocation());
611 
612   // Inform the target of the language options
613   //
614   // FIXME: We shouldn't need to do this, the target should be immutable once
615   // created. This complexity should be lifted elsewhere.
616   m_compiler->getTarget().adjust(m_compiler->getLangOpts());
617 
618   // 6. Set up the diagnostic buffer for reporting errors
619 
620   auto diag_mgr = new ClangDiagnosticManagerAdapter(
621       m_compiler->getDiagnostics().getDiagnosticOptions());
622   m_compiler->getDiagnostics().setClient(diag_mgr);
623 
624   // 7. Set up the source management objects inside the compiler
625   m_compiler->createFileManager();
626   if (!m_compiler->hasSourceManager())
627     m_compiler->createSourceManager(m_compiler->getFileManager());
628   m_compiler->createPreprocessor(TU_Complete);
629 
630   if (ClangModulesDeclVendor *decl_vendor =
631           target_sp->GetClangModulesDeclVendor()) {
632     if (auto *clang_persistent_vars = llvm::cast<ClangPersistentVariables>(
633             target_sp->GetPersistentExpressionStateForLanguage(
634                 lldb::eLanguageTypeC))) {
635       std::unique_ptr<PPCallbacks> pp_callbacks(
636           new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars,
637                                         m_compiler->getSourceManager()));
638       m_pp_callbacks =
639           static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
640       m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
641     }
642   }
643 
644   // 8. Most of this we get from the CompilerInstance, but we also want to give
645   // the context an ExternalASTSource.
646 
647   auto &PP = m_compiler->getPreprocessor();
648   auto &builtin_context = PP.getBuiltinInfo();
649   builtin_context.initializeBuiltins(PP.getIdentifierTable(),
650                                      m_compiler->getLangOpts());
651 
652   m_compiler->createASTContext();
653   clang::ASTContext &ast_context = m_compiler->getASTContext();
654 
655   m_ast_context = std::make_unique<TypeSystemClang>(
656       "Expression ASTContext for '" + m_filename + "'", ast_context);
657 
658   std::string module_name("$__lldb_module");
659 
660   m_llvm_context = std::make_unique<LLVMContext>();
661   m_code_generator.reset(CreateLLVMCodeGen(
662       m_compiler->getDiagnostics(), module_name,
663       m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
664       m_compiler->getCodeGenOpts(), *m_llvm_context));
665 }
666 
667 ClangExpressionParser::~ClangExpressionParser() {}
668 
669 namespace {
670 
671 /// \class CodeComplete
672 ///
673 /// A code completion consumer for the clang Sema that is responsible for
674 /// creating the completion suggestions when a user requests completion
675 /// of an incomplete `expr` invocation.
676 class CodeComplete : public CodeCompleteConsumer {
677   CodeCompletionTUInfo m_info;
678 
679   std::string m_expr;
680   unsigned m_position = 0;
681   /// The printing policy we use when printing declarations for our completion
682   /// descriptions.
683   clang::PrintingPolicy m_desc_policy;
684 
685   struct CompletionWithPriority {
686     CompletionResult::Completion completion;
687     /// See CodeCompletionResult::Priority;
688     unsigned Priority;
689 
690     /// Establishes a deterministic order in a list of CompletionWithPriority.
691     /// The order returned here is the order in which the completions are
692     /// displayed to the user.
693     bool operator<(const CompletionWithPriority &o) const {
694       // High priority results should come first.
695       if (Priority != o.Priority)
696         return Priority > o.Priority;
697 
698       // Identical priority, so just make sure it's a deterministic order.
699       return completion.GetUniqueKey() < o.completion.GetUniqueKey();
700     }
701   };
702 
703   /// The stored completions.
704   /// Warning: These are in a non-deterministic order until they are sorted
705   /// and returned back to the caller.
706   std::vector<CompletionWithPriority> m_completions;
707 
708   /// Returns true if the given character can be used in an identifier.
709   /// This also returns true for numbers because for completion we usually
710   /// just iterate backwards over iterators.
711   ///
712   /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
713   static bool IsIdChar(char c) {
714     return c == '_' || std::isalnum(c) || c == '$';
715   }
716 
717   /// Returns true if the given character is used to separate arguments
718   /// in the command line of lldb.
719   static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
720 
721   /// Drops all tokens in front of the expression that are unrelated for
722   /// the completion of the cmd line. 'unrelated' means here that the token
723   /// is not interested for the lldb completion API result.
724   StringRef dropUnrelatedFrontTokens(StringRef cmd) const {
725     if (cmd.empty())
726       return cmd;
727 
728     // If we are at the start of a word, then all tokens are unrelated to
729     // the current completion logic.
730     if (IsTokenSeparator(cmd.back()))
731       return StringRef();
732 
733     // Remove all previous tokens from the string as they are unrelated
734     // to completing the current token.
735     StringRef to_remove = cmd;
736     while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
737       to_remove = to_remove.drop_back();
738     }
739     cmd = cmd.drop_front(to_remove.size());
740 
741     return cmd;
742   }
743 
744   /// Removes the last identifier token from the given cmd line.
745   StringRef removeLastToken(StringRef cmd) const {
746     while (!cmd.empty() && IsIdChar(cmd.back())) {
747       cmd = cmd.drop_back();
748     }
749     return cmd;
750   }
751 
752   /// Attempts to merge the given completion from the given position into the
753   /// existing command. Returns the completion string that can be returned to
754   /// the lldb completion API.
755   std::string mergeCompletion(StringRef existing, unsigned pos,
756                               StringRef completion) const {
757     StringRef existing_command = existing.substr(0, pos);
758     // We rewrite the last token with the completion, so let's drop that
759     // token from the command.
760     existing_command = removeLastToken(existing_command);
761     // We also should remove all previous tokens from the command as they
762     // would otherwise be added to the completion that already has the
763     // completion.
764     existing_command = dropUnrelatedFrontTokens(existing_command);
765     return existing_command.str() + completion.str();
766   }
767 
768 public:
769   /// Constructs a CodeComplete consumer that can be attached to a Sema.
770   ///
771   /// \param[out] expr
772   ///    The whole expression string that we are currently parsing. This
773   ///    string needs to be equal to the input the user typed, and NOT the
774   ///    final code that Clang is parsing.
775   /// \param[out] position
776   ///    The character position of the user cursor in the `expr` parameter.
777   ///
778   CodeComplete(clang::LangOptions ops, std::string expr, unsigned position)
779       : CodeCompleteConsumer(CodeCompleteOptions()),
780         m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
781         m_position(position), m_desc_policy(ops) {
782 
783     // Ensure that the printing policy is producing a description that is as
784     // short as possible.
785     m_desc_policy.SuppressScope = true;
786     m_desc_policy.SuppressTagKeyword = true;
787     m_desc_policy.FullyQualifiedName = false;
788     m_desc_policy.TerseOutput = true;
789     m_desc_policy.IncludeNewlines = false;
790     m_desc_policy.UseVoidForZeroParams = false;
791     m_desc_policy.Bool = true;
792   }
793 
794   /// \name Code-completion filtering
795   /// Check if the result should be filtered out.
796   bool isResultFilteredOut(StringRef Filter,
797                            CodeCompletionResult Result) override {
798     // This code is mostly copied from CodeCompleteConsumer.
799     switch (Result.Kind) {
800     case CodeCompletionResult::RK_Declaration:
801       return !(
802           Result.Declaration->getIdentifier() &&
803           Result.Declaration->getIdentifier()->getName().startswith(Filter));
804     case CodeCompletionResult::RK_Keyword:
805       return !StringRef(Result.Keyword).startswith(Filter);
806     case CodeCompletionResult::RK_Macro:
807       return !Result.Macro->getName().startswith(Filter);
808     case CodeCompletionResult::RK_Pattern:
809       return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
810     }
811     // If we trigger this assert or the above switch yields a warning, then
812     // CodeCompletionResult has been enhanced with more kinds of completion
813     // results. Expand the switch above in this case.
814     assert(false && "Unknown completion result type?");
815     // If we reach this, then we should just ignore whatever kind of unknown
816     // result we got back. We probably can't turn it into any kind of useful
817     // completion suggestion with the existing code.
818     return true;
819   }
820 
821 private:
822   /// Generate the completion strings for the given CodeCompletionResult.
823   /// Note that this function has to process results that could come in
824   /// non-deterministic order, so this function should have no side effects.
825   /// To make this easier to enforce, this function and all its parameters
826   /// should always be const-qualified.
827   /// \return Returns llvm::None if no completion should be provided for the
828   ///         given CodeCompletionResult.
829   llvm::Optional<CompletionWithPriority>
830   getCompletionForResult(const CodeCompletionResult &R) const {
831     std::string ToInsert;
832     std::string Description;
833     // Handle the different completion kinds that come from the Sema.
834     switch (R.Kind) {
835     case CodeCompletionResult::RK_Declaration: {
836       const NamedDecl *D = R.Declaration;
837       ToInsert = R.Declaration->getNameAsString();
838       // If we have a function decl that has no arguments we want to
839       // complete the empty parantheses for the user. If the function has
840       // arguments, we at least complete the opening bracket.
841       if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
842         if (F->getNumParams() == 0)
843           ToInsert += "()";
844         else
845           ToInsert += "(";
846         raw_string_ostream OS(Description);
847         F->print(OS, m_desc_policy, false);
848         OS.flush();
849       } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
850         Description = V->getType().getAsString(m_desc_policy);
851       } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {
852         Description = F->getType().getAsString(m_desc_policy);
853       } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
854         // If we try to complete a namespace, then we can directly append
855         // the '::'.
856         if (!N->isAnonymousNamespace())
857           ToInsert += "::";
858       }
859       break;
860     }
861     case CodeCompletionResult::RK_Keyword:
862       ToInsert = R.Keyword;
863       break;
864     case CodeCompletionResult::RK_Macro:
865       ToInsert = R.Macro->getName().str();
866       break;
867     case CodeCompletionResult::RK_Pattern:
868       ToInsert = R.Pattern->getTypedText();
869       break;
870     }
871     // We also filter some internal lldb identifiers here. The user
872     // shouldn't see these.
873     if (llvm::StringRef(ToInsert).startswith("$__lldb_"))
874       return llvm::None;
875     if (ToInsert.empty())
876       return llvm::None;
877     // Merge the suggested Token into the existing command line to comply
878     // with the kind of result the lldb API expects.
879     std::string CompletionSuggestion =
880         mergeCompletion(m_expr, m_position, ToInsert);
881 
882     CompletionResult::Completion completion(CompletionSuggestion, Description,
883                                             CompletionMode::Normal);
884     return {{completion, R.Priority}};
885   }
886 
887 public:
888   /// Adds the completions to the given CompletionRequest.
889   void GetCompletions(CompletionRequest &request) {
890     // Bring m_completions into a deterministic order and pass it on to the
891     // CompletionRequest.
892     llvm::sort(m_completions);
893 
894     for (const CompletionWithPriority &C : m_completions)
895       request.AddCompletion(C.completion.GetCompletion(),
896                             C.completion.GetDescription(),
897                             C.completion.GetMode());
898   }
899 
900   /// \name Code-completion callbacks
901   /// Process the finalized code-completion results.
902   void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
903                                   CodeCompletionResult *Results,
904                                   unsigned NumResults) override {
905 
906     // The Sema put the incomplete token we try to complete in here during
907     // lexing, so we need to retrieve it here to know what we are completing.
908     StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
909 
910     // Iterate over all the results. Filter out results we don't want and
911     // process the rest.
912     for (unsigned I = 0; I != NumResults; ++I) {
913       // Filter the results with the information from the Sema.
914       if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
915         continue;
916 
917       CodeCompletionResult &R = Results[I];
918       llvm::Optional<CompletionWithPriority> CompletionAndPriority =
919           getCompletionForResult(R);
920       if (!CompletionAndPriority)
921         continue;
922       m_completions.push_back(*CompletionAndPriority);
923     }
924   }
925 
926   /// \param S the semantic-analyzer object for which code-completion is being
927   /// done.
928   ///
929   /// \param CurrentArg the index of the current argument.
930   ///
931   /// \param Candidates an array of overload candidates.
932   ///
933   /// \param NumCandidates the number of overload candidates
934   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
935                                  OverloadCandidate *Candidates,
936                                  unsigned NumCandidates,
937                                  SourceLocation OpenParLoc) override {
938     // At the moment we don't filter out any overloaded candidates.
939   }
940 
941   CodeCompletionAllocator &getAllocator() override {
942     return m_info.getAllocator();
943   }
944 
945   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
946 };
947 } // namespace
948 
949 bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line,
950                                      unsigned pos, unsigned typed_pos) {
951   DiagnosticManager mgr;
952   // We need the raw user expression here because that's what the CodeComplete
953   // class uses to provide completion suggestions.
954   // However, the `Text` method only gives us the transformed expression here.
955   // To actually get the raw user input here, we have to cast our expression to
956   // the LLVMUserExpression which exposes the right API. This should never fail
957   // as we always have a ClangUserExpression whenever we call this.
958   ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr);
959   CodeComplete CC(m_compiler->getLangOpts(), llvm_expr->GetUserText(),
960                   typed_pos);
961   // We don't need a code generator for parsing.
962   m_code_generator.reset();
963   // Start parsing the expression with our custom code completion consumer.
964   ParseInternal(mgr, &CC, line, pos);
965   CC.GetCompletions(request);
966   return true;
967 }
968 
969 unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
970   return ParseInternal(diagnostic_manager);
971 }
972 
973 unsigned
974 ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,
975                                      CodeCompleteConsumer *completion_consumer,
976                                      unsigned completion_line,
977                                      unsigned completion_column) {
978   ClangDiagnosticManagerAdapter *adapter =
979       static_cast<ClangDiagnosticManagerAdapter *>(
980           m_compiler->getDiagnostics().getClient());
981 
982   adapter->ResetManager(&diagnostic_manager);
983 
984   const char *expr_text = m_expr.Text();
985 
986   clang::SourceManager &source_mgr = m_compiler->getSourceManager();
987   bool created_main_file = false;
988 
989   // Clang wants to do completion on a real file known by Clang's file manager,
990   // so we have to create one to make this work.
991   // TODO: We probably could also simulate to Clang's file manager that there
992   // is a real file that contains our code.
993   bool should_create_file = completion_consumer != nullptr;
994 
995   // We also want a real file on disk if we generate full debug info.
996   should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
997                         codegenoptions::FullDebugInfo;
998 
999   if (should_create_file) {
1000     int temp_fd = -1;
1001     llvm::SmallString<128> result_path;
1002     if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
1003       tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
1004       std::string temp_source_path = tmpdir_file_spec.GetPath();
1005       llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
1006     } else {
1007       llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
1008     }
1009 
1010     if (temp_fd != -1) {
1011       lldb_private::NativeFile file(temp_fd, File::eOpenOptionWrite, true);
1012       const size_t expr_text_len = strlen(expr_text);
1013       size_t bytes_written = expr_text_len;
1014       if (file.Write(expr_text, bytes_written).Success()) {
1015         if (bytes_written == expr_text_len) {
1016           file.Close();
1017           if (auto fileEntry =
1018                   m_compiler->getFileManager().getFile(result_path)) {
1019             source_mgr.setMainFileID(source_mgr.createFileID(
1020                 *fileEntry,
1021                 SourceLocation(), SrcMgr::C_User));
1022             created_main_file = true;
1023           }
1024         }
1025       }
1026     }
1027   }
1028 
1029   if (!created_main_file) {
1030     std::unique_ptr<MemoryBuffer> memory_buffer =
1031         MemoryBuffer::getMemBufferCopy(expr_text, m_filename);
1032     source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
1033   }
1034 
1035   adapter->BeginSourceFile(m_compiler->getLangOpts(),
1036                            &m_compiler->getPreprocessor());
1037 
1038   ClangExpressionHelper *type_system_helper =
1039       dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1040 
1041   // If we want to parse for code completion, we need to attach our code
1042   // completion consumer to the Sema and specify a completion position.
1043   // While parsing the Sema will call this consumer with the provided
1044   // completion suggestions.
1045   if (completion_consumer) {
1046     auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID());
1047     auto &PP = m_compiler->getPreprocessor();
1048     // Lines and columns start at 1 in Clang, but code completion positions are
1049     // indexed from 0, so we need to add 1 to the line and column here.
1050     ++completion_line;
1051     ++completion_column;
1052     PP.SetCodeCompletionPoint(main_file, completion_line, completion_column);
1053   }
1054 
1055   ASTConsumer *ast_transformer =
1056       type_system_helper->ASTTransformer(m_code_generator.get());
1057 
1058   std::unique_ptr<clang::ASTConsumer> Consumer;
1059   if (ast_transformer) {
1060     Consumer = std::make_unique<ASTConsumerForwarder>(ast_transformer);
1061   } else if (m_code_generator) {
1062     Consumer = std::make_unique<ASTConsumerForwarder>(m_code_generator.get());
1063   } else {
1064     Consumer = std::make_unique<ASTConsumer>();
1065   }
1066 
1067   clang::ASTContext &ast_context = m_compiler->getASTContext();
1068 
1069   m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context,
1070                                *Consumer, TU_Complete, completion_consumer));
1071   m_compiler->setASTConsumer(std::move(Consumer));
1072 
1073   if (ast_context.getLangOpts().Modules) {
1074     m_compiler->createASTReader();
1075     m_ast_context->setSema(&m_compiler->getSema());
1076   }
1077 
1078   ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
1079   if (decl_map) {
1080     decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer());
1081 
1082     clang::ExternalASTSource *ast_source = decl_map->CreateProxy();
1083 
1084     if (ast_context.getExternalSource()) {
1085       auto module_wrapper =
1086           new ExternalASTSourceWrapper(ast_context.getExternalSource());
1087 
1088       auto ast_source_wrapper = new ExternalASTSourceWrapper(ast_source);
1089 
1090       auto multiplexer =
1091           new SemaSourceWithPriorities(*module_wrapper, *ast_source_wrapper);
1092       IntrusiveRefCntPtr<ExternalASTSource> Source(multiplexer);
1093       ast_context.setExternalSource(Source);
1094     } else {
1095       ast_context.setExternalSource(ast_source);
1096     }
1097     decl_map->InstallASTContext(*m_ast_context);
1098   }
1099 
1100   // Check that the ASTReader is properly attached to ASTContext and Sema.
1101   if (ast_context.getLangOpts().Modules) {
1102     assert(m_compiler->getASTContext().getExternalSource() &&
1103            "ASTContext doesn't know about the ASTReader?");
1104     assert(m_compiler->getSema().getExternalSource() &&
1105            "Sema doesn't know about the ASTReader?");
1106   }
1107 
1108   {
1109     llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(
1110         &m_compiler->getSema());
1111     ParseAST(m_compiler->getSema(), false, false);
1112   }
1113 
1114   // Make sure we have no pointer to the Sema we are about to destroy.
1115   if (ast_context.getLangOpts().Modules)
1116     m_ast_context->setSema(nullptr);
1117   // Destroy the Sema. This is necessary because we want to emulate the
1118   // original behavior of ParseAST (which also destroys the Sema after parsing).
1119   m_compiler->setSema(nullptr);
1120 
1121   adapter->EndSourceFile();
1122 
1123   unsigned num_errors = adapter->getNumErrors();
1124 
1125   if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
1126     num_errors++;
1127     diagnostic_manager.PutString(eDiagnosticSeverityError,
1128                                  "while importing modules:");
1129     diagnostic_manager.AppendMessageToDiagnostic(
1130         m_pp_callbacks->getErrorString());
1131   }
1132 
1133   if (!num_errors) {
1134     type_system_helper->CommitPersistentDecls();
1135   }
1136 
1137   adapter->ResetManager();
1138 
1139   return num_errors;
1140 }
1141 
1142 std::string
1143 ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
1144   std::string abi;
1145 
1146   if (target_arch.IsMIPS()) {
1147     switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
1148     case ArchSpec::eMIPSABI_N64:
1149       abi = "n64";
1150       break;
1151     case ArchSpec::eMIPSABI_N32:
1152       abi = "n32";
1153       break;
1154     case ArchSpec::eMIPSABI_O32:
1155       abi = "o32";
1156       break;
1157     default:
1158       break;
1159     }
1160   }
1161   return abi;
1162 }
1163 
1164 /// Applies the given Fix-It hint to the given commit.
1165 static void ApplyFixIt(const FixItHint &fixit, clang::edit::Commit &commit) {
1166   // This is cobbed from clang::Rewrite::FixItRewriter.
1167   if (fixit.CodeToInsert.empty()) {
1168     if (fixit.InsertFromRange.isValid()) {
1169       commit.insertFromRange(fixit.RemoveRange.getBegin(),
1170                              fixit.InsertFromRange, /*afterToken=*/false,
1171                              fixit.BeforePreviousInsertions);
1172       return;
1173     }
1174     commit.remove(fixit.RemoveRange);
1175     return;
1176   }
1177   if (fixit.RemoveRange.isTokenRange() ||
1178       fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd()) {
1179     commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
1180     return;
1181   }
1182   commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
1183                 /*afterToken=*/false, fixit.BeforePreviousInsertions);
1184 }
1185 
1186 bool ClangExpressionParser::RewriteExpression(
1187     DiagnosticManager &diagnostic_manager) {
1188   clang::SourceManager &source_manager = m_compiler->getSourceManager();
1189   clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
1190                                    nullptr);
1191   clang::edit::Commit commit(editor);
1192   clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
1193 
1194   class RewritesReceiver : public edit::EditsReceiver {
1195     Rewriter &rewrite;
1196 
1197   public:
1198     RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
1199 
1200     void insert(SourceLocation loc, StringRef text) override {
1201       rewrite.InsertText(loc, text);
1202     }
1203     void replace(CharSourceRange range, StringRef text) override {
1204       rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
1205     }
1206   };
1207 
1208   RewritesReceiver rewrites_receiver(rewriter);
1209 
1210   const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
1211   size_t num_diags = diagnostics.size();
1212   if (num_diags == 0)
1213     return false;
1214 
1215   for (const auto &diag : diagnostic_manager.Diagnostics()) {
1216     const auto *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag.get());
1217     if (!diagnostic)
1218       continue;
1219     if (!diagnostic->HasFixIts())
1220       continue;
1221     for (const FixItHint &fixit : diagnostic->FixIts())
1222       ApplyFixIt(fixit, commit);
1223   }
1224 
1225   // FIXME - do we want to try to propagate specific errors here?
1226   if (!commit.isCommitable())
1227     return false;
1228   else if (!editor.commit(commit))
1229     return false;
1230 
1231   // Now play all the edits, and stash the result in the diagnostic manager.
1232   editor.applyRewrites(rewrites_receiver);
1233   RewriteBuffer &main_file_buffer =
1234       rewriter.getEditBuffer(source_manager.getMainFileID());
1235 
1236   std::string fixed_expression;
1237   llvm::raw_string_ostream out_stream(fixed_expression);
1238 
1239   main_file_buffer.write(out_stream);
1240   out_stream.flush();
1241   diagnostic_manager.SetFixedExpression(fixed_expression);
1242 
1243   return true;
1244 }
1245 
1246 static bool FindFunctionInModule(ConstString &mangled_name,
1247                                  llvm::Module *module, const char *orig_name) {
1248   for (const auto &func : module->getFunctionList()) {
1249     const StringRef &name = func.getName();
1250     if (name.find(orig_name) != StringRef::npos) {
1251       mangled_name.SetString(name);
1252       return true;
1253     }
1254   }
1255 
1256   return false;
1257 }
1258 
1259 lldb_private::Status ClangExpressionParser::PrepareForExecution(
1260     lldb::addr_t &func_addr, lldb::addr_t &func_end,
1261     lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1262     bool &can_interpret, ExecutionPolicy execution_policy) {
1263   func_addr = LLDB_INVALID_ADDRESS;
1264   func_end = LLDB_INVALID_ADDRESS;
1265   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1266 
1267   lldb_private::Status err;
1268 
1269   std::unique_ptr<llvm::Module> llvm_module_up(
1270       m_code_generator->ReleaseModule());
1271 
1272   if (!llvm_module_up) {
1273     err.SetErrorToGenericError();
1274     err.SetErrorString("IR doesn't contain a module");
1275     return err;
1276   }
1277 
1278   ConstString function_name;
1279 
1280   if (execution_policy != eExecutionPolicyTopLevel) {
1281     // Find the actual name of the function (it's often mangled somehow)
1282 
1283     if (!FindFunctionInModule(function_name, llvm_module_up.get(),
1284                               m_expr.FunctionName())) {
1285       err.SetErrorToGenericError();
1286       err.SetErrorStringWithFormat("Couldn't find %s() in the module",
1287                                    m_expr.FunctionName());
1288       return err;
1289     } else {
1290       LLDB_LOGF(log, "Found function %s for %s", function_name.AsCString(),
1291                 m_expr.FunctionName());
1292     }
1293   }
1294 
1295   SymbolContext sc;
1296 
1297   if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1298     sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1299   } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1300     sc.target_sp = target_sp;
1301   }
1302 
1303   LLVMUserExpression::IRPasses custom_passes;
1304   {
1305     auto lang = m_expr.Language();
1306     LLDB_LOGF(log, "%s - Current expression language is %s\n", __FUNCTION__,
1307               Language::GetNameForLanguageType(lang));
1308     lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1309     if (process_sp && lang != lldb::eLanguageTypeUnknown) {
1310       auto runtime = process_sp->GetLanguageRuntime(lang);
1311       if (runtime)
1312         runtime->GetIRPasses(custom_passes);
1313     }
1314   }
1315 
1316   if (custom_passes.EarlyPasses) {
1317     LLDB_LOGF(log,
1318               "%s - Running Early IR Passes from LanguageRuntime on "
1319               "expression module '%s'",
1320               __FUNCTION__, m_expr.FunctionName());
1321 
1322     custom_passes.EarlyPasses->run(*llvm_module_up);
1323   }
1324 
1325   execution_unit_sp = std::make_shared<IRExecutionUnit>(
1326       m_llvm_context, // handed off here
1327       llvm_module_up, // handed off here
1328       function_name, exe_ctx.GetTargetSP(), sc,
1329       m_compiler->getTargetOpts().Features);
1330 
1331   ClangExpressionHelper *type_system_helper =
1332       dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1333   ClangExpressionDeclMap *decl_map =
1334       type_system_helper->DeclMap(); // result can be NULL
1335 
1336   if (decl_map) {
1337     StreamString error_stream;
1338     IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
1339                               *execution_unit_sp, error_stream,
1340                               function_name.AsCString());
1341 
1342     if (!ir_for_target.runOnModule(*execution_unit_sp->GetModule())) {
1343       err.SetErrorString(error_stream.GetString());
1344       return err;
1345     }
1346 
1347     Process *process = exe_ctx.GetProcessPtr();
1348 
1349     if (execution_policy != eExecutionPolicyAlways &&
1350         execution_policy != eExecutionPolicyTopLevel) {
1351       lldb_private::Status interpret_error;
1352 
1353       bool interpret_function_calls =
1354           !process ? false : process->CanInterpretFunctionCalls();
1355       can_interpret = IRInterpreter::CanInterpret(
1356           *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
1357           interpret_error, interpret_function_calls);
1358 
1359       if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1360         err.SetErrorStringWithFormat(
1361             "Can't evaluate the expression without a running target due to: %s",
1362             interpret_error.AsCString());
1363         return err;
1364       }
1365     }
1366 
1367     if (!process && execution_policy == eExecutionPolicyAlways) {
1368       err.SetErrorString("Expression needed to run in the target, but the "
1369                          "target can't be run");
1370       return err;
1371     }
1372 
1373     if (!process && execution_policy == eExecutionPolicyTopLevel) {
1374       err.SetErrorString("Top-level code needs to be inserted into a runnable "
1375                          "target, but the target can't be run");
1376       return err;
1377     }
1378 
1379     if (execution_policy == eExecutionPolicyAlways ||
1380         (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1381       if (m_expr.NeedsValidation() && process) {
1382         if (!process->GetDynamicCheckers()) {
1383           ClangDynamicCheckerFunctions *dynamic_checkers =
1384               new ClangDynamicCheckerFunctions();
1385 
1386           DiagnosticManager install_diagnostics;
1387 
1388           if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
1389             if (install_diagnostics.Diagnostics().size())
1390               err.SetErrorString(install_diagnostics.GetString().c_str());
1391             else
1392               err.SetErrorString("couldn't install checkers, unknown error");
1393 
1394             return err;
1395           }
1396 
1397           process->SetDynamicCheckers(dynamic_checkers);
1398 
1399           LLDB_LOGF(log, "== [ClangExpressionParser::PrepareForExecution] "
1400                          "Finished installing dynamic checkers ==");
1401         }
1402 
1403         if (auto *checker_funcs = llvm::dyn_cast<ClangDynamicCheckerFunctions>(
1404                 process->GetDynamicCheckers())) {
1405           IRDynamicChecks ir_dynamic_checks(*checker_funcs,
1406                                             function_name.AsCString());
1407 
1408           llvm::Module *module = execution_unit_sp->GetModule();
1409           if (!module || !ir_dynamic_checks.runOnModule(*module)) {
1410             err.SetErrorToGenericError();
1411             err.SetErrorString("Couldn't add dynamic checks to the expression");
1412             return err;
1413           }
1414 
1415           if (custom_passes.LatePasses) {
1416             LLDB_LOGF(log,
1417                       "%s - Running Late IR Passes from LanguageRuntime on "
1418                       "expression module '%s'",
1419                       __FUNCTION__, m_expr.FunctionName());
1420 
1421             custom_passes.LatePasses->run(*module);
1422           }
1423         }
1424       }
1425     }
1426 
1427     if (execution_policy == eExecutionPolicyAlways ||
1428         execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1429       execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1430     }
1431   } else {
1432     execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1433   }
1434 
1435   return err;
1436 }
1437 
1438 lldb_private::Status ClangExpressionParser::RunStaticInitializers(
1439     lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
1440   lldb_private::Status err;
1441 
1442   lldbassert(execution_unit_sp.get());
1443   lldbassert(exe_ctx.HasThreadScope());
1444 
1445   if (!execution_unit_sp.get()) {
1446     err.SetErrorString(
1447         "can't run static initializers for a NULL execution unit");
1448     return err;
1449   }
1450 
1451   if (!exe_ctx.HasThreadScope()) {
1452     err.SetErrorString("can't run static initializers without a thread");
1453     return err;
1454   }
1455 
1456   std::vector<lldb::addr_t> static_initializers;
1457 
1458   execution_unit_sp->GetStaticInitializers(static_initializers);
1459 
1460   for (lldb::addr_t static_initializer : static_initializers) {
1461     EvaluateExpressionOptions options;
1462 
1463     lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
1464         exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
1465         llvm::ArrayRef<lldb::addr_t>(), options));
1466 
1467     DiagnosticManager execution_errors;
1468     lldb::ExpressionResults results =
1469         exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
1470             exe_ctx, call_static_initializer, options, execution_errors);
1471 
1472     if (results != lldb::eExpressionCompleted) {
1473       err.SetErrorStringWithFormat("couldn't run static initializer: %s",
1474                                    execution_errors.GetString().c_str());
1475       return err;
1476     }
1477   }
1478 
1479   return err;
1480 }
1481