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