LLVM  5.0.0
LegalizerHelper.cpp
Go to the documentation of this file.
1 //===-- llvm/CodeGen/GlobalISel/LegalizerHelper.cpp -----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file This file implements the LegalizerHelper class to legalize
11 /// individual instructions and the LegalizeMachineIR wrapper pass for the
12 /// primary legalization.
13 //
14 //===----------------------------------------------------------------------===//
15 
20 #include "llvm/Support/Debug.h"
24 
25 #include <sstream>
26 
27 #define DEBUG_TYPE "legalizer"
28 
29 using namespace llvm;
30 
32  : MRI(MF.getRegInfo()), LI(*MF.getSubtarget().getLegalizerInfo()) {
33  MIRBuilder.setMF(MF);
34 }
35 
38  DEBUG(dbgs() << "Legalizing: "; MI.print(dbgs()));
39 
40  auto Action = LI.getAction(MI, MRI);
41  switch (std::get<0>(Action)) {
43  DEBUG(dbgs() << ".. Already legal\n");
44  return AlreadyLegal;
46  DEBUG(dbgs() << ".. Convert to libcall\n");
47  return libcall(MI);
49  DEBUG(dbgs() << ".. Narrow scalar\n");
50  return narrowScalar(MI, std::get<1>(Action), std::get<2>(Action));
52  DEBUG(dbgs() << ".. Widen scalar\n");
53  return widenScalar(MI, std::get<1>(Action), std::get<2>(Action));
55  DEBUG(dbgs() << ".. Lower\n");
56  return lower(MI, std::get<1>(Action), std::get<2>(Action));
58  DEBUG(dbgs() << ".. Reduce number of elements\n");
59  return fewerElementsVector(MI, std::get<1>(Action), std::get<2>(Action));
61  DEBUG(dbgs() << ".. Custom legalization\n");
62  return LI.legalizeCustom(MI, MRI, MIRBuilder) ? Legalized
64  default:
65  DEBUG(dbgs() << ".. Unable to legalize\n");
66  return UnableToLegalize;
67  }
68 }
69 
70 void LegalizerHelper::extractParts(unsigned Reg, LLT Ty, int NumParts,
72  for (int i = 0; i < NumParts; ++i)
74  MIRBuilder.buildUnmerge(VRegs, Reg);
75 }
76 
77 static RTLIB::Libcall getRTLibDesc(unsigned Opcode, unsigned Size) {
78  switch (Opcode) {
79  case TargetOpcode::G_SDIV:
80  assert(Size == 32 && "Unsupported size");
81  return RTLIB::SDIV_I32;
82  case TargetOpcode::G_UDIV:
83  assert(Size == 32 && "Unsupported size");
84  return RTLIB::UDIV_I32;
85  case TargetOpcode::G_SREM:
86  assert(Size == 32 && "Unsupported size");
87  return RTLIB::SREM_I32;
88  case TargetOpcode::G_UREM:
89  assert(Size == 32 && "Unsupported size");
90  return RTLIB::UREM_I32;
91  case TargetOpcode::G_FADD:
92  assert((Size == 32 || Size == 64) && "Unsupported size");
93  return Size == 64 ? RTLIB::ADD_F64 : RTLIB::ADD_F32;
94  case TargetOpcode::G_FREM:
95  return Size == 64 ? RTLIB::REM_F64 : RTLIB::REM_F32;
96  case TargetOpcode::G_FPOW:
97  return Size == 64 ? RTLIB::POW_F64 : RTLIB::POW_F32;
98  }
99  llvm_unreachable("Unknown libcall function");
100 }
101 
104  const CallLowering::ArgInfo &Result,
106  auto &CLI = *MIRBuilder.getMF().getSubtarget().getCallLowering();
107  auto &TLI = *MIRBuilder.getMF().getSubtarget().getTargetLowering();
108  const char *Name = TLI.getLibcallName(Libcall);
109 
110  MIRBuilder.getMF().getFrameInfo().setHasCalls(true);
111  if (!CLI.lowerCall(MIRBuilder, TLI.getLibcallCallingConv(Libcall),
112  MachineOperand::CreateES(Name), Result, Args))
114 
116 }
117 
120  Type *OpType) {
121  auto Libcall = getRTLibDesc(MI.getOpcode(), Size);
122  return createLibcall(MIRBuilder, Libcall, {MI.getOperand(0).getReg(), OpType},
123  {{MI.getOperand(1).getReg(), OpType},
124  {MI.getOperand(2).getReg(), OpType}});
125 }
126 
129  LLT LLTy = MRI.getType(MI.getOperand(0).getReg());
130  unsigned Size = LLTy.getSizeInBits();
131  auto &Ctx = MIRBuilder.getMF().getFunction()->getContext();
132 
133  MIRBuilder.setInstr(MI);
134 
135  switch (MI.getOpcode()) {
136  default:
137  return UnableToLegalize;
138  case TargetOpcode::G_SDIV:
139  case TargetOpcode::G_UDIV:
140  case TargetOpcode::G_SREM:
141  case TargetOpcode::G_UREM: {
142  Type *HLTy = Type::getInt32Ty(Ctx);
143  auto Status = simpleLibcall(MI, MIRBuilder, Size, HLTy);
144  if (Status != Legalized)
145  return Status;
146  break;
147  }
148  case TargetOpcode::G_FADD:
149  case TargetOpcode::G_FPOW:
150  case TargetOpcode::G_FREM: {
151  Type *HLTy = Size == 64 ? Type::getDoubleTy(Ctx) : Type::getFloatTy(Ctx);
152  auto Status = simpleLibcall(MI, MIRBuilder, Size, HLTy);
153  if (Status != Legalized)
154  return Status;
155  break;
156  }
157  }
158 
159  MI.eraseFromParent();
160  return Legalized;
161 }
162 
164  unsigned TypeIdx,
165  LLT NarrowTy) {
166  // FIXME: Don't know how to handle secondary types yet.
167  if (TypeIdx != 0 && MI.getOpcode() != TargetOpcode::G_EXTRACT)
168  return UnableToLegalize;
169 
170  MIRBuilder.setInstr(MI);
171 
172  switch (MI.getOpcode()) {
173  default:
174  return UnableToLegalize;
175  case TargetOpcode::G_IMPLICIT_DEF: {
176  int NumParts = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits() /
177  NarrowTy.getSizeInBits();
178 
179  SmallVector<unsigned, 2> DstRegs;
180  for (int i = 0; i < NumParts; ++i) {
181  unsigned Dst = MRI.createGenericVirtualRegister(NarrowTy);
182  MIRBuilder.buildUndef(Dst);
183  DstRegs.push_back(Dst);
184  }
185  MIRBuilder.buildMerge(MI.getOperand(0).getReg(), DstRegs);
186  MI.eraseFromParent();
187  return Legalized;
188  }
189  case TargetOpcode::G_ADD: {
190  // Expand in terms of carry-setting/consuming G_ADDE instructions.
191  int NumParts = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits() /
192  NarrowTy.getSizeInBits();
193 
194  SmallVector<unsigned, 2> Src1Regs, Src2Regs, DstRegs;
195  extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, Src1Regs);
196  extractParts(MI.getOperand(2).getReg(), NarrowTy, NumParts, Src2Regs);
197 
198  unsigned CarryIn = MRI.createGenericVirtualRegister(LLT::scalar(1));
199  MIRBuilder.buildConstant(CarryIn, 0);
200 
201  for (int i = 0; i < NumParts; ++i) {
202  unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy);
203  unsigned CarryOut = MRI.createGenericVirtualRegister(LLT::scalar(1));
204 
205  MIRBuilder.buildUAdde(DstReg, CarryOut, Src1Regs[i],
206  Src2Regs[i], CarryIn);
207 
208  DstRegs.push_back(DstReg);
209  CarryIn = CarryOut;
210  }
211  unsigned DstReg = MI.getOperand(0).getReg();
212  MIRBuilder.buildMerge(DstReg, DstRegs);
213  MI.eraseFromParent();
214  return Legalized;
215  }
216  case TargetOpcode::G_EXTRACT: {
217  if (TypeIdx != 1)
218  return UnableToLegalize;
219 
220  int64_t NarrowSize = NarrowTy.getSizeInBits();
221  int NumParts =
222  MRI.getType(MI.getOperand(1).getReg()).getSizeInBits() / NarrowSize;
223 
224  SmallVector<unsigned, 2> SrcRegs, DstRegs;
225  SmallVector<uint64_t, 2> Indexes;
226  extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
227 
228  unsigned OpReg = MI.getOperand(0).getReg();
229  int64_t OpStart = MI.getOperand(2).getImm();
230  int64_t OpSize = MRI.getType(OpReg).getSizeInBits();
231  for (int i = 0; i < NumParts; ++i) {
232  unsigned SrcStart = i * NarrowSize;
233 
234  if (SrcStart + NarrowSize <= OpStart || SrcStart >= OpStart + OpSize) {
235  // No part of the extract uses this subregister, ignore it.
236  continue;
237  } else if (SrcStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
238  // The entire subregister is extracted, forward the value.
239  DstRegs.push_back(SrcRegs[i]);
240  continue;
241  }
242 
243  // OpSegStart is where this destination segment would start in OpReg if it
244  // extended infinitely in both directions.
245  int64_t ExtractOffset, SegSize;
246  if (OpStart < SrcStart) {
247  ExtractOffset = 0;
248  SegSize = std::min(NarrowSize, OpStart + OpSize - SrcStart);
249  } else {
250  ExtractOffset = OpStart - SrcStart;
251  SegSize = std::min(SrcStart + NarrowSize - OpStart, OpSize);
252  }
253 
254  unsigned SegReg = SrcRegs[i];
255  if (ExtractOffset != 0 || SegSize != NarrowSize) {
256  // A genuine extract is needed.
257  SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
258  MIRBuilder.buildExtract(SegReg, SrcRegs[i], ExtractOffset);
259  }
260 
261  DstRegs.push_back(SegReg);
262  }
263 
264  MIRBuilder.buildMerge(MI.getOperand(0).getReg(), DstRegs);
265  MI.eraseFromParent();
266  return Legalized;
267  }
268  case TargetOpcode::G_INSERT: {
269  if (TypeIdx != 0)
270  return UnableToLegalize;
271 
272  int64_t NarrowSize = NarrowTy.getSizeInBits();
273  int NumParts =
274  MRI.getType(MI.getOperand(0).getReg()).getSizeInBits() / NarrowSize;
275 
276  SmallVector<unsigned, 2> SrcRegs, DstRegs;
277  SmallVector<uint64_t, 2> Indexes;
278  extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
279 
280  unsigned OpReg = MI.getOperand(2).getReg();
281  int64_t OpStart = MI.getOperand(3).getImm();
282  int64_t OpSize = MRI.getType(OpReg).getSizeInBits();
283  for (int i = 0; i < NumParts; ++i) {
284  unsigned DstStart = i * NarrowSize;
285 
286  if (DstStart + NarrowSize <= OpStart || DstStart >= OpStart + OpSize) {
287  // No part of the insert affects this subregister, forward the original.
288  DstRegs.push_back(SrcRegs[i]);
289  continue;
290  } else if (DstStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
291  // The entire subregister is defined by this insert, forward the new
292  // value.
293  DstRegs.push_back(OpReg);
294  continue;
295  }
296 
297  // OpSegStart is where this destination segment would start in OpReg if it
298  // extended infinitely in both directions.
299  int64_t ExtractOffset, InsertOffset, SegSize;
300  if (OpStart < DstStart) {
301  InsertOffset = 0;
302  ExtractOffset = DstStart - OpStart;
303  SegSize = std::min(NarrowSize, OpStart + OpSize - DstStart);
304  } else {
305  InsertOffset = OpStart - DstStart;
306  ExtractOffset = 0;
307  SegSize =
308  std::min(NarrowSize - InsertOffset, OpStart + OpSize - DstStart);
309  }
310 
311  unsigned SegReg = OpReg;
312  if (ExtractOffset != 0 || SegSize != OpSize) {
313  // A genuine extract is needed.
314  SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
315  MIRBuilder.buildExtract(SegReg, OpReg, ExtractOffset);
316  }
317 
318  unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy);
319  MIRBuilder.buildInsert(DstReg, SrcRegs[i], SegReg, InsertOffset);
320  DstRegs.push_back(DstReg);
321  }
322 
323  assert(DstRegs.size() == (unsigned)NumParts && "not all parts covered");
324  MIRBuilder.buildMerge(MI.getOperand(0).getReg(), DstRegs);
325  MI.eraseFromParent();
326  return Legalized;
327  }
328  case TargetOpcode::G_LOAD: {
329  unsigned NarrowSize = NarrowTy.getSizeInBits();
330  int NumParts =
331  MRI.getType(MI.getOperand(0).getReg()).getSizeInBits() / NarrowSize;
332  LLT OffsetTy = LLT::scalar(
333  MRI.getType(MI.getOperand(1).getReg()).getScalarSizeInBits());
334 
335  SmallVector<unsigned, 2> DstRegs;
336  for (int i = 0; i < NumParts; ++i) {
337  unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy);
338  unsigned SrcReg = 0;
339  unsigned Adjustment = i * NarrowSize / 8;
340 
341  MIRBuilder.materializeGEP(SrcReg, MI.getOperand(1).getReg(), OffsetTy,
342  Adjustment);
343 
344  // TODO: This is conservatively correct, but we probably want to split the
345  // memory operands in the future.
346  MIRBuilder.buildLoad(DstReg, SrcReg, **MI.memoperands_begin());
347 
348  DstRegs.push_back(DstReg);
349  }
350  unsigned DstReg = MI.getOperand(0).getReg();
351  MIRBuilder.buildMerge(DstReg, DstRegs);
352  MI.eraseFromParent();
353  return Legalized;
354  }
355  case TargetOpcode::G_STORE: {
356  unsigned NarrowSize = NarrowTy.getSizeInBits();
357  int NumParts =
358  MRI.getType(MI.getOperand(0).getReg()).getSizeInBits() / NarrowSize;
359  LLT OffsetTy = LLT::scalar(
360  MRI.getType(MI.getOperand(1).getReg()).getScalarSizeInBits());
361 
362  SmallVector<unsigned, 2> SrcRegs;
363  extractParts(MI.getOperand(0).getReg(), NarrowTy, NumParts, SrcRegs);
364 
365  for (int i = 0; i < NumParts; ++i) {
366  unsigned DstReg = 0;
367  unsigned Adjustment = i * NarrowSize / 8;
368 
369  MIRBuilder.materializeGEP(DstReg, MI.getOperand(1).getReg(), OffsetTy,
370  Adjustment);
371 
372  // TODO: This is conservatively correct, but we probably want to split the
373  // memory operands in the future.
374  MIRBuilder.buildStore(SrcRegs[i], DstReg, **MI.memoperands_begin());
375  }
376  MI.eraseFromParent();
377  return Legalized;
378  }
379  case TargetOpcode::G_CONSTANT: {
380  unsigned NarrowSize = NarrowTy.getSizeInBits();
381  int NumParts =
382  MRI.getType(MI.getOperand(0).getReg()).getSizeInBits() / NarrowSize;
383  const APInt &Cst = MI.getOperand(1).getCImm()->getValue();
385 
386  SmallVector<unsigned, 2> DstRegs;
387  for (int i = 0; i < NumParts; ++i) {
388  unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy);
389  ConstantInt *CI =
390  ConstantInt::get(Ctx, Cst.lshr(NarrowSize * i).trunc(NarrowSize));
391  MIRBuilder.buildConstant(DstReg, *CI);
392  DstRegs.push_back(DstReg);
393  }
394  unsigned DstReg = MI.getOperand(0).getReg();
395  MIRBuilder.buildMerge(DstReg, DstRegs);
396  MI.eraseFromParent();
397  return Legalized;
398  }
399  }
400 }
401 
403 LegalizerHelper::widenScalar(MachineInstr &MI, unsigned TypeIdx, LLT WideTy) {
404  MIRBuilder.setInstr(MI);
405 
406  switch (MI.getOpcode()) {
407  default:
408  return UnableToLegalize;
409  case TargetOpcode::G_ADD:
410  case TargetOpcode::G_AND:
411  case TargetOpcode::G_MUL:
412  case TargetOpcode::G_OR:
413  case TargetOpcode::G_XOR:
414  case TargetOpcode::G_SUB:
415  case TargetOpcode::G_SHL: {
416  // Perform operation at larger width (any extension is fine here, high bits
417  // don't affect the result) and then truncate the result back to the
418  // original type.
419  unsigned Src1Ext = MRI.createGenericVirtualRegister(WideTy);
420  unsigned Src2Ext = MRI.createGenericVirtualRegister(WideTy);
421  MIRBuilder.buildAnyExt(Src1Ext, MI.getOperand(1).getReg());
422  MIRBuilder.buildAnyExt(Src2Ext, MI.getOperand(2).getReg());
423 
424  unsigned DstExt = MRI.createGenericVirtualRegister(WideTy);
426  .addDef(DstExt)
427  .addUse(Src1Ext)
428  .addUse(Src2Ext);
429 
430  MIRBuilder.buildTrunc(MI.getOperand(0).getReg(), DstExt);
431  MI.eraseFromParent();
432  return Legalized;
433  }
434  case TargetOpcode::G_SDIV:
435  case TargetOpcode::G_UDIV:
436  case TargetOpcode::G_SREM:
437  case TargetOpcode::G_UREM:
438  case TargetOpcode::G_ASHR:
439  case TargetOpcode::G_LSHR: {
440  unsigned ExtOp = MI.getOpcode() == TargetOpcode::G_SDIV ||
441  MI.getOpcode() == TargetOpcode::G_SREM ||
442  MI.getOpcode() == TargetOpcode::G_ASHR
443  ? TargetOpcode::G_SEXT
444  : TargetOpcode::G_ZEXT;
445 
446  unsigned LHSExt = MRI.createGenericVirtualRegister(WideTy);
447  MIRBuilder.buildInstr(ExtOp).addDef(LHSExt).addUse(
448  MI.getOperand(1).getReg());
449 
450  unsigned RHSExt = MRI.createGenericVirtualRegister(WideTy);
451  MIRBuilder.buildInstr(ExtOp).addDef(RHSExt).addUse(
452  MI.getOperand(2).getReg());
453 
454  unsigned ResExt = MRI.createGenericVirtualRegister(WideTy);
456  .addDef(ResExt)
457  .addUse(LHSExt)
458  .addUse(RHSExt);
459 
460  MIRBuilder.buildTrunc(MI.getOperand(0).getReg(), ResExt);
461  MI.eraseFromParent();
462  return Legalized;
463  }
464  case TargetOpcode::G_SELECT: {
465  if (TypeIdx != 0)
466  return UnableToLegalize;
467 
468  // Perform operation at larger width (any extension is fine here, high bits
469  // don't affect the result) and then truncate the result back to the
470  // original type.
471  unsigned Src1Ext = MRI.createGenericVirtualRegister(WideTy);
472  unsigned Src2Ext = MRI.createGenericVirtualRegister(WideTy);
473  MIRBuilder.buildAnyExt(Src1Ext, MI.getOperand(2).getReg());
474  MIRBuilder.buildAnyExt(Src2Ext, MI.getOperand(3).getReg());
475 
476  unsigned DstExt = MRI.createGenericVirtualRegister(WideTy);
477  MIRBuilder.buildInstr(TargetOpcode::G_SELECT)
478  .addDef(DstExt)
479  .addReg(MI.getOperand(1).getReg())
480  .addUse(Src1Ext)
481  .addUse(Src2Ext);
482 
483  MIRBuilder.buildTrunc(MI.getOperand(0).getReg(), DstExt);
484  MI.eraseFromParent();
485  return Legalized;
486  }
487  case TargetOpcode::G_FPTOSI:
488  case TargetOpcode::G_FPTOUI: {
489  if (TypeIdx != 0)
490  return UnableToLegalize;
491 
492  unsigned DstExt = MRI.createGenericVirtualRegister(WideTy);
494  .addDef(DstExt)
495  .addUse(MI.getOperand(1).getReg());
496 
497  MIRBuilder.buildTrunc(MI.getOperand(0).getReg(), DstExt);
498  MI.eraseFromParent();
499  return Legalized;
500  }
501  case TargetOpcode::G_SITOFP:
502  case TargetOpcode::G_UITOFP: {
503  if (TypeIdx != 1)
504  return UnableToLegalize;
505 
506  unsigned Src = MI.getOperand(1).getReg();
507  unsigned SrcExt = MRI.createGenericVirtualRegister(WideTy);
508 
509  if (MI.getOpcode() == TargetOpcode::G_SITOFP) {
510  MIRBuilder.buildSExt(SrcExt, Src);
511  } else {
512  assert(MI.getOpcode() == TargetOpcode::G_UITOFP && "Unexpected conv op");
513  MIRBuilder.buildZExt(SrcExt, Src);
514  }
515 
517  .addDef(MI.getOperand(0).getReg())
518  .addUse(SrcExt);
519 
520  MI.eraseFromParent();
521  return Legalized;
522  }
523  case TargetOpcode::G_INSERT: {
524  if (TypeIdx != 0)
525  return UnableToLegalize;
526 
527  unsigned Src = MI.getOperand(1).getReg();
528  unsigned SrcExt = MRI.createGenericVirtualRegister(WideTy);
529  MIRBuilder.buildAnyExt(SrcExt, Src);
530 
531  unsigned DstExt = MRI.createGenericVirtualRegister(WideTy);
532  auto MIB = MIRBuilder.buildInsert(DstExt, SrcExt, MI.getOperand(2).getReg(),
533  MI.getOperand(3).getImm());
534  for (unsigned OpNum = 4; OpNum < MI.getNumOperands(); OpNum += 2) {
535  MIB.addReg(MI.getOperand(OpNum).getReg());
536  MIB.addImm(MI.getOperand(OpNum + 1).getImm());
537  }
538 
539  MIRBuilder.buildTrunc(MI.getOperand(0).getReg(), DstExt);
540  MI.eraseFromParent();
541  return Legalized;
542  }
543  case TargetOpcode::G_LOAD: {
544  assert(alignTo(MRI.getType(MI.getOperand(0).getReg()).getSizeInBits(), 8) ==
545  WideTy.getSizeInBits() &&
546  "illegal to increase number of bytes loaded");
547 
548  unsigned DstExt = MRI.createGenericVirtualRegister(WideTy);
549  MIRBuilder.buildLoad(DstExt, MI.getOperand(1).getReg(),
550  **MI.memoperands_begin());
551  MIRBuilder.buildTrunc(MI.getOperand(0).getReg(), DstExt);
552  MI.eraseFromParent();
553  return Legalized;
554  }
555  case TargetOpcode::G_STORE: {
556  if (MRI.getType(MI.getOperand(0).getReg()) != LLT::scalar(1) ||
557  WideTy != LLT::scalar(8))
558  return UnableToLegalize;
559 
560  auto &TLI = *MIRBuilder.getMF().getSubtarget().getTargetLowering();
561  auto Content = TLI.getBooleanContents(false, false);
562 
563  unsigned ExtOp = TargetOpcode::G_ANYEXT;
565  ExtOp = TargetOpcode::G_ZEXT;
567  ExtOp = TargetOpcode::G_SEXT;
568  else
569  ExtOp = TargetOpcode::G_ANYEXT;
570 
571  unsigned SrcExt = MRI.createGenericVirtualRegister(WideTy);
572  MIRBuilder.buildInstr(ExtOp).addDef(SrcExt).addUse(
573  MI.getOperand(0).getReg());
574  MIRBuilder.buildStore(SrcExt, MI.getOperand(1).getReg(),
575  **MI.memoperands_begin());
576  MI.eraseFromParent();
577  return Legalized;
578  }
579  case TargetOpcode::G_CONSTANT: {
580  unsigned DstExt = MRI.createGenericVirtualRegister(WideTy);
581  MIRBuilder.buildConstant(DstExt, *MI.getOperand(1).getCImm());
582  MIRBuilder.buildTrunc(MI.getOperand(0).getReg(), DstExt);
583  MI.eraseFromParent();
584  return Legalized;
585  }
586  case TargetOpcode::G_FCONSTANT: {
587  unsigned DstExt = MRI.createGenericVirtualRegister(WideTy);
588  MIRBuilder.buildFConstant(DstExt, *MI.getOperand(1).getFPImm());
589  MIRBuilder.buildFPTrunc(MI.getOperand(0).getReg(), DstExt);
590  MI.eraseFromParent();
591  return Legalized;
592  }
593  case TargetOpcode::G_BRCOND: {
594  unsigned TstExt = MRI.createGenericVirtualRegister(WideTy);
595  MIRBuilder.buildAnyExt(TstExt, MI.getOperand(0).getReg());
596  MIRBuilder.buildBrCond(TstExt, *MI.getOperand(1).getMBB());
597  MI.eraseFromParent();
598  return Legalized;
599  }
600  case TargetOpcode::G_ICMP: {
601  assert(TypeIdx == 1 && "unable to legalize predicate");
602  bool IsSigned = CmpInst::isSigned(
603  static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate()));
604  unsigned Op0Ext = MRI.createGenericVirtualRegister(WideTy);
605  unsigned Op1Ext = MRI.createGenericVirtualRegister(WideTy);
606  if (IsSigned) {
607  MIRBuilder.buildSExt(Op0Ext, MI.getOperand(2).getReg());
608  MIRBuilder.buildSExt(Op1Ext, MI.getOperand(3).getReg());
609  } else {
610  MIRBuilder.buildZExt(Op0Ext, MI.getOperand(2).getReg());
611  MIRBuilder.buildZExt(Op1Ext, MI.getOperand(3).getReg());
612  }
614  static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate()),
615  MI.getOperand(0).getReg(), Op0Ext, Op1Ext);
616  MI.eraseFromParent();
617  return Legalized;
618  }
619  case TargetOpcode::G_GEP: {
620  assert(TypeIdx == 1 && "unable to legalize pointer of GEP");
621  unsigned OffsetExt = MRI.createGenericVirtualRegister(WideTy);
622  MIRBuilder.buildSExt(OffsetExt, MI.getOperand(2).getReg());
623  MI.getOperand(2).setReg(OffsetExt);
624  return Legalized;
625  }
626  }
627 }
628 
630 LegalizerHelper::lower(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
631  using namespace TargetOpcode;
632  MIRBuilder.setInstr(MI);
633 
634  switch(MI.getOpcode()) {
635  default:
636  return UnableToLegalize;
637  case TargetOpcode::G_SREM:
638  case TargetOpcode::G_UREM: {
639  unsigned QuotReg = MRI.createGenericVirtualRegister(Ty);
640  MIRBuilder.buildInstr(MI.getOpcode() == G_SREM ? G_SDIV : G_UDIV)
641  .addDef(QuotReg)
642  .addUse(MI.getOperand(1).getReg())
643  .addUse(MI.getOperand(2).getReg());
644 
645  unsigned ProdReg = MRI.createGenericVirtualRegister(Ty);
646  MIRBuilder.buildMul(ProdReg, QuotReg, MI.getOperand(2).getReg());
648  ProdReg);
649  MI.eraseFromParent();
650  return Legalized;
651  }
652  case TargetOpcode::G_SMULO:
653  case TargetOpcode::G_UMULO: {
654  // Generate G_UMULH/G_SMULH to check for overflow and a normal G_MUL for the
655  // result.
656  unsigned Res = MI.getOperand(0).getReg();
657  unsigned Overflow = MI.getOperand(1).getReg();
658  unsigned LHS = MI.getOperand(2).getReg();
659  unsigned RHS = MI.getOperand(3).getReg();
660 
661  MIRBuilder.buildMul(Res, LHS, RHS);
662 
663  unsigned Opcode = MI.getOpcode() == TargetOpcode::G_SMULO
664  ? TargetOpcode::G_SMULH
665  : TargetOpcode::G_UMULH;
666 
667  unsigned HiPart = MRI.createGenericVirtualRegister(Ty);
668  MIRBuilder.buildInstr(Opcode)
669  .addDef(HiPart)
670  .addUse(LHS)
671  .addUse(RHS);
672 
673  unsigned Zero = MRI.createGenericVirtualRegister(Ty);
674  MIRBuilder.buildConstant(Zero, 0);
675  MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Zero);
676  MI.eraseFromParent();
677  return Legalized;
678  }
679  case TargetOpcode::G_FNEG: {
680  // TODO: Handle vector types once we are able to
681  // represent them.
682  if (Ty.isVector())
683  return UnableToLegalize;
684  unsigned Res = MI.getOperand(0).getReg();
685  Type *ZeroTy;
687  switch (Ty.getSizeInBits()) {
688  case 16:
689  ZeroTy = Type::getHalfTy(Ctx);
690  break;
691  case 32:
692  ZeroTy = Type::getFloatTy(Ctx);
693  break;
694  case 64:
695  ZeroTy = Type::getDoubleTy(Ctx);
696  break;
697  default:
698  llvm_unreachable("unexpected floating-point type");
699  }
700  ConstantFP &ZeroForNegation =
701  *cast<ConstantFP>(ConstantFP::getZeroValueForNegation(ZeroTy));
702  unsigned Zero = MRI.createGenericVirtualRegister(Ty);
703  MIRBuilder.buildFConstant(Zero, ZeroForNegation);
704  MIRBuilder.buildInstr(TargetOpcode::G_FSUB)
705  .addDef(Res)
706  .addUse(Zero)
707  .addUse(MI.getOperand(1).getReg());
708  MI.eraseFromParent();
709  return Legalized;
710  }
711  case TargetOpcode::G_FSUB: {
712  // Lower (G_FSUB LHS, RHS) to (G_FADD LHS, (G_FNEG RHS)).
713  // First, check if G_FNEG is marked as Lower. If so, we may
714  // end up with an infinite loop as G_FSUB is used to legalize G_FNEG.
715  if (LI.getAction({G_FNEG, Ty}).first == LegalizerInfo::Lower)
716  return UnableToLegalize;
717  unsigned Res = MI.getOperand(0).getReg();
718  unsigned LHS = MI.getOperand(1).getReg();
719  unsigned RHS = MI.getOperand(2).getReg();
720  unsigned Neg = MRI.createGenericVirtualRegister(Ty);
721  MIRBuilder.buildInstr(TargetOpcode::G_FNEG).addDef(Neg).addUse(RHS);
722  MIRBuilder.buildInstr(TargetOpcode::G_FADD)
723  .addDef(Res)
724  .addUse(LHS)
725  .addUse(Neg);
726  MI.eraseFromParent();
727  return Legalized;
728  }
729  }
730 }
731 
734  LLT NarrowTy) {
735  // FIXME: Don't know how to handle secondary types yet.
736  if (TypeIdx != 0)
737  return UnableToLegalize;
738  switch (MI.getOpcode()) {
739  default:
740  return UnableToLegalize;
741  case TargetOpcode::G_ADD: {
742  unsigned NarrowSize = NarrowTy.getSizeInBits();
743  unsigned DstReg = MI.getOperand(0).getReg();
744  int NumParts = MRI.getType(DstReg).getSizeInBits() / NarrowSize;
745 
746  MIRBuilder.setInstr(MI);
747 
748  SmallVector<unsigned, 2> Src1Regs, Src2Regs, DstRegs;
749  extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, Src1Regs);
750  extractParts(MI.getOperand(2).getReg(), NarrowTy, NumParts, Src2Regs);
751 
752  for (int i = 0; i < NumParts; ++i) {
753  unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy);
754  MIRBuilder.buildAdd(DstReg, Src1Regs[i], Src2Regs[i]);
755  DstRegs.push_back(DstReg);
756  }
757 
758  MIRBuilder.buildMerge(DstReg, DstRegs);
759  MI.eraseFromParent();
760  return Legalized;
761  }
762  }
763 }
static LegalizerHelper::LegalizeResult simpleLibcall(MachineInstr &MI, MachineIRBuilder &MIRBuilder, unsigned Size, Type *OpType)
void push_back(const T &Elt)
Definition: SmallVector.h:211
MachineIRBuilder MIRBuilder
Expose MIRBuilder so clients can set their own RecordInsertInstruction functions. ...
static Type * getDoubleTy(LLVMContext &C)
Definition: Type.cpp:165
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:194
LLT getType(unsigned VReg) const
Get the low-level type of VReg or LLT{} if VReg is not a generic (target independent) virtual registe...
const ConstantFP * getFPImm() const
MachineBasicBlock * getMBB() const
MachineInstrBuilder buildZExt(unsigned Res, unsigned Op)
Build and insert Res<def> = G_ZEXT Op.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
std::pair< LegalizeAction, LLT > getAction(const InstrAspect &Aspect) const
Determine what action should be taken to legalize the given generic instruction opcode, type-index and type.
Libcall
RTLIB::Libcall enum - This enum defines all of the runtime library calls the backend can emit...
bool isSigned() const
Determine if this instruction is using a signed comparison.
Definition: InstrTypes.h:1001
static const MCPhysReg VRegs[32]
MachineInstrBuilder buildTrunc(unsigned Res, unsigned Op)
Build and insert Res<def> = G_TRUNC Op.
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
MachineInstrBuilder buildSub(unsigned Res, unsigned Op0, unsigned Op1)
Build and insert Res<def> = G_SUB Op0, Op1.
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:677
MachineInstrBuilder buildAnyExt(unsigned Res, unsigned Op)
Build and insert Res<def> = G_ANYEXT Op0.
virtual const CallLowering * getCallLowering() const
void print(raw_ostream &OS, bool SkipOpers=false, bool SkipDebugLoc=false, const TargetInstrInfo *TII=nullptr) const
Debugging supportPrint this MI to OS.
unsigned createGenericVirtualRegister(LLT Ty)
Create and return a new generic virtual register with low-level type Ty.
MachineInstrBuilder buildExtract(unsigned Res, unsigned Src, uint64_t Index)
Build and insert `Res0<def>, ...
const MachineInstrBuilder & addDef(unsigned RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
MachineInstrBuilder buildFPTrunc(unsigned Res, unsigned Op)
Build and insert Res<def> = G_FPTRUNC Op.
LegalizerHelper(MachineFunction &MF)
MachineInstrBuilder buildStore(unsigned Val, unsigned Addr, MachineMemOperand &MMO)
Build and insert G_STORE Val, Addr, MMO.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
LegalizeResult widenScalar(MachineInstr &MI, unsigned TypeIdx, LLT WideTy)
Legalize an instruction by performing the operation on a wider scalar type (for example a 16-bit addi...
static Type * getFloatTy(LLVMContext &C)
Definition: Type.cpp:164
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:138
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineInstrBuilder buildFConstant(unsigned Res, const ConstantFP &Val)
Build and insert Res = G_FCONSTANT Val.
Reg
All possible values of the reg field in the ModR/M byte.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
LegalizerHelper::LegalizeResult createLibcall(MachineIRBuilder &MIRBuilder, RTLIB::Libcall Libcall, const CallLowering::ArgInfo &Result, ArrayRef< CallLowering::ArgInfo > Args)
Helper function that creates the given libcall.
unsigned getNumOperands() const
Access to explicit operands of the instruction.
Definition: MachineInstr.h:282
MachineFunction & getMF()
Getter for the function we currently build.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
int64_t getImm() const
static LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
const char * Name
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:279
The target wants to do something special with this combination of operand and type.
Definition: LegalizerInfo.h:92
unsigned const MachineRegisterInfo * MRI
The (vector) operation should be implemented by splitting it into sub-vectors where the operation is ...
Definition: LegalizerInfo.h:73
APInt trunc(unsigned width) const
Truncate to new width.
Definition: APInt.cpp:818
LegalizeResult legalizeInstrStep(MachineInstr &MI)
Replace MI by a sequence of legal instructions that can implement the same operation.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
static unsigned getSizeInBits(unsigned Reg, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI)
Get the size in bits of Reg.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:284
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:264
Helper class to build MachineInstr.
MachineInstrBuilder buildICmp(CmpInst::Predicate Pred, unsigned Res, unsigned Op0, unsigned Op1)
Build and insert a Res = G_ICMP Pred, Op0, Op1.
void setInstr(MachineInstr &MI)
Set the insertion point to before MI.
MachineInstrBuilder buildInsert(unsigned Res, unsigned Src, unsigned Op, unsigned Index)
void setMF(MachineFunction &)
Some kind of error has occurred and we could not legalize this instruction.
Instruction was already legal and no change was made to the MachineFunction.
MachineInstrBuilder buildUAdde(unsigned Res, unsigned CarryOut, unsigned Op0, unsigned Op1, unsigned CarryIn)
Build and insert Res<def>, CarryOut<def> = G_UADDE Op0, Op1, CarryIn.
BooleanContent getBooleanContents(bool isVec, bool isFloat) const
For targets without i1 registers, this gives the nature of the high-bits of boolean values held in ty...
virtual bool legalizeCustom(MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &MIRBuilder) const
unsigned first
The operation should be synthesized from multiple instructions acting on a narrower scalar base-type...
Definition: LegalizerInfo.h:63
static Type * getHalfTy(LLVMContext &C)
Definition: Type.cpp:163
The operation should be implemented as a call to some kind of runtime support library.
Definition: LegalizerInfo.h:88
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
LegalizeResult libcall(MachineInstr &MI)
Legalize an instruction by emiting a runtime library call instead.
static RTLIB::Libcall getRTLibDesc(unsigned Opcode, unsigned Size)
virtual const TargetLowering * getTargetLowering() const
The operation should be implemented in terms of a wider scalar base-type.
Definition: LegalizerInfo.h:68
unsigned getPredicate() const
LegalizeResult lower(MachineInstr &MI, unsigned TypeIdx, LLT Ty)
Legalize an instruction by splitting it into simpler parts, hopefully understood by the target...
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:560
LegalizeResult fewerElementsVector(MachineInstr &MI, unsigned TypeIdx, LLT NarrowTy)
Legalize a vector instruction by splitting into multiple components, each acting on the same scalar t...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
const ConstantInt * getCImm() const
Class for arbitrary precision integers.
Definition: APInt.h:69
The operation itself must be expressed in terms of simpler actions on this target.
Definition: LegalizerInfo.h:83
static MachineOperand CreateES(const char *SymName, unsigned char TargetFlags=0)
MachineInstrBuilder buildSExt(unsigned Res, unsigned Op)
Build and insert Res<def> = G_SEXT Op.
The operation is expected to be selectable directly by the target, and no transformation is necessary...
Definition: LegalizerInfo.h:58
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
Representation of each machine instruction.
Definition: MachineInstr.h:59
Instruction has been legalized and the MachineFunction changed.
MachineInstrBuilder buildUndef(unsigned Dst)
Build and insert Res = IMPLICIT_DEF.
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
MachineInstrBuilder buildAdd(unsigned Res, unsigned Op0, unsigned Op1)
Build and insert Res<def> = G_ADD Op0, Op1.
MachineInstrBuilder buildConstant(unsigned Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
void setReg(unsigned Reg)
Change the register this operand corresponds to.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
static Constant * getZeroValueForNegation(Type *Ty)
Floating point negation must be implemented with f(x) = -0.0 - x.
Definition: Constants.cpp:676
MachineInstrBuilder buildMul(unsigned Res, unsigned Op0, unsigned Op1)
Build and insert Res<def> = G_MUL Op0, Op1.
static volatile int Zero
Optional< MachineInstrBuilder > materializeGEP(unsigned &Res, unsigned Op0, const LLT &ValueTy, uint64_t Value)
Materialize and insert Res<def> = G_GEP Op0, (G_CONSTANT Value)
MachineInstrBuilder buildUnmerge(ArrayRef< unsigned > Res, unsigned Op)
Build and insert Res0<def>, ...
unsigned getReg() const
getReg - Returns the register number.
LegalizeResult narrowScalar(MachineInstr &MI, unsigned TypeIdx, LLT NarrowTy)
Legalize an instruction by reducing the width of the underlying scalar type.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const MachineInstrBuilder & addUse(unsigned RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
This file describes how to lower LLVM calls to machine code calls.
MachineInstrBuilder buildLoad(unsigned Res, unsigned Addr, MachineMemOperand &MMO)
Build and insert Res<def> = G_LOAD Addr, MMO.
#define DEBUG(X)
Definition: Debug.h:118
IRTranslator LLVM IR MI
unsigned getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
bool isVector() const
MachineInstrBuilder buildMerge(unsigned Res, ArrayRef< unsigned > Ops)
Build and insert Res<def> = G_MERGE_VALUES Op0, ...
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:959
This file describes how to lower LLVM code to machine code.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
Definition: MachineInstr.h:363
MachineInstrBuilder buildBrCond(unsigned Tst, MachineBasicBlock &BB)
Build and insert G_BRCOND Tst, Dest.