LLVM  12.0.0git
LegalizerHelper.cpp
Go to the documentation of this file.
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 
24 #include "llvm/Support/Debug.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 
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 
86  GISelChangeObserver &Observer,
88  : MIRBuilder(Builder), Observer(Observer), MRI(MF.getRegInfo()),
89  LI(*MF.getSubtarget().getLegalizerInfo()) {
90  MIRBuilder.setChangeObserver(Observer);
91 }
92 
96  : MIRBuilder(B), Observer(Observer), MRI(MF.getRegInfo()), LI(LI) {
97  MIRBuilder.setChangeObserver(Observer);
98 }
101  LLVM_DEBUG(dbgs() << "Legalizing: " << MI);
102 
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)
147  MIRBuilder.buildUnmerge(VRegs, Reg);
148 }
149 
150 bool LegalizerHelper::extractParts(Register Reg, LLT RegTy,
151  LLT MainTy, LLT &LeftoverTy,
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
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,
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 =
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.
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 
492  const CallLowering::ArgInfo &Result,
494  const CallingConv::ID CC) {
495  auto &CLI = *MIRBuilder.getMF().getSubtarget().getCallLowering();
496 
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))
504 
506 }
507 
510  const CallLowering::ArgInfo &Result,
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.
521  Type *OpType) {
522  auto Libcall = getRTLibDesc(MI.getOpcode(), Size);
523 
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 
533  MachineInstr &MI) {
534  assert(MI.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS);
535  auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
536 
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();
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:
568  }
569  const char *Name = TLI.getLibcallName(RTLibcall);
570 
571  MIRBuilder.setInstrAndDebugLoc(MI);
572 
574  Info.CallConv = TLI.getLibcallCallingConv(RTLibcall);
575  Info.Callee = MachineOperand::CreateES(Name);
577  Info.IsTailCall = MI.getOperand(MI.getNumOperands() - 1).getImm() == 1 &&
579 
580  std::copy(Args.begin(), Args.end(), std::back_inserter(Info.OrigArgs));
581  if (!CLI.lowerCall(MIRBuilder, Info))
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 
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 
625  Type *FromType) {
627  return createLibcall(MIRBuilder, Libcall, {MI.getOperand(0).getReg(), ToType},
628  {{MI.getOperand(1).getReg(), FromType}});
629 }
630 
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;
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;
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 
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);
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);
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);
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);
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);
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 
1219  LLT Ty = MRI.getType(Val);
1220  if (Ty.isScalar())
1221  return Val;
1222 
1224  LLT NewTy = LLT::scalar(Ty.getSizeInBits());
1225  if (Ty.isPointer()) {
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 
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 
1248  unsigned OpIdx) {
1249  MachineOperand &MO = MI.getOperand(OpIdx);
1250  auto ExtB = MIRBuilder.buildTrunc(NarrowTy, MO);
1251  MO.setReg(ExtB.getReg(0));
1252 }
1253 
1255  unsigned OpIdx, unsigned TruncOpcode) {
1256  MachineOperand &MO = MI.getOperand(OpIdx);
1257  Register DstExt = MRI.createGenericVirtualRegister(WideTy);
1259  MIRBuilder.buildInstr(TruncOpcode, {MO}, {DstExt});
1260  MO.setReg(DstExt);
1261 }
1262 
1264  unsigned OpIdx, unsigned ExtOpcode) {
1265  MachineOperand &MO = MI.getOperand(OpIdx);
1266  Register DstTrunc = MRI.createGenericVirtualRegister(NarrowTy);
1268  MIRBuilder.buildInstr(ExtOpcode, {MO}, {DstTrunc});
1269  MO.setReg(DstTrunc);
1270 }
1271 
1273  unsigned OpIdx) {
1274  MachineOperand &MO = MI.getOperand(OpIdx);
1275  Register DstExt = MRI.createGenericVirtualRegister(WideTy);
1277  MIRBuilder.buildExtract(MO, DstExt, 0);
1278  MO.setReg(DstExt);
1279 }
1280 
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) {
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);
1320  MIRBuilder.buildBitcast(MO, CastDst);
1321  MO.setReg(CastDst);
1322 }
1323 
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 
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 
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()) {
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 
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.
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 
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 
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 
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 
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);
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);
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);
1973  APFloat Val = SrcMO.getFPImm()->getValueAPF();
1974  bool LosesInfo;
1975  switch (WideTy.getSizeInBits()) {
1976  case 32:
1978  &LosesInfo);
1979  break;
1980  case 64:
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 
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 
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 
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 
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 
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 
2372 
2373  auto HiPart = MIRBuilder.buildInstr(Opcode, {Ty}, {LHS, RHS});
2374  auto Zero = MIRBuilder.buildConstant(Ty, 0);
2375 
2376  // For *signed* multiply, overflow is detected by checking:
2377  // (hi != (lo >> bitwidth-1))
2378  if (Opcode == TargetOpcode::G_SMULH) {
2379  auto ShiftAmt = MIRBuilder.buildConstant(Ty, Ty.getSizeInBits() - 1);
2380  auto Shifted = MIRBuilder.buildAShr(Ty, Res, ShiftAmt);
2381  MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Shifted);
2382  } else {
2383  MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Zero);
2384  }
2385  return Legalized;
2386  }
2387  case TargetOpcode::G_FNEG: {
2388  // TODO: Handle vector types once we are able to
2389  // represent them.
2390  if (Ty.isVector())
2391  return UnableToLegalize;
2392  Register Res = MI.getOperand(0).getReg();
2394  Type *ZeroTy = getFloatTypeForLLT(Ctx, Ty);
2395  if (!ZeroTy)
2396  return UnableToLegalize;
2397  ConstantFP &ZeroForNegation =
2398  *cast<ConstantFP>(ConstantFP::getZeroValueForNegation(ZeroTy));
2399  auto Zero = MIRBuilder.buildFConstant(Ty, ZeroForNegation);
2400  Register SubByReg = MI.getOperand(1).getReg();
2401  Register ZeroReg = Zero.getReg(0);
2402  MIRBuilder.buildFSub(Res, ZeroReg, SubByReg, MI.getFlags());
2403  MI.eraseFromParent();
2404  return Legalized;
2405  }
2406  case TargetOpcode::G_FSUB: {
2407  // Lower (G_FSUB LHS, RHS) to (G_FADD LHS, (G_FNEG RHS)).
2408  // First, check if G_FNEG is marked as Lower. If so, we may
2409  // end up with an infinite loop as G_FSUB is used to legalize G_FNEG.
2410  if (LI.getAction({G_FNEG, {Ty}}).Action == Lower)
2411  return UnableToLegalize;
2412  Register Res = MI.getOperand(0).getReg();
2413  Register LHS = MI.getOperand(1).getReg();
2414  Register RHS = MI.getOperand(2).getReg();
2415  Register Neg = MRI.createGenericVirtualRegister(Ty);
2416  MIRBuilder.buildFNeg(Neg, RHS);
2417  MIRBuilder.buildFAdd(Res, LHS, Neg, MI.getFlags());
2418  MI.eraseFromParent();
2419  return Legalized;
2420  }
2421  case TargetOpcode::G_FMAD:
2422  return lowerFMad(MI);
2423  case TargetOpcode::G_FFLOOR:
2424  return lowerFFloor(MI);
2425  case TargetOpcode::G_INTRINSIC_ROUND:
2426  return lowerIntrinsicRound(MI);
2427  case TargetOpcode::G_ATOMIC_CMPXCHG_WITH_SUCCESS: {
2428  Register OldValRes = MI.getOperand(0).getReg();
2429  Register SuccessRes = MI.getOperand(1).getReg();
2430  Register Addr = MI.getOperand(2).getReg();
2431  Register CmpVal = MI.getOperand(3).getReg();
2432  Register NewVal = MI.getOperand(4).getReg();
2433  MIRBuilder.buildAtomicCmpXchg(OldValRes, Addr, CmpVal, NewVal,
2434  **MI.memoperands_begin());
2435  MIRBuilder.buildICmp(CmpInst::ICMP_EQ, SuccessRes, OldValRes, CmpVal);
2436  MI.eraseFromParent();
2437  return Legalized;
2438  }
2439  case TargetOpcode::G_LOAD:
2440  case TargetOpcode::G_SEXTLOAD:
2441  case TargetOpcode::G_ZEXTLOAD: {
2442  // Lower to a memory-width G_LOAD and a G_SEXT/G_ZEXT/G_ANYEXT
2443  Register DstReg = MI.getOperand(0).getReg();
2444  Register PtrReg = MI.getOperand(1).getReg();
2445  LLT DstTy = MRI.getType(DstReg);
2446  auto &MMO = **MI.memoperands_begin();
2447 
2448  if (DstTy.getSizeInBits() == MMO.getSizeInBits()) {
2449  if (MI.getOpcode() == TargetOpcode::G_LOAD) {
2450  // This load needs splitting into power of 2 sized loads.
2451  if (DstTy.isVector())
2452  return UnableToLegalize;
2453  if (isPowerOf2_32(DstTy.getSizeInBits()))
2454  return UnableToLegalize; // Don't know what we're being asked to do.
2455 
2456  // Our strategy here is to generate anyextending loads for the smaller
2457  // types up to next power-2 result type, and then combine the two larger
2458  // result values together, before truncating back down to the non-pow-2
2459  // type.
2460  // E.g. v1 = i24 load =>
2461  // v2 = i32 zextload (2 byte)
2462  // v3 = i32 load (1 byte)
2463  // v4 = i32 shl v3, 16
2464  // v5 = i32 or v4, v2
2465  // v1 = i24 trunc v5
2466  // By doing this we generate the correct truncate which should get
2467  // combined away as an artifact with a matching extend.
2468  uint64_t LargeSplitSize = PowerOf2Floor(DstTy.getSizeInBits());
2469  uint64_t SmallSplitSize = DstTy.getSizeInBits() - LargeSplitSize;
2470 
2472  MachineMemOperand *LargeMMO =
2473  MF.getMachineMemOperand(&MMO, 0, LargeSplitSize / 8);
2474  MachineMemOperand *SmallMMO = MF.getMachineMemOperand(
2475  &MMO, LargeSplitSize / 8, SmallSplitSize / 8);
2476 
2477  LLT PtrTy = MRI.getType(PtrReg);
2478  unsigned AnyExtSize = NextPowerOf2(DstTy.getSizeInBits());
2479  LLT AnyExtTy = LLT::scalar(AnyExtSize);
2480  Register LargeLdReg = MRI.createGenericVirtualRegister(AnyExtTy);
2481  Register SmallLdReg = MRI.createGenericVirtualRegister(AnyExtTy);
2482  auto LargeLoad = MIRBuilder.buildLoadInstr(
2483  TargetOpcode::G_ZEXTLOAD, LargeLdReg, PtrReg, *LargeMMO);
2484 
2485  auto OffsetCst = MIRBuilder.buildConstant(
2486  LLT::scalar(PtrTy.getSizeInBits()), LargeSplitSize / 8);
2487  Register PtrAddReg = MRI.createGenericVirtualRegister(PtrTy);
2488  auto SmallPtr =
2489  MIRBuilder.buildPtrAdd(PtrAddReg, PtrReg, OffsetCst.getReg(0));
2490  auto SmallLoad = MIRBuilder.buildLoad(SmallLdReg, SmallPtr.getReg(0),
2491  *SmallMMO);
2492 
2493  auto ShiftAmt = MIRBuilder.buildConstant(AnyExtTy, LargeSplitSize);
2494  auto Shift = MIRBuilder.buildShl(AnyExtTy, SmallLoad, ShiftAmt);
2495  auto Or = MIRBuilder.buildOr(AnyExtTy, Shift, LargeLoad);
2496  MIRBuilder.buildTrunc(DstReg, {Or.getReg(0)});
2497  MI.eraseFromParent();
2498  return Legalized;
2499  }
2500  MIRBuilder.buildLoad(DstReg, PtrReg, MMO);
2501  MI.eraseFromParent();
2502  return Legalized;
2503  }
2504 
2505  if (DstTy.isScalar()) {
2506  Register TmpReg =
2507  MRI.createGenericVirtualRegister(LLT::scalar(MMO.getSizeInBits()));
2508  MIRBuilder.buildLoad(TmpReg, PtrReg, MMO);
2509  switch (MI.getOpcode()) {
2510  default:
2511  llvm_unreachable("Unexpected opcode");
2512  case TargetOpcode::G_LOAD:
2513  MIRBuilder.buildExtOrTrunc(TargetOpcode::G_ANYEXT, DstReg, TmpReg);
2514  break;
2515  case TargetOpcode::G_SEXTLOAD:
2516  MIRBuilder.buildSExt(DstReg, TmpReg);
2517  break;
2518  case TargetOpcode::G_ZEXTLOAD:
2519  MIRBuilder.buildZExt(DstReg, TmpReg);
2520  break;
2521  }
2522  MI.eraseFromParent();
2523  return Legalized;
2524  }
2525 
2526  return UnableToLegalize;
2527  }
2528  case TargetOpcode::G_STORE: {
2529  // Lower a non-power of 2 store into multiple pow-2 stores.
2530  // E.g. split an i24 store into an i16 store + i8 store.
2531  // We do this by first extending the stored value to the next largest power
2532  // of 2 type, and then using truncating stores to store the components.
2533  // By doing this, likewise with G_LOAD, generate an extend that can be
2534  // artifact-combined away instead of leaving behind extracts.
2535  Register SrcReg = MI.getOperand(0).getReg();
2536  Register PtrReg = MI.getOperand(1).getReg();
2537  LLT SrcTy = MRI.getType(SrcReg);
2538  MachineMemOperand &MMO = **MI.memoperands_begin();
2539  if (SrcTy.getSizeInBits() != MMO.getSizeInBits())
2540  return UnableToLegalize;
2541  if (SrcTy.isVector())
2542  return UnableToLegalize;
2543  if (isPowerOf2_32(SrcTy.getSizeInBits()))
2544  return UnableToLegalize; // Don't know what we're being asked to do.
2545 
2546  // Extend to the next pow-2.
2547  const LLT ExtendTy = LLT::scalar(NextPowerOf2(SrcTy.getSizeInBits()));
2548  auto ExtVal = MIRBuilder.buildAnyExt(ExtendTy, SrcReg);
2549 
2550  // Obtain the smaller value by shifting away the larger value.
2551  uint64_t LargeSplitSize = PowerOf2Floor(SrcTy.getSizeInBits());
2552  uint64_t SmallSplitSize = SrcTy.getSizeInBits() - LargeSplitSize;
2553  auto ShiftAmt = MIRBuilder.buildConstant(ExtendTy, LargeSplitSize);
2554  auto SmallVal = MIRBuilder.buildLShr(ExtendTy, ExtVal, ShiftAmt);
2555 
2556  // Generate the PtrAdd and truncating stores.
2557  LLT PtrTy = MRI.getType(PtrReg);
2558  auto OffsetCst = MIRBuilder.buildConstant(
2559  LLT::scalar(PtrTy.getSizeInBits()), LargeSplitSize / 8);
2560  Register PtrAddReg = MRI.createGenericVirtualRegister(PtrTy);
2561  auto SmallPtr =
2562  MIRBuilder.buildPtrAdd(PtrAddReg, PtrReg, OffsetCst.getReg(0));
2563 
2565  MachineMemOperand *LargeMMO =
2566  MF.getMachineMemOperand(&MMO, 0, LargeSplitSize / 8);
2567  MachineMemOperand *SmallMMO =
2568  MF.getMachineMemOperand(&MMO, LargeSplitSize / 8, SmallSplitSize / 8);
2569  MIRBuilder.buildStore(ExtVal.getReg(0), PtrReg, *LargeMMO);
2570  MIRBuilder.buildStore(SmallVal.getReg(0), SmallPtr.getReg(0), *SmallMMO);
2571  MI.eraseFromParent();
2572  return Legalized;
2573  }
2574  case TargetOpcode::G_CTLZ_ZERO_UNDEF:
2575  case TargetOpcode::G_CTTZ_ZERO_UNDEF:
2576  case TargetOpcode::G_CTLZ:
2577  case TargetOpcode::G_CTTZ:
2578  case TargetOpcode::G_CTPOP:
2579  return lowerBitCount(MI, TypeIdx, Ty);
2580  case G_UADDO: {
2581  Register Res = MI.getOperand(0).getReg();
2582  Register CarryOut = MI.getOperand(1).getReg();
2583  Register LHS = MI.getOperand(2).getReg();
2584  Register RHS = MI.getOperand(3).getReg();
2585 
2586  MIRBuilder.buildAdd(Res, LHS, RHS);
2587  MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, RHS);
2588 
2589  MI.eraseFromParent();
2590  return Legalized;
2591  }
2592  case G_UADDE: {
2593  Register Res = MI.getOperand(0).getReg();
2594  Register CarryOut = MI.getOperand(1).getReg();
2595  Register LHS = MI.getOperand(2).getReg();
2596  Register RHS = MI.getOperand(3).getReg();
2597  Register CarryIn = MI.getOperand(4).getReg();
2598  LLT Ty = MRI.getType(Res);
2599 
2600  auto TmpRes = MIRBuilder.buildAdd(Ty, LHS, RHS);
2601  auto ZExtCarryIn = MIRBuilder.buildZExt(Ty, CarryIn);
2602  MIRBuilder.buildAdd(Res, TmpRes, ZExtCarryIn);
2603  MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, LHS);
2604 
2605  MI.eraseFromParent();
2606  return Legalized;
2607  }
2608  case G_USUBO: {
2609  Register Res = MI.getOperand(0).getReg();
2610  Register BorrowOut = MI.getOperand(1).getReg();
2611  Register LHS = MI.getOperand(2).getReg();
2612  Register RHS = MI.getOperand(3).getReg();
2613 
2614  MIRBuilder.buildSub(Res, LHS, RHS);
2615  MIRBuilder.buildICmp(CmpInst::ICMP_ULT, BorrowOut, LHS, RHS);
2616 
2617  MI.eraseFromParent();
2618  return Legalized;
2619  }
2620  case G_USUBE: {
2621  Register Res = MI.getOperand(0).getReg();
2622  Register BorrowOut = MI.getOperand(1).getReg();
2623  Register LHS = MI.getOperand(2).getReg();
2624  Register RHS = MI.getOperand(3).getReg();
2625  Register BorrowIn = MI.getOperand(4).getReg();
2626  const LLT CondTy = MRI.getType(BorrowOut);
2627  const LLT Ty = MRI.getType(Res);
2628 
2629  auto TmpRes = MIRBuilder.buildSub(Ty, LHS, RHS);
2630  auto ZExtBorrowIn = MIRBuilder.buildZExt(Ty, BorrowIn);
2631  MIRBuilder.buildSub(Res, TmpRes, ZExtBorrowIn);
2632 
2633  auto LHS_EQ_RHS = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, CondTy, LHS, RHS);
2634  auto LHS_ULT_RHS = MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CondTy, LHS, RHS);
2635  MIRBuilder.buildSelect(BorrowOut, LHS_EQ_RHS, BorrowIn, LHS_ULT_RHS);
2636 
2637  MI.eraseFromParent();
2638  return Legalized;
2639  }
2640  case G_UITOFP:
2641  return lowerUITOFP(MI, TypeIdx, Ty);
2642  case G_SITOFP:
2643  return lowerSITOFP(MI, TypeIdx, Ty);
2644  case G_FPTOUI:
2645  return lowerFPTOUI(MI, TypeIdx, Ty);
2646  case G_FPTOSI:
2647  return lowerFPTOSI(MI);
2648  case G_FPTRUNC:
2649  return lowerFPTRUNC(MI, TypeIdx, Ty);
2650  case G_SMIN:
2651  case G_SMAX:
2652  case G_UMIN:
2653  case G_UMAX:
2654  return lowerMinMax(MI, TypeIdx, Ty);
2655  case G_FCOPYSIGN:
2656  return lowerFCopySign(MI, TypeIdx, Ty);
2657  case G_FMINNUM:
2658  case G_FMAXNUM:
2659  return lowerFMinNumMaxNum(MI);
2660  case G_MERGE_VALUES:
2661  return lowerMergeValues(MI);
2662  case G_UNMERGE_VALUES:
2663  return lowerUnmergeValues(MI);
2664  case TargetOpcode::G_SEXT_INREG: {
2665  assert(MI.getOperand(2).isImm() && "Expected immediate");
2666  int64_t SizeInBits = MI.getOperand(2).getImm();
2667 
2668  Register DstReg = MI.getOperand(0).getReg();
2669  Register SrcReg = MI.getOperand(1).getReg();
2670  LLT DstTy = MRI.getType(DstReg);
2671  Register TmpRes = MRI.createGenericVirtualRegister(DstTy);
2672 
2673  auto MIBSz = MIRBuilder.buildConstant(DstTy, DstTy.getScalarSizeInBits() - SizeInBits);
2674  MIRBuilder.buildShl(TmpRes, SrcReg, MIBSz->getOperand(0));
2675  MIRBuilder.buildAShr(DstReg, TmpRes, MIBSz->getOperand(0));
2676  MI.eraseFromParent();
2677  return Legalized;
2678  }
2679  case G_SHUFFLE_VECTOR:
2680  return lowerShuffleVector(MI);
2681  case G_DYN_STACKALLOC:
2682  return lowerDynStackAlloc(MI);
2683  case G_EXTRACT:
2684  return lowerExtract(MI);
2685  case G_INSERT:
2686  return lowerInsert(MI);
2687  case G_BSWAP:
2688  return lowerBswap(MI);
2689  case G_BITREVERSE:
2690  return lowerBitreverse(MI);
2691  case G_READ_REGISTER:
2692  case G_WRITE_REGISTER:
2693  return lowerReadWriteRegister(MI);
2694  }
2695 }
2696 
2698  MachineInstr &MI, unsigned TypeIdx, LLT NarrowTy) {
2699  SmallVector<Register, 2> DstRegs;
2700 
2701  unsigned NarrowSize = NarrowTy.getSizeInBits();
2702  Register DstReg = MI.getOperand(0).getReg();
2703  unsigned Size = MRI.getType(DstReg).getSizeInBits();
2704  int NumParts = Size / NarrowSize;
2705  // FIXME: Don't know how to handle the situation where the small vectors
2706  // aren't all the same size yet.
2707  if (Size % NarrowSize != 0)
2708  return UnableToLegalize;
2709 
2710  for (int i = 0; i < NumParts; ++i) {
2711  Register TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
2712  MIRBuilder.buildUndef(TmpReg);
2713  DstRegs.push_back(TmpReg);
2714  }
2715 
2716  if (NarrowTy.isVector())
2717  MIRBuilder.buildConcatVectors(DstReg, DstRegs);
2718  else
2719  MIRBuilder.buildBuildVector(DstReg, DstRegs);
2720 
2721  MI.eraseFromParent();
2722  return Legalized;
2723 }
2724 
2725 // Handle splitting vector operations which need to have the same number of
2726 // elements in each type index, but each type index may have a different element
2727 // type.
2728 //
2729 // e.g. <4 x s64> = G_SHL <4 x s64>, <4 x s32> ->
2730 // <2 x s64> = G_SHL <2 x s64>, <2 x s32>
2731 // <2 x s64> = G_SHL <2 x s64>, <2 x s32>
2732 //
2733 // Also handles some irregular breakdown cases, e.g.
2734 // e.g. <3 x s64> = G_SHL <3 x s64>, <3 x s32> ->
2735 // <2 x s64> = G_SHL <2 x s64>, <2 x s32>
2736 // s64 = G_SHL s64, s32
2739  MachineInstr &MI, unsigned TypeIdx, LLT NarrowTyArg) {
2740  if (TypeIdx != 0)
2741  return UnableToLegalize;
2742 
2743  const LLT NarrowTy0 = NarrowTyArg;
2744  const unsigned NewNumElts =
2745  NarrowTy0.isVector() ? NarrowTy0.getNumElements() : 1;
2746 
2747  const Register DstReg = MI.getOperand(0).getReg();
2748  LLT DstTy = MRI.getType(DstReg);
2749  LLT LeftoverTy0;
2750 
2751  // All of the operands need to have the same number of elements, so if we can
2752  // determine a type breakdown for the result type, we can for all of the
2753  // source types.
2754  int NumParts = getNarrowTypeBreakDown(DstTy, NarrowTy0, LeftoverTy0).first;
2755  if (NumParts < 0)
2756  return UnableToLegalize;
2757 
2759 
2760  SmallVector<Register, 4> DstRegs, LeftoverDstRegs;
2761  SmallVector<Register, 4> PartRegs, LeftoverRegs;
2762 
2763  for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) {
2764  Register SrcReg = MI.getOperand(I).getReg();
2765  LLT SrcTyI = MRI.getType(SrcReg);
2766  LLT NarrowTyI = LLT::scalarOrVector(NewNumElts, SrcTyI.getScalarType());
2767  LLT LeftoverTyI;
2768 
2769  // Split this operand into the requested typed registers, and any leftover
2770  // required to reproduce the original type.
2771  if (!extractParts(SrcReg, SrcTyI, NarrowTyI, LeftoverTyI, PartRegs,
2772  LeftoverRegs))
2773  return UnableToLegalize;
2774 
2775  if (I == 1) {
2776  // For the first operand, create an instruction for each part and setup
2777  // the result.
2778  for (Register PartReg : PartRegs) {
2779  Register PartDstReg = MRI.createGenericVirtualRegister(NarrowTy0);
2781  .addDef(PartDstReg)
2782  .addUse(PartReg));
2783  DstRegs.push_back(PartDstReg);
2784  }
2785 
2786  for (Register LeftoverReg : LeftoverRegs) {
2787  Register PartDstReg = MRI.createGenericVirtualRegister(LeftoverTy0);
2789  .addDef(PartDstReg)
2790  .addUse(LeftoverReg));
2791  LeftoverDstRegs.push_back(PartDstReg);
2792  }
2793  } else {
2794  assert(NewInsts.size() == PartRegs.size() + LeftoverRegs.size());
2795 
2796  // Add the newly created operand splits to the existing instructions. The
2797  // odd-sized pieces are ordered after the requested NarrowTyArg sized
2798  // pieces.
2799  unsigned InstCount = 0;
2800  for (unsigned J = 0, JE = PartRegs.size(); J != JE; ++J)
2801  NewInsts[InstCount++].addUse(PartRegs[J]);
2802  for (unsigned J = 0, JE = LeftoverRegs.size(); J != JE; ++J)
2803  NewInsts[InstCount++].addUse(LeftoverRegs[J]);
2804  }
2805 
2806  PartRegs.clear();
2807  LeftoverRegs.clear();
2808  }
2809 
2810  // Insert the newly built operations and rebuild the result register.
2811  for (auto &MIB : NewInsts)
2812  MIRBuilder.insertInstr(MIB);
2813 
2814  insertParts(DstReg, DstTy, NarrowTy0, DstRegs, LeftoverTy0, LeftoverDstRegs);
2815 
2816  MI.eraseFromParent();
2817  return Legalized;
2818 }
2819 
2822  LLT NarrowTy) {
2823  if (TypeIdx != 0)
2824  return UnableToLegalize;
2825 
2826  Register DstReg = MI.getOperand(0).getReg();
2827  Register SrcReg = MI.getOperand(1).getReg();
2828  LLT DstTy = MRI.getType(DstReg);
2829  LLT SrcTy = MRI.getType(SrcReg);
2830 
2831  LLT NarrowTy0 = NarrowTy;
2832  LLT NarrowTy1;
2833  unsigned NumParts;
2834 
2835  if (NarrowTy.isVector()) {
2836  // Uneven breakdown not handled.
2837  NumParts = DstTy.getNumElements() / NarrowTy.getNumElements();
2838  if (NumParts * NarrowTy.getNumElements() != DstTy.getNumElements())
2839  return UnableToLegalize;
2840 
2841  NarrowTy1 = LLT::vector(NumParts, SrcTy.getElementType().getSizeInBits());
2842  } else {
2843  NumParts = DstTy.getNumElements();
2844  NarrowTy1 = SrcTy.getElementType();
2845  }
2846 
2847  SmallVector<Register, 4> SrcRegs, DstRegs;
2848  extractParts(SrcReg, NarrowTy1, NumParts, SrcRegs);
2849 
2850  for (unsigned I = 0; I < NumParts; ++I) {
2851  Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
2852  MachineInstr *NewInst =
2853  MIRBuilder.buildInstr(MI.getOpcode(), {DstReg}, {SrcRegs[I]});
2854 
2855  NewInst->setFlags(MI.getFlags());
2856  DstRegs.push_back(DstReg);
2857  }
2858 
2859  if (NarrowTy.isVector())
2860  MIRBuilder.buildConcatVectors(DstReg, DstRegs);
2861  else
2862  MIRBuilder.buildBuildVector(DstReg, DstRegs);
2863 
2864  MI.eraseFromParent();
2865  return Legalized;
2866 }
2867 
2870  LLT NarrowTy) {
2871  Register DstReg = MI.getOperand(0).getReg();
2872  Register Src0Reg = MI.getOperand(2).getReg();
2873  LLT DstTy = MRI.getType(DstReg);
2874  LLT SrcTy = MRI.getType(Src0Reg);
2875 
2876  unsigned NumParts;
2877  LLT NarrowTy0, NarrowTy1;
2878 
2879  if (TypeIdx == 0) {
2880  unsigned NewElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
2881  unsigned OldElts = DstTy.getNumElements();
2882 
2883  NarrowTy0 = NarrowTy;
2884  NumParts = NarrowTy.isVector() ? (OldElts / NewElts) : DstTy.getNumElements();
2885  NarrowTy1 = NarrowTy.isVector() ?
2886  LLT::vector(NarrowTy.getNumElements(), SrcTy.getScalarSizeInBits()) :
2887  SrcTy.getElementType();
2888 
2889  } else {
2890  unsigned NewElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
2891  unsigned OldElts = SrcTy.getNumElements();
2892 
2893  NumParts = NarrowTy.isVector() ? (OldElts / NewElts) :
2894  NarrowTy.getNumElements();
2895  NarrowTy0 = LLT::vector(NarrowTy.getNumElements(),
2896  DstTy.getScalarSizeInBits());
2897  NarrowTy1 = NarrowTy;
2898  }
2899 
2900  // FIXME: Don't know how to handle the situation where the small vectors
2901  // aren't all the same size yet.
2902  if (NarrowTy1.isVector() &&
2903  NarrowTy1.getNumElements() * NumParts != DstTy.getNumElements())
2904  return UnableToLegalize;
2905 
2906  CmpInst::Predicate Pred
2907  = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
2908 
2909  SmallVector<Register, 2> Src1Regs, Src2Regs, DstRegs;
2910  extractParts(MI.getOperand(2).getReg(), NarrowTy1, NumParts, Src1Regs);
2911  extractParts(MI.getOperand(3).getReg(), NarrowTy1, NumParts, Src2Regs);
2912 
2913  for (unsigned I = 0; I < NumParts; ++I) {
2914  Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
2915  DstRegs.push_back(DstReg);
2916 
2917  if (MI.getOpcode() == TargetOpcode::G_ICMP)
2918  MIRBuilder.buildICmp(Pred, DstReg, Src1Regs[I], Src2Regs[I]);
2919  else {
2920  MachineInstr *NewCmp
2921  = MIRBuilder.buildFCmp(Pred, DstReg, Src1Regs[I], Src2Regs[I]);
2922  NewCmp->setFlags(MI.getFlags());
2923  }
2924  }
2925 
2926  if (NarrowTy1.isVector())
2927  MIRBuilder.buildConcatVectors(DstReg, DstRegs);
2928  else
2929  MIRBuilder.buildBuildVector(DstReg, DstRegs);
2930 
2931  MI.eraseFromParent();
2932  return Legalized;
2933 }
2934 
2937  LLT NarrowTy) {
2938  Register DstReg = MI.getOperand(0).getReg();
2939  Register CondReg = MI.getOperand(1).getReg();
2940 
2941  unsigned NumParts = 0;
2942  LLT NarrowTy0, NarrowTy1;
2943 
2944  LLT DstTy = MRI.getType(DstReg);
2945  LLT CondTy = MRI.getType(CondReg);
2946  unsigned Size = DstTy.getSizeInBits();
2947 
2948  assert(TypeIdx == 0 || CondTy.isVector());
2949 
2950  if (TypeIdx == 0) {
2951  NarrowTy0 = NarrowTy;
2952  NarrowTy1 = CondTy;
2953 
2954  unsigned NarrowSize = NarrowTy0.getSizeInBits();
2955  // FIXME: Don't know how to handle the situation where the small vectors
2956  // aren't all the same size yet.
2957  if (Size % NarrowSize != 0)
2958  return UnableToLegalize;
2959 
2960  NumParts = Size / NarrowSize;
2961 
2962  // Need to break down the condition type
2963  if (CondTy.isVector()) {
2964  if (CondTy.getNumElements() == NumParts)
2965  NarrowTy1 = CondTy.getElementType();
2966  else
2967  NarrowTy1 = LLT::vector(CondTy.getNumElements() / NumParts,
2968  CondTy.getScalarSizeInBits());
2969  }
2970  } else {
2971  NumParts = CondTy.getNumElements();
2972  if (NarrowTy.isVector()) {
2973  // TODO: Handle uneven breakdown.
2974  if (NumParts * NarrowTy.getNumElements() != CondTy.getNumElements())
2975  return UnableToLegalize;
2976 
2977  return UnableToLegalize;
2978  } else {
2979  NarrowTy0 = DstTy.getElementType();
2980  NarrowTy1 = NarrowTy;
2981  }
2982  }
2983 
2984  SmallVector<Register, 2> DstRegs, Src0Regs, Src1Regs, Src2Regs;
2985  if (CondTy.isVector())
2986  extractParts(MI.getOperand(1).getReg(), NarrowTy1, NumParts, Src0Regs);
2987 
2988  extractParts(MI.getOperand(2).getReg(), NarrowTy0, NumParts, Src1Regs);
2989  extractParts(MI.getOperand(3).getReg(), NarrowTy0, NumParts, Src2Regs);
2990 
2991  for (unsigned i = 0; i < NumParts; ++i) {
2992  Register DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
2993  MIRBuilder.buildSelect(DstReg, CondTy.isVector() ? Src0Regs[i] : CondReg,
2994  Src1Regs[i], Src2Regs[i]);
2995  DstRegs.push_back(DstReg);
2996  }
2997 
2998  if (NarrowTy0.isVector())
2999  MIRBuilder.buildConcatVectors(DstReg, DstRegs);
3000  else
3001  MIRBuilder.buildBuildVector(DstReg, DstRegs);
3002 
3003  MI.eraseFromParent();
3004  return Legalized;
3005 }
3006 
3009  LLT NarrowTy) {
3010  const Register DstReg = MI.getOperand(0).getReg();
3011  LLT PhiTy = MRI.getType(DstReg);
3012  LLT LeftoverTy;
3013 
3014  // All of the operands need to have the same number of elements, so if we can
3015  // determine a type breakdown for the result type, we can for all of the
3016  // source types.
3017  int NumParts, NumLeftover;
3018  std::tie(NumParts, NumLeftover)
3019  = getNarrowTypeBreakDown(PhiTy, NarrowTy, LeftoverTy);
3020  if (NumParts < 0)
3021  return UnableToLegalize;
3022 
3023  SmallVector<Register, 4> DstRegs, LeftoverDstRegs;
3025 
3026  const int TotalNumParts = NumParts + NumLeftover;
3027 
3028  // Insert the new phis in the result block first.
3029  for (int I = 0; I != TotalNumParts; ++I) {
3030  LLT Ty = I < NumParts ? NarrowTy : LeftoverTy;
3031  Register PartDstReg = MRI.createGenericVirtualRegister(Ty);
3032  NewInsts.push_back(MIRBuilder.buildInstr(TargetOpcode::G_PHI)
3033  .addDef(PartDstReg));
3034  if (I < NumParts)
3035  DstRegs.push_back(PartDstReg);
3036  else
3037  LeftoverDstRegs.push_back(PartDstReg);
3038  }
3039 
3041  MIRBuilder.setInsertPt(*MBB, MBB->getFirstNonPHI());
3042  insertParts(DstReg, PhiTy, NarrowTy, DstRegs, LeftoverTy, LeftoverDstRegs);
3043 
3044  SmallVector<Register, 4> PartRegs, LeftoverRegs;
3045 
3046  // Insert code to extract the incoming values in each predecessor block.
3047  for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
3048  PartRegs.clear();
3049  LeftoverRegs.clear();
3050 
3051  Register SrcReg = MI.getOperand(I).getReg();
3052  MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
3053  MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
3054 
3055  LLT Unused;
3056  if (!extractParts(SrcReg, PhiTy, NarrowTy, Unused, PartRegs,
3057  LeftoverRegs))
3058  return UnableToLegalize;
3059 
3060  // Add the newly created operand splits to the existing instructions. The
3061  // odd-sized pieces are ordered after the requested NarrowTyArg sized
3062  // pieces.
3063  for (int J = 0; J != TotalNumParts; ++J) {
3064  MachineInstrBuilder MIB = NewInsts[J];
3065  MIB.addUse(J < NumParts ? PartRegs[J] : LeftoverRegs[J - NumParts]);
3066  MIB.addMBB(&OpMBB);
3067  }
3068  }
3069 
3070  MI.eraseFromParent();
3071  return Legalized;
3072 }
3073 
3076  unsigned TypeIdx,
3077  LLT NarrowTy) {
3078  if (TypeIdx != 1)
3079  return UnableToLegalize;
3080 
3081  const int NumDst = MI.getNumOperands() - 1;
3082  const Register SrcReg = MI.getOperand(NumDst).getReg();
3083  LLT SrcTy = MRI.getType(SrcReg);
3084 
3085  LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
3086 
3087  // TODO: Create sequence of extracts.
3088  if (DstTy == NarrowTy)
3089  return UnableToLegalize;
3090 
3091  LLT GCDTy = getGCDType(SrcTy, NarrowTy);
3092  if (DstTy == GCDTy) {
3093  // This would just be a copy of the same unmerge.
3094  // TODO: Create extracts, pad with undef and create intermediate merges.
3095  return UnableToLegalize;
3096  }
3097 
3098  auto Unmerge = MIRBuilder.buildUnmerge(GCDTy, SrcReg);
3099  const int NumUnmerge = Unmerge->getNumOperands() - 1;
3100  const int PartsPerUnmerge = NumDst / NumUnmerge;
3101 
3102  for (int I = 0; I != NumUnmerge; ++I) {
3103  auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
3104 
3105  for (int J = 0; J != PartsPerUnmerge; ++J)
3106  MIB.addDef(MI.getOperand(I * PartsPerUnmerge + J).getReg());
3107  MIB.addUse(Unmerge.getReg(I));
3108  }
3109 
3110  MI.eraseFromParent();
3111  return Legalized;
3112 }
3113 
3116  unsigned TypeIdx,
3117  LLT NarrowTy) {
3118  assert(TypeIdx == 0 && "not a vector type index");
3119  Register DstReg = MI.getOperand(0).getReg();
3120  LLT DstTy = MRI.getType(DstReg);
3121  LLT SrcTy = DstTy.getElementType();
3122 
3123  int DstNumElts = DstTy.getNumElements();
3124  int NarrowNumElts = NarrowTy.getNumElements();
3125  int NumConcat = (DstNumElts + NarrowNumElts - 1) / NarrowNumElts;
3126  LLT WidenedDstTy = LLT::vector(NarrowNumElts * NumConcat, SrcTy);
3127 
3128  SmallVector<Register, 8> ConcatOps;
3129  SmallVector<Register, 8> SubBuildVector;
3130 
3131  Register UndefReg;
3132  if (WidenedDstTy != DstTy)
3133  UndefReg = MIRBuilder.buildUndef(SrcTy).getReg(0);
3134 
3135  // Create a G_CONCAT_VECTORS of NarrowTy pieces, padding with undef as
3136  // necessary.
3137  //
3138  // %3:_(<3 x s16>) = G_BUILD_VECTOR %0, %1, %2
3139  // -> <2 x s16>
3140  //
3141  // %4:_(s16) = G_IMPLICIT_DEF
3142  // %5:_(<2 x s16>) = G_BUILD_VECTOR %0, %1
3143  // %6:_(<2 x s16>) = G_BUILD_VECTOR %2, %4
3144  // %7:_(<4 x s16>) = G_CONCAT_VECTORS %5, %6
3145  // %3:_(<3 x s16>) = G_EXTRACT %7, 0
3146  for (int I = 0; I != NumConcat; ++I) {
3147  for (int J = 0; J != NarrowNumElts; ++J) {
3148  int SrcIdx = NarrowNumElts * I + J;
3149 
3150  if (SrcIdx < DstNumElts) {
3151  Register SrcReg = MI.getOperand(SrcIdx + 1).getReg();
3152  SubBuildVector.push_back(SrcReg);
3153  } else
3154  SubBuildVector.push_back(UndefReg);
3155  }
3156 
3157  auto BuildVec = MIRBuilder.buildBuildVector(NarrowTy, SubBuildVector);
3158  ConcatOps.push_back(BuildVec.getReg(0));
3159  SubBuildVector.clear();
3160  }
3161 
3162  if (DstTy == WidenedDstTy)
3163  MIRBuilder.buildConcatVectors(DstReg, ConcatOps);
3164  else {
3165  auto Concat = MIRBuilder.buildConcatVectors(WidenedDstTy, ConcatOps);
3166  MIRBuilder.buildExtract(DstReg, Concat, 0);
3167  }
3168 
3169  MI.eraseFromParent();
3170  return Legalized;
3171 }
3172 
3175  LLT NarrowTy) {
3176  // FIXME: Don't know how to handle secondary types yet.
3177  if (TypeIdx != 0)
3178  return UnableToLegalize;
3179 
3180  MachineMemOperand *MMO = *MI.memoperands_begin();
3181 
3182  // This implementation doesn't work for atomics. Give up instead of doing
3183  // something invalid.
3184  if (MMO->getOrdering() != AtomicOrdering::NotAtomic ||
3186  return UnableToLegalize;
3187 
3188  bool IsLoad = MI.getOpcode() == TargetOpcode::G_LOAD;
3189  Register ValReg = MI.getOperand(0).getReg();
3190  Register AddrReg = MI.getOperand(1).getReg();
3191  LLT ValTy = MRI.getType(ValReg);
3192 
3193  // FIXME: Do we need a distinct NarrowMemory legalize action?
3194  if (ValTy.getSizeInBits() != 8 * MMO->getSize()) {
3195  LLVM_DEBUG(dbgs() << "Can't narrow extload/truncstore\n");
3196  return UnableToLegalize;
3197  }
3198 
3199  int NumParts = -1;
3200  int NumLeftover = -1;
3201  LLT LeftoverTy;
3202  SmallVector<Register, 8> NarrowRegs, NarrowLeftoverRegs;
3203  if (IsLoad) {
3204  std::tie(NumParts, NumLeftover) = getNarrowTypeBreakDown(ValTy, NarrowTy, LeftoverTy);
3205  } else {
3206  if (extractParts(ValReg, ValTy, NarrowTy, LeftoverTy, NarrowRegs,
3207  NarrowLeftoverRegs)) {
3208  NumParts = NarrowRegs.size();
3209  NumLeftover = NarrowLeftoverRegs.size();
3210  }
3211  }
3212 
3213  if (NumParts == -1)
3214  return UnableToLegalize;
3215 
3216  const LLT OffsetTy = LLT::scalar(MRI.getType(AddrReg).getScalarSizeInBits());
3217 
3218  unsigned TotalSize = ValTy.getSizeInBits();
3219 
3220  // Split the load/store into PartTy sized pieces starting at Offset. If this
3221  // is a load, return the new registers in ValRegs. For a store, each elements
3222  // of ValRegs should be PartTy. Returns the next offset that needs to be
3223  // handled.
3224  auto splitTypePieces = [=](LLT PartTy, SmallVectorImpl<Register> &ValRegs,
3225  unsigned Offset) -> unsigned {
3227  unsigned PartSize = PartTy.getSizeInBits();
3228  for (unsigned Idx = 0, E = NumParts; Idx != E && Offset < TotalSize;
3229  Offset += PartSize, ++Idx) {
3230  unsigned ByteSize = PartSize / 8;
3231  unsigned ByteOffset = Offset / 8;
3232  Register NewAddrReg;
3233 
3234  MIRBuilder.materializePtrAdd(NewAddrReg, AddrReg, OffsetTy, ByteOffset);
3235 
3236  MachineMemOperand *NewMMO =
3237  MF.getMachineMemOperand(MMO, ByteOffset, ByteSize);
3238 
3239  if (IsLoad) {
3240  Register Dst = MRI.createGenericVirtualRegister(PartTy);
3241  ValRegs.push_back(Dst);
3242  MIRBuilder.buildLoad(Dst, NewAddrReg, *NewMMO);
3243  } else {
3244  MIRBuilder.buildStore(ValRegs[Idx], NewAddrReg, *NewMMO);
3245  }
3246  }
3247 
3248  return Offset;
3249  };
3250 
3251  unsigned HandledOffset = splitTypePieces(NarrowTy, NarrowRegs, 0);
3252 
3253  // Handle the rest of the register if this isn't an even type breakdown.
3254  if (LeftoverTy.isValid())
3255  splitTypePieces(LeftoverTy, NarrowLeftoverRegs, HandledOffset);
3256 
3257  if (IsLoad) {
3258  insertParts(ValReg, ValTy, NarrowTy, NarrowRegs,
3259  LeftoverTy, NarrowLeftoverRegs);
3260  }
3261 
3262  MI.eraseFromParent();
3263  return Legalized;
3264 }
3265 
3268  LLT NarrowTy) {
3269  assert(TypeIdx == 0 && "only one type index expected");
3270 
3271  const unsigned Opc = MI.getOpcode();
3272  const int NumOps = MI.getNumOperands() - 1;
3273  const Register DstReg = MI.getOperand(0).getReg();
3274  const unsigned Flags = MI.getFlags();
3275  const unsigned NarrowSize = NarrowTy.getSizeInBits();
3276  const LLT NarrowScalarTy = LLT::scalar(NarrowSize);
3277 
3278  assert(NumOps <= 3 && "expected instruction with 1 result and 1-3 sources");
3279 
3280  // First of all check whether we are narrowing (changing the element type)
3281  // or reducing the vector elements
3282  const LLT DstTy = MRI.getType(DstReg);
3283  const bool IsNarrow = NarrowTy.getScalarType() != DstTy.getScalarType();
3284 
3285  SmallVector<Register, 8> ExtractedRegs[3];
3287 
3288  unsigned NarrowElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
3289 
3290  // Break down all the sources into NarrowTy pieces we can operate on. This may
3291  // involve creating merges to a wider type, padded with undef.
3292  for (int I = 0; I != NumOps; ++I) {
3293  Register SrcReg = MI.getOperand(I + 1).getReg();
3294  LLT SrcTy = MRI.getType(SrcReg);
3295 
3296  // The type to narrow SrcReg to. For narrowing, this is a smaller scalar.
3297  // For fewerElements, this is a smaller vector with the same element type.
3298  LLT OpNarrowTy;
3299  if (IsNarrow) {
3300  OpNarrowTy = NarrowScalarTy;
3301 
3302  // In case of narrowing, we need to cast vectors to scalars for this to
3303  // work properly
3304  // FIXME: Can we do without the bitcast here if we're narrowing?
3305  if (SrcTy.isVector()) {
3306  SrcTy = LLT::scalar(SrcTy.getSizeInBits());
3307  SrcReg = MIRBuilder.buildBitcast(SrcTy, SrcReg).getReg(0);
3308  }
3309  } else {
3310  OpNarrowTy = LLT::scalarOrVector(NarrowElts, SrcTy.getScalarType());
3311  }
3312 
3313  LLT GCDTy = extractGCDType(ExtractedRegs[I], SrcTy, OpNarrowTy, SrcReg);
3314 
3315  // Build a sequence of NarrowTy pieces in ExtractedRegs for this operand.
3316  buildLCMMergePieces(SrcTy, OpNarrowTy, GCDTy, ExtractedRegs[I],
3317  TargetOpcode::G_ANYEXT);
3318  }
3319 
3320  SmallVector<Register, 8> ResultRegs;
3321 
3322  // Input operands for each sub-instruction.
3323  SmallVector<SrcOp, 4> InputRegs(NumOps, Register());
3324 
3325  int NumParts = ExtractedRegs[0].size();
3326  const unsigned DstSize = DstTy.getSizeInBits();
3327  const LLT DstScalarTy = LLT::scalar(DstSize);
3328 
3329  // Narrowing needs to use scalar types
3330  LLT DstLCMTy, NarrowDstTy;
3331  if (IsNarrow) {
3332  DstLCMTy = getLCMType(DstScalarTy, NarrowScalarTy);
3333  NarrowDstTy = NarrowScalarTy;
3334  } else {
3335  DstLCMTy = getLCMType(DstTy, NarrowTy);
3336  NarrowDstTy = NarrowTy;
3337  }
3338 
3339  // We widened the source registers to satisfy merge/unmerge size
3340  // constraints. We'll have some extra fully undef parts.
3341  const int NumRealParts = (DstSize + NarrowSize - 1) / NarrowSize;
3342 
3343  for (int I = 0; I != NumRealParts; ++I) {
3344  // Emit this instruction on each of the split pieces.
3345  for (int J = 0; J != NumOps; ++J)
3346  InputRegs[J] = ExtractedRegs[J][I];
3347 
3348  auto Inst = MIRBuilder.buildInstr(Opc, {NarrowDstTy}, InputRegs, Flags);
3349  ResultRegs.push_back(Inst.getReg(0));
3350  }
3351 
3352  // Fill out the widened result with undef instead of creating instructions
3353  // with undef inputs.
3354  int NumUndefParts = NumParts - NumRealParts;
3355  if (NumUndefParts != 0)
3356  ResultRegs.append(NumUndefParts,
3357  MIRBuilder.buildUndef(NarrowDstTy).getReg(0));
3358 
3359  // Extract the possibly padded result. Use a scratch register if we need to do
3360  // a final bitcast, otherwise use the original result register.
3361  Register MergeDstReg;
3362  if (IsNarrow && DstTy.isVector())
3363  MergeDstReg = MRI.createGenericVirtualRegister(DstScalarTy);
3364  else
3365  MergeDstReg = DstReg;
3366 
3367  buildWidenedRemergeToDst(MergeDstReg, DstLCMTy, ResultRegs);
3368 
3369  // Recast to vector if we narrowed a vector
3370  if (IsNarrow && DstTy.isVector())
3371  MIRBuilder.buildBitcast(DstReg, MergeDstReg);
3372 
3373  MI.eraseFromParent();
3374  return Legalized;
3375 }
3376 
3379  LLT NarrowTy) {
3380  Register DstReg = MI.getOperand(0).getReg();
3381  Register SrcReg = MI.getOperand(1).getReg();
3382  int64_t Imm = MI.getOperand(2).getImm();
3383 
3384  LLT DstTy = MRI.getType(DstReg);
3385 
3387  LLT GCDTy = extractGCDType(Parts, DstTy, NarrowTy, SrcReg);
3388  LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts);
3389 
3390  for (Register &R : Parts)
3391  R = MIRBuilder.buildSExtInReg(NarrowTy, R, Imm).getReg(0);
3392 
3393  buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
3394 
3395  MI.eraseFromParent();
3396  return Legalized;
3397 }
3398 
3401  LLT NarrowTy) {
3402  using namespace TargetOpcode;
3403 
3404  switch (MI.getOpcode()) {
3405  case G_IMPLICIT_DEF:
3406  return fewerElementsVectorImplicitDef(MI, TypeIdx, NarrowTy);
3407  case G_TRUNC:
3408  case G_AND:
3409  case G_OR:
3410  case G_XOR:
3411  case G_ADD:
3412  case G_SUB:
3413  case G_MUL:
3414  case G_SMULH:
3415  case G_UMULH:
3416  case G_FADD:
3417  case G_FMUL:
3418  case G_FSUB:
3419  case G_FNEG:
3420  case G_FABS:
3421  case G_FCANONICALIZE:
3422  case G_FDIV:
3423  case G_FREM:
3424  case G_FMA:
3425  case G_FMAD:
3426  case G_FPOW:
3427  case G_FEXP:
3428  case G_FEXP2:
3429  case G_FLOG:
3430  case G_FLOG2:
3431  case G_FLOG10:
3432  case G_FNEARBYINT:
3433  case G_FCEIL:
3434  case G_FFLOOR:
3435  case G_FRINT:
3436  case G_INTRINSIC_ROUND:
3437  case G_INTRINSIC_TRUNC:
3438  case G_FCOS:
3439  case G_FSIN:
3440  case G_FSQRT:
3441  case G_BSWAP:
3442  case G_BITREVERSE:
3443  case G_SDIV:
3444  case G_UDIV:
3445  case G_SREM:
3446  case G_UREM:
3447  case G_SMIN:
3448  case G_SMAX:
3449  case G_UMIN:
3450  case G_UMAX:
3451  case G_FMINNUM:
3452  case G_FMAXNUM:
3453  case G_FMINNUM_IEEE:
3454  case G_FMAXNUM_IEEE:
3455  case G_FMINIMUM:
3456  case G_FMAXIMUM:
3457  case G_FSHL:
3458  case G_FSHR:
3459  case G_FREEZE:
3460  case G_SADDSAT:
3461  case G_SSUBSAT:
3462  case G_UADDSAT:
3463  case G_USUBSAT:
3464  return reduceOperationWidth(MI, TypeIdx, NarrowTy);
3465  case G_SHL:
3466  case G_LSHR:
3467  case G_ASHR:
3468  case G_CTLZ:
3469  case G_CTLZ_ZERO_UNDEF:
3470  case G_CTTZ:
3471  case G_CTTZ_ZERO_UNDEF:
3472  case G_CTPOP:
3473  case G_FCOPYSIGN:
3474  return fewerElementsVectorMultiEltType(MI, TypeIdx, NarrowTy);
3475  case G_ZEXT:
3476  case G_SEXT:
3477  case G_ANYEXT:
3478  case G_FPEXT:
3479  case G_FPTRUNC:
3480  case G_SITOFP:
3481  case G_UITOFP:
3482  case G_FPTOSI:
3483  case G_FPTOUI:
3484  case G_INTTOPTR:
3485  case G_PTRTOINT:
3486  case G_ADDRSPACE_CAST:
3487  return fewerElementsVectorCasts(MI, TypeIdx, NarrowTy);
3488  case G_ICMP:
3489  case G_FCMP:
3490  return fewerElementsVectorCmp(MI, TypeIdx, NarrowTy);
3491  case G_SELECT:
3492  return fewerElementsVectorSelect(MI, TypeIdx, NarrowTy);
3493  case G_PHI:
3494  return fewerElementsVectorPhi(MI, TypeIdx, NarrowTy);
3495  case G_UNMERGE_VALUES:
3496  return fewerElementsVectorUnmergeValues(MI, TypeIdx, NarrowTy);
3497  case G_BUILD_VECTOR:
3498  return fewerElementsVectorBuildVector(MI, TypeIdx, NarrowTy);
3499  case G_LOAD:
3500  case G_STORE:
3501  return reduceLoadStoreWidth(MI, TypeIdx, NarrowTy);
3502  case G_SEXT_INREG:
3503  return fewerElementsVectorSextInReg(MI, TypeIdx, NarrowTy);
3504  default:
3505  return UnableToLegalize;
3506  }
3507 }
3508 
3511  const LLT HalfTy, const LLT AmtTy) {
3512 
3513  Register InL = MRI.createGenericVirtualRegister(HalfTy);
3514  Register InH = MRI.createGenericVirtualRegister(HalfTy);
3515  MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1));
3516 
3517  if (Amt.isNullValue()) {
3518  MIRBuilder.buildMerge(MI.getOperand(0), {InL, InH});
3519  MI.eraseFromParent();
3520  return Legalized;
3521  }
3522 
3523  LLT NVT = HalfTy;
3524  unsigned NVTBits = HalfTy.getSizeInBits();
3525  unsigned VTBits = 2 * NVTBits;
3526 
3527  SrcOp Lo(Register(0)), Hi(Register(0));
3528  if (MI.getOpcode() == TargetOpcode::G_SHL) {
3529  if (Amt.ugt(VTBits)) {
3530  Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
3531  } else if (Amt.ugt(NVTBits)) {
3532  Lo = MIRBuilder.buildConstant(NVT, 0);
3533  Hi = MIRBuilder.buildShl(NVT, InL,
3534  MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
3535  } else if (Amt == NVTBits) {
3536  Lo = MIRBuilder.buildConstant(NVT, 0);
3537  Hi = InL;
3538  } else {
3539  Lo = MIRBuilder.buildShl(NVT, InL, MIRBuilder.buildConstant(AmtTy, Amt));
3540  auto OrLHS =
3541  MIRBuilder.buildShl(NVT, InH, MIRBuilder.buildConstant(AmtTy, Amt));
3542  auto OrRHS = MIRBuilder.buildLShr(
3543  NVT, InL, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
3544  Hi = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
3545  }
3546  } else if (MI.getOpcode() == TargetOpcode::G_LSHR) {
3547  if (Amt.ugt(VTBits)) {
3548  Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
3549  } else if (Amt.ugt(NVTBits)) {
3550  Lo = MIRBuilder.buildLShr(NVT, InH,
3551  MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
3552  Hi = MIRBuilder.buildConstant(NVT, 0);
3553  } else if (Amt == NVTBits) {
3554  Lo = InH;
3555  Hi = MIRBuilder.buildConstant(NVT, 0);
3556  } else {
3557  auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
3558 
3559  auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
3560  auto OrRHS = MIRBuilder.buildShl(
3561  NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
3562 
3563  Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
3564  Hi = MIRBuilder.buildLShr(NVT, InH, ShiftAmtConst);
3565  }
3566  } else {
3567  if (Amt.ugt(VTBits)) {
3568  Hi = Lo = MIRBuilder.buildAShr(
3569  NVT, InH, MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
3570  } else if (Amt.ugt(NVTBits)) {
3571  Lo = MIRBuilder.buildAShr(NVT, InH,
3572  MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
3573  Hi = MIRBuilder.buildAShr(NVT, InH,
3574  MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
3575  } else if (Amt == NVTBits) {
3576  Lo = InH;
3577  Hi = MIRBuilder.buildAShr(NVT, InH,
3578  MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
3579  } else {
3580  auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
3581 
3582  auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
3583  auto OrRHS = MIRBuilder.buildShl(
3584  NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
3585 
3586  Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
3587  Hi = MIRBuilder.buildAShr(NVT, InH, ShiftAmtConst);
3588  }
3589  }
3590 
3591  MIRBuilder.buildMerge(MI.getOperand(0), {Lo, Hi});
3592  MI.eraseFromParent();
3593 
3594  return Legalized;
3595 }
3596 
3597 // TODO: Optimize if constant shift amount.
3600  LLT RequestedTy) {
3601  if (TypeIdx == 1) {
3602  Observer.changingInstr(MI);
3603  narrowScalarSrc(MI, RequestedTy, 2);
3604  Observer.changedInstr(MI);
3605  return Legalized;
3606  }
3607 
3608  Register DstReg = MI.getOperand(0).getReg();
3609  LLT DstTy = MRI.getType(DstReg);
3610  if (DstTy.isVector())
3611  return UnableToLegalize;
3612 
3613  Register Amt = MI.getOperand(2).getReg();
3614  LLT ShiftAmtTy = MRI.getType(Amt);
3615  const unsigned DstEltSize = DstTy.getScalarSizeInBits();
3616  if (DstEltSize % 2 != 0)
3617  return UnableToLegalize;
3618 
3619  // Ignore the input type. We can only go to exactly half the size of the
3620  // input. If that isn't small enough, the resulting pieces will be further
3621  // legalized.
3622  const unsigned NewBitSize = DstEltSize / 2;
3623  const LLT HalfTy = LLT::scalar(NewBitSize);
3624  const LLT CondTy = LLT::scalar(1);
3625 
3626  if (const MachineInstr *KShiftAmt =
3627  getOpcodeDef(TargetOpcode::G_CONSTANT, Amt, MRI)) {
3629  MI, KShiftAmt->getOperand(1).getCImm()->getValue(), HalfTy, ShiftAmtTy);
3630  }
3631 
3632  // TODO: Expand with known bits.
3633 
3634  // Handle the fully general expansion by an unknown amount.
3635  auto NewBits = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize);
3636 
3637  Register InL = MRI.createGenericVirtualRegister(HalfTy);
3638  Register InH = MRI.createGenericVirtualRegister(HalfTy);
3639  MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1));
3640 
3641  auto AmtExcess = MIRBuilder.buildSub(ShiftAmtTy, Amt, NewBits);
3642  auto AmtLack = MIRBuilder.buildSub(ShiftAmtTy, NewBits, Amt);
3643 
3644  auto Zero = MIRBuilder.buildConstant(ShiftAmtTy, 0);
3645  auto IsShort = MIRBuilder.buildICmp(ICmpInst::ICMP_ULT, CondTy, Amt, NewBits);
3646  auto IsZero = MIRBuilder.buildICmp(ICmpInst::ICMP_EQ, CondTy, Amt, Zero);
3647 
3648  Register ResultRegs[2];
3649  switch (MI.getOpcode()) {
3650  case TargetOpcode::G_SHL: {
3651  // Short: ShAmt < NewBitSize
3652  auto LoS = MIRBuilder.buildShl(HalfTy, InL, Amt);
3653 
3654  auto LoOr = MIRBuilder.buildLShr(HalfTy, InL, AmtLack);
3655  auto HiOr = MIRBuilder.buildShl(HalfTy, InH, Amt);
3656  auto HiS = MIRBuilder.buildOr(HalfTy, LoOr, HiOr);
3657 
3658  // Long: ShAmt >= NewBitSize
3659  auto LoL = MIRBuilder.buildConstant(HalfTy, 0); // Lo part is zero.
3660  auto HiL = MIRBuilder.buildShl(HalfTy, InL, AmtExcess); // Hi from Lo part.
3661 
3662  auto Lo = MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL);
3663  auto Hi = MIRBuilder.buildSelect(
3664  HalfTy, IsZero, InH, MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL));
3665 
3666  ResultRegs[0] = Lo.getReg(0);
3667  ResultRegs[1] = Hi.getReg(0);
3668  break;
3669  }
3670  case TargetOpcode::G_LSHR:
3671  case TargetOpcode::G_ASHR: {
3672  // Short: ShAmt < NewBitSize
3673  auto HiS = MIRBuilder.buildInstr(MI.getOpcode(), {HalfTy}, {InH, Amt});
3674 
3675  auto LoOr = MIRBuilder.buildLShr(HalfTy, InL, Amt);
3676  auto HiOr = MIRBuilder.buildShl(HalfTy, InH, AmtLack);
3677  auto LoS = MIRBuilder.buildOr(HalfTy, LoOr, HiOr);
3678 
3679  // Long: ShAmt >= NewBitSize
3680  MachineInstrBuilder HiL;
3681  if (MI.getOpcode() == TargetOpcode::G_LSHR) {
3682  HiL = MIRBuilder.buildConstant(HalfTy, 0); // Hi part is zero.
3683  } else {
3684  auto ShiftAmt = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize - 1);
3685  HiL = MIRBuilder.buildAShr(HalfTy, InH, ShiftAmt); // Sign of Hi part.
3686  }
3687  auto LoL = MIRBuilder.buildInstr(MI.getOpcode(), {HalfTy},
3688  {InH, AmtExcess}); // Lo from Hi part.
3689 
3690  auto Lo = MIRBuilder.buildSelect(
3691  HalfTy, IsZero, InL, MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL));
3692 
3693  auto Hi = MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL);
3694 
3695  ResultRegs[0] = Lo.getReg(0);
3696  ResultRegs[1] = Hi.getReg(0);
3697  break;
3698  }
3699  default:
3700  llvm_unreachable("not a shift");
3701  }
3702 
3703  MIRBuilder.buildMerge(DstReg, ResultRegs);
3704  MI.eraseFromParent();
3705  return Legalized;
3706 }
3707 
3710  LLT MoreTy) {
3711  assert(TypeIdx == 0 && "Expecting only Idx 0");
3712 
3713  Observer.changingInstr(MI);
3714  for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
3715  MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
3716  MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
3717  moreElementsVectorSrc(MI, MoreTy, I);
3718  }
3719 
3720  MachineBasicBlock &MBB = *MI.getParent();
3721  MIRBuilder.setInsertPt(MBB, --MBB.getFirstNonPHI());
3722  moreElementsVectorDst(MI, MoreTy, 0);
3723  Observer.changedInstr(MI);
3724  return Legalized;
3725 }
3726 
3729  LLT MoreTy) {
3730  unsigned Opc = MI.getOpcode();
3731  switch (Opc) {
3732  case TargetOpcode::G_IMPLICIT_DEF:
3733  case TargetOpcode::G_LOAD: {
3734  if (TypeIdx != 0)
3735  return UnableToLegalize;
3736  Observer.changingInstr(MI);
3737  moreElementsVectorDst(MI, MoreTy, 0);
3738  Observer.changedInstr(MI);
3739  return Legalized;
3740  }
3741  case TargetOpcode::G_STORE:
3742  if (TypeIdx != 0)
3743  return UnableToLegalize;
3744  Observer.changingInstr(MI);
3745  moreElementsVectorSrc(MI, MoreTy, 0);
3746  Observer.changedInstr(MI);
3747  return Legalized;
3748  case TargetOpcode::G_AND:
3749  case TargetOpcode::G_OR:
3750  case TargetOpcode::G_XOR:
3751  case TargetOpcode::G_SMIN:
3752  case TargetOpcode::G_SMAX:
3753  case TargetOpcode::G_UMIN:
3754  case TargetOpcode::G_UMAX:
3755  case TargetOpcode::G_FMINNUM:
3756  case TargetOpcode::G_FMAXNUM:
3757  case TargetOpcode::G_FMINNUM_IEEE:
3758  case TargetOpcode::G_FMAXNUM_IEEE:
3759  case TargetOpcode::G_FMINIMUM:
3760  case TargetOpcode::G_FMAXIMUM: {
3761  Observer.changingInstr(MI);
3762  moreElementsVectorSrc(MI, MoreTy, 1);
3763  moreElementsVectorSrc(MI, MoreTy, 2);
3764  moreElementsVectorDst(MI, MoreTy, 0);
3765  Observer.changedInstr(MI);
3766  return Legalized;
3767  }
3768  case TargetOpcode::G_EXTRACT:
3769  if (TypeIdx != 1)
3770  return UnableToLegalize;
3771  Observer.changingInstr(MI);
3772  moreElementsVectorSrc(MI, MoreTy, 1);
3773  Observer.changedInstr(MI);
3774  return Legalized;
3775  case TargetOpcode::G_INSERT:
3776  case TargetOpcode::G_FREEZE:
3777  if (TypeIdx != 0)
3778  return UnableToLegalize;
3779  Observer.changingInstr(MI);
3780  moreElementsVectorSrc(MI, MoreTy, 1);
3781  moreElementsVectorDst(MI, MoreTy, 0);
3782  Observer.changedInstr(MI);
3783  return Legalized;
3784  case TargetOpcode::G_SELECT:
3785  if (TypeIdx != 0)
3786  return UnableToLegalize;
3787  if (MRI.getType(MI.getOperand(1).getReg()).isVector())
3788  return UnableToLegalize;
3789 
3790  Observer.changingInstr(MI);
3791  moreElementsVectorSrc(MI, MoreTy, 2);
3792  moreElementsVectorSrc(MI, MoreTy, 3);
3793  moreElementsVectorDst(MI, MoreTy, 0);
3794  Observer.changedInstr(MI);
3795  return Legalized;
3796  case TargetOpcode::G_UNMERGE_VALUES: {
3797  if (TypeIdx != 1)
3798  return UnableToLegalize;
3799 
3800  LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
3801  int NumDst = MI.getNumOperands() - 1;
3802  moreElementsVectorSrc(MI, MoreTy, NumDst);
3803 
3804  auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_UNMERGE_VALUES);
3805  for (int I = 0; I != NumDst; ++I)
3806  MIB.addDef(MI.getOperand(I).getReg());
3807 
3808  int NewNumDst = MoreTy.getSizeInBits() / DstTy.getSizeInBits();
3809  for (int I = NumDst; I != NewNumDst; ++I)
3810  MIB.addDef(MRI.createGenericVirtualRegister(DstTy));
3811 
3812  MIB.addUse(MI.getOperand(NumDst).getReg());
3813  MI.eraseFromParent();
3814  return Legalized;
3815  }
3816  case TargetOpcode::G_PHI:
3817  return moreElementsVectorPhi(MI, TypeIdx, MoreTy);
3818  default:
3819  return UnableToLegalize;
3820  }
3821 }
3822 
3823 void LegalizerHelper::multiplyRegisters(SmallVectorImpl<Register> &DstRegs,
3824  ArrayRef<Register> Src1Regs,
3825  ArrayRef<Register> Src2Regs,
3826  LLT NarrowTy) {
3828  unsigned SrcParts = Src1Regs.size();
3829  unsigned DstParts = DstRegs.size();
3830 
3831  unsigned DstIdx = 0; // Low bits of the result.
3832  Register FactorSum =
3833  B.buildMul(NarrowTy, Src1Regs[DstIdx], Src2Regs[DstIdx]).getReg(0);
3834  DstRegs[DstIdx] = FactorSum;
3835 
3836  unsigned CarrySumPrevDstIdx;
3837  SmallVector<Register, 4> Factors;
3838 
3839  for (DstIdx = 1; DstIdx < DstParts; DstIdx++) {
3840  // Collect low parts of muls for DstIdx.
3841  for (unsigned i = DstIdx + 1 < SrcParts ? 0 : DstIdx - SrcParts + 1;
3842  i <= std::min(DstIdx, SrcParts - 1); ++i) {
3843  MachineInstrBuilder Mul =
3844  B.buildMul(NarrowTy, Src1Regs[DstIdx - i], Src2Regs[i]);
3845  Factors.push_back(Mul.getReg(0));
3846  }
3847  // Collect high parts of muls from previous DstIdx.
3848  for (unsigned i = DstIdx < SrcParts ? 0 : DstIdx - SrcParts;
3849  i <= std::min(DstIdx - 1, SrcParts - 1); ++i) {
3850  MachineInstrBuilder Umulh =
3851  B.buildUMulH(NarrowTy, Src1Regs[DstIdx - 1 - i], Src2Regs[i]);
3852  Factors.push_back(Umulh.getReg(0));
3853  }
3854  // Add CarrySum from additions calculated for previous DstIdx.
3855  if (DstIdx != 1) {
3856  Factors.push_back(CarrySumPrevDstIdx);
3857  }
3858 
3859  Register CarrySum;
3860  // Add all factors and accumulate all carries into CarrySum.
3861  if (DstIdx != DstParts - 1) {
3862  MachineInstrBuilder Uaddo =
3863  B.buildUAddo(NarrowTy, LLT::scalar(1), Factors[0], Factors[1]);
3864  FactorSum = Uaddo.getReg(0);
3865  CarrySum = B.buildZExt(NarrowTy, Uaddo.getReg(1)).getReg(0);
3866  for (unsigned i = 2; i < Factors.size(); ++i) {
3867  MachineInstrBuilder Uaddo =
3868  B.buildUAddo(NarrowTy, LLT::scalar(1), FactorSum, Factors[i]);
3869  FactorSum = Uaddo.getReg(0);
3870  MachineInstrBuilder Carry = B.buildZExt(NarrowTy, Uaddo.getReg(1));
3871  CarrySum = B.buildAdd(NarrowTy, CarrySum, Carry).getReg(0);
3872  }
3873  } else {
3874  // Since value for the next index is not calculated, neither is CarrySum.
3875  FactorSum = B.buildAdd(NarrowTy, Factors[0], Factors[1]).getReg(0);
3876  for (unsigned i = 2; i < Factors.size(); ++i)
3877  FactorSum = B.buildAdd(NarrowTy, FactorSum, Factors[i]).getReg(0);
3878  }
3879 
3880  CarrySumPrevDstIdx = CarrySum;
3881  DstRegs[DstIdx] = FactorSum;
3882  Factors.clear();
3883  }
3884 }
3885 
3888  Register DstReg = MI.getOperand(0).getReg();
3889  Register Src1 = MI.getOperand(1).getReg();
3890  Register Src2 = MI.getOperand(2).getReg();
3891 
3892  LLT Ty = MRI.getType(DstReg);
3893  if (Ty.isVector())
3894  return UnableToLegalize;
3895 
3896  unsigned SrcSize = MRI.getType(Src1).getSizeInBits();
3897  unsigned DstSize = Ty.getSizeInBits();
3898  unsigned NarrowSize = NarrowTy.getSizeInBits();
3899  if (DstSize % NarrowSize != 0 || SrcSize % NarrowSize != 0)
3900  return UnableToLegalize;
3901 
3902  unsigned NumDstParts = DstSize / NarrowSize;
3903  unsigned NumSrcParts = SrcSize / NarrowSize;
3904  bool IsMulHigh = MI.getOpcode() == TargetOpcode::G_UMULH;
3905  unsigned DstTmpParts = NumDstParts * (IsMulHigh ? 2 : 1);
3906 
3907  SmallVector<Register, 2> Src1Parts, Src2Parts;
3908  SmallVector<Register, 2> DstTmpRegs(DstTmpParts);
3909  extractParts(Src1, NarrowTy, NumSrcParts, Src1Parts);
3910  extractParts(Src2, NarrowTy, NumSrcParts, Src2Parts);
3911  multiplyRegisters(DstTmpRegs, Src1Parts, Src2Parts, NarrowTy);
3912 
3913  // Take only high half of registers if this is high mul.
3914  ArrayRef<Register> DstRegs(
3915  IsMulHigh ? &DstTmpRegs[DstTmpParts / 2] : &DstTmpRegs[0], NumDstParts);
3916  MIRBuilder.buildMerge(DstReg, DstRegs);
3917  MI.eraseFromParent();
3918  return Legalized;
3919 }
3920 
3923  LLT NarrowTy) {
3924  if (TypeIdx != 1)
3925  return UnableToLegalize;
3926 
3927  uint64_t NarrowSize = NarrowTy.getSizeInBits();
3928 
3929  int64_t SizeOp1 = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
3930  // FIXME: add support for when SizeOp1 isn't an exact multiple of
3931  // NarrowSize.
3932  if (SizeOp1 % NarrowSize != 0)
3933  return UnableToLegalize;
3934  int NumParts = SizeOp1 / NarrowSize;
3935 
3936  SmallVector<Register, 2> SrcRegs, DstRegs;
3937  SmallVector<uint64_t, 2> Indexes;
3938  extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
3939 
3940  Register OpReg = MI.getOperand(0).getReg();
3941  uint64_t OpStart = MI.getOperand(2).getImm();
3942  uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
3943  for (int i = 0; i < NumParts; ++i) {
3944  unsigned SrcStart = i * NarrowSize;
3945 
3946  if (SrcStart + NarrowSize <= OpStart || SrcStart >= OpStart + OpSize) {
3947  // No part of the extract uses this subregister, ignore it.
3948  continue;
3949  } else if (SrcStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
3950  // The entire subregister is extracted, forward the value.
3951  DstRegs.push_back(SrcRegs[i]);
3952  continue;
3953  }
3954 
3955  // OpSegStart is where this destination segment would start in OpReg if it
3956  // extended infinitely in both directions.
3957  int64_t ExtractOffset;
3958  uint64_t SegSize;
3959  if (OpStart < SrcStart) {
3960  ExtractOffset = 0;
3961  SegSize = std::min(NarrowSize, OpStart + OpSize - SrcStart);
3962  } else {
3963  ExtractOffset = OpStart - SrcStart;
3964  SegSize = std::min(SrcStart + NarrowSize - OpStart, OpSize);
3965  }
3966 
3967  Register SegReg = SrcRegs[i];
3968  if (ExtractOffset != 0 || SegSize != NarrowSize) {
3969  // A genuine extract is needed.
3970  SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
3971  MIRBuilder.buildExtract(SegReg, SrcRegs[i], ExtractOffset);
3972  }
3973 
3974  DstRegs.push_back(SegReg);
3975  }
3976 
3977  Register DstReg = MI.getOperand(0).getReg();
3978  if (MRI.getType(DstReg).isVector())
3979  MIRBuilder.buildBuildVector(DstReg, DstRegs);
3980  else if (DstRegs.size() > 1)
3981  MIRBuilder.buildMerge(DstReg, DstRegs);
3982  else
3983  MIRBuilder.buildCopy(DstReg, DstRegs[0]);
3984  MI.eraseFromParent();
3985  return Legalized;
3986 }
3987 
3990  LLT NarrowTy) {
3991  // FIXME: Don't know how to handle secondary types yet.
3992  if (TypeIdx != 0)
3993  return UnableToLegalize;
3994 
3995  uint64_t SizeOp0 = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
3996  uint64_t NarrowSize = NarrowTy.getSizeInBits();
3997 
3998  // FIXME: add support for when SizeOp0 isn't an exact multiple of
3999  // NarrowSize.
4000  if (SizeOp0 % NarrowSize != 0)
4001  return UnableToLegalize;
4002 
4003  int NumParts = SizeOp0 / NarrowSize;
4004 
4005  SmallVector<Register, 2> SrcRegs, DstRegs;
4006  SmallVector<uint64_t, 2> Indexes;
4007  extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
4008 
4009  Register OpReg = MI.getOperand(2).getReg();
4010  uint64_t OpStart = MI.getOperand(3).getImm();
4011  uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
4012  for (int i = 0; i < NumParts; ++i) {
4013  unsigned DstStart = i * NarrowSize;
4014 
4015  if (DstStart + NarrowSize <= OpStart || DstStart >= OpStart + OpSize) {
4016  // No part of the insert affects this subregister, forward the original.
4017  DstRegs.push_back(SrcRegs[i]);
4018  continue;
4019  } else if (DstStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
4020  // The entire subregister is defined by this insert, forward the new
4021  // value.
4022  DstRegs.push_back(OpReg);
4023  continue;
4024  }
4025 
4026  // OpSegStart is where this destination segment would start in OpReg if it
4027  // extended infinitely in both directions.
4028  int64_t ExtractOffset, InsertOffset;
4029  uint64_t SegSize;
4030  if (OpStart < DstStart) {
4031  InsertOffset = 0;
4032  ExtractOffset = DstStart - OpStart;
4033  SegSize = std::min(NarrowSize, OpStart + OpSize - DstStart);
4034  } else {
4035  InsertOffset = OpStart - DstStart;
4036  ExtractOffset = 0;
4037  SegSize =
4038  std::min(NarrowSize - InsertOffset, OpStart + OpSize - DstStart);
4039  }
4040 
4041  Register SegReg = OpReg;
4042  if (ExtractOffset != 0 || SegSize != OpSize) {
4043  // A genuine extract is needed.
4044  SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
4045  MIRBuilder.buildExtract(SegReg, OpReg, ExtractOffset);
4046  }
4047 
4048  Register DstReg = MRI.createGenericVirtualRegister(NarrowTy);
4049  MIRBuilder.buildInsert(DstReg, SrcRegs[i], SegReg, InsertOffset);
4050  DstRegs.push_back(DstReg);
4051  }
4052 
4053  assert(DstRegs.size() == (unsigned)NumParts && "not all parts covered");
4054  Register DstReg = MI.getOperand(0).getReg();
4055  if(MRI.getType(DstReg).isVector())
4056  MIRBuilder.buildBuildVector(DstReg, DstRegs);
4057  else
4058  MIRBuilder.buildMerge(DstReg, DstRegs);
4059  MI.eraseFromParent();
4060  return Legalized;
4061 }
4062 
4065  LLT NarrowTy) {
4066  Register DstReg = MI.getOperand(0).getReg();
4067  LLT DstTy = MRI.getType(DstReg);
4068 
4069  assert(MI.getNumOperands() == 3 && TypeIdx == 0);
4070 
4071  SmallVector<Register, 4> DstRegs, DstLeftoverRegs;
4072  SmallVector<Register, 4> Src0Regs, Src0LeftoverRegs;
4073  SmallVector<Register, 4> Src1Regs, Src1LeftoverRegs;
4074  LLT LeftoverTy;
4075  if (!extractParts(MI.getOperand(1).getReg(), DstTy, NarrowTy, LeftoverTy,
4076  Src0Regs, Src0LeftoverRegs))
4077  return UnableToLegalize;
4078 
4079  LLT Unused;
4080  if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, Unused,
4081  Src1Regs, Src1LeftoverRegs))
4082  llvm_unreachable("inconsistent extractParts result");
4083 
4084  for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
4085  auto Inst = MIRBuilder.buildInstr(MI.getOpcode(), {NarrowTy},
4086  {Src0Regs[I], Src1Regs[I]});
4087  DstRegs.push_back(Inst.getReg(0));
4088  }
4089 
4090  for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
4091  auto Inst = MIRBuilder.buildInstr(
4092  MI.getOpcode(),
4093  {LeftoverTy}, {Src0LeftoverRegs[I], Src1LeftoverRegs[I]});
4094  DstLeftoverRegs.push_back(Inst.getReg(0));
4095  }
4096 
4097  insertParts(DstReg, DstTy, NarrowTy, DstRegs,
4098  LeftoverTy, DstLeftoverRegs);
4099 
4100  MI.eraseFromParent();
4101  return Legalized;
4102 }
4103 
4106  LLT NarrowTy) {
4107  if (TypeIdx != 0)
4108  return UnableToLegalize;
4109 
4110  Register DstReg = MI.getOperand(0).getReg();
4111  Register SrcReg = MI.getOperand(1).getReg();
4112 
4113  LLT DstTy = MRI.getType(DstReg);
4114  if (DstTy.isVector())
4115  return UnableToLegalize;
4116 
4118  LLT GCDTy = extractGCDType(Parts, DstTy, NarrowTy, SrcReg);
4119  LLT LCMTy = buildLCMMergePieces(DstTy, NarrowTy, GCDTy, Parts, MI.getOpcode());
4120  buildWidenedRemergeToDst(DstReg, LCMTy, Parts);
4121 
4122  MI.eraseFromParent();
4123  return Legalized;
4124 }
4125 
4128  LLT NarrowTy) {
4129  if (TypeIdx != 0)
4130  return UnableToLegalize;
4131 
4132  Register CondReg = MI.getOperand(1).getReg();
4133  LLT CondTy = MRI.getType(CondReg);
4134  if (CondTy.isVector()) // TODO: Handle vselect
4135  return UnableToLegalize;
4136 
4137  Register DstReg = MI.getOperand(0).getReg();
4138  LLT DstTy = MRI.getType(DstReg);
4139 
4140  SmallVector<Register, 4> DstRegs, DstLeftoverRegs;
4141  SmallVector<Register, 4> Src1Regs, Src1LeftoverRegs;
4142  SmallVector<Register, 4> Src2Regs, Src2LeftoverRegs;
4143  LLT LeftoverTy;
4144  if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, LeftoverTy,
4145  Src1Regs, Src1LeftoverRegs))
4146  return UnableToLegalize;
4147 
4148  LLT Unused;
4149  if (!extractParts(MI.getOperand(3).getReg(), DstTy, NarrowTy, Unused,
4150  Src2Regs, Src2LeftoverRegs))
4151  llvm_unreachable("inconsistent extractParts result");
4152 
4153  for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
4154  auto Select = MIRBuilder.buildSelect(NarrowTy,
4155  CondReg, Src1Regs[I], Src2Regs[I]);
4156  DstRegs.push_back(Select.getReg(0));
4157  }
4158 
4159  for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
4160  auto Select = MIRBuilder.buildSelect(
4161  LeftoverTy, CondReg, Src1LeftoverRegs[I], Src2LeftoverRegs[I]);
4162  DstLeftoverRegs.push_back(Select.getReg(0));
4163  }
4164 
4165  insertParts(DstReg, DstTy, NarrowTy, DstRegs,
4166  LeftoverTy, DstLeftoverRegs);
4167 
4168  MI.eraseFromParent();
4169  return Legalized;
4170 }
4171 
4174  LLT NarrowTy) {
4175  if (TypeIdx != 1)
4176  return UnableToLegalize;
4177 
4178  Register DstReg = MI.getOperand(0).getReg();
4179  Register SrcReg = MI.getOperand(1).getReg();
4180  LLT DstTy = MRI.getType(DstReg);
4181  LLT SrcTy = MRI.getType(SrcReg);
4182  unsigned NarrowSize = NarrowTy.getSizeInBits();
4183 
4184  if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
4185  const bool IsUndef = MI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_UNDEF;
4186 
4188  auto UnmergeSrc = B.buildUnmerge(NarrowTy, SrcReg);
4189  // ctlz(Hi:Lo) -> Hi == 0 ? (NarrowSize + ctlz(Lo)) : ctlz(Hi)
4190  auto C_0 = B.buildConstant(NarrowTy, 0);
4191  auto HiIsZero = B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
4192  UnmergeSrc.getReg(1), C_0);
4193  auto LoCTLZ = IsUndef ?
4194  B.buildCTLZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(0)) :
4195  B.buildCTLZ(DstTy, UnmergeSrc.getReg(0));
4196  auto C_NarrowSize = B.buildConstant(DstTy, NarrowSize);
4197  auto HiIsZeroCTLZ = B.buildAdd(DstTy, LoCTLZ, C_NarrowSize);
4198  auto HiCTLZ = B.buildCTLZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(1));
4199  B.buildSelect(DstReg, HiIsZero, HiIsZeroCTLZ, HiCTLZ);
4200 
4201  MI.eraseFromParent();
4202  return Legalized;
4203  }
4204 
4205  return UnableToLegalize;
4206 }
4207 
4210  LLT NarrowTy) {
4211  if (TypeIdx != 1)
4212  return UnableToLegalize;
4213 
4214  Register DstReg = MI.getOperand(0).getReg();
4215  Register SrcReg = MI.getOperand(1).getReg();
4216  LLT DstTy = MRI.getType(DstReg);
4217  LLT SrcTy = MRI.getType(SrcReg);
4218  unsigned NarrowSize = NarrowTy.getSizeInBits();
4219 
4220  if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
4221  const bool IsUndef = MI.getOpcode() == TargetOpcode::G_CTTZ_ZERO_UNDEF;
4222 
4224  auto UnmergeSrc = B.buildUnmerge(NarrowTy, SrcReg);
4225  // cttz(Hi:Lo) -> Lo == 0 ? (cttz(Hi) + NarrowSize) : cttz(Lo)
4226  auto C_0 = B.buildConstant(NarrowTy, 0);
4227  auto LoIsZero = B.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
4228  UnmergeSrc.getReg(0), C_0);
4229  auto HiCTTZ = IsUndef ?
4230  B.buildCTTZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(1)) :
4231  B.buildCTTZ(DstTy, UnmergeSrc.getReg(1));
4232  auto C_NarrowSize = B.buildConstant(DstTy, NarrowSize);
4233  auto LoIsZeroCTTZ = B.buildAdd(DstTy, HiCTTZ, C_NarrowSize);
4234  auto LoCTTZ = B.buildCTTZ_ZERO_UNDEF(DstTy, UnmergeSrc.getReg(0));
4235  B.buildSelect(DstReg, LoIsZero, LoIsZeroCTTZ, LoCTTZ);
4236 
4237  MI.eraseFromParent();
4238  return Legalized;
4239  }
4240 
4241  return UnableToLegalize;
4242 }
4243 
4246  LLT NarrowTy) {
4247  if (TypeIdx != 1)
4248  return UnableToLegalize;
4249 
4250  Register DstReg = MI.getOperand(0).getReg();
4251  LLT DstTy = MRI.getType(DstReg);
4252  LLT SrcTy = MRI.getType(MI.getOperand(1).getReg());
4253  unsigned NarrowSize = NarrowTy.getSizeInBits();
4254 
4255  if (SrcTy.isScalar() && SrcTy.getSizeInBits() == 2 * NarrowSize) {
4256  auto UnmergeSrc = MIRBuilder.buildUnmerge(NarrowTy, MI.getOperand(1));
4257 
4258  auto LoCTPOP = MIRBuilder.buildCTPOP(DstTy, UnmergeSrc.getReg(0));
4259  auto HiCTPOP = MIRBuilder.buildCTPOP(DstTy, UnmergeSrc.getReg(1));
4260  MIRBuilder.buildAdd(DstReg, HiCTPOP, LoCTPOP);
4261 
4262  MI.eraseFromParent();
4263  return Legalized;
4264  }
4265 
4266  return UnableToLegalize;
4267 }
4268 
4271  unsigned Opc = MI.getOpcode();
4272  auto &TII = *MI.getMF()->getSubtarget().getInstrInfo();
4273  auto isSupported = [this](const LegalityQuery &Q) {
4274  auto QAction = LI.getAction(Q).Action;
4275  return QAction == Legal || QAction == Libcall || QAction == Custom;
4276  };
4277  switch (Opc) {
4278  default:
4279  return UnableToLegalize;
4280  case TargetOpcode::G_CTLZ_ZERO_UNDEF: {
4281  // This trivially expands to CTLZ.
4282  Observer.changingInstr(MI);
4283  MI.setDesc(TII.get(TargetOpcode::G_CTLZ));
4284  Observer.changedInstr(MI);
4285  return Legalized;
4286  }
4287  case TargetOpcode::G_CTLZ: {
4288  Register DstReg = MI.getOperand(0).getReg();
4289  Register SrcReg = MI.getOperand(1).getReg();
4290  LLT DstTy = MRI.getType(DstReg);
4291  LLT SrcTy = MRI.getType(SrcReg);
4292  unsigned Len = SrcTy.getSizeInBits();
4293 
4294  if (isSupported({TargetOpcode::G_CTLZ_ZERO_UNDEF, {DstTy, SrcTy}})) {
4295  // If CTLZ_ZERO_UNDEF is supported, emit that and a select for zero.
4296  auto CtlzZU = MIRBuilder.buildCTLZ_ZERO_UNDEF(DstTy, SrcReg);
4297  auto ZeroSrc = MIRBuilder.buildConstant(SrcTy, 0);
4298  auto ICmp = MIRBuilder.buildICmp(
4299  CmpInst::ICMP_EQ, SrcTy.changeElementSize(1), SrcReg, ZeroSrc);
4300  auto LenConst = MIRBuilder.buildConstant(DstTy, Len);
4301  MIRBuilder.buildSelect(DstReg, ICmp, LenConst, CtlzZU);
4302  MI.eraseFromParent();
4303  return Legalized;
4304  }
4305  // for now, we do this:
4306  // NewLen = NextPowerOf2(Len);
4307  // x = x | (x >> 1);
4308  // x = x | (x >> 2);
4309  // ...
4310  // x = x | (x >>16);
4311  // x = x | (x >>32); // for 64-bit input
4312  // Upto NewLen/2
4313  // return Len - popcount(x);
4314  //
4315  // Ref: "Hacker's Delight" by Henry Warren
4316  Register Op = SrcReg;
4317  unsigned NewLen = PowerOf2Ceil(Len);
4318  for (unsigned i = 0; (1U << i) <= (NewLen / 2); ++i) {
4319  auto MIBShiftAmt = MIRBuilder.buildConstant(SrcTy, 1ULL << i);
4320  auto MIBOp = MIRBuilder.buildOr(
4321  SrcTy, Op, MIRBuilder.buildLShr(SrcTy, Op, MIBShiftAmt));
4322  Op = MIBOp.getReg(0);
4323  }
4324  auto MIBPop = MIRBuilder.buildCTPOP(DstTy, Op);
4326  MIBPop);
4327  MI.eraseFromParent();
4328  return Legalized;
4329  }
4330  case TargetOpcode::G_CTTZ_ZERO_UNDEF: {
4331  // This trivially expands to CTTZ.
4332  Observer.changingInstr(MI);
4333  MI.setDesc(TII.get(TargetOpcode::G_CTTZ));
4334  Observer.changedInstr(MI);
4335  return Legalized;
4336  }
4337  case TargetOpcode::G_CTTZ: {
4338  Register DstReg = MI.getOperand(0).getReg();
4339  Register SrcReg = MI.getOperand(1).getReg();
4340  LLT DstTy = MRI.getType(DstReg);
4341  LLT SrcTy = MRI.getType(SrcReg);
4342 
4343  unsigned Len = SrcTy.getSizeInBits();
4344  if (isSupported({TargetOpcode::G_CTTZ_ZERO_UNDEF, {DstTy, SrcTy}})) {
4345  // If CTTZ_ZERO_UNDEF is legal or custom, emit that and a select with
4346  // zero.
4347  auto CttzZU = MIRBuilder.buildCTTZ_ZERO_UNDEF(DstTy, SrcReg);
4348  auto Zero = MIRBuilder.buildConstant(SrcTy, 0);
4349  auto ICmp = MIRBuilder.buildICmp(
4350  CmpInst::ICMP_EQ, DstTy.changeElementSize(1), SrcReg, Zero);
4351  auto LenConst = MIRBuilder.buildConstant(DstTy, Len);
4352  MIRBuilder.buildSelect(DstReg, ICmp, LenConst, CttzZU);
4353  MI.eraseFromParent();
4354  return Legalized;
4355  }
4356  // for now, we use: { return popcount(~x & (x - 1)); }
4357  // unless the target has ctlz but not ctpop, in which case we use:
4358  // { return 32 - nlz(~x & (x-1)); }
4359  // Ref: "Hacker's Delight" by Henry Warren
4360  auto MIBCstNeg1 = MIRBuilder.buildConstant(Ty, -1);
4361  auto MIBNot = MIRBuilder.buildXor(Ty, SrcReg, MIBCstNeg1);
4362  auto MIBTmp = MIRBuilder.buildAnd(
4363  Ty, MIBNot, MIRBuilder.buildAdd(Ty, SrcReg, MIBCstNeg1));
4364  if (!isSupported({TargetOpcode::G_CTPOP, {Ty, Ty}}) &&
4365  isSupported({TargetOpcode::G_CTLZ, {Ty, Ty}})) {
4366  auto MIBCstLen = MIRBuilder.buildConstant(Ty, Len);
4367  MIRBuilder.buildSub(MI.getOperand(0), MIBCstLen,
4368  MIRBuilder.buildCTLZ(Ty, MIBTmp));
4369  MI.eraseFromParent();
4370  return Legalized;
4371  }
4372  MI.setDesc(TII.get(TargetOpcode::G_CTPOP));
4373  MI.getOperand(1).setReg(MIBTmp.getReg(0));
4374  return Legalized;
4375  }
4376  case TargetOpcode::G_CTPOP: {
4377  unsigned Size = Ty.getSizeInBits();
4379 
4380  // Count set bits in blocks of 2 bits. Default approach would be
4381  // B2Count = { val & 0x55555555 } + { (val >> 1) & 0x55555555 }
4382  // We use following formula instead:
4383  // B2Count = val - { (val >> 1) & 0x55555555 }
4384  // since it gives same result in blocks of 2 with one instruction less.
4385  auto C_1 = B.buildConstant(Ty, 1);
4386  auto B2Set1LoTo1Hi = B.buildLShr(Ty, MI.getOperand(1).getReg(), C_1);
4387  APInt B2Mask1HiTo0 = APInt::getSplat(Size, APInt(8, 0x55));
4388  auto C_B2Mask1HiTo0 = B.buildConstant(Ty, B2Mask1HiTo0);
4389  auto B2Count1Hi = B.buildAnd(Ty, B2Set1LoTo1Hi, C_B2Mask1HiTo0);
4390  auto B2Count = B.buildSub(Ty, MI.getOperand(1).getReg(), B2Count1Hi);
4391 
4392  // In order to get count in blocks of 4 add values from adjacent block of 2.
4393  // B4Count = { B2Count & 0x33333333 } + { (B2Count >> 2) & 0x33333333 }
4394  auto C_2 = B.buildConstant(Ty, 2);
4395  auto B4Set2LoTo2Hi = B.buildLShr(Ty, B2Count, C_2);
4396  APInt B4Mask2HiTo0 = APInt::getSplat(Size, APInt(8, 0x33));
4397  auto C_B4Mask2HiTo0 = B.buildConstant(Ty, B4Mask2HiTo0);
4398  auto B4HiB2Count = B.buildAnd(Ty, B4Set2LoTo2Hi, C_B4Mask2HiTo0);
4399  auto B4LoB2Count = B.buildAnd(Ty, B2Count, C_B4Mask2HiTo0);
4400  auto B4Count = B.buildAdd(Ty, B4HiB2Count, B4LoB2Count);
4401 
4402  // For count in blocks of 8 bits we don't have to mask high 4 bits before
4403  // addition since count value sits in range {0,...,8} and 4 bits are enough
4404  // to hold such binary values. After addition high 4 bits still hold count
4405  // of set bits in high 4 bit block, set them to zero and get 8 bit result.
4406  // B8Count = { B4Count + (B4Count >> 4) } & 0x0F0F0F0F
4407  auto C_4 = B.buildConstant(Ty, 4);
4408  auto B8HiB4Count = B.buildLShr(Ty, B4Count, C_4);
4409  auto B8CountDirty4Hi = B.buildAdd(Ty, B8HiB4Count, B4Count);
4410  APInt B8Mask4HiTo0 = APInt::getSplat(Size, APInt(8, 0x0F));
4411  auto C_B8Mask4HiTo0 = B.buildConstant(Ty, B8Mask4HiTo0);
4412  auto B8Count = B.buildAnd(Ty, B8CountDirty4Hi, C_B8Mask4HiTo0);
4413 
4414  assert(Size<=128 && "Scalar size is too large for CTPOP lower algorithm");
4415  // 8 bits can hold CTPOP result of 128 bit int or smaller. Mul with this
4416  // bitmask will set 8 msb in ResTmp to sum of all B8Counts in 8 bit blocks.
4417  auto MulMask = B.buildConstant(Ty, APInt::getSplat(Size, APInt(8, 0x01)));
4418  auto ResTmp = B.buildMul(Ty, B8Count, MulMask);
4419 
4420  // Shift count result from 8 high bits to low bits.
4421  auto C_SizeM8 = B.buildConstant(Ty, Size - 8);
4422  B.buildLShr(MI.getOperand(0).getReg(), ResTmp, C_SizeM8);
4423 
4424  MI.eraseFromParent();
4425  return Legalized;
4426  }
4427  }
4428 }
4429 
4430 // Expand s32 = G_UITOFP s64 using bit operations to an IEEE float
4431 // representation.
4434  Register Dst = MI.getOperand(0).getReg();
4435  Register Src = MI.getOperand(1).getReg();
4436  const LLT S64 = LLT::scalar(64);
4437  const LLT S32 = LLT::scalar(32);
4438  const LLT S1 = LLT::scalar(1);
4439 
4440  assert(MRI.getType(Src) == S64 && MRI.getType(Dst) == S32);
4441 
4442  // unsigned cul2f(ulong u) {
4443  // uint lz = clz(u);
4444  // uint e = (u != 0) ? 127U + 63U - lz : 0;
4445  // u = (u << lz) & 0x7fffffffffffffffUL;
4446  // ulong t = u & 0xffffffffffUL;
4447  // uint v = (e << 23) | (uint)(u >> 40);
4448  // uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
4449  // return as_float(v + r);
4450  // }
4451 
4452  auto Zero32 = MIRBuilder.buildConstant(S32, 0);
4453  auto Zero64 = MIRBuilder.buildConstant(S64, 0);
4454 
4455  auto LZ = MIRBuilder.buildCTLZ_ZERO_UNDEF(S32, Src);
4456 
4457  auto K = MIRBuilder.buildConstant(S32, 127U + 63U);
4458  auto Sub = MIRBuilder.buildSub(S32, K, LZ);
4459 
4460  auto NotZero = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, Src, Zero64);
4461  auto E = MIRBuilder.buildSelect(S32, NotZero, Sub, Zero32);
4462 
4463  auto Mask0 = MIRBuilder.buildConstant(S64, (-1ULL) >> 1);
4464  auto ShlLZ = MIRBuilder.buildShl(S64, Src, LZ);
4465 
4466  auto U = MIRBuilder.buildAnd(S64, ShlLZ, Mask0);
4467 
4468  auto Mask1 = MIRBuilder.buildConstant(S64, 0xffffffffffULL);
4469  auto T = MIRBuilder.buildAnd(S64, U, Mask1);
4470 
4471  auto UShl = MIRBuilder.buildLShr(S64, U, MIRBuilder.buildConstant(S64, 40));
4472  auto ShlE = MIRBuilder.buildShl(S32, E, MIRBuilder.buildConstant(S32, 23));
4473  auto V = MIRBuilder.buildOr(S32, ShlE, MIRBuilder.buildTrunc(S32, UShl));
4474 
4475  auto C = MIRBuilder.buildConstant(S64, 0x8000000000ULL);
4476  auto RCmp = MIRBuilder.buildICmp(CmpInst::ICMP_UGT, S1, T, C);
4477  auto TCmp = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1, T, C);
4478  auto One = MIRBuilder.buildConstant(S32, 1);
4479 
4480  auto VTrunc1 = MIRBuilder.buildAnd(S32, V, One);
4481  auto Select0 = MIRBuilder.buildSelect(S32, TCmp, VTrunc1, Zero32);
4482  auto R = MIRBuilder.buildSelect(S32, RCmp, One, Select0);
4483  MIRBuilder.buildAdd(Dst, V, R);
4484 
4485  MI.eraseFromParent();
4486  return Legalized;
4487 }
4488 
4490 LegalizerHelper::lowerUITOFP(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
4491  Register Dst = MI.getOperand(0).getReg();
4492  Register Src = MI.getOperand(1).getReg();
4493  LLT DstTy = MRI.getType(Dst);
4494  LLT SrcTy = MRI.getType(Src);
4495 
4496  if (SrcTy == LLT::scalar(1)) {
4497  auto True = MIRBuilder.buildFConstant(DstTy, 1.0);
4498  auto False = MIRBuilder.buildFConstant(DstTy, 0.0);
4499  MIRBuilder.buildSelect(Dst, Src, True, False);
4500  MI.eraseFromParent();
4501  return Legalized;
4502  }
4503 
4504  if (SrcTy != LLT::scalar(64))
4505  return UnableToLegalize;
4506 
4507  if (DstTy == LLT::scalar(32)) {
4508  // TODO: SelectionDAG has several alternative expansions to port which may
4509  // be more reasonble depending on the available instructions. If a target
4510  // has sitofp, does not have CTLZ, or can efficiently use f64 as an
4511  // intermediate type, this is probably worse.
4512  return lowerU64ToF32BitOps(MI);
4513  }
4514 
4515  return UnableToLegalize;
4516 }
4517 
4519 LegalizerHelper::lowerSITOFP(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
4520  Register Dst = MI.getOperand(0).getReg();
4521  Register Src = MI.getOperand(1).getReg();
4522  LLT DstTy = MRI.getType(Dst);
4523  LLT SrcTy = MRI.getType(Src);
4524 
4525  const LLT S64 = LLT::scalar(64);
4526  const LLT S32 = LLT::scalar(32);
4527  const LLT S1 = LLT::scalar(1);
4528 
4529  if (SrcTy == S1) {
4530  auto True = MIRBuilder.buildFConstant(DstTy, -1.0);
4531  auto False = MIRBuilder.buildFConstant(DstTy, 0.0);
4532  MIRBuilder.buildSelect(Dst, Src, True, False);
4533  MI.eraseFromParent();
4534  return Legalized;
4535  }
4536 
4537  if (SrcTy != S64)
4538  return UnableToLegalize;
4539 
4540  if (DstTy == S32) {
4541  // signed cl2f(long l) {
4542  // long s = l >> 63;
4543  // float r = cul2f((l + s) ^ s);
4544  // return s ? -r : r;
4545  // }
4546  Register L = Src;
4547  auto SignBit = MIRBuilder.buildConstant(S64, 63);
4548  auto S = MIRBuilder.buildAShr(S64, L, SignBit);
4549 
4550  auto LPlusS = MIRBuilder.buildAdd(S64, L, S);
4551  auto Xor = MIRBuilder.buildXor(S64, LPlusS, S);
4552  auto R = MIRBuilder.buildUITOFP(S32, Xor);
4553 
4554  auto RNeg = MIRBuilder.buildFNeg(S32, R);
4555  auto SignNotZero = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, S,
4556  MIRBuilder.buildConstant(S64, 0));
4557  MIRBuilder.buildSelect(Dst, SignNotZero, RNeg, R);
4558  MI.eraseFromParent();
4559  return Legalized;
4560  }
4561 
4562  return UnableToLegalize;
4563 }
4564 
4566 LegalizerHelper::lowerFPTOUI(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
4567  Register Dst = MI.getOperand(0).getReg();
4568  Register Src = MI.getOperand(1).getReg();
4569  LLT DstTy = MRI.getType(Dst);
4570  LLT SrcTy = MRI.getType(Src);
4571  const LLT S64 = LLT::scalar(64);
4572  const LLT S32 = LLT::scalar(32);
4573 
4574  if (SrcTy != S64 && SrcTy != S32)
4575  return UnableToLegalize;
4576  if (DstTy != S32 && DstTy != S64)
4577  return UnableToLegalize;
4578 
4579  // FPTOSI gives same result as FPTOUI for positive signed integers.
4580  // FPTOUI needs to deal with fp values that convert to unsigned integers
4581  // greater or equal to 2^31 for float or 2^63 for double. For brevity 2^Exp.
4582 
4583  APInt TwoPExpInt = APInt::getSignMask(DstTy.getSizeInBits());
4584  APFloat TwoPExpFP(SrcTy.getSizeInBits() == 32 ? APFloat::IEEEsingle()
4585  : APFloat::IEEEdouble(),
4587  TwoPExpFP.convertFromAPInt(TwoPExpInt, false, APFloat::rmNearestTiesToEven);
4588 
4589  MachineInstrBuilder FPTOSI = MIRBuilder.buildFPTOSI(DstTy, Src);
4590 
4592  // For fp Value greater or equal to Threshold(2^Exp), we use FPTOSI on
4593  // (Value - 2^Exp) and add 2^Exp by setting highest bit in result to 1.
4594  MachineInstrBuilder FSub = MIRBuilder.buildFSub(SrcTy, Src, Threshold);
4595  MachineInstrBuilder ResLowBits = MIRBuilder.buildFPTOSI(DstTy, FSub);
4596  MachineInstrBuilder ResHighBit = MIRBuilder.buildConstant(DstTy, TwoPExpInt);
4597  MachineInstrBuilder Res = MIRBuilder.buildXor(DstTy, ResLowBits, ResHighBit);
4598 
4599  const LLT S1 = LLT::scalar(1);
4600 
4602  MIRBuilder.buildFCmp(CmpInst::FCMP_ULT, S1, Src, Threshold);
4603  MIRBuilder.buildSelect(Dst, FCMP, FPTOSI, Res);
4604 
4605  MI.eraseFromParent();
4606  return Legalized;
4607 }
4608 
4610  Register Dst = MI.getOperand(0).getReg();
4611  Register Src = MI.getOperand(1).getReg();
4612  LLT DstTy = MRI.getType(Dst);
4613  LLT SrcTy = MRI.getType(Src);
4614  const LLT S64 = LLT::scalar(64);
4615  const LLT S32 = LLT::scalar(32);
4616 
4617  // FIXME: Only f32 to i64 conversions are supported.
4618  if (SrcTy.getScalarType() != S32 || DstTy.getScalarType() != S64)
4619  return UnableToLegalize;
4620 
4621  // Expand f32 -> i64 conversion
4622  // This algorithm comes from compiler-rt's implementation of fixsfdi:
4623  // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/builtins/fixsfdi.c
4624 
4625  unsigned SrcEltBits = SrcTy.getScalarSizeInBits();
4626 
4627  auto ExponentMask = MIRBuilder.buildConstant(SrcTy, 0x7F800000);
4628  auto ExponentLoBit = MIRBuilder.buildConstant(SrcTy, 23);
4629 
4630  auto AndExpMask = MIRBuilder.buildAnd(SrcTy, Src, ExponentMask);
4631  auto ExponentBits = MIRBuilder.buildLShr(SrcTy, AndExpMask, ExponentLoBit);
4632 
4633  auto SignMask = MIRBuilder.buildConstant(SrcTy,
4634  APInt::getSignMask(SrcEltBits));
4635  auto AndSignMask = MIRBuilder.buildAnd(SrcTy, Src, SignMask);
4636  auto SignLowBit = MIRBuilder.buildConstant(SrcTy, SrcEltBits - 1);
4637  auto Sign = MIRBuilder.buildAShr(SrcTy, AndSignMask, SignLowBit);
4638  Sign = MIRBuilder.buildSExt(DstTy, Sign);
4639 
4640  auto MantissaMask = MIRBuilder.buildConstant(SrcTy, 0x007FFFFF);
4641  auto AndMantissaMask = MIRBuilder.buildAnd(SrcTy, Src, MantissaMask);
4642  auto K = MIRBuilder.buildConstant(SrcTy, 0x00800000);
4643 
4644  auto R = MIRBuilder.buildOr(SrcTy, AndMantissaMask, K);
4645  R = MIRBuilder.buildZExt(DstTy, R);
4646 
4647  auto Bias = MIRBuilder.buildConstant(SrcTy, 127);
4648  auto Exponent = MIRBuilder.buildSub(SrcTy, ExponentBits, Bias);
4649  auto SubExponent = MIRBuilder.buildSub(SrcTy, Exponent, ExponentLoBit);
4650  auto ExponentSub = MIRBuilder.buildSub(SrcTy, ExponentLoBit, Exponent);
4651 
4652  auto Shl = MIRBuilder.buildShl(DstTy, R, SubExponent);
4653  auto Srl = MIRBuilder.buildLShr(DstTy, R, ExponentSub);
4654 
4655  const LLT S1 = LLT::scalar(1);
4656  auto CmpGt = MIRBuilder.buildICmp(CmpInst::ICMP_SGT,
4657  S1, Exponent, ExponentLoBit);
4658 
4659  R = MIRBuilder.buildSelect(DstTy, CmpGt, Shl, Srl);
4660 
4661  auto XorSign = MIRBuilder.buildXor(DstTy, R, Sign);
4662  auto Ret = MIRBuilder.buildSub(DstTy, XorSign, Sign);
4663 
4664  auto ZeroSrcTy = MIRBuilder.buildConstant(SrcTy, 0);
4665 
4666  auto ExponentLt0 = MIRBuilder.buildICmp(CmpInst::ICMP_SLT,
4667  S1, Exponent, ZeroSrcTy);
4668 
4669  auto ZeroDstTy = MIRBuilder.buildConstant(DstTy, 0);
4670  MIRBuilder.buildSelect(Dst, ExponentLt0, ZeroDstTy, Ret);
4671 
4672  MI.eraseFromParent();
4673  return Legalized;
4674 }
4675 
4676 // f64 -> f16 conversion using round-to-nearest-even rounding mode.
4679  Register Dst = MI.getOperand(0).getReg();
4680  Register Src = MI.getOperand(1).getReg();
4681 
4682  if (MRI.getType(Src).isVector()) // TODO: Handle vectors directly.
4683  return UnableToLegalize;
4684 
4685  const unsigned ExpMask = 0x7ff;
4686  const unsigned ExpBiasf64 = 1023;
4687  const unsigned ExpBiasf16 = 15;
4688  const LLT S32 = LLT::scalar(32);
4689  const LLT S1 = LLT::scalar(1);
4690 
4691  auto Unmerge = MIRBuilder.buildUnmerge(S32, Src);
4692  Register U = Unmerge.getReg(0);
4693  Register UH = Unmerge.getReg(1);
4694 
4695  auto E = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 20));
4696  E = MIRBuilder.buildAnd(S32, E, MIRBuilder.buildConstant(S32, ExpMask));
4697 
4698  // Subtract the fp64 exponent bias (1023) to get the real exponent and
4699  // add the f16 bias (15) to get the biased exponent for the f16 format.
4700  E = MIRBuilder.buildAdd(
4701  S32, E, MIRBuilder.buildConstant(S32, -ExpBiasf64 + ExpBiasf16));
4702 
4703  auto M = MIRBuilder.buildLShr(S32, UH, MIRBuilder.buildConstant(S32, 8));
4704  M = MIRBuilder.buildAnd(S32, M, MIRBuilder.buildConstant(S32, 0xffe));
4705 
4706  auto MaskedSig = MIRBuilder.buildAnd(S32, UH,
4707  MIRBuilder.buildConstant(S32, 0x1ff));
4708  MaskedSig = MIRBuilder.buildOr(S32, MaskedSig, U);
4709 
4710  auto Zero = MIRBuilder.buildConstant(S32, 0);
4711  auto SigCmpNE0 = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, MaskedSig, Zero);
4712  auto Lo40Set = MIRBuilder.buildZExt(S32, SigCmpNE0);
4713  M = MIRBuilder.buildOr(S32, M, Lo40Set);
4714 
4715  // (M != 0 ? 0x0200 : 0) | 0x7c00;
4716  auto Bits0x200 = MIRBuilder.buildConstant(S32, 0x0200);
4717  auto CmpM_NE0 = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1, M, Zero);
4718  auto SelectCC = MIRBuilder.buildSelect(S32, CmpM_NE0, Bits0x200, Zero);
4719 
4720  auto Bits0x7c00 = MIRBuilder.buildConstant(S32, 0x7c00);
4721  auto I = MIRBuilder.buildOr(S32, SelectCC, Bits0x7c00);
4722 
4723  // N = M | (E << 12);
4724  auto EShl12 = MIRBuilder.buildShl(S32, E, MIRBuilder.buildConstant(S32, 12));
4725  auto N = MIRBuilder.buildOr(S32, M, EShl12);
4726 
4727  // B = clamp(1-E, 0, 13);
4728  auto One = MIRBuilder.buildConstant(S32, 1);
4729  auto OneSubExp = MIRBuilder.buildSub(S32, One, E);
4730  auto B = MIRBuilder.buildSMax(S32, OneSubExp, Zero);
4731  B = MIRBuilder.buildSMin(S32, B, MIRBuilder.buildConstant(S32, 13));
4732 
4733  auto SigSetHigh = MIRBuilder.buildOr(S32, M,
4734  MIRBuilder.buildConstant(S32, 0x1000));
4735 
4736  auto D = MIRBuilder.buildLShr(S32, SigSetHigh, B);
4737  auto D0 = MIRBuilder.buildShl(S32, D, B);
4738 
4739  auto D0_NE_SigSetHigh = MIRBuilder.buildICmp(CmpInst::ICMP_NE, S1,
4740  D0, SigSetHigh);
4741  auto D1 = MIRBuilder.buildZExt(S32, D0_NE_SigSetHigh);
4742  D = MIRBuilder.buildOr(S32, D, D1);
4743 
4744  auto CmpELtOne = MIRBuilder.buildICmp(CmpInst::ICMP_SLT, S1, E, One);
4745  auto V = MIRBuilder.buildSelect(S32, CmpELtOne, D, N);
4746 
4747  auto VLow3 = MIRBuilder.buildAnd(S32, V, MIRBuilder.buildConstant(S32, 7));
4748  V = MIRBuilder.buildLShr(S32, V, MIRBuilder.buildConstant(S32, 2));
4749 
4750  auto VLow3Eq3 = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, S1, VLow3,
4751  MIRBuilder.buildConstant(S32, 3));
4752  auto V0 = MIRBuilder.