1 //===-- ClangExpressionParser.cpp -------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // C Includes
11 // C++ Includes
12 // Other libraries and framework includes
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/ASTDiagnostic.h"
15 #include "clang/AST/ExternalASTSource.h"
16 #include "clang/Basic/DiagnosticIDs.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/Basic/Version.h"
21 #include "clang/CodeGen/CodeGenAction.h"
22 #include "clang/CodeGen/ModuleBuilder.h"
23 #include "clang/Edit/Commit.h"
24 #include "clang/Edit/EditedSource.h"
25 #include "clang/Edit/EditsReceiver.h"
26 #include "clang/Frontend/CompilerInstance.h"
27 #include "clang/Frontend/CompilerInvocation.h"
28 #include "clang/Frontend/FrontendActions.h"
29 #include "clang/Frontend/FrontendDiagnostic.h"
30 #include "clang/Frontend/FrontendPluginRegistry.h"
31 #include "clang/Frontend/TextDiagnosticBuffer.h"
32 #include "clang/Frontend/TextDiagnosticPrinter.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Parse/ParseAST.h"
35 #include "clang/Rewrite/Core/Rewriter.h"
36 #include "clang/Rewrite/Frontend/FrontendActions.h"
37 #include "clang/Sema/SemaConsumer.h"
38 
39 #include "llvm/ADT/StringRef.h"
40 #include "llvm/ExecutionEngine/ExecutionEngine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/TargetSelect.h"
44 
45 #pragma clang diagnostic push
46 #pragma clang diagnostic ignored "-Wglobal-constructors"
47 #include "llvm/ExecutionEngine/MCJIT.h"
48 #pragma clang diagnostic pop
49 
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/Support/DynamicLibrary.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/Host.h"
55 #include "llvm/Support/MemoryBuffer.h"
56 #include "llvm/Support/Signals.h"
57 
58 // Project includes
59 #include "ClangDiagnostic.h"
60 #include "ClangExpressionParser.h"
61 
62 #include "ClangASTSource.h"
63 #include "ClangExpressionDeclMap.h"
64 #include "ClangExpressionHelper.h"
65 #include "ClangModulesDeclVendor.h"
66 #include "ClangPersistentVariables.h"
67 #include "IRForTarget.h"
68 
69 #include "lldb/Core/ArchSpec.h"
70 #include "lldb/Core/Debugger.h"
71 #include "lldb/Core/Disassembler.h"
72 #include "lldb/Core/Module.h"
73 #include "lldb/Core/StreamFile.h"
74 #include "lldb/Expression/IRDynamicChecks.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/ClangASTContext.h"
80 #include "lldb/Symbol/SymbolVendor.h"
81 #include "lldb/Target/ExecutionContext.h"
82 #include "lldb/Target/Language.h"
83 #include "lldb/Target/ObjCLanguageRuntime.h"
84 #include "lldb/Target/Process.h"
85 #include "lldb/Target/Target.h"
86 #include "lldb/Target/ThreadPlanCallFunction.h"
87 #include "lldb/Utility/DataBufferHeap.h"
88 #include "lldb/Utility/LLDBAssert.h"
89 #include "lldb/Utility/Log.h"
90 #include "lldb/Utility/Stream.h"
91 #include "lldb/Utility/StreamString.h"
92 #include "lldb/Utility/StringList.h"
93 
94 using namespace clang;
95 using namespace llvm;
96 using namespace lldb_private;
97 
98 //===----------------------------------------------------------------------===//
99 // Utility Methods for Clang
100 //===----------------------------------------------------------------------===//
101 
102 class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
103   ClangModulesDeclVendor &m_decl_vendor;
104   ClangPersistentVariables &m_persistent_vars;
105   StreamString m_error_stream;
106   bool m_has_errors = false;
107 
108 public:
109   LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
110                             ClangPersistentVariables &persistent_vars)
111       : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars) {}
112 
113   void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
114                     const clang::Module * /*null*/) override {
115     std::vector<ConstString> string_path;
116 
117     for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) {
118       string_path.push_back(ConstString(component.first->getName()));
119     }
120 
121     StreamString error_stream;
122 
123     ClangModulesDeclVendor::ModuleVector exported_modules;
124 
125     if (!m_decl_vendor.AddModule(string_path, &exported_modules,
126                                  m_error_stream)) {
127       m_has_errors = true;
128     }
129 
130     for (ClangModulesDeclVendor::ModuleID module : exported_modules) {
131       m_persistent_vars.AddHandLoadedClangModule(module);
132     }
133   }
134 
135   bool hasErrors() { return m_has_errors; }
136 
137   llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
138 };
139 
140 class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
141 public:
142   ClangDiagnosticManagerAdapter()
143       : m_passthrough(new clang::TextDiagnosticBuffer) {}
144 
145   ClangDiagnosticManagerAdapter(
146       const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough)
147       : m_passthrough(passthrough) {}
148 
149   void ResetManager(DiagnosticManager *manager = nullptr) {
150     m_manager = manager;
151   }
152 
153   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
154                         const clang::Diagnostic &Info) {
155     if (m_manager) {
156       llvm::SmallVector<char, 32> diag_str;
157       Info.FormatDiagnostic(diag_str);
158       diag_str.push_back('\0');
159       const char *data = diag_str.data();
160 
161       lldb_private::DiagnosticSeverity severity;
162       bool make_new_diagnostic = true;
163 
164       switch (DiagLevel) {
165       case DiagnosticsEngine::Level::Fatal:
166       case DiagnosticsEngine::Level::Error:
167         severity = eDiagnosticSeverityError;
168         break;
169       case DiagnosticsEngine::Level::Warning:
170         severity = eDiagnosticSeverityWarning;
171         break;
172       case DiagnosticsEngine::Level::Remark:
173       case DiagnosticsEngine::Level::Ignored:
174         severity = eDiagnosticSeverityRemark;
175         break;
176       case DiagnosticsEngine::Level::Note:
177         m_manager->AppendMessageToDiagnostic(data);
178         make_new_diagnostic = false;
179       }
180       if (make_new_diagnostic) {
181         ClangDiagnostic *new_diagnostic =
182             new ClangDiagnostic(data, severity, Info.getID());
183         m_manager->AddDiagnostic(new_diagnostic);
184 
185         // Don't store away warning fixits, since the compiler doesn't have
186         // enough
187         // context in an expression for the warning to be useful.
188         // FIXME: Should we try to filter out FixIts that apply to our generated
189         // code, and not the user's expression?
190         if (severity == eDiagnosticSeverityError) {
191           size_t num_fixit_hints = Info.getNumFixItHints();
192           for (size_t i = 0; i < num_fixit_hints; i++) {
193             const clang::FixItHint &fixit = Info.getFixItHint(i);
194             if (!fixit.isNull())
195               new_diagnostic->AddFixitHint(fixit);
196           }
197         }
198       }
199     }
200 
201     m_passthrough->HandleDiagnostic(DiagLevel, Info);
202   }
203 
204   void FlushDiagnostics(DiagnosticsEngine &Diags) {
205     m_passthrough->FlushDiagnostics(Diags);
206   }
207 
208   DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
209     return new ClangDiagnosticManagerAdapter(m_passthrough);
210   }
211 
212   clang::TextDiagnosticBuffer *GetPassthrough() { return m_passthrough.get(); }
213 
214 private:
215   DiagnosticManager *m_manager = nullptr;
216   std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough;
217 };
218 
219 //===----------------------------------------------------------------------===//
220 // Implementation of ClangExpressionParser
221 //===----------------------------------------------------------------------===//
222 
223 ClangExpressionParser::ClangExpressionParser(ExecutionContextScope *exe_scope,
224                                              Expression &expr,
225                                              bool generate_debug_info)
226     : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
227       m_code_generator(), m_pp_callbacks(nullptr) {
228   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
229 
230   // We can't compile expressions without a target.  So if the exe_scope is null
231   // or doesn't have a target,
232   // then we just need to get out of here.  I'll lldb_assert and not make any of
233   // the compiler objects since
234   // I can't return errors directly from the constructor.  Further calls will
235   // check if the compiler was made and
236   // bag out if it wasn't.
237 
238   if (!exe_scope) {
239     lldb_assert(exe_scope, "Can't make an expression parser with a null scope.",
240                 __FUNCTION__, __FILE__, __LINE__);
241     return;
242   }
243 
244   lldb::TargetSP target_sp;
245   target_sp = exe_scope->CalculateTarget();
246   if (!target_sp) {
247     lldb_assert(target_sp.get(),
248                 "Can't make an expression parser with a null target.",
249                 __FUNCTION__, __FILE__, __LINE__);
250     return;
251   }
252 
253   // 1. Create a new compiler instance.
254   m_compiler.reset(new CompilerInstance());
255   lldb::LanguageType frame_lang =
256       expr.Language(); // defaults to lldb::eLanguageTypeUnknown
257   bool overridden_target_opts = false;
258   lldb_private::LanguageRuntime *lang_rt = nullptr;
259 
260   std::string abi;
261   ArchSpec target_arch;
262   target_arch = target_sp->GetArchitecture();
263 
264   const auto target_machine = target_arch.GetMachine();
265 
266   // If the expression is being evaluated in the context of an existing
267   // stack frame, we introspect to see if the language runtime is available.
268 
269   lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
270   lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
271 
272   // Make sure the user hasn't provided a preferred execution language
273   // with `expression --language X -- ...`
274   if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
275     frame_lang = frame_sp->GetLanguage();
276 
277   if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
278     lang_rt = process_sp->GetLanguageRuntime(frame_lang);
279     if (log)
280       log->Printf("Frame has language of type %s",
281                   Language::GetNameForLanguageType(frame_lang));
282   }
283 
284   // 2. Configure the compiler with a set of default options that are
285   // appropriate
286   // for most situations.
287   if (target_arch.IsValid()) {
288     std::string triple = target_arch.GetTriple().str();
289     m_compiler->getTargetOpts().Triple = triple;
290     if (log)
291       log->Printf("Using %s as the target triple",
292                   m_compiler->getTargetOpts().Triple.c_str());
293   } else {
294     // If we get here we don't have a valid target and just have to guess.
295     // Sometimes this will be ok to just use the host target triple (when we
296     // evaluate say "2+3", but other
297     // expressions like breakpoint conditions and other things that _are_ target
298     // specific really shouldn't just be
299     // using the host triple. In such a case the language runtime should expose
300     // an overridden options set (3),
301     // below.
302     m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
303     if (log)
304       log->Printf("Using default target triple of %s",
305                   m_compiler->getTargetOpts().Triple.c_str());
306   }
307   // Now add some special fixes for known architectures:
308   // Any arm32 iOS environment, but not on arm64
309   if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
310       m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
311       m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
312     m_compiler->getTargetOpts().ABI = "apcs-gnu";
313   }
314   // Supported subsets of x86
315   if (target_machine == llvm::Triple::x86 ||
316       target_machine == llvm::Triple::x86_64) {
317     m_compiler->getTargetOpts().Features.push_back("+sse");
318     m_compiler->getTargetOpts().Features.push_back("+sse2");
319   }
320 
321   // Set the target CPU to generate code for.
322   // This will be empty for any CPU that doesn't really need to make a special
323   // CPU string.
324   m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
325 
326   // Set the target ABI
327   abi = GetClangTargetABI(target_arch);
328   if (!abi.empty())
329     m_compiler->getTargetOpts().ABI = abi;
330 
331   // 3. Now allow the runtime to provide custom configuration options for the
332   // target.
333   // In this case, a specialized language runtime is available and we can query
334   // it for extra options.
335   // For 99% of use cases, this will not be needed and should be provided when
336   // basic platform detection is not enough.
337   if (lang_rt)
338     overridden_target_opts =
339         lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
340 
341   if (overridden_target_opts)
342     if (log && log->GetVerbose()) {
343       LLDB_LOGV(
344           log, "Using overridden target options for the expression evaluation");
345 
346       auto opts = m_compiler->getTargetOpts();
347       LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
348       LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
349       LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
350       LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
351       LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
352       StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
353       StringList::LogDump(log, opts.Features, "Features");
354       StringList::LogDump(log, opts.Reciprocals, "Reciprocals");
355     }
356 
357   // 4. Create and install the target on the compiler.
358   m_compiler->createDiagnostics();
359   auto target_info = TargetInfo::CreateTargetInfo(
360       m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
361   if (log) {
362     log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign());
363     log->Printf("Target datalayout string: '%s'",
364                 target_info->getDataLayout().getStringRepresentation().c_str());
365     log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str());
366     log->Printf("Target vector alignment: %d",
367                 target_info->getMaxVectorAlign());
368   }
369   m_compiler->setTarget(target_info);
370 
371   assert(m_compiler->hasTarget());
372 
373   // 5. Set language options.
374   lldb::LanguageType language = expr.Language();
375 
376   switch (language) {
377   case lldb::eLanguageTypeC:
378   case lldb::eLanguageTypeC89:
379   case lldb::eLanguageTypeC99:
380   case lldb::eLanguageTypeC11:
381     // FIXME: the following language option is a temporary workaround,
382     // to "ask for C, get C++."
383     // For now, the expression parser must use C++ anytime the
384     // language is a C family language, because the expression parser
385     // uses features of C++ to capture values.
386     m_compiler->getLangOpts().CPlusPlus = true;
387     break;
388   case lldb::eLanguageTypeObjC:
389     m_compiler->getLangOpts().ObjC1 = true;
390     m_compiler->getLangOpts().ObjC2 = true;
391     // FIXME: the following language option is a temporary workaround,
392     // to "ask for ObjC, get ObjC++" (see comment above).
393     m_compiler->getLangOpts().CPlusPlus = true;
394     break;
395   case lldb::eLanguageTypeC_plus_plus:
396   case lldb::eLanguageTypeC_plus_plus_11:
397   case lldb::eLanguageTypeC_plus_plus_14:
398     m_compiler->getLangOpts().CPlusPlus11 = true;
399     m_compiler->getHeaderSearchOpts().UseLibcxx = true;
400     LLVM_FALLTHROUGH;
401   case lldb::eLanguageTypeC_plus_plus_03:
402     m_compiler->getLangOpts().CPlusPlus = true;
403     // FIXME: the following language option is a temporary workaround,
404     // to "ask for C++, get ObjC++".  Apple hopes to remove this requirement
405     // on non-Apple platforms, but for now it is needed.
406     m_compiler->getLangOpts().ObjC1 = true;
407     break;
408   case lldb::eLanguageTypeObjC_plus_plus:
409   case lldb::eLanguageTypeUnknown:
410   default:
411     m_compiler->getLangOpts().ObjC1 = true;
412     m_compiler->getLangOpts().ObjC2 = true;
413     m_compiler->getLangOpts().CPlusPlus = true;
414     m_compiler->getLangOpts().CPlusPlus11 = true;
415     m_compiler->getHeaderSearchOpts().UseLibcxx = true;
416     break;
417   }
418 
419   m_compiler->getLangOpts().Bool = true;
420   m_compiler->getLangOpts().WChar = true;
421   m_compiler->getLangOpts().Blocks = true;
422   m_compiler->getLangOpts().DebuggerSupport =
423       true; // Features specifically for debugger clients
424   if (expr.DesiredResultType() == Expression::eResultTypeId)
425     m_compiler->getLangOpts().DebuggerCastResultToId = true;
426 
427   m_compiler->getLangOpts().CharIsSigned =
428       ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
429           .CharIsSignedByDefault();
430 
431   // Spell checking is a nice feature, but it ends up completing a
432   // lot of types that we didn't strictly speaking need to complete.
433   // As a result, we spend a long time parsing and importing debug
434   // information.
435   m_compiler->getLangOpts().SpellChecking = false;
436 
437   if (process_sp && m_compiler->getLangOpts().ObjC1) {
438     if (process_sp->GetObjCLanguageRuntime()) {
439       if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() ==
440           ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
441         m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX,
442                                                   VersionTuple(10, 7));
443       else
444         m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
445                                                   VersionTuple(10, 7));
446 
447       if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
448         m_compiler->getLangOpts().DebuggerObjCLiteral = true;
449     }
450   }
451 
452   m_compiler->getLangOpts().ThreadsafeStatics = false;
453   m_compiler->getLangOpts().AccessControl =
454       false; // Debuggers get universal access
455   m_compiler->getLangOpts().DollarIdents =
456       true; // $ indicates a persistent variable name
457 
458   // Set CodeGen options
459   m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
460   m_compiler->getCodeGenOpts().InstrumentFunctions = false;
461   m_compiler->getCodeGenOpts().DisableFPElim = true;
462   m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
463   if (generate_debug_info)
464     m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
465   else
466     m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
467 
468   // Disable some warnings.
469   m_compiler->getDiagnostics().setSeverityForGroup(
470       clang::diag::Flavor::WarningOrError, "unused-value",
471       clang::diag::Severity::Ignored, SourceLocation());
472   m_compiler->getDiagnostics().setSeverityForGroup(
473       clang::diag::Flavor::WarningOrError, "odr",
474       clang::diag::Severity::Ignored, SourceLocation());
475 
476   // Inform the target of the language options
477   //
478   // FIXME: We shouldn't need to do this, the target should be immutable once
479   // created. This complexity should be lifted elsewhere.
480   m_compiler->getTarget().adjust(m_compiler->getLangOpts());
481 
482   // 6. Set up the diagnostic buffer for reporting errors
483 
484   m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter);
485 
486   // 7. Set up the source management objects inside the compiler
487 
488   clang::FileSystemOptions file_system_options;
489   m_file_manager.reset(new clang::FileManager(file_system_options));
490 
491   if (!m_compiler->hasSourceManager())
492     m_compiler->createSourceManager(*m_file_manager.get());
493 
494   m_compiler->createFileManager();
495   m_compiler->createPreprocessor(TU_Complete);
496 
497   if (ClangModulesDeclVendor *decl_vendor =
498           target_sp->GetClangModulesDeclVendor()) {
499     ClangPersistentVariables *clang_persistent_vars =
500         llvm::cast<ClangPersistentVariables>(
501             target_sp->GetPersistentExpressionStateForLanguage(
502                 lldb::eLanguageTypeC));
503     std::unique_ptr<PPCallbacks> pp_callbacks(
504         new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars));
505     m_pp_callbacks =
506         static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
507     m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
508   }
509 
510   // 8. Most of this we get from the CompilerInstance, but we
511   // also want to give the context an ExternalASTSource.
512   m_selector_table.reset(new SelectorTable());
513   m_builtin_context.reset(new Builtin::Context());
514 
515   std::unique_ptr<clang::ASTContext> ast_context(
516       new ASTContext(m_compiler->getLangOpts(), m_compiler->getSourceManager(),
517                      m_compiler->getPreprocessor().getIdentifierTable(),
518                      *m_selector_table.get(), *m_builtin_context.get()));
519 
520   ast_context->InitBuiltinTypes(m_compiler->getTarget());
521 
522   ClangExpressionHelper *type_system_helper =
523       dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
524   ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
525 
526   if (decl_map) {
527     llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(
528         decl_map->CreateProxy());
529     decl_map->InstallASTContext(ast_context.get());
530     ast_context->setExternalSource(ast_source);
531   }
532 
533   m_ast_context.reset(
534       new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
535   m_ast_context->setASTContext(ast_context.get());
536   m_compiler->setASTContext(ast_context.release());
537 
538   std::string module_name("$__lldb_module");
539 
540   m_llvm_context.reset(new LLVMContext());
541   m_code_generator.reset(CreateLLVMCodeGen(
542       m_compiler->getDiagnostics(), module_name,
543       m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
544       m_compiler->getCodeGenOpts(), *m_llvm_context));
545 }
546 
547 ClangExpressionParser::~ClangExpressionParser() {}
548 
549 unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
550   ClangDiagnosticManagerAdapter *adapter =
551       static_cast<ClangDiagnosticManagerAdapter *>(
552           m_compiler->getDiagnostics().getClient());
553   clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough();
554   diag_buf->FlushDiagnostics(m_compiler->getDiagnostics());
555 
556   adapter->ResetManager(&diagnostic_manager);
557 
558   const char *expr_text = m_expr.Text();
559 
560   clang::SourceManager &source_mgr = m_compiler->getSourceManager();
561   bool created_main_file = false;
562   if (m_compiler->getCodeGenOpts().getDebugInfo() ==
563       codegenoptions::FullDebugInfo) {
564     int temp_fd = -1;
565     llvm::SmallString<PATH_MAX> result_path;
566     FileSpec tmpdir_file_spec;
567     if (HostInfo::GetLLDBPath(lldb::ePathTypeLLDBTempSystemDir,
568                               tmpdir_file_spec)) {
569       tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
570       std::string temp_source_path = tmpdir_file_spec.GetPath();
571       llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
572     } else {
573       llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
574     }
575 
576     if (temp_fd != -1) {
577       lldb_private::File file(temp_fd, true);
578       const size_t expr_text_len = strlen(expr_text);
579       size_t bytes_written = expr_text_len;
580       if (file.Write(expr_text, bytes_written).Success()) {
581         if (bytes_written == expr_text_len) {
582           file.Close();
583           source_mgr.setMainFileID(
584               source_mgr.createFileID(m_file_manager->getFile(result_path),
585                                       SourceLocation(), SrcMgr::C_User));
586           created_main_file = true;
587         }
588       }
589     }
590   }
591 
592   if (!created_main_file) {
593     std::unique_ptr<MemoryBuffer> memory_buffer =
594         MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
595     source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
596   }
597 
598   diag_buf->BeginSourceFile(m_compiler->getLangOpts(),
599                             &m_compiler->getPreprocessor());
600 
601   ClangExpressionHelper *type_system_helper =
602       dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
603 
604   ASTConsumer *ast_transformer =
605       type_system_helper->ASTTransformer(m_code_generator.get());
606 
607   if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap())
608     decl_map->InstallCodeGenerator(m_code_generator.get());
609 
610   if (ast_transformer) {
611     ast_transformer->Initialize(m_compiler->getASTContext());
612     ParseAST(m_compiler->getPreprocessor(), ast_transformer,
613              m_compiler->getASTContext());
614   } else {
615     m_code_generator->Initialize(m_compiler->getASTContext());
616     ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(),
617              m_compiler->getASTContext());
618   }
619 
620   diag_buf->EndSourceFile();
621 
622   unsigned num_errors = diag_buf->getNumErrors();
623 
624   if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
625     num_errors++;
626     diagnostic_manager.PutString(eDiagnosticSeverityError,
627                                  "while importing modules:");
628     diagnostic_manager.AppendMessageToDiagnostic(
629         m_pp_callbacks->getErrorString());
630   }
631 
632   if (!num_errors) {
633     if (type_system_helper->DeclMap() &&
634         !type_system_helper->DeclMap()->ResolveUnknownTypes()) {
635       diagnostic_manager.Printf(eDiagnosticSeverityError,
636                                 "Couldn't infer the type of a variable");
637       num_errors++;
638     }
639   }
640 
641   if (!num_errors) {
642     type_system_helper->CommitPersistentDecls();
643   }
644 
645   adapter->ResetManager();
646 
647   return num_errors;
648 }
649 
650 std::string
651 ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
652   std::string abi;
653 
654   if (target_arch.IsMIPS()) {
655     switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
656     case ArchSpec::eMIPSABI_N64:
657       abi = "n64";
658       break;
659     case ArchSpec::eMIPSABI_N32:
660       abi = "n32";
661       break;
662     case ArchSpec::eMIPSABI_O32:
663       abi = "o32";
664       break;
665     default:
666       break;
667     }
668   }
669   return abi;
670 }
671 
672 bool ClangExpressionParser::RewriteExpression(
673     DiagnosticManager &diagnostic_manager) {
674   clang::SourceManager &source_manager = m_compiler->getSourceManager();
675   clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
676                                    nullptr);
677   clang::edit::Commit commit(editor);
678   clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
679 
680   class RewritesReceiver : public edit::EditsReceiver {
681     Rewriter &rewrite;
682 
683   public:
684     RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
685 
686     void insert(SourceLocation loc, StringRef text) override {
687       rewrite.InsertText(loc, text);
688     }
689     void replace(CharSourceRange range, StringRef text) override {
690       rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
691     }
692   };
693 
694   RewritesReceiver rewrites_receiver(rewriter);
695 
696   const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
697   size_t num_diags = diagnostics.size();
698   if (num_diags == 0)
699     return false;
700 
701   for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
702     const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
703     if (diagnostic && diagnostic->HasFixIts()) {
704       for (const FixItHint &fixit : diagnostic->FixIts()) {
705         // This is cobbed from clang::Rewrite::FixItRewriter.
706         if (fixit.CodeToInsert.empty()) {
707           if (fixit.InsertFromRange.isValid()) {
708             commit.insertFromRange(fixit.RemoveRange.getBegin(),
709                                    fixit.InsertFromRange, /*afterToken=*/false,
710                                    fixit.BeforePreviousInsertions);
711           } else
712             commit.remove(fixit.RemoveRange);
713         } else {
714           if (fixit.RemoveRange.isTokenRange() ||
715               fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
716             commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
717           else
718             commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
719                           /*afterToken=*/false, fixit.BeforePreviousInsertions);
720         }
721       }
722     }
723   }
724 
725   // FIXME - do we want to try to propagate specific errors here?
726   if (!commit.isCommitable())
727     return false;
728   else if (!editor.commit(commit))
729     return false;
730 
731   // Now play all the edits, and stash the result in the diagnostic manager.
732   editor.applyRewrites(rewrites_receiver);
733   RewriteBuffer &main_file_buffer =
734       rewriter.getEditBuffer(source_manager.getMainFileID());
735 
736   std::string fixed_expression;
737   llvm::raw_string_ostream out_stream(fixed_expression);
738 
739   main_file_buffer.write(out_stream);
740   out_stream.flush();
741   diagnostic_manager.SetFixedExpression(fixed_expression);
742 
743   return true;
744 }
745 
746 static bool FindFunctionInModule(ConstString &mangled_name,
747                                  llvm::Module *module, const char *orig_name) {
748   for (const auto &func : module->getFunctionList()) {
749     const StringRef &name = func.getName();
750     if (name.find(orig_name) != StringRef::npos) {
751       mangled_name.SetString(name);
752       return true;
753     }
754   }
755 
756   return false;
757 }
758 
759 lldb_private::Status ClangExpressionParser::PrepareForExecution(
760     lldb::addr_t &func_addr, lldb::addr_t &func_end,
761     lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
762     bool &can_interpret, ExecutionPolicy execution_policy) {
763   func_addr = LLDB_INVALID_ADDRESS;
764   func_end = LLDB_INVALID_ADDRESS;
765   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
766 
767   lldb_private::Status err;
768 
769   std::unique_ptr<llvm::Module> llvm_module_ap(
770       m_code_generator->ReleaseModule());
771 
772   if (!llvm_module_ap.get()) {
773     err.SetErrorToGenericError();
774     err.SetErrorString("IR doesn't contain a module");
775     return err;
776   }
777 
778   ConstString function_name;
779 
780   if (execution_policy != eExecutionPolicyTopLevel) {
781     // Find the actual name of the function (it's often mangled somehow)
782 
783     if (!FindFunctionInModule(function_name, llvm_module_ap.get(),
784                               m_expr.FunctionName())) {
785       err.SetErrorToGenericError();
786       err.SetErrorStringWithFormat("Couldn't find %s() in the module",
787                                    m_expr.FunctionName());
788       return err;
789     } else {
790       if (log)
791         log->Printf("Found function %s for %s", function_name.AsCString(),
792                     m_expr.FunctionName());
793     }
794   }
795 
796   SymbolContext sc;
797 
798   if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
799     sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
800   } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
801     sc.target_sp = target_sp;
802   }
803 
804   LLVMUserExpression::IRPasses custom_passes;
805   {
806     auto lang = m_expr.Language();
807     if (log)
808       log->Printf("%s - Currrent expression language is %s\n", __FUNCTION__,
809                   Language::GetNameForLanguageType(lang));
810     lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
811     if (process_sp && lang != lldb::eLanguageTypeUnknown) {
812       auto runtime = process_sp->GetLanguageRuntime(lang);
813       if (runtime)
814         runtime->GetIRPasses(custom_passes);
815     }
816   }
817 
818   if (custom_passes.EarlyPasses) {
819     if (log)
820       log->Printf("%s - Running Early IR Passes from LanguageRuntime on "
821                   "expression module '%s'",
822                   __FUNCTION__, m_expr.FunctionName());
823 
824     custom_passes.EarlyPasses->run(*llvm_module_ap);
825   }
826 
827   execution_unit_sp.reset(
828       new IRExecutionUnit(m_llvm_context, // handed off here
829                           llvm_module_ap, // handed off here
830                           function_name, exe_ctx.GetTargetSP(), sc,
831                           m_compiler->getTargetOpts().Features));
832 
833   ClangExpressionHelper *type_system_helper =
834       dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
835   ClangExpressionDeclMap *decl_map =
836       type_system_helper->DeclMap(); // result can be NULL
837 
838   if (decl_map) {
839     Stream *error_stream = NULL;
840     Target *target = exe_ctx.GetTargetPtr();
841     error_stream = target->GetDebugger().GetErrorFile().get();
842 
843     IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
844                               *execution_unit_sp, *error_stream,
845                               function_name.AsCString());
846 
847     bool ir_can_run =
848         ir_for_target.runOnModule(*execution_unit_sp->GetModule());
849 
850     if (!ir_can_run) {
851       err.SetErrorString(
852           "The expression could not be prepared to run in the target");
853       return err;
854     }
855 
856     Process *process = exe_ctx.GetProcessPtr();
857 
858     if (execution_policy != eExecutionPolicyAlways &&
859         execution_policy != eExecutionPolicyTopLevel) {
860       lldb_private::Status interpret_error;
861 
862       bool interpret_function_calls =
863           !process ? false : process->CanInterpretFunctionCalls();
864       can_interpret = IRInterpreter::CanInterpret(
865           *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
866           interpret_error, interpret_function_calls);
867 
868       if (!can_interpret && execution_policy == eExecutionPolicyNever) {
869         err.SetErrorStringWithFormat("Can't run the expression locally: %s",
870                                      interpret_error.AsCString());
871         return err;
872       }
873     }
874 
875     if (!process && execution_policy == eExecutionPolicyAlways) {
876       err.SetErrorString("Expression needed to run in the target, but the "
877                          "target can't be run");
878       return err;
879     }
880 
881     if (!process && execution_policy == eExecutionPolicyTopLevel) {
882       err.SetErrorString("Top-level code needs to be inserted into a runnable "
883                          "target, but the target can't be run");
884       return err;
885     }
886 
887     if (execution_policy == eExecutionPolicyAlways ||
888         (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
889       if (m_expr.NeedsValidation() && process) {
890         if (!process->GetDynamicCheckers()) {
891           DynamicCheckerFunctions *dynamic_checkers =
892               new DynamicCheckerFunctions();
893 
894           DiagnosticManager install_diagnostics;
895 
896           if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
897             if (install_diagnostics.Diagnostics().size())
898               err.SetErrorString("couldn't install checkers, unknown error");
899             else
900               err.SetErrorString(install_diagnostics.GetString().c_str());
901 
902             return err;
903           }
904 
905           process->SetDynamicCheckers(dynamic_checkers);
906 
907           if (log)
908             log->Printf("== [ClangUserExpression::Evaluate] Finished "
909                         "installing dynamic checkers ==");
910         }
911 
912         IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(),
913                                           function_name.AsCString());
914 
915         llvm::Module *module = execution_unit_sp->GetModule();
916         if (!module || !ir_dynamic_checks.runOnModule(*module)) {
917           err.SetErrorToGenericError();
918           err.SetErrorString("Couldn't add dynamic checks to the expression");
919           return err;
920         }
921 
922         if (custom_passes.LatePasses) {
923           if (log)
924             log->Printf("%s - Running Late IR Passes from LanguageRuntime on "
925                         "expression module '%s'",
926                         __FUNCTION__, m_expr.FunctionName());
927 
928           custom_passes.LatePasses->run(*module);
929         }
930       }
931     }
932 
933     if (execution_policy == eExecutionPolicyAlways ||
934         execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
935       execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
936     }
937   } else {
938     execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
939   }
940 
941   return err;
942 }
943 
944 lldb_private::Status ClangExpressionParser::RunStaticInitializers(
945     lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
946   lldb_private::Status err;
947 
948   lldbassert(execution_unit_sp.get());
949   lldbassert(exe_ctx.HasThreadScope());
950 
951   if (!execution_unit_sp.get()) {
952     err.SetErrorString(
953         "can't run static initializers for a NULL execution unit");
954     return err;
955   }
956 
957   if (!exe_ctx.HasThreadScope()) {
958     err.SetErrorString("can't run static initializers without a thread");
959     return err;
960   }
961 
962   std::vector<lldb::addr_t> static_initializers;
963 
964   execution_unit_sp->GetStaticInitializers(static_initializers);
965 
966   for (lldb::addr_t static_initializer : static_initializers) {
967     EvaluateExpressionOptions options;
968 
969     lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
970         exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
971         llvm::ArrayRef<lldb::addr_t>(), options));
972 
973     DiagnosticManager execution_errors;
974     lldb::ExpressionResults results =
975         exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
976             exe_ctx, call_static_initializer, options, execution_errors);
977 
978     if (results != lldb::eExpressionCompleted) {
979       err.SetErrorStringWithFormat("couldn't run static initializer: %s",
980                                    execution_errors.GetString().c_str());
981       return err;
982     }
983   }
984 
985   return err;
986 }
987