In 4.2 with -O2 -m32 -fomit-frame-pointer on x86_64: unsigned int foo (unsigned int x) { return (8 - (x & 7)) & 7; } results in andl $7, reg; negl reg; andl $7, reg. On 4.3 apparently some RTL optimization catches this, but it is still a missed tree optimization, fold should be able to fold: (cst - (x & cstmask)) & cstmask2 as (cst & cstmask2) + (-x & cstmask2) if x is unsigned or if -INT_MIN wraps to INT_MIN, both cstmask and cstmask2 are constants z^2-1 for some z and (cstmask & cstmask2) == cstmask2. BTW, even for (8 + (x & 7)) & 7 the optimized dump contains: (x & 7) + 8 & 7 for both 4.2/4.3 (no idea why 8 & 7 hasn't been simplified as 0).
(x & 7) + 8 & 7 is actually ((x & 7) + 8) & 7
You would need to enhance associate_trees () or the reassoc pass to fix this.
Created attachment 13244 [details] gcc43-pr31261.patch Patch I'm testing ATM.
I think this could be generalized to more operators, e.g. (y | (x & 7)) & 7 ^ (bitwise or, xor, multiply, ...) This optimization could be for "e & M" where e contains a subexpression of the form "t & N" which can (sometimes) be simplified to "t". I suppose that would require walking the tree.
Author: jakub Date: Thu Sep 30 19:21:34 2010 New Revision: 164761 URL: http://gcc.gnu.org/viewcvs?root=gcc&view=rev&rev=164761 Log: PR tree-optimization/31261 * fold-const.c (fold_binary): Optimize ((A & N) + B) & M for constants M and N, M == (1LL << cst) - 1 && (N & M) == M. * gcc.dg/tree-ssa/pr31261.c: New test. Added: trunk/gcc/testsuite/gcc.dg/tree-ssa/pr31261.c Modified: trunk/gcc/ChangeLog trunk/gcc/fold-const.c trunk/gcc/testsuite/ChangeLog
Fixed.