Problem about inlineRegionBefore func

I’m a novice user to mlir and I want to add an affine_for op in a func:
initial mlir:

 func @f(%arg0: memref<200x200x200xf64>, %arg1: memref<200x200x200xf64>) {
    %cst = constant 1.250000e-01 : f64
    %cst_0 = constant 2.000000e+00 : f64
    affine.for %arg2 = 1 to 198 {
      affine.for %arg3 = 1 to 198 {
           %0 = affine.load %arg0[%arg2 + 1, %arg3, %arg4] : memref<200x200x200xf64>
      }
    }
    return
  }

my target mlir

 func @f(%arg0: memref<200x200x200xf64>, %arg1: memref<200x200x200xf64>) {
 affine.for %arg4 = 1 to 500{  
   %cst = constant 1.250000e-01 : f64
   %cst_0 = constant 2.000000e+00 : f64
   affine.for %arg2 = 1 to 198 {
      affine.for %arg3 = 1 to 198 {
         %0 = affine.load %arg0[%arg2 + 1, %arg3, %arg4] : memref<200x200x200xf64>
      }
    }
  }
 return
}

I can change the initial file to this form:

 func @f(%arg0: memref<200x200x200xf64>, %arg1: memref<200x200x200xf64>) {
   affine.for %arg4 = 1 to 500{  
   }
   %cst = constant 1.250000e-01 : f64
   %cst_0 = constant 2.000000e+00 : f64
   affine.for %arg2 = 1 to 198 {
      affine.for %arg3 = 1 to 198 {
         %0 = affine.load %arg0[%arg2 + 1, %arg3, %arg4] : memref<200x200x200xf64>
      }
    }
   return
}

But I have no idea about how to move the ops in func’s region(except return op) to affine region.
And if I use inlineRegionBefore to move affine for op in the original func’s region to the new affine for region, I’ll get this error:

error: operand #0 does not dominate this use

Any help on how to achieve this target is appreciated !!!

You can move operations using Operation::moveBefore/moveAfter (llvm-project/Operation.cpp at 51ba13b1aea3d6e04310b80b6bcfc641049b9890 · llvm/llvm-project · GitHub), that takes an iterator. Trying moving operations one-by-one before the end iterator.

Alternatively, split the block after the affine.for you introduced and before return, then merge the central block into the body block of the affine.for.

inlineRegionBefore, as its name indicates, moves the entire region. So you can’t move the affine.for with it, you are either moving the body of the loop, or the body of the function, neither of which is what you are trying to achieve.