yjshen commented on a change in pull request #1849: URL: https://github.com/apache/arrow-datafusion/pull/1849#discussion_r810603618
########## File path: datafusion-jit/src/jit.rs ########## @@ -0,0 +1,698 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::api::GeneratedFunction; +use crate::ast::{BinaryExpr, Expr, JITType, Literal, Stmt, TypedLit, BOOL, I64, NIL}; +use cranelift::prelude::*; +use cranelift_jit::{JITBuilder, JITModule}; +use cranelift_module::{DataContext, Linkage, Module}; +use datafusion_common::internal_err; +use datafusion_common::{DataFusionError, Result}; +use std::collections::HashMap; +use std::slice; + +/// The basic JIT class. +#[allow(clippy::upper_case_acronyms)] +pub struct JIT { + /// The function builder context, which is reused across multiple + /// FunctionBuilder instances. + builder_context: FunctionBuilderContext, + + /// The main Cranelift context, which holds the state for codegen. Cranelift + /// separates this from `Module` to allow for parallel compilation, with a + /// context per thread, though this is not the case now. + ctx: codegen::Context, + + /// The data context, which is to data objects what `ctx` is to functions. + data_ctx: DataContext, + + /// The module, with the jit backend, which manages the JIT'd + /// functions. + module: JITModule, +} + +impl Default for JIT { + fn default() -> Self { + let builder = JITBuilder::new(cranelift_module::default_libcall_names()); + let module = JITModule::new(builder); + Self { + builder_context: FunctionBuilderContext::new(), + ctx: module.make_context(), + data_ctx: DataContext::new(), + module, + } + } +} + +impl JIT { + /// New while registering external functions + pub fn new<It, K>(symbols: It) -> Self + where + It: IntoIterator<Item = (K, *const u8)>, + K: Into<String>, + { + let mut flag_builder = settings::builder(); + flag_builder.set("use_colocated_libcalls", "false").unwrap(); + flag_builder.set("is_pic", "true").unwrap(); + flag_builder.set("opt_level", "speed").unwrap(); + flag_builder.set("enable_simd", "true").unwrap(); + let isa_builder = cranelift_native::builder().unwrap_or_else(|msg| { + panic!("host machine is not supported: {}", msg); + }); + let isa = isa_builder.finish(settings::Flags::new(flag_builder)); + let mut builder = + JITBuilder::with_isa(isa, cranelift_module::default_libcall_names()); + builder.symbols(symbols); + let module = JITModule::new(builder); + Self { + builder_context: FunctionBuilderContext::new(), + ctx: module.make_context(), + data_ctx: DataContext::new(), + module, + } + } + + /// Compile the generated function into machine code. + pub fn compile(&mut self, func: GeneratedFunction) -> Result<*const u8> { + let GeneratedFunction { + name, + params, + body, + ret, + } = func; + + // Translate the AST nodes into Cranelift IR. + self.translate(params, ret, body)?; + + // Next, declare the function to jit. Functions must be declared + // before they can be called, or defined. + let id = self.module.declare_function( + &name, + Linkage::Export, + &self.ctx.func.signature, + )?; + + // Define the function to jit. This finishes compilation, although + // there may be outstanding relocations to perform. Currently, jit + // cannot finish relocations until all functions to be called are + // defined. For now, we'll just finalize the function below. + self.module.define_function(id, &mut self.ctx)?; + + // Now that compilation is finished, we can clear out the context state. + self.module.clear_context(&mut self.ctx); + + // Finalize the functions which we just defined, which resolves any + // outstanding relocations (patching in addresses, now that they're + // available). + self.module.finalize_definitions(); + + // We can now retrieve a pointer to the machine code. + let code = self.module.get_finalized_function(id); + + Ok(code) + } + + /// Create a zero-initialized data section. + pub fn create_data(&mut self, name: &str, contents: Vec<u8>) -> Result<&[u8]> { Review comment: I should remove this. Not used for the moment. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
