Skip to content

Commit 91d5653

Browse files
[mlir] Use OpBuilder::createBlock in op builders and patterns (#82770)
When creating a new block in (conversion) rewrite patterns, `OpBuilder::createBlock` must be used. Otherwise, no `notifyBlockInserted` notification is sent to the listener. Note: The dialect conversion relies on listener notifications to keep track of IR modifications. Creating blocks without the builder API can lead to memory leaks during rollback.
1 parent 96abee5 commit 91d5653

File tree

20 files changed

+71
-88
lines changed

20 files changed

+71
-88
lines changed

mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1456,7 +1456,7 @@ def LLVM_LLVMFuncOp : LLVM_Op<"func", [
14561456
let extraClassDeclaration = [{
14571457
// Add an entry block to an empty function, and set up the block arguments
14581458
// to match the signature of the function.
1459-
Block *addEntryBlock();
1459+
Block *addEntryBlock(OpBuilder &builder);
14601460

14611461
bool isVarArg() { return getFunctionType().isVarArg(); }
14621462

mlir/include/mlir/Dialect/SPIRV/IR/SPIRVControlFlowOps.td

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ def SPIRV_LoopOp : SPIRV_Op<"mlir.loop", [InFunctionScope]> {
285285

286286
// Adds an empty entry block and loop merge block containing one
287287
// spirv.mlir.merge op.
288-
void addEntryAndMergeBlock();
288+
void addEntryAndMergeBlock(OpBuilder &builder);
289289
}];
290290

291291
let hasOpcode = 0;
@@ -427,7 +427,7 @@ def SPIRV_SelectionOp : SPIRV_Op<"mlir.selection", [InFunctionScope]> {
427427
Block *getMergeBlock();
428428

429429
/// Adds a selection merge block containing one spirv.mlir.merge op.
430-
void addMergeBlock();
430+
void addMergeBlock(OpBuilder &builder);
431431

432432
/// Creates a spirv.mlir.selection op for `if (<condition>) then { <thenBody> }`
433433
/// with `builder`. `builder`'s insertion point will remain at after the

mlir/include/mlir/Interfaces/FunctionInterfaces.td

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ def FunctionOpInterface : OpInterface<"FunctionOpInterface", [
131131
static void buildWithEntryBlock(
132132
OpBuilder &builder, OperationState &state, StringRef name, Type type,
133133
ArrayRef<NamedAttribute> attrs, TypeRange inputTypes) {
134+
OpBuilder::InsertionGuard g(builder);
134135
state.addAttribute(SymbolTable::getSymbolAttrName(),
135136
builder.getStringAttr(name));
136137
state.addAttribute(ConcreteOp::getFunctionTypeAttrName(state.name),
@@ -139,8 +140,7 @@ def FunctionOpInterface : OpInterface<"FunctionOpInterface", [
139140

140141
// Add the function body.
141142
Region *bodyRegion = state.addRegion();
142-
Block *body = new Block();
143-
bodyRegion->push_back(body);
143+
Block *body = builder.createBlock(bodyRegion);
144144
for (Type input : inputTypes)
145145
body->addArgument(input, state.location);
146146
}

mlir/lib/Conversion/AsyncToLLVM/AsyncToLLVM.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ static void addResumeFunction(ModuleOp module) {
259259
kResume, LLVM::LLVMFunctionType::get(voidTy, {ptrType}));
260260
resumeOp.setPrivate();
261261

262-
auto *block = resumeOp.addEntryBlock();
262+
auto *block = resumeOp.addEntryBlock(moduleBuilder);
263263
auto blockBuilder = ImplicitLocOpBuilder::atBlockEnd(loc, block);
264264

265265
blockBuilder.create<LLVM::CoroResumeOp>(resumeOp.getArgument(0));

mlir/lib/Conversion/ControlFlowToSCF/ControlFlowToSCF.cpp

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,12 +98,10 @@ ControlFlowToSCFTransformation::createStructuredDoWhileLoopOp(
9898
loc, builder.create<arith::TruncIOp>(loc, builder.getI1Type(), condition),
9999
loopVariablesNextIter);
100100

101-
auto *afterBlock = new Block;
102-
whileOp.getAfter().push_back(afterBlock);
101+
Block *afterBlock = builder.createBlock(&whileOp.getAfter());
103102
afterBlock->addArguments(
104103
loopVariablesInit.getTypes(),
105104
SmallVector<Location>(loopVariablesInit.size(), loc));
106-
builder.setInsertionPointToEnd(afterBlock);
107105
builder.create<scf::YieldOp>(loc, afterBlock->getArguments());
108106

109107
return whileOp.getOperation();

mlir/lib/Conversion/FuncToLLVM/FuncToLLVM.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ static void wrapForExternalCallers(OpBuilder &rewriter, Location loc,
135135
propagateArgResAttrs(rewriter, !!resultStructType, funcOp, wrapperFuncOp);
136136

137137
OpBuilder::InsertionGuard guard(rewriter);
138-
rewriter.setInsertionPointToStart(wrapperFuncOp.addEntryBlock());
138+
rewriter.setInsertionPointToStart(wrapperFuncOp.addEntryBlock(rewriter));
139139

140140
SmallVector<Value, 8> args;
141141
size_t argOffset = resultStructType ? 1 : 0;
@@ -203,7 +203,7 @@ static void wrapExternalFunction(OpBuilder &builder, Location loc,
203203

204204
// The wrapper that we synthetize here should only be visible in this module.
205205
newFuncOp.setLinkage(LLVM::Linkage::Private);
206-
builder.setInsertionPointToStart(newFuncOp.addEntryBlock());
206+
builder.setInsertionPointToStart(newFuncOp.addEntryBlock(builder));
207207

208208
// Get a ValueRange containing arguments.
209209
FunctionType type = cast<FunctionType>(funcOp.getFunctionType());

mlir/lib/Conversion/MemRefToLLVM/MemRefToLLVM.cpp

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -520,9 +520,7 @@ struct GlobalMemrefOpLowering
520520
global, arrayTy, global.getConstant(), linkage, global.getSymName(),
521521
initialValue, alignment, *addressSpace);
522522
if (!global.isExternal() && global.isUninitialized()) {
523-
Block *blk = new Block();
524-
newGlobal.getInitializerRegion().push_back(blk);
525-
rewriter.setInsertionPointToStart(blk);
523+
rewriter.createBlock(&newGlobal.getInitializerRegion());
526524
Value undef[] = {
527525
rewriter.create<LLVM::UndefOp>(global.getLoc(), arrayTy)};
528526
rewriter.create<LLVM::ReturnOp>(global.getLoc(), undef);

mlir/lib/Conversion/SCFToSPIRV/SCFToSPIRV.cpp

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -138,14 +138,13 @@ struct ForOpConversion final : SCFToSPIRVPattern<scf::ForOp> {
138138
// from header to merge.
139139
auto loc = forOp.getLoc();
140140
auto loopOp = rewriter.create<spirv::LoopOp>(loc, spirv::LoopControl::None);
141-
loopOp.addEntryAndMergeBlock();
141+
loopOp.addEntryAndMergeBlock(rewriter);
142142

143143
OpBuilder::InsertionGuard guard(rewriter);
144144
// Create the block for the header.
145-
auto *header = new Block();
146-
// Insert the header.
147-
loopOp.getBody().getBlocks().insert(getBlockIt(loopOp.getBody(), 1),
148-
header);
145+
Block *header = rewriter.createBlock(&loopOp.getBody(),
146+
getBlockIt(loopOp.getBody(), 1));
147+
rewriter.setInsertionPointAfter(loopOp);
149148

150149
// Create the new induction variable to use.
151150
Value adapLowerBound = adaptor.getLowerBound();
@@ -342,7 +341,7 @@ struct WhileOpConversion final : SCFToSPIRVPattern<scf::WhileOp> {
342341
ConversionPatternRewriter &rewriter) const override {
343342
auto loc = whileOp.getLoc();
344343
auto loopOp = rewriter.create<spirv::LoopOp>(loc, spirv::LoopControl::None);
345-
loopOp.addEntryAndMergeBlock();
344+
loopOp.addEntryAndMergeBlock(rewriter);
346345

347346
Region &beforeRegion = whileOp.getBefore();
348347
Region &afterRegion = whileOp.getAfter();

mlir/lib/Dialect/Affine/IR/AffineOps.cpp

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1813,6 +1813,8 @@ void AffineForOp::build(OpBuilder &builder, OperationState &result,
18131813
"upper bound operand count does not match the affine map");
18141814
assert(step > 0 && "step has to be a positive integer constant");
18151815

1816+
OpBuilder::InsertionGuard guard(builder);
1817+
18161818
// Set variadic segment sizes.
18171819
result.addAttribute(
18181820
getOperandSegmentSizeAttr(),
@@ -1841,12 +1843,11 @@ void AffineForOp::build(OpBuilder &builder, OperationState &result,
18411843
// Create a region and a block for the body. The argument of the region is
18421844
// the loop induction variable.
18431845
Region *bodyRegion = result.addRegion();
1844-
bodyRegion->push_back(new Block);
1845-
Block &bodyBlock = bodyRegion->front();
1846+
Block *bodyBlock = builder.createBlock(bodyRegion);
18461847
Value inductionVar =
1847-
bodyBlock.addArgument(builder.getIndexType(), result.location);
1848+
bodyBlock->addArgument(builder.getIndexType(), result.location);
18481849
for (Value val : iterArgs)
1849-
bodyBlock.addArgument(val.getType(), val.getLoc());
1850+
bodyBlock->addArgument(val.getType(), val.getLoc());
18501851

18511852
// Create the default terminator if the builder is not provided and if the
18521853
// iteration arguments are not provided. Otherwise, leave this to the caller
@@ -1855,9 +1856,9 @@ void AffineForOp::build(OpBuilder &builder, OperationState &result,
18551856
ensureTerminator(*bodyRegion, builder, result.location);
18561857
} else if (bodyBuilder) {
18571858
OpBuilder::InsertionGuard guard(builder);
1858-
builder.setInsertionPointToStart(&bodyBlock);
1859+
builder.setInsertionPointToStart(bodyBlock);
18591860
bodyBuilder(builder, result.location, inductionVar,
1860-
bodyBlock.getArguments().drop_front());
1861+
bodyBlock->getArguments().drop_front());
18611862
}
18621863
}
18631864

@@ -2895,18 +2896,20 @@ void AffineIfOp::build(OpBuilder &builder, OperationState &result,
28952896
TypeRange resultTypes, IntegerSet set, ValueRange args,
28962897
bool withElseRegion) {
28972898
assert(resultTypes.empty() || withElseRegion);
2899+
OpBuilder::InsertionGuard guard(builder);
2900+
28982901
result.addTypes(resultTypes);
28992902
result.addOperands(args);
29002903
result.addAttribute(getConditionAttrStrName(), IntegerSetAttr::get(set));
29012904

29022905
Region *thenRegion = result.addRegion();
2903-
thenRegion->push_back(new Block());
2906+
builder.createBlock(thenRegion);
29042907
if (resultTypes.empty())
29052908
AffineIfOp::ensureTerminator(*thenRegion, builder, result.location);
29062909

29072910
Region *elseRegion = result.addRegion();
29082911
if (withElseRegion) {
2909-
elseRegion->push_back(new Block());
2912+
builder.createBlock(elseRegion);
29102913
if (resultTypes.empty())
29112914
AffineIfOp::ensureTerminator(*elseRegion, builder, result.location);
29122915
}
@@ -3693,6 +3696,7 @@ void AffineParallelOp::build(OpBuilder &builder, OperationState &result,
36933696
"expected upper bound maps to have as many inputs as upper bound "
36943697
"operands");
36953698

3699+
OpBuilder::InsertionGuard guard(builder);
36963700
result.addTypes(resultTypes);
36973701

36983702
// Convert the reductions to integer attributes.
@@ -3738,11 +3742,11 @@ void AffineParallelOp::build(OpBuilder &builder, OperationState &result,
37383742

37393743
// Create a region and a block for the body.
37403744
auto *bodyRegion = result.addRegion();
3741-
auto *body = new Block();
3745+
Block *body = builder.createBlock(bodyRegion);
3746+
37423747
// Add all the block arguments.
37433748
for (unsigned i = 0, e = steps.size(); i < e; ++i)
37443749
body->addArgument(IndexType::get(builder.getContext()), result.location);
3745-
bodyRegion->push_back(body);
37463750
if (resultTypes.empty())
37473751
ensureTerminator(*bodyRegion, builder, result.location);
37483752
}

mlir/lib/Dialect/Async/IR/Async.cpp

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ void ExecuteOp::getSuccessorRegions(RegionBranchPoint point,
6868
void ExecuteOp::build(OpBuilder &builder, OperationState &result,
6969
TypeRange resultTypes, ValueRange dependencies,
7070
ValueRange operands, BodyBuilderFn bodyBuilder) {
71-
71+
OpBuilder::InsertionGuard guard(builder);
7272
result.addOperands(dependencies);
7373
result.addOperands(operands);
7474

@@ -87,26 +87,21 @@ void ExecuteOp::build(OpBuilder &builder, OperationState &result,
8787

8888
// Add a body region with block arguments as unwrapped async value operands.
8989
Region *bodyRegion = result.addRegion();
90-
bodyRegion->push_back(new Block);
91-
Block &bodyBlock = bodyRegion->front();
90+
Block *bodyBlock = builder.createBlock(bodyRegion);
9291
for (Value operand : operands) {
9392
auto valueType = llvm::dyn_cast<ValueType>(operand.getType());
94-
bodyBlock.addArgument(valueType ? valueType.getValueType()
95-
: operand.getType(),
96-
operand.getLoc());
93+
bodyBlock->addArgument(valueType ? valueType.getValueType()
94+
: operand.getType(),
95+
operand.getLoc());
9796
}
9897

9998
// Create the default terminator if the builder is not provided and if the
10099
// expected result is empty. Otherwise, leave this to the caller
101100
// because we don't know which values to return from the execute op.
102101
if (resultTypes.empty() && !bodyBuilder) {
103-
OpBuilder::InsertionGuard guard(builder);
104-
builder.setInsertionPointToStart(&bodyBlock);
105102
builder.create<async::YieldOp>(result.location, ValueRange());
106103
} else if (bodyBuilder) {
107-
OpBuilder::InsertionGuard guard(builder);
108-
builder.setInsertionPointToStart(&bodyBlock);
109-
bodyBuilder(builder, result.location, bodyBlock.getArguments());
104+
bodyBuilder(builder, result.location, bodyBlock->getArguments());
110105
}
111106
}
112107

0 commit comments

Comments
 (0)