Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/codegen/flat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4795,7 +4795,7 @@ mod tests {
#[test]
fn emits_verifiable_affine_for_loop() {
// A signed range that nothing leaves is an `affine.for`. The bound `n` is cast to `index`
// before the loop, and the loop variable is cast back to `i32`.
// before the loop, and the loop variable becomes an i32 without signed overflow.
let mlir = emit_and_verify(
"fn sum(n: i32) -> i32 { let mut s = 0; for i in 0..n { s = s + i; } return s; }",
);
Expand All @@ -4804,7 +4804,7 @@ mod tests {
"{mlir}"
);
assert!(mlir.contains("affine.for "), "{mlir}");
assert!(mlir.contains(" : index to i32"), "{mlir}");
assert!(mlir.contains("overflow<nsw> : i64 to i32"), "{mlir}");
assert!(!mlir.contains("cf.cond_br "), "{mlir}");
assert!(!mlir.contains("scf.execute_region"), "{mlir}");
}
Expand Down
9 changes: 8 additions & 1 deletion src/codegen/flat/emit/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,14 @@ impl FnEmit<'_> {
let branches = ins.imm & AFFINE_FOR_BRANCHES != 0;
let at = self.body.len();
self.body += &format!(" affine.for {index} = {} to {} {{\n", bounds[0], bounds[1]);
self.body += &format!(" %v{idx} = arith.index_cast {index} : index to {mt}\n");
if e == ElementType::I32 {
// Both bounds are i32, so every counter value fits without signed overflow.
self.body += &format!(" %v{idx}_wide = arith.index_cast {index} : index to i64\n");
self.body +=
&format!(" %v{idx} = arith.trunci %v{idx}_wide overflow<nsw> : i64 to i32\n");
} else {
self.body += &format!(" %v{idx} = arith.index_cast {index} : index to {mt}\n");
}
if branches {
self.body += " scf.execute_region {\n";
}
Expand Down
30 changes: 26 additions & 4 deletions src/codegen/lower/control_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -662,10 +662,32 @@ fn lower_for_loop<'c>(
// a tuple or a tensor literal that holds it then gets the type it expects.
let iter_binding =
if start_ty != ty_index && melior::ir::r#type::TypeLike::is_integer(&start_ty) {
let cast = OperationBuilder::new("arith.index_cast", gen.loc())
.add_operands(&[current_idx])
.add_results(&[start_ty])
.build()?;
let cast = if start_ty == gen.i32_ty && !range_is_unsigned(gen, for_loop) {
// Both bounds are i32, so every counter value fits without signed overflow.
let wide = body_block
.append_operation(
OperationBuilder::new("arith.index_cast", gen.loc())
.add_operands(&[current_idx])
.add_results(&[gen.i64_ty])
.build()?,
)
.result(0)?
.into();
OperationBuilder::new("arith.trunci", gen.loc())
.add_operands(&[wide])
.add_results(&[start_ty])
.add_attributes(&[(
Identifier::new(gen.context, "overflowFlags"),
melior::ir::Attribute::parse(gen.context, "#arith.overflow<nsw>")
.expect("valid signed overflow flag"),
)])
.build()?
} else {
OperationBuilder::new("arith.index_cast", gen.loc())
.add_operands(&[current_idx])
.add_results(&[start_ty])
.build()?
};
(
body_block.append_operation(cast).result(0)?.into(),
start_ty,
Expand Down
17 changes: 17 additions & 0 deletions src/dialect/VxLowering.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13950,6 +13950,23 @@ struct RaiseLoopAccessesPass

void runOnOperation() override {
func::FuncOp func = getOperation();
// An exact signed truncation followed by a cast back to index recovers the
// counter. Fold it before raising accesses, so a[i] stays an affine access.
unsigned indexBits = DataLayout::closest(func)
.getTypeSizeInBits(IndexType::get(&getContext()))
.getFixedValue();
func.walk([&](arith::IndexCastOp cast) {
auto trunc = cast.getIn().getDefiningOp<arith::TruncIOp>();
if (!trunc || !trunc.hasNoSignedWrap())
return;
auto wide = trunc.getIn().getDefiningOp<arith::IndexCastOp>();
if (wide && isa<IntegerType>(wide.getType()) &&
wide.getType().getIntOrFloatBitWidth() >= indexBits &&
wide.getIn().getType() == cast.getType()) {
cast.replaceAllUsesWith(wide.getIn());
cast.erase();
}
});
OpPassManager pm(func::FuncOp::getOperationName());
if (failed(parsePassPipeline("affine-raise-from-memref", pm)) ||
failed(runPipeline(pm, func))) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ fn triangle(n: i32) -> i32 {
// IF-LABEL: func.func @with_if
// IF: affine.for
// IF-NEXT: arith.index_cast
// IF-NEXT: arith.trunci
// IF-NEXT: scf.execute_region {
fn with_if(n: i32) -> i32 {
let mut s = 0;
Expand Down
47 changes: 47 additions & 0 deletions tests/optimizations/pass/exact_counter_casts_recover_the_index.mlr
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// An exact signed narrowing can recover an index only if the first cast kept every bit.
// RUN: vxc %s -x mlir --emit-mlir -X mlir=--pass-pipeline="builtin.module(func.func(vx-raise-loop-accesses))" | FileCheck %s
module {
// CHECK-LABEL: func.func @exact(
// CHECK-SAME: %[[ORIGINAL:[^:]+]]: index)
// CHECK-NOT: func.func
// CHECK: return %[[ORIGINAL]] : index
func.func @exact(%i: index) -> index {
%wide = arith.index_cast %i : index to i64
%small = arith.trunci %wide overflow<nsw> : i64 to i32
%back = arith.index_cast %small : i32 to index
return %back : index
}

// CHECK-LABEL: func.func @may_wrap(
// CHECK-NOT: func.func
// CHECK: %[[BACK:[^ ]+]] = arith.index_cast {{.*}} : i32 to index
// CHECK: return %[[BACK]] : index
func.func @may_wrap(%i: index) -> index {
%wide = arith.index_cast %i : index to i64
%small = arith.trunci %wide : i64 to i32
%back = arith.index_cast %small : i32 to index
return %back : index
}

// CHECK-LABEL: func.func @first_cast_loses_bits(
// CHECK-NOT: func.func
// CHECK: %[[NARROW_BACK:[^ ]+]] = arith.index_cast {{.*}} : i16 to index
// CHECK: return %[[NARROW_BACK]] : index
func.func @first_cast_loses_bits(%i: index) -> index {
%wide = arith.index_cast %i : index to i32
%small = arith.trunci %wide overflow<nsw> : i32 to i16
%back = arith.index_cast %small : i16 to index
return %back : index
}

// Vector casts are also legal input to the pass.
// CHECK-LABEL: func.func @vector_casts(
// CHECK-NOT: func.func
// CHECK: return {{.*}} : vector<2xindex>
func.func @vector_casts(%i: vector<2xindex>) -> vector<2xindex> {
%wide = arith.index_cast %i : vector<2xindex> to vector<2xi64>
%small = arith.trunci %wide overflow<nsw> : vector<2xi64> to vector<2xi32>
%back = arith.index_cast %small : vector<2xi32> to vector<2xindex>
return %back : vector<2xindex>
}
}
85 changes: 85 additions & 0 deletions tests/optimizations/pass/i32_range_checks_are_removed.vx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
//===- i32_range_checks_are_removed.vx - Vx Compiler ----------*- Vx -*-===//
//
// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions.
// See LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// An i32 range keeps its signed bounds when the loop counter becomes an i32.
// LLVM can then remove the helper's redundant check.
// Only LEGACY tests the legacy code generator change. Its OPT and VECTOR checks
// also pass without this change.
//
// REQUIRES: flat-codegen
// REQUIRES: x86_64
// REQUIRES: aarch64
// RUN: vxc %s --emit-mlir 2>/dev/null | FileCheck %s --check-prefix=CAST
// RUN: vxc %s --legacy-codegen --emit-mlir 2>/dev/null | FileCheck %s --check-prefix=LEGACY
// RUN: vxc %s -O3 --emit-llvm 2>/dev/null | mlir-translate --mlir-to-llvmir | opt -mtriple=%arch-unknown-linux-gnu -mcpu=native -passes='default<O3>' -S > %t.ll
// RUN: FileCheck %s --check-prefix=OPT < %t.ll
// RUN: FileCheck %s --check-prefix=VECTOR < %t.ll
// RUN: vxc %s --legacy-codegen -O3 --emit-llvm 2>/dev/null | mlir-translate --mlir-to-llvmir | opt -mtriple=%arch-unknown-linux-gnu -mcpu=native -passes='default<O3>' -S > %t.legacy.ll
// RUN: FileCheck %s --check-prefix=OPT < %t.legacy.ll
// RUN: FileCheck %s --check-prefix=VECTOR < %t.legacy.ll
// RUN: vxc %s -O0 2>/dev/null | FileCheck %s --check-prefix=ANSWER
// RUN: vxc %s --legacy-codegen -O0 2>/dev/null | FileCheck %s --check-prefix=ANSWER
// RUN: vxc %s -O3 2>/dev/null | FileCheck %s --check-prefix=ANSWER
// RUN: vxc %s --legacy-codegen -O3 2>/dev/null | FileCheck %s --check-prefix=ANSWER

import core::convert;
import std::vec;

fn checked_value(p : *mut i64, i : i32, n : i32) -> i64 {
assert(i < n, "index out of range");
return unsafe { p[i] };
}

// CAST-LABEL: func.func @sum_counts(
// CAST-NOT: func.func
// CAST: affine.for %[[INDEX:[^ ]+]]
// CAST: %[[WIDE:[^ ]+]] = arith.index_cast %[[INDEX]] : index to i64
// CAST-NEXT: {{.*}}arith.trunci %[[WIDE]] overflow<nsw> : i64 to i32
// LEGACY-LABEL: func.func @sum_counts(
// LEGACY-NOT: func.func
// LEGACY: arith.trunci {{.*}} overflow<nsw> : i64 to i32
// OPT-LABEL: define {{.*}} @sum_counts(
// OPT-NOT: @abort
// OPT: {{^}}}
// VECTOR-LABEL: define {{.*}} @sum_counts(
// VECTOR-NOT: {{^}}}
// VECTOR: call i64 @llvm.vector.reduce.add.v{{[0-9]+}}i64(
// VECTOR: {{^}}}
fn sum_counts(p : *mut i64, n : i32) -> i64 {
let mut total : i64 = 0;
for i in 0..n {
total = total + checked_value(p, i, n);
}
return total;
}

fn sum_range(first : i32, last : i32) -> i64 {
let mut total : i64 = 0;
for i in first..last {
total = total + i64::from(i);
}
return total;
}

fn sum_unsigned(first : u32, last : u32) -> u64 {
let mut total : u64 = 0;
for i in first..last {
total = total + u64::from(i);
}
return total;
}

// ANSWER: {{^}}16 -5 2147483646 -4294967295 0 4294967294{{$}}
fn main() -> i32 {
let mut values = Vec<i64>::with_capacity(16);
for i in 0..16 {
values.push(1);
}
println!("{} {} {} {} {} {}", sum_counts(values.as_mut_ptr(), 16), sum_range(-3, 2),
sum_range(2147483646, 2147483647), sum_range(-2147483648, -2147483646), sum_range(2, -3), sum_unsigned(4294967294u32, 4294967295u32));
return 0;
}
Loading