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