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