xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
1 //===-- llvm/CodeGen/GlobalISel/LegalizerHelper.cpp -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file This file implements the LegalizerHelper class to legalize
10 /// individual instructions and the LegalizeMachineIR wrapper pass for the
11 /// primary legalization.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h"
16 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
17 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
18 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/TargetFrameLowering.h"
21 #include "llvm/CodeGen/TargetInstrInfo.h"
22 #include "llvm/CodeGen/TargetLowering.h"
23 #include "llvm/CodeGen/TargetSubtargetInfo.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/raw_ostream.h"
27 
28 #define DEBUG_TYPE "legalizer"
29 
30 using namespace llvm;
31 using namespace LegalizeActions;
32 
33 /// Try to break down \p OrigTy into \p NarrowTy sized pieces.
34 ///
35 /// Returns the number of \p NarrowTy elements needed to reconstruct \p OrigTy,
36 /// with any leftover piece as type \p LeftoverTy
37 ///
38 /// Returns -1 in the first element of the pair if the breakdown is not
39 /// satisfiable.
40 static std::pair<int, int>
41 getNarrowTypeBreakDown(LLT OrigTy, LLT NarrowTy, LLT &LeftoverTy) {
42   assert(!LeftoverTy.isValid() && "this is an out argument");
43 
44   unsigned Size = OrigTy.getSizeInBits();
45   unsigned NarrowSize = NarrowTy.getSizeInBits();
46   unsigned NumParts = Size / NarrowSize;
47   unsigned LeftoverSize = Size - NumParts * NarrowSize;
48   assert(Size > NarrowSize);
49 
50   if (LeftoverSize == 0)
51     return {NumParts, 0};
52 
53   if (NarrowTy.isVector()) {
54     unsigned EltSize = OrigTy.getScalarSizeInBits();
55     if (LeftoverSize % EltSize != 0)
56       return {-1, -1};
57     LeftoverTy = LLT::scalarOrVector(LeftoverSize / EltSize, EltSize);
58   } else {
59     LeftoverTy = LLT::scalar(LeftoverSize);
60   }
61 
62   int NumLeftover = LeftoverSize / LeftoverTy.getSizeInBits();
63   return std::make_pair(NumParts, NumLeftover);
64 }
65 
66 static Type *getFloatTypeForLLT(LLVMContext &Ctx, LLT Ty) {
67 
68   if (!Ty.isScalar())
69     return nullptr;
70 
71   switch (Ty.getSizeInBits()) {
72   case 16:
73     return Type::getHalfTy(Ctx);
74   case 32:
75     return Type::getFloatTy(Ctx);
76   case 64:
77     return Type::getDoubleTy(Ctx);
78   case 128:
79     return Type::getFP128Ty(Ctx);
80   default:
81     return nullptr;
82   }
83 }
84 
85 LegalizerHelper::LegalizerHelper(MachineFunction &MF,
86                                  GISelChangeObserver &Observer,
87                                  MachineIRBuilder &Builder)
88     : MIRBuilder(Builder), Observer(Observer), MRI(MF.getRegInfo()),
89       LI(*MF.getSubtarget().getLegalizerInfo()) {
90   MIRBuilder.setChangeObserver(Observer);
91 }
92 
93 LegalizerHelper::LegalizerHelper(MachineFunction &MF, const LegalizerInfo &LI,
94                                  GISelChangeObserver &Observer,
95                                  MachineIRBuilder &B)
96     : MIRBuilder(B), Observer(Observer), MRI(MF.getRegInfo()), LI(LI) {
97   MIRBuilder.setChangeObserver(Observer);
98 }
99 LegalizerHelper::LegalizeResult
100 LegalizerHelper::legalizeInstrStep(MachineInstr &MI) {
101   LLVM_DEBUG(dbgs() << "Legalizing: " << MI);
102 
103   MIRBuilder.setInstrAndDebugLoc(MI);
104 
105   if (MI.getOpcode() == TargetOpcode::G_INTRINSIC ||
106       MI.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS)
107     return LI.legalizeIntrinsic(*this, MI) ? Legalized : UnableToLegalize;
108   auto Step = LI.getAction(MI, MRI);
109   switch (Step.Action) {
110   case Legal:
111     LLVM_DEBUG(dbgs() << ".. Already legal\n");
112     return AlreadyLegal;
113   case Libcall:
114     LLVM_DEBUG(dbgs() << ".. Convert to libcall\n");
115     return libcall(MI);
116   case NarrowScalar:
117     LLVM_DEBUG(dbgs() << ".. Narrow scalar\n");
118     return narrowScalar(MI, Step.TypeIdx, Step.NewType);
119   case WidenScalar:
120     LLVM_DEBUG(dbgs() << ".. Widen scalar\n");
121     return widenScalar(MI, Step.TypeIdx, Step.NewType);
122   case Bitcast:
123     LLVM_DEBUG(dbgs() << ".. Bitcast type\n");
124     return bitcast(MI, Step.TypeIdx, Step.NewType);
125   case Lower:
126     LLVM_DEBUG(dbgs() << ".. Lower\n");
127     return lower(MI, Step.TypeIdx, Step.NewType);
128   case FewerElements:
129     LLVM_DEBUG(dbgs() << ".. Reduce number of elements\n");
130     return fewerElementsVector(MI, Step.TypeIdx, Step.NewType);
131   case MoreElements:
132     LLVM_DEBUG(dbgs() << ".. Increase number of elements\n");
133     return moreElementsVector(MI, Step.TypeIdx, Step.NewType);
134   case Custom:
135     LLVM_DEBUG(dbgs() << ".. Custom legalization\n");
136     return LI.legalizeCustom(*this, MI) ? Legalized : UnableToLegalize;
137   default:
138     LLVM_DEBUG(dbgs() << ".. Unable to legalize\n");
139     return UnableToLegalize;
140   }
141 }
142 
143 void LegalizerHelper::extractParts(Register Reg, LLT Ty, int NumParts,
144                                    SmallVectorImpl<Register> &VRegs) {
145   for (int i = 0; i < NumParts; ++i)
146     VRegs.push_back(MRI.createGenericVirtualRegister(Ty));
147   MIRBuilder.buildUnmerge(VRegs, Reg);
148 }
149 
150 bool LegalizerHelper::extractParts(Register Reg, LLT RegTy,
151                                    LLT MainTy, LLT &LeftoverTy,
152                                    SmallVectorImpl<Register> &VRegs,
153                                    SmallVectorImpl<Register> &LeftoverRegs) {
154   assert(!LeftoverTy.isValid() && "this is an out argument");
155 
156   unsigned RegSize = RegTy.getSizeInBits();
157   unsigned MainSize = MainTy.getSizeInBits();
158   unsigned NumParts = RegSize / MainSize;
159   unsigned LeftoverSize = RegSize - NumParts * MainSize;
160 
161   // Use an unmerge when possible.
162   if (LeftoverSize == 0) {
163     for (unsigned I = 0; I < NumParts; ++I)
164       VRegs.push_back(MRI.createGenericVirtualRegister(MainTy));
165     MIRBuilder.buildUnmerge(VRegs, Reg);
166     return true;
167   }
168 
169   if (MainTy.isVector()) {
170     unsigned EltSize = MainTy.getScalarSizeInBits();
171     if (LeftoverSize % EltSize != 0)
172       return false;
173     LeftoverTy = LLT::scalarOrVector(LeftoverSize / EltSize, EltSize);
174   } else {
175     LeftoverTy = LLT::scalar(LeftoverSize);
176   }
177 
178   // For irregular sizes, extract the individual parts.
179   for (unsigned I = 0; I != NumParts; ++I) {
180     Register NewReg = MRI.createGenericVirtualRegister(MainTy);
181     VRegs.push_back(NewReg);
182     MIRBuilder.buildExtract(NewReg, Reg, MainSize * I);
183   }
184 
185   for (unsigned Offset = MainSize * NumParts; Offset < RegSize;
186        Offset += LeftoverSize) {
187     Register NewReg = MRI.createGenericVirtualRegister(LeftoverTy);
188     LeftoverRegs.push_back(NewReg);
189     MIRBuilder.buildExtract(NewReg, Reg, Offset);
190   }
191 
192   return true;
193 }
194 
195 void LegalizerHelper::insertParts(Register DstReg,
196                                   LLT ResultTy, LLT PartTy,
197                                   ArrayRef<Register> PartRegs,
198                                   LLT LeftoverTy,
199                                   ArrayRef<Register> LeftoverRegs) {
200   if (!LeftoverTy.isValid()) {
201     assert(LeftoverRegs.empty());
202 
203     if (!ResultTy.isVector()) {
204       MIRBuilder.buildMerge(DstReg, PartRegs);
205       return;
206     }
207 
208     if (PartTy.isVector())
209       MIRBuilder.buildConcatVectors(DstReg, PartRegs);
210     else
211       MIRBuilder.buildBuildVector(DstReg, PartRegs);
212     return;
213   }
214 
215   unsigned PartSize = PartTy.getSizeInBits();
216   unsigned LeftoverPartSize = LeftoverTy.getSizeInBits();
217 
218   Register CurResultReg = MRI.createGenericVirtualRegister(ResultTy);
219   MIRBuilder.buildUndef(CurResultReg);
220 
221   unsigned Offset = 0;
222   for (Register PartReg : PartRegs) {
223     Register NewResultReg = MRI.createGenericVirtualRegister(ResultTy);
224     MIRBuilder.buildInsert(NewResultReg, CurResultReg, PartReg, Offset);
225     CurResultReg = NewResultReg;
226     Offset += PartSize;
227   }
228 
229   for (unsigned I = 0, E = LeftoverRegs.size(); I != E; ++I) {
230     // Use the original output register for the final insert to avoid a copy.
231     Register NewResultReg = (I + 1 == E) ?
232       DstReg : MRI.createGenericVirtualRegister(ResultTy);
233 
234     MIRBuilder.buildInsert(NewResultReg, CurResultReg, LeftoverRegs[I], Offset);
235     CurResultReg = NewResultReg;
236     Offset += LeftoverPartSize;
237   }
238 }
239 
240 /// Return the result registers of G_UNMERGE_VALUES \p MI in \p Regs
241 static void getUnmergeResults(SmallVectorImpl<Register> &Regs,
242                               const MachineInstr &MI) {
243   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES);
244 
245   const int NumResults = MI.getNumOperands() - 1;
246   Regs.resize(NumResults);
247   for (int I = 0; I != NumResults; ++I)
248     Regs[I] = MI.getOperand(I).getReg();
249 }
250 
251 LLT LegalizerHelper::extractGCDType(SmallVectorImpl<Register> &Parts, LLT DstTy,
252                                     LLT NarrowTy, Register SrcReg) {
253   LLT SrcTy = MRI.getType(SrcReg);
254 
255   LLT GCDTy = getGCDType(DstTy, getGCDType(SrcTy, NarrowTy));
256   if (SrcTy == GCDTy) {
257     // If the source already evenly divides the result type, we don't need to do
258     // anything.
259     Parts.push_back(SrcReg);
260   } else {
261     // Need to split into common type sized pieces.
262     auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
263     getUnmergeResults(Parts, *Unmerge);
264   }
265 
266   return GCDTy;
267 }
268 
269 LLT LegalizerHelper::buildLCMMergePieces(LLT DstTy, LLT NarrowTy, LLT GCDTy,
270                                          SmallVectorImpl<Register> &VRegs,
271                                          unsigned PadStrategy) {
272   LLT LCMTy = getLCMType(DstTy, NarrowTy);
273 
274   int NumParts = LCMTy.getSizeInBits() / NarrowTy.getSizeInBits();
275   int NumSubParts = NarrowTy.getSizeInBits() / GCDTy.getSizeInBits();
276   int NumOrigSrc = VRegs.size();
277 
278   Register PadReg;
279 
280   // Get a value we can use to pad the source value if the sources won't evenly
281   // cover the result type.
282   if (NumOrigSrc < NumParts * NumSubParts) {
283     if (PadStrategy == TargetOpcode::G_ZEXT)
284       PadReg = MIRBuilder.buildConstant(GCDTy, 0).getReg(0);
285     else if (PadStrategy == TargetOpcode::G_ANYEXT)
286       PadReg = MIRBuilder.buildUndef(GCDTy).getReg(0);
287     else {
288       assert(PadStrategy == TargetOpcode::G_SEXT);
289 
290       // Shift the sign bit of the low register through the high register.
291       auto ShiftAmt =
292         MIRBuilder.buildConstant(LLT::scalar(64), GCDTy.getSizeInBits() - 1);
293       PadReg = MIRBuilder.buildAShr(GCDTy, VRegs.back(), ShiftAmt).getReg(0);
294     }
295   }
296 
297   // Registers for the final merge to be produced.
298   SmallVector<Register, 4> Remerge(NumParts);
299 
300   // Registers needed for intermediate merges, which will be merged into a
301   // source for Remerge.
302   SmallVector<Register, 4> SubMerge(NumSubParts);
303 
304   // Once we've fully read off the end of the original source bits, we can reuse
305   // the same high bits for remaining padding elements.
306   Register AllPadReg;
307 
308   // Build merges to the LCM type to cover the original result type.
309   for (int I = 0; I != NumParts; ++I) {
310     bool AllMergePartsArePadding = true;
311 
312     // Build the requested merges to the requested type.
313     for (int J = 0; J != NumSubParts; ++J) {
314       int Idx = I * NumSubParts + J;
315       if (Idx >= NumOrigSrc) {
316         SubMerge[J] = PadReg;
317         continue;
318       }
319 
320       SubMerge[J] = VRegs[Idx];
321 
322       // There are meaningful bits here we can't reuse later.
323       AllMergePartsArePadding = false;
324     }
325 
326     // If we've filled up a complete piece with padding bits, we can directly
327     // emit the natural sized constant if applicable, rather than a merge of
328     // smaller constants.
329     if (AllMergePartsArePadding && !AllPadReg) {
330       if (PadStrategy == TargetOpcode::G_ANYEXT)
331         AllPadReg = MIRBuilder.buildUndef(NarrowTy).getReg(0);
332       else if (PadStrategy == TargetOpcode::G_ZEXT)
333         AllPadReg = MIRBuilder.buildConstant(NarrowTy, 0).getReg(0);
334 
335       // If this is a sign extension, we can't materialize a trivial constant
336       // with the right type and have to produce a merge.
337     }
338 
339     if (AllPadReg) {
340       // Avoid creating additional instructions if we're just adding additional
341       // copies of padding bits.
342       Remerge[I] = AllPadReg;
343       continue;
344     }
345 
346     if (NumSubParts == 1)
347       Remerge[I] = SubMerge[0];
348     else
349       Remerge[I] = MIRBuilder.buildMerge(NarrowTy, SubMerge).getReg(0);
350 
351     // In the sign extend padding case, re-use the first all-signbit merge.
352     if (AllMergePartsArePadding && !AllPadReg)
353       AllPadReg = Remerge[I];
354   }
355 
356   VRegs = std::move(Remerge);
357   return LCMTy;
358 }
359 
360 void LegalizerHelper::buildWidenedRemergeToDst(Register DstReg, LLT LCMTy,
361                                                ArrayRef<Register> RemergeRegs) {
362   LLT DstTy = MRI.getType(DstReg);
363 
364   // Create the merge to the widened source, and extract the relevant bits into
365   // the result.
366 
367   if (DstTy == LCMTy) {
368     MIRBuilder.buildMerge(DstReg, RemergeRegs);
369     return;
370   }
371 
372   auto Remerge = MIRBuilder.buildMerge(LCMTy, RemergeRegs);
373   if (DstTy.isScalar() && LCMTy.isScalar()) {
374     MIRBuilder.buildTrunc(DstReg, Remerge);
375     return;
376   }
377 
378   if (LCMTy.isVector()) {
379     MIRBuilder.buildExtract(DstReg, Remerge, 0);
380     return;
381   }
382 
383   llvm_unreachable("unhandled case");
384 }
385 
386 static RTLIB::Libcall getRTLibDesc(unsigned Opcode, unsigned Size) {
387 #define RTLIBCASE(LibcallPrefix)                                               \
388   do {                                                                         \
389     switch (Size) {                                                            \
390     case 32:                                                                   \
391       return RTLIB::LibcallPrefix##32;                                         \
392     case 64:                                                                   \
393       return RTLIB::LibcallPrefix##64;                                         \
394     case 128:                                                                  \
395       return RTLIB::LibcallPrefix##128;                                        \
396     default:                                                                   \
397       llvm_unreachable("unexpected size");                                     \
398     }                                                                          \
399   } while (0)
400 
401   assert((Size == 32 || Size == 64 || Size == 128) && "Unsupported size");
402 
403   switch (Opcode) {
404   case TargetOpcode::G_SDIV:
405     RTLIBCASE(SDIV_I);
406   case TargetOpcode::G_UDIV:
407     RTLIBCASE(UDIV_I);
408   case TargetOpcode::G_SREM:
409     RTLIBCASE(SREM_I);
410   case TargetOpcode::G_UREM:
411     RTLIBCASE(UREM_I);
412   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
413     RTLIBCASE(CTLZ_I);
414   case TargetOpcode::G_FADD:
415     RTLIBCASE(ADD_F);
416   case TargetOpcode::G_FSUB:
417     RTLIBCASE(SUB_F);
418   case TargetOpcode::G_FMUL:
419     RTLIBCASE(MUL_F);
420   case TargetOpcode::G_FDIV:
421     RTLIBCASE(DIV_F);
422   case TargetOpcode::G_FEXP:
423     RTLIBCASE(EXP_F);
424   case TargetOpcode::G_FEXP2:
425     RTLIBCASE(EXP2_F);
426   case TargetOpcode::G_FREM:
427     RTLIBCASE(REM_F);
428   case TargetOpcode::G_FPOW:
429     RTLIBCASE(POW_F);
430   case TargetOpcode::G_FMA:
431     RTLIBCASE(FMA_F);
432   case TargetOpcode::G_FSIN:
433     RTLIBCASE(SIN_F);
434   case TargetOpcode::G_FCOS:
435     RTLIBCASE(COS_F);
436   case TargetOpcode::G_FLOG10:
437     RTLIBCASE(LOG10_F);
438   case TargetOpcode::G_FLOG:
439     RTLIBCASE(LOG_F);
440   case TargetOpcode::G_FLOG2:
441     RTLIBCASE(LOG2_F);
442   case TargetOpcode::G_FCEIL:
443     RTLIBCASE(CEIL_F);
444   case TargetOpcode::G_FFLOOR:
445     RTLIBCASE(FLOOR_F);
446   case TargetOpcode::G_FMINNUM:
447     RTLIBCASE(FMIN_F);
448   case TargetOpcode::G_FMAXNUM:
449     RTLIBCASE(FMAX_F);
450   case TargetOpcode::G_FSQRT:
451     RTLIBCASE(SQRT_F);
452   case TargetOpcode::G_FRINT:
453     RTLIBCASE(RINT_F);
454   case TargetOpcode::G_FNEARBYINT:
455     RTLIBCASE(NEARBYINT_F);
456   }
457   llvm_unreachable("Unknown libcall function");
458 }
459 
460 /// True if an instruction is in tail position in its caller. Intended for
461 /// legalizing libcalls as tail calls when possible.
462 static bool isLibCallInTailPosition(MachineInstr &MI) {
463   MachineBasicBlock &MBB = *MI.getParent();
464   const Function &F = MBB.getParent()->getFunction();
465 
466   // Conservatively require the attributes of the call to match those of
467   // the return. Ignore NoAlias and NonNull because they don't affect the
468   // call sequence.
469   AttributeList CallerAttrs = F.getAttributes();
470   if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex)
471           .removeAttribute(Attribute::NoAlias)
472           .removeAttribute(Attribute::NonNull)
473           .hasAttributes())
474     return false;
475 
476   // It's not safe to eliminate the sign / zero extension of the return value.
477   if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) ||
478       CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
479     return false;
480 
481   // Only tail call if the following instruction is a standard return.
482   auto &TII = *MI.getMF()->getSubtarget().getInstrInfo();
483   auto Next = next_nodbg(MI.getIterator(), MBB.instr_end());
484   if (Next == MBB.instr_end() || TII.isTailCall(*Next) || !Next->isReturn())
485     return false;
486 
487   return true;
488 }
489 
490 LegalizerHelper::LegalizeResult
491 llvm::createLibcall(MachineIRBuilder &MIRBuilder, const char *Name,
492                     const CallLowering::ArgInfo &Result,
493                     ArrayRef<CallLowering::ArgInfo> Args,
494                     const CallingConv::ID CC) {
495   auto &CLI = *MIRBuilder.getMF().getSubtarget().getCallLowering();
496 
497   CallLowering::CallLoweringInfo Info;
498   Info.CallConv = CC;
499   Info.Callee = MachineOperand::CreateES(Name);
500   Info.OrigRet = Result;
501   std::copy(Args.begin(), Args.end(), std::back_inserter(Info.OrigArgs));
502   if (!CLI.lowerCall(MIRBuilder, Info))
503     return LegalizerHelper::UnableToLegalize;
504 
505   return LegalizerHelper::Legalized;
506 }
507 
508 LegalizerHelper::LegalizeResult
509 llvm::createLibcall(MachineIRBuilder &MIRBuilder, RTLIB::Libcall Libcall,
510                     const CallLowering::ArgInfo &Result,
511                     ArrayRef<CallLowering::ArgInfo> Args) {
512   auto &TLI = *MIRBuilder.getMF().getSubtarget().getTargetLowering();
513   const char *Name = TLI.getLibcallName(Libcall);
514   const CallingConv::ID CC = TLI.getLibcallCallingConv(Libcall);
515   return createLibcall(MIRBuilder, Name, Result, Args, CC);
516 }
517 
518 // Useful for libcalls where all operands have the same type.
519 static LegalizerHelper::LegalizeResult
520 simpleLibcall(MachineInstr &MI, MachineIRBuilder &MIRBuilder, unsigned Size,
521               Type *OpType) {
522   auto Libcall = getRTLibDesc(MI.getOpcode(), Size);
523 
524   SmallVector<CallLowering::ArgInfo, 3> Args;
525   for (unsigned i = 1; i < MI.getNumOperands(); i++)
526     Args.push_back({MI.getOperand(i).getReg(), OpType});
527   return createLibcall(MIRBuilder, Libcall, {MI.getOperand(0).getReg(), OpType},
528                        Args);
529 }
530 
531 LegalizerHelper::LegalizeResult
532 llvm::createMemLibcall(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
533                        MachineInstr &MI) {
534   assert(MI.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS);
535   auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
536 
537   SmallVector<CallLowering::ArgInfo, 3> Args;
538   // Add all the args, except for the last which is an imm denoting 'tail'.
539   for (unsigned i = 1; i < MI.getNumOperands() - 1; i++) {
540     Register Reg = MI.getOperand(i).getReg();
541 
542     // Need derive an IR type for call lowering.
543     LLT OpLLT = MRI.getType(Reg);
544     Type *OpTy = nullptr;
545     if (OpLLT.isPointer())
546       OpTy = Type::getInt8PtrTy(Ctx, OpLLT.getAddressSpace());
547     else
548       OpTy = IntegerType::get(Ctx, OpLLT.getSizeInBits());
549     Args.push_back({Reg, OpTy});
550   }
551 
552   auto &CLI = *MIRBuilder.getMF().getSubtarget().getCallLowering();
553   auto &TLI = *MIRBuilder.getMF().getSubtarget().getTargetLowering();
554   Intrinsic::ID ID = MI.getOperand(0).getIntrinsicID();
555   RTLIB::Libcall RTLibcall;
556   switch (ID) {
557   case Intrinsic::memcpy:
558     RTLibcall = RTLIB::MEMCPY;
559     break;
560   case Intrinsic::memset:
561     RTLibcall = RTLIB::MEMSET;
562     break;
563   case Intrinsic::memmove:
564     RTLibcall = RTLIB::MEMMOVE;
565     break;
566   default:
567     return LegalizerHelper::UnableToLegalize;
568   }
569   const char *Name = TLI.getLibcallName(RTLibcall);
570 
571   MIRBuilder.setInstrAndDebugLoc(MI);
572 
573   CallLowering::CallLoweringInfo Info;
574   Info.CallConv = TLI.getLibcallCallingConv(RTLibcall);
575   Info.Callee = MachineOperand::CreateES(Name);
576   Info.OrigRet = CallLowering::ArgInfo({0}, Type::getVoidTy(Ctx));
577   Info.IsTailCall = MI.getOperand(MI.getNumOperands() - 1).getImm() == 1 &&
578                     isLibCallInTailPosition(MI);
579 
580   std::copy(Args.begin(), Args.end(), std::back_inserter(Info.OrigArgs));
581   if (!CLI.lowerCall(MIRBuilder, Info))
582     return LegalizerHelper::UnableToLegalize;
583 
584   if (Info.LoweredTailCall) {
585     assert(Info.IsTailCall && "Lowered tail call when it wasn't a tail call?");
586     // We must have a return following the call (or debug insts) to get past
587     // isLibCallInTailPosition.
588     do {
589       MachineInstr *Next = MI.getNextNode();
590       assert(Next && (Next->isReturn() || Next->isDebugInstr()) &&
591              "Expected instr following MI to be return or debug inst?");
592       // We lowered a tail call, so the call is now the return from the block.
593       // Delete the old return.
594       Next->eraseFromParent();
595     } while (MI.getNextNode());
596   }
597 
598   return LegalizerHelper::Legalized;
599 }
600 
601 static RTLIB::Libcall getConvRTLibDesc(unsigned Opcode, Type *ToType,
602                                        Type *FromType) {
603   auto ToMVT = MVT::getVT(ToType);
604   auto FromMVT = MVT::getVT(FromType);
605 
606   switch (Opcode) {
607   case TargetOpcode::G_FPEXT:
608     return RTLIB::getFPEXT(FromMVT, ToMVT);
609   case TargetOpcode::G_FPTRUNC:
610     return RTLIB::getFPROUND(FromMVT, ToMVT);
611   case TargetOpcode::G_FPTOSI:
612     return RTLIB::getFPTOSINT(FromMVT, ToMVT);
613   case TargetOpcode::G_FPTOUI:
614     return RTLIB::getFPTOUINT(FromMVT, ToMVT);
615   case TargetOpcode::G_SITOFP:
616     return RTLIB::getSINTTOFP(FromMVT, ToMVT);
617   case TargetOpcode::G_UITOFP:
618     return RTLIB::getUINTTOFP(FromMVT, ToMVT);
619   }
620   llvm_unreachable("Unsupported libcall function");
621 }
622 
623 static LegalizerHelper::LegalizeResult
624 conversionLibcall(MachineInstr &MI, MachineIRBuilder &MIRBuilder, Type *ToType,
625                   Type *FromType) {
626   RTLIB::Libcall Libcall = getConvRTLibDesc(MI.getOpcode(), ToType, FromType);
627   return createLibcall(MIRBuilder, Libcall, {MI.getOperand(0).getReg(), ToType},
628                        {{MI.getOperand(1).getReg(), FromType}});
629 }
630 
631 LegalizerHelper::LegalizeResult
632 LegalizerHelper::libcall(MachineInstr &MI) {
633   LLT LLTy = MRI.getType(MI.getOperand(0).getReg());
634   unsigned Size = LLTy.getSizeInBits();
635   auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
636 
637   switch (MI.getOpcode()) {
638   default:
639     return UnableToLegalize;
640   case TargetOpcode::G_SDIV:
641   case TargetOpcode::G_UDIV:
642   case TargetOpcode::G_SREM:
643   case TargetOpcode::G_UREM:
644   case TargetOpcode::G_CTLZ_ZERO_UNDEF: {
645     Type *HLTy = IntegerType::get(Ctx, Size);
646     auto Status = simpleLibcall(MI, MIRBuilder, Size, HLTy);
647     if (Status != Legalized)
648       return Status;
649     break;
650   }
651   case TargetOpcode::G_FADD:
652   case TargetOpcode::G_FSUB:
653   case TargetOpcode::G_FMUL:
654   case TargetOpcode::G_FDIV:
655   case TargetOpcode::G_FMA:
656   case TargetOpcode::G_FPOW:
657   case TargetOpcode::G_FREM:
658   case TargetOpcode::G_FCOS:
659   case TargetOpcode::G_FSIN:
660   case TargetOpcode::G_FLOG10:
661   case TargetOpcode::G_FLOG:
662   case TargetOpcode::G_FLOG2:
663   case TargetOpcode::G_FEXP:
664   case TargetOpcode::G_FEXP2:
665   case TargetOpcode::G_FCEIL:
666   case TargetOpcode::G_FFLOOR:
667   case TargetOpcode::G_FMINNUM:
668   case TargetOpcode::G_FMAXNUM:
669   case TargetOpcode::G_FSQRT:
670   case TargetOpcode::G_FRINT:
671   case TargetOpcode::G_FNEARBYINT: {
672     Type *HLTy = getFloatTypeForLLT(Ctx, LLTy);
673     if (!HLTy || (Size != 32 && Size != 64 && Size != 128)) {
674       LLVM_DEBUG(dbgs() << "No libcall available for size " << Size << ".\n");
675       return UnableToLegalize;
676     }
677     auto Status = simpleLibcall(MI, MIRBuilder, Size, HLTy);
678     if (Status != Legalized)
679       return Status;
680     break;
681   }
682   case TargetOpcode::G_FPEXT:
683   case TargetOpcode::G_FPTRUNC: {
684     Type *FromTy = getFloatTypeForLLT(Ctx,  MRI.getType(MI.getOperand(1).getReg()));
685     Type *ToTy = getFloatTypeForLLT(Ctx, MRI.getType(MI.getOperand(0).getReg()));
686     if (!FromTy || !ToTy)
687       return UnableToLegalize;
688     LegalizeResult Status = conversionLibcall(MI, MIRBuilder, ToTy, FromTy );
689     if (Status != Legalized)
690       return Status;
691     break;
692   }
693   case TargetOpcode::G_FPTOSI:
694   case TargetOpcode::G_FPTOUI: {
695     // FIXME: Support other types
696     unsigned FromSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
697     unsigned ToSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
698     if ((ToSize != 32 && ToSize != 64) || (FromSize != 32 && FromSize != 64))
699       return UnableToLegalize;
700     LegalizeResult Status = conversionLibcall(
701         MI, MIRBuilder,
702         ToSize == 32 ? Type::getInt32Ty(Ctx) : Type::getInt64Ty(Ctx),
703         FromSize == 64 ? Type::getDoubleTy(Ctx) : Type::getFloatTy(Ctx));
704     if (Status != Legalized)
705       return Status;
706     break;
707   }
708   case TargetOpcode::G_SITOFP:
709   case TargetOpcode::G_UITOFP: {
710     // FIXME: Support other types
711     unsigned FromSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
712     unsigned ToSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
713     if ((FromSize != 32 && FromSize != 64) || (ToSize != 32 && ToSize != 64))
714       return UnableToLegalize;
715     LegalizeResult Status = conversionLibcall(
716         MI, MIRBuilder,
717         ToSize == 64 ? Type::getDoubleTy(Ctx) : Type::getFloatTy(Ctx),
718         FromSize == 32 ? Type::getInt32Ty(Ctx) : Type::getInt64Ty(Ctx));
719     if (Status != Legalized)
720       return Status;
721     break;
722   }
723   }
724 
725   MI.eraseFromParent();
726   return Legalized;
727 }
728 
729 LegalizerHelper::LegalizeResult LegalizerHelper::narrowScalar(MachineInstr &MI,
730                                                               unsigned TypeIdx,
731                                                               LLT NarrowTy) {
732   uint64_t SizeOp0 = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
733   uint64_t NarrowSize = NarrowTy.getSizeInBits();
734 
735   switch (MI.getOpcode()) {
736   default:
737     return UnableToLegalize;
738   case TargetOpcode::G_IMPLICIT_DEF: {
739     Register DstReg = MI.getOperand(0).getReg();
740     LLT DstTy = MRI.getType(DstReg);
741 
742     // If SizeOp0 is not an exact multiple of NarrowSize, emit
743     // G_ANYEXT(G_IMPLICIT_DEF). Cast result to vector if needed.
744     // FIXME: Although this would also be legal for the general case, it causes
745     //  a lot of regressions in the emitted code (superfluous COPYs, artifact
746     //  combines not being hit). This seems to be a problem related to the
747     //  artifact combiner.
748     if (SizeOp0 % NarrowSize != 0) {
749       LLT ImplicitTy = NarrowTy;
750       if (DstTy.isVector())
751         ImplicitTy = LLT::vector(DstTy.getNumElements(), ImplicitTy);
752 
753       Register ImplicitReg = MIRBuilder.buildUndef(ImplicitTy).getReg(0);
754       MIRBuilder.buildAnyExt(DstReg, ImplicitReg);
755 
756       MI.eraseFromParent();
757       return Legalized;
758     }
759 
760     int NumParts = SizeOp0 / NarrowSize;
761 
762     SmallVector<Register, 2> DstRegs;
763     for (int i = 0; i < NumParts; ++i)
764       DstRegs.push_back(MIRBuilder.buildUndef(NarrowTy).getReg(0));
765 
766     if (DstTy.isVector())
767       MIRBuilder.buildBuildVector(DstReg, DstRegs);
768     else
769       MIRBuilder.buildMerge(DstReg, DstRegs);
770     MI.eraseFromParent();
771     return Legalized;
772   }
773   case TargetOpcode::G_CONSTANT: {
774     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
775     const APInt &Val = MI.getOperand(1).getCImm()->getValue();
776     unsigned TotalSize = Ty.getSizeInBits();
777     unsigned NarrowSize = NarrowTy.getSizeInBits();
778     int NumParts = TotalSize / NarrowSize;
779 
780     SmallVector<Register, 4> PartRegs;
781     for (int I = 0; I != NumParts; ++I) {
782       unsigned Offset = I * NarrowSize;
783       auto K = MIRBuilder.buildConstant(NarrowTy,
784                                         Val.lshr(Offset).trunc(NarrowSize));
785       PartRegs.push_back(K.getReg(0));
786     }
787 
788     LLT LeftoverTy;
789     unsigned LeftoverBits = TotalSize - NumParts * NarrowSize;
790     SmallVector<Register, 1> LeftoverRegs;
791     if (LeftoverBits != 0) {
792       LeftoverTy = LLT::scalar(LeftoverBits);
793       auto K = MIRBuilder.buildConstant(
794         LeftoverTy,
795         Val.lshr(NumParts * NarrowSize).trunc(LeftoverBits));
796       LeftoverRegs.push_back(K.getReg(0));
797     }
798 
799     insertParts(MI.getOperand(0).getReg(),
800                 Ty, NarrowTy, PartRegs, LeftoverTy, LeftoverRegs);
801 
802     MI.eraseFromParent();
803     return Legalized;
804   }
805   case TargetOpcode::G_SEXT:
806   case TargetOpcode::G_ZEXT:
807   case TargetOpcode::G_ANYEXT:
808     return narrowScalarExt(MI, TypeIdx, NarrowTy);
809   case TargetOpcode::G_TRUNC: {
810     if (TypeIdx != 1)
811       return UnableToLegalize;
812 
813     uint64_t SizeOp1 = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
814     if (NarrowTy.getSizeInBits() * 2 != SizeOp1) {
815       LLVM_DEBUG(dbgs() << "Can't narrow trunc to type " << NarrowTy << "\n");
816       return UnableToLegalize;
817     }
818 
819     auto Unmerge = MIRBuilder.buildUnmerge(NarrowTy, MI.getOperand(1));
820     MIRBuilder.buildCopy(MI.getOperand(0), Unmerge.getReg(0));
821     MI.eraseFromParent();
822     return Legalized;
823   }
824 
825   case TargetOpcode::G_FREEZE:
826     return reduceOperationWidth(MI, TypeIdx, NarrowTy);
827 
828   case TargetOpcode::G_ADD: {
829     // FIXME: add support for when SizeOp0 isn't an exact multiple of
830     // NarrowSize.
831     if (SizeOp0 % NarrowSize != 0)
832       return UnableToLegalize;
833     // Expand in terms of carry-setting/consuming G_ADDE instructions.
834     int NumParts = SizeOp0 / NarrowTy.getSizeInBits();
835 
836     SmallVector<Register, 2> Src1Regs, Src2Regs, DstRegs;
837     extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, Src1Regs);
838     extractParts(MI.getOperand(2).getReg(), NarrowTy, NumParts, Src2Regs);
839 
840     Register CarryIn;
841     for (int i = 0; i < NumParts; ++i) {
842       Register DstReg = MRI.createGenericVirtualRegister(NarrowTy);
843       Register CarryOut = MRI.createGenericVirtualRegister(LLT::scalar(1));
844 
845       if (i == 0)
846         MIRBuilder.buildUAddo(DstReg, CarryOut, Src1Regs[i], Src2Regs[i]);
847       else {
848         MIRBuilder.buildUAdde(DstReg, CarryOut, Src1Regs[i],
849                               Src2Regs[i], CarryIn);
850       }
851 
852       DstRegs.push_back(DstReg);
853       CarryIn = CarryOut;
854     }
855     Register DstReg = MI.getOperand(0).getReg();
856     if(MRI.getType(DstReg).isVector())
857       MIRBuilder.buildBuildVector(DstReg, DstRegs);
858     else
859       MIRBuilder.buildMerge(DstReg, DstRegs);
860     MI.eraseFromParent();
861     return Legalized;
862   }
863   case TargetOpcode::G_SUB: {
864     // FIXME: add support for when SizeOp0 isn't an exact multiple of
865     // NarrowSize.
866     if (SizeOp0 % NarrowSize != 0)
867       return UnableToLegalize;
868 
869     int NumParts = SizeOp0 / NarrowTy.getSizeInBits();
870 
871     SmallVector<Register, 2> Src1Regs, Src2Regs, DstRegs;
872     extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, Src1Regs);
873     extractParts(MI.getOperand(2).getReg(), NarrowTy, NumParts, Src2Regs);
874 
875     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy);
876     Register BorrowOut = MRI.createGenericVirtualRegister(LLT::scalar(1));
877     MIRBuilder.buildInstr(TargetOpcode::G_USUBO, {DstReg, BorrowOut},
878                           {Src1Regs[0], Src2Regs[0]});
879     DstRegs.push_back(DstReg);
880     Register BorrowIn = BorrowOut;
881     for (int i = 1; i < NumParts; ++i) {
882       DstReg = MRI.createGenericVirtualRegister(NarrowTy);
883       BorrowOut = MRI.createGenericVirtualRegister(LLT::scalar(1));
884 
885       MIRBuilder.buildInstr(TargetOpcode::G_USUBE, {DstReg, BorrowOut},
886                             {Src1Regs[i], Src2Regs[i], BorrowIn});
887 
888       DstRegs.push_back(DstReg);
889       BorrowIn = BorrowOut;
890     }
891     MIRBuilder.buildMerge(MI.getOperand(0), DstRegs);
892     MI.eraseFromParent();
893     return Legalized;
894   }
895   case TargetOpcode::G_MUL:
896   case TargetOpcode::G_UMULH:
897     return narrowScalarMul(MI, NarrowTy);
898   case TargetOpcode::G_EXTRACT:
899     return narrowScalarExtract(MI, TypeIdx, NarrowTy);
900   case TargetOpcode::G_INSERT:
901     return narrowScalarInsert(MI, TypeIdx, NarrowTy);
902   case TargetOpcode::G_LOAD: {
903     const auto &MMO = **MI.memoperands_begin();
904     Register DstReg = MI.getOperand(0).getReg();
905     LLT DstTy = MRI.getType(DstReg);
906     if (DstTy.isVector())
907       return UnableToLegalize;
908 
909     if (8 * MMO.getSize() != DstTy.getSizeInBits()) {
910       Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
911       auto &MMO = **MI.memoperands_begin();
912       MIRBuilder.buildLoad(TmpReg, MI.getOperand(1), MMO);
913       MIRBuilder.buildAnyExt(DstReg, TmpReg);
914       MI.eraseFromParent();
915       return Legalized;
916     }
917 
918     return reduceLoadStoreWidth(MI, TypeIdx, NarrowTy);
919   }
920   case TargetOpcode::G_ZEXTLOAD:
921   case TargetOpcode::G_SEXTLOAD: {
922     bool ZExt = MI.getOpcode() == TargetOpcode::G_ZEXTLOAD;
923     Register DstReg = MI.getOperand(0).getReg();
924     Register PtrReg = MI.getOperand(1).getReg();
925 
926     Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
927     auto &MMO = **MI.memoperands_begin();
928     if (MMO.getSizeInBits() == NarrowSize) {
929       MIRBuilder.buildLoad(TmpReg, PtrReg, MMO);
930     } else {
931       MIRBuilder.buildLoadInstr(MI.getOpcode(), TmpReg, PtrReg, MMO);
932     }
933 
934     if (ZExt)
935       MIRBuilder.buildZExt(DstReg, TmpReg);
936     else
937       MIRBuilder.buildSExt(DstReg, TmpReg);
938 
939     MI.eraseFromParent();
940     return Legalized;
941   }
942   case TargetOpcode::G_STORE: {
943     const auto &MMO = **MI.memoperands_begin();
944 
945     Register SrcReg = MI.getOperand(0).getReg();
946     LLT SrcTy = MRI.getType(SrcReg);
947     if (SrcTy.isVector())
948       return UnableToLegalize;
949 
950     int NumParts = SizeOp0 / NarrowSize;
951     unsigned HandledSize = NumParts * NarrowTy.getSizeInBits();
952     unsigned LeftoverBits = SrcTy.getSizeInBits() - HandledSize;
953     if (SrcTy.isVector() && LeftoverBits != 0)
954       return UnableToLegalize;
955 
956     if (8 * MMO.getSize() != SrcTy.getSizeInBits()) {
957       Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
958       auto &MMO = **MI.memoperands_begin();
959       MIRBuilder.buildTrunc(TmpReg, SrcReg);
960       MIRBuilder.buildStore(TmpReg, MI.getOperand(1), MMO);
961       MI.eraseFromParent();
962       return Legalized;
963     }
964 
965     return reduceLoadStoreWidth(MI, 0, NarrowTy);
966   }
967   case TargetOpcode::G_SELECT:
968     return narrowScalarSelect(MI, TypeIdx, NarrowTy);
969   case TargetOpcode::G_AND:
970   case TargetOpcode::G_OR:
971   case TargetOpcode::G_XOR: {
972     // Legalize bitwise operation:
973     // A = BinOp<Ty> B, C
974     // into:
975     // B1, ..., BN = G_UNMERGE_VALUES B
976     // C1, ..., CN = G_UNMERGE_VALUES C
977     // A1 = BinOp<Ty/N> B1, C2
978     // ...
979     // AN = BinOp<Ty/N> BN, CN
980     // A = G_MERGE_VALUES A1, ..., AN
981     return narrowScalarBasic(MI, TypeIdx, NarrowTy);
982   }
983   case TargetOpcode::G_SHL:
984   case TargetOpcode::G_LSHR:
985   case TargetOpcode::G_ASHR:
986     return narrowScalarShift(MI, TypeIdx, NarrowTy);
987   case TargetOpcode::G_CTLZ:
988   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
989   case TargetOpcode::G_CTTZ:
990   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
991   case TargetOpcode::G_CTPOP:
992     if (TypeIdx == 1)
993       switch (MI.getOpcode()) {
994       case TargetOpcode::G_CTLZ:
995       case TargetOpcode::G_CTLZ_ZERO_UNDEF:
996         return narrowScalarCTLZ(MI, TypeIdx, NarrowTy);
997       case TargetOpcode::G_CTTZ:
998       case TargetOpcode::G_CTTZ_ZERO_UNDEF:
999         return narrowScalarCTTZ(MI, TypeIdx, NarrowTy);
1000       case TargetOpcode::G_CTPOP:
1001         return narrowScalarCTPOP(MI, TypeIdx, NarrowTy);
1002       default:
1003         return UnableToLegalize;
1004       }
1005 
1006     Observer.changingInstr(MI);
1007     narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_ZEXT);
1008     Observer.changedInstr(MI);
1009     return Legalized;
1010   case TargetOpcode::G_INTTOPTR:
1011     if (TypeIdx != 1)
1012       return UnableToLegalize;
1013 
1014     Observer.changingInstr(MI);
1015     narrowScalarSrc(MI, NarrowTy, 1);
1016     Observer.changedInstr(MI);
1017     return Legalized;
1018   case TargetOpcode::G_PTRTOINT:
1019     if (TypeIdx != 0)
1020       return UnableToLegalize;
1021 
1022     Observer.changingInstr(MI);
1023     narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_ZEXT);
1024     Observer.changedInstr(MI);
1025     return Legalized;
1026   case TargetOpcode::G_PHI: {
1027     unsigned NumParts = SizeOp0 / NarrowSize;
1028     SmallVector<Register, 2> DstRegs(NumParts);
1029     SmallVector<SmallVector<Register, 2>, 2> SrcRegs(MI.getNumOperands() / 2);
1030     Observer.changingInstr(MI);
1031     for (unsigned i = 1; i < MI.getNumOperands(); i += 2) {
1032       MachineBasicBlock &OpMBB = *MI.getOperand(i + 1).getMBB();
1033       MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
1034       extractParts(MI.getOperand(i).getReg(), NarrowTy, NumParts,
1035                    SrcRegs[i / 2]);
1036     }
1037     MachineBasicBlock &MBB = *MI.getParent();
1038     MIRBuilder.setInsertPt(MBB, MI);
1039     for (unsigned i = 0; i < NumParts; ++i) {
1040       DstRegs[i] = MRI.createGenericVirtualRegister(NarrowTy);
1041       MachineInstrBuilder MIB =
1042           MIRBuilder.buildInstr(TargetOpcode::G_PHI).addDef(DstRegs[i]);
1043       for (unsigned j = 1; j < MI.getNumOperands(); j += 2)
1044         MIB.addUse(SrcRegs[j / 2][i]).add(MI.getOperand(j + 1));
1045     }
1046     MIRBuilder.setInsertPt(MBB, MBB.getFirstNonPHI());
1047     MIRBuilder.buildMerge(MI.getOperand(0), DstRegs);
1048     Observer.changedInstr(MI);
1049     MI.eraseFromParent();
1050     return Legalized;
1051   }
1052   case TargetOpcode::G_EXTRACT_VECTOR_ELT:
1053   case TargetOpcode::G_INSERT_VECTOR_ELT: {
1054     if (TypeIdx != 2)
1055       return UnableToLegalize;
1056 
1057     int OpIdx = MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT ? 2 : 3;
1058     Observer.changingInstr(MI);
1059     narrowScalarSrc(MI, NarrowTy, OpIdx);
1060     Observer.changedInstr(MI);
1061     return Legalized;
1062   }
1063   case TargetOpcode::G_ICMP: {
1064     uint64_t SrcSize = MRI.getType(MI.getOperand(2).getReg()).getSizeInBits();
1065     if (NarrowSize * 2 != SrcSize)
1066       return UnableToLegalize;
1067 
1068     Observer.changingInstr(MI);
1069     Register LHSL = MRI.createGenericVirtualRegister(NarrowTy);
1070     Register LHSH = MRI.createGenericVirtualRegister(NarrowTy);
1071     MIRBuilder.buildUnmerge({LHSL, LHSH}, MI.getOperand(2));
1072 
1073     Register RHSL = MRI.createGenericVirtualRegister(NarrowTy);
1074     Register RHSH = MRI.createGenericVirtualRegister(NarrowTy);
1075     MIRBuilder.buildUnmerge({RHSL, RHSH}, MI.getOperand(3));
1076 
1077     CmpInst::Predicate Pred =
1078         static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
1079     LLT ResTy = MRI.getType(MI.getOperand(0).getReg());
1080 
1081     if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1082       MachineInstrBuilder XorL = MIRBuilder.buildXor(NarrowTy, LHSL, RHSL);
1083       MachineInstrBuilder XorH = MIRBuilder.buildXor(NarrowTy, LHSH, RHSH);
1084       MachineInstrBuilder Or = MIRBuilder.buildOr(NarrowTy, XorL, XorH);
1085       MachineInstrBuilder Zero = MIRBuilder.buildConstant(NarrowTy, 0);
1086       MIRBuilder.buildICmp(Pred, MI.getOperand(0), Or, Zero);
1087     } else {
1088       MachineInstrBuilder CmpH = MIRBuilder.buildICmp(Pred, ResTy, LHSH, RHSH);
1089       MachineInstrBuilder CmpHEQ =
1090           MIRBuilder.buildICmp(CmpInst::Predicate::ICMP_EQ, ResTy, LHSH, RHSH);
1091       MachineInstrBuilder CmpLU = MIRBuilder.buildICmp(
1092           ICmpInst::getUnsignedPredicate(Pred), ResTy, LHSL, RHSL);
1093       MIRBuilder.buildSelect(MI.getOperand(0), CmpHEQ, CmpLU, CmpH);
1094     }
1095     Observer.changedInstr(MI);
1096     MI.eraseFromParent();
1097     return Legalized;
1098   }
1099   case TargetOpcode::G_SEXT_INREG: {
1100     if (TypeIdx != 0)
1101       return UnableToLegalize;
1102 
1103     int64_t SizeInBits = MI.getOperand(2).getImm();
1104 
1105     // So long as the new type has more bits than the bits we're extending we
1106     // don't need to break it apart.
1107     if (NarrowTy.getScalarSizeInBits() >= SizeInBits) {
1108       Observer.changingInstr(MI);
1109       // We don't lose any non-extension bits by truncating the src and
1110       // sign-extending the dst.
1111       MachineOperand &MO1 = MI.getOperand(1);
1112       auto TruncMIB = MIRBuilder.buildTrunc(NarrowTy, MO1);
1113       MO1.setReg(TruncMIB.getReg(0));
1114 
1115       MachineOperand &MO2 = MI.getOperand(0);
1116       Register DstExt = MRI.createGenericVirtualRegister(NarrowTy);
1117       MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
1118       MIRBuilder.buildSExt(MO2, DstExt);
1119       MO2.setReg(DstExt);
1120       Observer.changedInstr(MI);
1121       return Legalized;
1122     }
1123 
1124     // Break it apart. Components below the extension point are unmodified. The
1125     // component containing the extension point becomes a narrower SEXT_INREG.
1126     // Components above it are ashr'd from the component containing the
1127     // extension point.
1128     if (SizeOp0 % NarrowSize != 0)
1129       return UnableToLegalize;
1130     int NumParts = SizeOp0 / NarrowSize;
1131 
1132     // List the registers where the destination will be scattered.
1133     SmallVector<Register, 2> DstRegs;
1134     // List the registers where the source will be split.
1135     SmallVector<Register, 2> SrcRegs;
1136 
1137     // Create all the temporary registers.
1138     for (int i = 0; i < NumParts; ++i) {
1139       Register SrcReg = MRI.createGenericVirtualRegister(NarrowTy);
1140 
1141       SrcRegs.push_back(SrcReg);
1142     }
1143 
1144     // Explode the big arguments into smaller chunks.
1145     MIRBuilder.buildUnmerge(SrcRegs, MI.getOperand(1));
1146 
1147     Register AshrCstReg =
1148         MIRBuilder.buildConstant(NarrowTy, NarrowTy.getScalarSizeInBits() - 1)
1149             .getReg(0);
1150     Register FullExtensionReg = 0;
1151     Register PartialExtensionReg = 0;
1152 
1153     // Do the operation on each small part.
1154     for (int i = 0; i < NumParts; ++i) {
1155       if ((i + 1) * NarrowTy.getScalarSizeInBits() < SizeInBits)
1156         DstRegs.push_back(SrcRegs[i]);
1157       else if (i * NarrowTy.getScalarSizeInBits() > SizeInBits) {
1158         assert(PartialExtensionReg &&
1159                "Expected to visit partial extension before full");
1160         if (FullExtensionReg) {
1161           DstRegs.push_back(FullExtensionReg);
1162           continue;
1163         }
1164         DstRegs.push_back(
1165             MIRBuilder.buildAShr(NarrowTy, PartialExtensionReg, AshrCstReg)
1166                 .getReg(0));
1167         FullExtensionReg = DstRegs.back();
1168       } else {
1169         DstRegs.push_back(
1170             MIRBuilder
1171                 .buildInstr(
1172                     TargetOpcode::G_SEXT_INREG, {NarrowTy},
1173                     {SrcRegs[i], SizeInBits % NarrowTy.getScalarSizeInBits()})
1174                 .getReg(0));
1175         PartialExtensionReg = DstRegs.back();
1176       }
1177     }
1178 
1179     // Gather the destination registers into the final destination.
1180     Register DstReg = MI.getOperand(0).getReg();
1181     MIRBuilder.buildMerge(DstReg, DstRegs);
1182     MI.eraseFromParent();
1183     return Legalized;
1184   }
1185   case TargetOpcode::G_BSWAP:
1186   case TargetOpcode::G_BITREVERSE: {
1187     if (SizeOp0 % NarrowSize != 0)
1188       return UnableToLegalize;
1189 
1190     Observer.changingInstr(MI);
1191     SmallVector<Register, 2> SrcRegs, DstRegs;
1192     unsigned NumParts = SizeOp0 / NarrowSize;
1193     extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
1194 
1195     for (unsigned i = 0; i < NumParts; ++i) {
1196       auto DstPart = MIRBuilder.buildInstr(MI.getOpcode(), {NarrowTy},
1197                                            {SrcRegs[NumParts - 1 - i]});
1198       DstRegs.push_back(DstPart.getReg(0));
1199     }
1200 
1201     MIRBuilder.buildMerge(MI.getOperand(0), DstRegs);
1202 
1203     Observer.changedInstr(MI);
1204     MI.eraseFromParent();
1205     return Legalized;
1206   }
1207   case TargetOpcode::G_PTRMASK: {
1208     if (TypeIdx != 1)
1209       return UnableToLegalize;
1210     Observer.changingInstr(MI);
1211     narrowScalarSrc(MI, NarrowTy, 2);
1212     Observer.changedInstr(MI);
1213     return Legalized;
1214   }
1215   }
1216 }
1217 
1218 Register LegalizerHelper::coerceToScalar(Register Val) {
1219   LLT Ty = MRI.getType(Val);
1220   if (Ty.isScalar())
1221     return Val;
1222 
1223   const DataLayout &DL = MIRBuilder.getDataLayout();
1224   LLT NewTy = LLT::scalar(Ty.getSizeInBits());
1225   if (Ty.isPointer()) {
1226     if (DL.isNonIntegralAddressSpace(Ty.getAddressSpace()))
1227       return Register();
1228     return MIRBuilder.buildPtrToInt(NewTy, Val).getReg(0);
1229   }
1230 
1231   Register NewVal = Val;
1232 
1233   assert(Ty.isVector());
1234   LLT EltTy = Ty.getElementType();
1235   if (EltTy.isPointer())
1236     NewVal = MIRBuilder.buildPtrToInt(NewTy, NewVal).getReg(0);
1237   return MIRBuilder.buildBitcast(NewTy, NewVal).getReg(0);
1238 }
1239 
1240 void LegalizerHelper::widenScalarSrc(MachineInstr &MI, LLT WideTy,
1241                                      unsigned OpIdx, unsigned ExtOpcode) {
1242   MachineOperand &MO = MI.getOperand(OpIdx);
1243   auto ExtB = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MO});
1244   MO.setReg(ExtB.getReg(0));
1245 }
1246 
1247 void LegalizerHelper::narrowScalarSrc(MachineInstr &MI, LLT NarrowTy,
1248                                       unsigned OpIdx) {
1249   MachineOperand &MO = MI.getOperand(OpIdx);
1250   auto ExtB = MIRBuilder.buildTrunc(NarrowTy, MO);
1251   MO.setReg(ExtB.getReg(0));
1252 }
1253 
1254 void LegalizerHelper::widenScalarDst(MachineInstr &MI, LLT WideTy,
1255                                      unsigned OpIdx, unsigned TruncOpcode) {
1256   MachineOperand &MO = MI.getOperand(OpIdx);
1257   Register DstExt = MRI.createGenericVirtualRegister(WideTy);
1258   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
1259   MIRBuilder.buildInstr(TruncOpcode, {MO}, {DstExt});
1260   MO.setReg(DstExt);
1261 }
1262 
1263 void LegalizerHelper::narrowScalarDst(MachineInstr &MI, LLT NarrowTy,
1264                                       unsigned OpIdx, unsigned ExtOpcode) {
1265   MachineOperand &MO = MI.getOperand(OpIdx);
1266   Register DstTrunc = MRI.createGenericVirtualRegister(NarrowTy);
1267   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
1268   MIRBuilder.buildInstr(ExtOpcode, {MO}, {DstTrunc});
1269   MO.setReg(DstTrunc);
1270 }
1271 
1272 void LegalizerHelper::moreElementsVectorDst(MachineInstr &MI, LLT WideTy,
1273                                             unsigned OpIdx) {
1274   MachineOperand &MO = MI.getOperand(OpIdx);
1275   Register DstExt = MRI.createGenericVirtualRegister(WideTy);
1276   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
1277   MIRBuilder.buildExtract(MO, DstExt, 0);
1278   MO.setReg(DstExt);
1279 }
1280 
1281 void LegalizerHelper::moreElementsVectorSrc(MachineInstr &MI, LLT MoreTy,
1282                                             unsigned OpIdx) {
1283   MachineOperand &MO = MI.getOperand(OpIdx);
1284 
1285   LLT OldTy = MRI.getType(MO.getReg());
1286   unsigned OldElts = OldTy.getNumElements();
1287   unsigned NewElts = MoreTy.getNumElements();
1288 
1289   unsigned NumParts = NewElts / OldElts;
1290 
1291   // Use concat_vectors if the result is a multiple of the number of elements.
1292   if (NumParts * OldElts == NewElts) {
1293     SmallVector<Register, 8> Parts;
1294     Parts.push_back(MO.getReg());
1295 
1296     Register ImpDef = MIRBuilder.buildUndef(OldTy).getReg(0);
1297     for (unsigned I = 1; I != NumParts; ++I)
1298       Parts.push_back(ImpDef);
1299 
1300     auto Concat = MIRBuilder.buildConcatVectors(MoreTy, Parts);
1301     MO.setReg(Concat.getReg(0));
1302     return;
1303   }
1304 
1305   Register MoreReg = MRI.createGenericVirtualRegister(MoreTy);
1306   Register ImpDef = MIRBuilder.buildUndef(MoreTy).getReg(0);
1307   MIRBuilder.buildInsert(MoreReg, ImpDef, MO.getReg(), 0);
1308   MO.setReg(MoreReg);
1309 }
1310 
1311 void LegalizerHelper::bitcastSrc(MachineInstr &MI, LLT CastTy, unsigned OpIdx) {
1312   MachineOperand &Op = MI.getOperand(OpIdx);
1313   Op.setReg(MIRBuilder.buildBitcast(CastTy, Op).getReg(0));
1314 }
1315 
1316 void LegalizerHelper::bitcastDst(MachineInstr &MI, LLT CastTy, unsigned OpIdx) {
1317   MachineOperand &MO = MI.getOperand(OpIdx);
1318   Register CastDst = MRI.createGenericVirtualRegister(CastTy);
1319   MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
1320   MIRBuilder.buildBitcast(MO, CastDst);
1321   MO.setReg(CastDst);
1322 }
1323 
1324 LegalizerHelper::LegalizeResult
1325 LegalizerHelper::widenScalarMergeValues(MachineInstr &MI, unsigned TypeIdx,
1326                                         LLT WideTy) {
1327   if (TypeIdx != 1)
1328     return UnableToLegalize;
1329 
1330   Register DstReg = MI.getOperand(0).getReg();
1331   LLT DstTy = MRI.getType(DstReg);
1332   if (DstTy.isVector())
1333     return UnableToLegalize;
1334 
1335   Register Src1 = MI.getOperand(1).getReg();
1336   LLT SrcTy = MRI.getType(Src1);
1337   const int DstSize = DstTy.getSizeInBits();
1338   const int SrcSize = SrcTy.getSizeInBits();
1339   const int WideSize = WideTy.getSizeInBits();
1340   const int NumMerge = (DstSize + WideSize - 1) / WideSize;
1341 
1342   unsigned NumOps = MI.getNumOperands();
1343   unsigned NumSrc = MI.getNumOperands() - 1;
1344   unsigned PartSize = DstTy.getSizeInBits() / NumSrc;
1345 
1346   if (WideSize >= DstSize) {
1347     // Directly pack the bits in the target type.
1348     Register ResultReg = MIRBuilder.buildZExt(WideTy, Src1).getReg(0);
1349 
1350     for (unsigned I = 2; I != NumOps; ++I) {
1351       const unsigned Offset = (I - 1) * PartSize;
1352 
1353       Register SrcReg = MI.getOperand(I).getReg();
1354       assert(MRI.getType(SrcReg) == LLT::scalar(PartSize));
1355 
1356       auto ZextInput = MIRBuilder.buildZExt(WideTy, SrcReg);
1357 
1358       Register NextResult = I + 1 == NumOps && WideTy == DstTy ? DstReg :
1359         MRI.createGenericVirtualRegister(WideTy);
1360 
1361       auto ShiftAmt = MIRBuilder.buildConstant(WideTy, Offset);
1362       auto Shl = MIRBuilder.buildShl(WideTy, ZextInput, ShiftAmt);
1363       MIRBuilder.buildOr(NextResult, ResultReg, Shl);
1364       ResultReg = NextResult;
1365     }
1366 
1367     if (WideSize > DstSize)
1368       MIRBuilder.buildTrunc(DstReg, ResultReg);
1369     else if (DstTy.isPointer())
1370       MIRBuilder.buildIntToPtr(DstReg, ResultReg);
1371 
1372     MI.eraseFromParent();
1373     return Legalized;
1374   }
1375 
1376   // Unmerge the original values to the GCD type, and recombine to the next
1377   // multiple greater than the original type.
1378   //
1379   // %3:_(s12) = G_MERGE_VALUES %0:_(s4), %1:_(s4), %2:_(s4) -> s6
1380   // %4:_(s2), %5:_(s2) = G_UNMERGE_VALUES %0
1381   // %6:_(s2), %7:_(s2) = G_UNMERGE_VALUES %1
1382   // %8:_(s2), %9:_(s2) = G_UNMERGE_VALUES %2
1383   // %10:_(s6) = G_MERGE_VALUES %4, %5, %6
1384   // %11:_(s6) = G_MERGE_VALUES %7, %8, %9
1385   // %12:_(s12) = G_MERGE_VALUES %10, %11
1386   //
1387   // Padding with undef if necessary:
1388   //
1389   // %2:_(s8) = G_MERGE_VALUES %0:_(s4), %1:_(s4) -> s6
1390   // %3:_(s2), %4:_(s2) = G_UNMERGE_VALUES %0
1391   // %5:_(s2), %6:_(s2) = G_UNMERGE_VALUES %1
1392   // %7:_(s2) = G_IMPLICIT_DEF
1393   // %8:_(s6) = G_MERGE_VALUES %3, %4, %5
1394   // %9:_(s6) = G_MERGE_VALUES %6, %7, %7
1395   // %10:_(s12) = G_MERGE_VALUES %8, %9
1396 
1397   const int GCD = greatestCommonDivisor(SrcSize, WideSize);
1398   LLT GCDTy = LLT::scalar(GCD);
1399 
1400   SmallVector<Register, 8> Parts;
1401   SmallVector<Register, 8> NewMergeRegs;
1402   SmallVector<Register, 8> Unmerges;
1403   LLT WideDstTy = LLT::scalar(NumMerge * WideSize);
1404 
1405   // Decompose the original operands if they don't evenly divide.
1406   for (int I = 1, E = MI.getNumOperands(); I != E; ++I) {
1407     Register SrcReg = MI.getOperand(I).getReg();
1408     if (GCD == SrcSize) {
1409       Unmerges.push_back(SrcReg);
1410     } else {
1411       auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
1412       for (int J = 0, JE = Unmerge->getNumOperands() - 1; J != JE; ++J)
1413         Unmerges.push_back(Unmerge.getReg(J));
1414     }
1415   }
1416 
1417   // Pad with undef to the next size that is a multiple of the requested size.
1418   if (static_cast<int>(Unmerges.size()) != NumMerge * WideSize) {
1419     Register UndefReg = MIRBuilder.buildUndef(GCDTy).getReg(0);
1420     for (int I = Unmerges.size(); I != NumMerge * WideSize; ++I)
1421       Unmerges.push_back(UndefReg);
1422   }
1423 
1424   const int PartsPerGCD = WideSize / GCD;
1425 
1426   // Build merges of each piece.
1427   ArrayRef<Register> Slicer(Unmerges);
1428   for (int I = 0; I != NumMerge; ++I, Slicer = Slicer.drop_front(PartsPerGCD)) {
1429     auto Merge = MIRBuilder.buildMerge(WideTy, Slicer.take_front(PartsPerGCD));
1430     NewMergeRegs.push_back(Merge.getReg(0));
1431   }
1432 
1433   // A truncate may be necessary if the requested type doesn't evenly divide the
1434   // original result type.
1435   if (DstTy.getSizeInBits() == WideDstTy.getSizeInBits()) {
1436     MIRBuilder.buildMerge(DstReg, NewMergeRegs);
1437   } else {
1438     auto FinalMerge = MIRBuilder.buildMerge(WideDstTy, NewMergeRegs);
1439     MIRBuilder.buildTrunc(DstReg, FinalMerge.getReg(0));
1440   }
1441 
1442   MI.eraseFromParent();
1443   return Legalized;
1444 }
1445 
1446 LegalizerHelper::LegalizeResult
1447 LegalizerHelper::widenScalarUnmergeValues(MachineInstr &MI, unsigned TypeIdx,
1448                                           LLT WideTy) {
1449   if (TypeIdx != 0)
1450     return UnableToLegalize;
1451 
1452   int NumDst = MI.getNumOperands() - 1;
1453   Register SrcReg = MI.getOperand(NumDst).getReg();
1454   LLT SrcTy = MRI.getType(SrcReg);
1455   if (SrcTy.isVector())
1456     return UnableToLegalize;
1457 
1458   Register Dst0Reg = MI.getOperand(0).getReg();
1459   LLT DstTy = MRI.getType(Dst0Reg);
1460   if (!DstTy.isScalar())
1461     return UnableToLegalize;
1462 
1463   if (WideTy.getSizeInBits() >= SrcTy.getSizeInBits()) {
1464     if (SrcTy.isPointer()) {
1465       const DataLayout &DL = MIRBuilder.getDataLayout();
1466       if (DL.isNonIntegralAddressSpace(SrcTy.getAddressSpace())) {
1467         LLVM_DEBUG(
1468             dbgs() << "Not casting non-integral address space integer\n");
1469         return UnableToLegalize;
1470       }
1471 
1472       SrcTy = LLT::scalar(SrcTy.getSizeInBits());
1473       SrcReg = MIRBuilder.buildPtrToInt(SrcTy, SrcReg).getReg(0);
1474     }
1475 
1476     // Widen SrcTy to WideTy. This does not affect the result, but since the
1477     // user requested this size, it is probably better handled than SrcTy and
1478     // should reduce the total number of legalization artifacts
1479     if (WideTy.getSizeInBits() > SrcTy.getSizeInBits()) {
1480       SrcTy = WideTy;
1481       SrcReg = MIRBuilder.buildAnyExt(WideTy, SrcReg).getReg(0);
1482     }
1483 
1484     // Theres no unmerge type to target. Directly extract the bits from the
1485     // source type
1486     unsigned DstSize = DstTy.getSizeInBits();
1487 
1488     MIRBuilder.buildTrunc(Dst0Reg, SrcReg);
1489     for (int I = 1; I != NumDst; ++I) {
1490       auto ShiftAmt = MIRBuilder.buildConstant(SrcTy, DstSize * I);
1491       auto Shr = MIRBuilder.buildLShr(SrcTy, SrcReg, ShiftAmt);
1492       MIRBuilder.buildTrunc(MI.getOperand(I), Shr);
1493     }
1494 
1495     MI.eraseFromParent();
1496     return Legalized;
1497   }
1498 
1499   // Extend the source to a wider type.
1500   LLT LCMTy = getLCMType(SrcTy, WideTy);
1501 
1502   Register WideSrc = SrcReg;
1503   if (LCMTy.getSizeInBits() != SrcTy.getSizeInBits()) {
1504     // TODO: If this is an integral address space, cast to integer and anyext.
1505     if (SrcTy.isPointer()) {
1506       LLVM_DEBUG(dbgs() << "Widening pointer source types not implemented\n");
1507       return UnableToLegalize;
1508     }
1509 
1510     WideSrc = MIRBuilder.buildAnyExt(LCMTy, WideSrc).getReg(0);
1511   }
1512 
1513   auto Unmerge = MIRBuilder.buildUnmerge(WideTy, WideSrc);
1514 
1515   // Create a sequence of unmerges to the original results. since we may have
1516   // widened the source, we will need to pad the results with dead defs to cover
1517   // the source register.
1518   // e.g. widen s16 to s32:
1519   // %1:_(s16), %2:_(s16), %3:_(s16) = G_UNMERGE_VALUES %0:_(s48)
1520   //
1521   // =>
1522   //  %4:_(s64) = G_ANYEXT %0:_(s48)
1523   //  %5:_(s32), %6:_(s32) = G_UNMERGE_VALUES %4 ; Requested unmerge
1524   //  %1:_(s16), %2:_(s16) = G_UNMERGE_VALUES %5 ; unpack to original regs
1525   //  %3:_(s16), dead %7 = G_UNMERGE_VALUES %6 ; original reg + extra dead def
1526 
1527   const int NumUnmerge = Unmerge->getNumOperands() - 1;
1528   const int PartsPerUnmerge = WideTy.getSizeInBits() / DstTy.getSizeInBits();
1529 
1530   for (int I = 0; I != NumUnmerge; ++I) {
1531     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
1532 
1533     for (int J = 0; J != PartsPerUnmerge; ++J) {
1534       int Idx = I * PartsPerUnmerge + J;
1535       if (Idx < NumDst)
1536         MIB.addDef(MI.getOperand(Idx).getReg());
1537       else {
1538         // Create dead def for excess components.
1539         MIB.addDef(MRI.createGenericVirtualRegister(DstTy));
1540       }
1541     }
1542 
1543     MIB.addUse(Unmerge.getReg(I));
1544   }
1545 
1546   MI.eraseFromParent();
1547   return Legalized;
1548 }
1549 
1550 LegalizerHelper::LegalizeResult
1551 LegalizerHelper::widenScalarExtract(MachineInstr &MI, unsigned TypeIdx,
1552                                     LLT WideTy) {
1553   Register DstReg = MI.getOperand(0).getReg();
1554   Register SrcReg = MI.getOperand(1).getReg();
1555   LLT SrcTy = MRI.getType(SrcReg);
1556 
1557   LLT DstTy = MRI.getType(DstReg);
1558   unsigned Offset = MI.getOperand(2).getImm();
1559 
1560   if (TypeIdx == 0) {
1561     if (SrcTy.isVector() || DstTy.isVector())
1562       return UnableToLegalize;
1563 
1564     SrcOp Src(SrcReg);
1565     if (SrcTy.isPointer()) {
1566       // Extracts from pointers can be handled only if they are really just
1567       // simple integers.
1568       const DataLayout &DL = MIRBuilder.getDataLayout();
1569       if (DL.isNonIntegralAddressSpace(SrcTy.getAddressSpace()))
1570         return UnableToLegalize;
1571 
1572       LLT SrcAsIntTy = LLT::scalar(SrcTy.getSizeInBits());
1573       Src = MIRBuilder.buildPtrToInt(SrcAsIntTy, Src);
1574       SrcTy = SrcAsIntTy;
1575     }
1576 
1577     if (DstTy.isPointer())
1578       return UnableToLegalize;
1579 
1580     if (Offset == 0) {
1581       // Avoid a shift in the degenerate case.
1582       MIRBuilder.buildTrunc(DstReg,
1583                             MIRBuilder.buildAnyExtOrTrunc(WideTy, Src));
1584       MI.eraseFromParent();
1585       return Legalized;
1586     }
1587 
1588     // Do a shift in the source type.
1589     LLT ShiftTy = SrcTy;
1590     if (WideTy.getSizeInBits() > SrcTy.getSizeInBits()) {
1591       Src = MIRBuilder.buildAnyExt(WideTy, Src);
1592       ShiftTy = WideTy;
1593     } else if (WideTy.getSizeInBits() > SrcTy.getSizeInBits())
1594       return UnableToLegalize;
1595 
1596     auto LShr = MIRBuilder.buildLShr(
1597       ShiftTy, Src, MIRBuilder.buildConstant(ShiftTy, Offset));
1598     MIRBuilder.buildTrunc(DstReg, LShr);
1599     MI.eraseFromParent();
1600     return Legalized;
1601   }
1602 
1603   if (SrcTy.isScalar()) {
1604     Observer.changingInstr(MI);
1605     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
1606     Observer.changedInstr(MI);
1607     return Legalized;
1608   }
1609 
1610   if (!SrcTy.isVector())
1611     return UnableToLegalize;
1612 
1613   if (DstTy != SrcTy.getElementType())
1614     return UnableToLegalize;
1615 
1616   if (Offset % SrcTy.getScalarSizeInBits() != 0)
1617     return UnableToLegalize;
1618 
1619   Observer.changingInstr(MI);
1620   widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
1621 
1622   MI.getOperand(2).setImm((WideTy.getSizeInBits() / SrcTy.getSizeInBits()) *
1623                           Offset);
1624   widenScalarDst(MI, WideTy.getScalarType(), 0);
1625   Observer.changedInstr(MI);
1626   return Legalized;
1627 }
1628 
1629 LegalizerHelper::LegalizeResult
1630 LegalizerHelper::widenScalarInsert(MachineInstr &MI, unsigned TypeIdx,
1631                                    LLT WideTy) {
1632   if (TypeIdx != 0)
1633     return UnableToLegalize;
1634   Observer.changingInstr(MI);
1635   widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
1636   widenScalarDst(MI, WideTy);
1637   Observer.changedInstr(MI);
1638   return Legalized;
1639 }
1640 
1641 LegalizerHelper::LegalizeResult
1642 LegalizerHelper::widenScalarAddSubSat(MachineInstr &MI, unsigned TypeIdx,
1643                                       LLT WideTy) {
1644   bool IsSigned = MI.getOpcode() == TargetOpcode::G_SADDSAT ||
1645                   MI.getOpcode() == TargetOpcode::G_SSUBSAT;
1646   // We can convert this to:
1647   //   1. Any extend iN to iM
1648   //   2. SHL by M-N
1649   //   3. [US][ADD|SUB]SAT
1650   //   4. L/ASHR by M-N
1651   //
1652   // It may be more efficient to lower this to a min and a max operation in
1653   // the higher precision arithmetic if the promoted operation isn't legal,
1654   // but this decision is up to the target's lowering request.
1655   Register DstReg = MI.getOperand(0).getReg();
1656 
1657   unsigned NewBits = WideTy.getScalarSizeInBits();
1658   unsigned SHLAmount = NewBits - MRI.getType(DstReg).getScalarSizeInBits();
1659 
1660   auto LHS = MIRBuilder.buildAnyExt(WideTy, MI.getOperand(1));
1661   auto RHS = MIRBuilder.buildAnyExt(WideTy, MI.getOperand(2));
1662   auto ShiftK = MIRBuilder.buildConstant(WideTy, SHLAmount);
1663   auto ShiftL = MIRBuilder.buildShl(WideTy, LHS, ShiftK);
1664   auto ShiftR = MIRBuilder.buildShl(WideTy, RHS, ShiftK);
1665 
1666   auto WideInst = MIRBuilder.buildInstr(MI.getOpcode(), {WideTy},
1667                                         {ShiftL, ShiftR}, MI.getFlags());
1668 
1669   // Use a shift that will preserve the number of sign bits when the trunc is
1670   // folded away.
1671   auto Result = IsSigned ? MIRBuilder.buildAShr(WideTy, WideInst, ShiftK)
1672                          : MIRBuilder.buildLShr(WideTy, WideInst, ShiftK);
1673 
1674   MIRBuilder.buildTrunc(DstReg, Result);
1675   MI.eraseFromParent();
1676   return Legalized;
1677 }
1678 
1679 LegalizerHelper::LegalizeResult
1680 LegalizerHelper::widenScalar(MachineInstr &MI, unsigned TypeIdx, LLT WideTy) {
1681   switch (MI.getOpcode()) {
1682   default:
1683     return UnableToLegalize;
1684   case TargetOpcode::G_EXTRACT:
1685     return widenScalarExtract(MI, TypeIdx, WideTy);
1686   case TargetOpcode::G_INSERT:
1687     return widenScalarInsert(MI, TypeIdx, WideTy);
1688   case TargetOpcode::G_MERGE_VALUES:
1689     return widenScalarMergeValues(MI, TypeIdx, WideTy);
1690   case TargetOpcode::G_UNMERGE_VALUES:
1691     return widenScalarUnmergeValues(MI, TypeIdx, WideTy);
1692   case TargetOpcode::G_UADDO:
1693   case TargetOpcode::G_USUBO: {
1694     if (TypeIdx == 1)
1695       return UnableToLegalize; // TODO
1696     auto LHSZext = MIRBuilder.buildZExt(WideTy, MI.getOperand(2));
1697     auto RHSZext = MIRBuilder.buildZExt(WideTy, MI.getOperand(3));
1698     unsigned Opcode = MI.getOpcode() == TargetOpcode::G_UADDO
1699                           ? TargetOpcode::G_ADD
1700                           : TargetOpcode::G_SUB;
1701     // Do the arithmetic in the larger type.
1702     auto NewOp = MIRBuilder.buildInstr(Opcode, {WideTy}, {LHSZext, RHSZext});
1703     LLT OrigTy = MRI.getType(MI.getOperand(0).getReg());
1704     APInt Mask =
1705         APInt::getLowBitsSet(WideTy.getSizeInBits(), OrigTy.getSizeInBits());
1706     auto AndOp = MIRBuilder.buildAnd(
1707         WideTy, NewOp, MIRBuilder.buildConstant(WideTy, Mask));
1708     // There is no overflow if the AndOp is the same as NewOp.
1709     MIRBuilder.buildICmp(CmpInst::ICMP_NE, MI.getOperand(1), NewOp, AndOp);
1710     // Now trunc the NewOp to the original result.
1711     MIRBuilder.buildTrunc(MI.getOperand(0), NewOp);
1712     MI.eraseFromParent();
1713     return Legalized;
1714   }
1715   case TargetOpcode::G_SADDSAT:
1716   case TargetOpcode::G_SSUBSAT:
1717   case TargetOpcode::G_UADDSAT:
1718   case TargetOpcode::G_USUBSAT:
1719     return widenScalarAddSubSat(MI, TypeIdx, WideTy);
1720   case TargetOpcode::G_CTTZ:
1721   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
1722   case TargetOpcode::G_CTLZ:
1723   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
1724   case TargetOpcode::G_CTPOP: {
1725     if (TypeIdx == 0) {
1726       Observer.changingInstr(MI);
1727       widenScalarDst(MI, WideTy, 0);
1728       Observer.changedInstr(MI);
1729       return Legalized;
1730     }
1731 
1732     Register SrcReg = MI.getOperand(1).getReg();
1733 
1734     // First ZEXT the input.
1735     auto MIBSrc = MIRBuilder.buildZExt(WideTy, SrcReg);
1736     LLT CurTy = MRI.getType(SrcReg);
1737     if (MI.getOpcode() == TargetOpcode::G_CTTZ) {
1738       // The count is the same in the larger type except if the original
1739       // value was zero.  This can be handled by setting the bit just off
1740       // the top of the original type.
1741       auto TopBit =
1742           APInt::getOneBitSet(WideTy.getSizeInBits(), CurTy.getSizeInBits());
1743       MIBSrc = MIRBuilder.buildOr(
1744         WideTy, MIBSrc, MIRBuilder.buildConstant(WideTy, TopBit));
1745     }
1746 
1747     // Perform the operation at the larger size.
1748     auto MIBNewOp = MIRBuilder.buildInstr(MI.getOpcode(), {WideTy}, {MIBSrc});
1749     // This is already the correct result for CTPOP and CTTZs
1750     if (MI.getOpcode() == TargetOpcode::G_CTLZ ||
1751         MI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_UNDEF) {
1752       // The correct result is NewOp - (Difference in widety and current ty).
1753       unsigned SizeDiff = WideTy.getSizeInBits() - CurTy.getSizeInBits();
1754       MIBNewOp = MIRBuilder.buildSub(
1755           WideTy, MIBNewOp, MIRBuilder.buildConstant(WideTy, SizeDiff));
1756     }
1757 
1758     MIRBuilder.buildZExtOrTrunc(MI.getOperand(0), MIBNewOp);
1759     MI.eraseFromParent();
1760     return Legalized;
1761   }
1762   case TargetOpcode::G_BSWAP: {
1763     Observer.changingInstr(MI);
1764     Register DstReg = MI.getOperand(0).getReg();
1765 
1766     Register ShrReg = MRI.createGenericVirtualRegister(WideTy);
1767     Register DstExt = MRI.createGenericVirtualRegister(WideTy);
1768     Register ShiftAmtReg = MRI.createGenericVirtualRegister(WideTy);
1769     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
1770 
1771     MI.getOperand(0).setReg(DstExt);
1772 
1773     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
1774 
1775     LLT Ty = MRI.getType(DstReg);
1776     unsigned DiffBits = WideTy.getScalarSizeInBits() - Ty.getScalarSizeInBits();
1777     MIRBuilder.buildConstant(ShiftAmtReg, DiffBits);
1778     MIRBuilder.buildLShr(ShrReg, DstExt, ShiftAmtReg);
1779 
1780     MIRBuilder.buildTrunc(DstReg, ShrReg);
1781     Observer.changedInstr(MI);
1782     return Legalized;
1783   }
1784   case TargetOpcode::G_BITREVERSE: {
1785     Observer.changingInstr(MI);
1786 
1787     Register DstReg = MI.getOperand(0).getReg();
1788     LLT Ty = MRI.getType(DstReg);
1789     unsigned DiffBits = WideTy.getScalarSizeInBits() - Ty.getScalarSizeInBits();
1790 
1791     Register DstExt = MRI.createGenericVirtualRegister(WideTy);
1792     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
1793     MI.getOperand(0).setReg(DstExt);
1794     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
1795 
1796     auto ShiftAmt = MIRBuilder.buildConstant(WideTy, DiffBits);
1797     auto Shift = MIRBuilder.buildLShr(WideTy, DstExt, ShiftAmt);
1798     MIRBuilder.buildTrunc(DstReg, Shift);
1799     Observer.changedInstr(MI);
1800     return Legalized;
1801   }
1802   case TargetOpcode::G_FREEZE:
1803     Observer.changingInstr(MI);
1804     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
1805     widenScalarDst(MI, WideTy);
1806     Observer.changedInstr(MI);
1807     return Legalized;
1808 
1809   case TargetOpcode::G_ADD:
1810   case TargetOpcode::G_AND:
1811   case TargetOpcode::G_MUL:
1812   case TargetOpcode::G_OR:
1813   case TargetOpcode::G_XOR:
1814   case TargetOpcode::G_SUB:
1815     // Perform operation at larger width (any extension is fines here, high bits
1816     // don't affect the result) and then truncate the result back to the
1817     // original type.
1818     Observer.changingInstr(MI);
1819     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
1820     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
1821     widenScalarDst(MI, WideTy);
1822     Observer.changedInstr(MI);
1823     return Legalized;
1824 
1825   case TargetOpcode::G_SHL:
1826     Observer.changingInstr(MI);
1827 
1828     if (TypeIdx == 0) {
1829       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
1830       widenScalarDst(MI, WideTy);
1831     } else {
1832       assert(TypeIdx == 1);
1833       // The "number of bits to shift" operand must preserve its value as an
1834       // unsigned integer:
1835       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
1836     }
1837 
1838     Observer.changedInstr(MI);
1839     return Legalized;
1840 
1841   case TargetOpcode::G_SDIV:
1842   case TargetOpcode::G_SREM:
1843   case TargetOpcode::G_SMIN:
1844   case TargetOpcode::G_SMAX:
1845     Observer.changingInstr(MI);
1846     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
1847     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
1848     widenScalarDst(MI, WideTy);
1849     Observer.changedInstr(MI);
1850     return Legalized;
1851 
1852   case TargetOpcode::G_ASHR:
1853   case TargetOpcode::G_LSHR:
1854     Observer.changingInstr(MI);
1855 
1856     if (TypeIdx == 0) {
1857       unsigned CvtOp = MI.getOpcode() == TargetOpcode::G_ASHR ?
1858         TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
1859 
1860       widenScalarSrc(MI, WideTy, 1, CvtOp);
1861       widenScalarDst(MI, WideTy);
1862     } else {
1863       assert(TypeIdx == 1);
1864       // The "number of bits to shift" operand must preserve its value as an
1865       // unsigned integer:
1866       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
1867     }
1868 
1869     Observer.changedInstr(MI);
1870     return Legalized;
1871   case TargetOpcode::G_UDIV:
1872   case TargetOpcode::G_UREM:
1873   case TargetOpcode::G_UMIN:
1874   case TargetOpcode::G_UMAX:
1875     Observer.changingInstr(MI);
1876     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
1877     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
1878     widenScalarDst(MI, WideTy);
1879     Observer.changedInstr(MI);
1880     return Legalized;
1881 
1882   case TargetOpcode::G_SELECT:
1883     Observer.changingInstr(MI);
1884     if (TypeIdx == 0) {
1885       // Perform operation at larger width (any extension is fine here, high
1886       // bits don't affect the result) and then truncate the result back to the
1887       // original type.
1888       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
1889       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ANYEXT);
1890       widenScalarDst(MI, WideTy);
1891     } else {
1892       bool IsVec = MRI.getType(MI.getOperand(1).getReg()).isVector();
1893       // Explicit extension is required here since high bits affect the result.
1894       widenScalarSrc(MI, WideTy, 1, MIRBuilder.getBoolExtOp(IsVec, false));
1895     }
1896     Observer.changedInstr(MI);
1897     return Legalized;
1898 
1899   case TargetOpcode::G_FPTOSI:
1900   case TargetOpcode::G_FPTOUI:
1901     Observer.changingInstr(MI);
1902 
1903     if (TypeIdx == 0)
1904       widenScalarDst(MI, WideTy);
1905     else
1906       widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_FPEXT);
1907 
1908     Observer.changedInstr(MI);
1909     return Legalized;
1910   case TargetOpcode::G_SITOFP:
1911     if (TypeIdx != 1)
1912       return UnableToLegalize;
1913     Observer.changingInstr(MI);
1914     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
1915     Observer.changedInstr(MI);
1916     return Legalized;
1917 
1918   case TargetOpcode::G_UITOFP:
1919     if (TypeIdx != 1)
1920       return UnableToLegalize;
1921     Observer.changingInstr(MI);
1922     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
1923     Observer.changedInstr(MI);
1924     return Legalized;
1925 
1926   case TargetOpcode::G_LOAD:
1927   case TargetOpcode::G_SEXTLOAD:
1928   case TargetOpcode::G_ZEXTLOAD:
1929     Observer.changingInstr(MI);
1930     widenScalarDst(MI, WideTy);
1931     Observer.changedInstr(MI);
1932     return Legalized;
1933 
1934   case TargetOpcode::G_STORE: {
1935     if (TypeIdx != 0)
1936       return UnableToLegalize;
1937 
1938     LLT Ty = MRI.getType(MI.getOperand(0).getReg());
1939     if (!isPowerOf2_32(Ty.getSizeInBits()))
1940       return UnableToLegalize;
1941 
1942     Observer.changingInstr(MI);
1943 
1944     unsigned ExtType = Ty.getScalarSizeInBits() == 1 ?
1945       TargetOpcode::G_ZEXT : TargetOpcode::G_ANYEXT;
1946     widenScalarSrc(MI, WideTy, 0, ExtType);
1947 
1948     Observer.changedInstr(MI);
1949     return Legalized;
1950   }
1951   case TargetOpcode::G_CONSTANT: {
1952     MachineOperand &SrcMO = MI.getOperand(1);
1953     LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
1954     unsigned ExtOpc = LI.getExtOpcodeForWideningConstant(
1955         MRI.getType(MI.getOperand(0).getReg()));
1956     assert((ExtOpc == TargetOpcode::G_ZEXT || ExtOpc == TargetOpcode::G_SEXT ||
1957             ExtOpc == TargetOpcode::G_ANYEXT) &&
1958            "Illegal Extend");
1959     const APInt &SrcVal = SrcMO.getCImm()->getValue();
1960     const APInt &Val = (ExtOpc == TargetOpcode::G_SEXT)
1961                            ? SrcVal.sext(WideTy.getSizeInBits())
1962                            : SrcVal.zext(WideTy.getSizeInBits());
1963     Observer.changingInstr(MI);
1964     SrcMO.setCImm(ConstantInt::get(Ctx, Val));
1965 
1966     widenScalarDst(MI, WideTy);
1967     Observer.changedInstr(MI);
1968     return Legalized;
1969   }
1970   case TargetOpcode::G_FCONSTANT: {
1971     MachineOperand &SrcMO = MI.getOperand(1);
1972     LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
1973     APFloat Val = SrcMO.getFPImm()->getValueAPF();
1974     bool LosesInfo;
1975     switch (WideTy.getSizeInBits()) {
1976     case 32:
1977       Val.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
1978                   &LosesInfo);
1979       break;
1980     case 64:
1981       Val.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
1982                   &LosesInfo);
1983       break;
1984     default:
1985       return UnableToLegalize;
1986     }
1987 
1988     assert(!LosesInfo && "extend should always be lossless");
1989 
1990     Observer.changingInstr(MI);
1991     SrcMO.setFPImm(ConstantFP::get(Ctx, Val));
1992 
1993     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
1994     Observer.changedInstr(MI);
1995     return Legalized;
1996   }
1997   case TargetOpcode::G_IMPLICIT_DEF: {
1998     Observer.changingInstr(MI);
1999     widenScalarDst(MI, WideTy);
2000     Observer.changedInstr(MI);
2001     return Legalized;
2002   }
2003   case TargetOpcode::G_BRCOND:
2004     Observer.changingInstr(MI);
2005     widenScalarSrc(MI, WideTy, 0, MIRBuilder.getBoolExtOp(false, false));
2006     Observer.changedInstr(MI);
2007     return Legalized;
2008 
2009   case TargetOpcode::G_FCMP:
2010     Observer.changingInstr(MI);
2011     if (TypeIdx == 0)
2012       widenScalarDst(MI, WideTy);
2013     else {
2014       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_FPEXT);
2015       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_FPEXT);
2016     }
2017     Observer.changedInstr(MI);
2018     return Legalized;
2019 
2020   case TargetOpcode::G_ICMP:
2021     Observer.changingInstr(MI);
2022     if (TypeIdx == 0)
2023       widenScalarDst(MI, WideTy);
2024     else {
2025       unsigned ExtOpcode = CmpInst::isSigned(static_cast<CmpInst::Predicate>(
2026                                MI.getOperand(1).getPredicate()))
2027                                ? TargetOpcode::G_SEXT
2028                                : TargetOpcode::G_ZEXT;
2029       widenScalarSrc(MI, WideTy, 2, ExtOpcode);
2030       widenScalarSrc(MI, WideTy, 3, ExtOpcode);
2031     }
2032     Observer.changedInstr(MI);
2033     return Legalized;
2034 
2035   case TargetOpcode::G_PTR_ADD:
2036     assert(TypeIdx == 1 && "unable to legalize pointer of G_PTR_ADD");
2037     Observer.changingInstr(MI);
2038     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
2039     Observer.changedInstr(MI);
2040     return Legalized;
2041 
2042   case TargetOpcode::G_PHI: {
2043     assert(TypeIdx == 0 && "Expecting only Idx 0");
2044 
2045     Observer.changingInstr(MI);
2046     for (unsigned I = 1; I < MI.getNumOperands(); I += 2) {
2047       MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
2048       MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
2049       widenScalarSrc(MI, WideTy, I, TargetOpcode::G_ANYEXT);
2050     }
2051 
2052     MachineBasicBlock &MBB = *MI.getParent();
2053     MIRBuilder.setInsertPt(MBB, --MBB.getFirstNonPHI());
2054     widenScalarDst(MI, WideTy);
2055     Observer.changedInstr(MI);
2056     return Legalized;
2057   }
2058   case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
2059     if (TypeIdx == 0) {
2060       Register VecReg = MI.getOperand(1).getReg();
2061       LLT VecTy = MRI.getType(VecReg);
2062       Observer.changingInstr(MI);
2063 
2064       widenScalarSrc(MI, LLT::vector(VecTy.getNumElements(),
2065                                      WideTy.getSizeInBits()),
2066                      1, TargetOpcode::G_SEXT);
2067 
2068       widenScalarDst(MI, WideTy, 0);
2069       Observer.changedInstr(MI);
2070       return Legalized;
2071     }
2072 
2073     if (TypeIdx != 2)
2074       return UnableToLegalize;
2075     Observer.changingInstr(MI);
2076     // TODO: Probably should be zext
2077     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
2078     Observer.changedInstr(MI);
2079     return Legalized;
2080   }
2081   case TargetOpcode::G_INSERT_VECTOR_ELT: {
2082     if (TypeIdx == 1) {
2083       Observer.changingInstr(MI);
2084 
2085       Register VecReg = MI.getOperand(1).getReg();
2086       LLT VecTy = MRI.getType(VecReg);
2087       LLT WideVecTy = LLT::vector(VecTy.getNumElements(), WideTy);
2088 
2089       widenScalarSrc(MI, WideVecTy, 1, TargetOpcode::G_ANYEXT);
2090       widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
2091       widenScalarDst(MI, WideVecTy, 0);
2092       Observer.changedInstr(MI);
2093       return Legalized;
2094     }
2095 
2096     if (TypeIdx == 2) {
2097       Observer.changingInstr(MI);
2098       // TODO: Probably should be zext
2099       widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_SEXT);
2100       Observer.changedInstr(MI);
2101       return Legalized;
2102     }
2103 
2104     return UnableToLegalize;
2105   }
2106   case TargetOpcode::G_FADD:
2107   case TargetOpcode::G_FMUL:
2108   case TargetOpcode::G_FSUB:
2109   case TargetOpcode::G_FMA:
2110   case TargetOpcode::G_FMAD:
2111   case TargetOpcode::G_FNEG:
2112   case TargetOpcode::G_FABS:
2113   case TargetOpcode::G_FCANONICALIZE:
2114   case TargetOpcode::G_FMINNUM:
2115   case TargetOpcode::G_FMAXNUM:
2116   case TargetOpcode::G_FMINNUM_IEEE:
2117   case TargetOpcode::G_FMAXNUM_IEEE:
2118   case TargetOpcode::G_FMINIMUM:
2119   case TargetOpcode::G_FMAXIMUM:
2120   case TargetOpcode::G_FDIV:
2121   case TargetOpcode::G_FREM:
2122   case TargetOpcode::G_FCEIL:
2123   case TargetOpcode::G_FFLOOR:
2124   case TargetOpcode::G_FCOS:
2125   case TargetOpcode::G_FSIN:
2126   case TargetOpcode::G_FLOG10:
2127   case TargetOpcode::G_FLOG:
2128   case TargetOpcode::G_FLOG2:
2129   case TargetOpcode::G_FRINT:
2130   case TargetOpcode::G_FNEARBYINT:
2131   case TargetOpcode::G_FSQRT:
2132   case TargetOpcode::G_FEXP:
2133   case TargetOpcode::G_FEXP2:
2134   case TargetOpcode::G_FPOW:
2135   case TargetOpcode::G_INTRINSIC_TRUNC:
2136   case TargetOpcode::G_INTRINSIC_ROUND:
2137     assert(TypeIdx == 0);
2138     Observer.changingInstr(MI);
2139 
2140     for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
2141       widenScalarSrc(MI, WideTy, I, TargetOpcode::G_FPEXT);
2142 
2143     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
2144     Observer.changedInstr(MI);
2145     return Legalized;
2146   case TargetOpcode::G_INTTOPTR:
2147     if (TypeIdx != 1)
2148       return UnableToLegalize;
2149 
2150     Observer.changingInstr(MI);
2151     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
2152     Observer.changedInstr(MI);
2153     return Legalized;
2154   case TargetOpcode::G_PTRTOINT:
2155     if (TypeIdx != 0)
2156       return UnableToLegalize;
2157 
2158     Observer.changingInstr(MI);
2159     widenScalarDst(MI, WideTy, 0);
2160     Observer.changedInstr(MI);
2161     return Legalized;
2162   case TargetOpcode::G_BUILD_VECTOR: {
2163     Observer.changingInstr(MI);
2164 
2165     const LLT WideEltTy = TypeIdx == 1 ? WideTy : WideTy.getElementType();
2166     for (int I = 1, E = MI.getNumOperands(); I != E; ++I)
2167       widenScalarSrc(MI, WideEltTy, I, TargetOpcode::G_ANYEXT);
2168 
2169     // Avoid changing the result vector type if the source element type was
2170     // requested.
2171     if (TypeIdx == 1) {
2172       auto &TII = *MI.getMF()->getSubtarget().getInstrInfo();
2173       MI.setDesc(TII.get(TargetOpcode::G_BUILD_VECTOR_TRUNC));
2174     } else {
2175       widenScalarDst(MI, WideTy, 0);
2176     }
2177 
2178     Observer.changedInstr(MI);
2179     return Legalized;
2180   }
2181   case TargetOpcode::G_SEXT_INREG:
2182     if (TypeIdx != 0)
2183       return UnableToLegalize;
2184 
2185     Observer.changingInstr(MI);
2186     widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
2187     widenScalarDst(MI, WideTy, 0, TargetOpcode::G_TRUNC);
2188     Observer.changedInstr(MI);
2189     return Legalized;
2190   case TargetOpcode::G_PTRMASK: {
2191     if (TypeIdx != 1)
2192       return UnableToLegalize;
2193     Observer.changingInstr(MI);
2194     widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
2195     Observer.changedInstr(MI);
2196     return Legalized;
2197   }
2198   }
2199 }
2200 
2201 static void getUnmergePieces(SmallVectorImpl<Register> &Pieces,
2202                              MachineIRBuilder &B, Register Src, LLT Ty) {
2203   auto Unmerge = B.buildUnmerge(Ty, Src);
2204   for (int I = 0, E = Unmerge->getNumOperands() - 1; I != E; ++I)
2205     Pieces.push_back(Unmerge.getReg(I));
2206 }
2207 
2208 LegalizerHelper::LegalizeResult
2209 LegalizerHelper::lowerBitcast(MachineInstr &MI) {
2210   Register Dst = MI.getOperand(0).getReg();
2211   Register Src = MI.getOperand(1).getReg();
2212   LLT DstTy = MRI.getType(Dst);
2213   LLT SrcTy = MRI.getType(Src);
2214 
2215   if (SrcTy.isVector()) {
2216     LLT SrcEltTy = SrcTy.getElementType();
2217     SmallVector<Register, 8> SrcRegs;
2218 
2219     if (DstTy.isVector()) {
2220       int NumDstElt = DstTy.getNumElements();
2221       int NumSrcElt = SrcTy.getNumElements();
2222 
2223       LLT DstEltTy = DstTy.getElementType();
2224       LLT DstCastTy = DstEltTy; // Intermediate bitcast result type
2225       LLT SrcPartTy = SrcEltTy; // Original unmerge result type.
2226 
2227       // If there's an element size mismatch, insert intermediate casts to match
2228       // the result element type.
2229       if (NumSrcElt < NumDstElt) { // Source element type is larger.
2230         // %1:_(<4 x s8>) = G_BITCAST %0:_(<2 x s16>)
2231         //
2232         // =>
2233         //
2234         // %2:_(s16), %3:_(s16) = G_UNMERGE_VALUES %0
2235         // %3:_(<2 x s8>) = G_BITCAST %2
2236         // %4:_(<2 x s8>) = G_BITCAST %3
2237         // %1:_(<4 x s16>) = G_CONCAT_VECTORS %3, %4
2238         DstCastTy = LLT::vector(NumDstElt / NumSrcElt, DstEltTy);
2239         SrcPartTy = SrcEltTy;
2240       } else if (NumSrcElt > NumDstElt) { // Source element type is smaller.
2241         //
2242         // %1:_(<2 x s16>) = G_BITCAST %0:_(<4 x s8>)
2243         //
2244         // =>
2245         //
2246         // %2:_(<2 x s8>), %3:_(<2 x s8>) = G_UNMERGE_VALUES %0
2247         // %3:_(s16) = G_BITCAST %2
2248         // %4:_(s16) = G_BITCAST %3
2249         // %1:_(<2 x s16>) = G_BUILD_VECTOR %3, %4
2250         SrcPartTy = LLT::vector(NumSrcElt / NumDstElt, SrcEltTy);
2251         DstCastTy = DstEltTy;
2252       }
2253 
2254       getUnmergePieces(SrcRegs, MIRBuilder, Src, SrcPartTy);
2255       for (Register &SrcReg : SrcRegs)
2256         SrcReg = MIRBuilder.buildBitcast(DstCastTy, SrcReg).getReg(0);
2257     } else
2258       getUnmergePieces(SrcRegs, MIRBuilder, Src, SrcEltTy);
2259 
2260     MIRBuilder.buildMerge(Dst, SrcRegs);
2261     MI.eraseFromParent();
2262     return Legalized;
2263   }
2264 
2265   if (DstTy.isVector()) {
2266     SmallVector<Register, 8> SrcRegs;
2267     getUnmergePieces(SrcRegs, MIRBuilder, Src, DstTy.getElementType());
2268     MIRBuilder.buildMerge(Dst, SrcRegs);
2269     MI.eraseFromParent();
2270     return Legalized;
2271   }
2272 
2273   return UnableToLegalize;
2274 }
2275 
2276 LegalizerHelper::LegalizeResult
2277 LegalizerHelper::bitcast(MachineInstr &MI, unsigned TypeIdx, LLT CastTy) {
2278   switch (MI.getOpcode()) {
2279   case TargetOpcode::G_LOAD: {
2280     if (TypeIdx != 0)
2281       return UnableToLegalize;
2282 
2283     Observer.changingInstr(MI);
2284     bitcastDst(MI, CastTy, 0);
2285     Observer.changedInstr(MI);
2286     return Legalized;
2287   }
2288   case TargetOpcode::G_STORE: {
2289     if (TypeIdx != 0)
2290       return UnableToLegalize;
2291 
2292     Observer.changingInstr(MI);
2293     bitcastSrc(MI, CastTy, 0);
2294     Observer.changedInstr(MI);
2295     return Legalized;
2296   }
2297   case TargetOpcode::G_SELECT: {
2298     if (TypeIdx != 0)
2299       return UnableToLegalize;
2300 
2301     if (MRI.getType(MI.getOperand(1).getReg()).isVector()) {
2302       LLVM_DEBUG(
2303           dbgs() << "bitcast action not implemented for vector select\n");
2304       return UnableToLegalize;
2305     }
2306 
2307     Observer.changingInstr(MI);
2308     bitcastSrc(MI, CastTy, 2);
2309     bitcastSrc(MI, CastTy, 3);
2310     bitcastDst(MI, CastTy, 0);
2311     Observer.changedInstr(MI);
2312     return Legalized;
2313   }
2314   case TargetOpcode::G_AND:
2315   case TargetOpcode::G_OR:
2316   case TargetOpcode::G_XOR: {
2317     Observer.changingInstr(MI);
2318     bitcastSrc(MI, CastTy, 1);
2319     bitcastSrc(MI, CastTy, 2);
2320     bitcastDst(MI, CastTy, 0);
2321     Observer.changedInstr(MI);
2322     return Legalized;
2323   }
2324   default:
2325     return UnableToLegalize;
2326   }
2327 }
2328 
2329 LegalizerHelper::LegalizeResult
2330 LegalizerHelper::lower(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
2331   using namespace TargetOpcode;
2332 
2333   switch(MI.getOpcode()) {
2334   default:
2335     return UnableToLegalize;
2336   case TargetOpcode::G_BITCAST:
2337     return lowerBitcast(MI);
2338   case TargetOpcode::G_SREM:
2339   case TargetOpcode::G_UREM: {
2340     auto Quot =
2341         MIRBuilder.buildInstr(MI.getOpcode() == G_SREM ? G_SDIV : G_UDIV, {Ty},
2342                               {MI.getOperand(1), MI.getOperand(2)});
2343 
2344     auto Prod = MIRBuilder.buildMul(Ty, Quot, MI.getOperand(2));
2345     MIRBuilder.buildSub(MI.getOperand(0), MI.getOperand(1), Prod);
2346     MI.eraseFromParent();
2347     return Legalized;
2348   }
2349   case TargetOpcode::G_SADDO:
2350   case TargetOpcode::G_SSUBO:
2351     return lowerSADDO_SSUBO(MI);
2352   case TargetOpcode::G_SMULO:
2353   case TargetOpcode::G_UMULO: {
2354     // Generate G_UMULH/G_SMULH to check for overflow and a normal G_MUL for the
2355     // result.
2356     Register Res = MI.getOperand(0).getReg();
2357     Register Overflow = MI.getOperand(1).getReg();
2358     Register LHS = MI.getOperand(2).getReg();
2359     Register RHS = MI.getOperand(3).getReg();
2360 
2361     unsigned Opcode = MI.getOpcode() == TargetOpcode::G_SMULO
2362                           ? TargetOpcode::G_SMULH
2363                           : TargetOpcode::G_UMULH;
2364 
2365     Observer.changingInstr(MI);
2366     const auto &TII = MIRBuilder.getTII();
2367     MI.setDesc(TII.get(TargetOpcode::G_MUL));
2368     MI.RemoveOperand(1);
2369     Observer.changedInstr(MI);
2370 
2371     auto HiPart = MIRBuilder.buildInstr(Opcode, {Ty}, {LHS, RHS});
2372     auto Zero = MIRBuilder.buildConstant(Ty, 0);
2373 
2374     // Move insert point forward so we can use the Res register if needed.
2375     MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
2376 
2377     // For *signed* multiply, overflow is detected by checking:
2378     // (hi != (lo >> bitwidth-1))
2379     if (Opcode == TargetOpcode::G_SMULH) {
2380       auto ShiftAmt = MIRBuilder.buildConstant(Ty, Ty.getSizeInBits() - 1);
2381       auto Shifted = MIRBuilder.buildAShr(Ty, Res, ShiftAmt);
2382       MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Shifted);
2383     } else {
2384       MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Zero);
2385     }
2386     return Legalized;
2387   }
2388   case TargetOpcode::G_FNEG: {
2389     // TODO: Handle vector types once we are able to
2390     // represent them.
2391     if (Ty.isVector())
2392       return UnableToLegalize;
2393     Register Res = MI.getOperand(0).getReg();
2394     LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
2395     Type *ZeroTy = getFloatTypeForLLT(Ctx, Ty);
2396     if (!ZeroTy)
2397       return UnableToLegalize;
2398     ConstantFP &ZeroForNegation =
2399         *cast<ConstantFP>(ConstantFP::getZeroValueForNegation(ZeroTy));
2400     auto Zero = MIRBuilder.buildFConstant(Ty, ZeroForNegation);
2401     Register SubByReg = MI.getOperand(1).getReg();
2402     Register ZeroReg = Zero.getReg(0);
2403     MIRBuilder.buildFSub(Res, ZeroReg, SubByReg, MI.getFlags());
2404     MI.eraseFromParent();
2405     return Legalized;
2406   }
2407   case TargetOpcode::G_FSUB: {
2408     // Lower (G_FSUB LHS, RHS) to (G_FADD LHS, (G_FNEG RHS)).
2409     // First, check if G_FNEG is marked as Lower. If so, we may
2410     // end up with an infinite loop as G_FSUB is used to legalize G_FNEG.
2411     if (LI.getAction({G_FNEG, {Ty}}).Action == Lower)
2412       return UnableToLegalize;
2413     Register Res = MI.getOperand(0).getReg();
2414     Register LHS = MI.getOperand(1).getReg();
2415     Register RHS = MI.getOperand(2).getReg();
2416     Register Neg = MRI.createGenericVirtualRegister(Ty);
2417     MIRBuilder.buildFNeg(Neg, RHS);
2418     MIRBuilder.buildFAdd(Res, LHS, Neg, MI.getFlags());
2419     MI.eraseFromParent();
2420     return Legalized;
2421   }
2422   case TargetOpcode::G_FMAD:
2423     return lowerFMad(MI);
2424   case TargetOpcode::G_FFLOOR:
2425     return lowerFFloor(MI);
2426   case TargetOpcode::G_INTRINSIC_ROUND:
2427     return lowerIntrinsicRound(MI);
2428   case TargetOpcode::G_ATOMIC_CMPXCHG_WITH_SUCCESS: {
2429     Register OldValRes = MI.getOperand(0).getReg();
2430     Register SuccessRes = MI.getOperand(1).getReg();
2431     Register Addr = MI.getOperand(2).getReg();
2432     Register CmpVal = MI.getOperand(3).getReg();
2433     Register NewVal = MI.getOperand(4).getReg();
2434     MIRBuilder.buildAtomicCmpXchg(OldValRes, Addr, CmpVal, NewVal,
2435                                   **MI.memoperands_begin());
2436     MIRBuilder.buildICmp(CmpInst::ICMP_EQ, SuccessRes, OldValRes, CmpVal);
2437     MI.eraseFromParent();
2438     return Legalized;
2439   }
2440   case TargetOpcode::G_LOAD:
2441   case TargetOpcode::G_SEXTLOAD:
2442   case TargetOpcode::G_ZEXTLOAD: {
2443     // Lower to a memory-width G_LOAD and a G_SEXT/G_ZEXT/G_ANYEXT
2444     Register DstReg = MI.getOperand(0).getReg();
2445     Register PtrReg = MI.getOperand(1).getReg();
2446     LLT DstTy = MRI.getType(DstReg);
2447     auto &MMO = **MI.memoperands_begin();
2448 
2449     if (DstTy.getSizeInBits() == MMO.getSizeInBits()) {
2450       if (MI.getOpcode() == TargetOpcode::G_LOAD) {
2451         // This load needs splitting into power of 2 sized loads.
2452         if (DstTy.isVector())
2453           return UnableToLegalize;
2454         if (isPowerOf2_32(DstTy.getSizeInBits()))
2455           return UnableToLegalize; // Don't know what we're being asked to do.
2456 
2457         // Our strategy here is to generate anyextending loads for the smaller
2458         // types up to next power-2 result type, and then combine the two larger
2459         // result values together, before truncating back down to the non-pow-2
2460         // type.
2461         // E.g. v1 = i24 load =>
2462         // v2 = i32 zextload (2 byte)
2463         // v3 = i32 load (1 byte)
2464         // v4 = i32 shl v3, 16
2465         // v5 = i32 or v4, v2
2466         // v1 = i24 trunc v5
2467         // By doing this we generate the correct truncate which should get
2468         // combined away as an artifact with a matching extend.
2469         uint64_t LargeSplitSize = PowerOf2Floor(DstTy.getSizeInBits());
2470         uint64_t SmallSplitSize = DstTy.getSizeInBits() - LargeSplitSize;
2471 
2472         MachineFunction &MF = MIRBuilder.getMF();
2473         MachineMemOperand *LargeMMO =
2474             MF.getMachineMemOperand(&MMO, 0, LargeSplitSize / 8);
2475         MachineMemOperand *SmallMMO = MF.getMachineMemOperand(
2476             &MMO, LargeSplitSize / 8, SmallSplitSize / 8);
2477 
2478         LLT PtrTy = MRI.getType(PtrReg);
2479         unsigned AnyExtSize = NextPowerOf2(DstTy.getSizeInBits());
2480         LLT AnyExtTy = LLT::scalar(AnyExtSize);
2481         Register LargeLdReg = MRI.createGenericVirtualRegister(AnyExtTy);
2482         Register SmallLdReg = MRI.createGenericVirtualRegister(AnyExtTy);
2483         auto LargeLoad = MIRBuilder.buildLoadInstr(
2484             TargetOpcode::G_ZEXTLOAD, LargeLdReg, PtrReg, *LargeMMO);
2485 
2486         auto OffsetCst = MIRBuilder.buildConstant(
2487             LLT::scalar(PtrTy.getSizeInBits()), LargeSplitSize / 8);
2488         Register PtrAddReg = MRI.createGenericVirtualRegister(PtrTy);
2489         auto SmallPtr =
2490             MIRBuilder.buildPtrAdd(PtrAddReg, PtrReg, OffsetCst.getReg(0));
2491         auto SmallLoad = MIRBuilder.buildLoad(SmallLdReg, SmallPtr.getReg(0),
2492                                               *SmallMMO);
2493 
2494         auto ShiftAmt = MIRBuilder.buildConstant(AnyExtTy, LargeSplitSize);
2495         auto Shift = MIRBuilder.buildShl(AnyExtTy, SmallLoad, ShiftAmt);
2496         auto Or = MIRBuilder.buildOr(AnyExtTy, Shift, LargeLoad);
2497         MIRBuilder.buildTrunc(DstReg, {Or.getReg(0)});
2498         MI.eraseFromParent();
2499         return Legalized;
2500       }
2501       MIRBuilder.buildLoad(DstReg, PtrReg, MMO);
2502       MI.eraseFromParent();
2503       return Legalized;
2504     }
2505 
2506     if (DstTy.isScalar()) {
2507       Register TmpReg =
2508           MRI.createGenericVirtualRegister(LLT::scalar(MMO.getSizeInBits()));
2509       MIRBuilder.buildLoad(TmpReg, PtrReg, MMO);
2510       switch (MI.getOpcode()) {
2511       default:
2512         llvm_unreachable("Unexpected opcode");
2513       case TargetOpcode::G_LOAD:
2514         MIRBuilder.buildExtOrTrunc(TargetOpcode::G_ANYEXT, DstReg, TmpReg);
2515         break;
2516       case TargetOpcode::G_SEXTLOAD:
2517         MIRBuilder.buildSExt(DstReg, TmpReg);
2518         break;
2519       case TargetOpcode::G_ZEXTLOAD:
2520         MIRBuilder.buildZExt(DstReg, TmpReg);
2521         break;
2522       }
2523       MI.eraseFromParent();
2524       return Legalized;
2525     }
2526 
2527     return UnableToLegalize;
2528   }
2529   case TargetOpcode::G_STORE: {
2530     // Lower a non-power of 2 store into multiple pow-2 stores.
2531     // E.g. split an i24 store into an i16 store + i8 store.
2532     // We do this by first extending the stored value to the next largest power
2533     // of 2 type, and then using truncating stores to store the components.
2534     // By doing this, likewise with G_LOAD, generate an extend that can be
2535     // artifact-combined away instead of leaving behind extracts.
2536     Register SrcReg = MI.getOperand(0).getReg();
2537     Register PtrReg = MI.getOperand(1).getReg();
2538     LLT SrcTy = MRI.getType(SrcReg);
2539     MachineMemOperand &MMO = **MI.memoperands_begin();
2540     if (SrcTy.getSizeInBits() != MMO.getSizeInBits())
2541       return UnableToLegalize;
2542     if (SrcTy.isVector())
2543       return UnableToLegalize;
2544     if (isPowerOf2_32(SrcTy.getSizeInBits()))
2545       return UnableToLegalize; // Don't know what we're being asked to do.
2546 
2547     // Extend to the next pow-2.
2548     const LLT ExtendTy = LLT::scalar(NextPowerOf2(SrcTy.getSizeInBits()));
2549     auto ExtVal = MIRBuilder.buildAnyExt(ExtendTy, SrcReg);
2550 
2551     // Obtain the smaller value by shifting away the larger value.
2552     uint64_t LargeSplitSize = PowerOf2Floor(SrcTy.getSizeInBits());
2553     uint64_t SmallSplitSize = SrcTy.getSizeInBits() - LargeSplitSize;
2554     auto ShiftAmt = MIRBuilder.buildConstant(ExtendTy, LargeSplitSize);
2555     auto SmallVal = MIRBuilder.buildLShr(ExtendTy, ExtVal, ShiftAmt);
2556 
2557     // Generate the PtrAdd and truncating stores.
2558     LLT PtrTy = MRI.getType(PtrReg);
2559     auto OffsetCst = MIRBuilder.buildConstant(
2560             LLT::scalar(PtrTy.getSizeInBits()), LargeSplitSize / 8);
2561     Register PtrAddReg = MRI.createGenericVirtualRegister(PtrTy);
2562     auto SmallPtr =
2563         MIRBuilder.buildPtrAdd(PtrAddReg, PtrReg, OffsetCst.getReg(0));
2564 
2565     MachineFunction &MF = MIRBuilder.getMF();
2566     MachineMemOperand *LargeMMO =
2567         MF.getMachineMemOperand(&MMO, 0, LargeSplitSize / 8);
2568     MachineMemOperand *SmallMMO =
2569         MF.getMachineMemOperand(&MMO, LargeSplitSize / 8, SmallSplitSize / 8);
2570     MIRBuilder.buildStore(ExtVal.getReg(0), PtrReg, *LargeMMO);
2571     MIRBuilder.buildStore(SmallVal.getReg(0), SmallPtr.getReg(0), *SmallMMO);
2572     MI.eraseFromParent();
2573     return Legalized;
2574   }
2575   case TargetOpcode::G_CTLZ_ZERO_UNDEF:
2576   case TargetOpcode::G_CTTZ_ZERO_UNDEF:
2577   case TargetOpcode::G_CTLZ:
2578   case TargetOpcode::G_CTTZ:
2579   case TargetOpcode::G_CTPOP:
2580     return lowerBitCount(MI, TypeIdx, Ty);
2581   case G_UADDO: {
2582     Register Res = MI.getOperand(0).getReg();
2583     Register CarryOut = MI.getOperand(1).getReg();
2584     Register LHS = MI.getOperand(2).getReg();
2585     Register RHS = MI.getOperand(3).getReg();
2586 
2587     MIRBuilder.buildAdd(Res, LHS, RHS);
2588     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, RHS);
2589 
2590     MI.eraseFromParent();
2591     return Legalized;
2592   }
2593   case G_UADDE: {
2594     Register Res = MI.getOperand(0).getReg();
2595     Register CarryOut = MI.getOperand(1).getReg();
2596     Register LHS = MI.getOperand(2).getReg();
2597     Register RHS = MI.getOperand(3).getReg();
2598     Register CarryIn = MI.getOperand(4).getReg();
2599     LLT Ty = MRI.getType(Res);
2600 
2601     auto TmpRes = MIRBuilder.buildAdd(Ty, LHS, RHS);
2602     auto ZExtCarryIn = MIRBuilder.buildZExt(Ty, CarryIn);
2603     MIRBuilder.buildAdd(Res, TmpRes, ZExtCarryIn);
2604     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, LHS);
2605 
2606     MI.eraseFromParent();
2607     return Legalized;
2608   }
2609   case G_USUBO: {
2610     Register Res = MI.getOperand(0).getReg();
2611     Register BorrowOut = MI.getOperand(1).getReg();
2612     Register LHS = MI.getOperand(2).getReg();
2613     Register RHS = MI.getOperand(3).getReg();
2614 
2615     MIRBuilder.buildSub(Res, LHS, RHS);
2616     MIRBuilder.buildICmp(CmpInst::ICMP_ULT, BorrowOut, LHS, RHS);
2617 
2618     MI.eraseFromParent();
2619     return Legalized;
2620   }
2621   case G_USUBE: {
2622     Register Res = MI.getOperand(0).getReg();
2623     Register BorrowOut = MI.getOperand(1).getReg();
2624     Register LHS = MI.getOperand(2).getReg();
2625     Register RHS = MI.getOperand(3).getReg();
2626     Register BorrowIn = MI.getOperand(4).getReg();
2627     const LLT CondTy = MRI.getType(BorrowOut);
2628     const LLT Ty = MRI.getType(Res);
2629 
2630     auto TmpRes = MIRBuilder.buildSub(Ty, LHS, RHS);
2631     auto ZExtBorrowIn = MIRBuilder.buildZExt(Ty, BorrowIn);
2632     MIRBuilder.buildSub(Res, TmpRes, ZExtBorrowIn);
2633 
2634     auto LHS_EQ_RHS = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, CondTy, LHS, RHS);
2635     auto LHS_ULT_RHS = MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CondTy, LHS, RHS);
2636     MIRBuilder.buildSelect(BorrowOut, LHS_EQ_RHS, BorrowIn, LHS_ULT_RHS);
2637 
2638     MI.eraseFromParent();
2639     return Legalized;
2640   }
2641   case G_UITOFP:
2642     return lowerUITOFP(MI, TypeIdx, Ty);
2643   case G_SITOFP:
2644     return lowerSITOFP(MI, TypeIdx, Ty);
2645   case G_FPTOUI:
2646     return lowerFPTOUI(MI, TypeIdx, Ty);
2647   case G_FPTOSI:
2648     return lowerFPTOSI(MI);
2649   case G_FPTRUNC:
2650     return lowerFPTRUNC(MI, TypeIdx, Ty);
2651   case G_SMIN:
2652   case G_SMAX:
2653   case G_UMIN:
2654   case G_UMAX:
2655     return lowerMinMax(MI, TypeIdx, Ty);
2656   case G_FCOPYSIGN:
2657     return lowerFCopySign(MI, TypeIdx, Ty);
2658   case G_FMINNUM:
2659   case G_FMAXNUM:
2660     return lowerFMinNumMaxNum(MI);
2661   case G_MERGE_VALUES:
2662     return lowerMergeValues(MI);
2663   case G_UNMERGE_VALUES:
2664     return lowerUnmergeValues(MI);
2665   case TargetOpcode::G_SEXT_INREG: {
2666     assert(MI.getOperand(2).isImm() && "Expected immediate");
2667     int64_t SizeInBits = MI.getOperand(2).getImm();
2668 
2669     Register DstReg = MI.getOperand(0).getReg();
2670     Register SrcReg = MI.getOperand(1).getReg();
2671     LLT DstTy = MRI.getType(DstReg);
2672     Register TmpRes = MRI.createGenericVirtualRegister(DstTy);
2673 
2674     auto MIBSz = MIRBuilder.buildConstant(DstTy, DstTy.getScalarSizeInBits() - SizeInBits);
2675     MIRBuilder.buildShl(TmpRes, SrcReg, MIBSz->getOperand(0));
2676     MIRBuilder.buildAShr(DstReg, TmpRes, MIBSz->getOperand(0));
2677     MI.eraseFromParent();
2678     return Legalized;
2679   }
2680   case G_SHUFFLE_VECTOR:
2681     return lowerShuffleVector(MI);
2682   case G_DYN_STACKALLOC:
2683     return lowerDynStackAlloc(MI);
2684   case G_EXTRACT:
2685     return lowerExtract(MI);
2686   case G_INSERT:
2687     return lowerInsert(MI);
2688   case G_BSWAP:
2689     return lowerBswap(MI);
2690   case G_BITREVERSE:
2691     return lowerBitreverse(MI);
2692   case G_READ_REGISTER:
2693   case G_WRITE_REGISTER:
2694     return lowerReadWriteRegister(MI);
2695   }
2696 }
2697 
2698 LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorImplicitDef(
2699     MachineInstr &MI, unsigned TypeIdx, LLT NarrowTy) {
2700   SmallVector<Register, 2> DstRegs;
2701 
2702   unsigned NarrowSize = NarrowTy.getSizeInBits();
2703   Register DstReg = MI.getOperand(0).getReg();
2704   unsigned Size = MRI.getType(DstReg).getSizeInBits();
2705   int NumParts = Size / NarrowSize;
2706   // FIXME: Don't know how to handle the situation where the small vectors
2707   // aren't all the same size yet.
2708   if (Size % NarrowSize != 0)
2709     return UnableToLegalize;
2710 
2711   for (int i = 0; i < NumParts; ++i) {
2712     Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
2713     MIRBuilder.buildUndef(TmpReg);
2714     DstRegs.push_back(TmpReg);
2715   }
2716 
2717   if (NarrowTy.isVector())
2718     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
2719   else
2720     MIRBuilder.buildBuildVector(DstReg, DstRegs);
2721 
2722   MI.eraseFromParent();
2723   return Legalized;
2724 }
2725 
2726 // Handle splitting vector operations which need to have the same number of
2727 // elements in each type index, but each type index may have a different element
2728 // type.
2729 //
2730 // e.g.  <4 x s64> = G_SHL <4 x s64>, <4 x s32> ->
2731 //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
2732 //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
2733 //
2734 // Also handles some irregular breakdown cases, e.g.
2735 // e.g.  <3 x s64> = G_SHL <3 x s64>, <3 x s32> ->
2736 //       <2 x s64> = G_SHL <2 x s64>, <2 x s32>
2737 //             s64 = G_SHL s64, s32
2738 LegalizerHelper::LegalizeResult
2739 LegalizerHelper::fewerElementsVectorMultiEltType(
2740   MachineInstr &MI, unsigned TypeIdx, LLT NarrowTyArg) {
2741   if (TypeIdx != 0)
2742     return UnableToLegalize;
2743 
2744   const LLT NarrowTy0 = NarrowTyArg;
2745   const unsigned NewNumElts =
2746       NarrowTy0.isVector() ? NarrowTy0.getNumElements() : 1;
2747 
2748   const Register DstReg = MI.getOperand(0).getReg();
2749   LLT DstTy = MRI.getType(DstReg);
2750   LLT LeftoverTy0;
2751 
2752   // All of the operands need to have the same number of elements, so if we can
2753   // determine a type breakdown for the result type, we can for all of the
2754   // source types.
2755   int NumParts = getNarrowTypeBreakDown(DstTy, NarrowTy0, LeftoverTy0).first;
2756   if (NumParts < 0)
2757     return UnableToLegalize;
2758 
2759   SmallVector<MachineInstrBuilder, 4> NewInsts;
2760 
2761   SmallVector<Register, 4> DstRegs, LeftoverDstRegs;
2762   SmallVector<Register, 4> PartRegs, LeftoverRegs;
2763 
2764   for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) {
2765     Register SrcReg = MI.getOperand(I).getReg();
2766     LLT SrcTyI = MRI.getType(SrcReg);
2767     LLT NarrowTyI = LLT::scalarOrVector(NewNumElts, SrcTyI.getScalarType());
2768     LLT LeftoverTyI;
2769 
2770     // Split this operand into the requested typed registers, and any leftover
2771     // required to reproduce the original type.
2772     if (!extractParts(SrcReg, SrcTyI, NarrowTyI, LeftoverTyI, PartRegs,
2773                       LeftoverRegs))
2774       return UnableToLegalize;
2775 
2776     if (I == 1) {
2777       // For the first operand, create an instruction for each part and setup
2778       // the result.
2779       for (Register PartReg : PartRegs) {
2780         Register PartDstReg = MRI.createGenericVirtualRegister(NarrowTy0);
2781         NewInsts.push_back(MIRBuilder.buildInstrNoInsert(MI.getOpcode())
2782                                .addDef(PartDstReg)
2783                                .addUse(PartReg));
2784         DstRegs.push_back(PartDstReg);
2785       }
2786 
2787       for (Register LeftoverReg : LeftoverRegs) {
2788         Register PartDstReg = MRI.createGenericVirtualRegister(LeftoverTy0);
2789         NewInsts.push_back(MIRBuilder.buildInstrNoInsert(MI.getOpcode())
2790                                .addDef(PartDstReg)
2791                                .addUse(LeftoverReg));
2792         LeftoverDstRegs.push_back(PartDstReg);
2793       }
2794     } else {
2795       assert(NewInsts.size() == PartRegs.size() + LeftoverRegs.size());
2796 
2797       // Add the newly created operand splits to the existing instructions. The
2798       // odd-sized pieces are ordered after the requested NarrowTyArg sized
2799       // pieces.
2800       unsigned InstCount = 0;
2801       for (unsigned J = 0, JE = PartRegs.size(); J != JE; ++J)
2802         NewInsts[InstCount++].addUse(PartRegs[J]);
2803       for (unsigned J = 0, JE = LeftoverRegs.size(); J != JE; ++J)
2804         NewInsts[InstCount++].addUse(LeftoverRegs[J]);
2805     }
2806 
2807     PartRegs.clear();
2808     LeftoverRegs.clear();
2809   }
2810 
2811   // Insert the newly built operations and rebuild the result register.
2812   for (auto &MIB : NewInsts)
2813     MIRBuilder.insertInstr(MIB);
2814 
2815   insertParts(DstReg, DstTy, NarrowTy0, DstRegs, LeftoverTy0, LeftoverDstRegs);
2816 
2817   MI.eraseFromParent();
2818   return Legalized;
2819 }
2820 
2821 LegalizerHelper::LegalizeResult
2822 LegalizerHelper::fewerElementsVectorCasts(MachineInstr &MI, unsigned TypeIdx,
2823                                           LLT NarrowTy) {
2824   if (TypeIdx != 0)
2825     return UnableToLegalize;
2826 
2827   Register DstReg = MI.getOperand(0).getReg();
2828   Register SrcReg = MI.getOperand(1).getReg();
2829   LLT DstTy = MRI.getType(DstReg);
2830   LLT SrcTy = MRI.getType(SrcReg);
2831 
2832   LLT NarrowTy0 = NarrowTy;
2833   LLT NarrowTy1;
2834   unsigned NumParts;
2835 
2836   if (NarrowTy.isVector()) {
2837     // Uneven breakdown not handled.
2838     NumParts = DstTy.getNumElements() / NarrowTy.getNumElements();
2839     if (NumParts * NarrowTy.getNumElements() != DstTy.getNumElements())
2840       return UnableToLegalize;
2841 
2842     NarrowTy1 = LLT::vector(NumParts, SrcTy.getElementType().getSizeInBits());
2843   } else {
2844     NumParts = DstTy.getNumElements();
2845     NarrowTy1 = SrcTy.getElementType();
2846   }
2847 
2848   SmallVector<Register, 4> SrcRegs, DstRegs;
2849   extractParts(SrcReg, NarrowTy1, NumParts, SrcRegs);
2850 
2851   for (unsigned I = 0; I < NumParts; ++I) {
2852     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
2853     MachineInstr *NewInst =
2854         MIRBuilder.buildInstr(MI.getOpcode(), {DstReg}, {SrcRegs[I]});
2855 
2856     NewInst->setFlags(MI.getFlags());
2857     DstRegs.push_back(DstReg);
2858   }
2859 
2860   if (NarrowTy.isVector())
2861     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
2862   else
2863     MIRBuilder.buildBuildVector(DstReg, DstRegs);
2864 
2865   MI.eraseFromParent();
2866   return Legalized;
2867 }
2868 
2869 LegalizerHelper::LegalizeResult
2870 LegalizerHelper::fewerElementsVectorCmp(MachineInstr &MI, unsigned TypeIdx,
2871                                         LLT NarrowTy) {
2872   Register DstReg = MI.getOperand(0).getReg();
2873   Register Src0Reg = MI.getOperand(2).getReg();
2874   LLT DstTy = MRI.getType(DstReg);
2875   LLT SrcTy = MRI.getType(Src0Reg);
2876 
2877   unsigned NumParts;
2878   LLT NarrowTy0, NarrowTy1;
2879 
2880   if (TypeIdx == 0) {
2881     unsigned NewElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
2882     unsigned OldElts = DstTy.getNumElements();
2883 
2884     NarrowTy0 = NarrowTy;
2885     NumParts = NarrowTy.isVector() ? (OldElts / NewElts) : DstTy.getNumElements();
2886     NarrowTy1 = NarrowTy.isVector() ?
2887       LLT::vector(NarrowTy.getNumElements(), SrcTy.getScalarSizeInBits()) :
2888       SrcTy.getElementType();
2889 
2890   } else {
2891     unsigned NewElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
2892     unsigned OldElts = SrcTy.getNumElements();
2893 
2894     NumParts = NarrowTy.isVector() ? (OldElts / NewElts) :
2895       NarrowTy.getNumElements();
2896     NarrowTy0 = LLT::vector(NarrowTy.getNumElements(),
2897                             DstTy.getScalarSizeInBits());
2898     NarrowTy1 = NarrowTy;
2899   }
2900 
2901   // FIXME: Don't know how to handle the situation where the small vectors
2902   // aren't all the same size yet.
2903   if (NarrowTy1.isVector() &&
2904       NarrowTy1.getNumElements() * NumParts != DstTy.getNumElements())
2905     return UnableToLegalize;
2906 
2907   CmpInst::Predicate Pred
2908     = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
2909 
2910   SmallVector<Register, 2> Src1Regs, Src2Regs, DstRegs;
2911   extractParts(MI.getOperand(2).getReg(), NarrowTy1, NumParts, Src1Regs);
2912   extractParts(MI.getOperand(3).getReg(), NarrowTy1, NumParts, Src2Regs);
2913 
2914   for (unsigned I = 0; I < NumParts; ++I) {
2915     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
2916     DstRegs.push_back(DstReg);
2917 
2918     if (MI.getOpcode() == TargetOpcode::G_ICMP)
2919       MIRBuilder.buildICmp(Pred, DstReg, Src1Regs[I], Src2Regs[I]);
2920     else {
2921       MachineInstr *NewCmp
2922         = MIRBuilder.buildFCmp(Pred, DstReg, Src1Regs[I], Src2Regs[I]);
2923       NewCmp->setFlags(MI.getFlags());
2924     }
2925   }
2926 
2927   if (NarrowTy1.isVector())
2928     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
2929   else
2930     MIRBuilder.buildBuildVector(DstReg, DstRegs);
2931 
2932   MI.eraseFromParent();
2933   return Legalized;
2934 }
2935 
2936 LegalizerHelper::LegalizeResult
2937 LegalizerHelper::fewerElementsVectorSelect(MachineInstr &MI, unsigned TypeIdx,
2938                                            LLT NarrowTy) {
2939   Register DstReg = MI.getOperand(0).getReg();
2940   Register CondReg = MI.getOperand(1).getReg();
2941 
2942   unsigned NumParts = 0;
2943   LLT NarrowTy0, NarrowTy1;
2944 
2945   LLT DstTy = MRI.getType(DstReg);
2946   LLT CondTy = MRI.getType(CondReg);
2947   unsigned Size = DstTy.getSizeInBits();
2948 
2949   assert(TypeIdx == 0 || CondTy.isVector());
2950 
2951   if (TypeIdx == 0) {
2952     NarrowTy0 = NarrowTy;
2953     NarrowTy1 = CondTy;
2954 
2955     unsigned NarrowSize = NarrowTy0.getSizeInBits();
2956     // FIXME: Don't know how to handle the situation where the small vectors
2957     // aren't all the same size yet.
2958     if (Size % NarrowSize != 0)
2959       return UnableToLegalize;
2960 
2961     NumParts = Size / NarrowSize;
2962 
2963     // Need to break down the condition type
2964     if (CondTy.isVector()) {
2965       if (CondTy.getNumElements() == NumParts)
2966         NarrowTy1 = CondTy.getElementType();
2967       else
2968         NarrowTy1 = LLT::vector(CondTy.getNumElements() / NumParts,
2969                                 CondTy.getScalarSizeInBits());
2970     }
2971   } else {
2972     NumParts = CondTy.getNumElements();
2973     if (NarrowTy.isVector()) {
2974       // TODO: Handle uneven breakdown.
2975       if (NumParts * NarrowTy.getNumElements() != CondTy.getNumElements())
2976         return UnableToLegalize;
2977 
2978       return UnableToLegalize;
2979     } else {
2980       NarrowTy0 = DstTy.getElementType();
2981       NarrowTy1 = NarrowTy;
2982     }
2983   }
2984 
2985   SmallVector<Register, 2> DstRegs, Src0Regs, Src1Regs, Src2Regs;
2986   if (CondTy.isVector())
2987     extractParts(MI.getOperand(1).getReg(), NarrowTy1, NumParts, Src0Regs);
2988 
2989   extractParts(MI.getOperand(2).getReg(), NarrowTy0, NumParts, Src1Regs);
2990   extractParts(MI.getOperand(3).getReg(), NarrowTy0, NumParts, Src2Regs);
2991 
2992   for (unsigned i = 0; i < NumParts; ++i) {
2993     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
2994     MIRBuilder.buildSelect(DstReg, CondTy.isVector() ? Src0Regs[i] : CondReg,
2995                            Src1Regs[i], Src2Regs[i]);
2996     DstRegs.push_back(DstReg);
2997   }
2998 
2999   if (NarrowTy0.isVector())
3000     MIRBuilder.buildConcatVectors(DstReg, DstRegs);
3001   else
3002     MIRBuilder.buildBuildVector(DstReg, DstRegs);
3003 
3004   MI.eraseFromParent();
3005   return Legalized;
3006 }
3007 
3008 LegalizerHelper::LegalizeResult
3009 LegalizerHelper::fewerElementsVectorPhi(MachineInstr &MI, unsigned TypeIdx,
3010                                         LLT NarrowTy) {
3011   const Register DstReg = MI.getOperand(0).getReg();
3012   LLT PhiTy = MRI.getType(DstReg);
3013   LLT LeftoverTy;
3014 
3015   // All of the operands need to have the same number of elements, so if we can
3016   // determine a type breakdown for the result type, we can for all of the
3017   // source types.
3018   int NumParts, NumLeftover;
3019   std::tie(NumParts, NumLeftover)
3020     = getNarrowTypeBreakDown(PhiTy, NarrowTy, LeftoverTy);
3021   if (NumParts < 0)
3022     return UnableToLegalize;
3023 
3024   SmallVector<Register, 4> DstRegs, LeftoverDstRegs;
3025   SmallVector<MachineInstrBuilder, 4> NewInsts;
3026 
3027   const int TotalNumParts = NumParts + NumLeftover;
3028 
3029   // Insert the new phis in the result block first.
3030   for (int I = 0; I != TotalNumParts; ++I) {
3031     LLT Ty = I < NumParts ? NarrowTy : LeftoverTy;
3032     Register PartDstReg = MRI.createGenericVirtualRegister(Ty);
3033     NewInsts.push_back(MIRBuilder.buildInstr(TargetOpcode::G_PHI)
3034                        .addDef(PartDstReg));
3035     if (I < NumParts)
3036       DstRegs.push_back(PartDstReg);
3037     else
3038       LeftoverDstRegs.push_back(PartDstReg);
3039   }
3040 
3041   MachineBasicBlock *MBB = MI.getParent();
3042   MIRBuilder.setInsertPt(*MBB, MBB->getFirstNonPHI());
3043   insertParts(DstReg, PhiTy, NarrowTy, DstRegs, LeftoverTy, LeftoverDstRegs);
3044 
3045   SmallVector<Register, 4> PartRegs, LeftoverRegs;
3046 
3047   // Insert code to extract the incoming values in each predecessor block.
3048   for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
3049     PartRegs.clear();
3050     LeftoverRegs.clear();
3051 
3052     Register SrcReg = MI.getOperand(I).getReg();
3053     MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
3054     MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
3055 
3056     LLT Unused;
3057     if (!extractParts(SrcReg, PhiTy, NarrowTy, Unused, PartRegs,
3058                       LeftoverRegs))
3059       return UnableToLegalize;
3060 
3061     // Add the newly created operand splits to the existing instructions. The
3062     // odd-sized pieces are ordered after the requested NarrowTyArg sized
3063     // pieces.
3064     for (int J = 0; J != TotalNumParts; ++J) {
3065       MachineInstrBuilder MIB = NewInsts[J];
3066       MIB.addUse(J < NumParts ? PartRegs[J] : LeftoverRegs[J - NumParts]);
3067       MIB.addMBB(&OpMBB);
3068     }
3069   }
3070 
3071   MI.eraseFromParent();
3072   return Legalized;
3073 }
3074 
3075 LegalizerHelper::LegalizeResult
3076 LegalizerHelper::fewerElementsVectorUnmergeValues(MachineInstr &MI,
3077                                                   unsigned TypeIdx,
3078                                                   LLT NarrowTy) {
3079   if (TypeIdx != 1)
3080     return UnableToLegalize;
3081 
3082   const int NumDst = MI.getNumOperands() - 1;
3083   const Register SrcReg = MI.getOperand(NumDst).getReg();
3084   LLT SrcTy = MRI.getType(SrcReg);
3085 
3086   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
3087 
3088   // TODO: Create sequence of extracts.
3089   if (DstTy == NarrowTy)
3090     return UnableToLegalize;
3091 
3092   LLT GCDTy = getGCDType(SrcTy, NarrowTy);
3093   if (DstTy == GCDTy) {
3094     // This would just be a copy of the same unmerge.
3095     // TODO: Create extracts, pad with undef and create intermediate merges.
3096     return UnableToLegalize;
3097   }
3098 
3099   auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
3100   const int NumUnmerge = Unmerge->getNumOperands() - 1;
3101   const int PartsPerUnmerge = NumDst / NumUnmerge;
3102 
3103   for (int I = 0; I != NumUnmerge; ++I) {
3104     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
3105 
3106     for (int J = 0; J != PartsPerUnmerge; ++J)
3107       MIB.addDef(MI.getOperand(I * PartsPerUnmerge + J).getReg());
3108     MIB.addUse(Unmerge.getReg(I));
3109   }
3110 
3111   MI.eraseFromParent();
3112   return Legalized;
3113 }
3114 
3115 LegalizerHelper::LegalizeResult
3116 LegalizerHelper::fewerElementsVectorBuildVector(MachineInstr &MI,
3117                                                 unsigned TypeIdx,
3118                                                 LLT NarrowTy) {
3119   assert(TypeIdx == 0 && "not a vector type index");
3120   Register DstReg = MI.getOperand(0).getReg();
3121   LLT DstTy = MRI.getType(DstReg);
3122   LLT SrcTy = DstTy.getElementType();
3123 
3124   int DstNumElts = DstTy.getNumElements();
3125   int NarrowNumElts = NarrowTy.getNumElements();
3126   int NumConcat = (DstNumElts + NarrowNumElts - 1) / NarrowNumElts;
3127   LLT WidenedDstTy = LLT::vector(NarrowNumElts * NumConcat, SrcTy);
3128 
3129   SmallVector<Register, 8> ConcatOps;
3130   SmallVector<Register, 8> SubBuildVector;
3131 
3132   Register UndefReg;
3133   if (WidenedDstTy != DstTy)
3134     UndefReg = MIRBuilder.buildUndef(SrcTy).getReg(0);
3135 
3136   // Create a G_CONCAT_VECTORS of NarrowTy pieces, padding with undef as
3137   // necessary.
3138   //
3139   // %3:_(<3 x s16>) = G_BUILD_VECTOR %0, %1, %2
3140   //   -> <2 x s16>
3141   //
3142   // %4:_(s16) = G_IMPLICIT_DEF
3143   // %5:_(<2 x s16>) = G_BUILD_VECTOR %0, %1
3144   // %6:_(<2 x s16>) = G_BUILD_VECTOR %2, %4
3145   // %7:_(<4 x s16>) = G_CONCAT_VECTORS %5, %6
3146   // %3:_(<3 x s16>) = G_EXTRACT %7, 0
3147   for (int I = 0; I != NumConcat; ++I) {
3148     for (int J = 0; J != NarrowNumElts; ++J) {
3149       int SrcIdx = NarrowNumElts * I + J;
3150 
3151       if (SrcIdx < DstNumElts) {
3152         Register SrcReg = MI.getOperand(SrcIdx + 1).getReg();
3153         SubBuildVector.push_back(SrcReg);
3154       } else
3155         SubBuildVector.push_back(UndefReg);
3156     }
3157 
3158     auto BuildVec = MIRBuilder.buildBuildVector(NarrowTy, SubBuildVector);
3159     ConcatOps.push_back(BuildVec.getReg(0));
3160     SubBuildVector.clear();
3161   }
3162 
3163   if (DstTy == WidenedDstTy)
3164     MIRBuilder.buildConcatVectors(DstReg, ConcatOps);
3165   else {
3166     auto Concat = MIRBuilder.buildConcatVectors(WidenedDstTy, ConcatOps);
3167     MIRBuilder.buildExtract(DstReg, Concat, 0);
3168   }
3169 
3170   MI.eraseFromParent();
3171   return Legalized;
3172 }
3173 
3174 LegalizerHelper::LegalizeResult
3175 LegalizerHelper::reduceLoadStoreWidth(MachineInstr &MI, unsigned TypeIdx,
3176                                       LLT NarrowTy) {
3177   // FIXME: Don't know how to handle secondary types yet.
3178   if (TypeIdx != 0)
3179     return UnableToLegalize;
3180 
3181   MachineMemOperand *MMO = *MI.memoperands_begin();
3182 
3183   // This implementation doesn't work for atomics. Give up instead of doing
3184   // something invalid.
3185   if (MMO->getOrdering() != AtomicOrdering::NotAtomic ||
3186       MMO->getFailureOrdering() != AtomicOrdering::NotAtomic)
3187     return UnableToLegalize;
3188 
3189   bool IsLoad = MI.getOpcode() == TargetOpcode::G_LOAD;
3190   Register ValReg = MI.getOperand(0).getReg();
3191   Register AddrReg = MI.getOperand(1).getReg();
3192   LLT ValTy = MRI.getType(ValReg);
3193 
3194   // FIXME: Do we need a distinct NarrowMemory legalize action?
3195   if (ValTy.getSizeInBits() != 8 * MMO->getSize()) {
3196     LLVM_DEBUG(dbgs() << "Can't narrow extload/truncstore\n");
3197     return UnableToLegalize;
3198   }
3199 
3200   int NumParts = -1;
3201   int NumLeftover = -1;
3202   LLT LeftoverTy;
3203   SmallVector<Register, 8> NarrowRegs, NarrowLeftoverRegs;
3204   if (IsLoad) {
3205     std::tie(NumParts, NumLeftover) = getNarrowTypeBreakDown(ValTy, NarrowTy, LeftoverTy);
3206   } else {
3207     if (extractParts(ValReg, ValTy, NarrowTy, LeftoverTy, NarrowRegs,
3208                      NarrowLeftoverRegs)) {
3209       NumParts = NarrowRegs.size();
3210       NumLeftover = NarrowLeftoverRegs.size();
3211     }
3212   }
3213 
3214   if (NumParts == -1)
3215     return UnableToLegalize;
3216 
3217   const LLT OffsetTy = LLT::scalar(MRI.getType(AddrReg).getScalarSizeInBits());
3218 
3219   unsigned TotalSize = ValTy.getSizeInBits();
3220 
3221   // Split the load/store into PartTy sized pieces starting at Offset. If this
3222   // is a load, return the new registers in ValRegs. For a store, each elements
3223   // of ValRegs should be PartTy. Returns the next offset that needs to be
3224   // handled.
3225   auto splitTypePieces = [=](LLT PartTy, SmallVectorImpl<Register> &ValRegs,
3226                              unsigned Offset) -> unsigned {
3227     MachineFunction &MF = MIRBuilder.getMF();
3228     unsigned PartSize = PartTy.getSizeInBits();
3229     for (unsigned Idx = 0, E = NumParts; Idx != E && Offset < TotalSize;
3230          Offset += PartSize, ++Idx) {
3231       unsigned ByteSize = PartSize / 8;
3232       unsigned ByteOffset = Offset / 8;
3233       Register NewAddrReg;
3234 
3235       MIRBuilder.materializePtrAdd(NewAddrReg, AddrReg, OffsetTy, ByteOffset);
3236 
3237       MachineMemOperand *NewMMO =
3238         MF.getMachineMemOperand(MMO, ByteOffset, ByteSize);
3239 
3240       if (IsLoad) {
3241         Register Dst = MRI.createGenericVirtualRegister(PartTy);
3242         ValRegs.push_back(Dst);
3243         MIRBuilder.buildLoad(Dst, NewAddrReg, *NewMMO);
3244       } else {
3245         MIRBuilder.buildStore(ValRegs[Idx], NewAddrReg, *NewMMO);
3246       }
3247     }
3248 
3249     return Offset;
3250   };
3251 
3252   unsigned HandledOffset = splitTypePieces(NarrowTy, NarrowRegs, 0);
3253 
3254   // Handle the rest of the register if this isn't an even type breakdown.
3255   if (LeftoverTy.isValid())
3256     splitTypePieces(LeftoverTy, NarrowLeftoverRegs, HandledOffset);
3257 
3258   if (IsLoad) {
3259     insertParts(ValReg, ValTy, NarrowTy, NarrowRegs,
3260                 LeftoverTy, NarrowLeftoverRegs);
3261   }
3262 
3263   MI.eraseFromParent();
3264   return Legalized;
3265 }
3266 
3267 LegalizerHelper::LegalizeResult
3268 LegalizerHelper::reduceOperationWidth(MachineInstr &MI, unsigned int TypeIdx,
3269                                       LLT NarrowTy) {
3270   assert(TypeIdx == 0 && "only one type index expected");
3271 
3272   const unsigned Opc = MI.getOpcode();
3273   const int NumOps = MI.getNumOperands() - 1;
3274   const Register DstReg = MI.getOperand(0).getReg();
3275   const unsigned Flags = MI.getFlags();
3276   const unsigned NarrowSize = NarrowTy.getSizeInBits();
3277   const LLT NarrowScalarTy = LLT::scalar(NarrowSize);
3278 
3279   assert(NumOps <= 3 && "expected instruction with 1 result and 1-3 sources");
3280 
3281   // First of all check whether we are narrowing (changing the element type)
3282   // or reducing the vector elements
3283   const LLT DstTy = MRI.getType(DstReg);
3284   const bool IsNarrow = NarrowTy.getScalarType() != DstTy.getScalarType();
3285 
3286   SmallVector<Register, 8> ExtractedRegs[3];
3287   SmallVector<Register, 8> Parts;
3288 
3289   unsigned NarrowElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
3290 
3291   // Break down all the sources into NarrowTy pieces we can operate on. This may
3292   // involve creating merges to a wider type, padded with undef.
3293   for (int I = 0; I != NumOps; ++I) {
3294     Register SrcReg = MI.getOperand(I + 1).getReg();
3295     LLT SrcTy = MRI.getType(SrcReg);
3296 
3297     // The type to narrow SrcReg to. For narrowing, this is a smaller scalar.
3298     // For fewerElements, this is a smaller vector with the same element type.
3299     LLT OpNarrowTy;
3300     if (IsNarrow) {
3301       OpNarrowTy = NarrowScalarTy;
3302 
3303       // In case of narrowing, we need to cast vectors to scalars for this to
3304       // work properly
3305       // FIXME: Can we do without the bitcast here if we're narrowing?
3306       if (SrcTy.isVector()) {
3307         SrcTy = LLT::scalar(SrcTy.getSizeInBits());
3308         SrcReg = MIRBuilder.buildBitcast(SrcTy, SrcReg).getReg(0);
3309       }
3310     } else {
3311       OpNarrowTy = LLT::scalarOrVector(NarrowElts, SrcTy.getScalarType());
3312     }
3313 
3314     LLT GCDTy = extractGCDType(ExtractedRegs[I], SrcTy, OpNarrowTy, SrcReg);
3315 
3316     // Build a sequence of NarrowTy pieces in ExtractedRegs for this operand.
3317     buildLCMMergePieces(SrcTy, OpNarrowTy, GCDTy, ExtractedRegs[I],
3318                         TargetOpcode::G_ANYEXT);
3319   }
3320 
3321   SmallVector<Register, 8> ResultRegs;
3322 
3323   // Input operands for each sub-instruction.
3324   SmallVector<SrcOp, 4> InputRegs(NumOps, Register());
3325 
3326   int NumParts = ExtractedRegs[0].size();
3327   const unsigned DstSize = DstTy.getSizeInBits();
3328   const LLT DstScalarTy = LLT::scalar(DstSize);
3329 
3330   // Narrowing needs to use scalar types
3331   LLT DstLCMTy, NarrowDstTy;
3332   if (IsNarrow) {
3333     DstLCMTy = getLCMType(DstScalarTy, NarrowScalarTy);
3334     NarrowDstTy = NarrowScalarTy;
3335   } else {
3336     DstLCMTy = getLCMType(DstTy, NarrowTy);
3337     NarrowDstTy = NarrowTy;
3338   }
3339 
3340   // We widened the source registers to satisfy merge/unmerge size
3341   // constraints. We'll have some extra fully undef parts.
3342   const int NumRealParts = (DstSize + NarrowSize - 1) / NarrowSize;
3343 
3344   for (int I = 0; I != NumRealParts; ++I) {
3345     // Emit this instruction on each of the split pieces.
3346     for (int J = 0; J != NumOps; ++J)
3347       InputRegs[J] = ExtractedRegs[J][I];
3348 
3349     auto Inst = MIRBuilder.buildInstr(Opc, {NarrowDstTy}, InputRegs, Flags);
3350     ResultRegs.push_back(Inst.getReg(0));
3351   }
3352 
3353   // Fill out the widened result with undef instead of creating instructions
3354   // with undef inputs.
3355   int NumUndefParts = NumParts - NumRealParts;
3356   if (NumUndefParts != 0)
3357     ResultRegs.append(NumUndefParts,
3358                       MIRBuilder.buildUndef(NarrowDstTy).getReg(0));
3359 
3360   // Extract the possibly padded result. Use a scratch register if we need to do
3361   // a final bitcast, otherwise use the original result register.
3362   Register MergeDstReg;
3363   if (IsNarrow && DstTy.isVector())
3364     MergeDstReg = MRI.createGenericVirtualRegister(DstScalarTy);
3365   else
3366     MergeDstReg = DstReg;
3367 
3368   buildWidenedRemergeToDst(MergeDstReg, DstLCMTy, ResultRegs);
3369 
3370   // Recast to vector if we narrowed a vector
3371   if (IsNarrow && DstTy.isVector())
3372     MIRBuilder.buildBitcast(DstReg, MergeDstReg);
3373 
3374   MI.eraseFromParent();
3375   return Legalized;
3376 }
3377 
3378 LegalizerHelper::LegalizeResult
3379 LegalizerHelper::fewerElementsVectorSextInReg(MachineInstr &MI, unsigned TypeIdx,
3380                                               LLT NarrowTy) {
3381   Register DstReg = MI.getOperand(0).getReg();
3382   Register SrcReg = MI.getOperand(1).getReg();
3383   int64_t Imm = MI.getOperand(2).getImm();
3384 
3385   LLT DstTy = MRI.getType(DstReg);
3386 
3387   SmallVector<Register, 8> Parts;
3388   LLT GCDTy = extractGCDType(Parts, DstTy, NarrowTy, SrcReg);
3389   LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts);
3390 
3391   for (Register &R : Parts)
3392     R = MIRBuilder.buildSExtInReg(NarrowTy, R, Imm).getReg(0);
3393 
3394   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
3395 
3396   MI.eraseFromParent();
3397   return Legalized;
3398 }
3399 
3400 LegalizerHelper::LegalizeResult
3401 LegalizerHelper::fewerElementsVector(MachineInstr &MI, unsigned TypeIdx,
3402                                      LLT NarrowTy) {
3403   using namespace TargetOpcode;
3404 
3405   switch (MI.getOpcode()) {
3406   case G_IMPLICIT_DEF:
3407     return fewerElementsVectorImplicitDef(MI, TypeIdx, NarrowTy);
3408   case G_TRUNC:
3409   case G_AND:
3410   case G_OR:
3411   case G_XOR:
3412   case G_ADD:
3413   case G_SUB:
3414   case G_MUL:
3415   case G_SMULH:
3416   case G_UMULH:
3417   case G_FADD:
3418   case G_FMUL:
3419   case G_FSUB:
3420   case G_FNEG:
3421   case G_FABS:
3422   case G_FCANONICALIZE:
3423   case G_FDIV:
3424   case G_FREM:
3425   case G_FMA:
3426   case G_FMAD:
3427   case G_FPOW:
3428   case G_FEXP:
3429   case G_FEXP2:
3430   case G_FLOG:
3431   case G_FLOG2:
3432   case G_FLOG10:
3433   case G_FNEARBYINT:
3434   case G_FCEIL:
3435   case G_FFLOOR:
3436   case G_FRINT:
3437   case G_INTRINSIC_ROUND:
3438   case G_INTRINSIC_TRUNC:
3439   case G_FCOS:
3440   case G_FSIN:
3441   case G_FSQRT:
3442   case G_BSWAP:
3443   case G_BITREVERSE:
3444   case G_SDIV:
3445   case G_UDIV:
3446   case G_SREM:
3447   case G_UREM:
3448   case G_SMIN:
3449   case G_SMAX:
3450   case G_UMIN:
3451   case G_UMAX:
3452   case G_FMINNUM:
3453   case G_FMAXNUM:
3454   case G_FMINNUM_IEEE:
3455   case G_FMAXNUM_IEEE:
3456   case G_FMINIMUM:
3457   case G_FMAXIMUM:
3458   case G_FSHL:
3459   case G_FSHR:
3460   case G_FREEZE:
3461   case G_SADDSAT:
3462   case G_SSUBSAT:
3463   case G_UADDSAT:
3464   case G_USUBSAT:
3465     return reduceOperationWidth(MI, TypeIdx, NarrowTy);
3466   case G_SHL:
3467   case G_LSHR:
3468   case G_ASHR:
3469   case G_CTLZ:
3470   case G_CTLZ_ZERO_UNDEF:
3471   case G_CTTZ:
3472   case G_CTTZ_ZERO_UNDEF:
3473   case G_CTPOP:
3474   case G_FCOPYSIGN:
3475     return fewerElementsVectorMultiEltType(MI, TypeIdx, NarrowTy);
3476   case G_ZEXT:
3477   case G_SEXT:
3478   case G_ANYEXT:
3479   case G_FPEXT:
3480   case G_FPTRUNC:
3481   case G_SITOFP:
3482   case G_UITOFP:
3483   case G_FPTOSI:
3484   case G_FPTOUI:
3485   case G_INTTOPTR:
3486   case G_PTRTOINT:
3487   case G_ADDRSPACE_CAST:
3488     return fewerElementsVectorCasts(MI, TypeIdx, NarrowTy);
3489   case G_ICMP:
3490   case G_FCMP:
3491     return fewerElementsVectorCmp(MI, TypeIdx, NarrowTy);
3492   case G_SELECT:
3493     return fewerElementsVectorSelect(MI, TypeIdx, NarrowTy);
3494   case G_PHI:
3495     return fewerElementsVectorPhi(MI, TypeIdx, NarrowTy);
3496   case G_UNMERGE_VALUES:
3497     return fewerElementsVectorUnmergeValues(MI, TypeIdx, NarrowTy);
3498   case G_BUILD_VECTOR:
3499     return fewerElementsVectorBuildVector(MI, TypeIdx, NarrowTy);
3500   case G_LOAD:
3501   case G_STORE:
3502     return reduceLoadStoreWidth(MI, TypeIdx, NarrowTy);
3503   case G_SEXT_INREG:
3504     return fewerElementsVectorSextInReg(MI, TypeIdx, NarrowTy);
3505   default:
3506     return UnableToLegalize;
3507   }
3508 }
3509 
3510 LegalizerHelper::LegalizeResult
3511 LegalizerHelper::narrowScalarShiftByConstant(MachineInstr &MI, const APInt &Amt,
3512                                              const LLT HalfTy, const LLT AmtTy) {
3513 
3514   Register InL = MRI.createGenericVirtualRegister(HalfTy);
3515   Register InH = MRI.createGenericVirtualRegister(HalfTy);
3516   MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1));
3517 
3518   if (Amt.isNullValue()) {
3519     MIRBuilder.buildMerge(MI.getOperand(0), {InL, InH});
3520     MI.eraseFromParent();
3521     return Legalized;
3522   }
3523 
3524   LLT NVT = HalfTy;
3525   unsigned NVTBits = HalfTy.getSizeInBits();
3526   unsigned VTBits = 2 * NVTBits;
3527 
3528   SrcOp Lo(Register(0)), Hi(Register(0));
3529   if (MI.getOpcode() == TargetOpcode::G_SHL) {
3530     if (Amt.ugt(VTBits)) {
3531       Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
3532     } else if (Amt.ugt(NVTBits)) {
3533       Lo = MIRBuilder.buildConstant(NVT, 0);
3534       Hi = MIRBuilder.buildShl(NVT, InL,
3535                                MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
3536     } else if (Amt == NVTBits) {
3537       Lo = MIRBuilder.buildConstant(NVT, 0);
3538       Hi = InL;
3539     } else {
3540       Lo = MIRBuilder.buildShl(NVT, InL, MIRBuilder.buildConstant(AmtTy, Amt));
3541       auto OrLHS =
3542           MIRBuilder.buildShl(NVT, InH, MIRBuilder.buildConstant(AmtTy, Amt));
3543       auto OrRHS = MIRBuilder.buildLShr(
3544           NVT, InL, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
3545       Hi = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
3546     }
3547   } else if (MI.getOpcode() == TargetOpcode::G_LSHR) {
3548     if (Amt.ugt(VTBits)) {
3549       Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
3550     } else if (Amt.ugt(NVTBits)) {
3551       Lo = MIRBuilder.buildLShr(NVT, InH,
3552                                 MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
3553       Hi = MIRBuilder.buildConstant(NVT, 0);
3554     } else if (Amt == NVTBits) {
3555       Lo = InH;
3556       Hi = MIRBuilder.buildConstant(NVT, 0);
3557     } else {
3558       auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
3559 
3560       auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
3561       auto OrRHS = MIRBuilder.buildShl(
3562           NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
3563 
3564       Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
3565       Hi = MIRBuilder.buildLShr(NVT, InH, ShiftAmtConst);
3566     }
3567   } else {
3568     if (Amt.ugt(VTBits)) {
3569       Hi = Lo = MIRBuilder.buildAShr(
3570           NVT, InH, MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
3571     } else if (Amt.ugt(NVTBits)) {
3572       Lo = MIRBuilder.buildAShr(NVT, InH,
3573                                 MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
3574       Hi = MIRBuilder.buildAShr(NVT, InH,
3575                                 MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
3576     } else if (Amt == NVTBits) {
3577       Lo = InH;
3578       Hi = MIRBuilder.buildAShr(NVT, InH,
3579                                 MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
3580     } else {
3581       auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
3582 
3583       auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
3584       auto OrRHS = MIRBuilder.buildShl(
3585           NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
3586 
3587       Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
3588       Hi = MIRBuilder.buildAShr(NVT, InH, ShiftAmtConst);
3589     }
3590   }
3591 
3592   MIRBuilder.buildMerge(MI.getOperand(0), {Lo, Hi});
3593   MI.eraseFromParent();
3594 
3595   return Legalized;
3596 }
3597 
3598 // TODO: Optimize if constant shift amount.
3599 LegalizerHelper::LegalizeResult
3600 LegalizerHelper::narrowScalarShift(MachineInstr &MI, unsigned TypeIdx,
3601                                    LLT RequestedTy) {
3602   if (TypeIdx == 1) {
3603     Observer.changingInstr(MI);
3604     narrowScalarSrc(MI, RequestedTy, 2);
3605     Observer.changedInstr(MI);
3606     return Legalized;
3607   }
3608 
3609   Register DstReg = MI.getOperand(0).getReg();
3610   LLT DstTy = MRI.getType(DstReg);
3611   if (DstTy.isVector())
3612     return UnableToLegalize;
3613 
3614   Register Amt = MI.getOperand(2).getReg();
3615   LLT ShiftAmtTy = MRI.getType(Amt);
3616   const unsigned DstEltSize = DstTy.getScalarSizeInBits();
3617   if (DstEltSize % 2 != 0)
3618     return UnableToLegalize;
3619 
3620   // Ignore the input type. We can only go to exactly half the size of the
3621   // input. If that isn't small enough, the resulting pieces will be further
3622   // legalized.
3623   const unsigned NewBitSize = DstEltSize / 2;
3624   const LLT HalfTy = LLT::scalar(NewBitSize);
3625   const LLT CondTy = LLT::scalar(1);
3626 
3627   if (const MachineInstr *KShiftAmt =
3628           getOpcodeDef(TargetOpcode::G_CONSTANT, Amt, MRI)) {
3629     return narrowScalarShiftByConstant(
3630         MI, KShiftAmt->getOperand(1).getCImm()->getValue(), HalfTy, ShiftAmtTy);
3631   }
3632 
3633   // TODO: Expand with known bits.
3634 
3635   // Handle the fully general expansion by an unknown amount.
3636   auto NewBits = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize);
3637 
3638   Register InL = MRI.createGenericVirtualRegister(HalfTy);
3639   Register InH = MRI.createGenericVirtualRegister(HalfTy);
3640   MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1));
3641 
3642   auto AmtExcess = MIRBuilder.buildSub(ShiftAmtTy, Amt, NewBits);
3643   auto AmtLack = MIRBuilder.buildSub(ShiftAmtTy, NewBits, Amt);
3644 
3645   auto Zero = MIRBuilder.buildConstant(ShiftAmtTy, 0);
3646   auto IsShort = MIRBuilder.buildICmp(ICmpInst::ICMP_ULT, CondTy, Amt, NewBits);
3647   auto IsZero = MIRBuilder.buildICmp(ICmpInst::ICMP_EQ, CondTy, Amt, Zero);
3648 
3649   Register ResultRegs[2];
3650   switch (MI.getOpcode()) {
3651   case TargetOpcode::G_SHL: {
3652     // Short: ShAmt < NewBitSize
3653     auto LoS = MIRBuilder.buildShl(HalfTy, InL, Amt);
3654 
3655     auto LoOr = MIRBuilder.buildLShr(HalfTy, InL, AmtLack);
3656     auto HiOr = MIRBuilder.buildShl(HalfTy, InH, Amt);
3657     auto HiS = MIRBuilder.buildOr(HalfTy, LoOr, HiOr);
3658 
3659     // Long: ShAmt >= NewBitSize
3660     auto LoL = MIRBuilder.buildConstant(HalfTy, 0);         // Lo part is zero.
3661     auto HiL = MIRBuilder.buildShl(HalfTy, InL, AmtExcess); // Hi from Lo part.
3662 
3663     auto Lo = MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL);
3664     auto Hi = MIRBuilder.buildSelect(
3665         HalfTy, IsZero, InH, MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL));
3666 
3667     ResultRegs[0] = Lo.getReg(0);
3668     ResultRegs[1] = Hi.getReg(0);
3669     break;
3670   }
3671   case TargetOpcode::G_LSHR:
3672   case TargetOpcode::G_ASHR: {
3673     // Short: ShAmt < NewBitSize
3674     auto HiS = MIRBuilder.buildInstr(MI.getOpcode(), {HalfTy}, {InH, Amt});
3675 
3676     auto LoOr = MIRBuilder.buildLShr(HalfTy, InL, Amt);
3677     auto HiOr = MIRBuilder.buildShl(HalfTy, InH, AmtLack);
3678     auto LoS = MIRBuilder.buildOr(HalfTy, LoOr, HiOr);
3679 
3680     // Long: ShAmt >= NewBitSize
3681     MachineInstrBuilder HiL;
3682     if (MI.getOpcode() == TargetOpcode::G_LSHR) {
3683       HiL = MIRBuilder.buildConstant(HalfTy, 0);            // Hi part is zero.
3684     } else {
3685       auto ShiftAmt = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize - 1);
3686       HiL = MIRBuilder.buildAShr(HalfTy, InH, ShiftAmt);    // Sign of Hi part.
3687     }
3688     auto LoL = MIRBuilder.buildInstr(MI.getOpcode(), {HalfTy},
3689                                      {InH, AmtExcess});     // Lo from Hi part.
3690 
3691     auto Lo = MIRBuilder.buildSelect(
3692         HalfTy, IsZero, InL, MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL));
3693 
3694     auto Hi = MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL);
3695 
3696     ResultRegs[0] = Lo.getReg(0);
3697     ResultRegs[1] = Hi.getReg(0);
3698     break;
3699   }
3700   default:
3701     llvm_unreachable("not a shift");
3702   }
3703 
3704   MIRBuilder.buildMerge(DstReg, ResultRegs);
3705   MI.eraseFromParent();
3706   return Legalized;
3707 }
3708 
3709 LegalizerHelper::LegalizeResult
3710 LegalizerHelper::moreElementsVectorPhi(MachineInstr &MI, unsigned TypeIdx,
3711                                        LLT MoreTy) {
3712   assert(TypeIdx == 0 && "Expecting only Idx 0");
3713 
3714   Observer.changingInstr(MI);
3715   for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
3716     MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
3717     MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
3718     moreElementsVectorSrc(MI, MoreTy, I);
3719   }
3720 
3721   MachineBasicBlock &MBB = *MI.getParent();
3722   MIRBuilder.setInsertPt(MBB, --MBB.getFirstNonPHI());
3723   moreElementsVectorDst(MI, MoreTy, 0);
3724   Observer.changedInstr(MI);
3725   return Legalized;
3726 }
3727 
3728 LegalizerHelper::LegalizeResult
3729 LegalizerHelper::moreElementsVector(MachineInstr &MI, unsigned TypeIdx,
3730                                     LLT MoreTy) {
3731   unsigned Opc = MI.getOpcode();
3732   switch (Opc) {
3733   case TargetOpcode::G_IMPLICIT_DEF:
3734   case TargetOpcode::G_LOAD: {
3735     if (TypeIdx != 0)
3736       return UnableToLegalize;
3737     Observer.changingInstr(MI);
3738     moreElementsVectorDst(MI, MoreTy, 0);
3739     Observer.changedInstr(MI);
3740     return Legalized;
3741   }
3742   case TargetOpcode::G_STORE:
3743     if (TypeIdx != 0)
3744       return UnableToLegalize;
3745     Observer.changingInstr(MI);
3746     moreElementsVectorSrc(MI, MoreTy, 0);
3747     Observer.changedInstr(MI);
3748     return Legalized;
3749   case TargetOpcode::G_AND:
3750   case TargetOpcode::G_OR:
3751   case TargetOpcode::G_XOR:
3752   case TargetOpcode::G_SMIN:
3753   case TargetOpcode::G_SMAX:
3754   case TargetOpcode::G_UMIN:
3755   case TargetOpcode::G_UMAX:
3756   case TargetOpcode::G_FMINNUM:
3757   case TargetOpcode::G_FMAXNUM:
3758   case TargetOpcode::G_FMINNUM_IEEE:
3759   case TargetOpcode::G_FMAXNUM_IEEE:
3760   case TargetOpcode::G_FMINIMUM:
3761   case TargetOpcode::G_FMAXIMUM: {
3762     Observer.changingInstr(MI);
3763     moreElementsVectorSrc(MI, MoreTy, 1);
3764     moreElementsVectorSrc(MI, MoreTy, 2);
3765     moreElementsVectorDst(MI, MoreTy, 0);
3766     Observer.changedInstr(MI);
3767     return Legalized;
3768   }
3769   case TargetOpcode::G_EXTRACT:
3770     if (TypeIdx != 1)
3771       return UnableToLegalize;
3772     Observer.changingInstr(MI);
3773     moreElementsVectorSrc(MI, MoreTy, 1);
3774     Observer.changedInstr(MI);
3775     return Legalized;
3776   case TargetOpcode::G_INSERT:
3777   case TargetOpcode::G_FREEZE:
3778     if (TypeIdx != 0)
3779       return UnableToLegalize;
3780     Observer.changingInstr(MI);
3781     moreElementsVectorSrc(MI, MoreTy, 1);
3782     moreElementsVectorDst(MI, MoreTy, 0);
3783     Observer.changedInstr(MI);
3784     return Legalized;
3785   case TargetOpcode::G_SELECT:
3786     if (TypeIdx != 0)
3787       return UnableToLegalize;
3788     if (MRI.getType(MI.getOperand(1).getReg()).isVector())
3789       return UnableToLegalize;
3790 
3791     Observer.changingInstr(MI);
3792     moreElementsVectorSrc(MI, MoreTy, 2);
3793     moreElementsVectorSrc(MI, MoreTy, 3);
3794     moreElementsVectorDst(MI, MoreTy, 0);
3795     Observer.changedInstr(MI);
3796     return Legalized;
3797   case TargetOpcode::G_UNMERGE_VALUES: {
3798     if (TypeIdx != 1)
3799       return UnableToLegalize;
3800 
3801     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
3802     int NumDst = MI.getNumOperands() - 1;
3803     moreElementsVectorSrc(MI, MoreTy, NumDst);
3804 
3805     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
3806     for (int I = 0; I != NumDst; ++I)
3807       MIB.addDef(MI.getOperand(I).getReg());
3808 
3809     int NewNumDst = MoreTy.getSizeInBits() / DstTy.getSizeInBits();
3810     for (int I = NumDst; I != NewNumDst; ++I)
3811       MIB.addDef(MRI.createGenericVirtualRegister(DstTy));
3812 
3813     MIB.addUse(MI.getOperand(NumDst).getReg());
3814     MI.eraseFromParent();
3815     return Legalized;
3816   }
3817   case TargetOpcode::G_PHI:
3818     return moreElementsVectorPhi(MI, TypeIdx, MoreTy);
3819   default:
3820     return UnableToLegalize;
3821   }
3822 }
3823 
3824 void LegalizerHelper::multiplyRegisters(SmallVectorImpl<Register> &DstRegs,
3825                                         ArrayRef<Register> Src1Regs,
3826                                         ArrayRef<Register> Src2Regs,
3827                                         LLT NarrowTy) {
3828   MachineIRBuilder &B = MIRBuilder;
3829   unsigned SrcParts = Src1Regs.size();
3830   unsigned DstParts = DstRegs.size();
3831 
3832   unsigned DstIdx = 0; // Low bits of the result.
3833   Register FactorSum =
3834       B.buildMul(NarrowTy, Src1Regs[DstIdx], Src2Regs[DstIdx]).getReg(0);
3835   DstRegs[DstIdx] = FactorSum;
3836 
3837   unsigned CarrySumPrevDstIdx;
3838   SmallVector<Register, 4> Factors;
3839 
3840   for (DstIdx = 1; DstIdx < DstParts; DstIdx++) {
3841     // Collect low parts of muls for DstIdx.
3842     for (unsigned i = DstIdx + 1 < SrcParts ? 0 : DstIdx - SrcParts + 1;
3843          i <= std::min(DstIdx, SrcParts - 1); ++i) {
3844       MachineInstrBuilder Mul =
3845           B.buildMul(NarrowTy, Src1Regs[DstIdx - i], Src2Regs[i]);
3846       Factors.push_back(Mul.getReg(0));
3847     }
3848     // Collect high parts of muls from previous DstIdx.
3849     for (unsigned i = DstIdx < SrcParts ? 0 : DstIdx - SrcParts;
3850          i <= std::min(DstIdx - 1, SrcParts - 1); ++i) {
3851       MachineInstrBuilder Umulh =
3852           B.buildUMulH(NarrowTy, Src1Regs[DstIdx - 1 - i], Src2Regs[i]);
3853       Factors.push_back(Umulh.getReg(0));
3854     }
3855     // Add CarrySum from additions calculated for previous DstIdx.
3856     if (DstIdx != 1) {
3857       Factors.push_back(CarrySumPrevDstIdx);
3858     }
3859 
3860     Register CarrySum;
3861     // Add all factors and accumulate all carries into CarrySum.
3862     if (DstIdx != DstParts - 1) {
3863       MachineInstrBuilder Uaddo =
3864           B.buildUAddo(NarrowTy, LLT::scalar(1), Factors[0], Factors[1]);
3865       FactorSum = Uaddo.getReg(0);
3866       CarrySum = B.buildZExt(NarrowTy, Uaddo.getReg(1)).getReg(0);
3867       for (unsigned i = 2; i < Factors.size(); ++i) {
3868         MachineInstrBuilder Uaddo =
3869             B.buildUAddo(NarrowTy, LLT::scalar(1), FactorSum, Factors[i]);
3870         FactorSum = Uaddo.getReg(0);
3871         MachineInstrBuilder Carry = B.buildZExt(NarrowTy, Uaddo.getReg(1));
3872         CarrySum = B.buildAdd(NarrowTy, CarrySum, Carry).getReg(0);
3873       }
3874     } else {
3875       // Since value for the next index is not calculated, neither is CarrySum.
3876       FactorSum = B.buildAdd(NarrowTy, Factors[0], Factors[1]).getReg(0);
3877       for (unsigned i = 2; i < Factors.size(); ++i)
3878         FactorSum = B.buildAdd(NarrowTy, FactorSum, Factors[i]).getReg(0);
3879     }
3880 
3881     CarrySumPrevDstIdx = CarrySum;
3882     DstRegs[DstIdx] = FactorSum;
3883     Factors.clear();
3884   }
3885 }
3886 
3887 LegalizerHelper::LegalizeResult
3888 LegalizerHelper::narrowScalarMul(MachineInstr &MI, LLT NarrowTy) {
3889   Register DstReg = MI.getOperand(0).getReg();
3890   Register Src1 = MI.getOperand(1).getReg();
3891   Register Src2 = MI.getOperand(2).getReg();
3892 
3893   LLT Ty = MRI.getType(DstReg);
3894   if (Ty.isVector())
3895     return UnableToLegalize;
3896 
3897   unsigned SrcSize = MRI.getType(Src1).getSizeInBits();
3898   unsigned DstSize = Ty.getSizeInBits();
3899   unsigned NarrowSize = NarrowTy.getSizeInBits();
3900   if (DstSize % NarrowSize != 0 || SrcSize % NarrowSize != 0)
3901     return UnableToLegalize;
3902 
3903   unsigned NumDstParts = DstSize / NarrowSize;
3904   unsigned NumSrcParts = SrcSize / NarrowSize;
3905   bool IsMulHigh = MI.getOpcode() == TargetOpcode::G_UMULH;
3906   unsigned DstTmpParts = NumDstParts * (IsMulHigh ? 2 : 1);
3907 
3908   SmallVector<Register, 2> Src1Parts, Src2Parts;
3909   SmallVector<Register, 2> DstTmpRegs(DstTmpParts);
3910   extractParts(Src1, NarrowTy, NumSrcParts, Src1Parts);
3911   extractParts(Src2, NarrowTy, NumSrcParts, Src2Parts);
3912   multiplyRegisters(DstTmpRegs, Src1Parts, Src2Parts, NarrowTy);
3913 
3914   // Take only high half of registers if this is high mul.
3915   ArrayRef<Register> DstRegs(
3916       IsMulHigh ? &DstTmpRegs[DstTmpParts / 2] : &DstTmpRegs[0], NumDstParts);
3917   MIRBuilder.buildMerge(DstReg, DstRegs);
3918   MI.eraseFromParent();
3919   return Legalized;
3920 }
3921 
3922 LegalizerHelper::LegalizeResult
3923 LegalizerHelper::narrowScalarExtract(MachineInstr &MI, unsigned TypeIdx,
3924                                      LLT NarrowTy) {
3925   if (TypeIdx != 1)
3926     return UnableToLegalize;
3927 
3928   uint64_t NarrowSize = NarrowTy.getSizeInBits();
3929 
3930   int64_t SizeOp1 = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
3931   // FIXME: add support for when SizeOp1 isn't an exact multiple of
3932   // NarrowSize.
3933   if (SizeOp1 % NarrowSize != 0)
3934     return UnableToLegalize;
3935   int NumParts = SizeOp1 / NarrowSize;
3936 
3937   SmallVector<Register, 2> SrcRegs, DstRegs;
3938   SmallVector<uint64_t, 2> Indexes;
3939   extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
3940 
3941   Register OpReg = MI.getOperand(0).getReg();
3942   uint64_t OpStart = MI.getOperand(2).getImm();
3943   uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
3944   for (int i = 0; i < NumParts; ++i) {
3945     unsigned SrcStart = i * NarrowSize;
3946 
3947     if (SrcStart + NarrowSize <= OpStart || SrcStart >= OpStart + OpSize) {
3948       // No part of the extract uses this subregister, ignore it.
3949       continue;
3950     } else if (SrcStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
3951       // The entire subregister is extracted, forward the value.
3952       DstRegs.push_back(SrcRegs[i]);
3953       continue;
3954     }
3955 
3956     // OpSegStart is where this destination segment would start in OpReg if it
3957     // extended infinitely in both directions.
3958     int64_t ExtractOffset;
3959     uint64_t SegSize;
3960     if (OpStart < SrcStart) {
3961       ExtractOffset = 0;
3962       SegSize = std::min(NarrowSize, OpStart + OpSize - SrcStart);
3963     } else {
3964       ExtractOffset = OpStart - SrcStart;
3965       SegSize = std::min(SrcStart + NarrowSize - OpStart, OpSize);
3966     }
3967 
3968     Register SegReg = SrcRegs[i];
3969     if (ExtractOffset != 0 || SegSize != NarrowSize) {
3970       // A genuine extract is needed.
3971       SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
3972       MIRBuilder.buildExtract(SegReg, SrcRegs[i], ExtractOffset);
3973     }
3974 
3975     DstRegs.push_back(SegReg);
3976   }
3977 
3978   Register DstReg = MI.getOperand(0).getReg();
3979   if (MRI.getType(DstReg).isVector())
3980     MIRBuilder.buildBuildVector(DstReg, DstRegs);
3981   else if (DstRegs.size() > 1)
3982     MIRBuilder.buildMerge(DstReg, DstRegs);
3983   else
3984     MIRBuilder.buildCopy(DstReg, DstRegs[0]);
3985   MI.eraseFromParent();
3986   return Legalized;
3987 }
3988 
3989 LegalizerHelper::LegalizeResult
3990 LegalizerHelper::narrowScalarInsert(MachineInstr &MI, unsigned TypeIdx,
3991                                     LLT NarrowTy) {
3992   // FIXME: Don't know how to handle secondary types yet.
3993   if (TypeIdx != 0)
3994     return UnableToLegalize;
3995 
3996   uint64_t SizeOp0 = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
3997   uint64_t NarrowSize = NarrowTy.getSizeInBits();
3998 
3999   // FIXME: add support for when SizeOp0 isn't an exact multiple of
4000   // NarrowSize.
4001   if (SizeOp0 % NarrowSize != 0)
4002     return UnableToLegalize;
4003 
4004   int NumParts = SizeOp0 / NarrowSize;
4005 
4006   SmallVector<Register, 2> SrcRegs, DstRegs;
4007   SmallVector<uint64_t, 2> Indexes;
4008   extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
4009 
4010   Register OpReg = MI.getOperand(2).getReg();
4011   uint64_t OpStart = MI.getOperand(3).getImm();
4012   uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
4013   for (int i = 0; i < NumParts; ++i) {
4014     unsigned DstStart = i * NarrowSize;
4015 
4016     if (DstStart + NarrowSize <= OpStart || DstStart >= OpStart + OpSize) {
4017       // No part of the insert affects this subregister, forward the original.
4018       DstRegs.push_back(SrcRegs[i]);
4019       continue;
4020     } else if (DstStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
4021       // The entire subregister is defined by this insert, forward the new
4022       // value.
4023       DstRegs.push_back(OpReg);
4024       continue;
4025     }
4026 
4027     // OpSegStart is where this destination segment would start in OpReg if it
4028     // extended infinitely in both directions.
4029     int64_t ExtractOffset, InsertOffset;
4030     uint64_t SegSize;
4031     if (OpStart < DstStart) {
4032       InsertOffset = 0;
4033       ExtractOffset = DstStart - OpStart;
4034       SegSize = std::min(NarrowSize, OpStart + OpSize - DstStart);
4035     } else {
4036       InsertOffset = OpStart - DstStart;
4037       ExtractOffset = 0;
4038       SegSize =
4039         std::min(NarrowSize - InsertOffset, OpStart + OpSize - DstStart);
4040     }
4041 
4042     Register SegReg = OpReg;
4043     if (ExtractOffset != 0 || SegSize != OpSize) {
4044       // A genuine extract is needed.
4045       SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
4046       MIRBuilder.buildExtract(SegReg, OpReg, ExtractOffset);
4047     }
4048 
4049     Register DstReg = MRI.createGenericVirtualRegister(NarrowTy);
4050     MIRBuilder.buildInsert(DstReg, SrcRegs[i], SegReg, InsertOffset);
4051     DstRegs.push_back(DstReg);
4052   }
4053 
4054   assert(DstRegs.size() == (unsigned)NumParts && "not all parts covered");
4055   Register DstReg = MI.getOperand(0).getReg();
4056   if(MRI.getType(DstReg).isVector())
4057     MIRBuilder.buildBuildVector(DstReg, DstRegs);
4058   else
4059     MIRBuilder.buildMerge(DstReg, DstRegs);
4060   MI.eraseFromParent();
4061   return Legalized;
4062 }
4063 
4064 LegalizerHelper::LegalizeResult
4065 LegalizerHelper::narrowScalarBasic(MachineInstr &MI, unsigned TypeIdx,
4066                                    LLT NarrowTy) {
4067   Register DstReg = MI.getOperand(0).getReg();
4068   LLT DstTy = MRI.getType(DstReg);
4069 
4070   assert(MI.getNumOperands() == 3 && TypeIdx == 0);
4071 
4072   SmallVector<Register, 4> DstRegs, DstLeftoverRegs;
4073   SmallVector<Register, 4> Src0Regs, Src0LeftoverRegs;
4074   SmallVector<Register, 4> Src1Regs, Src1LeftoverRegs;
4075   LLT LeftoverTy;
4076   if (!extractParts(MI.getOperand(1).getReg(), DstTy, NarrowTy, LeftoverTy,
4077                     Src0Regs, Src0LeftoverRegs))
4078     return UnableToLegalize;
4079 
4080   LLT Unused;
4081   if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, Unused,
4082                     Src1Regs, Src1LeftoverRegs))
4083     llvm_unreachable("inconsistent extractParts result");
4084 
4085   for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
4086     auto Inst = MIRBuilder.buildInstr(MI.getOpcode(), {NarrowTy},
4087                                         {Src0Regs[I], Src1Regs[I]});
4088     DstRegs.push_back(Inst.getReg(0));
4089   }
4090 
4091   for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
4092     auto Inst = MIRBuilder.buildInstr(
4093       MI.getOpcode(),
4094       {LeftoverTy}, {Src0LeftoverRegs[I], Src1LeftoverRegs[I]});
4095     DstLeftoverRegs.push_back(Inst.getReg(0));
4096   }
4097 
4098   insertParts(DstReg, DstTy, NarrowTy, DstRegs,
4099               LeftoverTy, DstLeftoverRegs);
4100 
4101   MI.eraseFromParent();
4102   return Legalized;
4103 }
4104 
4105 LegalizerHelper::LegalizeResult
4106 LegalizerHelper::narrowScalarExt(MachineInstr &MI, unsigned TypeIdx,
4107                                  LLT NarrowTy) {
4108   if (TypeIdx != 0)
4109     return UnableToLegalize;
4110 
4111   Register DstReg = MI.getOperand(0).getReg();
4112   Register SrcReg = MI.getOperand(1).getReg();
4113 
4114   LLT DstTy = MRI.getType(DstReg);
4115   if (DstTy.isVector())
4116     return UnableToLegalize;
4117 
4118   SmallVector<Register, 8> Parts;
4119   LLT GCDTy = extractGCDType(Parts, DstTy, NarrowTy, SrcReg);
4120   LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts, MI.getOpcode());
4121   buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
4122 
4123   MI.eraseFromParent();
4124   return Legalized;
4125 }
4126 
4127 LegalizerHelper::LegalizeResult
4128 LegalizerHelper::narrowScalarSelect(MachineInstr &MI, unsigned TypeIdx,
4129                                     LLT NarrowTy) {
4130   if (TypeIdx != 0)
4131     return UnableToLegalize;
4132 
4133   Register CondReg = MI.getOperand(1).getReg();
4134   LLT CondTy = MRI.getType(CondReg);
4135   if (CondTy.isVector()) // TODO: Handle vselect
4136     return UnableToLegalize;
4137 
4138   Register DstReg = MI.getOperand(0).getReg();
4139   LLT DstTy = MRI.getType(DstReg);
4140 
4141   SmallVector<Register, 4> DstRegs, DstLeftoverRegs;
4142   SmallVector<Register, 4> Src1Regs, Src1LeftoverRegs;
4143   SmallVector<Register, 4> Src2Regs, Src2LeftoverRegs;
4144   LLT LeftoverTy;
4145   if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, LeftoverTy,
4146                     Src1Regs, Src1LeftoverRegs))
4147     return UnableToLegalize;
4148 
4149   LLT Unused;
4150   if (!extractParts(MI.getOperand(3).getReg(), DstTy, NarrowTy, Unused,
4151                     Src2Regs, Src2LeftoverRegs))
4152     llvm_unreachable("inconsistent extractParts result");
4153 
4154   for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
4155     auto Select = MIRBuilder.buildSelect(NarrowTy,
4156                                          CondReg, Src1Regs[I], Src2Regs[I]);
4157     DstRegs.push_back(Select.getReg(0));
4158   }
4159 
4160   for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
4161     auto Select = MIRBuilder.buildSelect(
4162       LeftoverTy, CondReg, Src1LeftoverRegs[I], Src2LeftoverRegs[I]);
4163     DstLeftoverRegs.push_back(Select.getReg(0));
4164   }
4165 
4166   insertParts(DstReg, DstTy, NarrowTy, DstRegs,
4167               LeftoverTy, DstLeftoverRegs);
4168 
4169   MI.eraseFromParent();
4170   return Legalized;
4171 }
4172 
4173 LegalizerHelper::LegalizeResult
4174 LegalizerHelper::narrowScalarCTLZ(MachineInstr &MI, unsigned TypeIdx,
4175                                   LLT NarrowTy) {
4176   if (TypeIdx != 1)
4177     return UnableToLegalize;
4178 
4179   Register DstReg = MI.getOperand(0).getReg();
4180   Register SrcReg = MI.getOperand(1).getReg();
4181   LLT DstTy = MRI.getType(DstReg);
4182   LLT SrcTy = MRI.getType(SrcReg);
4183   unsigned NarrowSize = NarrowTy.getSizeInBits();
4184 
4185   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
4186     const bool IsUndef = MI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_UNDEF;
4187 
4188     MachineIRBuilder &B = MIRBuilder;
4189     auto UnmergeSrc = B.buildUnmerge(NarrowTy, SrcReg);
4190     // ctlz(Hi:Lo) -> Hi == 0 ? (NarrowSize + ctlz(Lo)) : ctlz(Hi)
4191     auto C_0 = B.buildConstant(NarrowTy, 0);
4192     auto HiIsZero = B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
4193                                 UnmergeSrc.getReg(1), C_0);
4194     auto LoCTLZ = IsUndef ?
4195       B.buildCTLZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(0)) :
4196       B.buildCTLZ(DstTy, UnmergeSrc.getReg(0));
4197     auto C_NarrowSize = B.buildConstant(DstTy, NarrowSize);
4198     auto HiIsZeroCTLZ = B.buildAdd(DstTy, LoCTLZ, C_NarrowSize);
4199     auto HiCTLZ = B.buildCTLZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(1));
4200     B.buildSelect(DstReg, HiIsZero, HiIsZeroCTLZ, HiCTLZ);
4201 
4202     MI.eraseFromParent();
4203     return Legalized;
4204   }
4205 
4206   return UnableToLegalize;
4207 }
4208 
4209 LegalizerHelper::LegalizeResult
4210 LegalizerHelper::narrowScalarCTTZ(MachineInstr &MI, unsigned TypeIdx,
4211                                   LLT NarrowTy) {
4212   if (TypeIdx != 1)
4213     return UnableToLegalize;
4214 
4215   Register DstReg = MI.getOperand(0).getReg();
4216   Register SrcReg = MI.getOperand(1).getReg();
4217   LLT DstTy = MRI.getType(DstReg);
4218   LLT SrcTy = MRI.getType(SrcReg);
4219   unsigned NarrowSize = NarrowTy.getSizeInBits();
4220 
4221   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
4222     const bool IsUndef = MI.getOpcode() == TargetOpcode::G_CTTZ_ZERO_UNDEF;
4223 
4224     MachineIRBuilder &B = MIRBuilder;
4225     auto UnmergeSrc = B.buildUnmerge(NarrowTy, SrcReg);
4226     // cttz(Hi:Lo) -> Lo == 0 ? (cttz(Hi) + NarrowSize) : cttz(Lo)
4227     auto C_0 = B.buildConstant(NarrowTy, 0);
4228     auto LoIsZero = B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
4229                                 UnmergeSrc.getReg(0), C_0);
4230     auto HiCTTZ = IsUndef ?
4231       B.buildCTTZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(1)) :
4232       B.buildCTTZ(DstTy, UnmergeSrc.getReg(1));
4233     auto C_NarrowSize = B.buildConstant(DstTy, NarrowSize);
4234     auto LoIsZeroCTTZ = B.buildAdd(DstTy, HiCTTZ, C_NarrowSize);
4235     auto LoCTTZ = B.buildCTTZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(0));
4236     B.buildSelect(DstReg, LoIsZero, LoIsZeroCTTZ, LoCTTZ);
4237 
4238     MI.eraseFromParent();
4239     return Legalized;
4240   }
4241 
4242   return UnableToLegalize;
4243 }
4244 
4245 LegalizerHelper::LegalizeResult
4246 LegalizerHelper::narrowScalarCTPOP(MachineInstr &MI, unsigned TypeIdx,
4247                                    LLT NarrowTy) {
4248   if (TypeIdx != 1)
4249     return UnableToLegalize;
4250 
4251   Register DstReg = MI.getOperand(0).getReg();
4252   LLT DstTy = MRI.getType(DstReg);
4253   LLT SrcTy = MRI.getType(MI.getOperand(1).getReg());
4254   unsigned NarrowSize = NarrowTy.getSizeInBits();
4255 
4256   if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
4257     auto UnmergeSrc = MIRBuilder.buildUnmerge(NarrowTy, MI.getOperand(1));
4258 
4259     auto LoCTPOP = MIRBuilder.buildCTPOP(DstTy, UnmergeSrc.getReg(0));
4260     auto HiCTPOP = MIRBuilder.buildCTPOP(DstTy, UnmergeSrc.getReg(1));
4261     MIRBuilder.buildAdd(DstReg, HiCTPOP, LoCTPOP);
4262 
4263     MI.eraseFromParent();
4264     return Legalized;
4265   }
4266 
4267   return UnableToLegalize;
4268 }
4269 
4270 LegalizerHelper::LegalizeResult
4271 LegalizerHelper::lowerBitCount(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
4272   unsigned Opc = MI.getOpcode();
4273   auto &TII = *MI.getMF()->getSubtarget().getInstrInfo();
4274   auto isSupported = [this](const LegalityQuery &Q) {
4275     auto QAction = LI.getAction(Q).Action;
4276     return QAction == Legal || QAction == Libcall || QAction == Custom;
4277   };
4278   switch (Opc) {
4279   default:
4280     return UnableToLegalize;
4281   case TargetOpcode::G_CTLZ_ZERO_UNDEF: {
4282     // This trivially expands to CTLZ.
4283     Observer.changingInstr(MI);
4284     MI.setDesc(TII.get(TargetOpcode::G_CTLZ));
4285     Observer.changedInstr(MI);
4286     return Legalized;
4287   }
4288   case TargetOpcode::G_CTLZ: {
4289     Register DstReg = MI.getOperand(0).getReg();
4290     Register SrcReg = MI.getOperand(1).getReg();
4291     LLT DstTy = MRI.getType(DstReg);
4292     LLT SrcTy = MRI.getType(SrcReg);
4293     unsigned Len = SrcTy.getSizeInBits();
4294 
4295     if (isSupported({TargetOpcode::G_CTLZ_ZERO_UNDEF, {DstTy, SrcTy}})) {
4296       // If CTLZ_ZERO_UNDEF is supported, emit that and a select for zero.
4297       auto CtlzZU = MIRBuilder.buildCTLZ_ZERO_UNDEF(DstTy, SrcReg);
4298       auto ZeroSrc = MIRBuilder.buildConstant(SrcTy, 0);
4299       auto ICmp = MIRBuilder.buildICmp(
4300           CmpInst::ICMP_EQ, SrcTy.changeElementSize(1), SrcReg, ZeroSrc);
4301       auto LenConst = MIRBuilder.buildConstant(DstTy, Len);
4302       MIRBuilder.buildSelect(DstReg, ICmp, LenConst, CtlzZU);
4303       MI.eraseFromParent();
4304       return Legalized;
4305     }
4306     // for now, we do this:
4307     // NewLen = NextPowerOf2(Len);
4308     // x = x | (x >> 1);
4309     // x = x | (x >> 2);
4310     // ...
4311     // x = x | (x >>16);
4312     // x = x | (x >>32); // for 64-bit input
4313     // Upto NewLen/2
4314     // return Len - popcount(x);
4315     //
4316     // Ref: "Hacker's Delight" by Henry Warren
4317     Register Op = SrcReg;
4318     unsigned NewLen = PowerOf2Ceil(Len);
4319     for (unsigned i = 0; (1U << i) <= (NewLen / 2); ++i) {
4320       auto MIBShiftAmt = MIRBuilder.buildConstant(SrcTy, 1ULL << i);
4321       auto MIBOp = MIRBuilder.buildOr(
4322           SrcTy, Op, MIRBuilder.buildLShr(SrcTy, Op, MIBShiftAmt));
4323       Op = MIBOp.getReg(0);
4324     }
4325     auto MIBPop = MIRBuilder.buildCTPOP(DstTy, Op);
4326     MIRBuilder.buildSub(MI.getOperand(0), MIRBuilder.buildConstant(DstTy, Len),
4327                         MIBPop);
4328     MI.eraseFromParent();
4329     return Legalized;
4330   }
4331   case TargetOpcode::G_CTTZ_ZERO_UNDEF: {
4332     // This trivially expands to CTTZ.
4333     Observer.changingInstr(MI);
4334     MI.setDesc(TII.get(TargetOpcode::G_CTTZ));
4335     Observer.changedInstr(MI);
4336     return Legalized;
4337   }
4338   case TargetOpcode::G_CTTZ: {
4339     Register DstReg = MI.getOperand(0).getReg();
4340     Register SrcReg = MI.getOperand(1).getReg();
4341     LLT DstTy = MRI.getType(DstReg);
4342     LLT SrcTy = MRI.getType(SrcReg);
4343 
4344     unsigned Len = SrcTy.getSizeInBits();
4345     if (isSupported({TargetOpcode::G_CTTZ_ZERO_UNDEF, {DstTy, SrcTy}})) {
4346       // If CTTZ_ZERO_UNDEF is legal or custom, emit that and a select with
4347       // zero.
4348       auto CttzZU = MIRBuilder.buildCTTZ_ZERO_UNDEF(DstTy, SrcReg);
4349       auto Zero = MIRBuilder.buildConstant(SrcTy, 0);
4350       auto ICmp = MIRBuilder.buildICmp(
4351           CmpInst::ICMP_EQ, DstTy.changeElementSize(1), SrcReg, Zero);
4352       auto LenConst = MIRBuilder.buildConstant(DstTy, Len);
4353       MIRBuilder.buildSelect(DstReg, ICmp, LenConst, CttzZU);
4354       MI.eraseFromParent();
4355       return Legalized;
4356     }
4357     // for now, we use: { return popcount(~x & (x - 1)); }
4358     // unless the target has ctlz but not ctpop, in which case we use:
4359     // { return 32 - nlz(~x & (x-1)); }
4360     // Ref: "Hacker's Delight" by Henry Warren
4361     auto MIBCstNeg1 = MIRBuilder.buildConstant(Ty, -1);
4362     auto MIBNot = MIRBuilder.buildXor(Ty, SrcReg, MIBCstNeg1);
4363     auto MIBTmp = MIRBuilder.buildAnd(
4364         Ty, MIBNot, MIRBuilder.buildAdd(Ty, SrcReg, MIBCstNeg1));
4365     if (!isSupported({TargetOpcode::G_CTPOP, {Ty, Ty}}) &&
4366         isSupported({TargetOpcode::G_CTLZ, {Ty, Ty}})) {
4367       auto MIBCstLen = MIRBuilder.buildConstant(Ty, Len);
4368       MIRBuilder.buildSub(MI.getOperand(0), MIBCstLen,
4369                           MIRBuilder.buildCTLZ(Ty, MIBTmp));
4370       MI.eraseFromParent();
4371       return Legalized;
4372     }
4373     MI.setDesc(TII.get(TargetOpcode::G_CTPOP));
4374     MI.getOperand(1).setReg(MIBTmp.getReg(0));
4375     return Legalized;
4376   }
4377   case TargetOpcode::G_CTPOP: {
4378     unsigned Size = Ty.getSizeInBits();
4379     MachineIRBuilder &B = MIRBuilder;
4380 
4381     // Count set bits in blocks of 2 bits. Default approach would be
4382     // B2Count = { val & 0x55555555 } + { (val >> 1) & 0x55555555 }
4383     // We use following formula instead:
4384     // B2Count = val - { (val >> 1) & 0x55555555 }
4385     // since it gives same result in blocks of 2 with one instruction less.
4386     auto C_1 = B.buildConstant(Ty, 1);
4387     auto B2Set1LoTo1Hi = B.buildLShr(Ty, MI.getOperand(1).getReg(), C_1);
4388     APInt B2Mask1HiTo0 = APInt::getSplat(Size, APInt(8, 0x55));
4389     auto C_B2Mask1HiTo0 = B.buildConstant(Ty, B2Mask1HiTo0);
4390     auto B2Count1Hi = B.buildAnd(Ty, B2Set1LoTo1Hi, C_B2Mask1HiTo0);
4391     auto B2Count = B.buildSub(Ty, MI.getOperand(1).getReg(), B2Count1Hi);
4392 
4393     // In order to get count in blocks of 4 add values from adjacent block of 2.
4394     // B4Count = { B2Count & 0x33333333 } + { (B2Count >> 2) & 0x33333333 }
4395     auto C_2 = B.buildConstant(Ty, 2);
4396     auto B4Set2LoTo2Hi = B.buildLShr(Ty, B2Count, C_2);
4397     APInt B4Mask2HiTo0 = APInt::getSplat(Size, APInt(8, 0x33));
4398     auto C_B4Mask2HiTo0 = B.buildConstant(Ty, B4Mask2HiTo0);
4399     auto B4HiB2Count = B.buildAnd(Ty, B4Set2LoTo2Hi, C_B4Mask2HiTo0);
4400     auto B4LoB2Count = B.buildAnd(Ty, B2Count, C_B4Mask2HiTo0);
4401     auto B4Count = B.buildAdd(Ty, B4HiB2Count, B4LoB2Count);
4402 
4403     // For count in blocks of 8 bits we don't have to mask high 4 bits before
4404     // addition since count value sits in range {0,...,8} and 4 bits are enough
4405     // to hold such binary values. After addition high 4 bits still hold count
4406     // of set bits in high 4 bit block, set them to zero and get 8 bit result.
4407     // B8Count = { B4Count + (B4Count >> 4) } & 0x0F0F0F0F
4408     auto C_4 = B.buildConstant(Ty, 4);
4409     auto B8HiB4Count = B.buildLShr(Ty, B4Count, C_4);
4410     auto B8CountDirty4Hi = B.buildAdd(Ty, B8HiB4Count, B4Count);
4411     APInt B8Mask4HiTo0 = APInt::getSplat(Size, APInt(8, 0x0F));
4412     auto C_B8Mask4HiTo0 = B.buildConstant(Ty, B8Mask4HiTo0);
4413     auto B8Count = B.buildAnd(Ty, B8CountDirty4Hi, C_B8Mask4HiTo0);
4414 
4415     assert(Size<=128 && "Scalar size is too large for CTPOP lower algorithm");
4416     // 8 bits can hold CTPOP result of 128 bit int or smaller. Mul with this
4417     // bitmask will set 8 msb in ResTmp to sum of all B8Counts in 8 bit blocks.
4418     auto MulMask = B.buildConstant(Ty, APInt::getSplat(Size, APInt(8, 0x01)));
4419     auto ResTmp = B.buildMul(Ty, B8Count, MulMask);
4420 
4421     // Shift count result from 8 high bits to low bits.
4422     auto C_SizeM8 = B.buildConstant(Ty, Size - 8);
4423     B.buildLShr(MI.getOperand(0).getReg(), ResTmp, C_SizeM8);
4424 
4425     MI.eraseFromParent();
4426     return Legalized;
4427   }
4428   }
4429 }
4430 
4431 // Expand s32 = G_UITOFP s64 using bit operations to an IEEE float
4432 // representation.
4433 LegalizerHelper::LegalizeResult
4434 LegalizerHelper::lowerU64ToF32BitOps(MachineInstr &MI) {
4435   Register Dst = MI.getOperand(0).getReg();
4436   Register Src = MI.getOperand(1).getReg();
4437   const LLT S64 = LLT::scalar(64);
4438   const LLT S32 = LLT::scalar(32);
4439   const LLT S1 = LLT::scalar(1);
4440 
4441   assert(MRI.getType(Src) == S64 && MRI.getType(Dst) == S32);
4442 
4443   // unsigned cul2f(ulong u) {
4444   //   uint lz = clz(u);
4445   //   uint e = (u != 0) ? 127U + 63U - lz : 0;
4446   //   u = (u << lz) & 0x7fffffffffffffffUL;
4447   //   ulong t = u & 0xffffffffffUL;
4448   //   uint v = (e << 23) | (uint)(u >> 40);
4449   //   uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
4450   //   return as_float(v + r);
4451   // }
4452 
4453   auto Zero32 = MIRBuilder.buildConstant(S32, 0);
4454   auto Zero64 = MIRBuilder.buildConstant(S64, 0);
4455 
4456   auto LZ = MIRBuilder.buildCTLZ_ZERO_UNDEF(S32, Src);
4457 
4458   auto K = MIRBuilder.buildConstant(S32, 127U + 63U);
4459   auto Sub = MIRBuilder.buildSub(S32, K, LZ);
4460 
4461   auto NotZero = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, Src, Zero64);
4462   auto E = MIRBuilder.buildSelect(S32, NotZero, Sub, Zero32);
4463 
4464   auto Mask0 = MIRBuilder.buildConstant(S64, (-1ULL) >> 1);
4465   auto ShlLZ = MIRBuilder.buildShl(S64, Src, LZ);
4466 
4467   auto U = MIRBuilder.buildAnd(S64, ShlLZ, Mask0);
4468 
4469   auto Mask1 = MIRBuilder.buildConstant(S64, 0xffffffffffULL);
4470   auto T = MIRBuilder.buildAnd(S64, U, Mask1);
4471 
4472   auto UShl = MIRBuilder.buildLShr(S64, U, MIRBuilder.buildConstant(S64, 40));
4473   auto ShlE = MIRBuilder.buildShl(S32, E, MIRBuilder.buildConstant(S32, 23));
4474   auto V = MIRBuilder.buildOr(S32, ShlE, MIRBuilder.buildTrunc(S32, UShl));
4475 
4476   auto C = MIRBuilder.buildConstant(S64, 0x8000000000ULL);
4477   auto RCmp = MIRBuilder.buildICmp(CmpInst::ICMP_UGT, S1, T, C);
4478   auto TCmp = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1, T, C);
4479   auto One = MIRBuilder.buildConstant(S32, 1);
4480 
4481   auto VTrunc1 = MIRBuilder.buildAnd(S32, V, One);
4482   auto Select0 = MIRBuilder.buildSelect(S32, TCmp, VTrunc1, Zero32);
4483   auto R = MIRBuilder.buildSelect(S32, RCmp, One, Select0);
4484   MIRBuilder.buildAdd(Dst, V, R);
4485 
4486   MI.eraseFromParent();
4487   return Legalized;
4488 }
4489 
4490 LegalizerHelper::LegalizeResult
4491 LegalizerHelper::lowerUITOFP(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
4492   Register Dst = MI.getOperand(0).getReg();
4493   Register Src = MI.getOperand(1).getReg();
4494   LLT DstTy = MRI.getType(Dst);
4495   LLT SrcTy = MRI.getType(Src);
4496 
4497   if (SrcTy == LLT::scalar(1)) {
4498     auto True = MIRBuilder.buildFConstant(DstTy, 1.0);
4499     auto False = MIRBuilder.buildFConstant(DstTy, 0.0);
4500     MIRBuilder.buildSelect(Dst, Src, True, False);
4501     MI.eraseFromParent();
4502     return Legalized;
4503   }
4504 
4505   if (SrcTy != LLT::scalar(64))
4506     return UnableToLegalize;
4507 
4508   if (DstTy == LLT::scalar(32)) {
4509     // TODO: SelectionDAG has several alternative expansions to port which may
4510     // be more reasonble depending on the available instructions. If a target
4511     // has sitofp, does not have CTLZ, or can efficiently use f64 as an
4512     // intermediate type, this is probably worse.
4513     return lowerU64ToF32BitOps(MI);
4514   }
4515 
4516   return UnableToLegalize;
4517 }
4518 
4519 LegalizerHelper::LegalizeResult
4520 LegalizerHelper::lowerSITOFP(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
4521   Register Dst = MI.getOperand(0).getReg();
4522   Register Src = MI.getOperand(1).getReg();
4523   LLT DstTy = MRI.getType(Dst);
4524   LLT SrcTy = MRI.getType(Src);
4525 
4526   const LLT S64 = LLT::scalar(64);
4527   const LLT S32 = LLT::scalar(32);
4528   const LLT S1 = LLT::scalar(1);
4529 
4530   if (SrcTy == S1) {
4531     auto True = MIRBuilder.buildFConstant(DstTy, -1.0);
4532     auto False = MIRBuilder.buildFConstant(DstTy, 0.0);
4533     MIRBuilder.buildSelect(Dst, Src, True, False);
4534     MI.eraseFromParent();
4535     return Legalized;
4536   }
4537 
4538   if (SrcTy != S64)
4539     return UnableToLegalize;
4540 
4541   if (DstTy == S32) {
4542     // signed cl2f(long l) {
4543     //   long s = l >> 63;
4544     //   float r = cul2f((l + s) ^ s);
4545     //   return s ? -r : r;
4546     // }
4547     Register L = Src;
4548     auto SignBit = MIRBuilder.buildConstant(S64, 63);
4549     auto S = MIRBuilder.buildAShr(S64, L, SignBit);
4550 
4551     auto LPlusS = MIRBuilder.buildAdd(S64, L, S);
4552     auto Xor = MIRBuilder.buildXor(S64, LPlusS, S);
4553     auto R = MIRBuilder.buildUITOFP(S32, Xor);
4554 
4555     auto RNeg = MIRBuilder.buildFNeg(S32, R);
4556     auto SignNotZero = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, S,
4557                                             MIRBuilder.buildConstant(S64, 0));
4558     MIRBuilder.buildSelect(Dst, SignNotZero, RNeg, R);
4559     MI.eraseFromParent();
4560     return Legalized;
4561   }
4562 
4563   return UnableToLegalize;
4564 }
4565 
4566 LegalizerHelper::LegalizeResult
4567 LegalizerHelper::lowerFPTOUI(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
4568   Register Dst = MI.getOperand(0).getReg();
4569   Register Src = MI.getOperand(1).getReg();
4570   LLT DstTy = MRI.getType(Dst);
4571   LLT SrcTy = MRI.getType(Src);
4572   const LLT S64 = LLT::scalar(64);
4573   const LLT S32 = LLT::scalar(32);
4574 
4575   if (SrcTy != S64 && SrcTy != S32)
4576     return UnableToLegalize;
4577   if (DstTy != S32 && DstTy != S64)
4578     return UnableToLegalize;
4579 
4580   // FPTOSI gives same result as FPTOUI for positive signed integers.
4581   // FPTOUI needs to deal with fp values that convert to unsigned integers
4582   // greater or equal to 2^31 for float or 2^63 for double. For brevity 2^Exp.
4583 
4584   APInt TwoPExpInt = APInt::getSignMask(DstTy.getSizeInBits());
4585   APFloat TwoPExpFP(SrcTy.getSizeInBits() == 32 ? APFloat::IEEEsingle()
4586                                                 : APFloat::IEEEdouble(),
4587                     APInt::getNullValue(SrcTy.getSizeInBits()));
4588   TwoPExpFP.convertFromAPInt(TwoPExpInt, false, APFloat::rmNearestTiesToEven);
4589 
4590   MachineInstrBuilder FPTOSI = MIRBuilder.buildFPTOSI(DstTy, Src);
4591 
4592   MachineInstrBuilder Threshold = MIRBuilder.buildFConstant(SrcTy, TwoPExpFP);
4593   // For fp Value greater or equal to Threshold(2^Exp), we use FPTOSI on
4594   // (Value - 2^Exp) and add 2^Exp by setting highest bit in result to 1.
4595   MachineInstrBuilder FSub = MIRBuilder.buildFSub(SrcTy, Src, Threshold);
4596   MachineInstrBuilder ResLowBits = MIRBuilder.buildFPTOSI(DstTy, FSub);
4597   MachineInstrBuilder ResHighBit = MIRBuilder.buildConstant(DstTy, TwoPExpInt);
4598   MachineInstrBuilder Res = MIRBuilder.buildXor(DstTy, ResLowBits, ResHighBit);
4599 
4600   const LLT S1 = LLT::scalar(1);
4601 
4602   MachineInstrBuilder FCMP =
4603       MIRBuilder.buildFCmp(CmpInst::FCMP_ULT, S1, Src, Threshold);
4604   MIRBuilder.buildSelect(Dst, FCMP, FPTOSI, Res);
4605 
4606   MI.eraseFromParent();
4607   return Legalized;
4608 }
4609 
4610 LegalizerHelper::LegalizeResult LegalizerHelper::lowerFPTOSI(MachineInstr &MI) {
4611   Register Dst = MI.getOperand(0).getReg();
4612   Register Src = MI.getOperand(1).getReg();
4613   LLT DstTy = MRI.getType(Dst);
4614   LLT SrcTy = MRI.getType(Src);
4615   const LLT S64 = LLT::scalar(64);
4616   const LLT S32 = LLT::scalar(32);
4617 
4618   // FIXME: Only f32 to i64 conversions are supported.
4619   if (SrcTy.getScalarType() != S32 || DstTy.getScalarType() != S64)
4620     return UnableToLegalize;
4621 
4622   // Expand f32 -> i64 conversion
4623   // This algorithm comes from compiler-rt's implementation of fixsfdi:
4624   // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/builtins/fixsfdi.c
4625 
4626   unsigned SrcEltBits = SrcTy.getScalarSizeInBits();
4627 
4628   auto ExponentMask = MIRBuilder.buildConstant(SrcTy, 0x7F800000);
4629   auto ExponentLoBit = MIRBuilder.buildConstant(SrcTy, 23);
4630 
4631   auto AndExpMask = MIRBuilder.buildAnd(SrcTy, Src, ExponentMask);
4632   auto ExponentBits = MIRBuilder.buildLShr(SrcTy, AndExpMask, ExponentLoBit);
4633 
4634   auto SignMask = MIRBuilder.buildConstant(SrcTy,
4635                                            APInt::getSignMask(SrcEltBits));
4636   auto AndSignMask = MIRBuilder.buildAnd(SrcTy, Src, SignMask);
4637   auto SignLowBit = MIRBuilder.buildConstant(SrcTy, SrcEltBits - 1);
4638   auto Sign = MIRBuilder.buildAShr(SrcTy, AndSignMask, SignLowBit);
4639   Sign = MIRBuilder.buildSExt(DstTy, Sign);
4640 
4641   auto MantissaMask = MIRBuilder.buildConstant(SrcTy, 0x007FFFFF);
4642   auto AndMantissaMask = MIRBuilder.buildAnd(SrcTy, Src, MantissaMask);
4643   auto K = MIRBuilder.buildConstant(SrcTy, 0x00800000);
4644 
4645   auto R = MIRBuilder.buildOr(SrcTy, AndMantissaMask, K);
4646   R = MIRBuilder.buildZExt(DstTy, R);
4647 
4648   auto Bias = MIRBuilder.buildConstant(SrcTy, 127);
4649   auto Exponent = MIRBuilder.buildSub(SrcTy, ExponentBits, Bias);
4650   auto SubExponent = MIRBuilder.buildSub(SrcTy, Exponent, ExponentLoBit);
4651   auto ExponentSub = MIRBuilder.buildSub(SrcTy, ExponentLoBit, Exponent);
4652 
4653   auto Shl = MIRBuilder.buildShl(DstTy, R, SubExponent);
4654   auto Srl = MIRBuilder.buildLShr(DstTy, R, ExponentSub);
4655 
4656   const LLT S1 = LLT::scalar(1);
4657   auto CmpGt = MIRBuilder.buildICmp(CmpInst::ICMP_SGT,
4658                                     S1, Exponent, ExponentLoBit);
4659 
4660   R = MIRBuilder.buildSelect(DstTy, CmpGt, Shl, Srl);
4661 
4662   auto XorSign = MIRBuilder.buildXor(DstTy, R, Sign);
4663   auto Ret = MIRBuilder.buildSub(DstTy, XorSign, Sign);
4664 
4665   auto ZeroSrcTy = MIRBuilder.buildConstant(SrcTy, 0);
4666 
4667   auto ExponentLt0 = MIRBuilder.buildICmp(CmpInst::ICMP_SLT,
4668                                           S1, Exponent, ZeroSrcTy);
4669 
4670   auto ZeroDstTy = MIRBuilder.buildConstant(DstTy, 0);
4671   MIRBuilder.buildSelect(Dst, ExponentLt0, ZeroDstTy, Ret);
4672 
4673   MI.eraseFromParent();
4674   return Legalized;
4675 }
4676 
4677 // f64 -> f16 conversion using round-to-nearest-even rounding mode.
4678 LegalizerHelper::LegalizeResult
4679 LegalizerHelper::lowerFPTRUNC_F64_TO_F16(MachineInstr &MI) {
4680   Register Dst = MI.getOperand(0).getReg();
4681   Register Src = MI.getOperand(1).getReg();
4682 
4683   if (MRI.getType(Src).isVector()) // TODO: Handle vectors directly.
4684     return UnableToLegalize;
4685 
4686   const unsigned ExpMask = 0x7ff;
4687   const unsigned ExpBiasf64 = 1023;
4688   const unsigned ExpBiasf16 = 15;
4689   const LLT S32 = LLT::scalar(32);
4690   const LLT S1 = LLT::scalar(1);
4691 
4692   auto Unmerge = MIRBuilder.buildUnmerge(S32, Src);
4693   Register U = Unmerge.getReg(0);
4694   Register UH = Unmerge.getReg(1);
4695 
4696   auto E = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 20));
4697   E = MIRBuilder.buildAnd(S32, E, MIRBuilder.buildConstant(S32, ExpMask));
4698 
4699   // Subtract the fp64 exponent bias (1023) to get the real exponent and
4700   // add the f16 bias (15) to get the biased exponent for the f16 format.
4701   E = MIRBuilder.buildAdd(
4702     S32, E, MIRBuilder.buildConstant(S32, -ExpBiasf64 + ExpBiasf16));
4703 
4704   auto M = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 8));
4705   M = MIRBuilder.buildAnd(S32, M, MIRBuilder.buildConstant(S32, 0xffe));
4706 
4707   auto MaskedSig = MIRBuilder.buildAnd(S32, UH,
4708                                        MIRBuilder.buildConstant(S32, 0x1ff));
4709   MaskedSig = MIRBuilder.buildOr(S32, MaskedSig, U);
4710 
4711   auto Zero = MIRBuilder.buildConstant(S32, 0);
4712   auto SigCmpNE0 = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, MaskedSig, Zero);
4713   auto Lo40Set = MIRBuilder.buildZExt(S32, SigCmpNE0);
4714   M = MIRBuilder.buildOr(S32, M, Lo40Set);
4715 
4716   // (M != 0 ? 0x0200 : 0) | 0x7c00;
4717   auto Bits0x200 = MIRBuilder.buildConstant(S32, 0x0200);
4718   auto CmpM_NE0 = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, M, Zero);
4719   auto SelectCC = MIRBuilder.buildSelect(S32, CmpM_NE0, Bits0x200, Zero);
4720 
4721   auto Bits0x7c00 = MIRBuilder.buildConstant(S32, 0x7c00);
4722   auto I = MIRBuilder.buildOr(S32, SelectCC, Bits0x7c00);
4723 
4724   // N = M | (E << 12);
4725   auto EShl12 = MIRBuilder.buildShl(S32, E, MIRBuilder.buildConstant(S32, 12));
4726   auto N = MIRBuilder.buildOr(S32, M, EShl12);
4727 
4728   // B = clamp(1-E, 0, 13);
4729   auto One = MIRBuilder.buildConstant(S32, 1);
4730   auto OneSubExp = MIRBuilder.buildSub(S32, One, E);
4731   auto B = MIRBuilder.buildSMax(S32, OneSubExp, Zero);
4732   B = MIRBuilder.buildSMin(S32, B, MIRBuilder.buildConstant(S32, 13));
4733 
4734   auto SigSetHigh = MIRBuilder.buildOr(S32, M,
4735                                        MIRBuilder.buildConstant(S32, 0x1000));
4736 
4737   auto D = MIRBuilder.buildLShr(S32, SigSetHigh, B);
4738   auto D0 = MIRBuilder.buildShl(S32, D, B);
4739 
4740   auto D0_NE_SigSetHigh = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1,
4741                                              D0, SigSetHigh);
4742   auto D1 = MIRBuilder.buildZExt(S32, D0_NE_SigSetHigh);
4743   D = MIRBuilder.buildOr(S32, D, D1);
4744 
4745   auto CmpELtOne = MIRBuilder.buildICmp(CmpInst::ICMP_SLT, S1, E, One);
4746   auto V = MIRBuilder.buildSelect(S32, CmpELtOne, D, N);
4747 
4748   auto VLow3 = MIRBuilder.buildAnd(S32, V, MIRBuilder.buildConstant(S32, 7));
4749   V = MIRBuilder.buildLShr(S32, V, MIRBuilder.buildConstant(S32, 2));
4750 
4751   auto VLow3Eq3 = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1, VLow3,
4752                                        MIRBuilder.buildConstant(S32, 3));
4753   auto V0 = MIRBuilder.buildZExt(S32, VLow3Eq3);
4754 
4755   auto VLow3Gt5 = MIRBuilder.buildICmp(CmpInst::ICMP_SGT, S1, VLow3,
4756                                        MIRBuilder.buildConstant(S32, 5));
4757   auto V1 = MIRBuilder.buildZExt(S32, VLow3Gt5);
4758 
4759   V1 = MIRBuilder.buildOr(S32, V0, V1);
4760   V = MIRBuilder.buildAdd(S32, V, V1);
4761 
4762   auto CmpEGt30 = MIRBuilder.buildICmp(CmpInst::ICMP_SGT,  S1,
4763                                        E, MIRBuilder.buildConstant(S32, 30));
4764   V = MIRBuilder.buildSelect(S32, CmpEGt30,
4765                              MIRBuilder.buildConstant(S32, 0x7c00), V);
4766 
4767   auto CmpEGt1039 = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1,
4768                                          E, MIRBuilder.buildConstant(S32, 1039));
4769   V = MIRBuilder.buildSelect(S32, CmpEGt1039, I, V);
4770 
4771   // Extract the sign bit.
4772   auto Sign = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 16));
4773   Sign = MIRBuilder.buildAnd(S32, Sign, MIRBuilder.buildConstant(S32, 0x8000));
4774 
4775   // Insert the sign bit
4776   V = MIRBuilder.buildOr(S32, Sign, V);
4777 
4778   MIRBuilder.buildTrunc(Dst, V);
4779   MI.eraseFromParent();
4780   return Legalized;
4781 }
4782 
4783 LegalizerHelper::LegalizeResult
4784 LegalizerHelper::lowerFPTRUNC(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
4785   Register Dst = MI.getOperand(0).getReg();
4786   Register Src = MI.getOperand(1).getReg();
4787 
4788   LLT DstTy = MRI.getType(Dst);
4789   LLT SrcTy = MRI.getType(Src);
4790   const LLT S64 = LLT::scalar(64);
4791   const LLT S16 = LLT::scalar(16);
4792 
4793   if (DstTy.getScalarType() == S16 && SrcTy.getScalarType() == S64)
4794     return lowerFPTRUNC_F64_TO_F16(MI);
4795 
4796   return UnableToLegalize;
4797 }
4798 
4799 static CmpInst::Predicate minMaxToCompare(unsigned Opc) {
4800   switch (Opc) {
4801   case TargetOpcode::G_SMIN:
4802     return CmpInst::ICMP_SLT;
4803   case TargetOpcode::G_SMAX:
4804     return CmpInst::ICMP_SGT;
4805   case TargetOpcode::G_UMIN:
4806     return CmpInst::ICMP_ULT;
4807   case TargetOpcode::G_UMAX:
4808     return CmpInst::ICMP_UGT;
4809   default:
4810     llvm_unreachable("not in integer min/max");
4811   }
4812 }
4813 
4814 LegalizerHelper::LegalizeResult
4815 LegalizerHelper::lowerMinMax(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
4816   Register Dst = MI.getOperand(0).getReg();
4817   Register Src0 = MI.getOperand(1).getReg();
4818   Register Src1 = MI.getOperand(2).getReg();
4819 
4820   const CmpInst::Predicate Pred = minMaxToCompare(MI.getOpcode());
4821   LLT CmpType = MRI.getType(Dst).changeElementSize(1);
4822 
4823   auto Cmp = MIRBuilder.buildICmp(Pred, CmpType, Src0, Src1);
4824   MIRBuilder.buildSelect(Dst, Cmp, Src0, Src1);
4825 
4826   MI.eraseFromParent();
4827   return Legalized;
4828 }
4829 
4830 LegalizerHelper::LegalizeResult
4831 LegalizerHelper::lowerFCopySign(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
4832   Register Dst = MI.getOperand(0).getReg();
4833   Register Src0 = MI.getOperand(1).getReg();
4834   Register Src1 = MI.getOperand(2).getReg();
4835 
4836   const LLT Src0Ty = MRI.getType(Src0);
4837   const LLT Src1Ty = MRI.getType(Src1);
4838 
4839   const int Src0Size = Src0Ty.getScalarSizeInBits();
4840   const int Src1Size = Src1Ty.getScalarSizeInBits();
4841 
4842   auto SignBitMask = MIRBuilder.buildConstant(
4843     Src0Ty, APInt::getSignMask(Src0Size));
4844 
4845   auto NotSignBitMask = MIRBuilder.buildConstant(
4846     Src0Ty, APInt::getLowBitsSet(Src0Size, Src0Size - 1));
4847 
4848   auto And0 = MIRBuilder.buildAnd(Src0Ty, Src0, NotSignBitMask);
4849   MachineInstr *Or;
4850 
4851   if (Src0Ty == Src1Ty) {
4852     auto And1 = MIRBuilder.buildAnd(Src1Ty, Src1, SignBitMask);
4853     Or = MIRBuilder.buildOr(Dst, And0, And1);
4854   } else if (Src0Size > Src1Size) {
4855     auto ShiftAmt = MIRBuilder.buildConstant(Src0Ty, Src0Size - Src1Size);
4856     auto Zext = MIRBuilder.buildZExt(Src0Ty, Src1);
4857     auto Shift = MIRBuilder.buildShl(Src0Ty, Zext, ShiftAmt);
4858     auto And1 = MIRBuilder.buildAnd(Src0Ty, Shift, SignBitMask);
4859     Or = MIRBuilder.buildOr(Dst, And0, And1);
4860   } else {
4861     auto ShiftAmt = MIRBuilder.buildConstant(Src1Ty, Src1Size - Src0Size);
4862     auto Shift = MIRBuilder.buildLShr(Src1Ty, Src1, ShiftAmt);
4863     auto Trunc = MIRBuilder.buildTrunc(Src0Ty, Shift);
4864     auto And1 = MIRBuilder.buildAnd(Src0Ty, Trunc, SignBitMask);
4865     Or = MIRBuilder.buildOr(Dst, And0, And1);
4866   }
4867 
4868   // Be careful about setting nsz/nnan/ninf on every instruction, since the
4869   // constants are a nan and -0.0, but the final result should preserve
4870   // everything.
4871   if (unsigned Flags = MI.getFlags())
4872     Or->setFlags(Flags);
4873 
4874   MI.eraseFromParent();
4875   return Legalized;
4876 }
4877 
4878 LegalizerHelper::LegalizeResult
4879 LegalizerHelper::lowerFMinNumMaxNum(MachineInstr &MI) {
4880   unsigned NewOp = MI.getOpcode() == TargetOpcode::G_FMINNUM ?
4881     TargetOpcode::G_FMINNUM_IEEE : TargetOpcode::G_FMAXNUM_IEEE;
4882 
4883   Register Dst = MI.getOperand(0).getReg();
4884   Register Src0 = MI.getOperand(1).getReg();
4885   Register Src1 = MI.getOperand(2).getReg();
4886   LLT Ty = MRI.getType(Dst);
4887 
4888   if (!MI.getFlag(MachineInstr::FmNoNans)) {
4889     // Insert canonicalizes if it's possible we need to quiet to get correct
4890     // sNaN behavior.
4891 
4892     // Note this must be done here, and not as an optimization combine in the
4893     // absence of a dedicate quiet-snan instruction as we're using an
4894     // omni-purpose G_FCANONICALIZE.
4895     if (!isKnownNeverSNaN(Src0, MRI))
4896       Src0 = MIRBuilder.buildFCanonicalize(Ty, Src0, MI.getFlags()).getReg(0);
4897 
4898     if (!isKnownNeverSNaN(Src1, MRI))
4899       Src1 = MIRBuilder.buildFCanonicalize(Ty, Src1, MI.getFlags()).getReg(0);
4900   }
4901 
4902   // If there are no nans, it's safe to simply replace this with the non-IEEE
4903   // version.
4904   MIRBuilder.buildInstr(NewOp, {Dst}, {Src0, Src1}, MI.getFlags());
4905   MI.eraseFromParent();
4906   return Legalized;
4907 }
4908 
4909 LegalizerHelper::LegalizeResult LegalizerHelper::lowerFMad(MachineInstr &MI) {
4910   // Expand G_FMAD a, b, c -> G_FADD (G_FMUL a, b), c
4911   Register DstReg = MI.getOperand(0).getReg();
4912   LLT Ty = MRI.getType(DstReg);
4913   unsigned Flags = MI.getFlags();
4914 
4915   auto Mul = MIRBuilder.buildFMul(Ty, MI.getOperand(1), MI.getOperand(2),
4916                                   Flags);
4917   MIRBuilder.buildFAdd(DstReg, Mul, MI.getOperand(3), Flags);
4918   MI.eraseFromParent();
4919   return Legalized;
4920 }
4921 
4922 LegalizerHelper::LegalizeResult
4923 LegalizerHelper::lowerIntrinsicRound(MachineInstr &MI) {
4924   Register DstReg = MI.getOperand(0).getReg();
4925   Register X = MI.getOperand(1).getReg();
4926   const unsigned Flags = MI.getFlags();
4927   const LLT Ty = MRI.getType(DstReg);
4928   const LLT CondTy = Ty.changeElementSize(1);
4929 
4930   // round(x) =>
4931   //  t = trunc(x);
4932   //  d = fabs(x - t);
4933   //  o = copysign(1.0f, x);
4934   //  return t + (d >= 0.5 ? o : 0.0);
4935 
4936   auto T = MIRBuilder.buildIntrinsicTrunc(Ty, X, Flags);
4937 
4938   auto Diff = MIRBuilder.buildFSub(Ty, X, T, Flags);
4939   auto AbsDiff = MIRBuilder.buildFAbs(Ty, Diff, Flags);
4940   auto Zero = MIRBuilder.buildFConstant(Ty, 0.0);
4941   auto One = MIRBuilder.buildFConstant(Ty, 1.0);
4942   auto Half = MIRBuilder.buildFConstant(Ty, 0.5);
4943   auto SignOne = MIRBuilder.buildFCopysign(Ty, One, X);
4944 
4945   auto Cmp = MIRBuilder.buildFCmp(CmpInst::FCMP_OGE, CondTy, AbsDiff, Half,
4946                                   Flags);
4947   auto Sel = MIRBuilder.buildSelect(Ty, Cmp, SignOne, Zero, Flags);
4948 
4949   MIRBuilder.buildFAdd(DstReg, T, Sel, Flags);
4950 
4951   MI.eraseFromParent();
4952   return Legalized;
4953 }
4954 
4955 LegalizerHelper::LegalizeResult
4956 LegalizerHelper::lowerFFloor(MachineInstr &MI) {
4957   Register DstReg = MI.getOperand(0).getReg();
4958   Register SrcReg = MI.getOperand(1).getReg();
4959   unsigned Flags = MI.getFlags();
4960   LLT Ty = MRI.getType(DstReg);
4961   const LLT CondTy = Ty.changeElementSize(1);
4962 
4963   // result = trunc(src);
4964   // if (src < 0.0 && src != result)
4965   //   result += -1.0.
4966 
4967   auto Trunc = MIRBuilder.buildIntrinsicTrunc(Ty, SrcReg, Flags);
4968   auto Zero = MIRBuilder.buildFConstant(Ty, 0.0);
4969 
4970   auto Lt0 = MIRBuilder.buildFCmp(CmpInst::FCMP_OLT, CondTy,
4971                                   SrcReg, Zero, Flags);
4972   auto NeTrunc = MIRBuilder.buildFCmp(CmpInst::FCMP_ONE, CondTy,
4973                                       SrcReg, Trunc, Flags);
4974   auto And = MIRBuilder.buildAnd(CondTy, Lt0, NeTrunc);
4975   auto AddVal = MIRBuilder.buildSITOFP(Ty, And);
4976 
4977   MIRBuilder.buildFAdd(DstReg, Trunc, AddVal, Flags);
4978   MI.eraseFromParent();
4979   return Legalized;
4980 }
4981 
4982 LegalizerHelper::LegalizeResult
4983 LegalizerHelper::lowerMergeValues(MachineInstr &MI) {
4984   const unsigned NumOps = MI.getNumOperands();
4985   Register DstReg = MI.getOperand(0).getReg();
4986   Register Src0Reg = MI.getOperand(1).getReg();
4987   LLT DstTy = MRI.getType(DstReg);
4988   LLT SrcTy = MRI.getType(Src0Reg);
4989   unsigned PartSize = SrcTy.getSizeInBits();
4990 
4991   LLT WideTy = LLT::scalar(DstTy.getSizeInBits());
4992   Register ResultReg = MIRBuilder.buildZExt(WideTy, Src0Reg).getReg(0);
4993 
4994   for (unsigned I = 2; I != NumOps; ++I) {
4995     const unsigned Offset = (I - 1) * PartSize;
4996 
4997     Register SrcReg = MI.getOperand(I).getReg();
4998     auto ZextInput = MIRBuilder.buildZExt(WideTy, SrcReg);
4999 
5000     Register NextResult = I + 1 == NumOps && WideTy == DstTy ? DstReg :
5001       MRI.createGenericVirtualRegister(WideTy);
5002 
5003     auto ShiftAmt = MIRBuilder.buildConstant(WideTy, Offset);
5004     auto Shl = MIRBuilder.buildShl(WideTy, ZextInput, ShiftAmt);
5005     MIRBuilder.buildOr(NextResult, ResultReg, Shl);
5006     ResultReg = NextResult;
5007   }
5008 
5009   if (DstTy.isPointer()) {
5010     if (MIRBuilder.getDataLayout().isNonIntegralAddressSpace(
5011           DstTy.getAddressSpace())) {
5012       LLVM_DEBUG(dbgs() << "Not casting nonintegral address space\n");
5013       return UnableToLegalize;
5014     }
5015 
5016     MIRBuilder.buildIntToPtr(DstReg, ResultReg);
5017   }
5018 
5019   MI.eraseFromParent();
5020   return Legalized;
5021 }
5022 
5023 LegalizerHelper::LegalizeResult
5024 LegalizerHelper::lowerUnmergeValues(MachineInstr &MI) {
5025   const unsigned NumDst = MI.getNumOperands() - 1;
5026   Register SrcReg = MI.getOperand(NumDst).getReg();
5027   Register Dst0Reg = MI.getOperand(0).getReg();
5028   LLT DstTy = MRI.getType(Dst0Reg);
5029   if (DstTy.isPointer())
5030     return UnableToLegalize; // TODO
5031 
5032   SrcReg = coerceToScalar(SrcReg);
5033   if (!SrcReg)
5034     return UnableToLegalize;
5035 
5036   // Expand scalarizing unmerge as bitcast to integer and shift.
5037   LLT IntTy = MRI.getType(SrcReg);
5038 
5039   MIRBuilder.buildTrunc(Dst0Reg, SrcReg);
5040 
5041   const unsigned DstSize = DstTy.getSizeInBits();
5042   unsigned Offset = DstSize;
5043   for (unsigned I = 1; I != NumDst; ++I, Offset += DstSize) {
5044     auto ShiftAmt = MIRBuilder.buildConstant(IntTy, Offset);
5045     auto Shift = MIRBuilder.buildLShr(IntTy, SrcReg, ShiftAmt);
5046     MIRBuilder.buildTrunc(MI.getOperand(I), Shift);
5047   }
5048 
5049   MI.eraseFromParent();
5050   return Legalized;
5051 }
5052 
5053 LegalizerHelper::LegalizeResult
5054 LegalizerHelper::lowerShuffleVector(MachineInstr &MI) {
5055   Register DstReg = MI.getOperand(0).getReg();
5056   Register Src0Reg = MI.getOperand(1).getReg();
5057   Register Src1Reg = MI.getOperand(2).getReg();
5058   LLT Src0Ty = MRI.getType(Src0Reg);
5059   LLT DstTy = MRI.getType(DstReg);
5060   LLT IdxTy = LLT::scalar(32);
5061 
5062   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
5063 
5064   if (DstTy.isScalar()) {
5065     if (Src0Ty.isVector())
5066       return UnableToLegalize;
5067 
5068     // This is just a SELECT.
5069     assert(Mask.size() == 1 && "Expected a single mask element");
5070     Register Val;
5071     if (Mask[0] < 0 || Mask[0] > 1)
5072       Val = MIRBuilder.buildUndef(DstTy).getReg(0);
5073     else
5074       Val = Mask[0] == 0 ? Src0Reg : Src1Reg;
5075     MIRBuilder.buildCopy(DstReg, Val);
5076     MI.eraseFromParent();
5077     return Legalized;
5078   }
5079 
5080   Register Undef;
5081   SmallVector<Register, 32> BuildVec;
5082   LLT EltTy = DstTy.getElementType();
5083 
5084   for (int Idx : Mask) {
5085     if (Idx < 0) {
5086       if (!Undef.isValid())
5087         Undef = MIRBuilder.buildUndef(EltTy).getReg(0);
5088       BuildVec.push_back(Undef);
5089       continue;
5090     }
5091 
5092     if (Src0Ty.isScalar()) {
5093       BuildVec.push_back(Idx == 0 ? Src0Reg : Src1Reg);
5094     } else {
5095       int NumElts = Src0Ty.getNumElements();
5096       Register SrcVec = Idx < NumElts ? Src0Reg : Src1Reg;
5097       int ExtractIdx = Idx < NumElts ? Idx : Idx - NumElts;
5098       auto IdxK = MIRBuilder.buildConstant(IdxTy, ExtractIdx);
5099       auto Extract = MIRBuilder.buildExtractVectorElement(EltTy, SrcVec, IdxK);
5100       BuildVec.push_back(Extract.getReg(0));
5101     }
5102   }
5103 
5104   MIRBuilder.buildBuildVector(DstReg, BuildVec);
5105   MI.eraseFromParent();
5106   return Legalized;
5107 }
5108 
5109 LegalizerHelper::LegalizeResult
5110 LegalizerHelper::lowerDynStackAlloc(MachineInstr &MI) {
5111   const auto &MF = *MI.getMF();
5112   const auto &TFI = *MF.getSubtarget().getFrameLowering();
5113   if (TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp)
5114     return UnableToLegalize;
5115 
5116   Register Dst = MI.getOperand(0).getReg();
5117   Register AllocSize = MI.getOperand(1).getReg();
5118   Align Alignment = assumeAligned(MI.getOperand(2).getImm());
5119 
5120   LLT PtrTy = MRI.getType(Dst);
5121   LLT IntPtrTy = LLT::scalar(PtrTy.getSizeInBits());
5122 
5123   const auto &TLI = *MF.getSubtarget().getTargetLowering();
5124   Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
5125   auto SPTmp = MIRBuilder.buildCopy(PtrTy, SPReg);
5126   SPTmp = MIRBuilder.buildCast(IntPtrTy, SPTmp);
5127 
5128   // Subtract the final alloc from the SP. We use G_PTRTOINT here so we don't
5129   // have to generate an extra instruction to negate the alloc and then use
5130   // G_PTR_ADD to add the negative offset.
5131   auto Alloc = MIRBuilder.buildSub(IntPtrTy, SPTmp, AllocSize);
5132   if (Alignment > Align(1)) {
5133     APInt AlignMask(IntPtrTy.getSizeInBits(), Alignment.value(), true);
5134     AlignMask.negate();
5135     auto AlignCst = MIRBuilder.buildConstant(IntPtrTy, AlignMask);
5136     Alloc = MIRBuilder.buildAnd(IntPtrTy, Alloc, AlignCst);
5137   }
5138 
5139   SPTmp = MIRBuilder.buildCast(PtrTy, Alloc);
5140   MIRBuilder.buildCopy(SPReg, SPTmp);
5141   MIRBuilder.buildCopy(Dst, SPTmp);
5142 
5143   MI.eraseFromParent();
5144   return Legalized;
5145 }
5146 
5147 LegalizerHelper::LegalizeResult
5148 LegalizerHelper::lowerExtract(MachineInstr &MI) {
5149   Register Dst = MI.getOperand(0).getReg();
5150   Register Src = MI.getOperand(1).getReg();
5151   unsigned Offset = MI.getOperand(2).getImm();
5152 
5153   LLT DstTy = MRI.getType(Dst);
5154   LLT SrcTy = MRI.getType(Src);
5155 
5156   if (DstTy.isScalar() &&
5157       (SrcTy.isScalar() ||
5158        (SrcTy.isVector() && DstTy == SrcTy.getElementType()))) {
5159     LLT SrcIntTy = SrcTy;
5160     if (!SrcTy.isScalar()) {
5161       SrcIntTy = LLT::scalar(SrcTy.getSizeInBits());
5162       Src = MIRBuilder.buildBitcast(SrcIntTy, Src).getReg(0);
5163     }
5164 
5165     if (Offset == 0)
5166       MIRBuilder.buildTrunc(Dst, Src);
5167     else {
5168       auto ShiftAmt = MIRBuilder.buildConstant(SrcIntTy, Offset);
5169       auto Shr = MIRBuilder.buildLShr(SrcIntTy, Src, ShiftAmt);
5170       MIRBuilder.buildTrunc(Dst, Shr);
5171     }
5172 
5173     MI.eraseFromParent();
5174     return Legalized;
5175   }
5176 
5177   return UnableToLegalize;
5178 }
5179 
5180 LegalizerHelper::LegalizeResult LegalizerHelper::lowerInsert(MachineInstr &MI) {
5181   Register Dst = MI.getOperand(0).getReg();
5182   Register Src = MI.getOperand(1).getReg();
5183   Register InsertSrc = MI.getOperand(2).getReg();
5184   uint64_t Offset = MI.getOperand(3).getImm();
5185 
5186   LLT DstTy = MRI.getType(Src);
5187   LLT InsertTy = MRI.getType(InsertSrc);
5188 
5189   if (InsertTy.isVector() ||
5190       (DstTy.isVector() && DstTy.getElementType() != InsertTy))
5191     return UnableToLegalize;
5192 
5193   const DataLayout &DL = MIRBuilder.getDataLayout();
5194   if ((DstTy.isPointer() &&
5195        DL.isNonIntegralAddressSpace(DstTy.getAddressSpace())) ||
5196       (InsertTy.isPointer() &&
5197        DL.isNonIntegralAddressSpace(InsertTy.getAddressSpace()))) {
5198     LLVM_DEBUG(dbgs() << "Not casting non-integral address space integer\n");
5199     return UnableToLegalize;
5200   }
5201 
5202   LLT IntDstTy = DstTy;
5203 
5204   if (!DstTy.isScalar()) {
5205     IntDstTy = LLT::scalar(DstTy.getSizeInBits());
5206     Src = MIRBuilder.buildCast(IntDstTy, Src).getReg(0);
5207   }
5208 
5209   if (!InsertTy.isScalar()) {
5210     const LLT IntInsertTy = LLT::scalar(InsertTy.getSizeInBits());
5211     InsertSrc = MIRBuilder.buildPtrToInt(IntInsertTy, InsertSrc).getReg(0);
5212   }
5213 
5214   Register ExtInsSrc = MIRBuilder.buildZExt(IntDstTy, InsertSrc).getReg(0);
5215   if (Offset != 0) {
5216     auto ShiftAmt = MIRBuilder.buildConstant(IntDstTy, Offset);
5217     ExtInsSrc = MIRBuilder.buildShl(IntDstTy, ExtInsSrc, ShiftAmt).getReg(0);
5218   }
5219 
5220   APInt MaskVal = APInt::getBitsSetWithWrap(
5221       DstTy.getSizeInBits(), Offset + InsertTy.getSizeInBits(), Offset);
5222 
5223   auto Mask = MIRBuilder.buildConstant(IntDstTy, MaskVal);
5224   auto MaskedSrc = MIRBuilder.buildAnd(IntDstTy, Src, Mask);
5225   auto Or = MIRBuilder.buildOr(IntDstTy, MaskedSrc, ExtInsSrc);
5226 
5227   MIRBuilder.buildCast(Dst, Or);
5228   MI.eraseFromParent();
5229   return Legalized;
5230 }
5231 
5232 LegalizerHelper::LegalizeResult
5233 LegalizerHelper::lowerSADDO_SSUBO(MachineInstr &MI) {
5234   Register Dst0 = MI.getOperand(0).getReg();
5235   Register Dst1 = MI.getOperand(1).getReg();
5236   Register LHS = MI.getOperand(2).getReg();
5237   Register RHS = MI.getOperand(3).getReg();
5238   const bool IsAdd = MI.getOpcode() == TargetOpcode::G_SADDO;
5239 
5240   LLT Ty = MRI.getType(Dst0);
5241   LLT BoolTy = MRI.getType(Dst1);
5242 
5243   if (IsAdd)
5244     MIRBuilder.buildAdd(Dst0, LHS, RHS);
5245   else
5246     MIRBuilder.buildSub(Dst0, LHS, RHS);
5247 
5248   // TODO: If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
5249 
5250   auto Zero = MIRBuilder.buildConstant(Ty, 0);
5251 
5252   // For an addition, the result should be less than one of the operands (LHS)
5253   // if and only if the other operand (RHS) is negative, otherwise there will
5254   // be overflow.
5255   // For a subtraction, the result should be less than one of the operands
5256   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
5257   // otherwise there will be overflow.
5258   auto ResultLowerThanLHS =
5259       MIRBuilder.buildICmp(CmpInst::ICMP_SLT, BoolTy, Dst0, LHS);
5260   auto ConditionRHS = MIRBuilder.buildICmp(
5261       IsAdd ? CmpInst::ICMP_SLT : CmpInst::ICMP_SGT, BoolTy, RHS, Zero);
5262 
5263   MIRBuilder.buildXor(Dst1, ConditionRHS, ResultLowerThanLHS);
5264   MI.eraseFromParent();
5265   return Legalized;
5266 }
5267 
5268 LegalizerHelper::LegalizeResult
5269 LegalizerHelper::lowerBswap(MachineInstr &MI) {
5270   Register Dst = MI.getOperand(0).getReg();
5271   Register Src = MI.getOperand(1).getReg();
5272   const LLT Ty = MRI.getType(Src);
5273   unsigned SizeInBytes = (Ty.getScalarSizeInBits() + 7) / 8;
5274   unsigned BaseShiftAmt = (SizeInBytes - 1) * 8;
5275 
5276   // Swap most and least significant byte, set remaining bytes in Res to zero.
5277   auto ShiftAmt = MIRBuilder.buildConstant(Ty, BaseShiftAmt);
5278   auto LSByteShiftedLeft = MIRBuilder.buildShl(Ty, Src, ShiftAmt);
5279   auto MSByteShiftedRight = MIRBuilder.buildLShr(Ty, Src, ShiftAmt);
5280   auto Res = MIRBuilder.buildOr(Ty, MSByteShiftedRight, LSByteShiftedLeft);
5281 
5282   // Set i-th high/low byte in Res to i-th low/high byte from Src.
5283   for (unsigned i = 1; i < SizeInBytes / 2; ++i) {
5284     // AND with Mask leaves byte i unchanged and sets remaining bytes to 0.
5285     APInt APMask(SizeInBytes * 8, 0xFF << (i * 8));
5286     auto Mask = MIRBuilder.buildConstant(Ty, APMask);
5287     auto ShiftAmt = MIRBuilder.buildConstant(Ty, BaseShiftAmt - 16 * i);
5288     // Low byte shifted left to place of high byte: (Src & Mask) << ShiftAmt.
5289     auto LoByte = MIRBuilder.buildAnd(Ty, Src, Mask);
5290     auto LoShiftedLeft = MIRBuilder.buildShl(Ty, LoByte, ShiftAmt);
5291     Res = MIRBuilder.buildOr(Ty, Res, LoShiftedLeft);
5292     // High byte shifted right to place of low byte: (Src >> ShiftAmt) & Mask.
5293     auto SrcShiftedRight = MIRBuilder.buildLShr(Ty, Src, ShiftAmt);
5294     auto HiShiftedRight = MIRBuilder.buildAnd(Ty, SrcShiftedRight, Mask);
5295     Res = MIRBuilder.buildOr(Ty, Res, HiShiftedRight);
5296   }
5297   Res.getInstr()->getOperand(0).setReg(Dst);
5298 
5299   MI.eraseFromParent();
5300   return Legalized;
5301 }
5302 
5303 //{ (Src & Mask) >> N } | { (Src << N) & Mask }
5304 static MachineInstrBuilder SwapN(unsigned N, DstOp Dst, MachineIRBuilder &B,
5305                                  MachineInstrBuilder Src, APInt Mask) {
5306   const LLT Ty = Dst.getLLTTy(*B.getMRI());
5307   MachineInstrBuilder C_N = B.buildConstant(Ty, N);
5308   MachineInstrBuilder MaskLoNTo0 = B.buildConstant(Ty, Mask);
5309   auto LHS = B.buildLShr(Ty, B.buildAnd(Ty, Src, MaskLoNTo0), C_N);
5310   auto RHS = B.buildAnd(Ty, B.buildShl(Ty, Src, C_N), MaskLoNTo0);
5311   return B.buildOr(Dst, LHS, RHS);
5312 }
5313 
5314 LegalizerHelper::LegalizeResult
5315 LegalizerHelper::lowerBitreverse(MachineInstr &MI) {
5316   Register Dst = MI.getOperand(0).getReg();
5317   Register Src = MI.getOperand(1).getReg();
5318   const LLT Ty = MRI.getType(Src);
5319   unsigned Size = Ty.getSizeInBits();
5320 
5321   MachineInstrBuilder BSWAP =
5322       MIRBuilder.buildInstr(TargetOpcode::G_BSWAP, {Ty}, {Src});
5323 
5324   // swap high and low 4 bits in 8 bit blocks 7654|3210 -> 3210|7654
5325   //    [(val & 0xF0F0F0F0) >> 4] | [(val & 0x0F0F0F0F) << 4]
5326   // -> [(val & 0xF0F0F0F0) >> 4] | [(val << 4) & 0xF0F0F0F0]
5327   MachineInstrBuilder Swap4 =
5328       SwapN(4, Ty, MIRBuilder, BSWAP, APInt::getSplat(Size, APInt(8, 0xF0)));
5329 
5330   // swap high and low 2 bits in 4 bit blocks 32|10 76|54 -> 10|32 54|76
5331   //    [(val & 0xCCCCCCCC) >> 2] & [(val & 0x33333333) << 2]
5332   // -> [(val & 0xCCCCCCCC) >> 2] & [(val << 2) & 0xCCCCCCCC]
5333   MachineInstrBuilder Swap2 =
5334       SwapN(2, Ty, MIRBuilder, Swap4, APInt::getSplat(Size, APInt(8, 0xCC)));
5335 
5336   // swap high and low 1 bit in 2 bit blocks 1|0 3|2 5|4 7|6 -> 0|1 2|3 4|5 6|7
5337   //    [(val & 0xAAAAAAAA) >> 1] & [(val & 0x55555555) << 1]
5338   // -> [(val & 0xAAAAAAAA) >> 1] & [(val << 1) & 0xAAAAAAAA]
5339   SwapN(1, Dst, MIRBuilder, Swap2, APInt::getSplat(Size, APInt(8, 0xAA)));
5340 
5341   MI.eraseFromParent();
5342   return Legalized;
5343 }
5344 
5345 LegalizerHelper::LegalizeResult
5346 LegalizerHelper::lowerReadWriteRegister(MachineInstr &MI) {
5347   MachineFunction &MF = MIRBuilder.getMF();
5348   const TargetSubtargetInfo &STI = MF.getSubtarget();
5349   const TargetLowering *TLI = STI.getTargetLowering();
5350 
5351   bool IsRead = MI.getOpcode() == TargetOpcode::G_READ_REGISTER;
5352   int NameOpIdx = IsRead ? 1 : 0;
5353   int ValRegIndex = IsRead ? 0 : 1;
5354 
5355   Register ValReg = MI.getOperand(ValRegIndex).getReg();
5356   const LLT Ty = MRI.getType(ValReg);
5357   const MDString *RegStr = cast<MDString>(
5358     cast<MDNode>(MI.getOperand(NameOpIdx).getMetadata())->getOperand(0));
5359 
5360   Register PhysReg = TLI->getRegisterByName(RegStr->getString().data(), Ty, MF);
5361   if (!PhysReg.isValid())
5362     return UnableToLegalize;
5363 
5364   if (IsRead)
5365     MIRBuilder.buildCopy(ValReg, PhysReg);
5366   else
5367     MIRBuilder.buildCopy(PhysReg, ValReg);
5368 
5369   MI.eraseFromParent();
5370   return Legalized;
5371 }
5372