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