@@ -1960,17 +1960,38 @@ unsigned GISelValueTracking::computeNumSignBits(Register R,
19601960 break ;
19611961 }
19621962 case TargetOpcode::G_SUB: {
1963+ Register Src2 = MI.getOperand (2 ).getReg ();
1964+ unsigned Src2NumSignBits =
1965+ computeNumSignBits (Src2, DemandedElts, Depth + 1 );
1966+ if (Src2NumSignBits == 1 )
1967+ return 1 ; // Early out.
1968+
1969+ // Handle NEG.
19631970 Register Src1 = MI.getOperand (1 ).getReg ();
1971+ KnownBits Known1 = getKnownBits (Src1, DemandedElts, Depth);
1972+ if (Known1.isZero ()) {
1973+ KnownBits Known2 = getKnownBits (Src2, DemandedElts, Depth);
1974+ // If the input is known to be 0 or 1, the output is 0/-1, which is all
1975+ // sign bits set.
1976+ if ((Known2.Zero | 1 ).isAllOnes ())
1977+ return TyBits;
1978+
1979+ // If the input is known to be positive (the sign bit is known clear),
1980+ // the output of the NEG has the same number of sign bits as the input.
1981+ if (Known2.isNonNegative ())
1982+ return Src2NumSignBits;
1983+
1984+ // Otherwise, we treat this like a SUB.
1985+ }
1986+
19641987 unsigned Src1NumSignBits =
19651988 computeNumSignBits (Src1, DemandedElts, Depth + 1 );
1966- if (Src1NumSignBits != 1 ) {
1967- Register Src2 = MI.getOperand (2 ).getReg ();
1968- unsigned Src2NumSignBits =
1969- computeNumSignBits (Src2, DemandedElts, Depth + 1 );
1970- if (Src2NumSignBits == 1 )
1971- return 1 ; // Early out.
1972- FirstAnswer = std::min (Src1NumSignBits, Src2NumSignBits) - 1 ;
1973- }
1989+ if (Src1NumSignBits == 1 )
1990+ return 1 ; // Early Out.
1991+
1992+ // Sub can have at most one carry bit. Thus we know that the output
1993+ // is, at worst, one more bit than the inputs.
1994+ FirstAnswer = std::min (Src1NumSignBits, Src2NumSignBits) - 1 ;
19741995 break ;
19751996 }
19761997 case TargetOpcode::G_FCMP:
0 commit comments