https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105994

            Bug ID: 105994
           Summary: Incorrect optimization with -ftree-sra and casting
                    (strictly compatible) refs
           Product: gcc
           Version: 13.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: gcc_bugzilla.calin79 at neverbox dot com
  Target Milestone: ---

This code (also in attachment) should return 106, but instead returns 14:


////////////////////////////////////////////////////////////////

struct bar
{
    int id;
};

struct foo
{
    int id;
};

inline const bar& h(const foo& t)
{
    return reinterpret_cast<const bar&>(t);
}

int g(foo t)
{
    const bar& test = h(foo{t});

    if(test.id == 5)
        return 7;

    return test.id;
}

int main()
{
    int a = g(foo{5});
    int b = g(foo{99});
    return a + b;
}
////////////////////////////////////////////////////////////////


It happens with -O1 - and more specifically, as long as `-finline -ftree-ccp
-ftree-sra` are enabled.


Version: gcc version 13.0.0 20220615 (experimental) (GCC)
    built from latest master as of 2022-06-15,
dc9b92facf87a6f2d8b0e5d5fc404f30c3b15a74
Target: x86_64-pc-linux-gnu
Configured with: ../src/configure
--prefix=/opt/compiler-explorer/gcc-build/install --enable-languages=c++

Triggered with:
g++ -std=c++20 -O1 -o buggy_bin_14 gcc_bug_reference_cast.cpp
# should print 106 (7 + 99)
./buggy_bin_14; echo $?
# instead prints 14 - g() always returns 7

Shortest number of optimizations that triggers it:
g++ -std=c++20 -O1 -fno-auto-inc-dec -fno-branch-count-reg
-fno-combine-stack-adjustments -fno-compare-elim -fno-cprop-registers -fno-dce
-fno-defer-pop -fno-delayed-branch -fno-dse -fno-forward-propagate
-fno-guess-branch-probability -fno-if-conversion -fno-if-conversion2
-fno-inline-functions-called-once -fno-ipa-profile -fno-ipa-pure-const
-fno-ipa-reference -fno-ipa-reference-addressable -fno-merge-constants
-fno-move-loop-invariants -fno-omit-frame-pointer -fno-reorder-blocks
-fno-shrink-wrap -fno-shrink-wrap-separate -fno-split-wide-types
-fno-ssa-backprop -fno-ssa-phiopt -fno-tree-bit-ccp -fno-tree-ch
-fno-tree-coalesce-vars -fno-tree-copy-prop -fno-tree-dce
-fno-tree-dominator-opts -fno-tree-dse -fno-tree-forwprop -fno-tree-fre
-fno-tree-phiprop -fno-tree-pta -fno-tree-scev-cprop -fno-tree-sink
-fno-tree-slsr -fno-tree-ter -fno-unit-at-a-time -finline -ftree-ccp -ftree-sra
-o buggy_bin_14 gcc_bug_reference_cast.cpp

Compiler output:
None

Reply via email to