xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/Utils.cpp (revision cb14a3fe5122c879eae1fb480ed7ce82a699ddb6)
1 //===- llvm/CodeGen/GlobalISel/Utils.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 /// \file This file implements the utility functions used by the GlobalISel
9 /// pipeline.
10 //===----------------------------------------------------------------------===//
11 
12 #include "llvm/CodeGen/GlobalISel/Utils.h"
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/CodeGen/CodeGenCommonISel.h"
16 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
17 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
18 #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
19 #include "llvm/CodeGen/GlobalISel/LostDebugLocObserver.h"
20 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/MachineSizeOpts.h"
26 #include "llvm/CodeGen/RegisterBankInfo.h"
27 #include "llvm/CodeGen/StackProtector.h"
28 #include "llvm/CodeGen/TargetInstrInfo.h"
29 #include "llvm/CodeGen/TargetLowering.h"
30 #include "llvm/CodeGen/TargetPassConfig.h"
31 #include "llvm/CodeGen/TargetRegisterInfo.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Transforms/Utils/SizeOpts.h"
35 #include <numeric>
36 #include <optional>
37 
38 #define DEBUG_TYPE "globalisel-utils"
39 
40 using namespace llvm;
41 using namespace MIPatternMatch;
42 
43 Register llvm::constrainRegToClass(MachineRegisterInfo &MRI,
44                                    const TargetInstrInfo &TII,
45                                    const RegisterBankInfo &RBI, Register Reg,
46                                    const TargetRegisterClass &RegClass) {
47   if (!RBI.constrainGenericRegister(Reg, RegClass, MRI))
48     return MRI.createVirtualRegister(&RegClass);
49 
50   return Reg;
51 }
52 
53 Register llvm::constrainOperandRegClass(
54     const MachineFunction &MF, const TargetRegisterInfo &TRI,
55     MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
56     const RegisterBankInfo &RBI, MachineInstr &InsertPt,
57     const TargetRegisterClass &RegClass, MachineOperand &RegMO) {
58   Register Reg = RegMO.getReg();
59   // Assume physical registers are properly constrained.
60   assert(Reg.isVirtual() && "PhysReg not implemented");
61 
62   // Save the old register class to check whether
63   // the change notifications will be required.
64   // TODO: A better approach would be to pass
65   // the observers to constrainRegToClass().
66   auto *OldRegClass = MRI.getRegClassOrNull(Reg);
67   Register ConstrainedReg = constrainRegToClass(MRI, TII, RBI, Reg, RegClass);
68   // If we created a new virtual register because the class is not compatible
69   // then create a copy between the new and the old register.
70   if (ConstrainedReg != Reg) {
71     MachineBasicBlock::iterator InsertIt(&InsertPt);
72     MachineBasicBlock &MBB = *InsertPt.getParent();
73     // FIXME: The copy needs to have the classes constrained for its operands.
74     // Use operand's regbank to get the class for old register (Reg).
75     if (RegMO.isUse()) {
76       BuildMI(MBB, InsertIt, InsertPt.getDebugLoc(),
77               TII.get(TargetOpcode::COPY), ConstrainedReg)
78           .addReg(Reg);
79     } else {
80       assert(RegMO.isDef() && "Must be a definition");
81       BuildMI(MBB, std::next(InsertIt), InsertPt.getDebugLoc(),
82               TII.get(TargetOpcode::COPY), Reg)
83           .addReg(ConstrainedReg);
84     }
85     if (GISelChangeObserver *Observer = MF.getObserver()) {
86       Observer->changingInstr(*RegMO.getParent());
87     }
88     RegMO.setReg(ConstrainedReg);
89     if (GISelChangeObserver *Observer = MF.getObserver()) {
90       Observer->changedInstr(*RegMO.getParent());
91     }
92   } else if (OldRegClass != MRI.getRegClassOrNull(Reg)) {
93     if (GISelChangeObserver *Observer = MF.getObserver()) {
94       if (!RegMO.isDef()) {
95         MachineInstr *RegDef = MRI.getVRegDef(Reg);
96         Observer->changedInstr(*RegDef);
97       }
98       Observer->changingAllUsesOfReg(MRI, Reg);
99       Observer->finishedChangingAllUsesOfReg();
100     }
101   }
102   return ConstrainedReg;
103 }
104 
105 Register llvm::constrainOperandRegClass(
106     const MachineFunction &MF, const TargetRegisterInfo &TRI,
107     MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
108     const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II,
109     MachineOperand &RegMO, unsigned OpIdx) {
110   Register Reg = RegMO.getReg();
111   // Assume physical registers are properly constrained.
112   assert(Reg.isVirtual() && "PhysReg not implemented");
113 
114   const TargetRegisterClass *OpRC = TII.getRegClass(II, OpIdx, &TRI, MF);
115   // Some of the target independent instructions, like COPY, may not impose any
116   // register class constraints on some of their operands: If it's a use, we can
117   // skip constraining as the instruction defining the register would constrain
118   // it.
119 
120   if (OpRC) {
121     // Obtain the RC from incoming regbank if it is a proper sub-class. Operands
122     // can have multiple regbanks for a superclass that combine different
123     // register types (E.g., AMDGPU's VGPR and AGPR). The regbank ambiguity
124     // resolved by targets during regbankselect should not be overridden.
125     if (const auto *SubRC = TRI.getCommonSubClass(
126             OpRC, TRI.getConstrainedRegClassForOperand(RegMO, MRI)))
127       OpRC = SubRC;
128 
129     OpRC = TRI.getAllocatableClass(OpRC);
130   }
131 
132   if (!OpRC) {
133     assert((!isTargetSpecificOpcode(II.getOpcode()) || RegMO.isUse()) &&
134            "Register class constraint is required unless either the "
135            "instruction is target independent or the operand is a use");
136     // FIXME: Just bailing out like this here could be not enough, unless we
137     // expect the users of this function to do the right thing for PHIs and
138     // COPY:
139     //   v1 = COPY v0
140     //   v2 = COPY v1
141     // v1 here may end up not being constrained at all. Please notice that to
142     // reproduce the issue we likely need a destination pattern of a selection
143     // rule producing such extra copies, not just an input GMIR with them as
144     // every existing target using selectImpl handles copies before calling it
145     // and they never reach this function.
146     return Reg;
147   }
148   return constrainOperandRegClass(MF, TRI, MRI, TII, RBI, InsertPt, *OpRC,
149                                   RegMO);
150 }
151 
152 bool llvm::constrainSelectedInstRegOperands(MachineInstr &I,
153                                             const TargetInstrInfo &TII,
154                                             const TargetRegisterInfo &TRI,
155                                             const RegisterBankInfo &RBI) {
156   assert(!isPreISelGenericOpcode(I.getOpcode()) &&
157          "A selected instruction is expected");
158   MachineBasicBlock &MBB = *I.getParent();
159   MachineFunction &MF = *MBB.getParent();
160   MachineRegisterInfo &MRI = MF.getRegInfo();
161 
162   for (unsigned OpI = 0, OpE = I.getNumExplicitOperands(); OpI != OpE; ++OpI) {
163     MachineOperand &MO = I.getOperand(OpI);
164 
165     // There's nothing to be done on non-register operands.
166     if (!MO.isReg())
167       continue;
168 
169     LLVM_DEBUG(dbgs() << "Converting operand: " << MO << '\n');
170     assert(MO.isReg() && "Unsupported non-reg operand");
171 
172     Register Reg = MO.getReg();
173     // Physical registers don't need to be constrained.
174     if (Reg.isPhysical())
175       continue;
176 
177     // Register operands with a value of 0 (e.g. predicate operands) don't need
178     // to be constrained.
179     if (Reg == 0)
180       continue;
181 
182     // If the operand is a vreg, we should constrain its regclass, and only
183     // insert COPYs if that's impossible.
184     // constrainOperandRegClass does that for us.
185     constrainOperandRegClass(MF, TRI, MRI, TII, RBI, I, I.getDesc(), MO, OpI);
186 
187     // Tie uses to defs as indicated in MCInstrDesc if this hasn't already been
188     // done.
189     if (MO.isUse()) {
190       int DefIdx = I.getDesc().getOperandConstraint(OpI, MCOI::TIED_TO);
191       if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefIdx))
192         I.tieOperands(DefIdx, OpI);
193     }
194   }
195   return true;
196 }
197 
198 bool llvm::canReplaceReg(Register DstReg, Register SrcReg,
199                          MachineRegisterInfo &MRI) {
200   // Give up if either DstReg or SrcReg  is a physical register.
201   if (DstReg.isPhysical() || SrcReg.isPhysical())
202     return false;
203   // Give up if the types don't match.
204   if (MRI.getType(DstReg) != MRI.getType(SrcReg))
205     return false;
206   // Replace if either DstReg has no constraints or the register
207   // constraints match.
208   const auto &DstRBC = MRI.getRegClassOrRegBank(DstReg);
209   if (!DstRBC || DstRBC == MRI.getRegClassOrRegBank(SrcReg))
210     return true;
211 
212   // Otherwise match if the Src is already a regclass that is covered by the Dst
213   // RegBank.
214   return DstRBC.is<const RegisterBank *>() && MRI.getRegClassOrNull(SrcReg) &&
215          DstRBC.get<const RegisterBank *>()->covers(
216              *MRI.getRegClassOrNull(SrcReg));
217 }
218 
219 bool llvm::isTriviallyDead(const MachineInstr &MI,
220                            const MachineRegisterInfo &MRI) {
221   // FIXME: This logical is mostly duplicated with
222   // DeadMachineInstructionElim::isDead. Why is LOCAL_ESCAPE not considered in
223   // MachineInstr::isLabel?
224 
225   // Don't delete frame allocation labels.
226   if (MI.getOpcode() == TargetOpcode::LOCAL_ESCAPE)
227     return false;
228   // LIFETIME markers should be preserved even if they seem dead.
229   if (MI.getOpcode() == TargetOpcode::LIFETIME_START ||
230       MI.getOpcode() == TargetOpcode::LIFETIME_END)
231     return false;
232 
233   // If we can move an instruction, we can remove it.  Otherwise, it has
234   // a side-effect of some sort.
235   bool SawStore = false;
236   if (!MI.isSafeToMove(/*AA=*/nullptr, SawStore) && !MI.isPHI())
237     return false;
238 
239   // Instructions without side-effects are dead iff they only define dead vregs.
240   for (const auto &MO : MI.all_defs()) {
241     Register Reg = MO.getReg();
242     if (Reg.isPhysical() || !MRI.use_nodbg_empty(Reg))
243       return false;
244   }
245   return true;
246 }
247 
248 static void reportGISelDiagnostic(DiagnosticSeverity Severity,
249                                   MachineFunction &MF,
250                                   const TargetPassConfig &TPC,
251                                   MachineOptimizationRemarkEmitter &MORE,
252                                   MachineOptimizationRemarkMissed &R) {
253   bool IsFatal = Severity == DS_Error &&
254                  TPC.isGlobalISelAbortEnabled();
255   // Print the function name explicitly if we don't have a debug location (which
256   // makes the diagnostic less useful) or if we're going to emit a raw error.
257   if (!R.getLocation().isValid() || IsFatal)
258     R << (" (in function: " + MF.getName() + ")").str();
259 
260   if (IsFatal)
261     report_fatal_error(Twine(R.getMsg()));
262   else
263     MORE.emit(R);
264 }
265 
266 void llvm::reportGISelWarning(MachineFunction &MF, const TargetPassConfig &TPC,
267                               MachineOptimizationRemarkEmitter &MORE,
268                               MachineOptimizationRemarkMissed &R) {
269   reportGISelDiagnostic(DS_Warning, MF, TPC, MORE, R);
270 }
271 
272 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC,
273                               MachineOptimizationRemarkEmitter &MORE,
274                               MachineOptimizationRemarkMissed &R) {
275   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
276   reportGISelDiagnostic(DS_Error, MF, TPC, MORE, R);
277 }
278 
279 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC,
280                               MachineOptimizationRemarkEmitter &MORE,
281                               const char *PassName, StringRef Msg,
282                               const MachineInstr &MI) {
283   MachineOptimizationRemarkMissed R(PassName, "GISelFailure: ",
284                                     MI.getDebugLoc(), MI.getParent());
285   R << Msg;
286   // Printing MI is expensive;  only do it if expensive remarks are enabled.
287   if (TPC.isGlobalISelAbortEnabled() || MORE.allowExtraAnalysis(PassName))
288     R << ": " << ore::MNV("Inst", MI);
289   reportGISelFailure(MF, TPC, MORE, R);
290 }
291 
292 std::optional<APInt> llvm::getIConstantVRegVal(Register VReg,
293                                                const MachineRegisterInfo &MRI) {
294   std::optional<ValueAndVReg> ValAndVReg = getIConstantVRegValWithLookThrough(
295       VReg, MRI, /*LookThroughInstrs*/ false);
296   assert((!ValAndVReg || ValAndVReg->VReg == VReg) &&
297          "Value found while looking through instrs");
298   if (!ValAndVReg)
299     return std::nullopt;
300   return ValAndVReg->Value;
301 }
302 
303 std::optional<int64_t>
304 llvm::getIConstantVRegSExtVal(Register VReg, const MachineRegisterInfo &MRI) {
305   std::optional<APInt> Val = getIConstantVRegVal(VReg, MRI);
306   if (Val && Val->getBitWidth() <= 64)
307     return Val->getSExtValue();
308   return std::nullopt;
309 }
310 
311 namespace {
312 
313 typedef std::function<bool(const MachineInstr *)> IsOpcodeFn;
314 typedef std::function<std::optional<APInt>(const MachineInstr *MI)> GetAPCstFn;
315 
316 std::optional<ValueAndVReg> getConstantVRegValWithLookThrough(
317     Register VReg, const MachineRegisterInfo &MRI, IsOpcodeFn IsConstantOpcode,
318     GetAPCstFn getAPCstValue, bool LookThroughInstrs = true,
319     bool LookThroughAnyExt = false) {
320   SmallVector<std::pair<unsigned, unsigned>, 4> SeenOpcodes;
321   MachineInstr *MI;
322 
323   while ((MI = MRI.getVRegDef(VReg)) && !IsConstantOpcode(MI) &&
324          LookThroughInstrs) {
325     switch (MI->getOpcode()) {
326     case TargetOpcode::G_ANYEXT:
327       if (!LookThroughAnyExt)
328         return std::nullopt;
329       [[fallthrough]];
330     case TargetOpcode::G_TRUNC:
331     case TargetOpcode::G_SEXT:
332     case TargetOpcode::G_ZEXT:
333       SeenOpcodes.push_back(std::make_pair(
334           MI->getOpcode(),
335           MRI.getType(MI->getOperand(0).getReg()).getSizeInBits()));
336       VReg = MI->getOperand(1).getReg();
337       break;
338     case TargetOpcode::COPY:
339       VReg = MI->getOperand(1).getReg();
340       if (VReg.isPhysical())
341         return std::nullopt;
342       break;
343     case TargetOpcode::G_INTTOPTR:
344       VReg = MI->getOperand(1).getReg();
345       break;
346     default:
347       return std::nullopt;
348     }
349   }
350   if (!MI || !IsConstantOpcode(MI))
351     return std::nullopt;
352 
353   std::optional<APInt> MaybeVal = getAPCstValue(MI);
354   if (!MaybeVal)
355     return std::nullopt;
356   APInt &Val = *MaybeVal;
357   while (!SeenOpcodes.empty()) {
358     std::pair<unsigned, unsigned> OpcodeAndSize = SeenOpcodes.pop_back_val();
359     switch (OpcodeAndSize.first) {
360     case TargetOpcode::G_TRUNC:
361       Val = Val.trunc(OpcodeAndSize.second);
362       break;
363     case TargetOpcode::G_ANYEXT:
364     case TargetOpcode::G_SEXT:
365       Val = Val.sext(OpcodeAndSize.second);
366       break;
367     case TargetOpcode::G_ZEXT:
368       Val = Val.zext(OpcodeAndSize.second);
369       break;
370     }
371   }
372 
373   return ValueAndVReg{Val, VReg};
374 }
375 
376 bool isIConstant(const MachineInstr *MI) {
377   if (!MI)
378     return false;
379   return MI->getOpcode() == TargetOpcode::G_CONSTANT;
380 }
381 
382 bool isFConstant(const MachineInstr *MI) {
383   if (!MI)
384     return false;
385   return MI->getOpcode() == TargetOpcode::G_FCONSTANT;
386 }
387 
388 bool isAnyConstant(const MachineInstr *MI) {
389   if (!MI)
390     return false;
391   unsigned Opc = MI->getOpcode();
392   return Opc == TargetOpcode::G_CONSTANT || Opc == TargetOpcode::G_FCONSTANT;
393 }
394 
395 std::optional<APInt> getCImmAsAPInt(const MachineInstr *MI) {
396   const MachineOperand &CstVal = MI->getOperand(1);
397   if (CstVal.isCImm())
398     return CstVal.getCImm()->getValue();
399   return std::nullopt;
400 }
401 
402 std::optional<APInt> getCImmOrFPImmAsAPInt(const MachineInstr *MI) {
403   const MachineOperand &CstVal = MI->getOperand(1);
404   if (CstVal.isCImm())
405     return CstVal.getCImm()->getValue();
406   if (CstVal.isFPImm())
407     return CstVal.getFPImm()->getValueAPF().bitcastToAPInt();
408   return std::nullopt;
409 }
410 
411 } // end anonymous namespace
412 
413 std::optional<ValueAndVReg> llvm::getIConstantVRegValWithLookThrough(
414     Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) {
415   return getConstantVRegValWithLookThrough(VReg, MRI, isIConstant,
416                                            getCImmAsAPInt, LookThroughInstrs);
417 }
418 
419 std::optional<ValueAndVReg> llvm::getAnyConstantVRegValWithLookThrough(
420     Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs,
421     bool LookThroughAnyExt) {
422   return getConstantVRegValWithLookThrough(
423       VReg, MRI, isAnyConstant, getCImmOrFPImmAsAPInt, LookThroughInstrs,
424       LookThroughAnyExt);
425 }
426 
427 std::optional<FPValueAndVReg> llvm::getFConstantVRegValWithLookThrough(
428     Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) {
429   auto Reg = getConstantVRegValWithLookThrough(
430       VReg, MRI, isFConstant, getCImmOrFPImmAsAPInt, LookThroughInstrs);
431   if (!Reg)
432     return std::nullopt;
433   return FPValueAndVReg{getConstantFPVRegVal(Reg->VReg, MRI)->getValueAPF(),
434                         Reg->VReg};
435 }
436 
437 const ConstantFP *
438 llvm::getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI) {
439   MachineInstr *MI = MRI.getVRegDef(VReg);
440   if (TargetOpcode::G_FCONSTANT != MI->getOpcode())
441     return nullptr;
442   return MI->getOperand(1).getFPImm();
443 }
444 
445 std::optional<DefinitionAndSourceRegister>
446 llvm::getDefSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI) {
447   Register DefSrcReg = Reg;
448   auto *DefMI = MRI.getVRegDef(Reg);
449   auto DstTy = MRI.getType(DefMI->getOperand(0).getReg());
450   if (!DstTy.isValid())
451     return std::nullopt;
452   unsigned Opc = DefMI->getOpcode();
453   while (Opc == TargetOpcode::COPY || isPreISelGenericOptimizationHint(Opc)) {
454     Register SrcReg = DefMI->getOperand(1).getReg();
455     auto SrcTy = MRI.getType(SrcReg);
456     if (!SrcTy.isValid())
457       break;
458     DefMI = MRI.getVRegDef(SrcReg);
459     DefSrcReg = SrcReg;
460     Opc = DefMI->getOpcode();
461   }
462   return DefinitionAndSourceRegister{DefMI, DefSrcReg};
463 }
464 
465 MachineInstr *llvm::getDefIgnoringCopies(Register Reg,
466                                          const MachineRegisterInfo &MRI) {
467   std::optional<DefinitionAndSourceRegister> DefSrcReg =
468       getDefSrcRegIgnoringCopies(Reg, MRI);
469   return DefSrcReg ? DefSrcReg->MI : nullptr;
470 }
471 
472 Register llvm::getSrcRegIgnoringCopies(Register Reg,
473                                        const MachineRegisterInfo &MRI) {
474   std::optional<DefinitionAndSourceRegister> DefSrcReg =
475       getDefSrcRegIgnoringCopies(Reg, MRI);
476   return DefSrcReg ? DefSrcReg->Reg : Register();
477 }
478 
479 MachineInstr *llvm::getOpcodeDef(unsigned Opcode, Register Reg,
480                                  const MachineRegisterInfo &MRI) {
481   MachineInstr *DefMI = getDefIgnoringCopies(Reg, MRI);
482   return DefMI && DefMI->getOpcode() == Opcode ? DefMI : nullptr;
483 }
484 
485 APFloat llvm::getAPFloatFromSize(double Val, unsigned Size) {
486   if (Size == 32)
487     return APFloat(float(Val));
488   if (Size == 64)
489     return APFloat(Val);
490   if (Size != 16)
491     llvm_unreachable("Unsupported FPConstant size");
492   bool Ignored;
493   APFloat APF(Val);
494   APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &Ignored);
495   return APF;
496 }
497 
498 std::optional<APInt> llvm::ConstantFoldBinOp(unsigned Opcode,
499                                              const Register Op1,
500                                              const Register Op2,
501                                              const MachineRegisterInfo &MRI) {
502   auto MaybeOp2Cst = getAnyConstantVRegValWithLookThrough(Op2, MRI, false);
503   if (!MaybeOp2Cst)
504     return std::nullopt;
505 
506   auto MaybeOp1Cst = getAnyConstantVRegValWithLookThrough(Op1, MRI, false);
507   if (!MaybeOp1Cst)
508     return std::nullopt;
509 
510   const APInt &C1 = MaybeOp1Cst->Value;
511   const APInt &C2 = MaybeOp2Cst->Value;
512   switch (Opcode) {
513   default:
514     break;
515   case TargetOpcode::G_ADD:
516   case TargetOpcode::G_PTR_ADD:
517     return C1 + C2;
518   case TargetOpcode::G_AND:
519     return C1 & C2;
520   case TargetOpcode::G_ASHR:
521     return C1.ashr(C2);
522   case TargetOpcode::G_LSHR:
523     return C1.lshr(C2);
524   case TargetOpcode::G_MUL:
525     return C1 * C2;
526   case TargetOpcode::G_OR:
527     return C1 | C2;
528   case TargetOpcode::G_SHL:
529     return C1 << C2;
530   case TargetOpcode::G_SUB:
531     return C1 - C2;
532   case TargetOpcode::G_XOR:
533     return C1 ^ C2;
534   case TargetOpcode::G_UDIV:
535     if (!C2.getBoolValue())
536       break;
537     return C1.udiv(C2);
538   case TargetOpcode::G_SDIV:
539     if (!C2.getBoolValue())
540       break;
541     return C1.sdiv(C2);
542   case TargetOpcode::G_UREM:
543     if (!C2.getBoolValue())
544       break;
545     return C1.urem(C2);
546   case TargetOpcode::G_SREM:
547     if (!C2.getBoolValue())
548       break;
549     return C1.srem(C2);
550   case TargetOpcode::G_SMIN:
551     return APIntOps::smin(C1, C2);
552   case TargetOpcode::G_SMAX:
553     return APIntOps::smax(C1, C2);
554   case TargetOpcode::G_UMIN:
555     return APIntOps::umin(C1, C2);
556   case TargetOpcode::G_UMAX:
557     return APIntOps::umax(C1, C2);
558   }
559 
560   return std::nullopt;
561 }
562 
563 std::optional<APFloat>
564 llvm::ConstantFoldFPBinOp(unsigned Opcode, const Register Op1,
565                           const Register Op2, const MachineRegisterInfo &MRI) {
566   const ConstantFP *Op2Cst = getConstantFPVRegVal(Op2, MRI);
567   if (!Op2Cst)
568     return std::nullopt;
569 
570   const ConstantFP *Op1Cst = getConstantFPVRegVal(Op1, MRI);
571   if (!Op1Cst)
572     return std::nullopt;
573 
574   APFloat C1 = Op1Cst->getValueAPF();
575   const APFloat &C2 = Op2Cst->getValueAPF();
576   switch (Opcode) {
577   case TargetOpcode::G_FADD:
578     C1.add(C2, APFloat::rmNearestTiesToEven);
579     return C1;
580   case TargetOpcode::G_FSUB:
581     C1.subtract(C2, APFloat::rmNearestTiesToEven);
582     return C1;
583   case TargetOpcode::G_FMUL:
584     C1.multiply(C2, APFloat::rmNearestTiesToEven);
585     return C1;
586   case TargetOpcode::G_FDIV:
587     C1.divide(C2, APFloat::rmNearestTiesToEven);
588     return C1;
589   case TargetOpcode::G_FREM:
590     C1.mod(C2);
591     return C1;
592   case TargetOpcode::G_FCOPYSIGN:
593     C1.copySign(C2);
594     return C1;
595   case TargetOpcode::G_FMINNUM:
596     return minnum(C1, C2);
597   case TargetOpcode::G_FMAXNUM:
598     return maxnum(C1, C2);
599   case TargetOpcode::G_FMINIMUM:
600     return minimum(C1, C2);
601   case TargetOpcode::G_FMAXIMUM:
602     return maximum(C1, C2);
603   case TargetOpcode::G_FMINNUM_IEEE:
604   case TargetOpcode::G_FMAXNUM_IEEE:
605     // FIXME: These operations were unfortunately named. fminnum/fmaxnum do not
606     // follow the IEEE behavior for signaling nans and follow libm's fmin/fmax,
607     // and currently there isn't a nice wrapper in APFloat for the version with
608     // correct snan handling.
609     break;
610   default:
611     break;
612   }
613 
614   return std::nullopt;
615 }
616 
617 SmallVector<APInt>
618 llvm::ConstantFoldVectorBinop(unsigned Opcode, const Register Op1,
619                               const Register Op2,
620                               const MachineRegisterInfo &MRI) {
621   auto *SrcVec2 = getOpcodeDef<GBuildVector>(Op2, MRI);
622   if (!SrcVec2)
623     return SmallVector<APInt>();
624 
625   auto *SrcVec1 = getOpcodeDef<GBuildVector>(Op1, MRI);
626   if (!SrcVec1)
627     return SmallVector<APInt>();
628 
629   SmallVector<APInt> FoldedElements;
630   for (unsigned Idx = 0, E = SrcVec1->getNumSources(); Idx < E; ++Idx) {
631     auto MaybeCst = ConstantFoldBinOp(Opcode, SrcVec1->getSourceReg(Idx),
632                                       SrcVec2->getSourceReg(Idx), MRI);
633     if (!MaybeCst)
634       return SmallVector<APInt>();
635     FoldedElements.push_back(*MaybeCst);
636   }
637   return FoldedElements;
638 }
639 
640 bool llvm::isKnownNeverNaN(Register Val, const MachineRegisterInfo &MRI,
641                            bool SNaN) {
642   const MachineInstr *DefMI = MRI.getVRegDef(Val);
643   if (!DefMI)
644     return false;
645 
646   const TargetMachine& TM = DefMI->getMF()->getTarget();
647   if (DefMI->getFlag(MachineInstr::FmNoNans) || TM.Options.NoNaNsFPMath)
648     return true;
649 
650   // If the value is a constant, we can obviously see if it is a NaN or not.
651   if (const ConstantFP *FPVal = getConstantFPVRegVal(Val, MRI)) {
652     return !FPVal->getValueAPF().isNaN() ||
653            (SNaN && !FPVal->getValueAPF().isSignaling());
654   }
655 
656   if (DefMI->getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
657     for (const auto &Op : DefMI->uses())
658       if (!isKnownNeverNaN(Op.getReg(), MRI, SNaN))
659         return false;
660     return true;
661   }
662 
663   switch (DefMI->getOpcode()) {
664   default:
665     break;
666   case TargetOpcode::G_FADD:
667   case TargetOpcode::G_FSUB:
668   case TargetOpcode::G_FMUL:
669   case TargetOpcode::G_FDIV:
670   case TargetOpcode::G_FREM:
671   case TargetOpcode::G_FSIN:
672   case TargetOpcode::G_FCOS:
673   case TargetOpcode::G_FMA:
674   case TargetOpcode::G_FMAD:
675     if (SNaN)
676       return true;
677 
678     // TODO: Need isKnownNeverInfinity
679     return false;
680   case TargetOpcode::G_FMINNUM_IEEE:
681   case TargetOpcode::G_FMAXNUM_IEEE: {
682     if (SNaN)
683       return true;
684     // This can return a NaN if either operand is an sNaN, or if both operands
685     // are NaN.
686     return (isKnownNeverNaN(DefMI->getOperand(1).getReg(), MRI) &&
687             isKnownNeverSNaN(DefMI->getOperand(2).getReg(), MRI)) ||
688            (isKnownNeverSNaN(DefMI->getOperand(1).getReg(), MRI) &&
689             isKnownNeverNaN(DefMI->getOperand(2).getReg(), MRI));
690   }
691   case TargetOpcode::G_FMINNUM:
692   case TargetOpcode::G_FMAXNUM: {
693     // Only one needs to be known not-nan, since it will be returned if the
694     // other ends up being one.
695     return isKnownNeverNaN(DefMI->getOperand(1).getReg(), MRI, SNaN) ||
696            isKnownNeverNaN(DefMI->getOperand(2).getReg(), MRI, SNaN);
697   }
698   }
699 
700   if (SNaN) {
701     // FP operations quiet. For now, just handle the ones inserted during
702     // legalization.
703     switch (DefMI->getOpcode()) {
704     case TargetOpcode::G_FPEXT:
705     case TargetOpcode::G_FPTRUNC:
706     case TargetOpcode::G_FCANONICALIZE:
707       return true;
708     default:
709       return false;
710     }
711   }
712 
713   return false;
714 }
715 
716 Align llvm::inferAlignFromPtrInfo(MachineFunction &MF,
717                                   const MachinePointerInfo &MPO) {
718   auto PSV = dyn_cast_if_present<const PseudoSourceValue *>(MPO.V);
719   if (auto FSPV = dyn_cast_or_null<FixedStackPseudoSourceValue>(PSV)) {
720     MachineFrameInfo &MFI = MF.getFrameInfo();
721     return commonAlignment(MFI.getObjectAlign(FSPV->getFrameIndex()),
722                            MPO.Offset);
723   }
724 
725   if (const Value *V = dyn_cast_if_present<const Value *>(MPO.V)) {
726     const Module *M = MF.getFunction().getParent();
727     return V->getPointerAlignment(M->getDataLayout());
728   }
729 
730   return Align(1);
731 }
732 
733 Register llvm::getFunctionLiveInPhysReg(MachineFunction &MF,
734                                         const TargetInstrInfo &TII,
735                                         MCRegister PhysReg,
736                                         const TargetRegisterClass &RC,
737                                         const DebugLoc &DL, LLT RegTy) {
738   MachineBasicBlock &EntryMBB = MF.front();
739   MachineRegisterInfo &MRI = MF.getRegInfo();
740   Register LiveIn = MRI.getLiveInVirtReg(PhysReg);
741   if (LiveIn) {
742     MachineInstr *Def = MRI.getVRegDef(LiveIn);
743     if (Def) {
744       // FIXME: Should the verifier check this is in the entry block?
745       assert(Def->getParent() == &EntryMBB && "live-in copy not in entry block");
746       return LiveIn;
747     }
748 
749     // It's possible the incoming argument register and copy was added during
750     // lowering, but later deleted due to being/becoming dead. If this happens,
751     // re-insert the copy.
752   } else {
753     // The live in register was not present, so add it.
754     LiveIn = MF.addLiveIn(PhysReg, &RC);
755     if (RegTy.isValid())
756       MRI.setType(LiveIn, RegTy);
757   }
758 
759   BuildMI(EntryMBB, EntryMBB.begin(), DL, TII.get(TargetOpcode::COPY), LiveIn)
760     .addReg(PhysReg);
761   if (!EntryMBB.isLiveIn(PhysReg))
762     EntryMBB.addLiveIn(PhysReg);
763   return LiveIn;
764 }
765 
766 std::optional<APInt> llvm::ConstantFoldExtOp(unsigned Opcode,
767                                              const Register Op1, uint64_t Imm,
768                                              const MachineRegisterInfo &MRI) {
769   auto MaybeOp1Cst = getIConstantVRegVal(Op1, MRI);
770   if (MaybeOp1Cst) {
771     switch (Opcode) {
772     default:
773       break;
774     case TargetOpcode::G_SEXT_INREG: {
775       LLT Ty = MRI.getType(Op1);
776       return MaybeOp1Cst->trunc(Imm).sext(Ty.getScalarSizeInBits());
777     }
778     }
779   }
780   return std::nullopt;
781 }
782 
783 std::optional<APInt> llvm::ConstantFoldCastOp(unsigned Opcode, LLT DstTy,
784                                               const Register Op0,
785                                               const MachineRegisterInfo &MRI) {
786   std::optional<APInt> Val = getIConstantVRegVal(Op0, MRI);
787   if (!Val)
788     return Val;
789 
790   const unsigned DstSize = DstTy.getScalarSizeInBits();
791 
792   switch (Opcode) {
793   case TargetOpcode::G_SEXT:
794     return Val->sext(DstSize);
795   case TargetOpcode::G_ZEXT:
796   case TargetOpcode::G_ANYEXT:
797     // TODO: DAG considers target preference when constant folding any_extend.
798     return Val->zext(DstSize);
799   default:
800     break;
801   }
802 
803   llvm_unreachable("unexpected cast opcode to constant fold");
804 }
805 
806 std::optional<APFloat>
807 llvm::ConstantFoldIntToFloat(unsigned Opcode, LLT DstTy, Register Src,
808                              const MachineRegisterInfo &MRI) {
809   assert(Opcode == TargetOpcode::G_SITOFP || Opcode == TargetOpcode::G_UITOFP);
810   if (auto MaybeSrcVal = getIConstantVRegVal(Src, MRI)) {
811     APFloat DstVal(getFltSemanticForLLT(DstTy));
812     DstVal.convertFromAPInt(*MaybeSrcVal, Opcode == TargetOpcode::G_SITOFP,
813                             APFloat::rmNearestTiesToEven);
814     return DstVal;
815   }
816   return std::nullopt;
817 }
818 
819 std::optional<SmallVector<unsigned>>
820 llvm::ConstantFoldCTLZ(Register Src, const MachineRegisterInfo &MRI) {
821   LLT Ty = MRI.getType(Src);
822   SmallVector<unsigned> FoldedCTLZs;
823   auto tryFoldScalar = [&](Register R) -> std::optional<unsigned> {
824     auto MaybeCst = getIConstantVRegVal(R, MRI);
825     if (!MaybeCst)
826       return std::nullopt;
827     return MaybeCst->countl_zero();
828   };
829   if (Ty.isVector()) {
830     // Try to constant fold each element.
831     auto *BV = getOpcodeDef<GBuildVector>(Src, MRI);
832     if (!BV)
833       return std::nullopt;
834     for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
835       if (auto MaybeFold = tryFoldScalar(BV->getSourceReg(SrcIdx))) {
836         FoldedCTLZs.emplace_back(*MaybeFold);
837         continue;
838       }
839       return std::nullopt;
840     }
841     return FoldedCTLZs;
842   }
843   if (auto MaybeCst = tryFoldScalar(Src)) {
844     FoldedCTLZs.emplace_back(*MaybeCst);
845     return FoldedCTLZs;
846   }
847   return std::nullopt;
848 }
849 
850 bool llvm::isKnownToBeAPowerOfTwo(Register Reg, const MachineRegisterInfo &MRI,
851                                   GISelKnownBits *KB) {
852   std::optional<DefinitionAndSourceRegister> DefSrcReg =
853       getDefSrcRegIgnoringCopies(Reg, MRI);
854   if (!DefSrcReg)
855     return false;
856 
857   const MachineInstr &MI = *DefSrcReg->MI;
858   const LLT Ty = MRI.getType(Reg);
859 
860   switch (MI.getOpcode()) {
861   case TargetOpcode::G_CONSTANT: {
862     unsigned BitWidth = Ty.getScalarSizeInBits();
863     const ConstantInt *CI = MI.getOperand(1).getCImm();
864     return CI->getValue().zextOrTrunc(BitWidth).isPowerOf2();
865   }
866   case TargetOpcode::G_SHL: {
867     // A left-shift of a constant one will have exactly one bit set because
868     // shifting the bit off the end is undefined.
869 
870     // TODO: Constant splat
871     if (auto ConstLHS = getIConstantVRegVal(MI.getOperand(1).getReg(), MRI)) {
872       if (*ConstLHS == 1)
873         return true;
874     }
875 
876     break;
877   }
878   case TargetOpcode::G_LSHR: {
879     if (auto ConstLHS = getIConstantVRegVal(MI.getOperand(1).getReg(), MRI)) {
880       if (ConstLHS->isSignMask())
881         return true;
882     }
883 
884     break;
885   }
886   case TargetOpcode::G_BUILD_VECTOR: {
887     // TODO: Probably should have a recursion depth guard since you could have
888     // bitcasted vector elements.
889     for (const MachineOperand &MO : llvm::drop_begin(MI.operands()))
890       if (!isKnownToBeAPowerOfTwo(MO.getReg(), MRI, KB))
891         return false;
892 
893     return true;
894   }
895   case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
896     // Only handle constants since we would need to know if number of leading
897     // zeros is greater than the truncation amount.
898     const unsigned BitWidth = Ty.getScalarSizeInBits();
899     for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
900       auto Const = getIConstantVRegVal(MO.getReg(), MRI);
901       if (!Const || !Const->zextOrTrunc(BitWidth).isPowerOf2())
902         return false;
903     }
904 
905     return true;
906   }
907   default:
908     break;
909   }
910 
911   if (!KB)
912     return false;
913 
914   // More could be done here, though the above checks are enough
915   // to handle some common cases.
916 
917   // Fall back to computeKnownBits to catch other known cases.
918   KnownBits Known = KB->getKnownBits(Reg);
919   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
920 }
921 
922 void llvm::getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU) {
923   AU.addPreserved<StackProtector>();
924 }
925 
926 LLT llvm::getLCMType(LLT OrigTy, LLT TargetTy) {
927   const unsigned OrigSize = OrigTy.getSizeInBits();
928   const unsigned TargetSize = TargetTy.getSizeInBits();
929 
930   if (OrigSize == TargetSize)
931     return OrigTy;
932 
933   if (OrigTy.isVector()) {
934     const LLT OrigElt = OrigTy.getElementType();
935 
936     if (TargetTy.isVector()) {
937       const LLT TargetElt = TargetTy.getElementType();
938 
939       if (OrigElt.getSizeInBits() == TargetElt.getSizeInBits()) {
940         int GCDElts =
941             std::gcd(OrigTy.getNumElements(), TargetTy.getNumElements());
942         // Prefer the original element type.
943         ElementCount Mul = OrigTy.getElementCount() * TargetTy.getNumElements();
944         return LLT::vector(Mul.divideCoefficientBy(GCDElts),
945                            OrigTy.getElementType());
946       }
947     } else {
948       if (OrigElt.getSizeInBits() == TargetSize)
949         return OrigTy;
950     }
951 
952     unsigned LCMSize = std::lcm(OrigSize, TargetSize);
953     return LLT::fixed_vector(LCMSize / OrigElt.getSizeInBits(), OrigElt);
954   }
955 
956   if (TargetTy.isVector()) {
957     unsigned LCMSize = std::lcm(OrigSize, TargetSize);
958     return LLT::fixed_vector(LCMSize / OrigSize, OrigTy);
959   }
960 
961   unsigned LCMSize = std::lcm(OrigSize, TargetSize);
962 
963   // Preserve pointer types.
964   if (LCMSize == OrigSize)
965     return OrigTy;
966   if (LCMSize == TargetSize)
967     return TargetTy;
968 
969   return LLT::scalar(LCMSize);
970 }
971 
972 LLT llvm::getCoverTy(LLT OrigTy, LLT TargetTy) {
973   if (!OrigTy.isVector() || !TargetTy.isVector() || OrigTy == TargetTy ||
974       (OrigTy.getScalarSizeInBits() != TargetTy.getScalarSizeInBits()))
975     return getLCMType(OrigTy, TargetTy);
976 
977   unsigned OrigTyNumElts = OrigTy.getNumElements();
978   unsigned TargetTyNumElts = TargetTy.getNumElements();
979   if (OrigTyNumElts % TargetTyNumElts == 0)
980     return OrigTy;
981 
982   unsigned NumElts = alignTo(OrigTyNumElts, TargetTyNumElts);
983   return LLT::scalarOrVector(ElementCount::getFixed(NumElts),
984                              OrigTy.getElementType());
985 }
986 
987 LLT llvm::getGCDType(LLT OrigTy, LLT TargetTy) {
988   const unsigned OrigSize = OrigTy.getSizeInBits();
989   const unsigned TargetSize = TargetTy.getSizeInBits();
990 
991   if (OrigSize == TargetSize)
992     return OrigTy;
993 
994   if (OrigTy.isVector()) {
995     LLT OrigElt = OrigTy.getElementType();
996     if (TargetTy.isVector()) {
997       LLT TargetElt = TargetTy.getElementType();
998       if (OrigElt.getSizeInBits() == TargetElt.getSizeInBits()) {
999         int GCD = std::gcd(OrigTy.getNumElements(), TargetTy.getNumElements());
1000         return LLT::scalarOrVector(ElementCount::getFixed(GCD), OrigElt);
1001       }
1002     } else {
1003       // If the source is a vector of pointers, return a pointer element.
1004       if (OrigElt.getSizeInBits() == TargetSize)
1005         return OrigElt;
1006     }
1007 
1008     unsigned GCD = std::gcd(OrigSize, TargetSize);
1009     if (GCD == OrigElt.getSizeInBits())
1010       return OrigElt;
1011 
1012     // If we can't produce the original element type, we have to use a smaller
1013     // scalar.
1014     if (GCD < OrigElt.getSizeInBits())
1015       return LLT::scalar(GCD);
1016     return LLT::fixed_vector(GCD / OrigElt.getSizeInBits(), OrigElt);
1017   }
1018 
1019   if (TargetTy.isVector()) {
1020     // Try to preserve the original element type.
1021     LLT TargetElt = TargetTy.getElementType();
1022     if (TargetElt.getSizeInBits() == OrigSize)
1023       return OrigTy;
1024   }
1025 
1026   unsigned GCD = std::gcd(OrigSize, TargetSize);
1027   return LLT::scalar(GCD);
1028 }
1029 
1030 std::optional<int> llvm::getSplatIndex(MachineInstr &MI) {
1031   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
1032          "Only G_SHUFFLE_VECTOR can have a splat index!");
1033   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
1034   auto FirstDefinedIdx = find_if(Mask, [](int Elt) { return Elt >= 0; });
1035 
1036   // If all elements are undefined, this shuffle can be considered a splat.
1037   // Return 0 for better potential for callers to simplify.
1038   if (FirstDefinedIdx == Mask.end())
1039     return 0;
1040 
1041   // Make sure all remaining elements are either undef or the same
1042   // as the first non-undef value.
1043   int SplatValue = *FirstDefinedIdx;
1044   if (any_of(make_range(std::next(FirstDefinedIdx), Mask.end()),
1045              [&SplatValue](int Elt) { return Elt >= 0 && Elt != SplatValue; }))
1046     return std::nullopt;
1047 
1048   return SplatValue;
1049 }
1050 
1051 static bool isBuildVectorOp(unsigned Opcode) {
1052   return Opcode == TargetOpcode::G_BUILD_VECTOR ||
1053          Opcode == TargetOpcode::G_BUILD_VECTOR_TRUNC;
1054 }
1055 
1056 namespace {
1057 
1058 std::optional<ValueAndVReg> getAnyConstantSplat(Register VReg,
1059                                                 const MachineRegisterInfo &MRI,
1060                                                 bool AllowUndef) {
1061   MachineInstr *MI = getDefIgnoringCopies(VReg, MRI);
1062   if (!MI)
1063     return std::nullopt;
1064 
1065   bool isConcatVectorsOp = MI->getOpcode() == TargetOpcode::G_CONCAT_VECTORS;
1066   if (!isBuildVectorOp(MI->getOpcode()) && !isConcatVectorsOp)
1067     return std::nullopt;
1068 
1069   std::optional<ValueAndVReg> SplatValAndReg;
1070   for (MachineOperand &Op : MI->uses()) {
1071     Register Element = Op.getReg();
1072     // If we have a G_CONCAT_VECTOR, we recursively look into the
1073     // vectors that we're concatenating to see if they're splats.
1074     auto ElementValAndReg =
1075         isConcatVectorsOp
1076             ? getAnyConstantSplat(Element, MRI, AllowUndef)
1077             : getAnyConstantVRegValWithLookThrough(Element, MRI, true, true);
1078 
1079     // If AllowUndef, treat undef as value that will result in a constant splat.
1080     if (!ElementValAndReg) {
1081       if (AllowUndef && isa<GImplicitDef>(MRI.getVRegDef(Element)))
1082         continue;
1083       return std::nullopt;
1084     }
1085 
1086     // Record splat value
1087     if (!SplatValAndReg)
1088       SplatValAndReg = ElementValAndReg;
1089 
1090     // Different constant than the one already recorded, not a constant splat.
1091     if (SplatValAndReg->Value != ElementValAndReg->Value)
1092       return std::nullopt;
1093   }
1094 
1095   return SplatValAndReg;
1096 }
1097 
1098 } // end anonymous namespace
1099 
1100 bool llvm::isBuildVectorConstantSplat(const Register Reg,
1101                                       const MachineRegisterInfo &MRI,
1102                                       int64_t SplatValue, bool AllowUndef) {
1103   if (auto SplatValAndReg = getAnyConstantSplat(Reg, MRI, AllowUndef))
1104     return mi_match(SplatValAndReg->VReg, MRI, m_SpecificICst(SplatValue));
1105   return false;
1106 }
1107 
1108 bool llvm::isBuildVectorConstantSplat(const MachineInstr &MI,
1109                                       const MachineRegisterInfo &MRI,
1110                                       int64_t SplatValue, bool AllowUndef) {
1111   return isBuildVectorConstantSplat(MI.getOperand(0).getReg(), MRI, SplatValue,
1112                                     AllowUndef);
1113 }
1114 
1115 std::optional<APInt>
1116 llvm::getIConstantSplatVal(const Register Reg, const MachineRegisterInfo &MRI) {
1117   if (auto SplatValAndReg =
1118           getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false)) {
1119     if (std::optional<ValueAndVReg> ValAndVReg =
1120         getIConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI))
1121       return ValAndVReg->Value;
1122   }
1123 
1124   return std::nullopt;
1125 }
1126 
1127 std::optional<APInt>
1128 llvm::getIConstantSplatVal(const MachineInstr &MI,
1129                            const MachineRegisterInfo &MRI) {
1130   return getIConstantSplatVal(MI.getOperand(0).getReg(), MRI);
1131 }
1132 
1133 std::optional<int64_t>
1134 llvm::getIConstantSplatSExtVal(const Register Reg,
1135                                const MachineRegisterInfo &MRI) {
1136   if (auto SplatValAndReg =
1137           getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false))
1138     return getIConstantVRegSExtVal(SplatValAndReg->VReg, MRI);
1139   return std::nullopt;
1140 }
1141 
1142 std::optional<int64_t>
1143 llvm::getIConstantSplatSExtVal(const MachineInstr &MI,
1144                                const MachineRegisterInfo &MRI) {
1145   return getIConstantSplatSExtVal(MI.getOperand(0).getReg(), MRI);
1146 }
1147 
1148 std::optional<FPValueAndVReg>
1149 llvm::getFConstantSplat(Register VReg, const MachineRegisterInfo &MRI,
1150                         bool AllowUndef) {
1151   if (auto SplatValAndReg = getAnyConstantSplat(VReg, MRI, AllowUndef))
1152     return getFConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI);
1153   return std::nullopt;
1154 }
1155 
1156 bool llvm::isBuildVectorAllZeros(const MachineInstr &MI,
1157                                  const MachineRegisterInfo &MRI,
1158                                  bool AllowUndef) {
1159   return isBuildVectorConstantSplat(MI, MRI, 0, AllowUndef);
1160 }
1161 
1162 bool llvm::isBuildVectorAllOnes(const MachineInstr &MI,
1163                                 const MachineRegisterInfo &MRI,
1164                                 bool AllowUndef) {
1165   return isBuildVectorConstantSplat(MI, MRI, -1, AllowUndef);
1166 }
1167 
1168 std::optional<RegOrConstant>
1169 llvm::getVectorSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI) {
1170   unsigned Opc = MI.getOpcode();
1171   if (!isBuildVectorOp(Opc))
1172     return std::nullopt;
1173   if (auto Splat = getIConstantSplatSExtVal(MI, MRI))
1174     return RegOrConstant(*Splat);
1175   auto Reg = MI.getOperand(1).getReg();
1176   if (any_of(drop_begin(MI.operands(), 2),
1177              [&Reg](const MachineOperand &Op) { return Op.getReg() != Reg; }))
1178     return std::nullopt;
1179   return RegOrConstant(Reg);
1180 }
1181 
1182 static bool isConstantScalar(const MachineInstr &MI,
1183                              const MachineRegisterInfo &MRI,
1184                              bool AllowFP = true,
1185                              bool AllowOpaqueConstants = true) {
1186   switch (MI.getOpcode()) {
1187   case TargetOpcode::G_CONSTANT:
1188   case TargetOpcode::G_IMPLICIT_DEF:
1189     return true;
1190   case TargetOpcode::G_FCONSTANT:
1191     return AllowFP;
1192   case TargetOpcode::G_GLOBAL_VALUE:
1193   case TargetOpcode::G_FRAME_INDEX:
1194   case TargetOpcode::G_BLOCK_ADDR:
1195   case TargetOpcode::G_JUMP_TABLE:
1196     return AllowOpaqueConstants;
1197   default:
1198     return false;
1199   }
1200 }
1201 
1202 bool llvm::isConstantOrConstantVector(MachineInstr &MI,
1203                                       const MachineRegisterInfo &MRI) {
1204   Register Def = MI.getOperand(0).getReg();
1205   if (auto C = getIConstantVRegValWithLookThrough(Def, MRI))
1206     return true;
1207   GBuildVector *BV = dyn_cast<GBuildVector>(&MI);
1208   if (!BV)
1209     return false;
1210   for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
1211     if (getIConstantVRegValWithLookThrough(BV->getSourceReg(SrcIdx), MRI) ||
1212         getOpcodeDef<GImplicitDef>(BV->getSourceReg(SrcIdx), MRI))
1213       continue;
1214     return false;
1215   }
1216   return true;
1217 }
1218 
1219 bool llvm::isConstantOrConstantVector(const MachineInstr &MI,
1220                                       const MachineRegisterInfo &MRI,
1221                                       bool AllowFP, bool AllowOpaqueConstants) {
1222   if (isConstantScalar(MI, MRI, AllowFP, AllowOpaqueConstants))
1223     return true;
1224 
1225   if (!isBuildVectorOp(MI.getOpcode()))
1226     return false;
1227 
1228   const unsigned NumOps = MI.getNumOperands();
1229   for (unsigned I = 1; I != NumOps; ++I) {
1230     const MachineInstr *ElementDef = MRI.getVRegDef(MI.getOperand(I).getReg());
1231     if (!isConstantScalar(*ElementDef, MRI, AllowFP, AllowOpaqueConstants))
1232       return false;
1233   }
1234 
1235   return true;
1236 }
1237 
1238 std::optional<APInt>
1239 llvm::isConstantOrConstantSplatVector(MachineInstr &MI,
1240                                       const MachineRegisterInfo &MRI) {
1241   Register Def = MI.getOperand(0).getReg();
1242   if (auto C = getIConstantVRegValWithLookThrough(Def, MRI))
1243     return C->Value;
1244   auto MaybeCst = getIConstantSplatSExtVal(MI, MRI);
1245   if (!MaybeCst)
1246     return std::nullopt;
1247   const unsigned ScalarSize = MRI.getType(Def).getScalarSizeInBits();
1248   return APInt(ScalarSize, *MaybeCst, true);
1249 }
1250 
1251 bool llvm::isNullOrNullSplat(const MachineInstr &MI,
1252                              const MachineRegisterInfo &MRI, bool AllowUndefs) {
1253   switch (MI.getOpcode()) {
1254   case TargetOpcode::G_IMPLICIT_DEF:
1255     return AllowUndefs;
1256   case TargetOpcode::G_CONSTANT:
1257     return MI.getOperand(1).getCImm()->isNullValue();
1258   case TargetOpcode::G_FCONSTANT: {
1259     const ConstantFP *FPImm = MI.getOperand(1).getFPImm();
1260     return FPImm->isZero() && !FPImm->isNegative();
1261   }
1262   default:
1263     if (!AllowUndefs) // TODO: isBuildVectorAllZeros assumes undef is OK already
1264       return false;
1265     return isBuildVectorAllZeros(MI, MRI);
1266   }
1267 }
1268 
1269 bool llvm::isAllOnesOrAllOnesSplat(const MachineInstr &MI,
1270                                    const MachineRegisterInfo &MRI,
1271                                    bool AllowUndefs) {
1272   switch (MI.getOpcode()) {
1273   case TargetOpcode::G_IMPLICIT_DEF:
1274     return AllowUndefs;
1275   case TargetOpcode::G_CONSTANT:
1276     return MI.getOperand(1).getCImm()->isAllOnesValue();
1277   default:
1278     if (!AllowUndefs) // TODO: isBuildVectorAllOnes assumes undef is OK already
1279       return false;
1280     return isBuildVectorAllOnes(MI, MRI);
1281   }
1282 }
1283 
1284 bool llvm::matchUnaryPredicate(
1285     const MachineRegisterInfo &MRI, Register Reg,
1286     std::function<bool(const Constant *ConstVal)> Match, bool AllowUndefs) {
1287 
1288   const MachineInstr *Def = getDefIgnoringCopies(Reg, MRI);
1289   if (AllowUndefs && Def->getOpcode() == TargetOpcode::G_IMPLICIT_DEF)
1290     return Match(nullptr);
1291 
1292   // TODO: Also handle fconstant
1293   if (Def->getOpcode() == TargetOpcode::G_CONSTANT)
1294     return Match(Def->getOperand(1).getCImm());
1295 
1296   if (Def->getOpcode() != TargetOpcode::G_BUILD_VECTOR)
1297     return false;
1298 
1299   for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
1300     Register SrcElt = Def->getOperand(I).getReg();
1301     const MachineInstr *SrcDef = getDefIgnoringCopies(SrcElt, MRI);
1302     if (AllowUndefs && SrcDef->getOpcode() == TargetOpcode::G_IMPLICIT_DEF) {
1303       if (!Match(nullptr))
1304         return false;
1305       continue;
1306     }
1307 
1308     if (SrcDef->getOpcode() != TargetOpcode::G_CONSTANT ||
1309         !Match(SrcDef->getOperand(1).getCImm()))
1310       return false;
1311   }
1312 
1313   return true;
1314 }
1315 
1316 bool llvm::isConstTrueVal(const TargetLowering &TLI, int64_t Val, bool IsVector,
1317                           bool IsFP) {
1318   switch (TLI.getBooleanContents(IsVector, IsFP)) {
1319   case TargetLowering::UndefinedBooleanContent:
1320     return Val & 0x1;
1321   case TargetLowering::ZeroOrOneBooleanContent:
1322     return Val == 1;
1323   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1324     return Val == -1;
1325   }
1326   llvm_unreachable("Invalid boolean contents");
1327 }
1328 
1329 bool llvm::isConstFalseVal(const TargetLowering &TLI, int64_t Val,
1330                            bool IsVector, bool IsFP) {
1331   switch (TLI.getBooleanContents(IsVector, IsFP)) {
1332   case TargetLowering::UndefinedBooleanContent:
1333     return ~Val & 0x1;
1334   case TargetLowering::ZeroOrOneBooleanContent:
1335   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1336     return Val == 0;
1337   }
1338   llvm_unreachable("Invalid boolean contents");
1339 }
1340 
1341 int64_t llvm::getICmpTrueVal(const TargetLowering &TLI, bool IsVector,
1342                              bool IsFP) {
1343   switch (TLI.getBooleanContents(IsVector, IsFP)) {
1344   case TargetLowering::UndefinedBooleanContent:
1345   case TargetLowering::ZeroOrOneBooleanContent:
1346     return 1;
1347   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1348     return -1;
1349   }
1350   llvm_unreachable("Invalid boolean contents");
1351 }
1352 
1353 bool llvm::shouldOptForSize(const MachineBasicBlock &MBB,
1354                             ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
1355   const auto &F = MBB.getParent()->getFunction();
1356   return F.hasOptSize() || F.hasMinSize() ||
1357          llvm::shouldOptimizeForSize(MBB.getBasicBlock(), PSI, BFI);
1358 }
1359 
1360 void llvm::saveUsesAndErase(MachineInstr &MI, MachineRegisterInfo &MRI,
1361                             LostDebugLocObserver *LocObserver,
1362                             SmallInstListTy &DeadInstChain) {
1363   for (MachineOperand &Op : MI.uses()) {
1364     if (Op.isReg() && Op.getReg().isVirtual())
1365       DeadInstChain.insert(MRI.getVRegDef(Op.getReg()));
1366   }
1367   LLVM_DEBUG(dbgs() << MI << "Is dead; erasing.\n");
1368   DeadInstChain.remove(&MI);
1369   MI.eraseFromParent();
1370   if (LocObserver)
1371     LocObserver->checkpoint(false);
1372 }
1373 
1374 void llvm::eraseInstrs(ArrayRef<MachineInstr *> DeadInstrs,
1375                        MachineRegisterInfo &MRI,
1376                        LostDebugLocObserver *LocObserver) {
1377   SmallInstListTy DeadInstChain;
1378   for (MachineInstr *MI : DeadInstrs)
1379     saveUsesAndErase(*MI, MRI, LocObserver, DeadInstChain);
1380 
1381   while (!DeadInstChain.empty()) {
1382     MachineInstr *Inst = DeadInstChain.pop_back_val();
1383     if (!isTriviallyDead(*Inst, MRI))
1384       continue;
1385     saveUsesAndErase(*Inst, MRI, LocObserver, DeadInstChain);
1386   }
1387 }
1388 
1389 void llvm::eraseInstr(MachineInstr &MI, MachineRegisterInfo &MRI,
1390                       LostDebugLocObserver *LocObserver) {
1391   return eraseInstrs({&MI}, MRI, LocObserver);
1392 }
1393 
1394 void llvm::salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI) {
1395   for (auto &Def : MI.defs()) {
1396     assert(Def.isReg() && "Must be a reg");
1397 
1398     SmallVector<MachineOperand *, 16> DbgUsers;
1399     for (auto &MOUse : MRI.use_operands(Def.getReg())) {
1400       MachineInstr *DbgValue = MOUse.getParent();
1401       // Ignore partially formed DBG_VALUEs.
1402       if (DbgValue->isNonListDebugValue() && DbgValue->getNumOperands() == 4) {
1403         DbgUsers.push_back(&MOUse);
1404       }
1405     }
1406 
1407     if (!DbgUsers.empty()) {
1408       salvageDebugInfoForDbgValue(MRI, MI, DbgUsers);
1409     }
1410   }
1411 }
1412