1 //===-- ClangExpressionParser.cpp -------------------------------*- C++ -*-===//
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/DiagnosticIDs.h"
14 #include "clang/Basic/SourceLocation.h"
15 #include "clang/Basic/TargetInfo.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/CodeGen/CodeGenAction.h"
18 #include "clang/CodeGen/ModuleBuilder.h"
19 #include "clang/Edit/Commit.h"
20 #include "clang/Edit/EditedSource.h"
21 #include "clang/Edit/EditsReceiver.h"
22 #include "clang/Frontend/CompilerInstance.h"
23 #include "clang/Frontend/CompilerInvocation.h"
24 #include "clang/Frontend/FrontendActions.h"
25 #include "clang/Frontend/FrontendDiagnostic.h"
26 #include "clang/Frontend/FrontendPluginRegistry.h"
27 #include "clang/Frontend/TextDiagnosticBuffer.h"
28 #include "clang/Frontend/TextDiagnosticPrinter.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Parse/ParseAST.h"
31 #include "clang/Rewrite/Core/Rewriter.h"
32 #include "clang/Rewrite/Frontend/FrontendActions.h"
33 #include "clang/Sema/CodeCompleteConsumer.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaConsumer.h"
36 
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ExecutionEngine/ExecutionEngine.h"
39 #include "llvm/Support/CrashRecoveryContext.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/TargetSelect.h"
43 
44 #include "llvm/IR/LLVMContext.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/DynamicLibrary.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/Signals.h"
51 
52 #include "ClangDiagnostic.h"
53 #include "ClangExpressionParser.h"
54 #include "ClangUserExpression.h"
55 
56 #include "ASTUtils.h"
57 #include "ClangASTSource.h"
58 #include "ClangDiagnostic.h"
59 #include "ClangExpressionDeclMap.h"
60 #include "ClangExpressionHelper.h"
61 #include "ClangExpressionParser.h"
62 #include "ClangHost.h"
63 #include "ClangModulesDeclVendor.h"
64 #include "ClangPersistentVariables.h"
65 #include "IRDynamicChecks.h"
66 #include "IRForTarget.h"
67 #include "ModuleDependencyCollector.h"
68 
69 #include "lldb/Core/Debugger.h"
70 #include "lldb/Core/Disassembler.h"
71 #include "lldb/Core/Module.h"
72 #include "lldb/Core/StreamFile.h"
73 #include "lldb/Expression/IRExecutionUnit.h"
74 #include "lldb/Expression/IRInterpreter.h"
75 #include "lldb/Host/File.h"
76 #include "lldb/Host/HostInfo.h"
77 #include "lldb/Symbol/ClangASTContext.h"
78 #include "lldb/Symbol/SymbolVendor.h"
79 #include "lldb/Target/ExecutionContext.h"
80 #include "lldb/Target/Language.h"
81 #include "lldb/Target/Process.h"
82 #include "lldb/Target/Target.h"
83 #include "lldb/Target/ThreadPlanCallFunction.h"
84 #include "lldb/Utility/DataBufferHeap.h"
85 #include "lldb/Utility/LLDBAssert.h"
86 #include "lldb/Utility/Log.h"
87 #include "lldb/Utility/Reproducer.h"
88 #include "lldb/Utility/Stream.h"
89 #include "lldb/Utility/StreamString.h"
90 #include "lldb/Utility/StringList.h"
91 
92 #include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
93 
94 #include <cctype>
95 #include <memory>
96 
97 using namespace clang;
98 using namespace llvm;
99 using namespace lldb_private;
100 
101 //===----------------------------------------------------------------------===//
102 // Utility Methods for Clang
103 //===----------------------------------------------------------------------===//
104 
105 class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
106   ClangModulesDeclVendor &m_decl_vendor;
107   ClangPersistentVariables &m_persistent_vars;
108   clang::SourceManager &m_source_mgr;
109   StreamString m_error_stream;
110   bool m_has_errors = false;
111 
112 public:
113   LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
114                             ClangPersistentVariables &persistent_vars,
115                             clang::SourceManager &source_mgr)
116       : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars),
117         m_source_mgr(source_mgr) {}
118 
119   void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
120                     const clang::Module * /*null*/) override {
121     // Ignore modules that are imported in the wrapper code as these are not
122     // loaded by the user.
123     llvm::StringRef filename =
124         m_source_mgr.getPresumedLoc(import_location).getFilename();
125     if (filename == ClangExpressionSourceCode::g_prefix_file_name)
126       return;
127 
128     SourceModule module;
129 
130     for (const std::pair<IdentifierInfo *, SourceLocation> &component : path)
131       module.path.push_back(ConstString(component.first->getName()));
132 
133     StreamString error_stream;
134 
135     ClangModulesDeclVendor::ModuleVector exported_modules;
136     if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream))
137       m_has_errors = true;
138 
139     for (ClangModulesDeclVendor::ModuleID module : exported_modules)
140       m_persistent_vars.AddHandLoadedClangModule(module);
141   }
142 
143   bool hasErrors() { return m_has_errors; }
144 
145   llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
146 };
147 
148 class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
149 public:
150   ClangDiagnosticManagerAdapter(DiagnosticOptions &opts) {
151     DiagnosticOptions *m_options = new DiagnosticOptions(opts);
152     m_options->ShowPresumedLoc = true;
153     m_options->ShowLevel = false;
154     m_os.reset(new llvm::raw_string_ostream(m_output));
155     m_passthrough.reset(
156         new clang::TextDiagnosticPrinter(*m_os, m_options, false));
157   }
158 
159   void ResetManager(DiagnosticManager *manager = nullptr) {
160     m_manager = manager;
161   }
162 
163   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
164                         const clang::Diagnostic &Info) override {
165     if (!m_manager) {
166       // We have no DiagnosticManager before/after parsing but we still could
167       // receive diagnostics (e.g., by the ASTImporter failing to copy decls
168       // when we move the expression result ot the ScratchASTContext). Let's at
169       // least log these diagnostics until we find a way to properly render
170       // them and display them to the user.
171       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
172       if (log) {
173         llvm::SmallVector<char, 32> diag_str;
174         Info.FormatDiagnostic(diag_str);
175         diag_str.push_back('\0');
176         const char *plain_diag = diag_str.data();
177         LLDB_LOG(log, "Received diagnostic outside parsing: {0}", plain_diag);
178       }
179       return;
180     }
181 
182     // Render diagnostic message to m_output.
183     m_output.clear();
184     m_passthrough->HandleDiagnostic(DiagLevel, Info);
185     m_os->flush();
186 
187     lldb_private::DiagnosticSeverity severity;
188     bool make_new_diagnostic = true;
189 
190     switch (DiagLevel) {
191     case DiagnosticsEngine::Level::Fatal:
192     case DiagnosticsEngine::Level::Error:
193       severity = eDiagnosticSeverityError;
194       break;
195     case DiagnosticsEngine::Level::Warning:
196       severity = eDiagnosticSeverityWarning;
197       break;
198     case DiagnosticsEngine::Level::Remark:
199     case DiagnosticsEngine::Level::Ignored:
200       severity = eDiagnosticSeverityRemark;
201       break;
202     case DiagnosticsEngine::Level::Note:
203       m_manager->AppendMessageToDiagnostic(m_output);
204       make_new_diagnostic = false;
205     }
206     if (make_new_diagnostic) {
207       // ClangDiagnostic messages are expected to have no whitespace/newlines
208       // around them.
209       std::string stripped_output = llvm::StringRef(m_output).trim();
210 
211       auto new_diagnostic = std::make_unique<ClangDiagnostic>(
212           stripped_output, severity, Info.getID());
213 
214       // Don't store away warning fixits, since the compiler doesn't have
215       // enough context in an expression for the warning to be useful.
216       // FIXME: Should we try to filter out FixIts that apply to our generated
217       // code, and not the user's expression?
218       if (severity == eDiagnosticSeverityError) {
219         size_t num_fixit_hints = Info.getNumFixItHints();
220         for (size_t i = 0; i < num_fixit_hints; i++) {
221           const clang::FixItHint &fixit = Info.getFixItHint(i);
222           if (!fixit.isNull())
223             new_diagnostic->AddFixitHint(fixit);
224         }
225       }
226 
227       m_manager->AddDiagnostic(std::move(new_diagnostic));
228     }
229   }
230 
231   clang::TextDiagnosticPrinter *GetPassthrough() { return m_passthrough.get(); }
232 
233 private:
234   DiagnosticManager *m_manager = nullptr;
235   std::shared_ptr<clang::TextDiagnosticPrinter> m_passthrough;
236   /// Output stream of m_passthrough.
237   std::shared_ptr<llvm::raw_string_ostream> m_os;
238   /// Output string filled by m_os.
239   std::string m_output;
240 };
241 
242 static void SetupModuleHeaderPaths(CompilerInstance *compiler,
243                                    std::vector<std::string> include_directories,
244                                    lldb::TargetSP target_sp) {
245   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
246 
247   HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();
248 
249   for (const std::string &dir : include_directories) {
250     search_opts.AddPath(dir, frontend::System, false, true);
251     LLDB_LOG(log, "Added user include dir: {0}", dir);
252   }
253 
254   llvm::SmallString<128> module_cache;
255   auto props = ModuleList::GetGlobalModuleListProperties();
256   props.GetClangModulesCachePath().GetPath(module_cache);
257   search_opts.ModuleCachePath = module_cache.str();
258   LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str());
259 
260   search_opts.ResourceDir = GetClangResourceDir().GetPath();
261 
262   search_opts.ImplicitModuleMaps = true;
263 }
264 
265 //===----------------------------------------------------------------------===//
266 // Implementation of ClangExpressionParser
267 //===----------------------------------------------------------------------===//
268 
269 ClangExpressionParser::ClangExpressionParser(
270     ExecutionContextScope *exe_scope, Expression &expr,
271     bool generate_debug_info, std::vector<std::string> include_directories,
272     std::string filename)
273     : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
274       m_pp_callbacks(nullptr),
275       m_include_directories(std::move(include_directories)),
276       m_filename(std::move(filename)) {
277   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
278 
279   // We can't compile expressions without a target.  So if the exe_scope is
280   // null or doesn't have a target, then we just need to get out of here.  I'll
281   // lldb_assert and not make any of the compiler objects since
282   // I can't return errors directly from the constructor.  Further calls will
283   // check if the compiler was made and
284   // bag out if it wasn't.
285 
286   if (!exe_scope) {
287     lldb_assert(exe_scope, "Can't make an expression parser with a null scope.",
288                 __FUNCTION__, __FILE__, __LINE__);
289     return;
290   }
291 
292   lldb::TargetSP target_sp;
293   target_sp = exe_scope->CalculateTarget();
294   if (!target_sp) {
295     lldb_assert(target_sp.get(),
296                 "Can't make an expression parser with a null target.",
297                 __FUNCTION__, __FILE__, __LINE__);
298     return;
299   }
300 
301   // 1. Create a new compiler instance.
302   m_compiler.reset(new CompilerInstance());
303 
304   // When capturing a reproducer, hook up the file collector with clang to
305   // collector modules and headers.
306   if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
307     repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>();
308     m_compiler->setModuleDepCollector(
309         std::make_shared<ModuleDependencyCollectorAdaptor>(
310             fp.GetFileCollector()));
311     DependencyOutputOptions &opts = m_compiler->getDependencyOutputOpts();
312     opts.IncludeSystemHeaders = true;
313     opts.IncludeModuleFiles = true;
314   }
315 
316   // Make sure clang uses the same VFS as LLDB.
317   m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
318 
319   lldb::LanguageType frame_lang =
320       expr.Language(); // defaults to lldb::eLanguageTypeUnknown
321   bool overridden_target_opts = false;
322   lldb_private::LanguageRuntime *lang_rt = nullptr;
323 
324   std::string abi;
325   ArchSpec target_arch;
326   target_arch = target_sp->GetArchitecture();
327 
328   const auto target_machine = target_arch.GetMachine();
329 
330   // If the expression is being evaluated in the context of an existing stack
331   // frame, we introspect to see if the language runtime is available.
332 
333   lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
334   lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
335 
336   // Make sure the user hasn't provided a preferred execution language with
337   // `expression --language X -- ...`
338   if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
339     frame_lang = frame_sp->GetLanguage();
340 
341   if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
342     lang_rt = process_sp->GetLanguageRuntime(frame_lang);
343     LLDB_LOGF(log, "Frame has language of type %s",
344               Language::GetNameForLanguageType(frame_lang));
345   }
346 
347   // 2. Configure the compiler with a set of default options that are
348   // appropriate for most situations.
349   if (target_arch.IsValid()) {
350     std::string triple = target_arch.GetTriple().str();
351     m_compiler->getTargetOpts().Triple = triple;
352     LLDB_LOGF(log, "Using %s as the target triple",
353               m_compiler->getTargetOpts().Triple.c_str());
354   } else {
355     // If we get here we don't have a valid target and just have to guess.
356     // Sometimes this will be ok to just use the host target triple (when we
357     // evaluate say "2+3", but other expressions like breakpoint conditions and
358     // other things that _are_ target specific really shouldn't just be using
359     // the host triple. In such a case the language runtime should expose an
360     // overridden options set (3), below.
361     m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
362     LLDB_LOGF(log, "Using default target triple of %s",
363               m_compiler->getTargetOpts().Triple.c_str());
364   }
365   // Now add some special fixes for known architectures: Any arm32 iOS
366   // environment, but not on arm64
367   if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
368       m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
369       m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
370     m_compiler->getTargetOpts().ABI = "apcs-gnu";
371   }
372   // Supported subsets of x86
373   if (target_machine == llvm::Triple::x86 ||
374       target_machine == llvm::Triple::x86_64) {
375     m_compiler->getTargetOpts().Features.push_back("+sse");
376     m_compiler->getTargetOpts().Features.push_back("+sse2");
377   }
378 
379   // Set the target CPU to generate code for. This will be empty for any CPU
380   // that doesn't really need to make a special
381   // CPU string.
382   m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
383 
384   // Set the target ABI
385   abi = GetClangTargetABI(target_arch);
386   if (!abi.empty())
387     m_compiler->getTargetOpts().ABI = abi;
388 
389   // 3. Now allow the runtime to provide custom configuration options for the
390   // target. In this case, a specialized language runtime is available and we
391   // can query it for extra options. For 99% of use cases, this will not be
392   // needed and should be provided when basic platform detection is not enough.
393   if (lang_rt)
394     overridden_target_opts =
395         lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
396 
397   if (overridden_target_opts)
398     if (log && log->GetVerbose()) {
399       LLDB_LOGV(
400           log, "Using overridden target options for the expression evaluation");
401 
402       auto opts = m_compiler->getTargetOpts();
403       LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
404       LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
405       LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
406       LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
407       LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
408       StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
409       StringList::LogDump(log, opts.Features, "Features");
410     }
411 
412   // 4. Create and install the target on the compiler.
413   m_compiler->createDiagnostics();
414   auto target_info = TargetInfo::CreateTargetInfo(
415       m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
416   if (log) {
417     LLDB_LOGF(log, "Using SIMD alignment: %d",
418               target_info->getSimdDefaultAlign());
419     LLDB_LOGF(log, "Target datalayout string: '%s'",
420               target_info->getDataLayout().getStringRepresentation().c_str());
421     LLDB_LOGF(log, "Target ABI: '%s'", target_info->getABI().str().c_str());
422     LLDB_LOGF(log, "Target vector alignment: %d",
423               target_info->getMaxVectorAlign());
424   }
425   m_compiler->setTarget(target_info);
426 
427   assert(m_compiler->hasTarget());
428 
429   // 5. Set language options.
430   lldb::LanguageType language = expr.Language();
431   LangOptions &lang_opts = m_compiler->getLangOpts();
432 
433   switch (language) {
434   case lldb::eLanguageTypeC:
435   case lldb::eLanguageTypeC89:
436   case lldb::eLanguageTypeC99:
437   case lldb::eLanguageTypeC11:
438     // FIXME: the following language option is a temporary workaround,
439     // to "ask for C, get C++."
440     // For now, the expression parser must use C++ anytime the language is a C
441     // family language, because the expression parser uses features of C++ to
442     // capture values.
443     lang_opts.CPlusPlus = true;
444     break;
445   case lldb::eLanguageTypeObjC:
446     lang_opts.ObjC = true;
447     // FIXME: the following language option is a temporary workaround,
448     // to "ask for ObjC, get ObjC++" (see comment above).
449     lang_opts.CPlusPlus = true;
450 
451     // Clang now sets as default C++14 as the default standard (with
452     // GNU extensions), so we do the same here to avoid mismatches that
453     // cause compiler error when evaluating expressions (e.g. nullptr not found
454     // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
455     // two lines below) so we decide to be consistent with that, but this could
456     // be re-evaluated in the future.
457     lang_opts.CPlusPlus11 = true;
458     break;
459   case lldb::eLanguageTypeC_plus_plus:
460   case lldb::eLanguageTypeC_plus_plus_11:
461   case lldb::eLanguageTypeC_plus_plus_14:
462     lang_opts.CPlusPlus11 = true;
463     m_compiler->getHeaderSearchOpts().UseLibcxx = true;
464     LLVM_FALLTHROUGH;
465   case lldb::eLanguageTypeC_plus_plus_03:
466     lang_opts.CPlusPlus = true;
467     if (process_sp)
468       lang_opts.ObjC =
469           process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
470     break;
471   case lldb::eLanguageTypeObjC_plus_plus:
472   case lldb::eLanguageTypeUnknown:
473   default:
474     lang_opts.ObjC = true;
475     lang_opts.CPlusPlus = true;
476     lang_opts.CPlusPlus11 = true;
477     m_compiler->getHeaderSearchOpts().UseLibcxx = true;
478     break;
479   }
480 
481   lang_opts.Bool = true;
482   lang_opts.WChar = true;
483   lang_opts.Blocks = true;
484   lang_opts.DebuggerSupport =
485       true; // Features specifically for debugger clients
486   if (expr.DesiredResultType() == Expression::eResultTypeId)
487     lang_opts.DebuggerCastResultToId = true;
488 
489   lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
490                                .CharIsSignedByDefault();
491 
492   // Spell checking is a nice feature, but it ends up completing a lot of types
493   // that we didn't strictly speaking need to complete. As a result, we spend a
494   // long time parsing and importing debug information.
495   lang_opts.SpellChecking = false;
496 
497   auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr);
498   if (clang_expr && clang_expr->DidImportCxxModules()) {
499     LLDB_LOG(log, "Adding lang options for importing C++ modules");
500 
501     lang_opts.Modules = true;
502     // We want to implicitly build modules.
503     lang_opts.ImplicitModules = true;
504     // To automatically import all submodules when we import 'std'.
505     lang_opts.ModulesLocalVisibility = false;
506 
507     // We use the @import statements, so we need this:
508     // FIXME: We could use the modules-ts, but that currently doesn't work.
509     lang_opts.ObjC = true;
510 
511     // Options we need to parse libc++ code successfully.
512     // FIXME: We should ask the driver for the appropriate default flags.
513     lang_opts.GNUMode = true;
514     lang_opts.GNUKeywords = true;
515     lang_opts.DoubleSquareBracketAttributes = true;
516     lang_opts.CPlusPlus11 = true;
517 
518     // The Darwin libc expects this macro to be set.
519     lang_opts.GNUCVersion = 40201;
520 
521     SetupModuleHeaderPaths(m_compiler.get(), m_include_directories,
522                            target_sp);
523   }
524 
525   if (process_sp && lang_opts.ObjC) {
526     if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) {
527       if (runtime->GetRuntimeVersion() ==
528           ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
529         lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
530       else
531         lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
532                                   VersionTuple(10, 7));
533 
534       if (runtime->HasNewLiteralsAndIndexing())
535         lang_opts.DebuggerObjCLiteral = true;
536     }
537   }
538 
539   lang_opts.ThreadsafeStatics = false;
540   lang_opts.AccessControl = false; // Debuggers get universal access
541   lang_opts.DollarIdents = true;   // $ indicates a persistent variable name
542   // We enable all builtin functions beside the builtins from libc/libm (e.g.
543   // 'fopen'). Those libc functions are already correctly handled by LLDB, and
544   // additionally enabling them as expandable builtins is breaking Clang.
545   lang_opts.NoBuiltin = true;
546 
547   // Set CodeGen options
548   m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
549   m_compiler->getCodeGenOpts().InstrumentFunctions = false;
550   m_compiler->getCodeGenOpts().setFramePointer(
551                                     CodeGenOptions::FramePointerKind::All);
552   if (generate_debug_info)
553     m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
554   else
555     m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
556 
557   // Disable some warnings.
558   m_compiler->getDiagnostics().setSeverityForGroup(
559       clang::diag::Flavor::WarningOrError, "unused-value",
560       clang::diag::Severity::Ignored, SourceLocation());
561   m_compiler->getDiagnostics().setSeverityForGroup(
562       clang::diag::Flavor::WarningOrError, "odr",
563       clang::diag::Severity::Ignored, SourceLocation());
564 
565   // Inform the target of the language options
566   //
567   // FIXME: We shouldn't need to do this, the target should be immutable once
568   // created. This complexity should be lifted elsewhere.
569   m_compiler->getTarget().adjust(m_compiler->getLangOpts());
570 
571   // 6. Set up the diagnostic buffer for reporting errors
572 
573   auto diag_mgr = new ClangDiagnosticManagerAdapter(
574       m_compiler->getDiagnostics().getDiagnosticOptions());
575   m_compiler->getDiagnostics().setClient(diag_mgr);
576 
577   // 7. Set up the source management objects inside the compiler
578   m_compiler->createFileManager();
579   if (!m_compiler->hasSourceManager())
580     m_compiler->createSourceManager(m_compiler->getFileManager());
581   m_compiler->createPreprocessor(TU_Complete);
582 
583   if (ClangModulesDeclVendor *decl_vendor =
584           target_sp->GetClangModulesDeclVendor()) {
585     ClangPersistentVariables *clang_persistent_vars =
586         llvm::cast<ClangPersistentVariables>(
587             target_sp->GetPersistentExpressionStateForLanguage(
588                 lldb::eLanguageTypeC));
589     std::unique_ptr<PPCallbacks> pp_callbacks(new LLDBPreprocessorCallbacks(
590         *decl_vendor, *clang_persistent_vars, m_compiler->getSourceManager()));
591     m_pp_callbacks =
592         static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
593     m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
594   }
595 
596   // 8. Most of this we get from the CompilerInstance, but we also want to give
597   // the context an ExternalASTSource.
598 
599   auto &PP = m_compiler->getPreprocessor();
600   auto &builtin_context = PP.getBuiltinInfo();
601   builtin_context.initializeBuiltins(PP.getIdentifierTable(),
602                                      m_compiler->getLangOpts());
603 
604   m_compiler->createASTContext();
605   clang::ASTContext &ast_context = m_compiler->getASTContext();
606 
607   m_ast_context.reset(new ClangASTContext(ast_context));
608 
609   std::string module_name("$__lldb_module");
610 
611   m_llvm_context.reset(new LLVMContext());
612   m_code_generator.reset(CreateLLVMCodeGen(
613       m_compiler->getDiagnostics(), module_name,
614       m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
615       m_compiler->getCodeGenOpts(), *m_llvm_context));
616 }
617 
618 ClangExpressionParser::~ClangExpressionParser() {}
619 
620 namespace {
621 
622 /// \class CodeComplete
623 ///
624 /// A code completion consumer for the clang Sema that is responsible for
625 /// creating the completion suggestions when a user requests completion
626 /// of an incomplete `expr` invocation.
627 class CodeComplete : public CodeCompleteConsumer {
628   CodeCompletionTUInfo m_info;
629 
630   std::string m_expr;
631   unsigned m_position = 0;
632   CompletionRequest &m_request;
633   /// The printing policy we use when printing declarations for our completion
634   /// descriptions.
635   clang::PrintingPolicy m_desc_policy;
636 
637   /// Returns true if the given character can be used in an identifier.
638   /// This also returns true for numbers because for completion we usually
639   /// just iterate backwards over iterators.
640   ///
641   /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
642   static bool IsIdChar(char c) {
643     return c == '_' || std::isalnum(c) || c == '$';
644   }
645 
646   /// Returns true if the given character is used to separate arguments
647   /// in the command line of lldb.
648   static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
649 
650   /// Drops all tokens in front of the expression that are unrelated for
651   /// the completion of the cmd line. 'unrelated' means here that the token
652   /// is not interested for the lldb completion API result.
653   StringRef dropUnrelatedFrontTokens(StringRef cmd) {
654     if (cmd.empty())
655       return cmd;
656 
657     // If we are at the start of a word, then all tokens are unrelated to
658     // the current completion logic.
659     if (IsTokenSeparator(cmd.back()))
660       return StringRef();
661 
662     // Remove all previous tokens from the string as they are unrelated
663     // to completing the current token.
664     StringRef to_remove = cmd;
665     while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
666       to_remove = to_remove.drop_back();
667     }
668     cmd = cmd.drop_front(to_remove.size());
669 
670     return cmd;
671   }
672 
673   /// Removes the last identifier token from the given cmd line.
674   StringRef removeLastToken(StringRef cmd) {
675     while (!cmd.empty() && IsIdChar(cmd.back())) {
676       cmd = cmd.drop_back();
677     }
678     return cmd;
679   }
680 
681   /// Attemps to merge the given completion from the given position into the
682   /// existing command. Returns the completion string that can be returned to
683   /// the lldb completion API.
684   std::string mergeCompletion(StringRef existing, unsigned pos,
685                               StringRef completion) {
686     StringRef existing_command = existing.substr(0, pos);
687     // We rewrite the last token with the completion, so let's drop that
688     // token from the command.
689     existing_command = removeLastToken(existing_command);
690     // We also should remove all previous tokens from the command as they
691     // would otherwise be added to the completion that already has the
692     // completion.
693     existing_command = dropUnrelatedFrontTokens(existing_command);
694     return existing_command.str() + completion.str();
695   }
696 
697 public:
698   /// Constructs a CodeComplete consumer that can be attached to a Sema.
699   ///
700   /// \param[out] expr
701   ///    The whole expression string that we are currently parsing. This
702   ///    string needs to be equal to the input the user typed, and NOT the
703   ///    final code that Clang is parsing.
704   /// \param[out] position
705   ///    The character position of the user cursor in the `expr` parameter.
706   ///
707   CodeComplete(CompletionRequest &request, clang::LangOptions ops,
708                std::string expr, unsigned position)
709       : CodeCompleteConsumer(CodeCompleteOptions()),
710         m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
711         m_position(position), m_request(request), m_desc_policy(ops) {
712 
713     // Ensure that the printing policy is producing a description that is as
714     // short as possible.
715     m_desc_policy.SuppressScope = true;
716     m_desc_policy.SuppressTagKeyword = true;
717     m_desc_policy.FullyQualifiedName = false;
718     m_desc_policy.TerseOutput = true;
719     m_desc_policy.IncludeNewlines = false;
720     m_desc_policy.UseVoidForZeroParams = false;
721     m_desc_policy.Bool = true;
722   }
723 
724   /// Deregisters and destroys this code-completion consumer.
725   ~CodeComplete() override {}
726 
727   /// \name Code-completion filtering
728   /// Check if the result should be filtered out.
729   bool isResultFilteredOut(StringRef Filter,
730                            CodeCompletionResult Result) override {
731     // This code is mostly copied from CodeCompleteConsumer.
732     switch (Result.Kind) {
733     case CodeCompletionResult::RK_Declaration:
734       return !(
735           Result.Declaration->getIdentifier() &&
736           Result.Declaration->getIdentifier()->getName().startswith(Filter));
737     case CodeCompletionResult::RK_Keyword:
738       return !StringRef(Result.Keyword).startswith(Filter);
739     case CodeCompletionResult::RK_Macro:
740       return !Result.Macro->getName().startswith(Filter);
741     case CodeCompletionResult::RK_Pattern:
742       return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
743     }
744     // If we trigger this assert or the above switch yields a warning, then
745     // CodeCompletionResult has been enhanced with more kinds of completion
746     // results. Expand the switch above in this case.
747     assert(false && "Unknown completion result type?");
748     // If we reach this, then we should just ignore whatever kind of unknown
749     // result we got back. We probably can't turn it into any kind of useful
750     // completion suggestion with the existing code.
751     return true;
752   }
753 
754   /// \name Code-completion callbacks
755   /// Process the finalized code-completion results.
756   void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
757                                   CodeCompletionResult *Results,
758                                   unsigned NumResults) override {
759 
760     // The Sema put the incomplete token we try to complete in here during
761     // lexing, so we need to retrieve it here to know what we are completing.
762     StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
763 
764     // Iterate over all the results. Filter out results we don't want and
765     // process the rest.
766     for (unsigned I = 0; I != NumResults; ++I) {
767       // Filter the results with the information from the Sema.
768       if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
769         continue;
770 
771       CodeCompletionResult &R = Results[I];
772       std::string ToInsert;
773       std::string Description;
774       // Handle the different completion kinds that come from the Sema.
775       switch (R.Kind) {
776       case CodeCompletionResult::RK_Declaration: {
777         const NamedDecl *D = R.Declaration;
778         ToInsert = R.Declaration->getNameAsString();
779         // If we have a function decl that has no arguments we want to
780         // complete the empty parantheses for the user. If the function has
781         // arguments, we at least complete the opening bracket.
782         if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
783           if (F->getNumParams() == 0)
784             ToInsert += "()";
785           else
786             ToInsert += "(";
787           raw_string_ostream OS(Description);
788           F->print(OS, m_desc_policy, false);
789           OS.flush();
790         } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
791           Description = V->getType().getAsString(m_desc_policy);
792         } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {
793           Description = F->getType().getAsString(m_desc_policy);
794         } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
795           // If we try to complete a namespace, then we can directly append
796           // the '::'.
797           if (!N->isAnonymousNamespace())
798             ToInsert += "::";
799         }
800         break;
801       }
802       case CodeCompletionResult::RK_Keyword:
803         ToInsert = R.Keyword;
804         break;
805       case CodeCompletionResult::RK_Macro:
806         ToInsert = R.Macro->getName().str();
807         break;
808       case CodeCompletionResult::RK_Pattern:
809         ToInsert = R.Pattern->getTypedText();
810         break;
811       }
812       // At this point all information is in the ToInsert string.
813 
814       // We also filter some internal lldb identifiers here. The user
815       // shouldn't see these.
816       if (StringRef(ToInsert).startswith("$__lldb_"))
817         continue;
818       if (!ToInsert.empty()) {
819         // Merge the suggested Token into the existing command line to comply
820         // with the kind of result the lldb API expects.
821         std::string CompletionSuggestion =
822             mergeCompletion(m_expr, m_position, ToInsert);
823         m_request.AddCompletion(CompletionSuggestion, Description);
824       }
825     }
826   }
827 
828   /// \param S the semantic-analyzer object for which code-completion is being
829   /// done.
830   ///
831   /// \param CurrentArg the index of the current argument.
832   ///
833   /// \param Candidates an array of overload candidates.
834   ///
835   /// \param NumCandidates the number of overload candidates
836   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
837                                  OverloadCandidate *Candidates,
838                                  unsigned NumCandidates,
839                                  SourceLocation OpenParLoc) override {
840     // At the moment we don't filter out any overloaded candidates.
841   }
842 
843   CodeCompletionAllocator &getAllocator() override {
844     return m_info.getAllocator();
845   }
846 
847   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
848 };
849 } // namespace
850 
851 bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line,
852                                      unsigned pos, unsigned typed_pos) {
853   DiagnosticManager mgr;
854   // We need the raw user expression here because that's what the CodeComplete
855   // class uses to provide completion suggestions.
856   // However, the `Text` method only gives us the transformed expression here.
857   // To actually get the raw user input here, we have to cast our expression to
858   // the LLVMUserExpression which exposes the right API. This should never fail
859   // as we always have a ClangUserExpression whenever we call this.
860   ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr);
861   CodeComplete CC(request, m_compiler->getLangOpts(), llvm_expr->GetUserText(),
862                   typed_pos);
863   // We don't need a code generator for parsing.
864   m_code_generator.reset();
865   // Start parsing the expression with our custom code completion consumer.
866   ParseInternal(mgr, &CC, line, pos);
867   return true;
868 }
869 
870 unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
871   return ParseInternal(diagnostic_manager);
872 }
873 
874 unsigned
875 ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,
876                                      CodeCompleteConsumer *completion_consumer,
877                                      unsigned completion_line,
878                                      unsigned completion_column) {
879   ClangDiagnosticManagerAdapter *adapter =
880       static_cast<ClangDiagnosticManagerAdapter *>(
881           m_compiler->getDiagnostics().getClient());
882   auto diag_buf = adapter->GetPassthrough();
883 
884   adapter->ResetManager(&diagnostic_manager);
885 
886   const char *expr_text = m_expr.Text();
887 
888   clang::SourceManager &source_mgr = m_compiler->getSourceManager();
889   bool created_main_file = false;
890 
891   // Clang wants to do completion on a real file known by Clang's file manager,
892   // so we have to create one to make this work.
893   // TODO: We probably could also simulate to Clang's file manager that there
894   // is a real file that contains our code.
895   bool should_create_file = completion_consumer != nullptr;
896 
897   // We also want a real file on disk if we generate full debug info.
898   should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
899                         codegenoptions::FullDebugInfo;
900 
901   if (should_create_file) {
902     int temp_fd = -1;
903     llvm::SmallString<128> result_path;
904     if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
905       tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
906       std::string temp_source_path = tmpdir_file_spec.GetPath();
907       llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
908     } else {
909       llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
910     }
911 
912     if (temp_fd != -1) {
913       lldb_private::NativeFile file(temp_fd, File::eOpenOptionWrite, true);
914       const size_t expr_text_len = strlen(expr_text);
915       size_t bytes_written = expr_text_len;
916       if (file.Write(expr_text, bytes_written).Success()) {
917         if (bytes_written == expr_text_len) {
918           file.Close();
919           if (auto fileEntry =
920                   m_compiler->getFileManager().getFile(result_path)) {
921             source_mgr.setMainFileID(source_mgr.createFileID(
922                 *fileEntry,
923                 SourceLocation(), SrcMgr::C_User));
924             created_main_file = true;
925           }
926         }
927       }
928     }
929   }
930 
931   if (!created_main_file) {
932     std::unique_ptr<MemoryBuffer> memory_buffer =
933         MemoryBuffer::getMemBufferCopy(expr_text, m_filename);
934     source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
935   }
936 
937   diag_buf->BeginSourceFile(m_compiler->getLangOpts(),
938                             &m_compiler->getPreprocessor());
939 
940   ClangExpressionHelper *type_system_helper =
941       dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
942 
943   // If we want to parse for code completion, we need to attach our code
944   // completion consumer to the Sema and specify a completion position.
945   // While parsing the Sema will call this consumer with the provided
946   // completion suggestions.
947   if (completion_consumer) {
948     auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID());
949     auto &PP = m_compiler->getPreprocessor();
950     // Lines and columns start at 1 in Clang, but code completion positions are
951     // indexed from 0, so we need to add 1 to the line and column here.
952     ++completion_line;
953     ++completion_column;
954     PP.SetCodeCompletionPoint(main_file, completion_line, completion_column);
955   }
956 
957   ASTConsumer *ast_transformer =
958       type_system_helper->ASTTransformer(m_code_generator.get());
959 
960   std::unique_ptr<clang::ASTConsumer> Consumer;
961   if (ast_transformer) {
962     Consumer.reset(new ASTConsumerForwarder(ast_transformer));
963   } else if (m_code_generator) {
964     Consumer.reset(new ASTConsumerForwarder(m_code_generator.get()));
965   } else {
966     Consumer.reset(new ASTConsumer());
967   }
968 
969   clang::ASTContext &ast_context = m_compiler->getASTContext();
970 
971   m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context,
972                                *Consumer, TU_Complete, completion_consumer));
973   m_compiler->setASTConsumer(std::move(Consumer));
974 
975   if (ast_context.getLangOpts().Modules) {
976     m_compiler->createModuleManager();
977     m_ast_context->setSema(&m_compiler->getSema());
978   }
979 
980   ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
981   if (decl_map) {
982     decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer());
983 
984     clang::ExternalASTSource *ast_source = decl_map->CreateProxy();
985 
986     if (ast_context.getExternalSource()) {
987       auto module_wrapper =
988           new ExternalASTSourceWrapper(ast_context.getExternalSource());
989 
990       auto ast_source_wrapper = new ExternalASTSourceWrapper(ast_source);
991 
992       auto multiplexer =
993           new SemaSourceWithPriorities(*module_wrapper, *ast_source_wrapper);
994       IntrusiveRefCntPtr<ExternalASTSource> Source(multiplexer);
995       ast_context.setExternalSource(Source);
996     } else {
997       ast_context.setExternalSource(ast_source);
998     }
999     decl_map->InstallASTContext(ast_context, m_compiler->getFileManager());
1000   }
1001 
1002   // Check that the ASTReader is properly attached to ASTContext and Sema.
1003   if (ast_context.getLangOpts().Modules) {
1004     assert(m_compiler->getASTContext().getExternalSource() &&
1005            "ASTContext doesn't know about the ASTReader?");
1006     assert(m_compiler->getSema().getExternalSource() &&
1007            "Sema doesn't know about the ASTReader?");
1008   }
1009 
1010   {
1011     llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(
1012         &m_compiler->getSema());
1013     ParseAST(m_compiler->getSema(), false, false);
1014   }
1015 
1016   // Make sure we have no pointer to the Sema we are about to destroy.
1017   if (ast_context.getLangOpts().Modules)
1018     m_ast_context->setSema(nullptr);
1019   // Destroy the Sema. This is necessary because we want to emulate the
1020   // original behavior of ParseAST (which also destroys the Sema after parsing).
1021   m_compiler->setSema(nullptr);
1022 
1023   diag_buf->EndSourceFile();
1024 
1025   unsigned num_errors = diag_buf->getNumErrors();
1026 
1027   if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
1028     num_errors++;
1029     diagnostic_manager.PutString(eDiagnosticSeverityError,
1030                                  "while importing modules:");
1031     diagnostic_manager.AppendMessageToDiagnostic(
1032         m_pp_callbacks->getErrorString());
1033   }
1034 
1035   if (!num_errors) {
1036     if (type_system_helper->DeclMap() &&
1037         !type_system_helper->DeclMap()->ResolveUnknownTypes()) {
1038       diagnostic_manager.Printf(eDiagnosticSeverityError,
1039                                 "Couldn't infer the type of a variable");
1040       num_errors++;
1041     }
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("Can't run the expression locally: %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