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