How to save the exact insertion point

Hi, I use OpBuilder to create my mlir, I would like to save a currently inserting point and resume it later.

However the OpBuilder::saveInsertionPoint() does not work if the block and insertion point are the same, it will insert ops after the current last op.

So I would like to ask if there is a way to save an exact place, including the n’th option, so that I can do the save and restore thing.

Thanks a lot!!

Example: The insertion point on b below is saved and get it back at the end of this scope (in braces).

{
  OpBuilder::InsertionGuard g(b);
  b.setInsertionPoint(ifOp->getParentOfType<FuncOp>())
  b.create<...>
  ...
}
1 Like

Hi, thanks for answering and could I further ask what it I would like to save it in one function and restore it in another??

I just looked it up, the guard actually called saveInsertionPoint()… which is the same method.

thus if the insertion point, which is a block::iterator object, does not change, it will create op after the last op created in the insertion point…

The insertion point identifies an op before which new ops are inserted. Consider inserting ops A and B into the following IR:

op1
op2
op3   # <-- insertion point
op4

calling builder.create<A>(...)

op1
op2
A     # A is inserted _before_ the point
op3   # <-- insertion point still here
op4

calling builder.create<B>(...)

op1
op2
A
B     # B is inserted _before_ the point
op3   # <-- insertion point
op4

So creating ops in a sequence will put them in the sequence before the op that the insertion point points to (or at the end of the block if it doesn’t point to an op). This is the reasonable behavior if you think about it: writing

Value result = builder.create<A>(...)
builder.create<B>(result);

one would expect B to be created after A not before, and having to move the insertion point to achieve this extremely common behavior would be obnoxious. Also, inserting before the element pointer to by the iterator is the normal behavior of C++ containers.

What you seem to want is to insert further ops before some ops you create. To do this, just call builder.setInsertionPoint(the-operation-before-which-to-insert-ops). Then you can save/restore the insertion point as much as you want. You can pass it around between functions, but it isn’t really common in MLIR because it is hard to track and debug.

1 Like