| Message ID | 20261011111209.3214394-1-daniel.barboza@oss.qualcomm.com |
|---|---|
| State | New |
| Headers |
Return-Path: <gcc-patches-bounces~patchwork=sourceware.org@gcc.gnu.org> X-Original-To: patchwork@sourceware.org Delivered-To: patchwork@sourceware.org Received: from vm01.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 27F384BA2E1E for <patchwork@sourceware.org>; Sun, 11 Oct 2026 11:13:00 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 27F384BA2E1E Authentication-Results: sourceware.org; dkim=pass (2048-bit key, unprotected) header.d=qualcomm.com header.i=@qualcomm.com header.a=rsa-sha256 header.s=qcppdkim1 header.b=lFg4PDOe; dkim=pass (2048-bit key, unprotected) header.d=oss.qualcomm.com header.i=@oss.qualcomm.com header.a=rsa-sha256 header.s=google header.b=WxkBDtK9 X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mx0a-0031df01.pphosted.com (mx0a-0031df01.pphosted.com [205.220.168.131]) by sourceware.org (Postfix) with ESMTPS id 931C24BA2E0F for <gcc-patches@gcc.gnu.org>; Sun, 11 Oct 2026 11:12:18 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org 931C24BA2E0F Authentication-Results: sourceware.org; dmarc=none (p=none dis=none) header.from=oss.qualcomm.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=oss.qualcomm.com ARC-Filter: OpenARC Filter v1.0.0 sourceware.org 931C24BA2E0F Authentication-Results: sourceware.org; arc=none smtp.remote-ip=205.220.168.131 ARC-Seal: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1791717139; cv=none; b=OT6M3wJ0QyCV3bU6ItAUG7XFsMzakSwn9hCVUQySmEZ1vMBw3HMNFYILNEiTTMWkrqVIhsDpTLFW1UjVboKn+j9kO3RFSyznzCuRF2myMg6QihN89umR9l4+TmkXJ6z3tvOuDkWssM7NSJnTNY/rLSSl834cFfNCYka79W6c6a4= ARC-Message-Signature: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1791717139; c=relaxed/simple; bh=ozPF61TMXYZND7o90xXmM87dxa3iB63l/bKnLO8ltr4=; h=DKIM-Signature:DKIM-Signature:From:To:Subject:Date:Message-ID: MIME-Version; b=tb//CesziGNI6YLvznBM7PG8ZF8jvZrGVEg3xd5TWAzPKnuyJH8zcUjeXHdY54YNixt3x+upiHJH1GZHKKOgDcCfBm3mxPwistrvN1GndtMItIf2Fz1ql8dko2pkP9caadRooWErkI08YBhG23uf8BPj3jXuumjlC0N+SiNhWGI= ARC-Authentication-Results: i=1; sourceware.org; dkim=pass (2048-bit key, unprotected) header.d=qualcomm.com header.i=@qualcomm.com header.a=rsa-sha256 header.s=qcppdkim1 header.b=lFg4PDOe; dkim=pass (2048-bit key, unprotected) header.d=oss.qualcomm.com header.i=@oss.qualcomm.com header.a=rsa-sha256 header.s=google header.b=WxkBDtK9 DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 931C24BA2E0F Received: from pps.filterd (m0279865.ppops.net [127.0.0.1]) by mx0a-0031df01.pphosted.com (8.18.1.11/8.18.1.11) with ESMTP id 69B851Ea3981857 for <gcc-patches@gcc.gnu.org>; Sun, 11 Oct 2026 11:12:15 GMT DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=qualcomm.com; h= cc:content-transfer-encoding:date:from:message-id:mime-version :subject:to; s=qcppdkim1; bh=7tYf+1K09mxBwjrXdKQcxG83MF3+ttta0d5 IBB1X2dI=; b=lFg4PDOeaKNrU6Dp1VIpUQpU00RLLzFOKccfOtaDBvG59TohLUi SimQXJVUz3l2O+trp/RPlCkgU8g4//HKYkKG7MLq1TyEtPP5LhuuPlV2GSrDAurG gTXo6lfudUajrmdZbm++vpRd1NgBeXtgKv3pzUZ7F1Je2TnfXjUBJaf2sdGy+ez+ 6oTTMMEEspQ0rKStN0i53sDIxA9E5OGYJYl0Hgo5K747J8jpv8Qe9xVv0t8Tjkqk OHbTK2z3keDKmJgp+R4BWaYB9/vulv3VT03rIZAx1MXg2rUNxZMIZ3pz2Ia/8Rqv zZC/P6JSN1SH3O0HHOZevlE9j2qr3epOi+Q== Received: from mail-qk1-f200.google.com (mail-qk1-f200.google.com [209.85.222.200]) by mx0a-0031df01.pphosted.com (PPS) with ESMTPS id 4h7casb19k-1 (version=TLSv1.3 cipher=TLS_AES_128_GCM_SHA256 bits=128 verify=NOT) for <gcc-patches@gcc.gnu.org>; Sun, 11 Oct 2026 11:12:15 +0000 (GMT) Received: by mail-qk1-f200.google.com with SMTP id af79cd13be357-93cc7a6e4e1so371906485a.1 for <gcc-patches@gcc.gnu.org>; Sun, 11 Oct 2026 04:12:15 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=oss.qualcomm.com; s=google; t=1791717134; x=1792321934; darn=gcc.gnu.org; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:from:to:cc:subject:date:message-id:reply-to:content-type; bh=7tYf+1K09mxBwjrXdKQcxG83MF3+ttta0d5IBB1X2dI=; b=WxkBDtK9Qe9viBxt0eRyKE//YXXFIPHfINfA9Lqr2mn0qt7jro6eguSMI3qIres0+y YIMTnqo1JB4+zLoSb3QdIAbx0AV/CRhXLdl5FrGfnoZ+2tJQ/cVHQgrUbzH1o53r23vU j//qUlsRV1lpCTARiUevU/sxTtSEqdR4Pam1pOf2czi6deaOXJOBGl9ujfGXHcG+8J+M 93hZuoJocsEF98K5i7h8ZbQc5vvgO7lTLCJGQdOMswMrr8X8kkVuAiW+Fo9gCFwQfgkG J5SuvkydAovpsygACSgzhaNKf+v/nTeoAqFd5iLU5qyTy/jdA7GibL6Pc3DNE+JnMTEz hfdA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1791717134; x=1792321934; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:x-gm-gg:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=7tYf+1K09mxBwjrXdKQcxG83MF3+ttta0d5IBB1X2dI=; b=pCSCpZwseoFacScC7Ot9AKv+VUuhoC4R6930JdHAhLjq8ijS5Jnr04zw33+FJ4es8S ZPEUFin51R7faI0ZuMCyaA4XCc5zDK5WngOT9xTFNrMBu3wGPM4dGMNxklM9qjoeI1Dk +o/eooxOUD0xklNk96CkpRVF9SgGN3eefZPwqMK1BXIp89WX6IoHKEEeEyZpR7PUegHR vxTkJbiKc1J7m45LPA28RbY0uWsd3IBf9QFyqAYBCK7kor19ZAcP66wST7/F0HtPxZCe eEfNm/kSrjqxx31xjNkDoYjBjnwdP/XaT7V2/nq6VsdOIyXBIiISzWHt49o5XFZaBXrQ jf4w== X-Gm-Message-State: AFq9FYKsHQNa7iP0Pu3WqKOwNwJ+0uniSwribSezBEfPzkGgxAnnPfnC 0hj6oYdkKCBMON+PnxR3P3uti13WrbgCt3StjjdykDM9fvRNqiX1T6FMztdhaKSvfwgY0JCgf7P dEi69u6nqOn04PRZNrJH/qeALvLcyUCFGvKPo4+bmme5VbbTbAPqfWAul9jaKWUkS4Ofh X-Gm-Gg: AYBFou3RqmlgN52rqzCCqeAF1VKvvcLL5/rCBC2DkB+GQ7yU+muCj2ACxQM4pmnHX6g GqNEJ+5qwGAaJ9wWvWKa+XCIWP6BZT0Gjpbsl66Rru8W2yO73JFyQGDm6gv/MP5WHxC1BnfkqGp wNo0qT08561DlymM/SdtwEySFbdjx1vOqamd/oC8ZGuFowvn6IWawncOSdmBKdB2bdMthc5zmni zGAhY7sMD0WgIhmQNT5NzM4vCUTU1skWIgS0jeR3TzDNAQMLe+rsqoBt/6+knvR0jfv+WUPhVsN SwV6JeeauxdgGVfdmCN9SSA/hMl60I4rFrvNL7oR/u2NTx/gUSBmqclmYrfgh9qs9Jqy3A2Yr1Z f3cnlI9Ioqu63g/+4NZG0IlJZRBQtE8nnqFdt X-Received: by 2002:a05:620a:84c3:b0:93e:9292:1b96 with SMTP id af79cd13be357-93ebd0a1ef1mr991968385a.3.1791717134054; Sun, 11 Oct 2026 04:12:14 -0700 (PDT) X-Received: by 2002:a05:620a:84c3:b0:93e:9292:1b96 with SMTP id af79cd13be357-93ebd0a1ef1mr991964985a.3.1791717133498; Sun, 11 Oct 2026 04:12:13 -0700 (PDT) Received: from QCOM-UWl2o8bcGT.qualcomm.com ([152.234.126.58]) by smtp.gmail.com with ESMTPSA id 6a1803df08f44-91b54c0c406sm68621806d6.0.2026.10.11.04.12.11 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 11 Oct 2026 04:12:12 -0700 (PDT) From: Daniel Barboza <daniel.barboza@oss.qualcomm.com> To: gcc-patches@gcc.gnu.org Cc: jeffrey.law@oss.qualcomm.com, andrew.pinski@oss.qualcomm.com, Daniel Barboza <daniel.barboza@oss.qualcomm.com> Subject: [PATCH v2] match.pd: (A << N) >> N -> A [PR126644] Date: Sun, 11 Oct 2026 08:12:09 -0300 Message-ID: <20261011111209.3214394-1-daniel.barboza@oss.qualcomm.com> X-Mailer: git-send-email 2.43.0 MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Proofpoint-Spam-Info: AW1haW4tMjYxMDExMDA0NCBTYWx0ZWRfX2AubLctfXUct sdKLyHfcnvnL6pS2bRhmCZmFr9dtno8HFXUhbdm6SF6n5eLqGHO7csTmkBLAA5JIU9t89/cxTR0 J9D1GlW5HGNBamiaBDwGoFYJ/XpglXI= X-Proofpoint-ORIG-GUID: sTD-EIB97nrv_Lhg1F8v5bCd10iaUNpI X-Proofpoint-GUID: sTD-EIB97nrv_Lhg1F8v5bCd10iaUNpI X-Authority-Analysis: v=2.4 cv=eMWGH3p1 c=1 sm=1 tr=0 ts=6acb6f0f cx=c_pps a=hnmNkyzTK/kJ09Xio7VxxA==:117 a=XIBTAJF/fpiF5bhQ2IRv1g==:17 a=660iZSQnnn4A:10 a=s4-Qcg_JpJYA:10 a=VkNPw1HP01LnGYTKEx00:22 a=u7WPNUs3qKkmUXheDGA7:22 a=Um2Pa8k9VHT-vaBCBUpS:22 a=mDV3o1hIAAAA:8 a=OzMynECsSGPTMokOaMcA:9 a=PEH46H7Ffwr30OY-TuGO:22 X-Proofpoint-Spam-Details-Enc: AW1haW4tMjYxMDExMDA0NCBTYWx0ZWRfX025nWiHTbJ5j pILqI7Ix2XiuFr7kHBqNXEneIWVkr0Ws9UDTjPGvEKEAu2QbXwCERdmvRxTFCW3OrxZdNkfURcV UesDmjNoMFDN/VLkM6RbebYLa/TIyzaZapEvgnRDmH/T5lfsayjNGOkdoDVaSd7jlZ4dpAhBpkV PupTqAFLbAssH4AHf7tTkElJHp0/lO82bW427e6P6rkXPH4OUk+W5ib7RTov0GhAQ0A0tRUKG7S fTF5+B/9u+QS3L7U41F9c2I2yYl1ZPWquYsAxe5sBgJb/gFG75VhXCnGNovZvG6/X2jiyNYUKfP dsN9YsIMdNjBLXZhJznZ1gVSqds1GbhrTbCgr2wOor0HIUt+iqAbwPeeCKWQMVOtgIiCL98cnWf AzLlOpfrubS3B101b/PZUnxujDHjb4/03lVQqjBJvgZyi4j5Hk2bEfIdQfMo4Apcy3FMman0JYG ASgimkK8kM63FTV9FlQ== X-Proofpoint-Virus-Version: vendor=baseguard engine=ICAP:2.0.293,Aquarius:18.0.1176,Hydra:6.1.134,FMLib:17.12.100.49 definitions=2026-10-11_03,2026-10-09_01,2025-10-01_01 X-Proofpoint-Spam-Details: rule=outbound_notspam policy=outbound score=0 adultscore=0 spamscore=0 phishscore=0 clxscore=1015 impostorscore=0 suspectscore=0 lowpriorityscore=0 priorityscore=1501 bulkscore=0 malwarescore=0 classifier=typeunknown authscore=0 authtc= authcc= route=outbound adjust=0 reason=mlx scancount=1 engine=8.22.0-2610080000 definitions=main-2610110044 X-Spam-Status: No, score=-13.4 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, GIT_PATCH_0, KAM_SHORT, RCVD_IN_DNSWL_LOW, SPF_HELO_NONE, SPF_PASS, TXREP shortcircuit=no autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.30 Precedence: list List-Id: Gcc-patches mailing list <gcc-patches.gcc.gnu.org> List-Unsubscribe: <https://gcc.gnu.org/mailman/options/gcc-patches>, <mailto:gcc-patches-request@gcc.gnu.org?subject=unsubscribe> List-Archive: <https://gcc.gnu.org/pipermail/gcc-patches/> List-Post: <mailto:gcc-patches@gcc.gnu.org> List-Help: <mailto:gcc-patches-request@gcc.gnu.org?subject=help> List-Subscribe: <https://gcc.gnu.org/mailman/listinfo/gcc-patches>, <mailto:gcc-patches-request@gcc.gnu.org?subject=subscribe> Errors-To: gcc-patches-bounces~patchwork=sourceware.org@gcc.gnu.org |
| Series |
[v2] match.pd: (A << N) >> N -> A [PR126644]
|
|
Commit Message
Daniel Barboza
Oct. 11, 2026, 11:12 a.m. UTC
This is done during RTL. Do it earlier in Gimple to potentially allow more optimizations opportunities. The same pattern have two distinct handlings depending on whether A is unsigned or not. For unsigned types we'll check if there will be any upper bits being lost during the lshift step, e.g. if A = 0x001.. we can do the simplication for N=1,2 only. N = 3 and above would waste original A bits and the end result wouldn't be the same as A anymore. For signed types we need to consider that the rshift will preserve the original sign of its operand, thus if there's a sign change in A during the lshift we can no longer do the simplfication since the end result is no longer equal to A. E.g: - for signed type A = 0x001.. and N = 2: (0x001.. << 2) >> 2 --> 0x1.. >> 2 --> 0x111.., which is not A; - Likewise, for signed type A = 0x110.. and N = 2: (0x110.. << 2) >> 2 --> 0x0.. >> 2 --> 0x000.., also not A. Bootstrapped and regression tested in x86_64, aarch64 and riscv64. PR tree-optimization/126644 gcc/ChangeLog: * match.pd(`((A << N) >> N) -> N`): New pattern. gcc/testsuite/ChangeLog: * gcc.dg/tree-ssa/pr126644.c: New test. --- Changes from v1: - document match.pd changes properly in commit msg; - remove unneeded INTEGRAL_TYPE_P check; - handle signed cases by checking if the lshift will cause a signal change in the original SSA_NAME. - v1 link: https://gcc.gnu.org/pipermail/gcc-patches/2026-October/733787.html gcc/match.pd | 58 ++++++++++++++++++++++++ gcc/testsuite/gcc.dg/tree-ssa/pr126644.c | 55 ++++++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/pr126644.c
Comments
On 10/11/26 5:12 AM, Daniel Barboza wrote: > This is done during RTL. Do it earlier in Gimple to potentially allow > more optimizations opportunities. > > The same pattern have two distinct handlings depending on whether A is > unsigned or not. For unsigned types we'll check if there will be any > upper bits being lost during the lshift step, e.g. if A = 0x001.. we can > do the simplication for N=1,2 only. N = 3 and above would waste original > A bits and the end result wouldn't be the same as A anymore. > > For signed types we need to consider that the rshift will preserve the > original sign of its operand, thus if there's a sign change in A during > the lshift we can no longer do the simplfication since the end result is > no longer equal to A. E.g: > > - for signed type A = 0x001.. and N = 2: > (0x001.. << 2) >> 2 --> 0x1.. >> 2 --> 0x111.., which is not A; > > - Likewise, for signed type A = 0x110.. and N = 2: > (0x110.. << 2) >> 2 --> 0x0.. >> 2 --> 0x000.., also not A. > > Bootstrapped and regression tested in x86_64, aarch64 and riscv64. > > PR tree-optimization/126644 > > gcc/ChangeLog: > > * match.pd(`((A << N) >> N) -> N`): New pattern. > > gcc/testsuite/ChangeLog: > > * gcc.dg/tree-ssa/pr126644.c: New test. > --- > > Changes from v1: > - document match.pd changes properly in commit msg; > - remove unneeded INTEGRAL_TYPE_P check; > - handle signed cases by checking if the lshift will > cause a signal change in the original SSA_NAME. > - v1 link: https://gcc.gnu.org/pipermail/gcc-patches/2026-October/733787.html Thanks. This looks pretty good. No issues raised by GCC Sashiko. Note that you could use the same approach for (A >> N) << N. For that case I don't think you need to worry about signedness issues since any sign bit copies from an arithmetic right shift get thrown away by the final left shift. That might be a useful follow-up. Closely related for the (A << N) >> N case, if you can't apply (say because you don't have useful nonzero-bits status on A), you could instead transform into a BIT_AND against an adjusted constant since this case is just clearing N high bits when A is unsigned. When A is signed what you have is sign extension from an arbitrary bit position, but the alternate formulations are no better than shift pairs from gimple's cost model standpoint. That might be another useful followup. > + (if (!TYPE_UNSIGNED (type)) > + (with { > + bool no_sign_bit_change = true; > + int_range_max vr; > + > + if (gimple_match_range_of_expr (vr, @A) > + && !vr.varying_p () > + && !vr.undefined_p () > + && vr.num_pairs () > 0) > + { > + int shift_amount = tree_to_uhwi (@N); > + for (unsigned int i = 0; i < vr.num_pairs (); i++) > + { > + wide_int lb = vr.lower_bound (i); > + wide_int ub = vr.upper_bound (i); > + > + if (wi::clrsb (lb) < shift_amount > + || wi::clrsb (ub) < shift_amount) > + { > + no_sign_bit_change = false; > + break; > + } > + } > + } > + else > + no_sign_bit_change = false; Is there some reason the tree_nonzero_bits test didn't help here? It would seem that if we have reasonable range information, then Ranger would also be giving us nonzero bit information and we just need to know if bit precision - N - 1 is potentially nonzero, right? Jeff
On 10/22/2026 2:37 PM, Jeff Law wrote: > > > On 10/11/26 5:12 AM, Daniel Barboza wrote: >> This is done during RTL. Do it earlier in Gimple to potentially allow >> more optimizations opportunities. >> >> The same pattern have two distinct handlings depending on whether A is >> unsigned or not. For unsigned types we'll check if there will be any >> upper bits being lost during the lshift step, e.g. if A = 0x001.. we can >> do the simplication for N=1,2 only. N = 3 and above would waste original >> A bits and the end result wouldn't be the same as A anymore. >> >> For signed types we need to consider that the rshift will preserve the >> original sign of its operand, thus if there's a sign change in A during >> the lshift we can no longer do the simplfication since the end result is >> no longer equal to A. E.g: >> >> - for signed type A = 0x001.. and N = 2: >> (0x001.. << 2) >> 2 --> 0x1.. >> 2 --> 0x111.., which is not A; >> >> - Likewise, for signed type A = 0x110.. and N = 2: >> (0x110.. << 2) >> 2 --> 0x0.. >> 2 --> 0x000.., also not A. >> >> Bootstrapped and regression tested in x86_64, aarch64 and riscv64. >> >> PR tree-optimization/126644 >> >> gcc/ChangeLog: >> >> * match.pd(`((A << N) >> N) -> N`): New pattern. >> >> gcc/testsuite/ChangeLog: >> >> * gcc.dg/tree-ssa/pr126644.c: New test. >> --- >> >> Changes from v1: >> - document match.pd changes properly in commit msg; >> - remove unneeded INTEGRAL_TYPE_P check; >> - handle signed cases by checking if the lshift will >> cause a signal change in the original SSA_NAME. >> - v1 link: https://gcc.gnu.org/pipermail/gcc-patches/2026-October/733787.html > Thanks. This looks pretty good. No issues raised by GCC Sashiko. > > Note that you could use the same approach for (A >> N) << N. For that case I don't think you need to worry about signedness issues since any sign bit copies from an arithmetic right shift get thrown away by the final left shift. That might be a useful follow-up. Good point. I'll do a follow-up. > > Closely related for the (A << N) >> N case, if you can't apply (say because you don't have useful nonzero-bits status on A), you could instead transform into a BIT_AND against an adjusted constant since this case is just clearing N high bits when A is unsigned. When A is signed what you have is sign extension from an arbitrary bit position, but the alternate formulations are no better than shift pairs from gimple's cost model standpoint. That might be another useful followup. > > >> + (if (!TYPE_UNSIGNED (type)) >> + (with { >> + bool no_sign_bit_change = true; >> + int_range_max vr; >> + >> + if (gimple_match_range_of_expr (vr, @A) >> + && !vr.varying_p () >> + && !vr.undefined_p () >> + && vr.num_pairs () > 0) >> + { >> + int shift_amount = tree_to_uhwi (@N); >> + for (unsigned int i = 0; i < vr.num_pairs (); i++) >> + { >> + wide_int lb = vr.lower_bound (i); >> + wide_int ub = vr.upper_bound (i); >> + >> + if (wi::clrsb (lb) < shift_amount >> + || wi::clrsb (ub) < shift_amount) >> + { >> + no_sign_bit_change = false; >> + break; >> + } >> + } >> + } >> + else >> + no_sign_bit_change = false; > Is there some reason the tree_nonzero_bits test didn't help here? It would seem that if we have reasonable range information, then Ranger would also be giving us nonzero bit information and we just need to know if bit precision - N - 1 is potentially nonzero, right? Good point again. I didn't even consider using tree_nonzero_bits() for the signed case. I got way too focused in the discussions in v1 about using ranger and checking lower and upper bounds and haven't considered it. In reality the same principle applies with tree_nonzero_bits(): we need to make sure that the shift won't change signs. I'll see if I can pull it off and send a v3. Cheers, Daniel > > Jeff
On Thu, Oct 22, 2026 at 10:38 AM Jeff Law <jeffrey.law@oss.qualcomm.com> wrote: > > > > On 10/11/26 5:12 AM, Daniel Barboza wrote: > > This is done during RTL. Do it earlier in Gimple to potentially allow > > more optimizations opportunities. > > > > The same pattern have two distinct handlings depending on whether A is > > unsigned or not. For unsigned types we'll check if there will be any > > upper bits being lost during the lshift step, e.g. if A = 0x001.. we can > > do the simplication for N=1,2 only. N = 3 and above would waste original > > A bits and the end result wouldn't be the same as A anymore. > > > > For signed types we need to consider that the rshift will preserve the > > original sign of its operand, thus if there's a sign change in A during > > the lshift we can no longer do the simplfication since the end result is > > no longer equal to A. E.g: > > > > - for signed type A = 0x001.. and N = 2: > > (0x001.. << 2) >> 2 --> 0x1.. >> 2 --> 0x111.., which is not A; > > > > - Likewise, for signed type A = 0x110.. and N = 2: > > (0x110.. << 2) >> 2 --> 0x0.. >> 2 --> 0x000.., also not A. > > > > Bootstrapped and regression tested in x86_64, aarch64 and riscv64. > > > > PR tree-optimization/126644 > > > > gcc/ChangeLog: > > > > * match.pd(`((A << N) >> N) -> N`): New pattern. > > > > gcc/testsuite/ChangeLog: > > > > * gcc.dg/tree-ssa/pr126644.c: New test. > > --- > > > > Changes from v1: > > - document match.pd changes properly in commit msg; > > - remove unneeded INTEGRAL_TYPE_P check; > > - handle signed cases by checking if the lshift will > > cause a signal change in the original SSA_NAME. > > - v1 link: https://gcc.gnu.org/pipermail/gcc-patches/2026-October/733787.html > Thanks. This looks pretty good. No issues raised by GCC Sashiko. > > Note that you could use the same approach for (A >> N) << N. For that > case I don't think you need to worry about signedness issues since any > sign bit copies from an arithmetic right shift get thrown away by the > final left shift. That might be a useful follow-up. > > Closely related for the (A << N) >> N case, if you can't apply (say > because you don't have useful nonzero-bits status on A), you could > instead transform into a BIT_AND against an adjusted constant since this > case is just clearing N high bits when A is unsigned. When A is signed > what you have is sign extension from an arbitrary bit position, but the > alternate formulations are no better than shift pairs from gimple's cost > model standpoint. That might be another useful followup. The function naming is part of the problem here which I think is confusing too; I don't know how to resolve it though. tree_nonzero_bits returns a mask where the bits are unknown (or always set). That is 0b0100 says bit 2 is unknown (or maybe even known to be set) while bits 0, 1 and 3 are known to be unset. There is another function which returns a mask for the bits that are known to be set, `get_known_nonzero_bits`. This function returns a mask which where the bits are known to be set. For an example 0b0110, bits 2 and 3 are known to be set while bits 0 and 3 are not known to be set or unset. Hope this helps. We most likely rename these functions but the whole GCC uses nonzero bits this way including on the RTL level. Plus there being like 2 different APIs to get the nonzero bits from a tree is another issue which should be resolved; but someone needs to sit down and figure out which one should be kept. There is also 2 different ways of handling boolean range (zero_one_valued) too in match which is another cleanup that needs to be done too. Thanks, Andrea > > > > + (if (!TYPE_UNSIGNED (type)) > > + (with { > > + bool no_sign_bit_change = true; > > + int_range_max vr; > > + > > + if (gimple_match_range_of_expr (vr, @A) > > + && !vr.varying_p () > > + && !vr.undefined_p () > > + && vr.num_pairs () > 0) > > + { > > + int shift_amount = tree_to_uhwi (@N); > > + for (unsigned int i = 0; i < vr.num_pairs (); i++) > > + { > > + wide_int lb = vr.lower_bound (i); > > + wide_int ub = vr.upper_bound (i); > > + > > + if (wi::clrsb (lb) < shift_amount > > + || wi::clrsb (ub) < shift_amount) > > + { > > + no_sign_bit_change = false; > > + break; > > + } > > + } > > + } > > + else > > + no_sign_bit_change = false; > Is there some reason the tree_nonzero_bits test didn't help here? It > would seem that if we have reasonable range information, then Ranger > would also be giving us nonzero bit information and we just need to know > if bit precision - N - 1 is potentially nonzero, right? > > Jeff
On 10/22/2026 2:37 PM, Jeff Law wrote: > > > On 10/11/26 5:12 AM, Daniel Barboza wrote: >> This is done during RTL. Do it earlier in Gimple to potentially allow >> more optimizations opportunities. >> >> The same pattern have two distinct handlings depending on whether A is >> unsigned or not. For unsigned types we'll check if there will be any >> upper bits being lost during the lshift step, e.g. if A = 0x001.. we can >> do the simplication for N=1,2 only. N = 3 and above would waste original >> A bits and the end result wouldn't be the same as A anymore. >> >> For signed types we need to consider that the rshift will preserve the >> original sign of its operand, thus if there's a sign change in A during >> the lshift we can no longer do the simplfication since the end result is >> no longer equal to A. E.g: >> >> - for signed type A = 0x001.. and N = 2: >> (0x001.. << 2) >> 2 --> 0x1.. >> 2 --> 0x111.., which is not A; >> >> - Likewise, for signed type A = 0x110.. and N = 2: >> (0x110.. << 2) >> 2 --> 0x0.. >> 2 --> 0x000.., also not A. >> >> Bootstrapped and regression tested in x86_64, aarch64 and riscv64. >> >> PR tree-optimization/126644 >> >> gcc/ChangeLog: >> >> * match.pd(`((A << N) >> N) -> N`): New pattern. >> >> gcc/testsuite/ChangeLog: >> >> * gcc.dg/tree-ssa/pr126644.c: New test. >> --- >> >> Changes from v1: >> - document match.pd changes properly in commit msg; >> - remove unneeded INTEGRAL_TYPE_P check; >> - handle signed cases by checking if the lshift will >> cause a signal change in the original SSA_NAME. >> - v1 link: https://gcc.gnu.org/pipermail/gcc-patches/2026-October/733787.html > Thanks. This looks pretty good. No issues raised by GCC Sashiko. > > Note that you could use the same approach for (A >> N) << N. For that case I don't think you need to worry about signedness issues since any sign bit copies from an arithmetic right shift get thrown away by the final left shift. That might be a useful follow-up. > > Closely related for the (A << N) >> N case, if you can't apply (say because you don't have useful nonzero-bits status on A), you could instead transform into a BIT_AND against an adjusted constant since this case is just clearing N high bits when A is unsigned. When A is signed what you have is sign extension from an arbitrary bit position, but the alternate formulations are no better than shift pairs from gimple's cost model standpoint. That might be another useful followup. Seems like we already have this implemented in match.pd: /* Optimize (x >> c) << c into x & (-1<<c). */ (simplify (lshift (nop_convert? (rshift @0 INTEGER_CST@1)) @1) (if (wi::ltu_p (wi::to_wide (@1), element_precision (type))) /* It doesn't matter if the right shift is arithmetic or logical. */ (bit_and (view_convert @0) (lshift { build_minus_one_cst (type); } @1)))) It'll turn that into a bit_and and, if the lower 'C' bit are proven to be zero, it'll reduce to just 'X'. And, as a matter of fact, we also have this: /* For (x << c) >> c, optimize into x & ((unsigned)-1 >> c) for unsigned x OR truncate into the precision(type) - c lowest bits of signed x (if they have mode precision or a precision of 1). */ (simplify (rshift (nop_convert? (lshift @0 INTEGER_CST@1)) @@1) (if (wi::ltu_p (wi::to_wide (@1), element_precision (type))) (if (TYPE_UNSIGNED (type)) (bit_and (convert @0) (rshift { build_minus_one_cst (type); } @1)) (....) Note that this simplification is the same I'm trying to add here but it's acting on 'original', before the new pattern can do anything about it. And, similar to the previous, if it's proven that there's no bits being lost, it'll also reduce to "X". In short, we don't need to handle TYPE_UNSIGNED() in this patch. I'll send a v3 with signed types only. > > >> + (if (!TYPE_UNSIGNED (type)) >> + (with { >> + bool no_sign_bit_change = true; >> + int_range_max vr; >> + >> + if (gimple_match_range_of_expr (vr, @A) >> + && !vr.varying_p () >> + && !vr.undefined_p () >> + && vr.num_pairs () > 0) >> + { >> + int shift_amount = tree_to_uhwi (@N); >> + for (unsigned int i = 0; i < vr.num_pairs (); i++) >> + { >> + wide_int lb = vr.lower_bound (i); >> + wide_int ub = vr.upper_bound (i); >> + >> + if (wi::clrsb (lb) < shift_amount >> + || wi::clrsb (ub) < shift_amount) >> + { >> + no_sign_bit_change = false; >> + break; >> + } >> + } >> + } >> + else >> + no_sign_bit_change = false; > Is there some reason the tree_nonzero_bits test didn't help here? It would seem that if we have reasonable range information, then Ranger would also be giving us nonzero bit information and we just need to know if bit precision - N - 1 is potentially nonzero, right? As Andrea said we can use a combo with get_nonzero_bits() to check for clear bits, along with get_known_nonzero_bits() to check for set bits. It's clearer than all the jazz I did with lower and upper bounds. If no bootstrap/regression problems I'll send a v3 using that. Thanks, Daniel > > Jeff
diff --git a/gcc/match.pd b/gcc/match.pd index 2d1161b860b..62e982cb9c2 100644 --- a/gcc/match.pd +++ b/gcc/match.pd @@ -1561,6 +1561,64 @@ DEFINE_INT_AND_FLOAT_ROUND_FN (RINT) { wide_int_to_tree (type, wi::lshift (wone, wi::to_wide (@2))); })))) +#if GIMPLE +/* PR126644: A << N >> N -> A + As long as the upper CST bits of A are known to be zero. */ +(simplify + (rshift (lshift@0 @A INTEGER_CST@N) @N) + (if (INTEGRAL_TYPE_P (type) + && tree_fits_uhwi_p (@N) + && tree_to_uhwi (@N) < TYPE_PRECISION (type) + && single_use (@0)) + (switch + /* For unsigned types it's a matter of checking if we'll + lose any of the upper N bits during A << N. */ + (if (TYPE_UNSIGNED (type)) + (with { + unsigned int prec = TYPE_PRECISION (type); + wide_int mask = wi::mask (prec - tree_to_uhwi (@N), + true, prec); + } + (if ((tree_nonzero_bits (@A) & mask) == 0) + @A))) + + /* For signed types we need to preserve the existing sign bit for + all possible values A might have. Otherwise we can have an + originally positive A (no sign bit), A << N ends up setting + the sign bit (i.e. it's a negative number now) and now + (A << N) >> N becomes an arithmetic shift that will preserve + the sign bit. */ + (if (!TYPE_UNSIGNED (type)) + (with { + bool no_sign_bit_change = true; + int_range_max vr; + + if (gimple_match_range_of_expr (vr, @A) + && !vr.varying_p () + && !vr.undefined_p () + && vr.num_pairs () > 0) + { + int shift_amount = tree_to_uhwi (@N); + for (unsigned int i = 0; i < vr.num_pairs (); i++) + { + wide_int lb = vr.lower_bound (i); + wide_int ub = vr.upper_bound (i); + + if (wi::clrsb (lb) < shift_amount + || wi::clrsb (ub) < shift_amount) + { + no_sign_bit_change = false; + break; + } + } + } + else + no_sign_bit_change = false; + } + (if (no_sign_bit_change) + @A)))))) +#endif + /* Fold (-x >> C) into -(x > 0) where C = precision(type) - 1. */ (for cst (INTEGER_CST VECTOR_CST) (simplify diff --git a/gcc/testsuite/gcc.dg/tree-ssa/pr126644.c b/gcc/testsuite/gcc.dg/tree-ssa/pr126644.c new file mode 100644 index 00000000000..b14fe905fa5 --- /dev/null +++ b/gcc/testsuite/gcc.dg/tree-ssa/pr126644.c @@ -0,0 +1,55 @@ +/* { dg-do compile } */ +/* { dg-options "-O1 -fdump-tree-optimized" } */ + +int f1 (int a) +{ + if ((a & 0xF0000000) != 0xF0000000) + __builtin_unreachable (); + + return a << 3 >> 3; +} + +/* Can't be optimized (not enough 1s to preserve sign). */ +int g1 (int a) +{ + if ((a & 0xF0000000) != 0xE0000000) + __builtin_unreachable (); + + return a << 3 >> 3; +} + +int f2 (int a) +{ + if ((a & 0xF0000000) != 0) __builtin_unreachable (); + + return a << 3 >> 3; +} + +/* Can't be optimized (not enough 0s to preserve sign). */ +int g2 (int a) +{ + if ((a & 0x10000000) != 0x10000000) + __builtin_unreachable (); + + return a << 3 >> 3; +} + +unsigned int f3 (unsigned int a) +{ + if ((a & 0xE0000000) != 0) __builtin_unreachable (); + + return a << 3 >> 3; +} + +/* Can't be optimized (will lose a bit during lshift). + This simplifies into a bit_and. */ +unsigned int g3 (unsigned int a) +{ + if ((a & 0xA0000000) != 0) __builtin_unreachable (); + + return a << 3 >> 3; +} + +/* { dg-final { scan-tree-dump-times " << " 2 "optimized" } } */ +/* { dg-final { scan-tree-dump-times " >> " 2 "optimized" } } */ +/* { dg-final { scan-tree-dump-times " & " 1 "optimized" } } */