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