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