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