xref: /llvm-project/llvm/lib/CodeGen/GlobalISel/Utils.cpp (revision c34819afe3fe944cb259157f7580d50885bbc68d)
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/MIPatternMatch.h"
19 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
23 #include "llvm/CodeGen/MachineSizeOpts.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/StackProtector.h"
26 #include "llvm/CodeGen/TargetInstrInfo.h"
27 #include "llvm/CodeGen/TargetLowering.h"
28 #include "llvm/CodeGen/TargetPassConfig.h"
29 #include "llvm/CodeGen/TargetRegisterInfo.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/Target/TargetMachine.h"
32 
33 #define DEBUG_TYPE "globalisel-utils"
34 
35 using namespace llvm;
36 using namespace MIPatternMatch;
37 
38 Register llvm::constrainRegToClass(MachineRegisterInfo &MRI,
39                                    const TargetInstrInfo &TII,
40                                    const RegisterBankInfo &RBI, Register Reg,
41                                    const TargetRegisterClass &RegClass) {
42   if (!RBI.constrainGenericRegister(Reg, RegClass, MRI))
43     return MRI.createVirtualRegister(&RegClass);
44 
45   return Reg;
46 }
47 
48 Register llvm::constrainOperandRegClass(
49     const MachineFunction &MF, const TargetRegisterInfo &TRI,
50     MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
51     const RegisterBankInfo &RBI, MachineInstr &InsertPt,
52     const TargetRegisterClass &RegClass, MachineOperand &RegMO) {
53   Register Reg = RegMO.getReg();
54   // Assume physical registers are properly constrained.
55   assert(Register::isVirtualRegister(Reg) && "PhysReg not implemented");
56 
57   Register ConstrainedReg = constrainRegToClass(MRI, TII, RBI, Reg, RegClass);
58   // If we created a new virtual register because the class is not compatible
59   // then create a copy between the new and the old register.
60   if (ConstrainedReg != Reg) {
61     MachineBasicBlock::iterator InsertIt(&InsertPt);
62     MachineBasicBlock &MBB = *InsertPt.getParent();
63     if (RegMO.isUse()) {
64       BuildMI(MBB, InsertIt, InsertPt.getDebugLoc(),
65               TII.get(TargetOpcode::COPY), ConstrainedReg)
66           .addReg(Reg);
67     } else {
68       assert(RegMO.isDef() && "Must be a definition");
69       BuildMI(MBB, std::next(InsertIt), InsertPt.getDebugLoc(),
70               TII.get(TargetOpcode::COPY), Reg)
71           .addReg(ConstrainedReg);
72     }
73     if (GISelChangeObserver *Observer = MF.getObserver()) {
74       Observer->changingInstr(*RegMO.getParent());
75     }
76     RegMO.setReg(ConstrainedReg);
77     if (GISelChangeObserver *Observer = MF.getObserver()) {
78       Observer->changedInstr(*RegMO.getParent());
79     }
80   } else {
81     if (GISelChangeObserver *Observer = MF.getObserver()) {
82       if (!RegMO.isDef()) {
83         MachineInstr *RegDef = MRI.getVRegDef(Reg);
84         Observer->changedInstr(*RegDef);
85       }
86       Observer->changingAllUsesOfReg(MRI, Reg);
87       Observer->finishedChangingAllUsesOfReg();
88     }
89   }
90   return ConstrainedReg;
91 }
92 
93 Register llvm::constrainOperandRegClass(
94     const MachineFunction &MF, const TargetRegisterInfo &TRI,
95     MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
96     const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II,
97     MachineOperand &RegMO, unsigned OpIdx) {
98   Register Reg = RegMO.getReg();
99   // Assume physical registers are properly constrained.
100   assert(Register::isVirtualRegister(Reg) && "PhysReg not implemented");
101 
102   const TargetRegisterClass *RegClass = TII.getRegClass(II, OpIdx, &TRI, MF);
103   // Some of the target independent instructions, like COPY, may not impose any
104   // register class constraints on some of their operands: If it's a use, we can
105   // skip constraining as the instruction defining the register would constrain
106   // it.
107 
108   // We can't constrain unallocatable register classes, because we can't create
109   // virtual registers for these classes, so we need to let targets handled this
110   // case.
111   if (RegClass && !RegClass->isAllocatable())
112     RegClass = TRI.getConstrainedRegClassForOperand(RegMO, MRI);
113 
114   if (!RegClass) {
115     assert((!isTargetSpecificOpcode(II.getOpcode()) || RegMO.isUse()) &&
116            "Register class constraint is required unless either the "
117            "instruction is target independent or the operand is a use");
118     // FIXME: Just bailing out like this here could be not enough, unless we
119     // expect the users of this function to do the right thing for PHIs and
120     // COPY:
121     //   v1 = COPY v0
122     //   v2 = COPY v1
123     // v1 here may end up not being constrained at all. Please notice that to
124     // reproduce the issue we likely need a destination pattern of a selection
125     // rule producing such extra copies, not just an input GMIR with them as
126     // every existing target using selectImpl handles copies before calling it
127     // and they never reach this function.
128     return Reg;
129   }
130   return constrainOperandRegClass(MF, TRI, MRI, TII, RBI, InsertPt, *RegClass,
131                                   RegMO);
132 }
133 
134 bool llvm::constrainSelectedInstRegOperands(MachineInstr &I,
135                                             const TargetInstrInfo &TII,
136                                             const TargetRegisterInfo &TRI,
137                                             const RegisterBankInfo &RBI) {
138   assert(!isPreISelGenericOpcode(I.getOpcode()) &&
139          "A selected instruction is expected");
140   MachineBasicBlock &MBB = *I.getParent();
141   MachineFunction &MF = *MBB.getParent();
142   MachineRegisterInfo &MRI = MF.getRegInfo();
143 
144   for (unsigned OpI = 0, OpE = I.getNumExplicitOperands(); OpI != OpE; ++OpI) {
145     MachineOperand &MO = I.getOperand(OpI);
146 
147     // There's nothing to be done on non-register operands.
148     if (!MO.isReg())
149       continue;
150 
151     LLVM_DEBUG(dbgs() << "Converting operand: " << MO << '\n');
152     assert(MO.isReg() && "Unsupported non-reg operand");
153 
154     Register Reg = MO.getReg();
155     // Physical registers don't need to be constrained.
156     if (Register::isPhysicalRegister(Reg))
157       continue;
158 
159     // Register operands with a value of 0 (e.g. predicate operands) don't need
160     // to be constrained.
161     if (Reg == 0)
162       continue;
163 
164     // If the operand is a vreg, we should constrain its regclass, and only
165     // insert COPYs if that's impossible.
166     // constrainOperandRegClass does that for us.
167     constrainOperandRegClass(MF, TRI, MRI, TII, RBI, I, I.getDesc(), MO, OpI);
168 
169     // Tie uses to defs as indicated in MCInstrDesc if this hasn't already been
170     // done.
171     if (MO.isUse()) {
172       int DefIdx = I.getDesc().getOperandConstraint(OpI, MCOI::TIED_TO);
173       if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefIdx))
174         I.tieOperands(DefIdx, OpI);
175     }
176   }
177   return true;
178 }
179 
180 bool llvm::canReplaceReg(Register DstReg, Register SrcReg,
181                          MachineRegisterInfo &MRI) {
182   // Give up if either DstReg or SrcReg  is a physical register.
183   if (DstReg.isPhysical() || SrcReg.isPhysical())
184     return false;
185   // Give up if the types don't match.
186   if (MRI.getType(DstReg) != MRI.getType(SrcReg))
187     return false;
188   // Replace if either DstReg has no constraints or the register
189   // constraints match.
190   return !MRI.getRegClassOrRegBank(DstReg) ||
191          MRI.getRegClassOrRegBank(DstReg) == MRI.getRegClassOrRegBank(SrcReg);
192 }
193 
194 bool llvm::isTriviallyDead(const MachineInstr &MI,
195                            const MachineRegisterInfo &MRI) {
196   // FIXME: This logical is mostly duplicated with
197   // DeadMachineInstructionElim::isDead. Why is LOCAL_ESCAPE not considered in
198   // MachineInstr::isLabel?
199 
200   // Don't delete frame allocation labels.
201   if (MI.getOpcode() == TargetOpcode::LOCAL_ESCAPE)
202     return false;
203   // LIFETIME markers should be preserved even if they seem dead.
204   if (MI.getOpcode() == TargetOpcode::LIFETIME_START ||
205       MI.getOpcode() == TargetOpcode::LIFETIME_END)
206     return false;
207 
208   // If we can move an instruction, we can remove it.  Otherwise, it has
209   // a side-effect of some sort.
210   bool SawStore = false;
211   if (!MI.isSafeToMove(/*AA=*/nullptr, SawStore) && !MI.isPHI())
212     return false;
213 
214   // Instructions without side-effects are dead iff they only define dead vregs.
215   for (auto &MO : MI.operands()) {
216     if (!MO.isReg() || !MO.isDef())
217       continue;
218 
219     Register Reg = MO.getReg();
220     if (Register::isPhysicalRegister(Reg) || !MRI.use_nodbg_empty(Reg))
221       return false;
222   }
223   return true;
224 }
225 
226 static void reportGISelDiagnostic(DiagnosticSeverity Severity,
227                                   MachineFunction &MF,
228                                   const TargetPassConfig &TPC,
229                                   MachineOptimizationRemarkEmitter &MORE,
230                                   MachineOptimizationRemarkMissed &R) {
231   bool IsFatal = Severity == DS_Error &&
232                  TPC.isGlobalISelAbortEnabled();
233   // Print the function name explicitly if we don't have a debug location (which
234   // makes the diagnostic less useful) or if we're going to emit a raw error.
235   if (!R.getLocation().isValid() || IsFatal)
236     R << (" (in function: " + MF.getName() + ")").str();
237 
238   if (IsFatal)
239     report_fatal_error(R.getMsg());
240   else
241     MORE.emit(R);
242 }
243 
244 void llvm::reportGISelWarning(MachineFunction &MF, const TargetPassConfig &TPC,
245                               MachineOptimizationRemarkEmitter &MORE,
246                               MachineOptimizationRemarkMissed &R) {
247   reportGISelDiagnostic(DS_Warning, MF, TPC, MORE, R);
248 }
249 
250 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC,
251                               MachineOptimizationRemarkEmitter &MORE,
252                               MachineOptimizationRemarkMissed &R) {
253   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
254   reportGISelDiagnostic(DS_Error, MF, TPC, MORE, R);
255 }
256 
257 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC,
258                               MachineOptimizationRemarkEmitter &MORE,
259                               const char *PassName, StringRef Msg,
260                               const MachineInstr &MI) {
261   MachineOptimizationRemarkMissed R(PassName, "GISelFailure: ",
262                                     MI.getDebugLoc(), MI.getParent());
263   R << Msg;
264   // Printing MI is expensive;  only do it if expensive remarks are enabled.
265   if (TPC.isGlobalISelAbortEnabled() || MORE.allowExtraAnalysis(PassName))
266     R << ": " << ore::MNV("Inst", MI);
267   reportGISelFailure(MF, TPC, MORE, R);
268 }
269 
270 Optional<APInt> llvm::getConstantVRegVal(Register VReg,
271                                          const MachineRegisterInfo &MRI) {
272   Optional<ValueAndVReg> ValAndVReg =
273       getConstantVRegValWithLookThrough(VReg, MRI, /*LookThroughInstrs*/ false);
274   assert((!ValAndVReg || ValAndVReg->VReg == VReg) &&
275          "Value found while looking through instrs");
276   if (!ValAndVReg)
277     return None;
278   return ValAndVReg->Value;
279 }
280 
281 Optional<int64_t> llvm::getConstantVRegSExtVal(Register VReg,
282                                                const MachineRegisterInfo &MRI) {
283   Optional<APInt> Val = getConstantVRegVal(VReg, MRI);
284   if (Val && Val->getBitWidth() <= 64)
285     return Val->getSExtValue();
286   return None;
287 }
288 
289 Optional<ValueAndVReg> llvm::getConstantVRegValWithLookThrough(
290     Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs,
291     bool HandleFConstant, bool LookThroughAnyExt) {
292   SmallVector<std::pair<unsigned, unsigned>, 4> SeenOpcodes;
293   MachineInstr *MI;
294   auto IsConstantOpcode = [HandleFConstant](unsigned Opcode) {
295     return Opcode == TargetOpcode::G_CONSTANT ||
296            (HandleFConstant && Opcode == TargetOpcode::G_FCONSTANT);
297   };
298   auto GetImmediateValue = [HandleFConstant,
299                             &MRI](const MachineInstr &MI) -> Optional<APInt> {
300     const MachineOperand &CstVal = MI.getOperand(1);
301     if (!CstVal.isImm() && !CstVal.isCImm() &&
302         (!HandleFConstant || !CstVal.isFPImm()))
303       return None;
304     if (!CstVal.isFPImm()) {
305       unsigned BitWidth =
306           MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
307       APInt Val = CstVal.isImm() ? APInt(BitWidth, CstVal.getImm())
308                                  : CstVal.getCImm()->getValue();
309       assert(Val.getBitWidth() == BitWidth &&
310              "Value bitwidth doesn't match definition type");
311       return Val;
312     }
313     return CstVal.getFPImm()->getValueAPF().bitcastToAPInt();
314   };
315   while ((MI = MRI.getVRegDef(VReg)) && !IsConstantOpcode(MI->getOpcode()) &&
316          LookThroughInstrs) {
317     switch (MI->getOpcode()) {
318     case TargetOpcode::G_ANYEXT:
319       if (!LookThroughAnyExt)
320         return None;
321       LLVM_FALLTHROUGH;
322     case TargetOpcode::G_TRUNC:
323     case TargetOpcode::G_SEXT:
324     case TargetOpcode::G_ZEXT:
325       SeenOpcodes.push_back(std::make_pair(
326           MI->getOpcode(),
327           MRI.getType(MI->getOperand(0).getReg()).getSizeInBits()));
328       VReg = MI->getOperand(1).getReg();
329       break;
330     case TargetOpcode::COPY:
331       VReg = MI->getOperand(1).getReg();
332       if (Register::isPhysicalRegister(VReg))
333         return None;
334       break;
335     case TargetOpcode::G_INTTOPTR:
336       VReg = MI->getOperand(1).getReg();
337       break;
338     default:
339       return None;
340     }
341   }
342   if (!MI || !IsConstantOpcode(MI->getOpcode()))
343     return None;
344 
345   Optional<APInt> MaybeVal = GetImmediateValue(*MI);
346   if (!MaybeVal)
347     return None;
348   APInt &Val = *MaybeVal;
349   while (!SeenOpcodes.empty()) {
350     std::pair<unsigned, unsigned> OpcodeAndSize = SeenOpcodes.pop_back_val();
351     switch (OpcodeAndSize.first) {
352     case TargetOpcode::G_TRUNC:
353       Val = Val.trunc(OpcodeAndSize.second);
354       break;
355     case TargetOpcode::G_ANYEXT:
356     case TargetOpcode::G_SEXT:
357       Val = Val.sext(OpcodeAndSize.second);
358       break;
359     case TargetOpcode::G_ZEXT:
360       Val = Val.zext(OpcodeAndSize.second);
361       break;
362     }
363   }
364 
365   return ValueAndVReg{Val, VReg};
366 }
367 
368 const ConstantFP *
369 llvm::getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI) {
370   MachineInstr *MI = MRI.getVRegDef(VReg);
371   if (TargetOpcode::G_FCONSTANT != MI->getOpcode())
372     return nullptr;
373   return MI->getOperand(1).getFPImm();
374 }
375 
376 Optional<DefinitionAndSourceRegister>
377 llvm::getDefSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI) {
378   Register DefSrcReg = Reg;
379   auto *DefMI = MRI.getVRegDef(Reg);
380   auto DstTy = MRI.getType(DefMI->getOperand(0).getReg());
381   if (!DstTy.isValid())
382     return None;
383   unsigned Opc = DefMI->getOpcode();
384   while (Opc == TargetOpcode::COPY || isPreISelGenericOptimizationHint(Opc)) {
385     Register SrcReg = DefMI->getOperand(1).getReg();
386     auto SrcTy = MRI.getType(SrcReg);
387     if (!SrcTy.isValid())
388       break;
389     DefMI = MRI.getVRegDef(SrcReg);
390     DefSrcReg = SrcReg;
391     Opc = DefMI->getOpcode();
392   }
393   return DefinitionAndSourceRegister{DefMI, DefSrcReg};
394 }
395 
396 MachineInstr *llvm::getDefIgnoringCopies(Register Reg,
397                                          const MachineRegisterInfo &MRI) {
398   Optional<DefinitionAndSourceRegister> DefSrcReg =
399       getDefSrcRegIgnoringCopies(Reg, MRI);
400   return DefSrcReg ? DefSrcReg->MI : nullptr;
401 }
402 
403 Register llvm::getSrcRegIgnoringCopies(Register Reg,
404                                        const MachineRegisterInfo &MRI) {
405   Optional<DefinitionAndSourceRegister> DefSrcReg =
406       getDefSrcRegIgnoringCopies(Reg, MRI);
407   return DefSrcReg ? DefSrcReg->Reg : Register();
408 }
409 
410 MachineInstr *llvm::getOpcodeDef(unsigned Opcode, Register Reg,
411                                  const MachineRegisterInfo &MRI) {
412   MachineInstr *DefMI = getDefIgnoringCopies(Reg, MRI);
413   return DefMI && DefMI->getOpcode() == Opcode ? DefMI : nullptr;
414 }
415 
416 APFloat llvm::getAPFloatFromSize(double Val, unsigned Size) {
417   if (Size == 32)
418     return APFloat(float(Val));
419   if (Size == 64)
420     return APFloat(Val);
421   if (Size != 16)
422     llvm_unreachable("Unsupported FPConstant size");
423   bool Ignored;
424   APFloat APF(Val);
425   APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &Ignored);
426   return APF;
427 }
428 
429 Optional<APInt> llvm::ConstantFoldBinOp(unsigned Opcode, const Register Op1,
430                                         const Register Op2,
431                                         const MachineRegisterInfo &MRI) {
432   auto MaybeOp2Cst = getConstantVRegVal(Op2, MRI);
433   if (!MaybeOp2Cst)
434     return None;
435 
436   auto MaybeOp1Cst = getConstantVRegVal(Op1, MRI);
437   if (!MaybeOp1Cst)
438     return None;
439 
440   const APInt &C1 = *MaybeOp1Cst;
441   const APInt &C2 = *MaybeOp2Cst;
442   switch (Opcode) {
443   default:
444     break;
445   case TargetOpcode::G_ADD:
446     return C1 + C2;
447   case TargetOpcode::G_AND:
448     return C1 & C2;
449   case TargetOpcode::G_ASHR:
450     return C1.ashr(C2);
451   case TargetOpcode::G_LSHR:
452     return C1.lshr(C2);
453   case TargetOpcode::G_MUL:
454     return C1 * C2;
455   case TargetOpcode::G_OR:
456     return C1 | C2;
457   case TargetOpcode::G_SHL:
458     return C1 << C2;
459   case TargetOpcode::G_SUB:
460     return C1 - C2;
461   case TargetOpcode::G_XOR:
462     return C1 ^ C2;
463   case TargetOpcode::G_UDIV:
464     if (!C2.getBoolValue())
465       break;
466     return C1.udiv(C2);
467   case TargetOpcode::G_SDIV:
468     if (!C2.getBoolValue())
469       break;
470     return C1.sdiv(C2);
471   case TargetOpcode::G_UREM:
472     if (!C2.getBoolValue())
473       break;
474     return C1.urem(C2);
475   case TargetOpcode::G_SREM:
476     if (!C2.getBoolValue())
477       break;
478     return C1.srem(C2);
479   }
480 
481   return None;
482 }
483 
484 bool llvm::isKnownNeverNaN(Register Val, const MachineRegisterInfo &MRI,
485                            bool SNaN) {
486   const MachineInstr *DefMI = MRI.getVRegDef(Val);
487   if (!DefMI)
488     return false;
489 
490   const TargetMachine& TM = DefMI->getMF()->getTarget();
491   if (DefMI->getFlag(MachineInstr::FmNoNans) || TM.Options.NoNaNsFPMath)
492     return true;
493 
494   // If the value is a constant, we can obviously see if it is a NaN or not.
495   if (const ConstantFP *FPVal = getConstantFPVRegVal(Val, MRI)) {
496     return !FPVal->getValueAPF().isNaN() ||
497            (SNaN && !FPVal->getValueAPF().isSignaling());
498   }
499 
500   if (DefMI->getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
501     for (const auto &Op : DefMI->uses())
502       if (!isKnownNeverNaN(Op.getReg(), MRI, SNaN))
503         return false;
504     return true;
505   }
506 
507   switch (DefMI->getOpcode()) {
508   default:
509     break;
510   case TargetOpcode::G_FMINNUM_IEEE:
511   case TargetOpcode::G_FMAXNUM_IEEE: {
512     if (SNaN)
513       return true;
514     // This can return a NaN if either operand is an sNaN, or if both operands
515     // are NaN.
516     return (isKnownNeverNaN(DefMI->getOperand(1).getReg(), MRI) &&
517             isKnownNeverSNaN(DefMI->getOperand(2).getReg(), MRI)) ||
518            (isKnownNeverSNaN(DefMI->getOperand(1).getReg(), MRI) &&
519             isKnownNeverNaN(DefMI->getOperand(2).getReg(), MRI));
520   }
521   case TargetOpcode::G_FMINNUM:
522   case TargetOpcode::G_FMAXNUM: {
523     // Only one needs to be known not-nan, since it will be returned if the
524     // other ends up being one.
525     return isKnownNeverNaN(DefMI->getOperand(1).getReg(), MRI, SNaN) ||
526            isKnownNeverNaN(DefMI->getOperand(2).getReg(), MRI, SNaN);
527   }
528   }
529 
530   if (SNaN) {
531     // FP operations quiet. For now, just handle the ones inserted during
532     // legalization.
533     switch (DefMI->getOpcode()) {
534     case TargetOpcode::G_FPEXT:
535     case TargetOpcode::G_FPTRUNC:
536     case TargetOpcode::G_FCANONICALIZE:
537       return true;
538     default:
539       return false;
540     }
541   }
542 
543   return false;
544 }
545 
546 Align llvm::inferAlignFromPtrInfo(MachineFunction &MF,
547                                   const MachinePointerInfo &MPO) {
548   auto PSV = MPO.V.dyn_cast<const PseudoSourceValue *>();
549   if (auto FSPV = dyn_cast_or_null<FixedStackPseudoSourceValue>(PSV)) {
550     MachineFrameInfo &MFI = MF.getFrameInfo();
551     return commonAlignment(MFI.getObjectAlign(FSPV->getFrameIndex()),
552                            MPO.Offset);
553   }
554 
555   if (const Value *V = MPO.V.dyn_cast<const Value *>()) {
556     const Module *M = MF.getFunction().getParent();
557     return V->getPointerAlignment(M->getDataLayout());
558   }
559 
560   return Align(1);
561 }
562 
563 Register llvm::getFunctionLiveInPhysReg(MachineFunction &MF,
564                                         const TargetInstrInfo &TII,
565                                         MCRegister PhysReg,
566                                         const TargetRegisterClass &RC,
567                                         LLT RegTy) {
568   DebugLoc DL; // FIXME: Is no location the right choice?
569   MachineBasicBlock &EntryMBB = MF.front();
570   MachineRegisterInfo &MRI = MF.getRegInfo();
571   Register LiveIn = MRI.getLiveInVirtReg(PhysReg);
572   if (LiveIn) {
573     MachineInstr *Def = MRI.getVRegDef(LiveIn);
574     if (Def) {
575       // FIXME: Should the verifier check this is in the entry block?
576       assert(Def->getParent() == &EntryMBB && "live-in copy not in entry block");
577       return LiveIn;
578     }
579 
580     // It's possible the incoming argument register and copy was added during
581     // lowering, but later deleted due to being/becoming dead. If this happens,
582     // re-insert the copy.
583   } else {
584     // The live in register was not present, so add it.
585     LiveIn = MF.addLiveIn(PhysReg, &RC);
586     if (RegTy.isValid())
587       MRI.setType(LiveIn, RegTy);
588   }
589 
590   BuildMI(EntryMBB, EntryMBB.begin(), DL, TII.get(TargetOpcode::COPY), LiveIn)
591     .addReg(PhysReg);
592   if (!EntryMBB.isLiveIn(PhysReg))
593     EntryMBB.addLiveIn(PhysReg);
594   return LiveIn;
595 }
596 
597 Optional<APInt> llvm::ConstantFoldExtOp(unsigned Opcode, const Register Op1,
598                                         uint64_t Imm,
599                                         const MachineRegisterInfo &MRI) {
600   auto MaybeOp1Cst = getConstantVRegVal(Op1, MRI);
601   if (MaybeOp1Cst) {
602     switch (Opcode) {
603     default:
604       break;
605     case TargetOpcode::G_SEXT_INREG: {
606       LLT Ty = MRI.getType(Op1);
607       return MaybeOp1Cst->trunc(Imm).sext(Ty.getScalarSizeInBits());
608     }
609     }
610   }
611   return None;
612 }
613 
614 bool llvm::isKnownToBeAPowerOfTwo(Register Reg, const MachineRegisterInfo &MRI,
615                                   GISelKnownBits *KB) {
616   Optional<DefinitionAndSourceRegister> DefSrcReg =
617       getDefSrcRegIgnoringCopies(Reg, MRI);
618   if (!DefSrcReg)
619     return false;
620 
621   const MachineInstr &MI = *DefSrcReg->MI;
622   const LLT Ty = MRI.getType(Reg);
623 
624   switch (MI.getOpcode()) {
625   case TargetOpcode::G_CONSTANT: {
626     unsigned BitWidth = Ty.getScalarSizeInBits();
627     const ConstantInt *CI = MI.getOperand(1).getCImm();
628     return CI->getValue().zextOrTrunc(BitWidth).isPowerOf2();
629   }
630   case TargetOpcode::G_SHL: {
631     // A left-shift of a constant one will have exactly one bit set because
632     // shifting the bit off the end is undefined.
633 
634     // TODO: Constant splat
635     if (auto ConstLHS = getConstantVRegVal(MI.getOperand(1).getReg(), MRI)) {
636       if (*ConstLHS == 1)
637         return true;
638     }
639 
640     break;
641   }
642   case TargetOpcode::G_LSHR: {
643     if (auto ConstLHS = getConstantVRegVal(MI.getOperand(1).getReg(), MRI)) {
644       if (ConstLHS->isSignMask())
645         return true;
646     }
647 
648     break;
649   }
650   case TargetOpcode::G_BUILD_VECTOR: {
651     // TODO: Probably should have a recursion depth guard since you could have
652     // bitcasted vector elements.
653     for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) {
654       if (!isKnownToBeAPowerOfTwo(MI.getOperand(I).getReg(), MRI, KB))
655         return false;
656     }
657 
658     return true;
659   }
660   case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
661     // Only handle constants since we would need to know if number of leading
662     // zeros is greater than the truncation amount.
663     const unsigned BitWidth = Ty.getScalarSizeInBits();
664     for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) {
665       auto Const = getConstantVRegVal(MI.getOperand(I).getReg(), MRI);
666       if (!Const || !Const->zextOrTrunc(BitWidth).isPowerOf2())
667         return false;
668     }
669 
670     return true;
671   }
672   default:
673     break;
674   }
675 
676   if (!KB)
677     return false;
678 
679   // More could be done here, though the above checks are enough
680   // to handle some common cases.
681 
682   // Fall back to computeKnownBits to catch other known cases.
683   KnownBits Known = KB->getKnownBits(Reg);
684   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
685 }
686 
687 void llvm::getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU) {
688   AU.addPreserved<StackProtector>();
689 }
690 
691 static unsigned getLCMSize(unsigned OrigSize, unsigned TargetSize) {
692   unsigned Mul = OrigSize * TargetSize;
693   unsigned GCDSize = greatestCommonDivisor(OrigSize, TargetSize);
694   return Mul / GCDSize;
695 }
696 
697 LLT llvm::getLCMType(LLT OrigTy, LLT TargetTy) {
698   const unsigned OrigSize = OrigTy.getSizeInBits();
699   const unsigned TargetSize = TargetTy.getSizeInBits();
700 
701   if (OrigSize == TargetSize)
702     return OrigTy;
703 
704   if (OrigTy.isVector()) {
705     const LLT OrigElt = OrigTy.getElementType();
706 
707     if (TargetTy.isVector()) {
708       const LLT TargetElt = TargetTy.getElementType();
709 
710       if (OrigElt.getSizeInBits() == TargetElt.getSizeInBits()) {
711         int GCDElts = greatestCommonDivisor(OrigTy.getNumElements(),
712                                             TargetTy.getNumElements());
713         // Prefer the original element type.
714         int Mul = OrigTy.getNumElements() * TargetTy.getNumElements();
715         return LLT::vector(Mul / GCDElts, OrigTy.getElementType());
716       }
717     } else {
718       if (OrigElt.getSizeInBits() == TargetSize)
719         return OrigTy;
720     }
721 
722     unsigned LCMSize = getLCMSize(OrigSize, TargetSize);
723     return LLT::vector(LCMSize / OrigElt.getSizeInBits(), OrigElt);
724   }
725 
726   if (TargetTy.isVector()) {
727     unsigned LCMSize = getLCMSize(OrigSize, TargetSize);
728     return LLT::vector(LCMSize / OrigSize, OrigTy);
729   }
730 
731   unsigned LCMSize = getLCMSize(OrigSize, TargetSize);
732 
733   // Preserve pointer types.
734   if (LCMSize == OrigSize)
735     return OrigTy;
736   if (LCMSize == TargetSize)
737     return TargetTy;
738 
739   return LLT::scalar(LCMSize);
740 }
741 
742 LLT llvm::getGCDType(LLT OrigTy, LLT TargetTy) {
743   const unsigned OrigSize = OrigTy.getSizeInBits();
744   const unsigned TargetSize = TargetTy.getSizeInBits();
745 
746   if (OrigSize == TargetSize)
747     return OrigTy;
748 
749   if (OrigTy.isVector()) {
750     LLT OrigElt = OrigTy.getElementType();
751     if (TargetTy.isVector()) {
752       LLT TargetElt = TargetTy.getElementType();
753       if (OrigElt.getSizeInBits() == TargetElt.getSizeInBits()) {
754         int GCD = greatestCommonDivisor(OrigTy.getNumElements(),
755                                         TargetTy.getNumElements());
756         return LLT::scalarOrVector(GCD, OrigElt);
757       }
758     } else {
759       // If the source is a vector of pointers, return a pointer element.
760       if (OrigElt.getSizeInBits() == TargetSize)
761         return OrigElt;
762     }
763 
764     unsigned GCD = greatestCommonDivisor(OrigSize, TargetSize);
765     if (GCD == OrigElt.getSizeInBits())
766       return OrigElt;
767 
768     // If we can't produce the original element type, we have to use a smaller
769     // scalar.
770     if (GCD < OrigElt.getSizeInBits())
771       return LLT::scalar(GCD);
772     return LLT::vector(GCD / OrigElt.getSizeInBits(), OrigElt);
773   }
774 
775   if (TargetTy.isVector()) {
776     // Try to preserve the original element type.
777     LLT TargetElt = TargetTy.getElementType();
778     if (TargetElt.getSizeInBits() == OrigSize)
779       return OrigTy;
780   }
781 
782   unsigned GCD = greatestCommonDivisor(OrigSize, TargetSize);
783   return LLT::scalar(GCD);
784 }
785 
786 Optional<int> llvm::getSplatIndex(MachineInstr &MI) {
787   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
788          "Only G_SHUFFLE_VECTOR can have a splat index!");
789   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
790   auto FirstDefinedIdx = find_if(Mask, [](int Elt) { return Elt >= 0; });
791 
792   // If all elements are undefined, this shuffle can be considered a splat.
793   // Return 0 for better potential for callers to simplify.
794   if (FirstDefinedIdx == Mask.end())
795     return 0;
796 
797   // Make sure all remaining elements are either undef or the same
798   // as the first non-undef value.
799   int SplatValue = *FirstDefinedIdx;
800   if (any_of(make_range(std::next(FirstDefinedIdx), Mask.end()),
801              [&SplatValue](int Elt) { return Elt >= 0 && Elt != SplatValue; }))
802     return None;
803 
804   return SplatValue;
805 }
806 
807 static bool isBuildVectorOp(unsigned Opcode) {
808   return Opcode == TargetOpcode::G_BUILD_VECTOR ||
809          Opcode == TargetOpcode::G_BUILD_VECTOR_TRUNC;
810 }
811 
812 // TODO: Handle mixed undef elements.
813 static bool isBuildVectorConstantSplat(const MachineInstr &MI,
814                                        const MachineRegisterInfo &MRI,
815                                        int64_t SplatValue) {
816   if (!isBuildVectorOp(MI.getOpcode()))
817     return false;
818 
819   const unsigned NumOps = MI.getNumOperands();
820   for (unsigned I = 1; I != NumOps; ++I) {
821     Register Element = MI.getOperand(I).getReg();
822     if (!mi_match(Element, MRI, m_SpecificICst(SplatValue)))
823       return false;
824   }
825 
826   return true;
827 }
828 
829 Optional<int64_t>
830 llvm::getBuildVectorConstantSplat(const MachineInstr &MI,
831                                   const MachineRegisterInfo &MRI) {
832   if (!isBuildVectorOp(MI.getOpcode()))
833     return None;
834 
835   const unsigned NumOps = MI.getNumOperands();
836   Optional<int64_t> Scalar;
837   for (unsigned I = 1; I != NumOps; ++I) {
838     Register Element = MI.getOperand(I).getReg();
839     int64_t ElementValue;
840     if (!mi_match(Element, MRI, m_ICst(ElementValue)))
841       return None;
842     if (!Scalar)
843       Scalar = ElementValue;
844     else if (*Scalar != ElementValue)
845       return None;
846   }
847 
848   return Scalar;
849 }
850 
851 bool llvm::isBuildVectorAllZeros(const MachineInstr &MI,
852                                  const MachineRegisterInfo &MRI) {
853   return isBuildVectorConstantSplat(MI, MRI, 0);
854 }
855 
856 bool llvm::isBuildVectorAllOnes(const MachineInstr &MI,
857                                 const MachineRegisterInfo &MRI) {
858   return isBuildVectorConstantSplat(MI, MRI, -1);
859 }
860 
861 Optional<RegOrConstant> llvm::getVectorSplat(const MachineInstr &MI,
862                                              const MachineRegisterInfo &MRI) {
863   unsigned Opc = MI.getOpcode();
864   if (!isBuildVectorOp(Opc))
865     return None;
866   if (auto Splat = getBuildVectorConstantSplat(MI, MRI))
867     return RegOrConstant(*Splat);
868   auto Reg = MI.getOperand(1).getReg();
869   if (any_of(make_range(MI.operands_begin() + 2, MI.operands_end()),
870              [&Reg](const MachineOperand &Op) { return Op.getReg() != Reg; }))
871     return None;
872   return RegOrConstant(Reg);
873 }
874 
875 bool llvm::isConstTrueVal(const TargetLowering &TLI, int64_t Val, bool IsVector,
876                           bool IsFP) {
877   switch (TLI.getBooleanContents(IsVector, IsFP)) {
878   case TargetLowering::UndefinedBooleanContent:
879     return Val & 0x1;
880   case TargetLowering::ZeroOrOneBooleanContent:
881     return Val == 1;
882   case TargetLowering::ZeroOrNegativeOneBooleanContent:
883     return Val == -1;
884   }
885   llvm_unreachable("Invalid boolean contents");
886 }
887 
888 int64_t llvm::getICmpTrueVal(const TargetLowering &TLI, bool IsVector,
889                              bool IsFP) {
890   switch (TLI.getBooleanContents(IsVector, IsFP)) {
891   case TargetLowering::UndefinedBooleanContent:
892   case TargetLowering::ZeroOrOneBooleanContent:
893     return 1;
894   case TargetLowering::ZeroOrNegativeOneBooleanContent:
895     return -1;
896   }
897   llvm_unreachable("Invalid boolean contents");
898 }
899 
900 bool llvm::shouldOptForSize(const MachineBasicBlock &MBB,
901                             ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
902   const auto &F = MBB.getParent()->getFunction();
903   return F.hasOptSize() || F.hasMinSize() ||
904          llvm::shouldOptimizeForSize(MBB.getBasicBlock(), PSI, BFI);
905 }
906