Coverage Report

Created: 2022-01-18 06:27

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