GCC: accuracy of strict aliasing warnings

后端 未结 4 840
囚心锁ツ
囚心锁ツ 2020-12-16 12:19

I\'m trying to check some of my code for strict aliasing violations, but it looks like I\'ve missed something while trying to understand the strict aliasing rule.

Im

4条回答
  •  失恋的感觉
    2020-12-16 12:49

    Your understanding is correct. Alias analysis is generally complicated and in this case apparently the mere use of a temporary pointer between the cast and dereference was enough to throw it off. Surprisingly, GCC 4.8.2 does a better job on this code, warning at -Wstrict-aliasing=2 as well as level 1, so this is a regression.

    As for clang, it simply does not currently have the facility to warn about aliasing violations. It does absolutely take advantage of the rule in optimization. To see this in action, take this example straight from the C standard (N1570 §6.5.2.3 9))

    struct t1 { int m; };
    struct t2 { int m; };
    
    int f(struct t1 *p1, struct t2 *p2) {
        if (p1->m < 0)
            p2->m = -p2->m;
        return p1->m;
    }
    

    If p1 and p2 point to the same struct, Clang (and GCC) will nevertheless return the value of p1->m before negation, since they may assume p2 does not alias p1 and therefore the previous negation never affects the result. Here's the full example and output with and without -fstrict-aliasing. For more examples, see here and the oft-cited What Every C Programmer Should Know About Undefined Behavior; strict aliasing optimizations are the final topic of the introductory post.

    As for when warnings will be implemented, the devs are quiet, but they are mentioned in clang's test suite, which lists -Wstrict-aliasing=X under the title (emphasis mine)

    These flags are currently unimplemented; test that we output them anyway.

    So it seems likely to happen at some point.

提交回复
热议问题