LLVM 24.0.0git
GISelValueTracking.cpp
Go to the documentation of this file.
1//===- lib/CodeGen/GlobalISel/GISelValueTracking.cpp --------------*- C++
2//*-===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9//
10/// Provides analysis for querying information about KnownBits during GISel
11/// passes.
12//
13//===----------------------------------------------------------------------===//
15#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/ScopeExit.h"
35#include "llvm/IR/FMF.h"
41
42#define DEBUG_TYPE "gisel-known-bits"
43
44using namespace llvm;
45using namespace MIPatternMatch;
46
48
50 "Analysis for ComputingKnownBits", false, true)
51
53 : MF(MF), MRI(MF.getRegInfo()), TL(*MF.getSubtarget().getTargetLowering()),
54 DL(MF.getFunction().getDataLayout()), MaxDepth(MaxDepth) {}
55
57 const MachineInstr *MI = MRI.getVRegDef(R);
58 switch (MI->getOpcode()) {
59 case TargetOpcode::COPY:
60 return computeKnownAlignment(MI->getOperand(1).getReg(), Depth);
61 case TargetOpcode::G_ASSERT_ALIGN: {
62 // TODO: Min with source
63 return Align(MI->getOperand(2).getImm());
64 }
65 case TargetOpcode::G_FRAME_INDEX: {
66 int FrameIdx = MI->getOperand(1).getIndex();
67 return MF.getFrameInfo().getObjectAlign(FrameIdx);
68 }
69 case TargetOpcode::G_INTRINSIC:
70 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
71 case TargetOpcode::G_INTRINSIC_CONVERGENT:
72 case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS:
73 default:
74 return TL.computeKnownAlignForTargetInstr(*this, R, MRI, Depth + 1);
75 }
76}
77
79 assert(MI.getNumExplicitDefs() == 1 &&
80 "expected single return generic instruction");
81 return getKnownBits(MI.getOperand(0).getReg());
82}
83
85 const LLT Ty = MRI.getType(R);
86 // Since the number of lanes in a scalable vector is unknown at compile time,
87 // we track one bit which is implicitly broadcast to all lanes. This means
88 // that all lanes in a scalable vector are considered demanded.
89 APInt DemandedElts =
90 Ty.isFixedVector() ? APInt::getAllOnes(Ty.getNumElements()) : APInt(1, 1);
91 return getKnownBits(R, DemandedElts);
92}
93
95 const APInt &DemandedElts,
96 unsigned Depth) {
98 computeKnownBitsImpl(R, Known, DemandedElts, Depth);
99 return Known;
100}
101
103 LLT Ty = MRI.getType(R);
104 unsigned BitWidth = Ty.getScalarSizeInBits();
106}
107
109 LLT Ty = MRI.getType(R);
110 const APInt ScalarDemandedElts(1, 1);
111 APInt DemandedElts = Ty.isFixedVector()
112 ? APInt::getAllOnes(Ty.getNumElements())
113 : ScalarDemandedElts;
114 return isKnownNeverZero(R, DemandedElts, Depth);
115}
116
118 unsigned Depth) {
119 if (Depth >= getMaxDepth())
120 return false;
121
122 MachineInstr &MI = *MRI.getVRegDef(R);
123
124 switch (MI.getOpcode()) {
125 default:
126 break;
127
128 case TargetOpcode::G_OR:
129 return isKnownNeverZero(MI.getOperand(1).getReg(), DemandedElts,
130 Depth + 1) ||
131 isKnownNeverZero(MI.getOperand(2).getReg(), DemandedElts, Depth + 1);
132
133 case TargetOpcode::G_SELECT:
134 return isKnownNeverZero(MI.getOperand(2).getReg(), DemandedElts,
135 Depth + 1) &&
136 isKnownNeverZero(MI.getOperand(3).getReg(), DemandedElts, Depth + 1);
137
138 case TargetOpcode::G_SHL: {
139 Register LHSReg = MI.getOperand(1).getReg();
140 if (MI.getFlag(MachineInstr::NoSWrap) || MI.getFlag(MachineInstr::NoUWrap))
141 return isKnownNeverZero(LHSReg, DemandedElts, Depth + 1);
142 KnownBits ValKnown = getKnownBits(LHSReg, DemandedElts, Depth + 1);
143 if (ValKnown.One[0])
144 return true;
145 APInt MaxCnt =
146 getKnownBits(MI.getOperand(2).getReg(), DemandedElts, Depth + 1)
147 .getMaxValue();
148 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
149 !ValKnown.One.shl(MaxCnt).isZero())
150 return true;
151 break;
152 }
153 }
154
155 // Pass through this frame's Depth (not Depth+1) because we have not recursed
156 // into a child MI here: the fallback queries KnownBits for the same R.
157 return getKnownBits(R, DemandedElts, Depth).isNonZero();
158}
159
163
167
168[[maybe_unused]] static void
169dumpResult(const MachineInstr &MI, const KnownBits &Known, unsigned Depth) {
170 dbgs() << "[" << Depth << "] Compute known bits: " << MI << "[" << Depth
171 << "] Computed for: " << MI << "[" << Depth << "] Known: 0x"
172 << toString(Known.Zero | Known.One, 16, false) << "\n"
173 << "[" << Depth << "] Zero: 0x" << toString(Known.Zero, 16, false)
174 << "\n"
175 << "[" << Depth << "] One: 0x" << toString(Known.One, 16, false)
176 << "\n";
177}
178
179/// Compute known bits for the intersection of \p Src0 and \p Src1
180void GISelValueTracking::computeKnownBitsMin(Register Src0, Register Src1,
182 const APInt &DemandedElts,
183 unsigned Depth) {
184 // Test src1 first, since we canonicalize simpler expressions to the RHS.
185 computeKnownBitsImpl(Src1, Known, DemandedElts, Depth);
186
187 // If we don't know any bits, early out.
188 if (Known.isUnknown())
189 return;
190
191 KnownBits Known2;
192 computeKnownBitsImpl(Src0, Known2, DemandedElts, Depth);
193
194 // Only known if known in both the LHS and RHS.
195 Known = Known.intersectWith(Known2);
196}
197
198// Bitfield extract is computed as (Src >> Offset) & Mask, where Mask is
199// created using Width. Use this function when the inputs are KnownBits
200// objects. TODO: Move this KnownBits.h if this is usable in more cases.
201static KnownBits extractBits(unsigned BitWidth, const KnownBits &SrcOpKnown,
202 const KnownBits &OffsetKnown,
203 const KnownBits &WidthKnown) {
204 KnownBits Mask(BitWidth);
205 Mask.Zero = APInt::getBitsSetFrom(
207 Mask.One = APInt::getLowBitsSet(
209 return KnownBits::lshr(SrcOpKnown, OffsetKnown) & Mask;
210}
211
213 const APInt &DemandedElts,
214 unsigned Depth) {
215 MachineInstr &MI = *MRI.getVRegDef(R);
216 unsigned Opcode = MI.getOpcode();
217 LLT DstTy = MRI.getType(R);
218
219 // Handle the case where this is called on a register that does not have a
220 // type constraint. For example, it may be post-ISel or this target might not
221 // preserve the type when early-selecting instructions.
222 if (!DstTy.isValid()) {
223 Known = KnownBits();
224 return;
225 }
226
227#ifndef NDEBUG
228 if (DstTy.isFixedVector()) {
229 assert(
230 DstTy.getNumElements() == DemandedElts.getBitWidth() &&
231 "DemandedElt width should equal the fixed vector number of elements");
232 } else {
233 assert(DemandedElts.getBitWidth() == 1 && DemandedElts == APInt(1, 1) &&
234 "DemandedElt width should be 1 for scalars or scalable vectors");
235 }
236#endif
237
238 unsigned BitWidth = DstTy.getScalarSizeInBits();
239 Known = KnownBits(BitWidth); // Don't know anything
240
241 // Depth may get bigger than max depth if it gets passed to a different
242 // GISelValueTracking object.
243 // This may happen when say a generic part uses a GISelValueTracking object
244 // with some max depth, but then we hit TL.computeKnownBitsForTargetInstr
245 // which creates a new GISelValueTracking object with a different and smaller
246 // depth. If we just check for equality, we would never exit if the depth
247 // that is passed down to the target specific GISelValueTracking object is
248 // already bigger than its max depth.
249 if (Depth >= getMaxDepth())
250 return;
251
252 if (!DemandedElts)
253 return; // No demanded elts, better to assume we don't know anything.
254
255 KnownBits Known2;
256
257 switch (Opcode) {
258 default:
259 TL.computeKnownBitsForTargetInstr(*this, R, Known, DemandedElts, MRI,
260 Depth);
261 break;
262 case TargetOpcode::G_BUILD_VECTOR: {
263 // Collect the known bits that are shared by every demanded vector element.
264 Known.Zero.setAllBits();
265 Known.One.setAllBits();
266 for (const auto &[I, MO] : enumerate(drop_begin(MI.operands()))) {
267 if (!DemandedElts[I])
268 continue;
269
270 computeKnownBitsImpl(MO.getReg(), Known2, APInt(1, 1), Depth + 1);
271
272 // Known bits are the values that are shared by every demanded element.
273 Known = Known.intersectWith(Known2);
274
275 // If we don't know any bits, early out.
276 if (Known.isUnknown())
277 break;
278 }
279 break;
280 }
281 case TargetOpcode::G_SPLAT_VECTOR: {
282 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, APInt(1, 1),
283 Depth + 1);
284 // Implicitly truncate the bits to match the official semantics of
285 // G_SPLAT_VECTOR.
286 Known = Known.trunc(BitWidth);
287 break;
288 }
289 case TargetOpcode::COPY:
290 case TargetOpcode::G_PHI:
291 case TargetOpcode::PHI: {
294 // Destination registers should not have subregisters at this
295 // point of the pipeline, otherwise the main live-range will be
296 // defined more than once, which is against SSA.
297 assert(MI.getOperand(0).getSubReg() == 0 && "Is this code in SSA?");
298 // PHI's operand are a mix of registers and basic blocks interleaved.
299 // We only care about the register ones.
300 for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
301 const MachineOperand &Src = MI.getOperand(Idx);
302 Register SrcReg = Src.getReg();
303 LLT SrcTy = MRI.getType(SrcReg);
304 // Look through trivial copies and phis but don't look through trivial
305 // copies or phis of the form `%1:(s32) = OP %0:gpr32`, known-bits
306 // analysis is currently unable to determine the bit width of a
307 // register class.
308 //
309 // We can't use NoSubRegister by name as it's defined by each target but
310 // it's always defined to be 0 by tablegen.
311 if (SrcReg.isVirtual() && Src.getSubReg() == 0 /*NoSubRegister*/ &&
312 SrcTy.isValid()) {
313 APInt NowDemandedElts;
314 if (!SrcTy.isFixedVector()) {
315 NowDemandedElts = APInt(1, 1);
316 } else if (DstTy.isFixedVector() &&
317 SrcTy.getNumElements() == DstTy.getNumElements()) {
318 NowDemandedElts = DemandedElts;
319 } else {
320 NowDemandedElts = APInt::getAllOnes(SrcTy.getNumElements());
321 }
322
323 // For COPYs we don't do anything, don't increase the depth.
324 computeKnownBitsImpl(SrcReg, Known2, NowDemandedElts,
325 Depth + (Opcode != TargetOpcode::COPY));
326 Known2 = Known2.anyextOrTrunc(BitWidth);
327 Known = Known.intersectWith(Known2);
328 // If we reach a point where we don't know anything
329 // just stop looking through the operands.
330 if (Known.isUnknown())
331 break;
332 } else {
333 // We know nothing.
335 break;
336 }
337 }
338 break;
339 }
340 case TargetOpcode::G_STEP_VECTOR: {
341 APInt Step = MI.getOperand(1).getCImm()->getValue();
342
343 if (Step.isPowerOf2())
344 Known.Zero.setLowBits(Step.logBase2());
345
347 break;
348
349 const APInt MinNumElts =
352 bool Overflow;
353 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
355 .umul_ov(MinNumElts, Overflow);
356 if (Overflow)
357 break;
358 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
359 if (Overflow)
360 break;
361 Known.Zero.setHighBits(MaxValue.countl_zero());
362 break;
363 }
364 case TargetOpcode::G_CONSTANT: {
365 Known = KnownBits::makeConstant(MI.getOperand(1).getCImm()->getValue());
366 break;
367 }
368 case TargetOpcode::G_FRAME_INDEX: {
369 int FrameIdx = MI.getOperand(1).getIndex();
370 TL.computeKnownBitsForStackObjectPointer(
371 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
372 break;
373 }
374 case TargetOpcode::G_SUB: {
375 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
376 Depth + 1);
377 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
378 Depth + 1);
380 MI.getFlag(MachineInstr::NoUWrap));
381 break;
382 }
383 case TargetOpcode::G_XOR: {
384 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
385 Depth + 1);
386 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
387 Depth + 1);
388
389 Known ^= Known2;
390 break;
391 }
392 case TargetOpcode::G_PTR_ADD: {
393 if (DstTy.isVector())
394 break;
395 // G_PTR_ADD is like G_ADD. FIXME: Is this true for all targets?
396 LLT Ty = MRI.getType(MI.getOperand(1).getReg());
397 if (DL.isNonIntegralAddressSpace(Ty.getAddressSpace()))
398 break;
399 [[fallthrough]];
400 }
401 case TargetOpcode::G_ADD: {
402 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
403 Depth + 1);
404 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
405 Depth + 1);
406 Known = KnownBits::add(Known, Known2);
407 break;
408 }
409 case TargetOpcode::G_AND: {
410 // If either the LHS or the RHS are Zero, the result is zero.
411 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
412 Depth + 1);
413 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
414 Depth + 1);
415
416 Known &= Known2;
417 break;
418 }
419 case TargetOpcode::G_OR: {
420 // If either the LHS or the RHS are Zero, the result is zero.
421 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
422 Depth + 1);
423 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
424 Depth + 1);
425
426 Known |= Known2;
427 break;
428 }
429 case TargetOpcode::G_MUL: {
430 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
431 Depth + 1);
432 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
433 Depth + 1);
434 Known = KnownBits::mul(Known, Known2);
435 break;
436 }
437 case TargetOpcode::G_UMULH: {
438 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
439 Depth + 1);
440 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
441 Depth + 1);
442 Known = KnownBits::mulhu(Known, Known2);
443 break;
444 }
445 case TargetOpcode::G_SMULH: {
446 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
447 Depth + 1);
448 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
449 Depth + 1);
450 Known = KnownBits::mulhs(Known, Known2);
451 break;
452 }
453 case TargetOpcode::G_UAVGFLOOR: {
454 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
455 Depth + 1);
456 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
457 Depth + 1);
459 break;
460 }
461 case TargetOpcode::G_UAVGCEIL: {
462 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
463 Depth + 1);
464 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
465 Depth + 1);
467 break;
468 }
469 case TargetOpcode::G_SAVGFLOOR: {
470 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
471 Depth + 1);
472 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
473 Depth + 1);
475 break;
476 }
477 case TargetOpcode::G_SAVGCEIL: {
478 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
479 Depth + 1);
480 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
481 Depth + 1);
483 break;
484 }
485 case TargetOpcode::G_ABDU: {
486 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
487 Depth + 1);
488 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
489 Depth + 1);
490 Known = KnownBits::abdu(Known, Known2);
491 break;
492 }
493 case TargetOpcode::G_ABDS: {
494 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
495 Depth + 1);
496 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
497 Depth + 1);
498 Known = KnownBits::abds(Known, Known2);
499
500 unsigned SignBits1 =
501 computeNumSignBits(MI.getOperand(2).getReg(), DemandedElts, Depth + 1);
502 if (SignBits1 == 1) {
503 break;
504 }
505 unsigned SignBits0 =
506 computeNumSignBits(MI.getOperand(1).getReg(), DemandedElts, Depth + 1);
507
508 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
509 break;
510 }
511 case TargetOpcode::G_SADDSAT: {
512 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
513 Depth + 1);
514 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
515 Depth + 1);
517 break;
518 }
519 case TargetOpcode::G_UADDSAT: {
520 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
521 Depth + 1);
522 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
523 Depth + 1);
525 break;
526 }
527 case TargetOpcode::G_SSUBSAT: {
528 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
529 Depth + 1);
530 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
531 Depth + 1);
533 break;
534 }
535 case TargetOpcode::G_USUBSAT: {
536 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
537 Depth + 1);
538 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
539 Depth + 1);
541 break;
542 }
543 case TargetOpcode::G_UDIV: {
544 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
545 Depth + 1);
546 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
547 Depth + 1);
548 Known = KnownBits::udiv(Known, Known2,
550 break;
551 }
552 case TargetOpcode::G_SDIV: {
553 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
554 Depth + 1);
555 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
556 Depth + 1);
557 Known = KnownBits::sdiv(Known, Known2,
559 break;
560 }
561 case TargetOpcode::G_UREM: {
562 KnownBits LHSKnown(Known.getBitWidth());
563 KnownBits RHSKnown(Known.getBitWidth());
564
565 computeKnownBitsImpl(MI.getOperand(1).getReg(), LHSKnown, DemandedElts,
566 Depth + 1);
567 computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
568 Depth + 1);
569
570 Known = KnownBits::urem(LHSKnown, RHSKnown);
571 break;
572 }
573 case TargetOpcode::G_SREM: {
574 KnownBits LHSKnown(Known.getBitWidth());
575 KnownBits RHSKnown(Known.getBitWidth());
576
577 computeKnownBitsImpl(MI.getOperand(1).getReg(), LHSKnown, DemandedElts,
578 Depth + 1);
579 computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
580 Depth + 1);
581
582 Known = KnownBits::srem(LHSKnown, RHSKnown);
583 break;
584 }
585 case TargetOpcode::G_SELECT: {
586 computeKnownBitsMin(MI.getOperand(2).getReg(), MI.getOperand(3).getReg(),
587 Known, DemandedElts, Depth + 1);
588 break;
589 }
590 case TargetOpcode::G_SMIN: {
591 // TODO: Handle clamp pattern with number of sign bits
592 KnownBits KnownRHS;
593 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
594 Depth + 1);
595 computeKnownBitsImpl(MI.getOperand(2).getReg(), KnownRHS, DemandedElts,
596 Depth + 1);
597 Known = KnownBits::smin(Known, KnownRHS);
598 break;
599 }
600 case TargetOpcode::G_SMAX: {
601 // TODO: Handle clamp pattern with number of sign bits
602 KnownBits KnownRHS;
603 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
604 Depth + 1);
605 computeKnownBitsImpl(MI.getOperand(2).getReg(), KnownRHS, DemandedElts,
606 Depth + 1);
607 Known = KnownBits::smax(Known, KnownRHS);
608 break;
609 }
610 case TargetOpcode::G_UMIN: {
611 KnownBits KnownRHS;
612 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
613 Depth + 1);
614 computeKnownBitsImpl(MI.getOperand(2).getReg(), KnownRHS, DemandedElts,
615 Depth + 1);
616 Known = KnownBits::umin(Known, KnownRHS);
617 break;
618 }
619 case TargetOpcode::G_UMAX: {
620 KnownBits KnownRHS;
621 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
622 Depth + 1);
623 computeKnownBitsImpl(MI.getOperand(2).getReg(), KnownRHS, DemandedElts,
624 Depth + 1);
625 Known = KnownBits::umax(Known, KnownRHS);
626 break;
627 }
628 case TargetOpcode::G_FCMP:
629 case TargetOpcode::G_ICMP: {
630 if (DstTy.isVector())
631 break;
632 if (TL.getBooleanContents(DstTy.isVector(),
633 Opcode == TargetOpcode::G_FCMP) ==
635 BitWidth > 1)
636 Known.Zero.setBitsFrom(1);
637 break;
638 }
639 case TargetOpcode::G_SEXT: {
640 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
641 Depth + 1);
642 // If the sign bit is known to be zero or one, then sext will extend
643 // it to the top bits, else it will just zext.
644 Known = Known.sext(BitWidth);
645 break;
646 }
647 case TargetOpcode::G_ASSERT_SEXT:
648 case TargetOpcode::G_SEXT_INREG: {
649 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
650 Depth + 1);
651 Known = Known.sextInReg(MI.getOperand(2).getImm());
652 break;
653 }
654 case TargetOpcode::G_ANYEXT: {
655 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
656 Depth + 1);
657 Known = Known.anyext(BitWidth);
658 break;
659 }
660 case TargetOpcode::G_LOAD: {
661 const MachineMemOperand *MMO = *MI.memoperands_begin();
662 KnownBits KnownRange(MMO->getMemoryType().getScalarSizeInBits());
663 if (const MDNode *Ranges = MMO->getRanges())
664 computeKnownBitsFromRangeMetadata(*Ranges, KnownRange);
665 Known = KnownRange.anyext(Known.getBitWidth());
666 break;
667 }
668 case TargetOpcode::G_SEXTLOAD:
669 case TargetOpcode::G_ZEXTLOAD: {
670 if (DstTy.isVector())
671 break;
672 const MachineMemOperand *MMO = *MI.memoperands_begin();
673 KnownBits KnownRange(MMO->getMemoryType().getScalarSizeInBits());
674 if (const MDNode *Ranges = MMO->getRanges())
675 computeKnownBitsFromRangeMetadata(*Ranges, KnownRange);
676 Known = Opcode == TargetOpcode::G_SEXTLOAD
677 ? KnownRange.sext(Known.getBitWidth())
678 : KnownRange.zext(Known.getBitWidth());
679 break;
680 }
681 case TargetOpcode::G_ASHR: {
682 KnownBits LHSKnown, RHSKnown;
683 computeKnownBitsImpl(MI.getOperand(1).getReg(), LHSKnown, DemandedElts,
684 Depth + 1);
685 computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
686 Depth + 1);
687 Known = KnownBits::ashr(LHSKnown, RHSKnown);
688 break;
689 }
690 case TargetOpcode::G_LSHR: {
691 KnownBits LHSKnown, RHSKnown;
692 computeKnownBitsImpl(MI.getOperand(1).getReg(), LHSKnown, DemandedElts,
693 Depth + 1);
694 computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
695 Depth + 1);
696 Known = KnownBits::lshr(LHSKnown, RHSKnown);
697 break;
698 }
699 case TargetOpcode::G_SHL: {
700 KnownBits LHSKnown, RHSKnown;
701 computeKnownBitsImpl(MI.getOperand(1).getReg(), LHSKnown, DemandedElts,
702 Depth + 1);
703 computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
704 Depth + 1);
705 Known = KnownBits::shl(LHSKnown, RHSKnown);
706 break;
707 }
708 case TargetOpcode::G_ROTL:
709 case TargetOpcode::G_ROTR: {
710 auto MaybeAmtOp =
711 isConstantOrConstantSplatVector(MI.getOperand(2).getReg(), MRI);
712 if (!MaybeAmtOp)
713 break;
714
715 Register SrcReg = MI.getOperand(1).getReg();
716 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
717
718 unsigned Amt = MaybeAmtOp->urem(BitWidth);
719
720 // Canonicalize to ROTR.
721 if (Opcode == TargetOpcode::G_ROTL)
722 Amt = BitWidth - Amt;
723
724 Known.Zero = Known.Zero.rotr(Amt);
725 Known.One = Known.One.rotr(Amt);
726 break;
727 }
728 case TargetOpcode::G_FSHL:
729 case TargetOpcode::G_FSHR: {
730 auto MaybeAmtOp =
731 isConstantOrConstantSplatVector(MI.getOperand(3).getReg(), MRI);
732 if (!MaybeAmtOp)
733 break;
734
735 const APInt Amt = *MaybeAmtOp;
736 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
737 Depth + 1);
738 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
739 Depth + 1);
740 Known = Opcode == TargetOpcode::G_FSHL
741 ? KnownBits::fshl(Known, Known2, Amt)
742 : KnownBits::fshr(Known, Known2, Amt);
743 break;
744 }
745 case TargetOpcode::G_INTTOPTR:
746 case TargetOpcode::G_PTRTOINT:
747 if (DstTy.isVector())
748 break;
749 // Fall through and handle them the same as zext/trunc.
750 [[fallthrough]];
751 case TargetOpcode::G_ZEXT:
752 case TargetOpcode::G_TRUNC: {
753 Register SrcReg = MI.getOperand(1).getReg();
754 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
755 Known = Known.zextOrTrunc(BitWidth);
756 break;
757 }
758 case TargetOpcode::G_ASSERT_ZEXT: {
759 Register SrcReg = MI.getOperand(1).getReg();
760 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
761
762 unsigned SrcBitWidth = MI.getOperand(2).getImm();
763 assert(SrcBitWidth && "SrcBitWidth can't be zero");
764 APInt InMask = APInt::getLowBitsSet(BitWidth, SrcBitWidth);
765 Known.Zero |= (~InMask);
766 Known.One &= (~Known.Zero);
767 break;
768 }
769 case TargetOpcode::G_ASSERT_ALIGN: {
770 int64_t LogOfAlign = Log2_64(MI.getOperand(2).getImm());
771
772 // TODO: Should use maximum with source
773 // If a node is guaranteed to be aligned, set low zero bits accordingly as
774 // well as clearing one bits.
775 Known.Zero.setLowBits(LogOfAlign);
776 Known.One.clearLowBits(LogOfAlign);
777 break;
778 }
779 case TargetOpcode::G_MERGE_VALUES: {
780 unsigned NumOps = MI.getNumOperands();
781 unsigned OpSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
782
783 for (unsigned I = 0; I != NumOps - 1; ++I) {
784 KnownBits SrcOpKnown;
785 computeKnownBitsImpl(MI.getOperand(I + 1).getReg(), SrcOpKnown,
786 DemandedElts, Depth + 1);
787 Known.insertBits(SrcOpKnown, I * OpSize);
788 }
789 break;
790 }
791 case TargetOpcode::G_UNMERGE_VALUES: {
792 unsigned NumOps = MI.getNumOperands();
793 Register SrcReg = MI.getOperand(NumOps - 1).getReg();
794 LLT SrcTy = MRI.getType(SrcReg);
795
796 if (SrcTy.isVector() && SrcTy.getScalarType() != DstTy.getScalarType())
797 return; // TODO: Handle vector->subelement unmerges
798
799 // Figure out the result operand index
800 unsigned DstIdx = 0;
801 for (; DstIdx != NumOps - 1 && MI.getOperand(DstIdx).getReg() != R;
802 ++DstIdx)
803 ;
804
805 APInt SubDemandedElts = DemandedElts;
806 if (SrcTy.isVector()) {
807 unsigned DstLanes = DstTy.isVector() ? DstTy.getNumElements() : 1;
808 SubDemandedElts =
809 DemandedElts.zext(SrcTy.getNumElements()).shl(DstIdx * DstLanes);
810 }
811
812 KnownBits SrcOpKnown;
813 computeKnownBitsImpl(SrcReg, SrcOpKnown, SubDemandedElts, Depth + 1);
814
815 if (SrcTy.isVector())
816 Known = std::move(SrcOpKnown);
817 else
818 Known = SrcOpKnown.extractBits(BitWidth, BitWidth * DstIdx);
819 break;
820 }
821 case TargetOpcode::G_BSWAP: {
822 Register SrcReg = MI.getOperand(1).getReg();
823 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
824 Known = Known.byteSwap();
825 break;
826 }
827 case TargetOpcode::G_BITREVERSE: {
828 Register SrcReg = MI.getOperand(1).getReg();
829 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
830 Known = Known.reverseBits();
831 break;
832 }
833 case TargetOpcode::G_CTPOP: {
834 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
835 Depth + 1);
836 // We can bound the space the count needs. Also, bits known to be zero
837 // can't contribute to the population.
838 unsigned BitsPossiblySet = Known2.countMaxPopulation();
839 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
840 Known.Zero.setBitsFrom(LowBits);
841 // TODO: we could bound Known.One using the lower bound on the number of
842 // bits which might be set provided by popcnt KnownOne2.
843 break;
844 }
845 case TargetOpcode::G_UBFX: {
846 KnownBits SrcOpKnown, OffsetKnown, WidthKnown;
847 computeKnownBitsImpl(MI.getOperand(1).getReg(), SrcOpKnown, DemandedElts,
848 Depth + 1);
849 computeKnownBitsImpl(MI.getOperand(2).getReg(), OffsetKnown, DemandedElts,
850 Depth + 1);
851 computeKnownBitsImpl(MI.getOperand(3).getReg(), WidthKnown, DemandedElts,
852 Depth + 1);
853 Known = extractBits(BitWidth, SrcOpKnown, OffsetKnown, WidthKnown);
854 break;
855 }
856 case TargetOpcode::G_SBFX: {
857 KnownBits SrcOpKnown, OffsetKnown, WidthKnown;
858 computeKnownBitsImpl(MI.getOperand(1).getReg(), SrcOpKnown, DemandedElts,
859 Depth + 1);
860 computeKnownBitsImpl(MI.getOperand(2).getReg(), OffsetKnown, DemandedElts,
861 Depth + 1);
862 computeKnownBitsImpl(MI.getOperand(3).getReg(), WidthKnown, DemandedElts,
863 Depth + 1);
864 OffsetKnown = OffsetKnown.sext(BitWidth);
865 WidthKnown = WidthKnown.sext(BitWidth);
866 Known = extractBits(BitWidth, SrcOpKnown, OffsetKnown, WidthKnown);
867 // Sign extend the extracted value using shift left and arithmetic shift
868 // right.
870 KnownBits ShiftKnown = KnownBits::sub(ExtKnown, WidthKnown);
871 Known = KnownBits::ashr(KnownBits::shl(Known, ShiftKnown), ShiftKnown);
872 break;
873 }
874 case TargetOpcode::G_UADDO:
875 case TargetOpcode::G_UADDE:
876 case TargetOpcode::G_SADDO:
877 case TargetOpcode::G_SADDE: {
878 if (MI.getOperand(1).getReg() == R) {
879 // If we know the result of a compare has the top bits zero, use this
880 // info.
881 if (TL.getBooleanContents(DstTy.isVector(), false) ==
883 BitWidth > 1)
884 Known.Zero.setBitsFrom(1);
885 break;
886 }
887
888 assert(MI.getOperand(0).getReg() == R &&
889 "We only compute knownbits for the sum here.");
890 // With [US]ADDE, a carry bit may be added in.
891 KnownBits Carry(1);
892 if (Opcode == TargetOpcode::G_UADDE || Opcode == TargetOpcode::G_SADDE) {
893 computeKnownBitsImpl(MI.getOperand(4).getReg(), Carry, DemandedElts,
894 Depth + 1);
895 // Carry has bit width 1
896 Carry = Carry.trunc(1);
897 } else {
898 Carry.setAllZero();
899 }
900
901 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
902 Depth + 1);
903 computeKnownBitsImpl(MI.getOperand(3).getReg(), Known2, DemandedElts,
904 Depth + 1);
905 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
906 break;
907 }
908 case TargetOpcode::G_USUBO:
909 case TargetOpcode::G_USUBE:
910 case TargetOpcode::G_SSUBO:
911 case TargetOpcode::G_SSUBE:
912 case TargetOpcode::G_UMULO:
913 case TargetOpcode::G_SMULO: {
914 if (MI.getOperand(1).getReg() == R) {
915 // If we know the result of a compare has the top bits zero, use this
916 // info.
917 if (TL.getBooleanContents(DstTy.isVector(), false) ==
919 BitWidth > 1)
920 Known.Zero.setBitsFrom(1);
921 }
922 break;
923 }
924 case TargetOpcode::G_CTTZ:
925 case TargetOpcode::G_CTTZ_ZERO_POISON: {
926 KnownBits SrcOpKnown;
927 computeKnownBitsImpl(MI.getOperand(1).getReg(), SrcOpKnown, DemandedElts,
928 Depth + 1);
929 // If we have a known 1, its position is our upper bound
930 unsigned PossibleTZ = SrcOpKnown.countMaxTrailingZeros();
931 unsigned LowBits = llvm::bit_width(PossibleTZ);
932 Known.Zero.setBitsFrom(LowBits);
933 break;
934 }
935 case TargetOpcode::G_CTLZ:
936 case TargetOpcode::G_CTLZ_ZERO_POISON: {
937 KnownBits SrcOpKnown;
938 computeKnownBitsImpl(MI.getOperand(1).getReg(), SrcOpKnown, DemandedElts,
939 Depth + 1);
940 // If we have a known 1, its position is our upper bound.
941 unsigned PossibleLZ = SrcOpKnown.countMaxLeadingZeros();
942 unsigned LowBits = llvm::bit_width(PossibleLZ);
943 Known.Zero.setBitsFrom(LowBits);
944 break;
945 }
946 case TargetOpcode::G_CTLS: {
947 Register Reg = MI.getOperand(1).getReg();
948 unsigned MinRedundantSignBits = computeNumSignBits(Reg, Depth + 1) - 1;
949
950 unsigned MaxUpperRedundantSignBits = MRI.getType(Reg).getScalarSizeInBits();
951
952 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
953 APInt(BitWidth, MaxUpperRedundantSignBits));
954
955 Known = Range.toKnownBits();
956 break;
957 }
958 case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
960 Register InVec = Extract.getVectorReg();
961 Register EltNo = Extract.getIndexReg();
962
963 auto ConstEltNo = getIConstantVRegVal(EltNo, MRI);
964
965 LLT VecVT = MRI.getType(InVec);
966 // computeKnownBits not yet implemented for scalable vectors.
967 if (VecVT.isScalableVector())
968 break;
969
970 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
971 const unsigned NumSrcElts = VecVT.getNumElements();
972 // A return type different from the vector's element type may lead to
973 // issues with pattern selection. Bail out to avoid that.
974 if (BitWidth > EltBitWidth)
975 break;
976
977 Known.Zero.setAllBits();
978 Known.One.setAllBits();
979
980 // If we know the element index, just demand that vector element, else for
981 // an unknown element index, ignore DemandedElts and demand them all.
982 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
983 if (ConstEltNo && ConstEltNo->ult(NumSrcElts))
984 DemandedSrcElts =
985 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
986
987 computeKnownBitsImpl(InVec, Known, DemandedSrcElts, Depth + 1);
988 break;
989 }
990 case TargetOpcode::G_INSERT_VECTOR_ELT: {
992 Register InVec = Insert.getVectorReg();
993 Register InVal = Insert.getElementReg();
994 Register EltNo = Insert.getIndexReg();
995 LLT VecVT = MRI.getType(InVec);
996
997 if (VecVT.isScalableVector())
998 break;
999
1000 auto ConstEltNo = getIConstantVRegVal(EltNo, MRI);
1001 unsigned NumElts = VecVT.getNumElements();
1002
1003 bool DemandedVal = true;
1004 APInt DemandedVecElts = DemandedElts;
1005 if (ConstEltNo && ConstEltNo->ult(NumElts)) {
1006 unsigned EltIdx = ConstEltNo->getZExtValue();
1007 DemandedVal = !!DemandedElts[EltIdx];
1008 DemandedVecElts.clearBit(EltIdx);
1009 }
1010 Known.setAllConflict();
1011 if (DemandedVal) {
1012 computeKnownBitsImpl(InVal, Known2, APInt(1, 1), Depth + 1);
1013 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
1014 }
1015 if (!!DemandedVecElts) {
1016 computeKnownBitsImpl(InVec, Known2, DemandedVecElts, Depth + 1);
1017 Known = Known.intersectWith(Known2);
1018 }
1019 break;
1020 }
1021 case TargetOpcode::G_SHUFFLE_VECTOR: {
1022 APInt DemandedLHS, DemandedRHS;
1023 // Collect the known bits that are shared by every vector element referenced
1024 // by the shuffle.
1025 unsigned NumElts = MRI.getType(MI.getOperand(1).getReg()).getNumElements();
1026 if (!getShuffleDemandedElts(NumElts, MI.getOperand(3).getShuffleMask(),
1027 DemandedElts, DemandedLHS, DemandedRHS))
1028 break;
1029
1030 // Known bits are the values that are shared by every demanded element.
1031 Known.Zero.setAllBits();
1032 Known.One.setAllBits();
1033 if (!!DemandedLHS) {
1034 computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedLHS,
1035 Depth + 1);
1036 Known = Known.intersectWith(Known2);
1037 }
1038 // If we don't know any bits, early out.
1039 if (Known.isUnknown())
1040 break;
1041 if (!!DemandedRHS) {
1042 computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedRHS,
1043 Depth + 1);
1044 Known = Known.intersectWith(Known2);
1045 }
1046 break;
1047 }
1048 case TargetOpcode::G_CONCAT_VECTORS: {
1049 if (MRI.getType(MI.getOperand(0).getReg()).isScalableVector())
1050 break;
1051 // Split DemandedElts and test each of the demanded subvectors.
1052 Known.Zero.setAllBits();
1053 Known.One.setAllBits();
1054 unsigned NumSubVectorElts =
1055 MRI.getType(MI.getOperand(1).getReg()).getNumElements();
1056
1057 for (const auto &[I, MO] : enumerate(drop_begin(MI.operands()))) {
1058 APInt DemandedSub =
1059 DemandedElts.extractBits(NumSubVectorElts, I * NumSubVectorElts);
1060 if (!!DemandedSub) {
1061 computeKnownBitsImpl(MO.getReg(), Known2, DemandedSub, Depth + 1);
1062
1063 Known = Known.intersectWith(Known2);
1064 }
1065 // If we don't know any bits, early out.
1066 if (Known.isUnknown())
1067 break;
1068 }
1069 break;
1070 }
1071 case TargetOpcode::G_ABS: {
1072 Register SrcReg = MI.getOperand(1).getReg();
1073 computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
1074 Known = Known.abs();
1075 Known.Zero.setHighBits(computeNumSignBits(SrcReg, DemandedElts, Depth + 1) -
1076 1);
1077 break;
1078 }
1079 }
1080
1082}
1083
1084void GISelValueTracking::computeKnownFPClass(Register R, KnownFPClass &Known,
1085 FPClassTest InterestedClasses,
1086 unsigned Depth) {
1087 LLT Ty = MRI.getType(R);
1088 APInt DemandedElts =
1089 Ty.isFixedVector() ? APInt::getAllOnes(Ty.getNumElements()) : APInt(1, 1);
1090 computeKnownFPClass(R, DemandedElts, InterestedClasses, Known, Depth);
1091}
1092
1093/// Return true if this value is known to be the fractional part x - floor(x),
1094/// which lies in [0, 1). This implies the value cannot introduce overflow in a
1095/// fmul when the other operand is known finite.
1097 using namespace MIPatternMatch;
1098 Register SubX;
1099 return mi_match(R, MRI, m_GFSub(m_Reg(SubX), m_GFFloor(m_DeferredReg(SubX))));
1100}
1101
1102void GISelValueTracking::computeKnownFPClassForFPTrunc(
1103 const MachineInstr &MI, const APInt &DemandedElts,
1104 FPClassTest InterestedClasses, KnownFPClass &Known, unsigned Depth) {
1105 if ((InterestedClasses & (KnownFPClass::OrderedLessThanZeroMask | fcNan)) ==
1106 fcNone)
1107 return;
1108
1109 Register Val = MI.getOperand(1).getReg();
1110 KnownFPClass KnownSrc;
1111 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1112 Depth + 1);
1113 Known = KnownFPClass::fptrunc(KnownSrc);
1114}
1115
1116void GISelValueTracking::computeKnownFPClass(Register R,
1117 const APInt &DemandedElts,
1118 FPClassTest InterestedClasses,
1120 unsigned Depth) {
1121 assert(Known.isUnknown() && "should not be called with known information");
1122
1123 if (!DemandedElts) {
1124 // No demanded elts, better to assume we don't know anything.
1125 Known.resetAll();
1126 return;
1127 }
1128
1129 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
1130
1131 MachineInstr &MI = *MRI.getVRegDef(R);
1132 unsigned Opcode = MI.getOpcode();
1133 LLT DstTy = MRI.getType(R);
1134
1135 if (!DstTy.isValid()) {
1136 Known.resetAll();
1137 return;
1138 }
1139
1140 if (auto Cst = GFConstant::getConstant(R, MRI)) {
1141 switch (Cst->getKind()) {
1143 auto APF = Cst->getScalarValue();
1144 Known.KnownFPClasses = APF.classify();
1145 Known.SignBit = APF.isNegative();
1146 break;
1147 }
1149 Known.KnownFPClasses = fcNone;
1150 bool SignBitAllZero = true;
1151 bool SignBitAllOne = true;
1152
1153 for (auto C : *Cst) {
1154 Known.KnownFPClasses |= C.classify();
1155 if (C.isNegative())
1156 SignBitAllZero = false;
1157 else
1158 SignBitAllOne = false;
1159 }
1160
1161 if (SignBitAllOne != SignBitAllZero)
1162 Known.SignBit = SignBitAllOne;
1163
1164 break;
1165 }
1167 Known.resetAll();
1168 break;
1169 }
1170 }
1171
1172 return;
1173 }
1174
1175 FPClassTest KnownNotFromFlags = fcNone;
1177 KnownNotFromFlags |= fcNan;
1179 KnownNotFromFlags |= fcInf;
1180
1181 // We no longer need to find out about these bits from inputs if we can
1182 // assume this from flags/attributes.
1183 InterestedClasses &= ~KnownNotFromFlags;
1184
1185 llvm::scope_exit ClearClassesFromFlags(
1186 [=, &Known] { Known.knownNot(KnownNotFromFlags); });
1187
1188 // All recursive calls that increase depth must come after this.
1190 return;
1191
1192 const MachineFunction *MF = MI.getMF();
1193
1194 switch (Opcode) {
1195 default:
1196 TL.computeKnownFPClassForTargetInstr(*this, R, Known, DemandedElts, MRI,
1197 Depth);
1198 break;
1199 case TargetOpcode::G_FNEG: {
1200 Register Val = MI.getOperand(1).getReg();
1201 computeKnownFPClass(Val, DemandedElts, InterestedClasses, Known, Depth + 1);
1202 Known.fneg();
1203 break;
1204 }
1205 case TargetOpcode::G_SELECT: {
1206 GSelect &SelMI = cast<GSelect>(MI);
1207 Register Cond = SelMI.getCondReg();
1208 Register LHS = SelMI.getTrueReg();
1209 Register RHS = SelMI.getFalseReg();
1210
1211 FPClassTest FilterLHS = fcAllFlags;
1212 FPClassTest FilterRHS = fcAllFlags;
1213
1214 Register TestedValue;
1215 FPClassTest MaskIfTrue = fcAllFlags;
1216 FPClassTest MaskIfFalse = fcAllFlags;
1217 FPClassTest ClassVal = fcNone;
1218
1219 CmpInst::Predicate Pred;
1220 Register CmpLHS, CmpRHS;
1221 if (mi_match(Cond, MRI,
1222 m_GFCmp(m_Pred(Pred), m_Reg(CmpLHS), m_Reg(CmpRHS)))) {
1223 // If the select filters out a value based on the class, it no longer
1224 // participates in the class of the result
1225
1226 // TODO: In some degenerate cases we can infer something if we try again
1227 // without looking through sign operations.
1228 bool LookThroughFAbsFNeg = CmpLHS != LHS && CmpLHS != RHS;
1229 std::tie(TestedValue, MaskIfTrue, MaskIfFalse) =
1230 fcmpImpliesClass(Pred, *MF, CmpLHS, CmpRHS, LookThroughFAbsFNeg);
1231 } else if (mi_match(
1232 Cond, MRI,
1233 m_GIsFPClass(m_Reg(TestedValue), m_FPClassTest(ClassVal)))) {
1234 FPClassTest TestedMask = ClassVal;
1235 MaskIfTrue = TestedMask;
1236 MaskIfFalse = ~TestedMask;
1237 }
1238
1239 if (TestedValue == LHS) {
1240 // match !isnan(x) ? x : y
1241 FilterLHS = MaskIfTrue;
1242 } else if (TestedValue == RHS) { // && IsExactClass
1243 // match !isnan(x) ? y : x
1244 FilterRHS = MaskIfFalse;
1245 }
1246
1247 KnownFPClass Known2;
1248 computeKnownFPClass(LHS, DemandedElts, InterestedClasses & FilterLHS, Known,
1249 Depth + 1);
1250 Known.KnownFPClasses &= FilterLHS;
1251
1252 computeKnownFPClass(RHS, DemandedElts, InterestedClasses & FilterRHS,
1253 Known2, Depth + 1);
1254 Known2.KnownFPClasses &= FilterRHS;
1255
1256 Known |= Known2;
1257 break;
1258 }
1259 case TargetOpcode::G_FCOPYSIGN: {
1260 Register Magnitude = MI.getOperand(1).getReg();
1261 Register Sign = MI.getOperand(2).getReg();
1262
1263 KnownFPClass KnownSign;
1264
1265 computeKnownFPClass(Magnitude, DemandedElts, InterestedClasses, Known,
1266 Depth + 1);
1267 computeKnownFPClass(Sign, DemandedElts, InterestedClasses, KnownSign,
1268 Depth + 1);
1269 Known.copysign(KnownSign);
1270 break;
1271 }
1272 case TargetOpcode::G_FMA:
1273 case TargetOpcode::G_STRICT_FMA:
1274 case TargetOpcode::G_FMAD: {
1275 if ((InterestedClasses & fcNegative) == fcNone)
1276 break;
1277
1278 Register A = MI.getOperand(1).getReg();
1279 Register B = MI.getOperand(2).getReg();
1280 Register C = MI.getOperand(3).getReg();
1281
1282 DenormalMode Mode =
1283 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1284
1285 if (A == B && isGuaranteedNotToBeUndef(A, MRI, Depth + 1)) {
1286 // x * x + y
1287 KnownFPClass KnownSrc, KnownAddend;
1288 computeKnownFPClass(C, DemandedElts, InterestedClasses, KnownAddend,
1289 Depth + 1);
1290 computeKnownFPClass(A, DemandedElts, InterestedClasses, KnownSrc,
1291 Depth + 1);
1292 if (KnownNotFromFlags) {
1293 KnownSrc.knownNot(KnownNotFromFlags);
1294 KnownAddend.knownNot(KnownNotFromFlags);
1295 }
1296 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
1297 } else {
1298 KnownFPClass KnownSrc[3];
1299 computeKnownFPClass(A, DemandedElts, InterestedClasses, KnownSrc[0],
1300 Depth + 1);
1301 if (KnownSrc[0].isUnknown())
1302 break;
1303 computeKnownFPClass(B, DemandedElts, InterestedClasses, KnownSrc[1],
1304 Depth + 1);
1305 if (KnownSrc[1].isUnknown())
1306 break;
1307 computeKnownFPClass(C, DemandedElts, InterestedClasses, KnownSrc[2],
1308 Depth + 1);
1309 if (KnownSrc[2].isUnknown())
1310 break;
1311 if (KnownNotFromFlags) {
1312 KnownSrc[0].knownNot(KnownNotFromFlags);
1313 KnownSrc[1].knownNot(KnownNotFromFlags);
1314 KnownSrc[2].knownNot(KnownNotFromFlags);
1315 }
1316 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
1317 }
1318 break;
1319 }
1320 case TargetOpcode::G_FSQRT:
1321 case TargetOpcode::G_STRICT_FSQRT: {
1322 KnownFPClass KnownSrc;
1323 FPClassTest InterestedSrcs = InterestedClasses;
1324 if (InterestedClasses & fcNan)
1325 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
1326
1327 Register Val = MI.getOperand(1).getReg();
1328 computeKnownFPClass(Val, DemandedElts, InterestedSrcs, KnownSrc, Depth + 1);
1329
1330 DenormalMode Mode =
1331 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1332 Known = KnownFPClass::sqrt(KnownSrc, Mode);
1333 if (MI.getFlag(MachineInstr::MIFlag::FmNsz))
1334 Known.knownNot(fcNegZero);
1335 break;
1336 }
1337 case TargetOpcode::G_FABS: {
1338 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
1339 Register Val = MI.getOperand(1).getReg();
1340 // If we only care about the sign bit we don't need to inspect the
1341 // operand.
1342 computeKnownFPClass(Val, DemandedElts, InterestedClasses, Known,
1343 Depth + 1);
1344 }
1345 Known.fabs();
1346 break;
1347 }
1348 case TargetOpcode::G_FATAN2: {
1349 Register Y = MI.getOperand(1).getReg();
1350 Register X = MI.getOperand(2).getReg();
1351 KnownFPClass KnownY, KnownX;
1352 computeKnownFPClass(Y, DemandedElts, InterestedClasses, KnownY, Depth + 1);
1353 computeKnownFPClass(X, DemandedElts, InterestedClasses, KnownX, Depth + 1);
1354 Known = KnownFPClass::atan2(KnownY, KnownX);
1355 break;
1356 }
1357 case TargetOpcode::G_FSINH: {
1358 Register Val = MI.getOperand(1).getReg();
1359 KnownFPClass KnownSrc;
1360 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1361 Depth + 1);
1362 Known = KnownFPClass::sinh(KnownSrc);
1363 break;
1364 }
1365 case TargetOpcode::G_FCOSH: {
1366 Register Val = MI.getOperand(1).getReg();
1367 KnownFPClass KnownSrc;
1368 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1369 Depth + 1);
1370 Known = KnownFPClass::cosh(KnownSrc);
1371 break;
1372 }
1373 case TargetOpcode::G_FTANH: {
1374 Register Val = MI.getOperand(1).getReg();
1375 KnownFPClass KnownSrc;
1376 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1377 Depth + 1);
1378 Known = KnownFPClass::tanh(KnownSrc);
1379 break;
1380 }
1381 case TargetOpcode::G_FASIN: {
1382 Register Val = MI.getOperand(1).getReg();
1383 KnownFPClass KnownSrc;
1384 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1385 Depth + 1);
1386 Known = KnownFPClass::asin(KnownSrc);
1387 break;
1388 }
1389 case TargetOpcode::G_FACOS: {
1390 Register Val = MI.getOperand(1).getReg();
1391 KnownFPClass KnownSrc;
1392 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1393 Depth + 1);
1394 Known = KnownFPClass::acos(KnownSrc);
1395 break;
1396 }
1397 case TargetOpcode::G_FATAN: {
1398 Register Val = MI.getOperand(1).getReg();
1399 KnownFPClass KnownSrc;
1400 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1401 Depth + 1);
1402 Known = KnownFPClass::atan(KnownSrc);
1403 break;
1404 }
1405 case TargetOpcode::G_FTAN: {
1406 Register Val = MI.getOperand(1).getReg();
1407 KnownFPClass KnownSrc;
1408 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1409 Depth + 1);
1410 Known = KnownFPClass::tan(KnownSrc);
1411 break;
1412 }
1413 case TargetOpcode::G_FSIN:
1414 case TargetOpcode::G_FCOS: {
1415 // Return NaN on infinite inputs.
1416 Register Val = MI.getOperand(1).getReg();
1417 KnownFPClass KnownSrc;
1418 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1419 Depth + 1);
1420 Known = Opcode == TargetOpcode::G_FCOS ? KnownFPClass::cos(KnownSrc)
1421 : KnownFPClass::sin(KnownSrc);
1422 break;
1423 }
1424 case TargetOpcode::G_FSINCOS: {
1425 // Operand layout: (sin_dst, cos_dst, src)
1426 Register Src = MI.getOperand(2).getReg();
1427 KnownFPClass KnownSrc;
1428 computeKnownFPClass(Src, DemandedElts, InterestedClasses, KnownSrc,
1429 Depth + 1);
1430 if (R == MI.getOperand(0).getReg())
1431 Known = KnownFPClass::sin(KnownSrc);
1432 else
1433 Known = KnownFPClass::cos(KnownSrc);
1434 break;
1435 }
1436 case TargetOpcode::G_FMAXNUM:
1437 case TargetOpcode::G_FMINNUM:
1438 case TargetOpcode::G_FMINNUM_IEEE:
1439 case TargetOpcode::G_FMAXIMUM:
1440 case TargetOpcode::G_FMINIMUM:
1441 case TargetOpcode::G_FMAXNUM_IEEE:
1442 case TargetOpcode::G_FMAXIMUMNUM:
1443 case TargetOpcode::G_FMINIMUMNUM: {
1444 Register LHS = MI.getOperand(1).getReg();
1445 Register RHS = MI.getOperand(2).getReg();
1446 KnownFPClass KnownLHS, KnownRHS;
1447
1448 computeKnownFPClass(LHS, DemandedElts, InterestedClasses, KnownLHS,
1449 Depth + 1);
1450 computeKnownFPClass(RHS, DemandedElts, InterestedClasses, KnownRHS,
1451 Depth + 1);
1452
1454 switch (Opcode) {
1455 case TargetOpcode::G_FMINIMUM:
1457 break;
1458 case TargetOpcode::G_FMAXIMUM:
1460 break;
1461 case TargetOpcode::G_FMINIMUMNUM:
1463 break;
1464 case TargetOpcode::G_FMAXIMUMNUM:
1466 break;
1467 case TargetOpcode::G_FMINNUM:
1468 case TargetOpcode::G_FMINNUM_IEEE:
1470 break;
1471 case TargetOpcode::G_FMAXNUM:
1472 case TargetOpcode::G_FMAXNUM_IEEE:
1474 break;
1475 default:
1476 llvm_unreachable("unhandled min/max opcode");
1477 }
1478
1479 DenormalMode Mode =
1480 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1481 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, Kind, Mode);
1482 break;
1483 }
1484 case TargetOpcode::G_FCANONICALIZE: {
1485 Register Val = MI.getOperand(1).getReg();
1486 KnownFPClass KnownSrc;
1487 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1488 Depth + 1);
1489
1490 LLT Ty = MRI.getType(Val).getScalarType();
1491 const fltSemantics &FPType = getFltSemanticForLLT(Ty);
1492 DenormalMode DenormMode = MF->getDenormalMode(FPType);
1493 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
1494 break;
1495 }
1496 case TargetOpcode::G_VECREDUCE_FMAX:
1497 case TargetOpcode::G_VECREDUCE_FMIN:
1498 case TargetOpcode::G_VECREDUCE_FMAXIMUM:
1499 case TargetOpcode::G_VECREDUCE_FMINIMUM: {
1500 Register Val = MI.getOperand(1).getReg();
1501 // reduce min/max will choose an element from one of the vector elements,
1502 // so we can infer and class information that is common to all elements.
1503
1504 Known =
1505 computeKnownFPClass(Val, MI.getFlags(), InterestedClasses, Depth + 1);
1506 // Can only propagate sign if output is never NaN.
1507 if (!Known.isKnownNeverNaN())
1508 Known.SignBit.reset();
1509 break;
1510 }
1511 case TargetOpcode::G_FFLOOR:
1512 case TargetOpcode::G_FCEIL:
1513 case TargetOpcode::G_FRINT:
1514 case TargetOpcode::G_FNEARBYINT:
1515 case TargetOpcode::G_INTRINSIC_FPTRUNC_ROUND:
1516 case TargetOpcode::G_INTRINSIC_ROUND:
1517 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
1518 case TargetOpcode::G_INTRINSIC_TRUNC: {
1519 Register Val = MI.getOperand(1).getReg();
1520 KnownFPClass KnownSrc;
1521 FPClassTest InterestedSrcs = InterestedClasses;
1522 if (InterestedSrcs & fcPosFinite)
1523 InterestedSrcs |= fcPosFinite;
1524 if (InterestedSrcs & fcNegFinite)
1525 InterestedSrcs |= fcNegFinite;
1526 computeKnownFPClass(Val, DemandedElts, InterestedSrcs, KnownSrc, Depth + 1);
1527
1528 // TODO: handle multi unit FPTypes once LLT FPInfo lands
1529 bool IsTrunc = Opcode == TargetOpcode::G_INTRINSIC_TRUNC;
1530 Known = KnownFPClass::roundToIntegral(KnownSrc, IsTrunc,
1531 /*IsMultiUnitFPType=*/false);
1532 break;
1533 }
1534 case TargetOpcode::G_FEXP:
1535 case TargetOpcode::G_FEXP2:
1536 case TargetOpcode::G_FEXP10: {
1537 Register Val = MI.getOperand(1).getReg();
1538 KnownFPClass KnownSrc;
1539 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1540 Depth + 1);
1541 Known = KnownFPClass::exp(KnownSrc);
1542 break;
1543 }
1544 case TargetOpcode::G_FLOG:
1545 case TargetOpcode::G_FLOG2:
1546 case TargetOpcode::G_FLOG10: {
1547 // log(+inf) -> +inf
1548 // log([+-]0.0) -> -inf
1549 // log(-inf) -> nan
1550 // log(-x) -> nan
1551 if ((InterestedClasses & (fcNan | fcInf)) == fcNone)
1552 break;
1553
1554 FPClassTest InterestedSrcs = InterestedClasses;
1555 if ((InterestedClasses & fcNegInf) != fcNone)
1556 InterestedSrcs |= fcZero | fcSubnormal;
1557 if ((InterestedClasses & fcNan) != fcNone)
1558 InterestedSrcs |= fcNan | fcNegative;
1559
1560 Register Val = MI.getOperand(1).getReg();
1561 KnownFPClass KnownSrc;
1562 computeKnownFPClass(Val, DemandedElts, InterestedSrcs, KnownSrc, Depth + 1);
1563
1564 LLT Ty = MRI.getType(Val).getScalarType();
1565 const fltSemantics &FltSem = getFltSemanticForLLT(Ty);
1566 DenormalMode Mode = MF->getDenormalMode(FltSem);
1567 Known = KnownFPClass::log(KnownSrc, Mode);
1568 break;
1569 }
1570 case TargetOpcode::G_FPOWI: {
1571 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
1572 break;
1573
1574 Register Exp = MI.getOperand(2).getReg();
1575 LLT ExpTy = MRI.getType(Exp);
1576 KnownBits ExponentKnownBits = getKnownBits(
1577 Exp, ExpTy.isVector() ? DemandedElts : APInt(1, 1), Depth + 1);
1578
1579 FPClassTest InterestedSrcs = fcNone;
1580 if (InterestedClasses & fcNan)
1581 InterestedSrcs |= fcNan;
1582 if (!ExponentKnownBits.isZero()) {
1583 if (InterestedClasses & fcInf)
1584 InterestedSrcs |= fcFinite | fcInf;
1585 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
1586 InterestedSrcs |= fcNegative;
1587 }
1588
1589 KnownFPClass KnownSrc;
1590 if (InterestedSrcs != fcNone) {
1591 Register Val = MI.getOperand(1).getReg();
1592 computeKnownFPClass(Val, DemandedElts, InterestedSrcs, KnownSrc,
1593 Depth + 1);
1594 }
1595
1596 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
1597 break;
1598 }
1599 case TargetOpcode::G_FLDEXP:
1600 case TargetOpcode::G_STRICT_FLDEXP: {
1601 Register Val = MI.getOperand(1).getReg();
1602 KnownFPClass KnownSrc;
1603 computeKnownFPClass(Val, DemandedElts, InterestedClasses, KnownSrc,
1604 Depth + 1);
1605
1606 // Can refine inf/zero handling based on the exponent operand.
1607 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
1608 KnownBits ExpBits;
1609 if ((KnownSrc.KnownFPClasses & ExpInfoMask) != fcNone) {
1610 Register ExpReg = MI.getOperand(2).getReg();
1611 LLT ExpTy = MRI.getType(ExpReg);
1612 ExpBits = getKnownBits(
1613 ExpReg, ExpTy.isVector() ? DemandedElts : APInt(1, 1), Depth + 1);
1614 }
1615
1616 LLT ScalarTy = DstTy.getScalarType();
1617 const fltSemantics &Flt = getFltSemanticForLLT(ScalarTy);
1618 DenormalMode Mode = MF->getDenormalMode(Flt);
1619 Known = KnownFPClass::ldexp(KnownSrc, ExpBits, Flt, Mode);
1620 break;
1621 }
1622 case TargetOpcode::G_FADD:
1623 case TargetOpcode::G_STRICT_FADD:
1624 case TargetOpcode::G_FSUB:
1625 case TargetOpcode::G_STRICT_FSUB: {
1626 Register LHS = MI.getOperand(1).getReg();
1627 Register RHS = MI.getOperand(2).getReg();
1628 bool IsAdd = (Opcode == TargetOpcode::G_FADD ||
1629 Opcode == TargetOpcode::G_STRICT_FADD);
1630 bool WantNegative =
1631 IsAdd &&
1632 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
1633 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
1634 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
1635
1636 if (!WantNaN && !WantNegative && !WantNegZero) {
1637 break;
1638 }
1639
1640 DenormalMode Mode =
1641 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1642
1643 FPClassTest InterestedSrcs = InterestedClasses;
1644 if (WantNegative)
1645 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
1646 if (InterestedClasses & fcNan)
1647 InterestedSrcs |= fcInf;
1648
1649 // Special case fadd x, x (canonical form of fmul x, 2).
1650 if (IsAdd && LHS == RHS && isGuaranteedNotToBeUndef(LHS, MRI, Depth + 1)) {
1651 KnownFPClass KnownSelf;
1652 computeKnownFPClass(LHS, DemandedElts, InterestedSrcs, KnownSelf,
1653 Depth + 1);
1654 Known = KnownFPClass::fadd_self(KnownSelf, Mode);
1655 break;
1656 }
1657
1658 KnownFPClass KnownLHS, KnownRHS;
1659 computeKnownFPClass(RHS, DemandedElts, InterestedSrcs, KnownRHS, Depth + 1);
1660
1661 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
1662 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
1663 WantNegZero || !IsAdd) {
1664 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
1665 // there's no point.
1666 computeKnownFPClass(LHS, DemandedElts, InterestedSrcs, KnownLHS,
1667 Depth + 1);
1668 }
1669
1670 if (IsAdd)
1671 Known = KnownFPClass::fadd(KnownLHS, KnownRHS, Mode);
1672 else
1673 Known = KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
1674 break;
1675 }
1676 case TargetOpcode::G_FMUL:
1677 case TargetOpcode::G_STRICT_FMUL: {
1678 Register LHS = MI.getOperand(1).getReg();
1679 Register RHS = MI.getOperand(2).getReg();
1680 DenormalMode Mode =
1681 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1682
1683 // X * X is always non-negative or a NaN (use square() for precision).
1684 if (LHS == RHS && isGuaranteedNotToBeUndef(LHS, MRI, Depth + 1)) {
1685 KnownFPClass KnownSrc;
1686 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Depth + 1);
1687 Known = KnownFPClass::square(KnownSrc, Mode);
1688 } else {
1689 // If RHS is a scalar constant, use the more precise APFloat overload.
1690 auto RHSCst = GFConstant::getConstant(RHS, MRI);
1691 if (RHSCst && RHSCst->getKind() == GFConstant::GFConstantKind::Scalar) {
1692 KnownFPClass KnownLHS;
1693 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Depth + 1);
1694 Known = KnownFPClass::fmul(KnownLHS, RHSCst->getScalarValue(), Mode);
1695 } else {
1696 KnownFPClass KnownLHS, KnownRHS;
1697 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Depth + 1);
1698 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Depth + 1);
1699 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
1700
1701 // If one operand is known |x| <= 1 and the other is finite, the
1702 // product cannot overflow to infinity.
1703 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS, MRI))
1704 Known.knownNot(fcInf);
1705 else if (KnownRHS.isKnownNever(fcInf) &&
1707 Known.knownNot(fcInf);
1708 }
1709 }
1710 break;
1711 }
1712 case TargetOpcode::G_FDIV:
1713 case TargetOpcode::G_FREM: {
1714 Register LHS = MI.getOperand(1).getReg();
1715 Register RHS = MI.getOperand(2).getReg();
1716
1717 if (Opcode == TargetOpcode::G_FREM)
1718 Known.knownNot(fcInf);
1719
1720 DenormalMode Mode =
1721 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1722
1723 if (LHS == RHS && isGuaranteedNotToBeUndef(LHS, MRI, Depth + 1)) {
1724 if (Opcode == TargetOpcode::G_FDIV) {
1725 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
1726 if (!WantNan) {
1727 // X / X is always exactly 1.0 or a NaN.
1728 Known.KnownFPClasses = fcPosNormal | fcNan;
1729 break;
1730 }
1731 KnownFPClass KnownSrc;
1732 computeKnownFPClass(LHS, DemandedElts,
1733 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc,
1734 Depth + 1);
1735 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
1736 } else {
1737 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
1738 if (!WantNan) {
1739 // X % X is always exactly [+-]0.0 or a NaN.
1740 Known.KnownFPClasses = fcZero | fcNan;
1741 break;
1742 }
1743 KnownFPClass KnownSrc;
1744 computeKnownFPClass(LHS, DemandedElts,
1745 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc,
1746 Depth + 1);
1747 Known = KnownFPClass::frem_self(KnownSrc, Mode);
1748 }
1749 break;
1750 }
1751
1752 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
1753 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
1754 const bool WantPositive = Opcode == TargetOpcode::G_FREM &&
1755 (InterestedClasses & fcPositive) != fcNone;
1756 if (!WantNan && !WantNegative && !WantPositive) {
1757 break;
1758 }
1759
1760 KnownFPClass KnownLHS, KnownRHS;
1761
1762 computeKnownFPClass(RHS, DemandedElts, fcNan | fcInf | fcZero | fcNegative,
1763 KnownRHS, Depth + 1);
1764
1765 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
1766 KnownRHS.isKnownNever(fcNegative) ||
1767 KnownRHS.isKnownNever(fcPositive);
1768
1769 if (KnowSomethingUseful || WantPositive) {
1770 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Depth + 1);
1771 }
1772
1773 if (Opcode == TargetOpcode::G_FDIV) {
1774 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
1775 } else {
1776 // Inf REM x and x REM 0 produce NaN.
1777 if (KnownLHS.isKnownNeverNaN() && KnownRHS.isKnownNeverNaN() &&
1778 KnownLHS.isKnownNeverInfinity() &&
1779 KnownRHS.isKnownNeverLogicalZero(Mode)) {
1780 Known.knownNot(fcNan);
1781 }
1782
1783 // The sign for frem is the same as the first operand.
1784 if (KnownLHS.cannotBeOrderedLessThanZero())
1786 if (KnownLHS.cannotBeOrderedGreaterThanZero())
1788
1789 // See if we can be more aggressive about the sign of 0.
1790 if (KnownLHS.isKnownNever(fcNegative))
1791 Known.knownNot(fcNegative);
1792 if (KnownLHS.isKnownNever(fcPositive))
1793 Known.knownNot(fcPositive);
1794 }
1795 break;
1796 }
1797 case TargetOpcode::G_FFREXP: {
1798 // Only handle the mantissa output (operand 0); the exponent is an integer.
1799 if (R != MI.getOperand(0).getReg())
1800 break;
1801 Register Src = MI.getOperand(2).getReg();
1802 KnownFPClass KnownSrc;
1803 computeKnownFPClass(Src, DemandedElts, InterestedClasses, KnownSrc,
1804 Depth + 1);
1805 DenormalMode Mode =
1806 MF->getDenormalMode(getFltSemanticForLLT(DstTy.getScalarType()));
1807 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
1808 break;
1809 }
1810 case TargetOpcode::G_FPEXT: {
1811 Register Src = MI.getOperand(1).getReg();
1812 KnownFPClass KnownSrc;
1813 computeKnownFPClass(Src, DemandedElts, InterestedClasses, KnownSrc,
1814 Depth + 1);
1815
1816 LLT DstScalarTy = DstTy.getScalarType();
1817 const fltSemantics &DstSem = getFltSemanticForLLT(DstScalarTy);
1818 LLT SrcTy = MRI.getType(Src).getScalarType();
1819 const fltSemantics &SrcSem = getFltSemanticForLLT(SrcTy);
1820
1821 Known = KnownFPClass::fpext(KnownSrc, DstSem, SrcSem);
1822 break;
1823 }
1824 case TargetOpcode::G_FPTRUNC: {
1825 computeKnownFPClassForFPTrunc(MI, DemandedElts, InterestedClasses, Known,
1826 Depth);
1827 break;
1828 }
1829 case TargetOpcode::G_SITOFP:
1830 case TargetOpcode::G_UITOFP: {
1831 // Cannot produce nan
1832 Known.knownNot(fcNan);
1833
1834 // Integers cannot be subnormal
1835 Known.knownNot(fcSubnormal);
1836
1837 // sitofp and uitofp turn into +0.0 for zero.
1838 Known.knownNot(fcNegZero);
1839
1840 // UIToFP is always non-negative regardless of known bits.
1841 if (Opcode == TargetOpcode::G_UITOFP)
1842 Known.signBitMustBeZero();
1843
1844 // Only compute known bits if we can learn something useful from them.
1845 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
1846 break;
1847
1848 Register Val = MI.getOperand(1).getReg();
1849 LLT Ty = MRI.getType(Val);
1850 KnownBits IntKnown = getKnownBits(
1851 Val, Ty.isVector() ? DemandedElts : APInt(1, 1), Depth + 1);
1852
1853 // If the integer is non-zero, the result cannot be +0.0.
1854 if (IntKnown.isNonZero())
1855 Known.knownNot(fcPosZero);
1856
1857 if (Opcode == TargetOpcode::G_SITOFP) {
1858 // If the signed integer is known non-negative, the result is
1859 // non-negative. If the signed integer is known negative, the result is
1860 // negative.
1861 if (IntKnown.isNonNegative())
1862 Known.signBitMustBeZero();
1863 else if (IntKnown.isNegative())
1864 Known.signBitMustBeOne();
1865 }
1866
1867 if (InterestedClasses & fcInf) {
1868 LLT FPTy = DstTy.getScalarType();
1869 const fltSemantics &FltSem = getFltSemanticForLLT(FPTy);
1870
1871 // Compute the effective integer width after removing known-zero leading
1872 // bits, to check if the result can overflow to infinity.
1873 int IntSize = IntKnown.getBitWidth();
1874 if (Opcode == TargetOpcode::G_UITOFP)
1875 IntSize -= IntKnown.countMinLeadingZeros();
1876 else
1877 IntSize -= IntKnown.countMinSignBits();
1878
1879 // If the exponent of the largest finite FP value can hold the largest
1880 // integer, the result of the cast must be finite.
1881 if (ilogb(APFloat::getLargest(FltSem)) >= IntSize)
1882 Known.knownNot(fcInf);
1883 }
1884
1885 break;
1886 }
1887 // case TargetOpcode::G_MERGE_VALUES:
1888 case TargetOpcode::G_BUILD_VECTOR:
1889 case TargetOpcode::G_CONCAT_VECTORS: {
1890 GMergeLikeInstr &Merge = cast<GMergeLikeInstr>(MI);
1891
1892 if (!DstTy.isFixedVector())
1893 break;
1894
1895 bool First = true;
1896 for (unsigned Idx = 0; Idx < Merge.getNumSources(); ++Idx) {
1897 // We know the index we are inserting to, so clear it from Vec check.
1898 bool NeedsElt = DemandedElts[Idx];
1899
1900 // Do we demand the inserted element?
1901 if (NeedsElt) {
1902 Register Src = Merge.getSourceReg(Idx);
1903 if (First) {
1904 computeKnownFPClass(Src, Known, InterestedClasses, Depth + 1);
1905 First = false;
1906 } else {
1907 KnownFPClass Known2;
1908 computeKnownFPClass(Src, Known2, InterestedClasses, Depth + 1);
1909 Known |= Known2;
1910 }
1911
1912 // If we don't know any bits, early out.
1913 if (Known.isUnknown())
1914 break;
1915 }
1916 }
1917
1918 break;
1919 }
1920 case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
1921 // Look through extract element. If the index is non-constant or
1922 // out-of-range demand all elements, otherwise just the extracted
1923 // element.
1924 GExtractVectorElement &Extract = cast<GExtractVectorElement>(MI);
1925 Register Vec = Extract.getVectorReg();
1926 Register Idx = Extract.getIndexReg();
1927
1928 auto CIdx = getIConstantVRegVal(Idx, MRI);
1929
1930 LLT VecTy = MRI.getType(Vec);
1931
1932 if (VecTy.isFixedVector()) {
1933 unsigned NumElts = VecTy.getNumElements();
1934 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
1935 if (CIdx && CIdx->ult(NumElts))
1936 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
1937 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
1938 Depth + 1);
1939 }
1940
1941 break;
1942 }
1943 case TargetOpcode::G_INSERT_VECTOR_ELT: {
1944 GInsertVectorElement &Insert = cast<GInsertVectorElement>(MI);
1945 Register Vec = Insert.getVectorReg();
1946 Register Elt = Insert.getElementReg();
1947 Register Idx = Insert.getIndexReg();
1948
1949 LLT VecTy = MRI.getType(Vec);
1950
1951 if (VecTy.isScalableVector())
1952 return;
1953
1954 auto CIdx = getIConstantVRegVal(Idx, MRI);
1955
1956 unsigned NumElts = DemandedElts.getBitWidth();
1957 APInt DemandedVecElts = DemandedElts;
1958 bool NeedsElt = true;
1959 // If we know the index we are inserting to, clear it from Vec check.
1960 if (CIdx && CIdx->ult(NumElts)) {
1961 DemandedVecElts.clearBit(CIdx->getZExtValue());
1962 NeedsElt = DemandedElts[CIdx->getZExtValue()];
1963 }
1964
1965 // Do we demand the inserted element?
1966 if (NeedsElt) {
1967 computeKnownFPClass(Elt, Known, InterestedClasses, Depth + 1);
1968 // If we don't know any bits, early out.
1969 if (Known.isUnknown())
1970 break;
1971 } else {
1972 Known.KnownFPClasses = fcNone;
1973 }
1974
1975 // Do we need anymore elements from Vec?
1976 if (!DemandedVecElts.isZero()) {
1977 KnownFPClass Known2;
1978 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2,
1979 Depth + 1);
1980 Known |= Known2;
1981 }
1982
1983 break;
1984 }
1985 case TargetOpcode::G_SHUFFLE_VECTOR: {
1986 // For undef elements, we don't know anything about the common state of
1987 // the shuffle result.
1988 GShuffleVector &Shuf = cast<GShuffleVector>(MI);
1989 APInt DemandedLHS, DemandedRHS;
1990 if (DstTy.isScalableVector()) {
1991 assert(DemandedElts == APInt(1, 1));
1992 DemandedLHS = DemandedRHS = DemandedElts;
1993 } else {
1994 unsigned NumElts = MRI.getType(Shuf.getSrc1Reg()).getNumElements();
1995 if (!llvm::getShuffleDemandedElts(NumElts, Shuf.getMask(), DemandedElts,
1996 DemandedLHS, DemandedRHS)) {
1997 Known.resetAll();
1998 return;
1999 }
2000 }
2001
2002 if (!!DemandedLHS) {
2003 Register LHS = Shuf.getSrc1Reg();
2004 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known,
2005 Depth + 1);
2006
2007 // If we don't know any bits, early out.
2008 if (Known.isUnknown())
2009 break;
2010 } else {
2011 Known.KnownFPClasses = fcNone;
2012 }
2013
2014 if (!!DemandedRHS) {
2015 KnownFPClass Known2;
2016 Register RHS = Shuf.getSrc2Reg();
2017 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2,
2018 Depth + 1);
2019 Known |= Known2;
2020 }
2021 break;
2022 }
2023 case TargetOpcode::G_PHI: {
2024 // Cap PHI recursion below the global limit to avoid spending the entire
2025 // budget chasing loop back-edges (matches ValueTracking's
2026 // PhiRecursionLimit).
2028 break;
2029 // PHI's operands are a mix of registers and basic blocks interleaved.
2030 // We only care about the register ones.
2031 bool First = true;
2032 for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
2033 const MachineOperand &Src = MI.getOperand(Idx);
2034 Register SrcReg = Src.getReg();
2035 if (First) {
2036 computeKnownFPClass(SrcReg, DemandedElts, InterestedClasses, Known,
2037 Depth + 1);
2038 First = false;
2039 } else {
2040 KnownFPClass Known2;
2041 computeKnownFPClass(SrcReg, DemandedElts, InterestedClasses, Known2,
2042 Depth + 1);
2043 Known = Known.intersectWith(Known2);
2044 }
2045 if (Known.isUnknown())
2046 break;
2047 }
2048 break;
2049 }
2050 case TargetOpcode::COPY: {
2051 Register Src = MI.getOperand(1).getReg();
2052
2053 if (!Src.isVirtual())
2054 return;
2055
2056 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Depth + 1);
2057 break;
2058 }
2059 }
2060}
2061
2063GISelValueTracking::computeKnownFPClass(Register R, const APInt &DemandedElts,
2064 FPClassTest InterestedClasses,
2065 unsigned Depth) {
2066 KnownFPClass KnownClasses;
2067 computeKnownFPClass(R, DemandedElts, InterestedClasses, KnownClasses, Depth);
2068 return KnownClasses;
2069}
2070
2071KnownFPClass GISelValueTracking::computeKnownFPClass(
2072 Register R, FPClassTest InterestedClasses, unsigned Depth) {
2074 computeKnownFPClass(R, Known, InterestedClasses, Depth);
2075 return Known;
2076}
2077
2078KnownFPClass GISelValueTracking::computeKnownFPClass(
2079 Register R, const APInt &DemandedElts, uint32_t Flags,
2080 FPClassTest InterestedClasses, unsigned Depth) {
2082 InterestedClasses &= ~fcNan;
2084 InterestedClasses &= ~fcInf;
2085
2086 KnownFPClass Result =
2087 computeKnownFPClass(R, DemandedElts, InterestedClasses, Depth);
2088
2090 Result.KnownFPClasses &= ~fcNan;
2092 Result.KnownFPClasses &= ~fcInf;
2093 return Result;
2094}
2095
2096KnownFPClass GISelValueTracking::computeKnownFPClass(
2097 Register R, uint32_t Flags, FPClassTest InterestedClasses, unsigned Depth) {
2098 LLT Ty = MRI.getType(R);
2099 APInt DemandedElts =
2100 Ty.isFixedVector() ? APInt::getAllOnes(Ty.getNumElements()) : APInt(1, 1);
2101 return computeKnownFPClass(R, DemandedElts, Flags, InterestedClasses, Depth);
2102}
2103
2105 const MachineInstr *DefMI = MRI.getVRegDef(Val);
2106 if (!DefMI)
2107 return false;
2108
2109 if (DefMI->getFlag(MachineInstr::FmNoNans))
2110 return true;
2111
2112 // IEEE 754 arithmetic operations always quiet signaling NaNs. Short-circuit
2113 // the value-tracking analysis for the SNaN-only case: if the defining op is
2114 // known to quiet sNaN, the output can never be an sNaN.
2115 if (SNaN) {
2116 switch (DefMI->getOpcode()) {
2117 default:
2118 break;
2119 case TargetOpcode::G_FADD:
2120 case TargetOpcode::G_STRICT_FADD:
2121 case TargetOpcode::G_FSUB:
2122 case TargetOpcode::G_STRICT_FSUB:
2123 case TargetOpcode::G_FMUL:
2124 case TargetOpcode::G_STRICT_FMUL:
2125 case TargetOpcode::G_FDIV:
2126 case TargetOpcode::G_FREM:
2127 case TargetOpcode::G_FMA:
2128 case TargetOpcode::G_STRICT_FMA:
2129 case TargetOpcode::G_FMAD:
2130 case TargetOpcode::G_FSQRT:
2131 case TargetOpcode::G_STRICT_FSQRT:
2132 // Note: G_FABS and G_FNEG are bit-manipulation ops that preserve sNaN
2133 // exactly (LLVM LangRef: "never change anything except possibly the sign
2134 // bit"). They must NOT be listed here.
2135 case TargetOpcode::G_FSIN:
2136 case TargetOpcode::G_FCOS:
2137 case TargetOpcode::G_FSINCOS:
2138 case TargetOpcode::G_FTAN:
2139 case TargetOpcode::G_FASIN:
2140 case TargetOpcode::G_FACOS:
2141 case TargetOpcode::G_FATAN:
2142 case TargetOpcode::G_FATAN2:
2143 case TargetOpcode::G_FSINH:
2144 case TargetOpcode::G_FCOSH:
2145 case TargetOpcode::G_FTANH:
2146 case TargetOpcode::G_FEXP:
2147 case TargetOpcode::G_FEXP2:
2148 case TargetOpcode::G_FEXP10:
2149 case TargetOpcode::G_FLOG:
2150 case TargetOpcode::G_FLOG2:
2151 case TargetOpcode::G_FLOG10:
2152 case TargetOpcode::G_FPOWI:
2153 case TargetOpcode::G_FLDEXP:
2154 case TargetOpcode::G_STRICT_FLDEXP:
2155 case TargetOpcode::G_FFREXP:
2156 case TargetOpcode::G_INTRINSIC_TRUNC:
2157 case TargetOpcode::G_INTRINSIC_ROUND:
2158 case TargetOpcode::G_INTRINSIC_ROUNDEVEN:
2159 case TargetOpcode::G_FFLOOR:
2160 case TargetOpcode::G_FCEIL:
2161 case TargetOpcode::G_FRINT:
2162 case TargetOpcode::G_FNEARBYINT:
2163 case TargetOpcode::G_FPEXT:
2164 case TargetOpcode::G_FPTRUNC:
2165 case TargetOpcode::G_FCANONICALIZE:
2166 case TargetOpcode::G_FMINNUM:
2167 case TargetOpcode::G_FMAXNUM:
2168 case TargetOpcode::G_FMINNUM_IEEE:
2169 case TargetOpcode::G_FMAXNUM_IEEE:
2170 case TargetOpcode::G_FMINIMUM:
2171 case TargetOpcode::G_FMAXIMUM:
2172 case TargetOpcode::G_FMINIMUMNUM:
2173 case TargetOpcode::G_FMAXIMUMNUM:
2174 return true;
2175 }
2176 }
2177
2178 KnownFPClass FPClass = computeKnownFPClass(Val, SNaN ? fcSNan : fcNan);
2179
2180 if (SNaN)
2181 return FPClass.isKnownNever(fcSNan);
2182
2183 return FPClass.isKnownNeverNaN();
2184}
2185
2186/// Compute number of sign bits for the intersection of \p Src0 and \p Src1
2187unsigned GISelValueTracking::computeNumSignBitsMin(Register Src0, Register Src1,
2188 const APInt &DemandedElts,
2189 unsigned Depth) {
2190 // Test src1 first, since we canonicalize simpler expressions to the RHS.
2191 unsigned Src1SignBits = computeNumSignBits(Src1, DemandedElts, Depth);
2192 if (Src1SignBits == 1)
2193 return 1;
2194 return std::min(computeNumSignBits(Src0, DemandedElts, Depth), Src1SignBits);
2195}
2196
2197/// Compute the known number of sign bits with attached range metadata in the
2198/// memory operand. If this is an extending load, accounts for the behavior of
2199/// the high bits.
2201 unsigned TyBits) {
2202 const MDNode *Ranges = Ld->getRanges();
2203 if (!Ranges)
2204 return 1;
2205
2207 if (TyBits > CR.getBitWidth()) {
2208 switch (Ld->getOpcode()) {
2209 case TargetOpcode::G_SEXTLOAD:
2210 CR = CR.signExtend(TyBits);
2211 break;
2212 case TargetOpcode::G_ZEXTLOAD:
2213 CR = CR.zeroExtend(TyBits);
2214 break;
2215 default:
2216 break;
2217 }
2218 }
2219
2220 return std::min(CR.getSignedMin().getNumSignBits(),
2222}
2223
2225 const APInt &DemandedElts,
2226 unsigned Depth) {
2227 MachineInstr &MI = *MRI.getVRegDef(R);
2228 unsigned Opcode = MI.getOpcode();
2229
2230 if (Opcode == TargetOpcode::G_CONSTANT)
2231 return MI.getOperand(1).getCImm()->getValue().getNumSignBits();
2232
2233 if (Depth == getMaxDepth())
2234 return 1;
2235
2236 if (!DemandedElts)
2237 return 1; // No demanded elts, better to assume we don't know anything.
2238
2239 LLT DstTy = MRI.getType(R);
2240 const unsigned TyBits = DstTy.getScalarSizeInBits();
2241
2242 // Handle the case where this is called on a register that does not have a
2243 // type constraint. This is unlikely to occur except by looking through copies
2244 // but it is possible for the initial register being queried to be in this
2245 // state.
2246 if (!DstTy.isValid())
2247 return 1;
2248
2249 unsigned FirstAnswer = 1;
2250 switch (Opcode) {
2251 case TargetOpcode::COPY: {
2252 MachineOperand &Src = MI.getOperand(1);
2253 if (Src.getReg().isVirtual() && Src.getSubReg() == 0 &&
2254 MRI.getType(Src.getReg()).isValid()) {
2255 // Don't increment Depth for this one since we didn't do any work.
2256 return computeNumSignBits(Src.getReg(), DemandedElts, Depth);
2257 }
2258
2259 return 1;
2260 }
2261 case TargetOpcode::G_SEXT: {
2262 Register Src = MI.getOperand(1).getReg();
2263 LLT SrcTy = MRI.getType(Src);
2264 unsigned Tmp = DstTy.getScalarSizeInBits() - SrcTy.getScalarSizeInBits();
2265 return computeNumSignBits(Src, DemandedElts, Depth + 1) + Tmp;
2266 }
2267 case TargetOpcode::G_ASSERT_SEXT:
2268 case TargetOpcode::G_SEXT_INREG: {
2269 // Max of the input and what this extends.
2270 Register Src = MI.getOperand(1).getReg();
2271 unsigned SrcBits = MI.getOperand(2).getImm();
2272 unsigned InRegBits = TyBits - SrcBits + 1;
2273 return std::max(computeNumSignBits(Src, DemandedElts, Depth + 1),
2274 InRegBits);
2275 }
2276 case TargetOpcode::G_LOAD: {
2277 GLoad *Ld = cast<GLoad>(&MI);
2278 if (DemandedElts != 1 || !getDataLayout().isLittleEndian())
2279 break;
2280
2281 return computeNumSignBitsFromRangeMetadata(Ld, TyBits);
2282 }
2283 case TargetOpcode::G_SEXTLOAD: {
2285
2286 // FIXME: We need an in-memory type representation.
2287 if (DstTy.isVector())
2288 return 1;
2289
2290 unsigned NumBits = computeNumSignBitsFromRangeMetadata(Ld, TyBits);
2291 if (NumBits != 1)
2292 return NumBits;
2293
2294 // e.g. i16->i32 = '17' bits known.
2295 const MachineMemOperand *MMO = *MI.memoperands_begin();
2296 return TyBits - MMO->getSizeInBits().getValue() + 1;
2297 }
2298 case TargetOpcode::G_ZEXTLOAD: {
2300
2301 // FIXME: We need an in-memory type representation.
2302 if (DstTy.isVector())
2303 return 1;
2304
2305 unsigned NumBits = computeNumSignBitsFromRangeMetadata(Ld, TyBits);
2306 if (NumBits != 1)
2307 return NumBits;
2308
2309 // e.g. i16->i32 = '16' bits known.
2310 const MachineMemOperand *MMO = *MI.memoperands_begin();
2311 return TyBits - MMO->getSizeInBits().getValue();
2312 }
2313 case TargetOpcode::G_AND:
2314 case TargetOpcode::G_OR:
2315 case TargetOpcode::G_XOR: {
2316 Register Src1 = MI.getOperand(1).getReg();
2317 unsigned Src1NumSignBits =
2318 computeNumSignBits(Src1, DemandedElts, Depth + 1);
2319 if (Src1NumSignBits != 1) {
2320 Register Src2 = MI.getOperand(2).getReg();
2321 unsigned Src2NumSignBits =
2322 computeNumSignBits(Src2, DemandedElts, Depth + 1);
2323 FirstAnswer = std::min(Src1NumSignBits, Src2NumSignBits);
2324 }
2325 break;
2326 }
2327 case TargetOpcode::G_ASHR: {
2328 Register Src1 = MI.getOperand(1).getReg();
2329 Register Src2 = MI.getOperand(2).getReg();
2330 FirstAnswer = computeNumSignBits(Src1, DemandedElts, Depth + 1);
2331 if (auto C = getValidMinimumShiftAmount(Src2, DemandedElts, Depth + 1))
2332 FirstAnswer = std::min<uint64_t>(FirstAnswer + *C, TyBits);
2333 break;
2334 }
2335 case TargetOpcode::G_SHL: {
2336 Register Src1 = MI.getOperand(1).getReg();
2337 Register Src2 = MI.getOperand(2).getReg();
2338 if (std::optional<ConstantRange> ShAmtRange =
2339 getValidShiftAmountRange(Src2, DemandedElts, Depth + 1)) {
2340 uint64_t MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
2341 uint64_t MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
2342
2343 MachineInstr &ExtMI = *MRI.getVRegDef(Src1);
2344 unsigned ExtOpc = ExtMI.getOpcode();
2345
2346 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
2347 // shifted out, then we can compute the number of sign bits for the
2348 // operand being extended. A future improvement could be to pass along the
2349 // "shifted left by" information in the recursive calls to
2350 // ComputeKnownSignBits. Allowing us to handle this more generically.
2351 if (ExtOpc == TargetOpcode::G_SEXT || ExtOpc == TargetOpcode::G_ZEXT ||
2352 ExtOpc == TargetOpcode::G_ANYEXT) {
2353 LLT ExtTy = MRI.getType(Src1);
2354 Register Extendee = ExtMI.getOperand(1).getReg();
2355 LLT ExtendeeTy = MRI.getType(Extendee);
2356 uint64_t SizeDiff =
2357 ExtTy.getScalarSizeInBits() - ExtendeeTy.getScalarSizeInBits();
2358
2359 if (SizeDiff <= MinShAmt) {
2360 unsigned Tmp =
2361 SizeDiff + computeNumSignBits(Extendee, DemandedElts, Depth + 1);
2362 if (MaxShAmt < Tmp)
2363 return Tmp - MaxShAmt;
2364 }
2365 }
2366 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
2367 unsigned Tmp = computeNumSignBits(Src1, DemandedElts, Depth + 1);
2368 if (MaxShAmt < Tmp)
2369 return Tmp - MaxShAmt;
2370 }
2371 break;
2372 }
2373 case TargetOpcode::G_SREM: {
2374 // The sign bit is the LHS's sign bit, except when the result of the
2375 // remainder is zero. The magnitude of the result should be less than or
2376 // equal to the magnitude of the LHS. Therefore, the result should have
2377 // at least as many sign bits as the left hand side.
2378 Register Src = MI.getOperand(1).getReg();
2379 return computeNumSignBits(Src, DemandedElts, Depth + 1);
2380 }
2381 case TargetOpcode::G_TRUNC: {
2382 Register Src = MI.getOperand(1).getReg();
2383 LLT SrcTy = MRI.getType(Src);
2384
2385 // Check if the sign bits of source go down as far as the truncated value.
2386 unsigned DstTyBits = DstTy.getScalarSizeInBits();
2387 unsigned NumSrcBits = SrcTy.getScalarSizeInBits();
2388 unsigned NumSrcSignBits = computeNumSignBits(Src, DemandedElts, Depth + 1);
2389 if (NumSrcSignBits > (NumSrcBits - DstTyBits))
2390 return NumSrcSignBits - (NumSrcBits - DstTyBits);
2391 break;
2392 }
2393 case TargetOpcode::G_SELECT: {
2394 return computeNumSignBitsMin(MI.getOperand(2).getReg(),
2395 MI.getOperand(3).getReg(), DemandedElts,
2396 Depth + 1);
2397 }
2398 case TargetOpcode::G_SMIN:
2399 case TargetOpcode::G_SMAX:
2400 case TargetOpcode::G_UMIN:
2401 case TargetOpcode::G_UMAX:
2402 // TODO: Handle clamp pattern with number of sign bits for SMIN/SMAX.
2403 return computeNumSignBitsMin(MI.getOperand(1).getReg(),
2404 MI.getOperand(2).getReg(), DemandedElts,
2405 Depth + 1);
2406 case TargetOpcode::G_SADDO:
2407 case TargetOpcode::G_SADDE:
2408 case TargetOpcode::G_UADDO:
2409 case TargetOpcode::G_UADDE:
2410 case TargetOpcode::G_SSUBO:
2411 case TargetOpcode::G_SSUBE:
2412 case TargetOpcode::G_USUBO:
2413 case TargetOpcode::G_USUBE:
2414 case TargetOpcode::G_SMULO:
2415 case TargetOpcode::G_UMULO: {
2416 // If compares returns 0/-1, all bits are sign bits.
2417 // We know that we have an integer-based boolean since these operations
2418 // are only available for integer.
2419 if (MI.getOperand(1).getReg() == R) {
2420 if (TL.getBooleanContents(DstTy.isVector(), false) ==
2422 return TyBits;
2423 }
2424
2425 break;
2426 }
2427 case TargetOpcode::G_SUB: {
2428 Register Src2 = MI.getOperand(2).getReg();
2429 unsigned Src2NumSignBits =
2430 computeNumSignBits(Src2, DemandedElts, Depth + 1);
2431 if (Src2NumSignBits == 1)
2432 return 1; // Early out.
2433
2434 // Handle NEG.
2435 Register Src1 = MI.getOperand(1).getReg();
2436 KnownBits Known1 = getKnownBits(Src1, DemandedElts, Depth);
2437 if (Known1.isZero()) {
2438 KnownBits Known2 = getKnownBits(Src2, DemandedElts, Depth);
2439 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2440 // sign bits set.
2441 if ((Known2.Zero | 1).isAllOnes())
2442 return TyBits;
2443
2444 // If the input is known to be positive (the sign bit is known clear),
2445 // the output of the NEG has, at worst, the same number of sign bits as
2446 // the input.
2447 if (Known2.isNonNegative()) {
2448 FirstAnswer = Src2NumSignBits;
2449 break;
2450 }
2451
2452 // Otherwise, we treat this like a SUB.
2453 }
2454
2455 unsigned Src1NumSignBits =
2456 computeNumSignBits(Src1, DemandedElts, Depth + 1);
2457 if (Src1NumSignBits == 1)
2458 return 1; // Early Out.
2459
2460 // Sub can have at most one carry bit. Thus we know that the output
2461 // is, at worst, one more bit than the inputs.
2462 FirstAnswer = std::min(Src1NumSignBits, Src2NumSignBits) - 1;
2463 break;
2464 }
2465 case TargetOpcode::G_ADD: {
2466 Register Src2 = MI.getOperand(2).getReg();
2467 unsigned Src2NumSignBits =
2468 computeNumSignBits(Src2, DemandedElts, Depth + 1);
2469 if (Src2NumSignBits <= 2)
2470 return 1; // Early out.
2471
2472 Register Src1 = MI.getOperand(1).getReg();
2473 unsigned Src1NumSignBits =
2474 computeNumSignBits(Src1, DemandedElts, Depth + 1);
2475 if (Src1NumSignBits == 1)
2476 return 1; // Early Out.
2477
2478 // Special case decrementing a value (ADD X, -1):
2479 KnownBits Known2 = getKnownBits(Src2, DemandedElts, Depth);
2480 if (Known2.isAllOnes()) {
2481 KnownBits Known1 = getKnownBits(Src1, DemandedElts, Depth);
2482 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2483 // sign bits set.
2484 if ((Known1.Zero | 1).isAllOnes())
2485 return TyBits;
2486
2487 // If we are subtracting one from a positive number, there is no carry
2488 // out of the result.
2489 if (Known1.isNonNegative()) {
2490 FirstAnswer = Src1NumSignBits;
2491 break;
2492 }
2493
2494 // Otherwise, we treat this like an ADD.
2495 }
2496
2497 // Add can have at most one carry bit. Thus we know that the output
2498 // is, at worst, one more bit than the inputs.
2499 FirstAnswer = std::min(Src1NumSignBits, Src2NumSignBits) - 1;
2500 break;
2501 }
2502 case TargetOpcode::G_FCMP:
2503 case TargetOpcode::G_ICMP: {
2504 bool IsFP = Opcode == TargetOpcode::G_FCMP;
2505 if (TyBits == 1)
2506 break;
2507 auto BC = TL.getBooleanContents(DstTy.isVector(), IsFP);
2509 return TyBits; // All bits are sign bits.
2511 return TyBits - 1; // Every always-zero bit is a sign bit.
2512 break;
2513 }
2514 case TargetOpcode::G_BUILD_VECTOR: {
2515 // Collect the known bits that are shared by every demanded vector element.
2516 FirstAnswer = TyBits;
2517 APInt SingleDemandedElt(1, 1);
2518 for (const auto &[I, MO] : enumerate(drop_begin(MI.operands()))) {
2519 if (!DemandedElts[I])
2520 continue;
2521
2522 unsigned Tmp2 =
2523 computeNumSignBits(MO.getReg(), SingleDemandedElt, Depth + 1);
2524 FirstAnswer = std::min(FirstAnswer, Tmp2);
2525
2526 // If we don't know any bits, early out.
2527 if (FirstAnswer == 1)
2528 break;
2529 }
2530 break;
2531 }
2532 case TargetOpcode::G_CONCAT_VECTORS: {
2533 if (MRI.getType(MI.getOperand(0).getReg()).isScalableVector())
2534 break;
2535 FirstAnswer = TyBits;
2536 // Determine the minimum number of sign bits across all demanded
2537 // elts of the input vectors. Early out if the result is already 1.
2538 unsigned NumSubVectorElts =
2539 MRI.getType(MI.getOperand(1).getReg()).getNumElements();
2540 for (const auto &[I, MO] : enumerate(drop_begin(MI.operands()))) {
2541 APInt DemandedSub =
2542 DemandedElts.extractBits(NumSubVectorElts, I * NumSubVectorElts);
2543 if (!DemandedSub)
2544 continue;
2545 unsigned Tmp2 = computeNumSignBits(MO.getReg(), DemandedSub, Depth + 1);
2546
2547 FirstAnswer = std::min(FirstAnswer, Tmp2);
2548
2549 // If we don't know any bits, early out.
2550 if (FirstAnswer == 1)
2551 break;
2552 }
2553 break;
2554 }
2555 case TargetOpcode::G_SHUFFLE_VECTOR: {
2556 // Collect the minimum number of sign bits that are shared by every vector
2557 // element referenced by the shuffle.
2558 APInt DemandedLHS, DemandedRHS;
2559 Register Src1 = MI.getOperand(1).getReg();
2560 unsigned NumElts = MRI.getType(Src1).getNumElements();
2561 if (!getShuffleDemandedElts(NumElts, MI.getOperand(3).getShuffleMask(),
2562 DemandedElts, DemandedLHS, DemandedRHS))
2563 return 1;
2564
2565 if (!!DemandedLHS)
2566 FirstAnswer = computeNumSignBits(Src1, DemandedLHS, Depth + 1);
2567 // If we don't know anything, early out and try computeKnownBits fall-back.
2568 if (FirstAnswer == 1)
2569 break;
2570 if (!!DemandedRHS) {
2571 unsigned Tmp2 =
2572 computeNumSignBits(MI.getOperand(2).getReg(), DemandedRHS, Depth + 1);
2573 FirstAnswer = std::min(FirstAnswer, Tmp2);
2574 }
2575 break;
2576 }
2577 case TargetOpcode::G_SPLAT_VECTOR: {
2578 // Check if the sign bits of source go down as far as the truncated value.
2579 Register Src = MI.getOperand(1).getReg();
2580 unsigned NumSrcSignBits = computeNumSignBits(Src, APInt(1, 1), Depth + 1);
2581 unsigned NumSrcBits = MRI.getType(Src).getSizeInBits();
2582 if (NumSrcSignBits > (NumSrcBits - TyBits))
2583 return NumSrcSignBits - (NumSrcBits - TyBits);
2584 break;
2585 }
2586 case TargetOpcode::G_INTRINSIC:
2587 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
2588 case TargetOpcode::G_INTRINSIC_CONVERGENT:
2589 case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS:
2590 default: {
2591 unsigned NumBits =
2592 TL.computeNumSignBitsForTargetInstr(*this, R, DemandedElts, MRI, Depth);
2593 if (NumBits > 1)
2594 FirstAnswer = std::max(FirstAnswer, NumBits);
2595 break;
2596 }
2597 }
2598
2599 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2600 // use this information.
2601 KnownBits Known = getKnownBits(R, DemandedElts, Depth);
2602 return std::max(FirstAnswer, Known.countMinSignBits());
2603}
2604
2606 LLT Ty = MRI.getType(R);
2607 APInt DemandedElts =
2608 Ty.isFixedVector() ? APInt::getAllOnes(Ty.getNumElements()) : APInt(1, 1);
2609 return computeNumSignBits(R, DemandedElts, Depth);
2610}
2611
2613 Register R, const APInt &DemandedElts, unsigned Depth) {
2614 // Shifting more than the bitwidth is not valid.
2615 MachineInstr &MI = *MRI.getVRegDef(R);
2616 unsigned Opcode = MI.getOpcode();
2617
2618 LLT Ty = MRI.getType(R);
2619 unsigned BitWidth = Ty.getScalarSizeInBits();
2620
2621 if (Opcode == TargetOpcode::G_CONSTANT) {
2622 const APInt &ShAmt = MI.getOperand(1).getCImm()->getValue();
2623 if (ShAmt.uge(BitWidth))
2624 return std::nullopt;
2625 return ConstantRange(ShAmt);
2626 }
2627
2628 if (Opcode == TargetOpcode::G_BUILD_VECTOR) {
2629 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
2630 for (unsigned I = 0, E = MI.getNumOperands() - 1; I != E; ++I) {
2631 if (!DemandedElts[I])
2632 continue;
2633 MachineInstr *Op = MRI.getVRegDef(MI.getOperand(I + 1).getReg());
2634 if (Op->getOpcode() != TargetOpcode::G_CONSTANT) {
2635 MinAmt = MaxAmt = nullptr;
2636 break;
2637 }
2638
2639 const APInt &ShAmt = Op->getOperand(1).getCImm()->getValue();
2640 if (ShAmt.uge(BitWidth))
2641 return std::nullopt;
2642 if (!MinAmt || MinAmt->ugt(ShAmt))
2643 MinAmt = &ShAmt;
2644 if (!MaxAmt || MaxAmt->ult(ShAmt))
2645 MaxAmt = &ShAmt;
2646 }
2647 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
2648 "Failed to find matching min/max shift amounts");
2649 if (MinAmt && MaxAmt)
2650 return ConstantRange(*MinAmt, *MaxAmt + 1);
2651 }
2652
2653 // Use computeKnownBits to find a hidden constant/knownbits (usually type
2654 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
2655 KnownBits KnownAmt = getKnownBits(R, DemandedElts, Depth);
2656 if (KnownAmt.getMaxValue().ult(BitWidth))
2657 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
2658
2659 return std::nullopt;
2660}
2661
2663 Register R, const APInt &DemandedElts, unsigned Depth) {
2664 if (std::optional<ConstantRange> AmtRange =
2665 getValidShiftAmountRange(R, DemandedElts, Depth))
2666 return AmtRange->getUnsignedMin().getZExtValue();
2667 return std::nullopt;
2668}
2669
2675
2680
2682 if (!Info) {
2683 unsigned MaxDepth =
2685 Info = std::make_unique<GISelValueTracking>(MF, MaxDepth);
2686 }
2687 return *Info;
2688}
2689
2690AnalysisKey GISelValueTrackingAnalysis::Key;
2691
2695 unsigned MaxDepth =
2697 return Result(MF, MaxDepth);
2698}
2699
2703 auto &VTA = MFAM.getResult<GISelValueTrackingAnalysis>(MF);
2704 const auto &MRI = MF.getRegInfo();
2705 OS << "name: ";
2706 MF.getFunction().printAsOperand(OS, /*PrintType=*/false);
2707 OS << '\n';
2708
2709 for (MachineBasicBlock &BB : MF) {
2710 for (MachineInstr &MI : BB) {
2711 for (MachineOperand &MO : MI.defs()) {
2712 if (!MO.isReg() || MO.getReg().isPhysical())
2713 continue;
2714 Register Reg = MO.getReg();
2715 if (!MRI.getType(Reg).isValid())
2716 continue;
2717 KnownBits Known = VTA.getKnownBits(Reg);
2718 unsigned SignedBits = VTA.computeNumSignBits(Reg);
2719 OS << " " << MO << " KnownBits:" << Known << " SignBits:" << SignedBits
2720 << '\n';
2721 };
2722 }
2723 }
2724 return PreservedAnalyses::all();
2725}
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file declares a class to represent arbitrary precision floating point values and provide a varie...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Utilities for dealing with flags related to floating point properties and mode controls.
static void dumpResult(const MachineInstr &MI, const KnownBits &Known, unsigned Depth)
static unsigned computeNumSignBitsFromRangeMetadata(const GAnyLoad *Ld, unsigned TyBits)
Compute the known number of sign bits with attached range metadata in the memory operand.
Provides analysis for querying information about KnownBits during GISel passes.
#define DEBUG_TYPE
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Implement a low-level type suitable for MachineInstr level instruction selection.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Contains matchers for matching SSA Machine Instructions.
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file describes how to lower LLVM code to machine code.
static bool isAbsoluteValueULEOne(const Value *V)
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
Value * RHS
Value * LHS
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1224
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2006
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1431
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:230
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1191
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1653
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1623
unsigned logBase2() const
Definition APInt.h:1786
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:476
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:880
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:483
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:287
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1230
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
This class represents a range of values.
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
Represents any generic load, including sign/zero extending variants.
const MDNode * getRanges() const
Returns the Ranges that describes the dereference.
Represents an extract vector element.
static LLVM_ABI std::optional< GFConstant > getConstant(Register Const, const MachineRegisterInfo &MRI)
Definition Utils.cpp:2037
To use KnownBitsInfo analysis in a pass, KnownBitsInfo &Info = getAnalysis<GISelValueTrackingInfoAnal...
GISelValueTracking & get(MachineFunction &MF)
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
KnownBits getKnownBits(Register R)
Align computeKnownAlignment(Register R, unsigned Depth=0)
std::optional< ConstantRange > getValidShiftAmountRange(Register R, const APInt &DemandedElts, unsigned Depth)
If a G_SHL/G_ASHR/G_LSHR node with shift operand R has shift amounts that are all less than the eleme...
bool maskedValueIsZero(Register Val, const APInt &Mask)
std::optional< uint64_t > getValidMinimumShiftAmount(Register R, const APInt &DemandedElts, unsigned Depth=0)
If a G_SHL/G_ASHR/G_LSHR node with shift operand R has shift amounts that are all less than the eleme...
const DataLayout & getDataLayout() const
unsigned computeNumSignBits(Register R, const APInt &DemandedElts, unsigned Depth=0)
const MachineFunction & getMachineFunction() const
bool isKnownNeverNaN(Register Val, bool SNaN=false)
Returns true if Val can be assumed to never be a NaN.
void computeKnownBitsImpl(Register R, KnownBits &Known, const APInt &DemandedElts, unsigned Depth=0)
bool isKnownNeverZero(Register R, unsigned Depth=0)
Return true if the value defined by R is provably never zero.
Represents an insert vector element.
Represents a G_LOAD.
Represents a G_SEXTLOAD.
Register getCondReg() const
Register getFalseReg() const
Register getTrueReg() const
ArrayRef< int > getMask() const
Represents a G_ZEXTLOAD.
constexpr bool isScalableVector() const
Returns true if the LLT is a scalable vector.
constexpr unsigned getScalarSizeInBits() const
LLT getScalarType() const
constexpr bool isValid() const
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
constexpr bool isVector() const
constexpr ElementCount getElementCount() const
constexpr bool isFixedVector() const
Returns true if the LLT is a fixed vector.
TypeSize getValue() const
Metadata node.
Definition Metadata.h:1069
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
LLT getMemoryType() const
Return the memory type of the memory reference.
const MDNode * getRanges() const
Return the range tag for the memory reference.
LocationSize getSizeInBits() const
Return the size in bits of the memory reference.
MachineOperand class - Representation of each machine instruction operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
operand_type_match m_Reg()
UnaryOp_match< SrcTy, TargetOpcode::G_FFLOOR > m_GFFloor(const SrcTy &Src)
operand_type_match m_Pred()
bind_ty< FPClassTest > m_FPClassTest(FPClassTest &T)
deferred_ty< Register > m_DeferredReg(Register &R)
Similar to m_SpecificReg/Type, but the specific value to match originated from an earlier sub-pattern...
BinaryOp_match< LHS, RHS, TargetOpcode::G_FSUB, false > m_GFSub(const LHS &L, const RHS &R)
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
ClassifyOp_match< LHS, Test, TargetOpcode::G_IS_FPCLASS > m_GIsFPClass(const LHS &L, const Test &T)
Matches the register and immediate used in a fpclass test G_IS_FPCLASS val, 96.
CompareOp_match< Pred, LHS, RHS, TargetOpcode::G_FCMP > m_GFCmp(const Pred &P, const LHS &L, const RHS &R)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
LLVM_ABI std::optional< APInt > isConstantOrConstantSplatVector(Register Def, const MachineRegisterInfo &MRI)
Determines if Def defines a constant integer or a splat vector of constant integers.
Definition Utils.cpp:1517
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
LLVM_ABI std::optional< APInt > getIConstantVRegVal(Register VReg, const MachineRegisterInfo &MRI)
If VReg is defined by a G_CONSTANT, return the corresponding value.
Definition Utils.cpp:297
@ Known
Known to have no common set bits.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
LLVM_ABI const llvm::fltSemantics & getFltSemanticForLLT(LLT Ty)
Get the appropriate floating point arithmetic semantic based on the bit size of the given scalar LLT.
scope_exit(Callable) -> scope_exit< Callable >
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1674
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:338
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
std::tuple< Value *, FPClassTest, FPClassTest > fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS, FPClassTest RHSClass, bool LookThroughSrc=true)
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
constexpr unsigned MaxAnalysisRecursionDepth
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
DWARFExpression::Operation Op
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
static uint32_t extractBits(uint64_t Val, uint32_t Hi, uint32_t Lo)
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:269
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:165
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
static LLVM_ABI KnownBits abdu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for abdu(LHS, RHS).
bool isEven() const
Return if the value is known even (the low bit is 0).
Definition KnownBits.h:162
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits avgFloorU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorU.
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition KnownBits.h:184
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
Definition KnownBits.h:200
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits abds(KnownBits LHS, KnownBits RHS)
Compute known bits for abds(LHS, RHS).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static LLVM_ABI KnownBits avgFloorS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorS.
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static LLVM_ABI KnownBits computeForAddCarry(const KnownBits &LHS, const KnownBits &RHS, const KnownBits &Carry)
Compute known bits resulting from adding LHS, RHS and a 1-bit Carry.
Definition KnownBits.cpp:54
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
static LLVM_ABI KnownBits avgCeilU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilU.
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
bool isAllOnes() const
Returns true if value is all one bits.
Definition KnownBits.h:81
static LLVM_ABI KnownBits avgCeilS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilS.
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
bool isKnownNeverInfinity() const
Return true if it's known this can never be an infinity.
bool cannotBeOrderedGreaterThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never greater tha...
static LLVM_ABI KnownFPClass sin(const KnownFPClass &Src)
Report known values for sin.
static LLVM_ABI KnownFPClass fdiv_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv x, x.
static constexpr FPClassTest OrderedGreaterThanZeroMask
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass atan2(const KnownFPClass &LHS, const KnownFPClass &RHS)
Report known values for atan2.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsTrunc, bool IsMultiUnitFPType)
Propagate known class for rounding intrinsics (trunc, floor, ceil, rint, nearbyint,...
static LLVM_ABI KnownFPClass cos(const KnownFPClass &Src)
Report known values for cos.
static LLVM_ABI KnownFPClass cosh(const KnownFPClass &Src)
Report known values for cosh.
static LLVM_ABI KnownFPClass minMaxLike(const KnownFPClass &LHS, const KnownFPClass &RHS, MinMaxKind Kind, DenormalMode DenormMode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
static LLVM_ABI KnownFPClass asin(const KnownFPClass &Src)
Report known values for asin.
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy)
Propagate known class for fpext.
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass tan(const KnownFPClass &Src)
Report known values for tan.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc)
Propagate known class for fptrunc.
bool cannotBeOrderedLessThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never less than -...
static LLVM_ABI KnownFPClass sqrt(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for sqrt.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass acos(const KnownFPClass &Src)
Report known values for acos.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
static LLVM_ABI KnownFPClass sinh(const KnownFPClass &Src)
Report known values for sinh.
static LLVM_ABI KnownFPClass tanh(const KnownFPClass &Src)
Report known values for tanh.