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