You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by ja...@apache.org on 2023/07/12 14:53:56 UTC

[flink] 05/05: [FLINK-22734][table-runtime] Fix comments for HashJoin and Calc OperatorFusionCodeGen

This is an automated email from the ASF dual-hosted git repository.

jark pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink.git

commit f480b6d313f64ff5d8d1e6f1d74f2dacc3ea133b
Author: fengli <ld...@163.com>
AuthorDate: Mon Jun 26 18:05:42 2023 +0800

    [FLINK-22734][table-runtime] Fix comments for HashJoin and Calc OperatorFusionCodeGen
    
    This closes #22734
---
 .../nodes/exec/batch/BatchExecMultipleInput.java   |   8 +-
 .../planner/codegen/GeneratedExpression.scala      |   2 +-
 .../planner/plan/fusion/FusionCodegenUtil.scala    |  84 ++++++-
 .../fusion/OpFusionCodegenSpecGeneratorBase.scala  | 107 ++++----
 .../plan/fusion/spec/CalcFusionCodegenSpec.scala   |  41 ++--
 .../fusion/spec/HashJoinFusionCodegenSpec.scala    | 269 +++++++++++----------
 .../spec/InputAdapterFusionCodegenSpec.scala       |  16 +-
 .../plan/fusion/spec/OutputFusionCodegenSpec.scala |   8 +-
 .../planner/utils/JavaScalaConversionUtil.scala    |   7 +-
 .../runtime/hashtable/BaseHybridHashTable.java     |   2 +-
 10 files changed, 322 insertions(+), 222 deletions(-)

diff --git a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecMultipleInput.java b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecMultipleInput.java
index c7b661609dd..8ffbcbc7fc9 100644
--- a/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecMultipleInput.java
+++ b/flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecMultipleInput.java
@@ -44,8 +44,8 @@ import org.apache.flink.table.planner.plan.nodes.exec.utils.ExecNodeUtil;
 import org.apache.flink.table.planner.plan.nodes.exec.visitor.AbstractExecNodeExactlyOnceVisitor;
 import org.apache.flink.table.runtime.operators.fusion.OperatorFusionCodegenFactory;
 import org.apache.flink.table.runtime.operators.multipleinput.BatchMultipleInputStreamOperatorFactory;
-import org.apache.flink.table.runtime.operators.multipleinput.MultipleInputSpec;
 import org.apache.flink.table.runtime.operators.multipleinput.TableOperatorWrapperGenerator;
+import org.apache.flink.table.runtime.operators.multipleinput.input.InputSelectionSpec;
 import org.apache.flink.table.runtime.operators.multipleinput.input.InputSpec;
 import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
 import org.apache.flink.table.types.logical.RowType;
@@ -140,7 +140,7 @@ public class BatchExecMultipleInput extends ExecNodeBase<RowData>
         boolean fusionCodegenEnabled = config.get(TABLE_EXEC_OPERATOR_FUSION_CODEGEN_ENABLED);
         // multiple operator fusion codegen
         if (fusionCodegenEnabled && allSupportFusionCodegen()) {
-            final List<MultipleInputSpec> multipleInputSpecs = new ArrayList<>();
+            final List<InputSelectionSpec> inputSelectionSpecs = new ArrayList<>();
             int i = 0;
             for (ExecEdge inputEdge : originalEdges) {
                 int multipleInputId = i + 1;
@@ -165,7 +165,7 @@ public class BatchExecMultipleInput extends ExecNodeBase<RowData>
                         ExecEdge.builder().source(inputAdapter).target(target).build());
 
                 // The input id and read order
-                multipleInputSpecs.add(new MultipleInputSpec(multipleInputId, readOrders[i]));
+                inputSelectionSpecs.add(new InputSelectionSpec(multipleInputId, readOrders[i]));
                 i++;
             }
 
@@ -184,7 +184,7 @@ public class BatchExecMultipleInput extends ExecNodeBase<RowData>
 
             // generate fusion operator
             Tuple2<OperatorFusionCodegenFactory<RowData>, Object> multipleOperatorTuple =
-                    FusionCodegenUtil.generateFusionOperator(outputGenerator, multipleInputSpecs);
+                    FusionCodegenUtil.generateFusionOperator(outputGenerator, inputSelectionSpecs);
             operatorFactory = multipleOperatorTuple._1;
 
             Pair<Integer, Integer> parallelismPair = getInputMaxParallelism(inputTransforms);
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/GeneratedExpression.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/GeneratedExpression.scala
index 13469590491..108ea10d1ad 100644
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/GeneratedExpression.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/GeneratedExpression.scala
@@ -39,7 +39,7 @@ import org.apache.flink.table.types.logical.LogicalType
 case class GeneratedExpression(
     resultTerm: String,
     nullTerm: String,
-    code: String,
+    var code: String,
     resultType: LogicalType,
     literalValue: Option[Any] = None) {
 
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/FusionCodegenUtil.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/FusionCodegenUtil.scala
index f80914a4a21..f2346b7d59f 100644
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/FusionCodegenUtil.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/FusionCodegenUtil.scala
@@ -19,30 +19,34 @@ package org.apache.flink.table.planner.plan.fusion
 
 import org.apache.flink.streaming.api.operators.{Input, InputSelection, StreamOperatorParameters}
 import org.apache.flink.table.data.RowData
-import org.apache.flink.table.planner.codegen.CodeGeneratorContext
+import org.apache.flink.table.planner.codegen.{CodeGeneratorContext, CodeGenException, GeneratedExpression}
 import org.apache.flink.table.planner.codegen.CodeGenUtils.{className, newName}
+import org.apache.flink.table.planner.codegen.GeneratedExpression.NO_CODE
 import org.apache.flink.table.planner.codegen.OperatorCodeGenerator.{OUT_ELEMENT, STREAM_RECORD}
 import org.apache.flink.table.planner.plan.fusion.OpFusionCodegenSpecGenerator.Context
 import org.apache.flink.table.runtime.generated.GeneratedOperator
 import org.apache.flink.table.runtime.operators.fusion.{FusionStreamOperatorBase, OperatorFusionCodegenFactory}
-import org.apache.flink.table.runtime.operators.multipleinput.MultipleInputSpec
-import org.apache.flink.table.runtime.operators.multipleinput.input.InputSelectionHandler
+import org.apache.flink.table.runtime.operators.multipleinput.input.{InputSelectionHandler, InputSelectionSpec}
+import org.apache.flink.table.types.logical.{LogicalType, RowType}
+
+import org.apache.calcite.rex.{RexInputRef, RexNode, RexVisitorImpl}
 
 import java.util
 
 import scala.collection.convert.ImplicitConversions.`collection AsScalaIterable`
+import scala.collection.mutable
 
 object FusionCodegenUtil {
 
   def generateFusionOperator(
       outputGenerator: OpFusionCodegenSpecGenerator,
-      inputSpecs: util.List[MultipleInputSpec]): (OperatorFusionCodegenFactory[RowData], Long) = {
+      inputSpecs: util.List[InputSelectionSpec]): (OperatorFusionCodegenFactory[RowData], Long) = {
     // Must initialize operator managedMemoryFraction before produce-consume call, codegen need it
     val (opSpecGenerators, totalManagedMemory) = setupOpSpecGenerator(outputGenerator)
 
     val fusionCtx = new CodeGeneratorContext(
-      outputGenerator.getOpFusionCodegenSpec.getOperatorCtx.tableConfig,
-      outputGenerator.getOpFusionCodegenSpec.getOperatorCtx.classLoader)
+      outputGenerator.getOpFusionCodegenSpec.getCodeGeneratorContext.tableConfig,
+      outputGenerator.getOpFusionCodegenSpec.getCodeGeneratorContext.classLoader)
 
     // generate process code
     outputGenerator.processProduce(fusionCtx)
@@ -168,4 +172,72 @@ object FusionCodegenUtil {
     // visit all input operator from output to leaf recursively
     outputOp.getInputs.foreach(op => getAllOpSpecGenerator(op, operators))
   }
+
+  /**
+   * Returns source code to evaluate all the variables, and clear the code of them, to prevent them
+   * to be evaluated twice.
+   */
+  def evaluateVariables(varExprs: Seq[GeneratedExpression]): String = {
+    val evaluate = varExprs.filter(_.code.nonEmpty).map(_.code).mkString("\n")
+    varExprs.foreach(_.code = NO_CODE)
+    evaluate
+  }
+
+  /**
+   * Returns source code to evaluate the variables for required attributes, to prevent them to be
+   * evaluated twice.
+   */
+  def evaluateRequiredVariables(
+      varExprs: Seq[GeneratedExpression],
+      requiredVarIndices: Set[Int]): String = {
+    val evaluateVars = new StringBuilder
+    requiredVarIndices.foreach(
+      index => {
+        val expr = varExprs(index)
+        if (expr.code.nonEmpty) {
+          evaluateVars.append(expr.code + "\n")
+          expr.code = NO_CODE
+        }
+      })
+    evaluateVars.toString()
+  }
+
+  def extractRefInputFields(
+      exprs: Seq[RexNode],
+      input1Type: LogicalType,
+      input2Type: LogicalType): (Set[Int], Set[Int]) = {
+    val visitor = new InputRefVisitor(input1Type, Option(input2Type))
+    // extract referenced input fields from expressions
+    exprs.foreach(_.accept(visitor))
+    (visitor.input1Fields.toSet, visitor.input2Fields.toSet)
+  }
+
+  def extractRefInputFields(exprs: Seq[RexNode], input1Type: LogicalType): Set[Int] = {
+    val visitor = new InputRefVisitor(input1Type)
+    // extract referenced input fields from expressions
+    exprs.foreach(_.accept(visitor))
+    visitor.input1Fields.toSet
+  }
+}
+
+/** An RexVisitor to extract all referenced input fields */
+class InputRefVisitor(input1Type: LogicalType, input2Type: Option[LogicalType] = None)
+  extends RexVisitorImpl[Unit](true) {
+
+  val input1Fields = mutable.ListBuffer[Int]()
+  val input2Fields = mutable.ListBuffer[Int]()
+
+  override def visitInputRef(inputRef: RexInputRef): Unit = {
+    val input1Arity = input1Type match {
+      case r: RowType => r.getFieldCount
+      case _ => 1
+    }
+    // if inputRef index is within size of input1 we work with input1, input2 otherwise
+    if (inputRef.getIndex < input1Arity) {
+      input1Fields += inputRef.getIndex
+    } else {
+      input2Type.getOrElse(throw new CodeGenException("Invalid input access."))
+      input2Fields += inputRef.getIndex - input1Arity
+    }
+  }
 }
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/OpFusionCodegenSpecGeneratorBase.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/OpFusionCodegenSpecGeneratorBase.scala
index 359326a50ec..ee174309689 100644
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/OpFusionCodegenSpecGeneratorBase.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/OpFusionCodegenSpecGeneratorBase.scala
@@ -21,10 +21,10 @@ import org.apache.flink.table.data.RowData
 import org.apache.flink.table.planner.codegen.{CodeGeneratorContext, ExprCodeGenerator, GeneratedExpression, GenerateUtils}
 import org.apache.flink.table.planner.codegen.CodeGenUtils.{fieldIndices, newName, DEFAULT_OUT_RECORD_WRITER_TERM}
 import org.apache.flink.table.planner.codegen.GeneratedExpression.{NEVER_NULL, NO_CODE}
+import org.apache.flink.table.planner.plan.fusion.FusionCodegenUtil.{evaluateRequiredVariables, evaluateVariables}
 import org.apache.flink.table.planner.utils.JavaScalaConversionUtil.{toJava, toScala}
 import org.apache.flink.table.types.logical.RowType
 
-import scala.collection.convert.ImplicitConversions.`collection AsScalaIterable`
 import scala.collection.mutable.ListBuffer
 
 /** The base class of {@link OpFusionCodegenSpecGenerator} that support operator fusion codegen. */
@@ -52,48 +52,52 @@ abstract class OpFusionCodegenSpecGeneratorBase(
 
   override def getManagedMemory: Long = managedMemory
 
-  def addReusableInitCode(fusionCtx: CodeGeneratorContext): Unit = {
-    val operatorCtx = getOperatorCtx
+  def addReusableInitCode(codegenCtx: CodeGeneratorContext): Unit = {
+    val opCodegenCtx = getCodeGeneratorContext
     // add operator reusable member and inner class definition to multiple codegen ctx
-    fusionCtx.addReusableMember(operatorCtx.reuseMemberCode())
-    fusionCtx.addReusableInnerClass(
+    codegenCtx.addReusableMember(opCodegenCtx.reuseMemberCode())
+    codegenCtx.addReusableInnerClass(
       newName(this.getClass.getCanonicalName),
-      operatorCtx.reuseInnerClassDefinitionCode())
+      opCodegenCtx.reuseInnerClassDefinitionCode())
 
     // add init code
-    val initCode = operatorCtx.reuseInitCode()
+    val initCode = opCodegenCtx.reuseInitCode()
     if (initCode.nonEmpty) {
       val initMethodTerm = newName(variablePrefix + "init")
-      fusionCtx.addReusableMember(
+      codegenCtx.addReusableMember(
         s"""
            |private void $initMethodTerm(Object[] references) throws Exception {
-           |  ${operatorCtx.reuseInitCode()}
+           |  ${opCodegenCtx.reuseInitCode()}
            |}
      """.stripMargin)
 
       val refs =
-        fusionCtx.addReusableObject(operatorCtx.references.toArray, variablePrefix + "Refs")
-      fusionCtx.addReusableInitStatement(s"$initMethodTerm($refs);")
+        codegenCtx.addReusableObject(opCodegenCtx.references.toArray, variablePrefix + "Refs")
+      codegenCtx.addReusableInitStatement(s"$initMethodTerm($refs);")
     }
   }
 
-  def addReusableOpenCode(fusionCtx: CodeGeneratorContext): Unit = {
+  def addReusableOpenCode(codegenCtx: CodeGeneratorContext): Unit = {
     // add open code
-    fusionCtx.addReusableOpenStatement(getOperatorCtx.reuseOpenCode())
+    codegenCtx.addReusableOpenStatement(getCodeGeneratorContext.reuseOpenCode())
   }
 
-  def addReusableCloseCode(fusionCtx: CodeGeneratorContext): Unit = {
+  def addReusableCloseCode(codegenCtx: CodeGeneratorContext): Unit = {
     // add close code
-    fusionCtx.addReusableCloseStatement(getOperatorCtx.reuseCloseCode())
+    codegenCtx.addReusableCloseStatement(getCodeGeneratorContext.reuseCloseCode())
   }
 
-  def processProduce(fusionCtx: CodeGeneratorContext): Unit = {
+  def processProduce(codegenCtx: CodeGeneratorContext): Unit = {
     if (!hasProcessProduceTraversed) {
-      opFusionCodegenSpec.doProcessProduce(fusionCtx)
+      opFusionCodegenSpec.doProcessProduce(codegenCtx)
       hasProcessProduceTraversed = true
     }
   }
 
+  /**
+   * <p> Note: The code of {@link GeneratedExpression} must not be empty for each member in
+   * outputVars, otherwise it has been evaluated before call this method.
+   */
   def processConsume(
       outputVars: java.util.List[GeneratedExpression],
       row: String = null): String = {
@@ -102,17 +106,19 @@ abstract class OpFusionCodegenSpecGeneratorBase(
       (toScala(outputVars), "")
     } else {
       assert(row != null, "outputVars and row can't both be null.")
-      getOperatorCtx.startNewLocalVariableStatement(row)
+      getCodeGeneratorContext.startNewLocalVariableStatement(row)
       val fieldExprs = fieldIndices(outputType)
-        .map(index => GenerateUtils.generateFieldAccess(getOperatorCtx, outputType, row, index))
+        .map(
+          index =>
+            GenerateUtils.generateFieldAccess(getCodeGeneratorContext, outputType, row, index))
         .toSeq
-      (fieldExprs, getOperatorCtx.reuseLocalVariableCode(row))
+      (fieldExprs, getCodeGeneratorContext.reuseLocalVariableCode(row))
     }
 
     // if this operator has multiple output operators, we need to materialize all vars in advance to
     // avoid be evaluated multiple times in downstream
     val evaluatedAllVars = if (outputs.length > 1) {
-      toScala(outputVars).map(expr => expr.getCode).mkString("\n")
+      evaluateVariables(inputVars)
     } else {
       ""
     }
@@ -126,16 +132,29 @@ abstract class OpFusionCodegenSpecGeneratorBase(
 
           // evaluate the expr code which will be used more than once in advance to avoid evaluated more time
           val evaluatedReqVars =
-            evaluateRequiredVariables(inputVars, outputSpec.usedInputVars(inputIdOfOutput))
+            evaluateRequiredVariables(
+              inputVars,
+              toScala(outputSpec.usedInputColumns(inputIdOfOutput)))
           val inputRowDataClass = outputSpec.getInputRowDataClass(inputIdOfOutput)
           val rowVar = prepareRowVar(row, inputVars, inputRowDataClass)
 
+          // need to copy composite type such as varchar for each output if has multiple output
+          val (deepCopyLocalVariable, copiedInputVars) = if (outputs.length > 1) {
+            val copiedRowVarTerm = newName("copiedRowVar")
+            getCodeGeneratorContext.startNewLocalVariableStatement(copiedRowVarTerm)
+            val copiedInputVars: Seq[GeneratedExpression] =
+              inputVars.map(_.deepCopy(getCodeGeneratorContext))
+            (getCodeGeneratorContext.reuseLocalVariableCode(copiedRowVarTerm), copiedInputVars)
+          } else {
+            ("", inputVars)
+          }
+
           // reuse input expr for output node
           val indices = fieldIndices(outputType)
           indices.foreach(
             index =>
-              outputSpec.getOperatorCtx
-                .addReusableInputUnboxingExprs(rowVar.resultTerm, index, inputVars(index)))
+              outputSpec.getCodeGeneratorContext
+                .addReusableInputUnboxingExprs(rowVar.resultTerm, index, copiedInputVars(index)))
           // bind downstream operator input type and input row before call its doProcessConsume
           if (inputIdOfOutput == 1) {
             outputSpec.getExprCodeGenerator
@@ -145,23 +164,12 @@ abstract class OpFusionCodegenSpecGeneratorBase(
               .bindSecondInput(outputType, rowVar.resultTerm, inputFieldMapping = Option(indices))
           }
 
-          // need to copy composite type such as varchar for each output if has multiple output
-          val (deepCopyLocalVariable, deepCopyCode) = if (outputs.length > 1) {
-            val copiedRowVarTerm = newName("copiedRowVar")
-            getOperatorCtx.startNewLocalVariableStatement(copiedRowVarTerm)
-            (
-              getOperatorCtx.reuseLocalVariableCode(copiedRowVarTerm),
-              inputVars.map(_.deepCopyMutableExpr(getOperatorCtx)).mkString("\n"))
-          } else {
-            ("", "")
-          }
           // always pass column vars and row var to output op simultaneously, the output decide to use which one
           s"""
              |$evaluatedReqVars
              |$deepCopyLocalVariable
-             |$deepCopyCode
              | // consume code
-             |${outputSpec.doProcessConsume(inputIdOfOutput, toJava(inputVars), rowVar)}
+             |${outputSpec.doProcessConsume(inputIdOfOutput, toJava(copiedInputVars), rowVar)}
              |""".stripMargin
         })
       .mkString("\n")
@@ -174,9 +182,9 @@ abstract class OpFusionCodegenSpecGeneratorBase(
      """.stripMargin
   }
 
-  def endInputProduce(fusionCtx: CodeGeneratorContext): Unit = {
+  def endInputProduce(codegenCtx: CodeGeneratorContext): Unit = {
     if (!hasEndInputProduceTraversed) {
-      opFusionCodegenSpec.doEndInputProduce(fusionCtx)
+      opFusionCodegenSpec.doEndInputProduce(codegenCtx)
       hasEndInputProduceTraversed = true
     }
   }
@@ -210,8 +218,7 @@ abstract class OpFusionCodegenSpecGeneratorBase(
       new GeneratedExpression(row, NEVER_NULL, NO_CODE, outputType)
     } else {
       getExprCodeGenerator.generateResultExpression(
-        // need copy the colVars first to avoid it code is used during generate row
-        colVars.map(_.copyExpr),
+        colVars,
         outputType,
         rowTypeClazz,
         getOutputRowTerm(row),
@@ -220,25 +227,7 @@ abstract class OpFusionCodegenSpecGeneratorBase(
     }
   }
 
-  /**
-   * Returns source code to evaluate the variables for required attributes, to prevent them to be
-   * evaluated twice.
-   */
-  private def evaluateRequiredVariables(
-      inputVars: Seq[GeneratedExpression],
-      requiredVariables: java.util.Set[Integer]): String = {
-    val evaluateVars = new StringBuilder
-    requiredVariables.foreach(
-      index => {
-        val expr = inputVars(index)
-        if (!expr.codeUsed) {
-          evaluateVars.append(expr.getCode + "\n")
-        }
-      })
-    evaluateVars.toString()
-  }
-
-  def getOperatorCtx: CodeGeneratorContext = opFusionCodegenSpec.getOperatorCtx
+  def getCodeGeneratorContext: CodeGeneratorContext = opFusionCodegenSpec.getCodeGeneratorContext
 
   def getExprCodeGenerator: ExprCodeGenerator = opFusionCodegenSpec.getExprCodeGenerator
 
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/CalcFusionCodegenSpec.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/CalcFusionCodegenSpec.scala
index 8c65daa3a49..155b6df671c 100644
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/CalcFusionCodegenSpec.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/CalcFusionCodegenSpec.scala
@@ -19,8 +19,9 @@ package org.apache.flink.table.planner.plan.fusion.spec
 
 import org.apache.flink.table.api.TableException
 import org.apache.flink.table.planner.codegen.{CodeGeneratorContext, GeneratedExpression}
+import org.apache.flink.table.planner.plan.fusion.FusionCodegenUtil.{evaluateRequiredVariables, extractRefInputFields}
 import org.apache.flink.table.planner.plan.fusion.OpFusionCodegenSpecBase
-import org.apache.flink.table.planner.utils.JavaScalaConversionUtil.toJava
+import org.apache.flink.table.planner.utils.JavaScalaConversionUtil.{toJava, toScala}
 
 import org.apache.calcite.rex.{RexInputRef, RexNode}
 
@@ -30,16 +31,16 @@ import scala.collection.convert.ImplicitConversions.`collection AsScalaIterable`
 
 /** The operator fusion codegen spec for Calc. */
 class CalcFusionCodegenSpec(
-    operatorCtx: CodeGeneratorContext,
+    opCodegenCtx: CodeGeneratorContext,
     projection: Seq[RexNode],
     condition: Option[RexNode])
-  extends OpFusionCodegenSpecBase(operatorCtx) {
+  extends OpFusionCodegenSpecBase(opCodegenCtx) {
 
   override def variablePrefix: String = "calc"
 
-  override def doProcessProduce(fusionCtx: CodeGeneratorContext): Unit = {
-    assert(fusionContext.getInputs.size == 1)
-    fusionContext.getInputs.head.processProduce(fusionCtx)
+  override def doProcessProduce(codegenCtx: CodeGeneratorContext): Unit = {
+    assert(fusionContext.getInputFusionContexts.size == 1)
+    fusionContext.getInputFusionContexts.head.processProduce(codegenCtx)
   }
 
   override def doProcessConsume(
@@ -47,12 +48,15 @@ class CalcFusionCodegenSpec(
       inputVars: util.List[GeneratedExpression],
       row: GeneratedExpression): String = {
     val onlyFilter =
-      projection.lengthCompare(fusionContext.getInputs.head.getOutputType.getFieldCount) == 0 &&
+      projection.lengthCompare(
+        fusionContext.getInputFusionContexts.head.getOutputType.getFieldCount) == 0 &&
         projection.zipWithIndex.forall {
           case (rexNode, index) =>
             rexNode.isInstanceOf[RexInputRef] && rexNode.asInstanceOf[RexInputRef].getIndex == index
         }
 
+    val projectionUsedColumns =
+      extractRefInputFields(projection, fusionContext.getInputFusionContexts.head.getOutputType)
     if (condition.isEmpty && onlyFilter) {
       throw new TableException(
         "This calc has no useful projection and no filter. " +
@@ -60,15 +64,22 @@ class CalcFusionCodegenSpec(
     } else if (condition.isEmpty) { // only projection
       val projectionExprs = projection.map(getExprCodeGenerator.generateExpression)
       s"""
+         |${evaluateRequiredVariables(toScala(inputVars), projectionUsedColumns)}
          |${fusionContext.processConsume(toJava(projectionExprs))}
          |""".stripMargin
     } else {
-      val filterCondition = getExprCodeGenerator.generateExpression(condition.get)
+      // materialize the field access code in advance which is referenced by filter condition to avoid it be evaluated more time
+      val filterUsedColumns = extractRefInputFields(
+        Seq(condition.get),
+        fusionContext.getInputFusionContexts.head.getOutputType)
+      val filterAccessCode = evaluateRequiredVariables(toScala(inputVars), filterUsedColumns)
+      val filterExpr = getExprCodeGenerator.generateExpression(condition.get)
       // only filter
       if (onlyFilter) {
         s"""
-           |${filterCondition.code}
-           |if (${filterCondition.resultTerm}) {
+           |$filterAccessCode
+           |${filterExpr.code}
+           |if (${filterExpr.resultTerm}) {
            |  ${fusionContext.processConsume(inputVars)}
            |}
            |""".stripMargin
@@ -76,8 +87,10 @@ class CalcFusionCodegenSpec(
         // if any filter conditions, projection code will enter an new scope
         val projectionExprs = projection.map(getExprCodeGenerator.generateExpression)
         s"""
-           |${filterCondition.code}
-           |if (${filterCondition.resultTerm}) {
+           |$filterAccessCode
+           |${filterExpr.code}
+           |if (${filterExpr.resultTerm}) {
+           |  ${evaluateRequiredVariables(toScala(inputVars), projectionUsedColumns)}
            |  ${fusionContext.processConsume(toJava(projectionExprs))}
            |}
            |""".stripMargin
@@ -85,8 +98,8 @@ class CalcFusionCodegenSpec(
     }
   }
 
-  override def doEndInputProduce(fusionCtx: CodeGeneratorContext): Unit = {
-    fusionContext.getInputs.head.endInputProduce(fusionCtx)
+  override def doEndInputProduce(codegenCtx: CodeGeneratorContext): Unit = {
+    fusionContext.getInputFusionContexts.head.endInputProduce(codegenCtx)
   }
 
   override def doEndInputConsume(inputId: Int): String = {
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/HashJoinFusionCodegenSpec.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/HashJoinFusionCodegenSpec.scala
index 532ab118517..f88e2074e96 100644
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/HashJoinFusionCodegenSpec.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/HashJoinFusionCodegenSpec.scala
@@ -22,7 +22,8 @@ import org.apache.flink.table.data.binary.BinaryRowData
 import org.apache.flink.table.planner.codegen.{CodeGeneratorContext, GeneratedExpression, GenerateUtils}
 import org.apache.flink.table.planner.codegen.CodeGenUtils.{fieldIndices, newName, newNames, primitiveDefaultValue, primitiveTypeTermForType, BINARY_ROW, ROW_DATA}
 import org.apache.flink.table.planner.codegen.LongHashJoinGenerator.{genGetLongKey, genProjection}
-import org.apache.flink.table.planner.plan.fusion.{OpFusionCodegenSpecBase, OpFusionCodegenSpecGenerator, OpFusionContext}
+import org.apache.flink.table.planner.plan.fusion.{OpFusionCodegenSpecBase, OpFusionContext}
+import org.apache.flink.table.planner.plan.fusion.FusionCodegenUtil.{evaluateRequiredVariables, extractRefInputFields}
 import org.apache.flink.table.planner.plan.nodes.exec.spec.JoinSpec
 import org.apache.flink.table.planner.utils.JavaScalaConversionUtil.{toJava, toScala}
 import org.apache.flink.table.runtime.hashtable.LongHybridHashTable
@@ -31,11 +32,13 @@ import org.apache.flink.table.runtime.typeutils.BinaryRowDataSerializer
 import org.apache.flink.table.runtime.util.RowIterator
 import org.apache.flink.table.types.logical.{LogicalType, RowType}
 
+import org.apache.calcite.rex.RexNode
+
 import java.util
 
 /** Base operator fusion codegen spec for HashJoin. */
 class HashJoinFusionCodegenSpec(
-    operatorCtx: CodeGeneratorContext,
+    opCodegenCtx: CodeGeneratorContext,
     isBroadcast: Boolean,
     leftIsBuild: Boolean,
     joinSpec: JoinSpec,
@@ -45,7 +48,7 @@ class HashJoinFusionCodegenSpec(
     estimatedRightRowCount: Long,
     compressionEnabled: Boolean,
     compressionBlockSize: Int)
-  extends OpFusionCodegenSpecBase(operatorCtx) {
+  extends OpFusionCodegenSpecBase(opCodegenCtx) {
 
   private lazy val joinType: FlinkJoinType = joinSpec.getJoinType
   private lazy val hashJoinType: HashJoinType = HashJoinType.of(
@@ -75,26 +78,26 @@ class HashJoinFusionCodegenSpec(
 
   private lazy val hashTableTerm: String = newName("hashTable")
 
-  private var buildInput: OpFusionCodegenSpecGenerator = _
-  private var probeInput: OpFusionCodegenSpecGenerator = _
+  private var buildContext: OpFusionContext = _
+  private var probeContext: OpFusionContext = _
   private var buildType: RowType = _
   private var probeType: RowType = _
   private var keyType: RowType = _
 
   override def setup(opFusionContext: OpFusionContext): Unit = {
     super.setup(opFusionContext)
-    val inputs = toScala(fusionContext.getInputs)
-    assert(inputs.size == 2)
+    val inputContexts = toScala(fusionContext.getInputFusionContexts)
+    assert(inputContexts.size == 2)
     if (leftIsBuild) {
-      buildInput = inputs.head
-      probeInput = inputs(1)
+      buildContext = inputContexts.head
+      probeContext = inputContexts(1)
     } else {
-      buildInput = inputs(1)
-      probeInput = inputs.head
+      buildContext = inputContexts(1)
+      probeContext = inputContexts.head
     }
 
-    buildType = buildInput.getOutputType
-    probeType = probeInput.getOutputType
+    buildType = buildContext.getOutputType
+    probeType = probeContext.getOutputType
     if (leftIsBuild) {
       keyType = RowType.of(joinSpec.getLeftKeys.map(idx => buildType.getTypeAt(idx)): _*)
     } else {
@@ -105,16 +108,16 @@ class HashJoinFusionCodegenSpec(
   override def variablePrefix: String = if (isBroadcast) { "bhj" }
   else { "shj" }
 
-  override protected def doProcessProduce(fusionCtx: CodeGeneratorContext): Unit = {
+  override protected def doProcessProduce(codegenCtx: CodeGeneratorContext): Unit = {
     // call build side first, then call probe side
-    buildInput.processProduce(fusionCtx)
-    probeInput.processProduce(fusionCtx)
+    buildContext.processProduce(codegenCtx)
+    probeContext.processProduce(codegenCtx)
   }
 
-  override protected def doEndInputProduce(fusionCtx: CodeGeneratorContext): Unit = {
+  override protected def doEndInputProduce(codegenCtx: CodeGeneratorContext): Unit = {
     // call build side first, then call probe side
-    buildInput.endInputProduce(fusionCtx)
-    probeInput.endInputProduce(fusionCtx)
+    buildContext.endInputProduce(codegenCtx)
+    probeContext.endInputProduce(codegenCtx)
   }
 
   override def doProcessConsume(
@@ -125,7 +128,7 @@ class HashJoinFusionCodegenSpec(
     if (inputId == buildInputId) {
       codegenBuild(toScala(inputVars), row)
     } else {
-      codegenProbe(inputVars)
+      codegenProbe(toScala(inputVars))
     }
   }
 
@@ -136,7 +139,7 @@ class HashJoinFusionCodegenSpec(
     if (isBroadcast) {
       codegenHashTable(false)
     } else {
-      // TODO Shuffled HashJoin support build side spill to disk
+      // TODO FLINK-32279 Shuffle HashJoin support build side spill to disk
       codegenHashTable(true)
     }
 
@@ -146,13 +149,13 @@ class HashJoinFusionCodegenSpec(
     s"""
        |$nullCheckBuildCode
        |if (!$nullCheckBuildTerm) {
-       |  ${row.getCode}
+       |  ${row.code}
        |  $hashTableTerm.putBuildRow(($BINARY_ROW) ${row.resultTerm});
        |}
        """.stripMargin
   }
 
-  private def codegenProbe(inputVars: util.List[GeneratedExpression]): String = {
+  private def codegenProbe(inputVars: Seq[GeneratedExpression]): String = {
     hashJoinType match {
       case HashJoinType.INNER =>
         codegenInnerProbe(inputVars)
@@ -165,19 +168,19 @@ class HashJoinFusionCodegenSpec(
     }
   }
 
-  private def codegenInnerProbe(inputVars: util.List[GeneratedExpression]): String = {
+  private def codegenInnerProbe(inputVars: Seq[GeneratedExpression]): String = {
     val (keyEv, anyNull) = genStreamSideJoinKey(probeKeys, inputVars)
-    val keyCode = keyEv.getCode
-    val (matched, checkCondition, buildLocalVars, buildVars) = getJoinCondition(buildType)
+    val (matched, checkCondition, buildLocalVars, buildVars) =
+      getJoinCondition(inputVars, buildType)
     val resultVars = if (leftIsBuild) {
-      buildVars ++ toScala(inputVars)
+      buildVars ++ inputVars
     } else {
-      toScala(inputVars) ++ buildVars
+      inputVars ++ buildVars
     }
     val buildIterTerm = newName("buildIter")
     s"""
        |// generate join key for probe side
-       |$keyCode
+       |${keyEv.code}
        |// find matches from hash table
        |${classOf[RowIterator[_]].getCanonicalName} $buildIterTerm = $anyNull ?
        |  null : $hashTableTerm.get(${keyEv.resultTerm});
@@ -193,13 +196,12 @@ class HashJoinFusionCodegenSpec(
            """.stripMargin
   }
 
-  private def codegenProbeOuterProbe(inputVars: util.List[GeneratedExpression]): String = {
+  private def codegenProbeOuterProbe(inputVars: Seq[GeneratedExpression]): String = {
     val (keyEv, anyNull) = genStreamSideJoinKey(probeKeys, inputVars)
-    val keyCode = keyEv.getCode
     val matched = newName("buildRow")
     // start new local variable
-    getOperatorCtx.startNewLocalVariableStatement(matched)
-    val buildVars = genInputVars(matched, buildType)
+    opCodegenCtx.startNewLocalVariableStatement(matched)
+    val buildVars = genBuildSideVars(opCodegenCtx, matched, buildType)
 
     // filter the output via condition
     val conditionPassed = newName("conditionPassed")
@@ -210,13 +212,16 @@ class HashJoinFusionCodegenSpec(
       } else {
         getExprCodeGenerator.bindSecondInput(buildType, matched)
       }
-      // TODO evaluate the variables from probe and build side that used by condition in advance
       // generate the expr code
-      val expr = getExprCodeGenerator.generateExpression(joinSpec.getNonEquiCondition.get)
+      val joinCondition = joinSpec.getNonEquiCondition.get
+      // evaluate the variables from probe and build side that used by condition
+      val evalCode = evaluateVarUsedInCondition(joinCondition, inputVars, buildVars)
+      val expr = getExprCodeGenerator.generateExpression(joinCondition)
       s"""
          |boolean $conditionPassed = true;
+         |$evalCode
          |if ($matched != null) {
-         |  ${expr.getCode}
+         |  ${expr.code}
          |  $conditionPassed = !${expr.nullTerm} && ${expr.resultTerm};
          |}
        """.stripMargin
@@ -224,26 +229,24 @@ class HashJoinFusionCodegenSpec(
       s"final boolean $conditionPassed = true;"
     }
 
-    // generate the final result vars that need to consider the null for outer join
-    val buildResultVars = genProbeOuterBuildVars(matched, buildVars)
     val resultVars = if (leftIsBuild) {
-      buildResultVars ++ toScala(inputVars)
+      buildVars ++ inputVars
     } else {
-      toScala(inputVars) ++ buildResultVars
+      inputVars ++ buildVars
     }
     val buildIterTerm = newName("buildIter")
     val found = newName("found")
     val hasNext = newName("hasNext")
     s"""
        |// generate join key for probe side
-       |$keyCode
+       |${keyEv.code}
        |
        |boolean $found = false;
        |boolean $hasNext = false;
        |// find matches from hash table
        |${classOf[RowIterator[_]].getCanonicalName} $buildIterTerm = $anyNull ?
        |  null : $hashTableTerm.get(${keyEv.resultTerm});
-       |${getOperatorCtx.reuseLocalVariableCode(matched)}
+       |${opCodegenCtx.reuseLocalVariableCode(matched)}
        |while (($buildIterTerm != null && ($hasNext = $buildIterTerm.advanceNext())) || !$found) {
        |  $ROW_DATA $matched = $buildIterTerm != null && $hasNext ? $buildIterTerm.getRow() : null;
        |  ${checkCondition.trim}
@@ -255,15 +258,14 @@ class HashJoinFusionCodegenSpec(
            """.stripMargin
   }
 
-  private def codegenSemiProbe(inputVars: util.List[GeneratedExpression]): String = {
+  private def codegenSemiProbe(inputVars: Seq[GeneratedExpression]): String = {
     val (keyEv, anyNull) = genStreamSideJoinKey(probeKeys, inputVars)
-    val keyCode = keyEv.getCode
-    val (matched, checkCondition, buildLocalVars, _) = getJoinCondition(buildType)
+    val (matched, checkCondition, buildLocalVars, _) = getJoinCondition(inputVars, buildType)
 
     val buildIterTerm = newName("buildIter")
     s"""
        |// generate join key for probe side
-       |$keyCode
+       |${keyEv.code}
        |// find matches from hash table
        |${classOf[RowIterator[_]].getCanonicalName} $buildIterTerm = $anyNull ?
        |  null : $hashTableTerm.get(${keyEv.resultTerm});
@@ -272,7 +274,7 @@ class HashJoinFusionCodegenSpec(
        |  while ($buildIterTerm.advanceNext()) {
        |    $ROW_DATA $matched = $buildIterTerm.getRow();
        |    $checkCondition {
-       |      ${fusionContext.processConsume(inputVars)}
+       |      ${fusionContext.processConsume(toJava(inputVars))}
        |      break;
        |    }
        |  }
@@ -280,17 +282,16 @@ class HashJoinFusionCodegenSpec(
            """.stripMargin
   }
 
-  private def codegenAntiProbe(inputVars: util.List[GeneratedExpression]): String = {
+  private def codegenAntiProbe(inputVars: Seq[GeneratedExpression]): String = {
     val (keyEv, anyNull) = genStreamSideJoinKey(probeKeys, inputVars)
-    val keyCode = keyEv.getCode
-    val (matched, checkCondition, buildLocalVars, _) = getJoinCondition(buildType)
+    val (matched, checkCondition, buildLocalVars, _) = getJoinCondition(inputVars, buildType)
 
     val buildIterTerm = newName("buildIter")
     val found = newName("found")
 
     s"""
        |// generate join key for probe side
-       |$keyCode
+       |${keyEv.code}
        |boolean $found = false;
        |// find matches from hash table
        |${classOf[RowIterator[_]].getCanonicalName} $buildIterTerm = $anyNull ?
@@ -307,7 +308,7 @@ class HashJoinFusionCodegenSpec(
        |}
        |
        |if (!$found) {
-       |  ${fusionContext.processConsume(inputVars)}
+       |  ${fusionContext.processConsume(toJava(inputVars))}
        |}
            """.stripMargin
   }
@@ -329,13 +330,13 @@ class HashJoinFusionCodegenSpec(
    * Returns the code for generating join key for stream side, and expression of whether the key has
    * any null in it or not.
    */
-  protected def genStreamSideJoinKey(
+  private def genStreamSideJoinKey(
       probeKeyMapping: Array[Int],
-      inputVars: util.List[GeneratedExpression]): (GeneratedExpression, String) = {
+      inputVars: Seq[GeneratedExpression]): (GeneratedExpression, String) = {
     // current only support one join key which is long type
     if (probeKeyMapping.length == 1) {
       // generate the join key as Long
-      val ev = inputVars.get(probeKeyMapping(0))
+      val ev = inputVars(probeKeyMapping(0))
       (ev, ev.nullTerm)
     } else {
       // generate the join key as BinaryRowData
@@ -344,7 +345,7 @@ class HashJoinFusionCodegenSpec(
     }
   }
 
-  protected def genAnyNullsInKeys(
+  private def genAnyNullsInKeys(
       keyMapping: Array[Int],
       input: Seq[GeneratedExpression]): (String, String) = {
     val builder = new StringBuilder
@@ -353,7 +354,7 @@ class HashJoinFusionCodegenSpec(
 
     keyMapping.foreach(
       key => {
-        codeBuilder.append(input(key).getCode + "\n")
+        codeBuilder.append(input(key).code + "\n")
         builder.append(s"$anyNullTerm |= ${input(key).nullTerm};")
       })
     (
@@ -365,7 +366,8 @@ class HashJoinFusionCodegenSpec(
       anyNullTerm)
   }
 
-  protected def getJoinCondition(
+  private def getJoinCondition(
+      probeVars: Seq[GeneratedExpression],
       buildType: RowType): (String, String, String, Seq[GeneratedExpression]) = {
     val buildRow = newName("buildRow")
     // here need bind the buildRow before generate build condition
@@ -375,15 +377,18 @@ class HashJoinFusionCodegenSpec(
       getExprCodeGenerator.bindSecondInput(buildType, buildRow)
     }
 
-    getOperatorCtx.startNewLocalVariableStatement(buildRow)
-    val buildVars = genInputVars(buildRow, buildType)
+    opCodegenCtx.startNewLocalVariableStatement(buildRow)
+    val buildVars = genBuildSideVars(opCodegenCtx, buildRow, buildType)
     val checkCondition = if (joinSpec.getNonEquiCondition.isPresent) {
-      // bind the build row name again
-      val expr = getExprCodeGenerator.generateExpression(joinSpec.getNonEquiCondition.get)
+      val joinCondition = joinSpec.getNonEquiCondition.get
+      // evaluate the variables from probe and build side that used by condition
+      val eval = evaluateVarUsedInCondition(joinCondition, probeVars, buildVars)
+      val expr = getExprCodeGenerator.generateExpression(joinCondition)
       val skipRow = s"${expr.nullTerm} || !${expr.resultTerm}"
       s"""
+         |$eval
          |// generate join condition
-         |${expr.getCode}
+         |${expr.code}
          |if (!($skipRow))
        """.stripMargin
     } else {
@@ -393,59 +398,75 @@ class HashJoinFusionCodegenSpec(
       if (hashJoinType.leftSemiOrAnti() && !joinSpec.getNonEquiCondition.isPresent) {
         ""
       } else {
-        getOperatorCtx.reuseLocalVariableCode(buildRow)
+        opCodegenCtx.reuseLocalVariableCode(buildRow)
       }
 
     (buildRow, checkCondition, buildLocalVars, buildVars)
   }
 
-  /** Generates build side expr for outer join. */
-  protected def genProbeOuterBuildVars(
+  /** Generates the input row variables expr. */
+  private def genBuildSideVars(
+      ctx: CodeGeneratorContext,
       buildRow: String,
-      buildVars: Seq[GeneratedExpression]): Seq[GeneratedExpression] = {
-    buildVars.zipWithIndex.map {
-      case (expr, i) =>
-        val fieldType = buildType.getTypeAt(i)
-        val resultTypeTerm = primitiveTypeTermForType(fieldType)
-        val defaultValue = primitiveDefaultValue(fieldType)
-        val Seq(fieldTerm, nullTerm) =
-          getOperatorCtx.addReusableLocalVariables((resultTypeTerm, "field"), ("boolean", "isNull"))
-        val code = s"""
-                      |$nullTerm = true;
-                      |$fieldTerm = $defaultValue;
-                      |if ($buildRow != null) {
-                      |  ${expr.getCode}
-                      |  $nullTerm = ${expr.nullTerm};
-                      |  $fieldTerm = ${expr.resultTerm};
-                      |}
+      buildType: RowType): Seq[GeneratedExpression] = {
+    fieldIndices(buildType)
+      .map(
+        index => {
+          var expr = GenerateUtils.generateFieldAccess(opCodegenCtx, buildType, buildRow, index)
+
+          if (hashJoinType == HashJoinType.PROBE_OUTER) {
+            val fieldType = buildType.getTypeAt(index)
+            val resultTypeTerm = primitiveTypeTermForType(fieldType)
+            val defaultValue = primitiveDefaultValue(fieldType)
+            val Seq(fieldTerm, nullTerm) =
+              opCodegenCtx
+                .addReusableLocalVariables((resultTypeTerm, "field"), ("boolean", "isNull"))
+            val code = s"""
+                          |$nullTerm = true;
+                          |$fieldTerm = $defaultValue;
+                          |if ($buildRow != null) {
+                          |  ${expr.code}
+                          |  $nullTerm = ${expr.nullTerm};
+                          |  $fieldTerm = ${expr.resultTerm};
+                          |}
           """.stripMargin
-        GeneratedExpression(fieldTerm, nullTerm, code, fieldType)
-    }
+            expr = GeneratedExpression(fieldTerm, nullTerm, code, fieldType)
+          }
+          // bind the field expr to ctx to reuse when generate join condition code
+          ctx
+            .addReusableInputUnboxingExprs(buildRow, index, expr)
+
+          expr
+        })
+      .toSeq
   }
 
-  /** Generates the input row variables expr. */
-  def genInputVars(inputRowTerm: String, inputType: RowType): Seq[GeneratedExpression] = {
-    val indices = fieldIndices(inputType)
-    val buildExprs = indices
-      .map(
-        index => GenerateUtils.generateFieldAccess(getOperatorCtx, inputType, inputRowTerm, index))
-      .toSeq
-    indices.foreach(
-      index =>
-        getOperatorCtx
-          .addReusableInputUnboxingExprs(inputRowTerm, index, buildExprs(index)))
+  private def evaluateVarUsedInCondition(
+      joinCondition: RexNode,
+      probeVars: Seq[GeneratedExpression],
+      buildVars: Seq[GeneratedExpression]): String = {
+    val (buildIndices, probeIndices) = if (buildInputId == 1) {
+      extractRefInputFields(Seq(joinCondition), buildType, probeType)
+    } else {
+      val (input1Indices, input2Indices) =
+        extractRefInputFields(Seq(joinCondition), probeType, buildType)
+      (input2Indices, input1Indices)
+    }
 
-    buildExprs
+    s"""
+       |${evaluateRequiredVariables(probeVars, probeIndices)}
+       |${evaluateRequiredVariables(buildVars, buildIndices)}
+       |""".stripMargin
   }
 
-  override def usedInputVars(inputId: Int): util.Set[Integer] = {
+  override def usedInputColumns(inputId: Int): util.Set[Integer] = {
+    val set: util.Set[Integer] = new util.HashSet[Integer]()
     if (inputId == buildInputId) {
-      val set: util.Set[Integer] = new util.HashSet[Integer]()
       buildKeys.toStream.map(key => set.add(key))
-      set
     } else {
-      super.usedInputVars(inputId)
+      probeKeys.toStream.map(key => set.add(key))
     }
+    set
   }
 
   override def getInputRowDataClass(inputId: Int): Class[_ <: RowData] = {
@@ -459,31 +480,31 @@ class HashJoinFusionCodegenSpec(
 
   private def codegenHashTable(spillEnabled: Boolean): Unit = {
     val buildSer = new BinaryRowDataSerializer(buildType.getFieldCount)
-    val buildSerTerm = operatorCtx.addReusableObject(buildSer, "buildSer")
+    val buildSerTerm = opCodegenCtx.addReusableObject(buildSer, "buildSer")
     val probeSer = new BinaryRowDataSerializer(probeType.getFieldCount)
-    val probeSerTerm = operatorCtx.addReusableObject(probeSer, "probeSer")
+    val probeSerTerm = opCodegenCtx.addReusableObject(probeSer, "probeSer")
 
     val bGenProj =
       genProjection(
-        operatorCtx.tableConfig,
-        operatorCtx.classLoader,
+        opCodegenCtx.tableConfig,
+        opCodegenCtx.classLoader,
         buildType.getChildren.toArray(Array[LogicalType]()))
-    operatorCtx.addReusableInnerClass(bGenProj.getClassName, bGenProj.getCode)
+    opCodegenCtx.addReusableInnerClass(bGenProj.getClassName, bGenProj.getCode)
     val pGenProj =
       genProjection(
-        operatorCtx.tableConfig,
-        operatorCtx.classLoader,
+        opCodegenCtx.tableConfig,
+        opCodegenCtx.classLoader,
         probeType.getChildren.toArray(Array[LogicalType]()))
-    operatorCtx.addReusableInnerClass(pGenProj.getClassName, pGenProj.getCode)
+    opCodegenCtx.addReusableInnerClass(pGenProj.getClassName, pGenProj.getCode)
 
-    operatorCtx.addReusableMember(s"${bGenProj.getClassName} $buildToBinaryRow;")
-    val buildProjRefs = operatorCtx.addReusableObject(bGenProj.getReferences, "buildProjRefs")
-    operatorCtx.addReusableInitStatement(
+    opCodegenCtx.addReusableMember(s"${bGenProj.getClassName} $buildToBinaryRow;")
+    val buildProjRefs = opCodegenCtx.addReusableObject(bGenProj.getReferences, "buildProjRefs")
+    opCodegenCtx.addReusableInitStatement(
       s"$buildToBinaryRow = new ${bGenProj.getClassName}($buildProjRefs);")
 
-    operatorCtx.addReusableMember(s"${pGenProj.getClassName} $probeToBinaryRow;")
-    val probeProjRefs = operatorCtx.addReusableObject(pGenProj.getReferences, "probeProjRefs")
-    operatorCtx.addReusableInitStatement(
+    opCodegenCtx.addReusableMember(s"${pGenProj.getClassName} $probeToBinaryRow;")
+    val probeProjRefs = opCodegenCtx.addReusableObject(pGenProj.getReferences, "probeProjRefs")
+    opCodegenCtx.addReusableInitStatement(
       s"$probeToBinaryRow = new ${pGenProj.getClassName}($probeProjRefs);")
 
     val hashTableClassTerm = newName("LongHashTable")
@@ -523,20 +544,20 @@ class HashJoinFusionCodegenSpec(
          |  }
          |}
        """.stripMargin
-    operatorCtx.addReusableInnerClass(hashTableClassTerm, tableCode)
-    operatorCtx.addReusableMember(s"$hashTableClassTerm $hashTableTerm;")
+    opCodegenCtx.addReusableInnerClass(hashTableClassTerm, tableCode)
+    opCodegenCtx.addReusableMember(s"$hashTableClassTerm $hashTableTerm;")
     val memorySizeTerm = newName("memorySize")
-    operatorCtx.addReusableOpenStatement(
+    opCodegenCtx.addReusableOpenStatement(
       s"long $memorySizeTerm = computeMemorySize(${fusionContext.getManagedMemoryFraction});")
-    operatorCtx.addReusableOpenStatement(
+    opCodegenCtx.addReusableOpenStatement(
       s"$hashTableTerm = new $hashTableClassTerm($memorySizeTerm);")
 
-    operatorCtx.addReusableCloseStatement(s"""
-                                             |if (this.$hashTableTerm != null) {
-                                             |  this.$hashTableTerm.close();
-                                             |  this.$hashTableTerm.free();
-                                             |  this.$hashTableTerm = null;
-                                             |}
+    opCodegenCtx.addReusableCloseStatement(s"""
+                                              |if (this.$hashTableTerm != null) {
+                                              |  this.$hashTableTerm.close();
+                                              |  this.$hashTableTerm.free();
+                                              |  this.$hashTableTerm = null;
+                                              |}
        """.stripMargin)
   }
 }
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/InputAdapterFusionCodegenSpec.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/InputAdapterFusionCodegenSpec.scala
index e369f8dcf04..e90a966af7e 100644
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/InputAdapterFusionCodegenSpec.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/InputAdapterFusionCodegenSpec.scala
@@ -26,24 +26,24 @@ import org.apache.flink.table.planner.plan.fusion.OpFusionCodegenSpecBase
 import java.util
 
 /** The operator fusion codegen spec for input operator. */
-class InputAdapterFusionCodegenSpec(operatorCtx: CodeGeneratorContext, inputId: Int)
-  extends OpFusionCodegenSpecBase(operatorCtx) {
+class InputAdapterFusionCodegenSpec(opCodegenCtx: CodeGeneratorContext, inputId: Int)
+  extends OpFusionCodegenSpecBase(opCodegenCtx) {
 
   override def variablePrefix: String = "input"
 
-  override protected def doProcessProduce(fusionCtx: CodeGeneratorContext): Unit = {
+  override protected def doProcessProduce(codegenCtx: CodeGeneratorContext): Unit = {
     val inputTypeTerm = boxedTypeTermForType(fusionContext.getOutputType)
     val inputTerm = DEFAULT_INPUT_TERM + inputId
 
     val processTerm = "processInput" + inputId
-    fusionCtx.addReusableMember(
+    codegenCtx.addReusableMember(
       s"""
          |public void $processTerm($inputTypeTerm $inputTerm) throws Exception {
          |  ${fusionContext.processConsume(null, inputTerm)}
          |}
          |""".stripMargin
     )
-    fusionCtx.addReusableFusionCodegenProcessStatement(
+    codegenCtx.addReusableFusionCodegenProcessStatement(
       inputId,
       s"""
          |new ${className[AbstractInput[_, _]]}(this, $inputId) {
@@ -64,16 +64,16 @@ class InputAdapterFusionCodegenSpec(operatorCtx: CodeGeneratorContext, inputId:
     throw new UnsupportedOperationException
   }
 
-  override protected def doEndInputProduce(fusionCtx: CodeGeneratorContext): Unit = {
+  override protected def doEndInputProduce(codegenCtx: CodeGeneratorContext): Unit = {
     val endInputTerm = "endInput" + inputId
-    fusionCtx.addReusableMember(
+    codegenCtx.addReusableMember(
       s"""
          |public void $endInputTerm() throws Exception {
          |  ${fusionContext.endInputConsume()}
          |}
          |""".stripMargin
     )
-    fusionCtx.addReusableFusionCodegenEndInputStatement(inputId, s"$endInputTerm();")
+    codegenCtx.addReusableFusionCodegenEndInputStatement(inputId, s"$endInputTerm();")
   }
 
   override def doEndInputConsume(inputId: Int): String = {
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/OutputFusionCodegenSpec.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/OutputFusionCodegenSpec.scala
index 799556c5c44..e2c013c9e29 100644
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/OutputFusionCodegenSpec.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/fusion/spec/OutputFusionCodegenSpec.scala
@@ -29,21 +29,21 @@ class OutputFusionCodegenSpec(operatorCtx: CodeGeneratorContext)
 
   override def variablePrefix: String = "output"
 
-  override protected def doProcessProduce(fusionCtx: CodeGeneratorContext): Unit =
-    fusionContext.getInputs.get(0).processProduce(fusionCtx)
+  override protected def doProcessProduce(codegenCtx: CodeGeneratorContext): Unit =
+    fusionContext.getInputFusionContexts.get(0).processProduce(codegenCtx)
 
   override def doProcessConsume(
       inputId: Int,
       inputVars: util.List[GeneratedExpression],
       row: GeneratedExpression): String = {
     s"""
-       |${row.getCode}
+       |${row.code}
        |${generateCollect(row.resultTerm)}
        |""".stripMargin.trim
   }
 
   override protected def doEndInputProduce(fusionCtx: CodeGeneratorContext): Unit =
-    fusionContext.getInputs.get(0).endInputProduce(fusionCtx)
+    fusionContext.getInputFusionContexts.get(0).endInputProduce(fusionCtx)
 
   override def doEndInputConsume(inputId: Int): String = ""
 }
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/utils/JavaScalaConversionUtil.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/utils/JavaScalaConversionUtil.scala
index 2b3e2fda80e..84ea3d15d8d 100644
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/utils/JavaScalaConversionUtil.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/utils/JavaScalaConversionUtil.scala
@@ -19,7 +19,7 @@ package org.apache.flink.table.planner.utils
 
 import org.apache.flink.api.java.tuple.{Tuple2 => JTuple2}
 
-import java.util.{List => JList, Optional}
+import java.util.{List => JList, Optional, Set => JSet}
 import java.util.function.{BiConsumer, Consumer, Function}
 
 import scala.collection.JavaConverters._
@@ -54,4 +54,9 @@ object JavaScalaConversionUtil {
 
   def toScala[T0, T1](tuple: JTuple2[T0, T1]): (T0, T1) =
     (tuple.f0, tuple.f1)
+
+  def toScala(set: JSet[Integer]): Set[Int] = set.asScala.map(_.toInt).toSet
+
+  def toJava(set: Set[Int]): JSet[Integer] =
+    set.map(_.asInstanceOf[Integer]).asJava
 }
diff --git a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/hashtable/BaseHybridHashTable.java b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/hashtable/BaseHybridHashTable.java
index 6fbd8938b13..32b32cad0ad 100644
--- a/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/hashtable/BaseHybridHashTable.java
+++ b/flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/hashtable/BaseHybridHashTable.java
@@ -101,7 +101,7 @@ public abstract class BaseHybridHashTable implements MemorySegmentPool {
 
     /**
      * In operator fusion codegen case, we don't support spill to disk for broadcast hashjoin, so
-     * his flag is introduced.
+     * this flag is introduced.
      */
     protected final boolean spillEnabled;