Skip to content

Commit

Permalink
[CIR][Lowering][Bugfix] Lower ScopeOp with return op (#364)
Browse files Browse the repository at this point in the history
`ScopeOp` may end with `ReturnOp` instead of `YieldOp`, that is not
expected now. This PR fix this.
The reduced example is:
```
int foo() {
    {
        return 0;
    }
}
```
This is quite frequent bug in `llvm-test-suite`
  • Loading branch information
gitoleg authored and lanza committed Mar 23, 2024
1 parent 46ca5a3 commit 3f00bd3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
4 changes: 2 additions & 2 deletions clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -818,9 +818,9 @@ class CIRScopeOpLowering
// Replace the scopeop return with a branch that jumps out of the body.
// Stack restore before leaving the body region.
rewriter.setInsertionPointToEnd(afterBody);
auto yieldOp = cast<mlir::cir::YieldOp>(afterBody->getTerminator());
auto yieldOp = dyn_cast<mlir::cir::YieldOp>(afterBody->getTerminator());

if (!isBreakOrContinue(yieldOp)) {
if (yieldOp && !isBreakOrContinue(yieldOp)) {
auto branchOp = rewriter.replaceOpWithNewOp<mlir::cir::BrOp>(
yieldOp, yieldOp.getArgs(), continueBlock);

Expand Down
29 changes: 28 additions & 1 deletion clang/test/CIR/Lowering/scope.cir
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,31 @@ module {
// MLIR-NEXT: llvm.return
// MLIR-NEXT: }

}

cir.func @scope_with_return() -> !u32i {
%0 = cir.alloca !u32i, cir.ptr <!u32i>, ["__retval"] {alignment = 4 : i64}
cir.scope {
%2 = cir.const(#cir.int<0> : !u32i) : !u32i
cir.store %2, %0 : !u32i, cir.ptr <!u32i>
%3 = cir.load %0 : cir.ptr <!u32i>, !u32i
cir.return %3 : !u32i
}
%1 = cir.load %0 : cir.ptr <!u32i>, !u32i
cir.return %1 : !u32i
}

// MLIR: llvm.func @scope_with_return()
// MLIR-NEXT: [[v0:%.*]] = llvm.mlir.constant(1 : index) : i64
// MLIR-NEXT: [[v1:%.*]] = llvm.alloca [[v0]] x i32 {alignment = 4 : i64} : (i64) -> !llvm.ptr
// MLIR-NEXT: llvm.br ^bb1
// MLIR-NEXT: ^bb1: // pred: ^bb0
// MLIR-NEXT: [[v2:%.*]] = llvm.mlir.constant(0 : i32) : i32
// MLIR-NEXT: llvm.store [[v2]], [[v1]] : i32, !llvm.ptr
// MLIR-NEXT: [[v3:%.*]] = llvm.load [[v1]] : !llvm.ptr -> i32
// MLIR-NEXT: llvm.return [[v3]] : i32
// MLIR-NEXT: ^bb2: // no predecessors
// MLIR-NEXT: [[v4:%.*]] = llvm.load [[v1]] : !llvm.ptr -> i32
// MLIR-NEXT: llvm.return [[v4]] : i32
// MLIR-NEXT: }

}

0 comments on commit 3f00bd3

Please sign in to comment.