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 #pragma clang diagnostic push
45 #pragma clang diagnostic ignored "-Wglobal-constructors"
46 #include "llvm/ExecutionEngine/MCJIT.h"
47 #pragma clang diagnostic pop
48 
49 #include "llvm/IR/LLVMContext.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/Support/DynamicLibrary.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/Host.h"
54 #include "llvm/Support/MemoryBuffer.h"
55 #include "llvm/Support/Signals.h"
56 
57 #include "ClangDiagnostic.h"
58 #include "ClangExpressionParser.h"
59 #include "ClangUserExpression.h"
60 
61 #include "ASTUtils.h"
62 #include "ClangASTSource.h"
63 #include "ClangDiagnostic.h"
64 #include "ClangExpressionDeclMap.h"
65 #include "ClangExpressionHelper.h"
66 #include "ClangExpressionParser.h"
67 #include "ClangHost.h"
68 #include "ClangModulesDeclVendor.h"
69 #include "ClangPersistentVariables.h"
70 #include "IRForTarget.h"
71 #include "ModuleDependencyCollector.h"
72 
73 #include "lldb/Core/Debugger.h"
74 #include "lldb/Core/Disassembler.h"
75 #include "lldb/Core/Module.h"
76 #include "lldb/Core/StreamFile.h"
77 #include "lldb/Expression/IRDynamicChecks.h"
78 #include "lldb/Expression/IRExecutionUnit.h"
79 #include "lldb/Expression/IRInterpreter.h"
80 #include "lldb/Host/File.h"
81 #include "lldb/Host/HostInfo.h"
82 #include "lldb/Symbol/ClangASTContext.h"
83 #include "lldb/Symbol/SymbolVendor.h"
84 #include "lldb/Target/ExecutionContext.h"
85 #include "lldb/Target/Language.h"
86 #include "lldb/Target/ObjCLanguageRuntime.h"
87 #include "lldb/Target/Process.h"
88 #include "lldb/Target/Target.h"
89 #include "lldb/Target/ThreadPlanCallFunction.h"
90 #include "lldb/Utility/DataBufferHeap.h"
91 #include "lldb/Utility/LLDBAssert.h"
92 #include "lldb/Utility/Log.h"
93 #include "lldb/Utility/Reproducer.h"
94 #include "lldb/Utility/Stream.h"
95 #include "lldb/Utility/StreamString.h"
96 #include "lldb/Utility/StringList.h"
97 
98 #include <cctype>
99 #include <memory>
100 
101 using namespace clang;
102 using namespace llvm;
103 using namespace lldb_private;
104 
105 //===----------------------------------------------------------------------===//
106 // Utility Methods for Clang
107 //===----------------------------------------------------------------------===//
108 
109 class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
110   ClangModulesDeclVendor &m_decl_vendor;
111   ClangPersistentVariables &m_persistent_vars;
112   StreamString m_error_stream;
113   bool m_has_errors = false;
114 
115 public:
116   LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
117                             ClangPersistentVariables &persistent_vars)
118       : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars) {}
119 
120   void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
121                     const clang::Module * /*null*/) override {
122     SourceModule module;
123 
124     for (const std::pair<IdentifierInfo *, SourceLocation> &component : path)
125       module.path.push_back(ConstString(component.first->getName()));
126 
127     StreamString error_stream;
128 
129     ClangModulesDeclVendor::ModuleVector exported_modules;
130     if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream))
131       m_has_errors = true;
132 
133     for (ClangModulesDeclVendor::ModuleID module : exported_modules)
134       m_persistent_vars.AddHandLoadedClangModule(module);
135   }
136 
137   bool hasErrors() { return m_has_errors; }
138 
139   llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
140 };
141 
142 class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
143 public:
144   ClangDiagnosticManagerAdapter()
145       : m_passthrough(new clang::TextDiagnosticBuffer) {}
146 
147   ClangDiagnosticManagerAdapter(
148       const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough)
149       : m_passthrough(passthrough) {}
150 
151   void ResetManager(DiagnosticManager *manager = nullptr) {
152     m_manager = manager;
153   }
154 
155   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
156                         const clang::Diagnostic &Info) {
157     if (m_manager) {
158       llvm::SmallVector<char, 32> diag_str;
159       Info.FormatDiagnostic(diag_str);
160       diag_str.push_back('\0');
161       const char *data = diag_str.data();
162 
163       lldb_private::DiagnosticSeverity severity;
164       bool make_new_diagnostic = true;
165 
166       switch (DiagLevel) {
167       case DiagnosticsEngine::Level::Fatal:
168       case DiagnosticsEngine::Level::Error:
169         severity = eDiagnosticSeverityError;
170         break;
171       case DiagnosticsEngine::Level::Warning:
172         severity = eDiagnosticSeverityWarning;
173         break;
174       case DiagnosticsEngine::Level::Remark:
175       case DiagnosticsEngine::Level::Ignored:
176         severity = eDiagnosticSeverityRemark;
177         break;
178       case DiagnosticsEngine::Level::Note:
179         m_manager->AppendMessageToDiagnostic(data);
180         make_new_diagnostic = false;
181       }
182       if (make_new_diagnostic) {
183         ClangDiagnostic *new_diagnostic =
184             new ClangDiagnostic(data, severity, Info.getID());
185         m_manager->AddDiagnostic(new_diagnostic);
186 
187         // Don't store away warning fixits, since the compiler doesn't have
188         // enough context in an expression for the warning to be useful.
189         // FIXME: Should we try to filter out FixIts that apply to our generated
190         // code, and not the user's expression?
191         if (severity == eDiagnosticSeverityError) {
192           size_t num_fixit_hints = Info.getNumFixItHints();
193           for (size_t i = 0; i < num_fixit_hints; i++) {
194             const clang::FixItHint &fixit = Info.getFixItHint(i);
195             if (!fixit.isNull())
196               new_diagnostic->AddFixitHint(fixit);
197           }
198         }
199       }
200     }
201 
202     m_passthrough->HandleDiagnostic(DiagLevel, Info);
203   }
204 
205   void FlushDiagnostics(DiagnosticsEngine &Diags) {
206     m_passthrough->FlushDiagnostics(Diags);
207   }
208 
209   DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
210     return new ClangDiagnosticManagerAdapter(m_passthrough);
211   }
212 
213   clang::TextDiagnosticBuffer *GetPassthrough() { return m_passthrough.get(); }
214 
215 private:
216   DiagnosticManager *m_manager = nullptr;
217   std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough;
218 };
219 
220 static void
221 SetupModuleHeaderPaths(CompilerInstance *compiler,
222                        std::vector<ConstString> include_directories,
223                        lldb::TargetSP target_sp) {
224   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
225 
226   HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();
227 
228   for (ConstString dir : include_directories) {
229     search_opts.AddPath(dir.AsCString(), frontend::System, false, true);
230     LLDB_LOG(log, "Added user include dir: {0}", dir);
231   }
232 
233   llvm::SmallString<128> module_cache;
234   auto props = ModuleList::GetGlobalModuleListProperties();
235   props.GetClangModulesCachePath().GetPath(module_cache);
236   search_opts.ModuleCachePath = module_cache.str();
237   LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str());
238 
239   FileSpec clang_resource_dir = GetClangResourceDir();
240   std::string resource_dir = clang_resource_dir.GetPath();
241   if (FileSystem::Instance().IsDirectory(resource_dir)) {
242     search_opts.ResourceDir = resource_dir;
243     std::string resource_include = resource_dir + "/include";
244     search_opts.AddPath(resource_include, frontend::System, false, true);
245 
246     LLDB_LOG(log, "Added resource include dir: {0}", resource_include);
247   }
248 
249   search_opts.ImplicitModuleMaps = true;
250 
251   std::vector<std::string> system_include_directories =
252       target_sp->GetPlatform()->GetSystemIncludeDirectories(
253           lldb::eLanguageTypeC_plus_plus);
254 
255   for (const std::string &include_dir : system_include_directories) {
256     search_opts.AddPath(include_dir, frontend::System, false, true);
257 
258     LLDB_LOG(log, "Added system include dir: {0}", include_dir);
259   }
260 }
261 
262 //===----------------------------------------------------------------------===//
263 // Implementation of ClangExpressionParser
264 //===----------------------------------------------------------------------===//
265 
266 ClangExpressionParser::ClangExpressionParser(
267     ExecutionContextScope *exe_scope, Expression &expr,
268     bool generate_debug_info, std::vector<ConstString> include_directories)
269     : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
270       m_pp_callbacks(nullptr),
271       m_include_directories(std::move(include_directories)) {
272   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
273 
274   // We can't compile expressions without a target.  So if the exe_scope is
275   // null or doesn't have a target, then we just need to get out of here.  I'll
276   // lldb_assert and not make any of the compiler objects since
277   // I can't return errors directly from the constructor.  Further calls will
278   // check if the compiler was made and
279   // bag out if it wasn't.
280 
281   if (!exe_scope) {
282     lldb_assert(exe_scope, "Can't make an expression parser with a null scope.",
283                 __FUNCTION__, __FILE__, __LINE__);
284     return;
285   }
286 
287   lldb::TargetSP target_sp;
288   target_sp = exe_scope->CalculateTarget();
289   if (!target_sp) {
290     lldb_assert(target_sp.get(),
291                 "Can't make an expression parser with a null target.",
292                 __FUNCTION__, __FILE__, __LINE__);
293     return;
294   }
295 
296   // 1. Create a new compiler instance.
297   m_compiler.reset(new CompilerInstance());
298 
299   // When capturing a reproducer, hook up the file collector with clang to
300   // collector modules and headers.
301   if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
302     repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>();
303     m_compiler->setModuleDepCollector(
304         std::make_shared<ModuleDependencyCollectorAdaptor>(
305             fp.GetFileCollector()));
306     DependencyOutputOptions &opts = m_compiler->getDependencyOutputOpts();
307     opts.IncludeSystemHeaders = true;
308     opts.IncludeModuleFiles = true;
309   }
310 
311   // Make sure clang uses the same VFS as LLDB.
312   m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
313 
314   lldb::LanguageType frame_lang =
315       expr.Language(); // defaults to lldb::eLanguageTypeUnknown
316   bool overridden_target_opts = false;
317   lldb_private::LanguageRuntime *lang_rt = nullptr;
318 
319   std::string abi;
320   ArchSpec target_arch;
321   target_arch = target_sp->GetArchitecture();
322 
323   const auto target_machine = target_arch.GetMachine();
324 
325   // If the expression is being evaluated in the context of an existing stack
326   // frame, we introspect to see if the language runtime is available.
327 
328   lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
329   lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
330 
331   // Make sure the user hasn't provided a preferred execution language with
332   // `expression --language X -- ...`
333   if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
334     frame_lang = frame_sp->GetLanguage();
335 
336   if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
337     lang_rt = process_sp->GetLanguageRuntime(frame_lang);
338     if (log)
339       log->Printf("Frame has language of type %s",
340                   Language::GetNameForLanguageType(frame_lang));
341   }
342 
343   // 2. Configure the compiler with a set of default options that are
344   // appropriate for most situations.
345   if (target_arch.IsValid()) {
346     std::string triple = target_arch.GetTriple().str();
347     m_compiler->getTargetOpts().Triple = triple;
348     if (log)
349       log->Printf("Using %s as the target triple",
350                   m_compiler->getTargetOpts().Triple.c_str());
351   } else {
352     // If we get here we don't have a valid target and just have to guess.
353     // Sometimes this will be ok to just use the host target triple (when we
354     // evaluate say "2+3", but other expressions like breakpoint conditions and
355     // other things that _are_ target specific really shouldn't just be using
356     // the host triple. In such a case the language runtime should expose an
357     // overridden options set (3), below.
358     m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
359     if (log)
360       log->Printf("Using default target triple of %s",
361                   m_compiler->getTargetOpts().Triple.c_str());
362   }
363   // Now add some special fixes for known architectures: Any arm32 iOS
364   // environment, but not on arm64
365   if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
366       m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
367       m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
368     m_compiler->getTargetOpts().ABI = "apcs-gnu";
369   }
370   // Supported subsets of x86
371   if (target_machine == llvm::Triple::x86 ||
372       target_machine == llvm::Triple::x86_64) {
373     m_compiler->getTargetOpts().Features.push_back("+sse");
374     m_compiler->getTargetOpts().Features.push_back("+sse2");
375   }
376 
377   // Set the target CPU to generate code for. This will be empty for any CPU
378   // that doesn't really need to make a special
379   // CPU string.
380   m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
381 
382   // Set the target ABI
383   abi = GetClangTargetABI(target_arch);
384   if (!abi.empty())
385     m_compiler->getTargetOpts().ABI = abi;
386 
387   // 3. Now allow the runtime to provide custom configuration options for the
388   // target. In this case, a specialized language runtime is available and we
389   // can query it for extra options. For 99% of use cases, this will not be
390   // needed and should be provided when basic platform detection is not enough.
391   if (lang_rt)
392     overridden_target_opts =
393         lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
394 
395   if (overridden_target_opts)
396     if (log && log->GetVerbose()) {
397       LLDB_LOGV(
398           log, "Using overridden target options for the expression evaluation");
399 
400       auto opts = m_compiler->getTargetOpts();
401       LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
402       LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
403       LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
404       LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
405       LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
406       StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
407       StringList::LogDump(log, opts.Features, "Features");
408     }
409 
410   // 4. Create and install the target on the compiler.
411   m_compiler->createDiagnostics();
412   auto target_info = TargetInfo::CreateTargetInfo(
413       m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
414   if (log) {
415     log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign());
416     log->Printf("Target datalayout string: '%s'",
417                 target_info->getDataLayout().getStringRepresentation().c_str());
418     log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str());
419     log->Printf("Target vector alignment: %d",
420                 target_info->getMaxVectorAlign());
421   }
422   m_compiler->setTarget(target_info);
423 
424   assert(m_compiler->hasTarget());
425 
426   // 5. Set language options.
427   lldb::LanguageType language = expr.Language();
428   LangOptions &lang_opts = m_compiler->getLangOpts();
429 
430   switch (language) {
431   case lldb::eLanguageTypeC:
432   case lldb::eLanguageTypeC89:
433   case lldb::eLanguageTypeC99:
434   case lldb::eLanguageTypeC11:
435     // FIXME: the following language option is a temporary workaround,
436     // to "ask for C, get C++."
437     // For now, the expression parser must use C++ anytime the language is a C
438     // family language, because the expression parser uses features of C++ to
439     // capture values.
440     lang_opts.CPlusPlus = true;
441     break;
442   case lldb::eLanguageTypeObjC:
443     lang_opts.ObjC = true;
444     // FIXME: the following language option is a temporary workaround,
445     // to "ask for ObjC, get ObjC++" (see comment above).
446     lang_opts.CPlusPlus = true;
447 
448     // Clang now sets as default C++14 as the default standard (with
449     // GNU extensions), so we do the same here to avoid mismatches that
450     // cause compiler error when evaluating expressions (e.g. nullptr not found
451     // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
452     // two lines below) so we decide to be consistent with that, but this could
453     // be re-evaluated in the future.
454     lang_opts.CPlusPlus11 = true;
455     break;
456   case lldb::eLanguageTypeC_plus_plus:
457   case lldb::eLanguageTypeC_plus_plus_11:
458   case lldb::eLanguageTypeC_plus_plus_14:
459     lang_opts.CPlusPlus11 = true;
460     m_compiler->getHeaderSearchOpts().UseLibcxx = true;
461     LLVM_FALLTHROUGH;
462   case lldb::eLanguageTypeC_plus_plus_03:
463     lang_opts.CPlusPlus = true;
464     if (process_sp)
465       lang_opts.ObjC =
466           process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
467     break;
468   case lldb::eLanguageTypeObjC_plus_plus:
469   case lldb::eLanguageTypeUnknown:
470   default:
471     lang_opts.ObjC = true;
472     lang_opts.CPlusPlus = true;
473     lang_opts.CPlusPlus11 = true;
474     m_compiler->getHeaderSearchOpts().UseLibcxx = true;
475     break;
476   }
477 
478   lang_opts.Bool = true;
479   lang_opts.WChar = true;
480   lang_opts.Blocks = true;
481   lang_opts.DebuggerSupport =
482       true; // Features specifically for debugger clients
483   if (expr.DesiredResultType() == Expression::eResultTypeId)
484     lang_opts.DebuggerCastResultToId = true;
485 
486   lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
487                                .CharIsSignedByDefault();
488 
489   // Spell checking is a nice feature, but it ends up completing a lot of types
490   // that we didn't strictly speaking need to complete. As a result, we spend a
491   // long time parsing and importing debug information.
492   lang_opts.SpellChecking = false;
493 
494   auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr);
495   if (clang_expr && clang_expr->DidImportCxxModules()) {
496     LLDB_LOG(log, "Adding lang options for importing C++ modules");
497 
498     lang_opts.Modules = true;
499     // We want to implicitly build modules.
500     lang_opts.ImplicitModules = true;
501     // To automatically import all submodules when we import 'std'.
502     lang_opts.ModulesLocalVisibility = false;
503 
504     // We use the @import statements, so we need this:
505     // FIXME: We could use the modules-ts, but that currently doesn't work.
506     lang_opts.ObjC = true;
507 
508     // Options we need to parse libc++ code successfully.
509     // FIXME: We should ask the driver for the appropriate default flags.
510     lang_opts.GNUMode = true;
511     lang_opts.GNUKeywords = true;
512     lang_opts.DoubleSquareBracketAttributes = true;
513     lang_opts.CPlusPlus11 = true;
514 
515     SetupModuleHeaderPaths(m_compiler.get(), m_include_directories,
516                            target_sp);
517   }
518 
519   if (process_sp && lang_opts.ObjC) {
520     if (process_sp->GetObjCLanguageRuntime()) {
521       if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() ==
522           ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
523         lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
524       else
525         lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
526                                   VersionTuple(10, 7));
527 
528       if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
529         lang_opts.DebuggerObjCLiteral = true;
530     }
531   }
532 
533   lang_opts.ThreadsafeStatics = false;
534   lang_opts.AccessControl = false; // Debuggers get universal access
535   lang_opts.DollarIdents = true;   // $ indicates a persistent variable name
536   // We enable all builtin functions beside the builtins from libc/libm (e.g.
537   // 'fopen'). Those libc functions are already correctly handled by LLDB, and
538   // additionally enabling them as expandable builtins is breaking Clang.
539   lang_opts.NoBuiltin = true;
540 
541   // Set CodeGen options
542   m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
543   m_compiler->getCodeGenOpts().InstrumentFunctions = false;
544   m_compiler->getCodeGenOpts().DisableFPElim = true;
545   m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
546   if (generate_debug_info)
547     m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
548   else
549     m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
550 
551   // Disable some warnings.
552   m_compiler->getDiagnostics().setSeverityForGroup(
553       clang::diag::Flavor::WarningOrError, "unused-value",
554       clang::diag::Severity::Ignored, SourceLocation());
555   m_compiler->getDiagnostics().setSeverityForGroup(
556       clang::diag::Flavor::WarningOrError, "odr",
557       clang::diag::Severity::Ignored, SourceLocation());
558 
559   // Inform the target of the language options
560   //
561   // FIXME: We shouldn't need to do this, the target should be immutable once
562   // created. This complexity should be lifted elsewhere.
563   m_compiler->getTarget().adjust(m_compiler->getLangOpts());
564 
565   // 6. Set up the diagnostic buffer for reporting errors
566 
567   m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter);
568 
569   // 7. Set up the source management objects inside the compiler
570   m_compiler->createFileManager();
571   if (!m_compiler->hasSourceManager())
572     m_compiler->createSourceManager(m_compiler->getFileManager());
573   m_compiler->createPreprocessor(TU_Complete);
574 
575   if (ClangModulesDeclVendor *decl_vendor =
576           target_sp->GetClangModulesDeclVendor()) {
577     ClangPersistentVariables *clang_persistent_vars =
578         llvm::cast<ClangPersistentVariables>(
579             target_sp->GetPersistentExpressionStateForLanguage(
580                 lldb::eLanguageTypeC));
581     std::unique_ptr<PPCallbacks> pp_callbacks(
582         new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars));
583     m_pp_callbacks =
584         static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
585     m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
586   }
587 
588   // 8. Most of this we get from the CompilerInstance, but we also want to give
589   // the context an ExternalASTSource.
590 
591   auto &PP = m_compiler->getPreprocessor();
592   auto &builtin_context = PP.getBuiltinInfo();
593   builtin_context.initializeBuiltins(PP.getIdentifierTable(),
594                                      m_compiler->getLangOpts());
595 
596   m_compiler->createASTContext();
597   clang::ASTContext &ast_context = m_compiler->getASTContext();
598 
599   m_ast_context.reset(
600       new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
601   m_ast_context->setASTContext(&ast_context);
602 
603   std::string module_name("$__lldb_module");
604 
605   m_llvm_context.reset(new LLVMContext());
606   m_code_generator.reset(CreateLLVMCodeGen(
607       m_compiler->getDiagnostics(), module_name,
608       m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
609       m_compiler->getCodeGenOpts(), *m_llvm_context));
610 }
611 
612 ClangExpressionParser::~ClangExpressionParser() {}
613 
614 namespace {
615 
616 //----------------------------------------------------------------------
617 /// \class CodeComplete
618 ///
619 /// A code completion consumer for the clang Sema that is responsible for
620 /// creating the completion suggestions when a user requests completion
621 /// of an incomplete `expr` invocation.
622 //----------------------------------------------------------------------
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(), false),
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   virtual ~CodeComplete() {}
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   clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough();
882   diag_buf->FlushDiagnostics(m_compiler->getDiagnostics());
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::File file(temp_fd, 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           source_mgr.setMainFileID(source_mgr.createFileID(
920               m_compiler->getFileManager().getFile(result_path),
921               SourceLocation(), SrcMgr::C_User));
922           created_main_file = true;
923         }
924       }
925     }
926   }
927 
928   if (!created_main_file) {
929     std::unique_ptr<MemoryBuffer> memory_buffer =
930         MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
931     source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
932   }
933 
934   diag_buf->BeginSourceFile(m_compiler->getLangOpts(),
935                             &m_compiler->getPreprocessor());
936 
937   ClangExpressionHelper *type_system_helper =
938       dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
939 
940   // If we want to parse for code completion, we need to attach our code
941   // completion consumer to the Sema and specify a completion position.
942   // While parsing the Sema will call this consumer with the provided
943   // completion suggestions.
944   if (completion_consumer) {
945     auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID());
946     auto &PP = m_compiler->getPreprocessor();
947     // Lines and columns start at 1 in Clang, but code completion positions are
948     // indexed from 0, so we need to add 1 to the line and column here.
949     ++completion_line;
950     ++completion_column;
951     PP.SetCodeCompletionPoint(main_file, completion_line, completion_column);
952   }
953 
954   ASTConsumer *ast_transformer =
955       type_system_helper->ASTTransformer(m_code_generator.get());
956 
957   std::unique_ptr<clang::ASTConsumer> Consumer;
958   if (ast_transformer) {
959     Consumer.reset(new ASTConsumerForwarder(ast_transformer));
960   } else if (m_code_generator) {
961     Consumer.reset(new ASTConsumerForwarder(m_code_generator.get()));
962   } else {
963     Consumer.reset(new ASTConsumer());
964   }
965 
966   clang::ASTContext &ast_context = m_compiler->getASTContext();
967 
968   m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context,
969                                *Consumer, TU_Complete, completion_consumer));
970   m_compiler->setASTConsumer(std::move(Consumer));
971 
972   if (ast_context.getLangOpts().Modules)
973     m_compiler->createModuleManager();
974 
975   ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
976   if (decl_map) {
977     decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer());
978 
979     clang::ExternalASTSource *ast_source = decl_map->CreateProxy();
980 
981     if (ast_context.getExternalSource()) {
982       auto module_wrapper =
983           new ExternalASTSourceWrapper(ast_context.getExternalSource());
984 
985       auto ast_source_wrapper = new ExternalASTSourceWrapper(ast_source);
986 
987       auto multiplexer =
988           new SemaSourceWithPriorities(*module_wrapper, *ast_source_wrapper);
989       IntrusiveRefCntPtr<ExternalASTSource> Source(multiplexer);
990       ast_context.setExternalSource(Source);
991     } else {
992       ast_context.setExternalSource(ast_source);
993     }
994     decl_map->InstallASTContext(ast_context, m_compiler->getFileManager());
995   }
996 
997   // Check that the ASTReader is properly attached to ASTContext and Sema.
998   if (ast_context.getLangOpts().Modules) {
999     assert(m_compiler->getASTContext().getExternalSource() &&
1000            "ASTContext doesn't know about the ASTReader?");
1001     assert(m_compiler->getSema().getExternalSource() &&
1002            "Sema doesn't know about the ASTReader?");
1003   }
1004 
1005   {
1006     llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(
1007         &m_compiler->getSema());
1008     ParseAST(m_compiler->getSema(), false, false);
1009   }
1010   // Destroy the Sema. This is necessary because we want to emulate the
1011   // original behavior of ParseAST (which also destroys the Sema after parsing).
1012   m_compiler->setSema(nullptr);
1013 
1014   diag_buf->EndSourceFile();
1015 
1016   unsigned num_errors = diag_buf->getNumErrors();
1017 
1018   if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
1019     num_errors++;
1020     diagnostic_manager.PutString(eDiagnosticSeverityError,
1021                                  "while importing modules:");
1022     diagnostic_manager.AppendMessageToDiagnostic(
1023         m_pp_callbacks->getErrorString());
1024   }
1025 
1026   if (!num_errors) {
1027     if (type_system_helper->DeclMap() &&
1028         !type_system_helper->DeclMap()->ResolveUnknownTypes()) {
1029       diagnostic_manager.Printf(eDiagnosticSeverityError,
1030                                 "Couldn't infer the type of a variable");
1031       num_errors++;
1032     }
1033   }
1034 
1035   if (!num_errors) {
1036     type_system_helper->CommitPersistentDecls();
1037   }
1038 
1039   adapter->ResetManager();
1040 
1041   return num_errors;
1042 }
1043 
1044 std::string
1045 ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
1046   std::string abi;
1047 
1048   if (target_arch.IsMIPS()) {
1049     switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
1050     case ArchSpec::eMIPSABI_N64:
1051       abi = "n64";
1052       break;
1053     case ArchSpec::eMIPSABI_N32:
1054       abi = "n32";
1055       break;
1056     case ArchSpec::eMIPSABI_O32:
1057       abi = "o32";
1058       break;
1059     default:
1060       break;
1061     }
1062   }
1063   return abi;
1064 }
1065 
1066 bool ClangExpressionParser::RewriteExpression(
1067     DiagnosticManager &diagnostic_manager) {
1068   clang::SourceManager &source_manager = m_compiler->getSourceManager();
1069   clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
1070                                    nullptr);
1071   clang::edit::Commit commit(editor);
1072   clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
1073 
1074   class RewritesReceiver : public edit::EditsReceiver {
1075     Rewriter &rewrite;
1076 
1077   public:
1078     RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
1079 
1080     void insert(SourceLocation loc, StringRef text) override {
1081       rewrite.InsertText(loc, text);
1082     }
1083     void replace(CharSourceRange range, StringRef text) override {
1084       rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
1085     }
1086   };
1087 
1088   RewritesReceiver rewrites_receiver(rewriter);
1089 
1090   const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
1091   size_t num_diags = diagnostics.size();
1092   if (num_diags == 0)
1093     return false;
1094 
1095   for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
1096     const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
1097     if (diagnostic && diagnostic->HasFixIts()) {
1098       for (const FixItHint &fixit : diagnostic->FixIts()) {
1099         // This is cobbed from clang::Rewrite::FixItRewriter.
1100         if (fixit.CodeToInsert.empty()) {
1101           if (fixit.InsertFromRange.isValid()) {
1102             commit.insertFromRange(fixit.RemoveRange.getBegin(),
1103                                    fixit.InsertFromRange, /*afterToken=*/false,
1104                                    fixit.BeforePreviousInsertions);
1105           } else
1106             commit.remove(fixit.RemoveRange);
1107         } else {
1108           if (fixit.RemoveRange.isTokenRange() ||
1109               fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
1110             commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
1111           else
1112             commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
1113                           /*afterToken=*/false, fixit.BeforePreviousInsertions);
1114         }
1115       }
1116     }
1117   }
1118 
1119   // FIXME - do we want to try to propagate specific errors here?
1120   if (!commit.isCommitable())
1121     return false;
1122   else if (!editor.commit(commit))
1123     return false;
1124 
1125   // Now play all the edits, and stash the result in the diagnostic manager.
1126   editor.applyRewrites(rewrites_receiver);
1127   RewriteBuffer &main_file_buffer =
1128       rewriter.getEditBuffer(source_manager.getMainFileID());
1129 
1130   std::string fixed_expression;
1131   llvm::raw_string_ostream out_stream(fixed_expression);
1132 
1133   main_file_buffer.write(out_stream);
1134   out_stream.flush();
1135   diagnostic_manager.SetFixedExpression(fixed_expression);
1136 
1137   return true;
1138 }
1139 
1140 static bool FindFunctionInModule(ConstString &mangled_name,
1141                                  llvm::Module *module, const char *orig_name) {
1142   for (const auto &func : module->getFunctionList()) {
1143     const StringRef &name = func.getName();
1144     if (name.find(orig_name) != StringRef::npos) {
1145       mangled_name.SetString(name);
1146       return true;
1147     }
1148   }
1149 
1150   return false;
1151 }
1152 
1153 lldb_private::Status ClangExpressionParser::PrepareForExecution(
1154     lldb::addr_t &func_addr, lldb::addr_t &func_end,
1155     lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1156     bool &can_interpret, ExecutionPolicy execution_policy) {
1157   func_addr = LLDB_INVALID_ADDRESS;
1158   func_end = LLDB_INVALID_ADDRESS;
1159   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1160 
1161   lldb_private::Status err;
1162 
1163   std::unique_ptr<llvm::Module> llvm_module_up(
1164       m_code_generator->ReleaseModule());
1165 
1166   if (!llvm_module_up) {
1167     err.SetErrorToGenericError();
1168     err.SetErrorString("IR doesn't contain a module");
1169     return err;
1170   }
1171 
1172   ConstString function_name;
1173 
1174   if (execution_policy != eExecutionPolicyTopLevel) {
1175     // Find the actual name of the function (it's often mangled somehow)
1176 
1177     if (!FindFunctionInModule(function_name, llvm_module_up.get(),
1178                               m_expr.FunctionName())) {
1179       err.SetErrorToGenericError();
1180       err.SetErrorStringWithFormat("Couldn't find %s() in the module",
1181                                    m_expr.FunctionName());
1182       return err;
1183     } else {
1184       if (log)
1185         log->Printf("Found function %s for %s", function_name.AsCString(),
1186                     m_expr.FunctionName());
1187     }
1188   }
1189 
1190   SymbolContext sc;
1191 
1192   if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1193     sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1194   } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1195     sc.target_sp = target_sp;
1196   }
1197 
1198   LLVMUserExpression::IRPasses custom_passes;
1199   {
1200     auto lang = m_expr.Language();
1201     if (log)
1202       log->Printf("%s - Current expression language is %s\n", __FUNCTION__,
1203                   Language::GetNameForLanguageType(lang));
1204     lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1205     if (process_sp && lang != lldb::eLanguageTypeUnknown) {
1206       auto runtime = process_sp->GetLanguageRuntime(lang);
1207       if (runtime)
1208         runtime->GetIRPasses(custom_passes);
1209     }
1210   }
1211 
1212   if (custom_passes.EarlyPasses) {
1213     if (log)
1214       log->Printf("%s - Running Early IR Passes from LanguageRuntime on "
1215                   "expression module '%s'",
1216                   __FUNCTION__, m_expr.FunctionName());
1217 
1218     custom_passes.EarlyPasses->run(*llvm_module_up);
1219   }
1220 
1221   execution_unit_sp = std::make_shared<IRExecutionUnit>(
1222       m_llvm_context, // handed off here
1223       llvm_module_up, // handed off here
1224       function_name, exe_ctx.GetTargetSP(), sc,
1225       m_compiler->getTargetOpts().Features);
1226 
1227   ClangExpressionHelper *type_system_helper =
1228       dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1229   ClangExpressionDeclMap *decl_map =
1230       type_system_helper->DeclMap(); // result can be NULL
1231 
1232   if (decl_map) {
1233     Stream *error_stream = NULL;
1234     Target *target = exe_ctx.GetTargetPtr();
1235     error_stream = target->GetDebugger().GetErrorFile().get();
1236 
1237     IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
1238                               *execution_unit_sp, *error_stream,
1239                               function_name.AsCString());
1240 
1241     bool ir_can_run =
1242         ir_for_target.runOnModule(*execution_unit_sp->GetModule());
1243 
1244     if (!ir_can_run) {
1245       err.SetErrorString(
1246           "The expression could not be prepared to run in the target");
1247       return err;
1248     }
1249 
1250     Process *process = exe_ctx.GetProcessPtr();
1251 
1252     if (execution_policy != eExecutionPolicyAlways &&
1253         execution_policy != eExecutionPolicyTopLevel) {
1254       lldb_private::Status interpret_error;
1255 
1256       bool interpret_function_calls =
1257           !process ? false : process->CanInterpretFunctionCalls();
1258       can_interpret = IRInterpreter::CanInterpret(
1259           *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
1260           interpret_error, interpret_function_calls);
1261 
1262       if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1263         err.SetErrorStringWithFormat("Can't run the expression locally: %s",
1264                                      interpret_error.AsCString());
1265         return err;
1266       }
1267     }
1268 
1269     if (!process && execution_policy == eExecutionPolicyAlways) {
1270       err.SetErrorString("Expression needed to run in the target, but the "
1271                          "target can't be run");
1272       return err;
1273     }
1274 
1275     if (!process && execution_policy == eExecutionPolicyTopLevel) {
1276       err.SetErrorString("Top-level code needs to be inserted into a runnable "
1277                          "target, but the target can't be run");
1278       return err;
1279     }
1280 
1281     if (execution_policy == eExecutionPolicyAlways ||
1282         (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1283       if (m_expr.NeedsValidation() && process) {
1284         if (!process->GetDynamicCheckers()) {
1285           DynamicCheckerFunctions *dynamic_checkers =
1286               new DynamicCheckerFunctions();
1287 
1288           DiagnosticManager install_diagnostics;
1289 
1290           if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
1291             if (install_diagnostics.Diagnostics().size())
1292               err.SetErrorString(install_diagnostics.GetString().c_str());
1293             else
1294               err.SetErrorString("couldn't install checkers, unknown error");
1295 
1296             return err;
1297           }
1298 
1299           process->SetDynamicCheckers(dynamic_checkers);
1300 
1301           if (log)
1302             log->Printf("== [ClangExpressionParser::PrepareForExecution] "
1303                         "Finished installing dynamic checkers ==");
1304         }
1305 
1306         IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(),
1307                                           function_name.AsCString());
1308 
1309         llvm::Module *module = execution_unit_sp->GetModule();
1310         if (!module || !ir_dynamic_checks.runOnModule(*module)) {
1311           err.SetErrorToGenericError();
1312           err.SetErrorString("Couldn't add dynamic checks to the expression");
1313           return err;
1314         }
1315 
1316         if (custom_passes.LatePasses) {
1317           if (log)
1318             log->Printf("%s - Running Late IR Passes from LanguageRuntime on "
1319                         "expression module '%s'",
1320                         __FUNCTION__, m_expr.FunctionName());
1321 
1322           custom_passes.LatePasses->run(*module);
1323         }
1324       }
1325     }
1326 
1327     if (execution_policy == eExecutionPolicyAlways ||
1328         execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1329       execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1330     }
1331   } else {
1332     execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1333   }
1334 
1335   return err;
1336 }
1337 
1338 lldb_private::Status ClangExpressionParser::RunStaticInitializers(
1339     lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
1340   lldb_private::Status err;
1341 
1342   lldbassert(execution_unit_sp.get());
1343   lldbassert(exe_ctx.HasThreadScope());
1344 
1345   if (!execution_unit_sp.get()) {
1346     err.SetErrorString(
1347         "can't run static initializers for a NULL execution unit");
1348     return err;
1349   }
1350 
1351   if (!exe_ctx.HasThreadScope()) {
1352     err.SetErrorString("can't run static initializers without a thread");
1353     return err;
1354   }
1355 
1356   std::vector<lldb::addr_t> static_initializers;
1357 
1358   execution_unit_sp->GetStaticInitializers(static_initializers);
1359 
1360   for (lldb::addr_t static_initializer : static_initializers) {
1361     EvaluateExpressionOptions options;
1362 
1363     lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
1364         exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
1365         llvm::ArrayRef<lldb::addr_t>(), options));
1366 
1367     DiagnosticManager execution_errors;
1368     lldb::ExpressionResults results =
1369         exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
1370             exe_ctx, call_static_initializer, options, execution_errors);
1371 
1372     if (results != lldb::eExpressionCompleted) {
1373       err.SetErrorStringWithFormat("couldn't run static initializer: %s",
1374                                    execution_errors.GetString().c_str());
1375       return err;
1376     }
1377   }
1378 
1379   return err;
1380 }
1381