1 //===- lib/CodeGen/GlobalISel/GISelKnownBits.cpp --------------*- C++ *-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// Provides analysis for querying information about KnownBits during GISel
10 /// passes.
11 //
12 //===------------------
13 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
14 #include "llvm/Analysis/ValueTracking.h"
15 #include "llvm/CodeGen/GlobalISel/Utils.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/TargetLowering.h"
19 #include "llvm/CodeGen/TargetOpcodes.h"
20 
21 #define DEBUG_TYPE "gisel-known-bits"
22 
23 using namespace llvm;
24 
25 char llvm::GISelKnownBitsAnalysis::ID = 0;
26 
27 INITIALIZE_PASS(GISelKnownBitsAnalysis, DEBUG_TYPE,
28                 "Analysis for ComputingKnownBits", false, true)
29 
30 GISelKnownBits::GISelKnownBits(MachineFunction &MF, unsigned MaxDepth)
31     : MF(MF), MRI(MF.getRegInfo()), TL(*MF.getSubtarget().getTargetLowering()),
32       DL(MF.getFunction().getParent()->getDataLayout()), MaxDepth(MaxDepth) {}
33 
34 Align GISelKnownBits::inferAlignmentForFrameIdx(int FrameIdx, int Offset,
35                                                 const MachineFunction &MF) {
36   const MachineFrameInfo &MFI = MF.getFrameInfo();
37   return commonAlignment(MFI.getObjectAlign(FrameIdx), Offset);
38   // TODO: How to handle cases with Base + Offset?
39 }
40 
41 MaybeAlign GISelKnownBits::inferPtrAlignment(const MachineInstr &MI) {
42   if (MI.getOpcode() == TargetOpcode::G_FRAME_INDEX) {
43     int FrameIdx = MI.getOperand(1).getIndex();
44     return inferAlignmentForFrameIdx(FrameIdx, 0, *MI.getMF());
45   }
46   return None;
47 }
48 
49 void GISelKnownBits::computeKnownBitsForFrameIndex(Register R, KnownBits &Known,
50                                                    const APInt &DemandedElts,
51                                                    unsigned Depth) {
52   const MachineInstr &MI = *MRI.getVRegDef(R);
53   computeKnownBitsForAlignment(Known, inferPtrAlignment(MI));
54 }
55 
56 void GISelKnownBits::computeKnownBitsForAlignment(KnownBits &Known,
57                                                   MaybeAlign Alignment) {
58   if (Alignment)
59     // The low bits are known zero if the pointer is aligned.
60     Known.Zero.setLowBits(Log2(Alignment));
61 }
62 
63 KnownBits GISelKnownBits::getKnownBits(MachineInstr &MI) {
64   return getKnownBits(MI.getOperand(0).getReg());
65 }
66 
67 KnownBits GISelKnownBits::getKnownBits(Register R) {
68   const LLT Ty = MRI.getType(R);
69   APInt DemandedElts =
70       Ty.isVector() ? APInt::getAllOnesValue(Ty.getNumElements()) : APInt(1, 1);
71   return getKnownBits(R, DemandedElts);
72 }
73 
74 KnownBits GISelKnownBits::getKnownBits(Register R, const APInt &DemandedElts,
75                                        unsigned Depth) {
76   // For now, we only maintain the cache during one request.
77   assert(ComputeKnownBitsCache.empty() && "Cache should have been cleared");
78 
79   KnownBits Known;
80   computeKnownBitsImpl(R, Known, DemandedElts);
81   ComputeKnownBitsCache.clear();
82   return Known;
83 }
84 
85 bool GISelKnownBits::signBitIsZero(Register R) {
86   LLT Ty = MRI.getType(R);
87   unsigned BitWidth = Ty.getScalarSizeInBits();
88   return maskedValueIsZero(R, APInt::getSignMask(BitWidth));
89 }
90 
91 APInt GISelKnownBits::getKnownZeroes(Register R) {
92   return getKnownBits(R).Zero;
93 }
94 
95 APInt GISelKnownBits::getKnownOnes(Register R) { return getKnownBits(R).One; }
96 
97 LLVM_ATTRIBUTE_UNUSED static void
98 dumpResult(const MachineInstr &MI, const KnownBits &Known, unsigned Depth) {
99   dbgs() << "[" << Depth << "] Compute known bits: " << MI << "[" << Depth
100          << "] Computed for: " << MI << "[" << Depth << "] Known: 0x"
101          << (Known.Zero | Known.One).toString(16, false) << "\n"
102          << "[" << Depth << "] Zero: 0x" << Known.Zero.toString(16, false)
103          << "\n"
104          << "[" << Depth << "] One:  0x" << Known.One.toString(16, false)
105          << "\n";
106 }
107 
108 void GISelKnownBits::computeKnownBitsImpl(Register R, KnownBits &Known,
109                                           const APInt &DemandedElts,
110                                           unsigned Depth) {
111   MachineInstr &MI = *MRI.getVRegDef(R);
112   unsigned Opcode = MI.getOpcode();
113   LLT DstTy = MRI.getType(R);
114 
115   // Handle the case where this is called on a register that does not have a
116   // type constraint (i.e. it has a register class constraint instead). This is
117   // unlikely to occur except by looking through copies but it is possible for
118   // the initial register being queried to be in this state.
119   if (!DstTy.isValid()) {
120     Known = KnownBits();
121     return;
122   }
123 
124   unsigned BitWidth = DstTy.getSizeInBits();
125   auto CacheEntry = ComputeKnownBitsCache.find(R);
126   if (CacheEntry != ComputeKnownBitsCache.end()) {
127     Known = CacheEntry->second;
128     LLVM_DEBUG(dbgs() << "Cache hit at ");
129     LLVM_DEBUG(dumpResult(MI, Known, Depth));
130     assert(Known.getBitWidth() == BitWidth && "Cache entry size doesn't match");
131     return;
132   }
133   Known = KnownBits(BitWidth); // Don't know anything
134 
135   if (DstTy.isVector())
136     return; // TODO: Handle vectors.
137 
138   // Depth may get bigger than max depth if it gets passed to a different
139   // GISelKnownBits object.
140   // This may happen when say a generic part uses a GISelKnownBits object
141   // with some max depth, but then we hit TL.computeKnownBitsForTargetInstr
142   // which creates a new GISelKnownBits object with a different and smaller
143   // depth. If we just check for equality, we would never exit if the depth
144   // that is passed down to the target specific GISelKnownBits object is
145   // already bigger than its max depth.
146   if (Depth >= getMaxDepth())
147     return;
148 
149   if (!DemandedElts)
150     return; // No demanded elts, better to assume we don't know anything.
151 
152   KnownBits Known2;
153 
154   switch (Opcode) {
155   default:
156     TL.computeKnownBitsForTargetInstr(*this, R, Known, DemandedElts, MRI,
157                                       Depth);
158     break;
159   case TargetOpcode::COPY:
160   case TargetOpcode::G_PHI:
161   case TargetOpcode::PHI: {
162     Known.One = APInt::getAllOnesValue(BitWidth);
163     Known.Zero = APInt::getAllOnesValue(BitWidth);
164     // Destination registers should not have subregisters at this
165     // point of the pipeline, otherwise the main live-range will be
166     // defined more than once, which is against SSA.
167     assert(MI.getOperand(0).getSubReg() == 0 && "Is this code in SSA?");
168     // Record in the cache that we know nothing for MI.
169     // This will get updated later and in the meantime, if we reach that
170     // phi again, because of a loop, we will cut the search thanks to this
171     // cache entry.
172     // We could actually build up more information on the phi by not cutting
173     // the search, but that additional information is more a side effect
174     // than an intended choice.
175     // Therefore, for now, save on compile time until we derive a proper way
176     // to derive known bits for PHIs within loops.
177     ComputeKnownBitsCache[R] = KnownBits(BitWidth);
178     // PHI's operand are a mix of registers and basic blocks interleaved.
179     // We only care about the register ones.
180     for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
181       const MachineOperand &Src = MI.getOperand(Idx);
182       Register SrcReg = Src.getReg();
183       // Look through trivial copies and phis but don't look through trivial
184       // copies or phis of the form `%1:(s32) = OP %0:gpr32`, known-bits
185       // analysis is currently unable to determine the bit width of a
186       // register class.
187       //
188       // We can't use NoSubRegister by name as it's defined by each target but
189       // it's always defined to be 0 by tablegen.
190       if (SrcReg.isVirtual() && Src.getSubReg() == 0 /*NoSubRegister*/ &&
191           MRI.getType(SrcReg).isValid()) {
192         // For COPYs we don't do anything, don't increase the depth.
193         computeKnownBitsImpl(SrcReg, Known2, DemandedElts,
194                              Depth + (Opcode != TargetOpcode::COPY));
195         Known.One &= Known2.One;
196         Known.Zero &= Known2.Zero;
197         // If we reach a point where we don't know anything
198         // just stop looking through the operands.
199         if (Known.One == 0 && Known.Zero == 0)
200           break;
201       } else {
202         // We know nothing.
203         Known = KnownBits(BitWidth);
204         break;
205       }
206     }
207     break;
208   }
209   case TargetOpcode::G_CONSTANT: {
210     auto CstVal = getConstantVRegVal(R, MRI);
211     if (!CstVal)
212       break;
213     Known.One = *CstVal;
214     Known.Zero = ~Known.One;
215     break;
216   }
217   case TargetOpcode::G_FRAME_INDEX: {
218     computeKnownBitsForFrameIndex(R, Known, DemandedElts);
219     break;
220   }
221   case TargetOpcode::G_SUB: {
222     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
223                          Depth + 1);
224     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
225                          Depth + 1);
226     Known = KnownBits::computeForAddSub(/*Add*/ false, /*NSW*/ false, Known,
227                                         Known2);
228     break;
229   }
230   case TargetOpcode::G_XOR: {
231     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
232                          Depth + 1);
233     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
234                          Depth + 1);
235 
236     // Output known-0 bits are known if clear or set in both the LHS & RHS.
237     APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
238     // Output known-1 are known to be set if set in only one of the LHS, RHS.
239     Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
240     Known.Zero = KnownZeroOut;
241     break;
242   }
243   case TargetOpcode::G_PTR_ADD: {
244     // G_PTR_ADD is like G_ADD. FIXME: Is this true for all targets?
245     LLT Ty = MRI.getType(MI.getOperand(1).getReg());
246     if (DL.isNonIntegralAddressSpace(Ty.getAddressSpace()))
247       break;
248     LLVM_FALLTHROUGH;
249   }
250   case TargetOpcode::G_ADD: {
251     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
252                          Depth + 1);
253     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
254                          Depth + 1);
255     Known =
256         KnownBits::computeForAddSub(/*Add*/ true, /*NSW*/ false, Known, Known2);
257     break;
258   }
259   case TargetOpcode::G_AND: {
260     // If either the LHS or the RHS are Zero, the result is zero.
261     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
262                          Depth + 1);
263     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
264                          Depth + 1);
265 
266     // Output known-1 bits are only known if set in both the LHS & RHS.
267     Known.One &= Known2.One;
268     // Output known-0 are known to be clear if zero in either the LHS | RHS.
269     Known.Zero |= Known2.Zero;
270     break;
271   }
272   case TargetOpcode::G_OR: {
273     // If either the LHS or the RHS are Zero, the result is zero.
274     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
275                          Depth + 1);
276     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
277                          Depth + 1);
278 
279     // Output known-0 bits are only known if clear in both the LHS & RHS.
280     Known.Zero &= Known2.Zero;
281     // Output known-1 are known to be set if set in either the LHS | RHS.
282     Known.One |= Known2.One;
283     break;
284   }
285   case TargetOpcode::G_MUL: {
286     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
287                          Depth + 1);
288     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
289                          Depth + 1);
290     // If low bits are zero in either operand, output low known-0 bits.
291     // Also compute a conservative estimate for high known-0 bits.
292     // More trickiness is possible, but this is sufficient for the
293     // interesting case of alignment computation.
294     unsigned TrailZ =
295         Known.countMinTrailingZeros() + Known2.countMinTrailingZeros();
296     unsigned LeadZ =
297         std::max(Known.countMinLeadingZeros() + Known2.countMinLeadingZeros(),
298                  BitWidth) -
299         BitWidth;
300 
301     Known.resetAll();
302     Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
303     Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
304     break;
305   }
306   case TargetOpcode::G_SELECT: {
307     computeKnownBitsImpl(MI.getOperand(3).getReg(), Known, DemandedElts,
308                          Depth + 1);
309     // If we don't know any bits, early out.
310     if (Known.isUnknown())
311       break;
312     computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
313                          Depth + 1);
314     // Only known if known in both the LHS and RHS.
315     Known.One &= Known2.One;
316     Known.Zero &= Known2.Zero;
317     break;
318   }
319   case TargetOpcode::G_FCMP:
320   case TargetOpcode::G_ICMP: {
321     if (TL.getBooleanContents(DstTy.isVector(),
322                               Opcode == TargetOpcode::G_FCMP) ==
323             TargetLowering::ZeroOrOneBooleanContent &&
324         BitWidth > 1)
325       Known.Zero.setBitsFrom(1);
326     break;
327   }
328   case TargetOpcode::G_SEXT: {
329     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
330                          Depth + 1);
331     // If the sign bit is known to be zero or one, then sext will extend
332     // it to the top bits, else it will just zext.
333     Known = Known.sext(BitWidth);
334     break;
335   }
336   case TargetOpcode::G_ANYEXT: {
337     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
338                          Depth + 1);
339     Known = Known.zext(BitWidth);
340     break;
341   }
342   case TargetOpcode::G_LOAD: {
343     if (MI.hasOneMemOperand()) {
344       const MachineMemOperand *MMO = *MI.memoperands_begin();
345       if (const MDNode *Ranges = MMO->getRanges()) {
346         computeKnownBitsFromRangeMetadata(*Ranges, Known);
347       }
348     }
349     break;
350   }
351   case TargetOpcode::G_ZEXTLOAD: {
352     // Everything above the retrieved bits is zero
353     if (MI.hasOneMemOperand())
354       Known.Zero.setBitsFrom((*MI.memoperands_begin())->getSizeInBits());
355     break;
356   }
357   case TargetOpcode::G_ASHR:
358   case TargetOpcode::G_LSHR:
359   case TargetOpcode::G_SHL: {
360     KnownBits RHSKnown;
361     computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
362                          Depth + 1);
363     if (!RHSKnown.isConstant()) {
364       LLVM_DEBUG(
365           MachineInstr *RHSMI = MRI.getVRegDef(MI.getOperand(2).getReg());
366           dbgs() << '[' << Depth << "] Shift not known constant: " << *RHSMI);
367       break;
368     }
369     uint64_t Shift = RHSKnown.getConstant().getZExtValue();
370     LLVM_DEBUG(dbgs() << '[' << Depth << "] Shift is " << Shift << '\n');
371 
372     computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
373                          Depth + 1);
374 
375     switch (Opcode) {
376     case TargetOpcode::G_ASHR:
377       Known.Zero = Known.Zero.ashr(Shift);
378       Known.One = Known.One.ashr(Shift);
379       break;
380     case TargetOpcode::G_LSHR:
381       Known.Zero = Known.Zero.lshr(Shift);
382       Known.One = Known.One.lshr(Shift);
383       Known.Zero.setBitsFrom(Known.Zero.getBitWidth() - Shift);
384       break;
385     case TargetOpcode::G_SHL:
386       Known.Zero = Known.Zero.shl(Shift);
387       Known.One = Known.One.shl(Shift);
388       Known.Zero.setBits(0, Shift);
389       break;
390     }
391     break;
392   }
393   case TargetOpcode::G_INTTOPTR:
394   case TargetOpcode::G_PTRTOINT:
395     // Fall through and handle them the same as zext/trunc.
396     LLVM_FALLTHROUGH;
397   case TargetOpcode::G_ZEXT:
398   case TargetOpcode::G_TRUNC: {
399     Register SrcReg = MI.getOperand(1).getReg();
400     LLT SrcTy = MRI.getType(SrcReg);
401     unsigned SrcBitWidth = SrcTy.isPointer()
402                                ? DL.getIndexSizeInBits(SrcTy.getAddressSpace())
403                                : SrcTy.getSizeInBits();
404     assert(SrcBitWidth && "SrcBitWidth can't be zero");
405     Known = Known.zextOrTrunc(SrcBitWidth);
406     computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
407     Known = Known.zextOrTrunc(BitWidth);
408     if (BitWidth > SrcBitWidth)
409       Known.Zero.setBitsFrom(SrcBitWidth);
410     break;
411   }
412   }
413 
414   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
415   LLVM_DEBUG(dumpResult(MI, Known, Depth));
416 
417   // Update the cache.
418   ComputeKnownBitsCache[R] = Known;
419 }
420 
421 unsigned GISelKnownBits::computeNumSignBits(Register R,
422                                             const APInt &DemandedElts,
423                                             unsigned Depth) {
424   MachineInstr &MI = *MRI.getVRegDef(R);
425   unsigned Opcode = MI.getOpcode();
426 
427   if (Opcode == TargetOpcode::G_CONSTANT)
428     return MI.getOperand(1).getCImm()->getValue().getNumSignBits();
429 
430   if (Depth == getMaxDepth())
431     return 1;
432 
433   if (!DemandedElts)
434     return 1; // No demanded elts, better to assume we don't know anything.
435 
436   LLT DstTy = MRI.getType(R);
437   const unsigned TyBits = DstTy.getScalarSizeInBits();
438 
439   // Handle the case where this is called on a register that does not have a
440   // type constraint. This is unlikely to occur except by looking through copies
441   // but it is possible for the initial register being queried to be in this
442   // state.
443   if (!DstTy.isValid())
444     return 1;
445 
446   unsigned FirstAnswer = 1;
447   switch (Opcode) {
448   case TargetOpcode::COPY: {
449     MachineOperand &Src = MI.getOperand(1);
450     if (Src.getReg().isVirtual() && Src.getSubReg() == 0 &&
451         MRI.getType(Src.getReg()).isValid()) {
452       // Don't increment Depth for this one since we didn't do any work.
453       return computeNumSignBits(Src.getReg(), DemandedElts, Depth);
454     }
455 
456     return 1;
457   }
458   case TargetOpcode::G_SEXT: {
459     Register Src = MI.getOperand(1).getReg();
460     LLT SrcTy = MRI.getType(Src);
461     unsigned Tmp = DstTy.getScalarSizeInBits() - SrcTy.getScalarSizeInBits();
462     return computeNumSignBits(Src, DemandedElts, Depth + 1) + Tmp;
463   }
464   case TargetOpcode::G_TRUNC: {
465     Register Src = MI.getOperand(1).getReg();
466     LLT SrcTy = MRI.getType(Src);
467 
468     // Check if the sign bits of source go down as far as the truncated value.
469     unsigned DstTyBits = DstTy.getScalarSizeInBits();
470     unsigned NumSrcBits = SrcTy.getScalarSizeInBits();
471     unsigned NumSrcSignBits = computeNumSignBits(Src, DemandedElts, Depth + 1);
472     if (NumSrcSignBits > (NumSrcBits - DstTyBits))
473       return NumSrcSignBits - (NumSrcBits - DstTyBits);
474     break;
475   }
476   case TargetOpcode::G_INTRINSIC:
477   case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
478   default: {
479     unsigned NumBits =
480       TL.computeNumSignBitsForTargetInstr(*this, R, DemandedElts, MRI, Depth);
481     if (NumBits > 1)
482       FirstAnswer = std::max(FirstAnswer, NumBits);
483     break;
484   }
485   }
486 
487   // Finally, if we can prove that the top bits of the result are 0's or 1's,
488   // use this information.
489   KnownBits Known = getKnownBits(R, DemandedElts, Depth);
490   APInt Mask;
491   if (Known.isNonNegative()) {        // sign bit is 0
492     Mask = Known.Zero;
493   } else if (Known.isNegative()) {  // sign bit is 1;
494     Mask = Known.One;
495   } else {
496     // Nothing known.
497     return FirstAnswer;
498   }
499 
500   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
501   // the number of identical bits in the top of the input value.
502   Mask <<= Mask.getBitWidth() - TyBits;
503   return std::max(FirstAnswer, Mask.countLeadingOnes());
504 }
505 
506 unsigned GISelKnownBits::computeNumSignBits(Register R, unsigned Depth) {
507   LLT Ty = MRI.getType(R);
508   APInt DemandedElts = Ty.isVector()
509                            ? APInt::getAllOnesValue(Ty.getNumElements())
510                            : APInt(1, 1);
511   return computeNumSignBits(R, DemandedElts, Depth);
512 }
513 
514 void GISelKnownBitsAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
515   AU.setPreservesAll();
516   MachineFunctionPass::getAnalysisUsage(AU);
517 }
518 
519 bool GISelKnownBitsAnalysis::runOnMachineFunction(MachineFunction &MF) {
520   return false;
521 }
522