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