Skip to content

Redundant overflow check in a simple 3-line function #77195

Open
@glessard

Description

@glessard

Description

From an implementation of the prefix(count:) function for an UnsafeBufferPointer-like struct:

    public func testOne(k: Int) -> Int {
        precondition(k >= 0)
        let dc = min(k, _count)
        return _count-dc
    }

The _count-dc line produces an overflow check (in -O), even though the possibility of overflow has been excluded by the previous operations.

Reproduction

struct Z {
    let _count: Int

    public func testOne(k: Int) -> Int {
        precondition(k >= 0)
        let dc = min(k, _count)
        return _count-dc
    }

    public func testTwo(k: Int) -> Int {
        precondition(k >= 0)
        let dc = min(k, _count)
        return _count&-dc
    }
}

Expected behavior

testTwo() produces one branch (in the precondition). I would expect the same of testOne(), since the precondition and the min() function combine to make an overflow impossible. However, testOne() produces two branches, one in the precondition and the other in the - operator.

Environment

Swift version 6.1-dev (LLVM 95f3fb07f8f5294, Swift 8ae66ec)
Target: x86_64-unknown-linux-gnu

Additional information

rdar://138518973

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.optimized onlyFlag: An issue whose reproduction requires optimized compilationperformance

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions