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