Skip to content

[AVR] integer division incorrectly yields result value 1 #82242

Closed
rust-lang/compiler-builtins
#462
@crclark96

Description

@crclark96

I'm writing some code for arduino using the avr-hal crate, and when I print the result of a division operation, I'm getting the result value of 1 for almost every combination of numbers. Exceptions that I've found so far include when the divisor is a power of two, which I'm assuming is being optimized to a bitshift operation (this is not happening in my minimum code example, I do not know why but it happened in another context so I'm including this detail here in case it comes up again).

I tried this code:

#![no_std]
#![no_main]

extern crate panic_halt;

use arduino_uno::prelude::*;

#[arduino_uno::entry]
fn main() -> ! {
    let dp = arduino_uno::Peripherals::take().unwrap();

    let mut pins = arduino_uno::Pins::new(
        dp.PORTB,
        dp.PORTC,
        dp.PORTD,
    );
    let mut serial = arduino_uno::Serial::new(
        dp.USART0,
        pins.d0,
        pins.d1.into_output(&mut pins.ddr),
        57600.into_baudrate(),
    );

    for x in (5..100).step_by(5) {
        for y in 1..5 {
            let z = x / y;
            ufmt::uwriteln!(&mut serial, "{} / {} = {}\r", x, y, z).void_unwrap();
        }
    }
    loop {}
}

Output:

5 / 1 = 1
5 / 2 = 1
5 / 3 = 1
5 / 4 = 1
10 / 1 = 1
10 / 2 = 1
10 / 3 = 1
10 / 4 = 1
-- snip --
90 / 1 = 1
90 / 2 = 1
90 / 3 = 1
90 / 4 = 1
95 / 1 = 1
95 / 2 = 1
95 / 3 = 1
95 / 4 = 1

Meta

rustc --version --verbose:

rustc 1.51.0-nightly (c2de47a9a 2021-01-06)
binary: rustc
commit-hash: c2de47a9aa4c9812884f341f1852e9c9610f5f7a
commit-date: 2021-01-06
host: x86_64-unknown-linux-gnu
release: 1.51.0-nightly

I'm using nightly-2021-01-07 since AVR support has been broken since then. The code has to be built with the --release flag due to this issue: rust-lang/compiler-builtins#400

Here's the repo with the code and configs for AVR: https://github.com/crclark96/avr-division-repro. I'm using an Arduino Uno board for this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.O-AVRTarget: AVR processors (ATtiny, ATmega, etc.)requires-nightlyThis issue requires a nightly compiler in some way.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions