You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/05/23 18:48:04 UTC

[GitHub] [arrow-datafusion] Dandandan commented on a diff in pull request #2587: Evaluate JIT'd expression over arrays

Dandandan commented on code in PR #2587:
URL: https://github.com/apache/arrow-datafusion/pull/2587#discussion_r879773733


##########
datafusion/jit/src/compile.rs:
##########
@@ -0,0 +1,184 @@
+// 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.
+
+//! Compile DataFusion Expr to JIT'd function.
+
+use datafusion_common::Result;
+
+use crate::api::Assembler;
+use crate::{
+    api::GeneratedFunction,
+    ast::{Expr as JITExpr, I64, PTR_SIZE},
+};
+
+/// Wrap JIT Expr to array compute function.
+pub fn build_calc_fn(
+    assembler: &Assembler,
+    jit_expr: JITExpr,
+    input_names: Vec<String>,
+) -> Result<GeneratedFunction> {
+    let mut builder = assembler.new_func_builder("calc_fn");
+    for input in &input_names {
+        builder = builder.param(format!("{}_array", input), I64);
+    }
+    let mut builder = builder.param("result", I64).param("len", I64);
+
+    let mut fn_body = builder.enter_block();
+    fn_body.declare_as("index", fn_body.lit_i(0))?;
+    fn_body.while_block(
+        |cond| cond.lt(cond.id("index")?, cond.id("len")?),
+        |w| {
+            w.declare_as("offset", w.mul(w.id("index")?, w.lit_i(PTR_SIZE as i64))?)?;
+            for input in &input_names {
+                w.declare_as(
+                    format!("{}_ptr", input),
+                    w.add(w.id(format!("{}_array", input))?, w.id("offset")?)?,
+                )?;
+                w.declare_as(input, w.deref(w.id(format!("{}_ptr", input))?, I64)?)?;
+            }
+            w.declare_as("res_ptr", w.add(w.id("result")?, w.id("offset")?)?)?;
+            w.declare_as("res", jit_expr.clone())?;
+            w.store(w.id("res")?, w.id("res_ptr")?)?;
+
+            w.assign("index", w.add(w.id("index")?, w.lit_i(1))?)?;
+            Ok(())
+        },
+    )?;
+
+    let gen_func = fn_body.build();
+    Ok(gen_func)
+}
+
+#[cfg(test)]
+mod test {
+    use std::{collections::HashMap, sync::Arc};
+
+    use arrow::{
+        array::{Array, PrimitiveArray},
+        datatypes::{DataType, Int64Type},
+    };
+    use datafusion_common::{DFField, DFSchema, DataFusionError};
+    use datafusion_expr::Expr as DFExpr;
+
+    use crate::ast::BinaryExpr;
+
+    use super::*;
+
+    fn run_df_expr(
+        df_expr: DFExpr,
+        schema: Arc<DFSchema>,
+        lhs: PrimitiveArray<Int64Type>,
+        rhs: PrimitiveArray<Int64Type>,
+    ) -> Result<PrimitiveArray<Int64Type>> {
+        if lhs.null_count() != 0 || rhs.null_count() != 0 {
+            return Err(DataFusionError::NotImplemented(
+                "Computing on nullable array not yet supported".to_string(),
+            ));
+        }
+        if lhs.len() != rhs.len() {
+            return Err(DataFusionError::NotImplemented(
+                "Computing on different length arrays not yet supported".to_string(),
+            ));
+        }
+
+        // translate DF Expr to JIT Expr
+        let input_fields = schema.field_names();
+        let jit_expr: JITExpr = (df_expr, schema).try_into()?;
+
+        // allocate memory for calc result
+        let len = lhs.len();
+        let result = vec![0i64; len];
+
+        // compile and run JIT code
+        let assembler = Assembler::default();
+        let gen_func = build_calc_fn(&assembler, jit_expr, input_fields)?;
+        let mut jit = assembler.create_jit();
+        let code_ptr = jit.compile(gen_func)?;
+        let code_fn =
+            unsafe { core::mem::transmute::<_, fn(i64, i64, i64, i64) -> ()>(code_ptr) };
+        code_fn(
+            lhs.values().as_ptr() as i64,
+            rhs.values().as_ptr() as i64,
+            result.as_ptr() as i64,
+            len as i64,
+        );
+
+        let result_array = PrimitiveArray::<Int64Type>::from_iter(result);
+        Ok(result_array)
+    }
+
+    #[test]
+    fn array_add() {
+        let array_a: PrimitiveArray<Int64Type> =
+            PrimitiveArray::from_iter_values((0..10).map(|x| x + 1));
+        let array_b: PrimitiveArray<Int64Type> =
+            PrimitiveArray::from_iter_values((0..10).map(|x| x + 1));
+        let expected =
+            arrow::compute::kernels::arithmetic::add(&array_a, &array_b).unwrap();
+
+        let df_expr = datafusion_expr::col("a") + datafusion_expr::col("b");
+        let schema = Arc::new(
+            DFSchema::new_with_metadata(
+                vec![
+                    DFField::new(Some("table1"), "a", DataType::Int64, false),
+                    DFField::new(Some("table1"), "b", DataType::Int64, false),
+                ],
+                HashMap::new(),
+            )
+            .unwrap(),
+        );
+
+        let result = run_df_expr(df_expr, schema, array_a, array_b).unwrap();
+        assert_eq!(result, expected);

Review Comment:
   Whoo, really nice 🎉



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org