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