LLVM  7.0.0svn
X86InstrInfo.cpp
Go to the documentation of this file.
1 //===-- X86InstrInfo.cpp - X86 Instruction Information --------------------===//
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 // This file contains the X86 implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "X86InstrInfo.h"
15 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86InstrFoldTables.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/CodeGen/StackMaps.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCExpr.h"
36 #include "llvm/MC/MCInst.h"
38 #include "llvm/Support/Debug.h"
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "x86-instr-info"
46 
47 #define GET_INSTRINFO_CTOR_DTOR
48 #include "X86GenInstrInfo.inc"
49 
50 static cl::opt<bool>
51  NoFusing("disable-spill-fusing",
52  cl::desc("Disable fusing of spill code into instructions"),
53  cl::Hidden);
54 static cl::opt<bool>
55 PrintFailedFusing("print-failed-fuse-candidates",
56  cl::desc("Print instructions that the allocator wants to"
57  " fuse, but the X86 backend currently can't"),
58  cl::Hidden);
59 static cl::opt<bool>
60 ReMatPICStubLoad("remat-pic-stub-load",
61  cl::desc("Re-materialize load from stub in PIC mode"),
62  cl::init(false), cl::Hidden);
63 static cl::opt<unsigned>
64 PartialRegUpdateClearance("partial-reg-update-clearance",
65  cl::desc("Clearance between two register writes "
66  "for inserting XOR to avoid partial "
67  "register update"),
68  cl::init(64), cl::Hidden);
69 static cl::opt<unsigned>
70 UndefRegClearance("undef-reg-clearance",
71  cl::desc("How many idle instructions we would like before "
72  "certain undef register reads"),
73  cl::init(128), cl::Hidden);
74 
75 
76 // Pin the vtable to this file.
77 void X86InstrInfo::anchor() {}
78 
80  : X86GenInstrInfo((STI.isTarget64BitLP64() ? X86::ADJCALLSTACKDOWN64
81  : X86::ADJCALLSTACKDOWN32),
82  (STI.isTarget64BitLP64() ? X86::ADJCALLSTACKUP64
83  : X86::ADJCALLSTACKUP32),
84  X86::CATCHRET,
85  (STI.is64Bit() ? X86::RETQ : X86::RETL)),
86  Subtarget(STI), RI(STI.getTargetTriple()) {
87 }
88 
89 bool
91  unsigned &SrcReg, unsigned &DstReg,
92  unsigned &SubIdx) const {
93  switch (MI.getOpcode()) {
94  default: break;
95  case X86::MOVSX16rr8:
96  case X86::MOVZX16rr8:
97  case X86::MOVSX32rr8:
98  case X86::MOVZX32rr8:
99  case X86::MOVSX64rr8:
100  if (!Subtarget.is64Bit())
101  // It's not always legal to reference the low 8-bit of the larger
102  // register in 32-bit mode.
103  return false;
105  case X86::MOVSX32rr16:
106  case X86::MOVZX32rr16:
107  case X86::MOVSX64rr16:
108  case X86::MOVSX64rr32: {
109  if (MI.getOperand(0).getSubReg() || MI.getOperand(1).getSubReg())
110  // Be conservative.
111  return false;
112  SrcReg = MI.getOperand(1).getReg();
113  DstReg = MI.getOperand(0).getReg();
114  switch (MI.getOpcode()) {
115  default: llvm_unreachable("Unreachable!");
116  case X86::MOVSX16rr8:
117  case X86::MOVZX16rr8:
118  case X86::MOVSX32rr8:
119  case X86::MOVZX32rr8:
120  case X86::MOVSX64rr8:
121  SubIdx = X86::sub_8bit;
122  break;
123  case X86::MOVSX32rr16:
124  case X86::MOVZX32rr16:
125  case X86::MOVSX64rr16:
126  SubIdx = X86::sub_16bit;
127  break;
128  case X86::MOVSX64rr32:
129  SubIdx = X86::sub_32bit;
130  break;
131  }
132  return true;
133  }
134  }
135  return false;
136 }
137 
139  const MachineFunction *MF = MI.getParent()->getParent();
141 
142  if (isFrameInstr(MI)) {
143  unsigned StackAlign = TFI->getStackAlignment();
144  int SPAdj = alignTo(getFrameSize(MI), StackAlign);
145  SPAdj -= getFrameAdjustment(MI);
146  if (!isFrameSetup(MI))
147  SPAdj = -SPAdj;
148  return SPAdj;
149  }
150 
151  // To know whether a call adjusts the stack, we need information
152  // that is bound to the following ADJCALLSTACKUP pseudo.
153  // Look for the next ADJCALLSTACKUP that follows the call.
154  if (MI.isCall()) {
155  const MachineBasicBlock *MBB = MI.getParent();
157  for (auto E = MBB->end(); I != E; ++I) {
158  if (I->getOpcode() == getCallFrameDestroyOpcode() ||
159  I->isCall())
160  break;
161  }
162 
163  // If we could not find a frame destroy opcode, then it has already
164  // been simplified, so we don't care.
165  if (I->getOpcode() != getCallFrameDestroyOpcode())
166  return 0;
167 
168  return -(I->getOperand(1).getImm());
169  }
170 
171  // Currently handle only PUSHes we can reasonably expect to see
172  // in call sequences
173  switch (MI.getOpcode()) {
174  default:
175  return 0;
176  case X86::PUSH32i8:
177  case X86::PUSH32r:
178  case X86::PUSH32rmm:
179  case X86::PUSH32rmr:
180  case X86::PUSHi32:
181  return 4;
182  case X86::PUSH64i8:
183  case X86::PUSH64r:
184  case X86::PUSH64rmm:
185  case X86::PUSH64rmr:
186  case X86::PUSH64i32:
187  return 8;
188  }
189 }
190 
191 /// Return true and the FrameIndex if the specified
192 /// operand and follow operands form a reference to the stack frame.
193 bool X86InstrInfo::isFrameOperand(const MachineInstr &MI, unsigned int Op,
194  int &FrameIndex) const {
195  if (MI.getOperand(Op + X86::AddrBaseReg).isFI() &&
196  MI.getOperand(Op + X86::AddrScaleAmt).isImm() &&
197  MI.getOperand(Op + X86::AddrIndexReg).isReg() &&
198  MI.getOperand(Op + X86::AddrDisp).isImm() &&
199  MI.getOperand(Op + X86::AddrScaleAmt).getImm() == 1 &&
200  MI.getOperand(Op + X86::AddrIndexReg).getReg() == 0 &&
201  MI.getOperand(Op + X86::AddrDisp).getImm() == 0) {
202  FrameIndex = MI.getOperand(Op + X86::AddrBaseReg).getIndex();
203  return true;
204  }
205  return false;
206 }
207 
208 static bool isFrameLoadOpcode(int Opcode, unsigned &MemBytes) {
209  switch (Opcode) {
210  default:
211  return false;
212  case X86::MOV8rm:
213  case X86::KMOVBkm:
214  MemBytes = 1;
215  return true;
216  case X86::MOV16rm:
217  case X86::KMOVWkm:
218  MemBytes = 2;
219  return true;
220  case X86::MOV32rm:
221  case X86::MOVSSrm:
222  case X86::VMOVSSZrm:
223  case X86::VMOVSSrm:
224  case X86::KMOVDkm:
225  MemBytes = 4;
226  return true;
227  case X86::MOV64rm:
228  case X86::LD_Fp64m:
229  case X86::MOVSDrm:
230  case X86::VMOVSDrm:
231  case X86::VMOVSDZrm:
232  case X86::MMX_MOVD64rm:
233  case X86::MMX_MOVQ64rm:
234  case X86::KMOVQkm:
235  MemBytes = 8;
236  return true;
237  case X86::MOVAPSrm:
238  case X86::MOVUPSrm:
239  case X86::MOVAPDrm:
240  case X86::MOVUPDrm:
241  case X86::MOVDQArm:
242  case X86::MOVDQUrm:
243  case X86::VMOVAPSrm:
244  case X86::VMOVUPSrm:
245  case X86::VMOVAPDrm:
246  case X86::VMOVUPDrm:
247  case X86::VMOVDQArm:
248  case X86::VMOVDQUrm:
249  case X86::VMOVAPSZ128rm:
250  case X86::VMOVUPSZ128rm:
251  case X86::VMOVAPSZ128rm_NOVLX:
252  case X86::VMOVUPSZ128rm_NOVLX:
253  case X86::VMOVAPDZ128rm:
254  case X86::VMOVUPDZ128rm:
255  case X86::VMOVDQU8Z128rm:
256  case X86::VMOVDQU16Z128rm:
257  case X86::VMOVDQA32Z128rm:
258  case X86::VMOVDQU32Z128rm:
259  case X86::VMOVDQA64Z128rm:
260  case X86::VMOVDQU64Z128rm:
261  MemBytes = 16;
262  return true;
263  case X86::VMOVAPSYrm:
264  case X86::VMOVUPSYrm:
265  case X86::VMOVAPDYrm:
266  case X86::VMOVUPDYrm:
267  case X86::VMOVDQAYrm:
268  case X86::VMOVDQUYrm:
269  case X86::VMOVAPSZ256rm:
270  case X86::VMOVUPSZ256rm:
271  case X86::VMOVAPSZ256rm_NOVLX:
272  case X86::VMOVUPSZ256rm_NOVLX:
273  case X86::VMOVAPDZ256rm:
274  case X86::VMOVUPDZ256rm:
275  case X86::VMOVDQU8Z256rm:
276  case X86::VMOVDQU16Z256rm:
277  case X86::VMOVDQA32Z256rm:
278  case X86::VMOVDQU32Z256rm:
279  case X86::VMOVDQA64Z256rm:
280  case X86::VMOVDQU64Z256rm:
281  MemBytes = 32;
282  return true;
283  case X86::VMOVAPSZrm:
284  case X86::VMOVUPSZrm:
285  case X86::VMOVAPDZrm:
286  case X86::VMOVUPDZrm:
287  case X86::VMOVDQU8Zrm:
288  case X86::VMOVDQU16Zrm:
289  case X86::VMOVDQA32Zrm:
290  case X86::VMOVDQU32Zrm:
291  case X86::VMOVDQA64Zrm:
292  case X86::VMOVDQU64Zrm:
293  MemBytes = 64;
294  return true;
295  }
296 }
297 
298 static bool isFrameStoreOpcode(int Opcode, unsigned &MemBytes) {
299  switch (Opcode) {
300  default:
301  return false;
302  case X86::MOV8mr:
303  case X86::KMOVBmk:
304  MemBytes = 1;
305  return true;
306  case X86::MOV16mr:
307  case X86::KMOVWmk:
308  MemBytes = 2;
309  return true;
310  case X86::MOV32mr:
311  case X86::MOVSSmr:
312  case X86::VMOVSSmr:
313  case X86::VMOVSSZmr:
314  case X86::KMOVDmk:
315  MemBytes = 4;
316  return true;
317  case X86::MOV64mr:
318  case X86::ST_FpP64m:
319  case X86::MOVSDmr:
320  case X86::VMOVSDmr:
321  case X86::VMOVSDZmr:
322  case X86::MMX_MOVD64mr:
323  case X86::MMX_MOVQ64mr:
324  case X86::MMX_MOVNTQmr:
325  case X86::KMOVQmk:
326  MemBytes = 8;
327  return true;
328  case X86::MOVAPSmr:
329  case X86::MOVUPSmr:
330  case X86::MOVAPDmr:
331  case X86::MOVUPDmr:
332  case X86::MOVDQAmr:
333  case X86::MOVDQUmr:
334  case X86::VMOVAPSmr:
335  case X86::VMOVUPSmr:
336  case X86::VMOVAPDmr:
337  case X86::VMOVUPDmr:
338  case X86::VMOVDQAmr:
339  case X86::VMOVDQUmr:
340  case X86::VMOVUPSZ128mr:
341  case X86::VMOVAPSZ128mr:
342  case X86::VMOVUPSZ128mr_NOVLX:
343  case X86::VMOVAPSZ128mr_NOVLX:
344  case X86::VMOVUPDZ128mr:
345  case X86::VMOVAPDZ128mr:
346  case X86::VMOVDQA32Z128mr:
347  case X86::VMOVDQU32Z128mr:
348  case X86::VMOVDQA64Z128mr:
349  case X86::VMOVDQU64Z128mr:
350  case X86::VMOVDQU8Z128mr:
351  case X86::VMOVDQU16Z128mr:
352  MemBytes = 16;
353  return true;
354  case X86::VMOVUPSYmr:
355  case X86::VMOVAPSYmr:
356  case X86::VMOVUPDYmr:
357  case X86::VMOVAPDYmr:
358  case X86::VMOVDQUYmr:
359  case X86::VMOVDQAYmr:
360  case X86::VMOVUPSZ256mr:
361  case X86::VMOVAPSZ256mr:
362  case X86::VMOVUPSZ256mr_NOVLX:
363  case X86::VMOVAPSZ256mr_NOVLX:
364  case X86::VMOVUPDZ256mr:
365  case X86::VMOVAPDZ256mr:
366  case X86::VMOVDQU8Z256mr:
367  case X86::VMOVDQU16Z256mr:
368  case X86::VMOVDQA32Z256mr:
369  case X86::VMOVDQU32Z256mr:
370  case X86::VMOVDQA64Z256mr:
371  case X86::VMOVDQU64Z256mr:
372  MemBytes = 32;
373  return true;
374  case X86::VMOVUPSZmr:
375  case X86::VMOVAPSZmr:
376  case X86::VMOVUPDZmr:
377  case X86::VMOVAPDZmr:
378  case X86::VMOVDQU8Zmr:
379  case X86::VMOVDQU16Zmr:
380  case X86::VMOVDQA32Zmr:
381  case X86::VMOVDQU32Zmr:
382  case X86::VMOVDQA64Zmr:
383  case X86::VMOVDQU64Zmr:
384  MemBytes = 64;
385  return true;
386  }
387  return false;
388 }
389 
391  int &FrameIndex) const {
392  unsigned Dummy;
393  return X86InstrInfo::isLoadFromStackSlot(MI, FrameIndex, Dummy);
394 }
395 
397  int &FrameIndex,
398  unsigned &MemBytes) const {
399  if (isFrameLoadOpcode(MI.getOpcode(), MemBytes))
400  if (MI.getOperand(0).getSubReg() == 0 && isFrameOperand(MI, 1, FrameIndex))
401  return MI.getOperand(0).getReg();
402  return 0;
403 }
404 
406  int &FrameIndex) const {
407  unsigned Dummy;
408  if (isFrameLoadOpcode(MI.getOpcode(), Dummy)) {
409  unsigned Reg;
410  if ((Reg = isLoadFromStackSlot(MI, FrameIndex)))
411  return Reg;
412  // Check for post-frame index elimination operations
413  const MachineMemOperand *Dummy;
414  return hasLoadFromStackSlot(MI, Dummy, FrameIndex);
415  }
416  return 0;
417 }
418 
420  int &FrameIndex) const {
421  unsigned Dummy;
422  return X86InstrInfo::isStoreToStackSlot(MI, FrameIndex, Dummy);
423 }
424 
426  int &FrameIndex,
427  unsigned &MemBytes) const {
428  if (isFrameStoreOpcode(MI.getOpcode(), MemBytes))
429  if (MI.getOperand(X86::AddrNumOperands).getSubReg() == 0 &&
430  isFrameOperand(MI, 0, FrameIndex))
432  return 0;
433 }
434 
436  int &FrameIndex) const {
437  unsigned Dummy;
438  if (isFrameStoreOpcode(MI.getOpcode(), Dummy)) {
439  unsigned Reg;
440  if ((Reg = isStoreToStackSlot(MI, FrameIndex)))
441  return Reg;
442  // Check for post-frame index elimination operations
443  const MachineMemOperand *Dummy;
444  return hasStoreToStackSlot(MI, Dummy, FrameIndex);
445  }
446  return 0;
447 }
448 
449 /// Return true if register is PIC base; i.e.g defined by X86::MOVPC32r.
450 static bool regIsPICBase(unsigned BaseReg, const MachineRegisterInfo &MRI) {
451  // Don't waste compile time scanning use-def chains of physregs.
453  return false;
454  bool isPICBase = false;
456  E = MRI.def_instr_end(); I != E; ++I) {
457  MachineInstr *DefMI = &*I;
458  if (DefMI->getOpcode() != X86::MOVPC32r)
459  return false;
460  assert(!isPICBase && "More than one PIC base?");
461  isPICBase = true;
462  }
463  return isPICBase;
464 }
465 
467  AliasAnalysis *AA) const {
468  switch (MI.getOpcode()) {
469  default: break;
470  case X86::MOV8rm:
471  case X86::MOV8rm_NOREX:
472  case X86::MOV16rm:
473  case X86::MOV32rm:
474  case X86::MOV64rm:
475  case X86::LD_Fp64m:
476  case X86::MOVSSrm:
477  case X86::MOVSDrm:
478  case X86::MOVAPSrm:
479  case X86::MOVUPSrm:
480  case X86::MOVAPDrm:
481  case X86::MOVUPDrm:
482  case X86::MOVDQArm:
483  case X86::MOVDQUrm:
484  case X86::VMOVSSrm:
485  case X86::VMOVSDrm:
486  case X86::VMOVAPSrm:
487  case X86::VMOVUPSrm:
488  case X86::VMOVAPDrm:
489  case X86::VMOVUPDrm:
490  case X86::VMOVDQArm:
491  case X86::VMOVDQUrm:
492  case X86::VMOVAPSYrm:
493  case X86::VMOVUPSYrm:
494  case X86::VMOVAPDYrm:
495  case X86::VMOVUPDYrm:
496  case X86::VMOVDQAYrm:
497  case X86::VMOVDQUYrm:
498  case X86::MMX_MOVD64rm:
499  case X86::MMX_MOVQ64rm:
500  // AVX-512
501  case X86::VMOVSSZrm:
502  case X86::VMOVSDZrm:
503  case X86::VMOVAPDZ128rm:
504  case X86::VMOVAPDZ256rm:
505  case X86::VMOVAPDZrm:
506  case X86::VMOVAPSZ128rm:
507  case X86::VMOVAPSZ256rm:
508  case X86::VMOVAPSZ128rm_NOVLX:
509  case X86::VMOVAPSZ256rm_NOVLX:
510  case X86::VMOVAPSZrm:
511  case X86::VMOVDQA32Z128rm:
512  case X86::VMOVDQA32Z256rm:
513  case X86::VMOVDQA32Zrm:
514  case X86::VMOVDQA64Z128rm:
515  case X86::VMOVDQA64Z256rm:
516  case X86::VMOVDQA64Zrm:
517  case X86::VMOVDQU16Z128rm:
518  case X86::VMOVDQU16Z256rm:
519  case X86::VMOVDQU16Zrm:
520  case X86::VMOVDQU32Z128rm:
521  case X86::VMOVDQU32Z256rm:
522  case X86::VMOVDQU32Zrm:
523  case X86::VMOVDQU64Z128rm:
524  case X86::VMOVDQU64Z256rm:
525  case X86::VMOVDQU64Zrm:
526  case X86::VMOVDQU8Z128rm:
527  case X86::VMOVDQU8Z256rm:
528  case X86::VMOVDQU8Zrm:
529  case X86::VMOVUPDZ128rm:
530  case X86::VMOVUPDZ256rm:
531  case X86::VMOVUPDZrm:
532  case X86::VMOVUPSZ128rm:
533  case X86::VMOVUPSZ256rm:
534  case X86::VMOVUPSZ128rm_NOVLX:
535  case X86::VMOVUPSZ256rm_NOVLX:
536  case X86::VMOVUPSZrm: {
537  // Loads from constant pools are trivially rematerializable.
538  if (MI.getOperand(1 + X86::AddrBaseReg).isReg() &&
539  MI.getOperand(1 + X86::AddrScaleAmt).isImm() &&
540  MI.getOperand(1 + X86::AddrIndexReg).isReg() &&
541  MI.getOperand(1 + X86::AddrIndexReg).getReg() == 0 &&
543  unsigned BaseReg = MI.getOperand(1 + X86::AddrBaseReg).getReg();
544  if (BaseReg == 0 || BaseReg == X86::RIP)
545  return true;
546  // Allow re-materialization of PIC load.
548  return false;
549  const MachineFunction &MF = *MI.getParent()->getParent();
550  const MachineRegisterInfo &MRI = MF.getRegInfo();
551  return regIsPICBase(BaseReg, MRI);
552  }
553  return false;
554  }
555 
556  case X86::LEA32r:
557  case X86::LEA64r: {
558  if (MI.getOperand(1 + X86::AddrScaleAmt).isImm() &&
559  MI.getOperand(1 + X86::AddrIndexReg).isReg() &&
560  MI.getOperand(1 + X86::AddrIndexReg).getReg() == 0 &&
561  !MI.getOperand(1 + X86::AddrDisp).isReg()) {
562  // lea fi#, lea GV, etc. are all rematerializable.
563  if (!MI.getOperand(1 + X86::AddrBaseReg).isReg())
564  return true;
565  unsigned BaseReg = MI.getOperand(1 + X86::AddrBaseReg).getReg();
566  if (BaseReg == 0)
567  return true;
568  // Allow re-materialization of lea PICBase + x.
569  const MachineFunction &MF = *MI.getParent()->getParent();
570  const MachineRegisterInfo &MRI = MF.getRegInfo();
571  return regIsPICBase(BaseReg, MRI);
572  }
573  return false;
574  }
575  }
576 
577  // All other instructions marked M_REMATERIALIZABLE are always trivially
578  // rematerializable.
579  return true;
580 }
581 
585 
586  // For compile time consideration, if we are not able to determine the
587  // safety after visiting 4 instructions in each direction, we will assume
588  // it's not safe.
590  for (unsigned i = 0; Iter != E && i < 4; ++i) {
591  bool SeenDef = false;
592  for (unsigned j = 0, e = Iter->getNumOperands(); j != e; ++j) {
593  MachineOperand &MO = Iter->getOperand(j);
594  if (MO.isRegMask() && MO.clobbersPhysReg(X86::EFLAGS))
595  SeenDef = true;
596  if (!MO.isReg())
597  continue;
598  if (MO.getReg() == X86::EFLAGS) {
599  if (MO.isUse())
600  return false;
601  SeenDef = true;
602  }
603  }
604 
605  if (SeenDef)
606  // This instruction defines EFLAGS, no need to look any further.
607  return true;
608  ++Iter;
609  // Skip over debug instructions.
610  while (Iter != E && Iter->isDebugInstr())
611  ++Iter;
612  }
613 
614  // It is safe to clobber EFLAGS at the end of a block of no successor has it
615  // live in.
616  if (Iter == E) {
617  for (MachineBasicBlock *S : MBB.successors())
618  if (S->isLiveIn(X86::EFLAGS))
619  return false;
620  return true;
621  }
622 
624  Iter = I;
625  for (unsigned i = 0; i < 4; ++i) {
626  // If we make it to the beginning of the block, it's safe to clobber
627  // EFLAGS iff EFLAGS is not live-in.
628  if (Iter == B)
629  return !MBB.isLiveIn(X86::EFLAGS);
630 
631  --Iter;
632  // Skip over debug instructions.
633  while (Iter != B && Iter->isDebugInstr())
634  --Iter;
635 
636  bool SawKill = false;
637  for (unsigned j = 0, e = Iter->getNumOperands(); j != e; ++j) {
638  MachineOperand &MO = Iter->getOperand(j);
639  // A register mask may clobber EFLAGS, but we should still look for a
640  // live EFLAGS def.
641  if (MO.isRegMask() && MO.clobbersPhysReg(X86::EFLAGS))
642  SawKill = true;
643  if (MO.isReg() && MO.getReg() == X86::EFLAGS) {
644  if (MO.isDef()) return MO.isDead();
645  if (MO.isKill()) SawKill = true;
646  }
647  }
648 
649  if (SawKill)
650  // This instruction kills EFLAGS and doesn't redefine it, so
651  // there's no need to look further.
652  return true;
653  }
654 
655  // Conservative answer.
656  return false;
657 }
658 
661  unsigned DestReg, unsigned SubIdx,
662  const MachineInstr &Orig,
663  const TargetRegisterInfo &TRI) const {
664  bool ClobbersEFLAGS = false;
665  for (const MachineOperand &MO : Orig.operands()) {
666  if (MO.isReg() && MO.isDef() && MO.getReg() == X86::EFLAGS) {
667  ClobbersEFLAGS = true;
668  break;
669  }
670  }
671 
672  if (ClobbersEFLAGS && !isSafeToClobberEFLAGS(MBB, I)) {
673  // The instruction clobbers EFLAGS. Re-materialize as MOV32ri to avoid side
674  // effects.
675  int Value;
676  switch (Orig.getOpcode()) {
677  case X86::MOV32r0: Value = 0; break;
678  case X86::MOV32r1: Value = 1; break;
679  case X86::MOV32r_1: Value = -1; break;
680  default:
681  llvm_unreachable("Unexpected instruction!");
682  }
683 
684  const DebugLoc &DL = Orig.getDebugLoc();
685  BuildMI(MBB, I, DL, get(X86::MOV32ri))
686  .add(Orig.getOperand(0))
687  .addImm(Value);
688  } else {
689  MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
690  MBB.insert(I, MI);
691  }
692 
693  MachineInstr &NewMI = *std::prev(I);
694  NewMI.substituteRegister(Orig.getOperand(0).getReg(), DestReg, SubIdx, TRI);
695 }
696 
697 /// True if MI has a condition code def, e.g. EFLAGS, that is not marked dead.
699  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
700  MachineOperand &MO = MI.getOperand(i);
701  if (MO.isReg() && MO.isDef() &&
702  MO.getReg() == X86::EFLAGS && !MO.isDead()) {
703  return true;
704  }
705  }
706  return false;
707 }
708 
709 /// Check whether the shift count for a machine operand is non-zero.
710 inline static unsigned getTruncatedShiftCount(MachineInstr &MI,
711  unsigned ShiftAmtOperandIdx) {
712  // The shift count is six bits with the REX.W prefix and five bits without.
713  unsigned ShiftCountMask = (MI.getDesc().TSFlags & X86II::REX_W) ? 63 : 31;
714  unsigned Imm = MI.getOperand(ShiftAmtOperandIdx).getImm();
715  return Imm & ShiftCountMask;
716 }
717 
718 /// Check whether the given shift count is appropriate
719 /// can be represented by a LEA instruction.
720 inline static bool isTruncatedShiftCountForLEA(unsigned ShAmt) {
721  // Left shift instructions can be transformed into load-effective-address
722  // instructions if we can encode them appropriately.
723  // A LEA instruction utilizes a SIB byte to encode its scale factor.
724  // The SIB.scale field is two bits wide which means that we can encode any
725  // shift amount less than 4.
726  return ShAmt < 4 && ShAmt > 0;
727 }
728 
730  unsigned Opc, bool AllowSP, unsigned &NewSrc,
731  bool &isKill, bool &isUndef,
732  MachineOperand &ImplicitOp,
733  LiveVariables *LV) const {
734  MachineFunction &MF = *MI.getParent()->getParent();
735  const TargetRegisterClass *RC;
736  if (AllowSP) {
737  RC = Opc != X86::LEA32r ? &X86::GR64RegClass : &X86::GR32RegClass;
738  } else {
739  RC = Opc != X86::LEA32r ?
740  &X86::GR64_NOSPRegClass : &X86::GR32_NOSPRegClass;
741  }
742  unsigned SrcReg = Src.getReg();
743 
744  // For both LEA64 and LEA32 the register already has essentially the right
745  // type (32-bit or 64-bit) we may just need to forbid SP.
746  if (Opc != X86::LEA64_32r) {
747  NewSrc = SrcReg;
748  isKill = Src.isKill();
749  isUndef = Src.isUndef();
750 
752  !MF.getRegInfo().constrainRegClass(NewSrc, RC))
753  return false;
754 
755  return true;
756  }
757 
758  // This is for an LEA64_32r and incoming registers are 32-bit. One way or
759  // another we need to add 64-bit registers to the final MI.
761  ImplicitOp = Src;
762  ImplicitOp.setImplicit();
763 
764  NewSrc = getX86SubSuperRegister(Src.getReg(), 64);
765  isKill = Src.isKill();
766  isUndef = Src.isUndef();
767  } else {
768  // Virtual register of the wrong class, we have to create a temporary 64-bit
769  // vreg to feed into the LEA.
770  NewSrc = MF.getRegInfo().createVirtualRegister(RC);
771  MachineInstr *Copy =
772  BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(TargetOpcode::COPY))
773  .addReg(NewSrc, RegState::Define | RegState::Undef, X86::sub_32bit)
774  .add(Src);
775 
776  // Which is obviously going to be dead after we're done with it.
777  isKill = true;
778  isUndef = false;
779 
780  if (LV)
781  LV->replaceKillInstruction(SrcReg, MI, *Copy);
782  }
783 
784  // We've set all the parameters without issue.
785  return true;
786 }
787 
788 /// Helper for convertToThreeAddress when 16-bit LEA is disabled, use 32-bit
789 /// LEA to form 3-address code by promoting to a 32-bit superregister and then
790 /// truncating back down to a 16-bit subregister.
791 MachineInstr *X86InstrInfo::convertToThreeAddressWithLEA(
792  unsigned MIOpc, MachineFunction::iterator &MFI, MachineInstr &MI,
793  LiveVariables *LV) const {
795  unsigned Dest = MI.getOperand(0).getReg();
796  unsigned Src = MI.getOperand(1).getReg();
797  bool isDead = MI.getOperand(0).isDead();
798  bool isKill = MI.getOperand(1).isKill();
799 
800  MachineRegisterInfo &RegInfo = MFI->getParent()->getRegInfo();
801  unsigned leaOutReg = RegInfo.createVirtualRegister(&X86::GR32RegClass);
802  unsigned Opc, leaInReg;
803  if (Subtarget.is64Bit()) {
804  Opc = X86::LEA64_32r;
805  leaInReg = RegInfo.createVirtualRegister(&X86::GR64_NOSPRegClass);
806  } else {
807  Opc = X86::LEA32r;
808  leaInReg = RegInfo.createVirtualRegister(&X86::GR32_NOSPRegClass);
809  }
810 
811  // Build and insert into an implicit UNDEF value. This is OK because
812  // well be shifting and then extracting the lower 16-bits.
813  // This has the potential to cause partial register stall. e.g.
814  // movw (%rbp,%rcx,2), %dx
815  // leal -65(%rdx), %esi
816  // But testing has shown this *does* help performance in 64-bit mode (at
817  // least on modern x86 machines).
818  BuildMI(*MFI, MBBI, MI.getDebugLoc(), get(X86::IMPLICIT_DEF), leaInReg);
819  MachineInstr *InsMI =
820  BuildMI(*MFI, MBBI, MI.getDebugLoc(), get(TargetOpcode::COPY))
821  .addReg(leaInReg, RegState::Define, X86::sub_16bit)
822  .addReg(Src, getKillRegState(isKill));
823 
824  MachineInstrBuilder MIB =
825  BuildMI(*MFI, MBBI, MI.getDebugLoc(), get(Opc), leaOutReg);
826  switch (MIOpc) {
827  default: llvm_unreachable("Unreachable!");
828  case X86::SHL16ri: {
829  unsigned ShAmt = MI.getOperand(2).getImm();
830  MIB.addReg(0).addImm(1ULL << ShAmt)
831  .addReg(leaInReg, RegState::Kill).addImm(0).addReg(0);
832  break;
833  }
834  case X86::INC16r:
835  addRegOffset(MIB, leaInReg, true, 1);
836  break;
837  case X86::DEC16r:
838  addRegOffset(MIB, leaInReg, true, -1);
839  break;
840  case X86::ADD16ri:
841  case X86::ADD16ri8:
842  case X86::ADD16ri_DB:
843  case X86::ADD16ri8_DB:
844  addRegOffset(MIB, leaInReg, true, MI.getOperand(2).getImm());
845  break;
846  case X86::ADD16rr:
847  case X86::ADD16rr_DB: {
848  unsigned Src2 = MI.getOperand(2).getReg();
849  bool isKill2 = MI.getOperand(2).isKill();
850  unsigned leaInReg2 = 0;
851  MachineInstr *InsMI2 = nullptr;
852  if (Src == Src2) {
853  // ADD16rr killed %reg1028, %reg1028
854  // just a single insert_subreg.
855  addRegReg(MIB, leaInReg, true, leaInReg, false);
856  } else {
857  if (Subtarget.is64Bit())
858  leaInReg2 = RegInfo.createVirtualRegister(&X86::GR64_NOSPRegClass);
859  else
860  leaInReg2 = RegInfo.createVirtualRegister(&X86::GR32_NOSPRegClass);
861  // Build and insert into an implicit UNDEF value. This is OK because
862  // well be shifting and then extracting the lower 16-bits.
863  BuildMI(*MFI, &*MIB, MI.getDebugLoc(), get(X86::IMPLICIT_DEF), leaInReg2);
864  InsMI2 = BuildMI(*MFI, &*MIB, MI.getDebugLoc(), get(TargetOpcode::COPY))
865  .addReg(leaInReg2, RegState::Define, X86::sub_16bit)
866  .addReg(Src2, getKillRegState(isKill2));
867  addRegReg(MIB, leaInReg, true, leaInReg2, true);
868  }
869  if (LV && isKill2 && InsMI2)
870  LV->replaceKillInstruction(Src2, MI, *InsMI2);
871  break;
872  }
873  }
874 
875  MachineInstr *NewMI = MIB;
876  MachineInstr *ExtMI =
877  BuildMI(*MFI, MBBI, MI.getDebugLoc(), get(TargetOpcode::COPY))
878  .addReg(Dest, RegState::Define | getDeadRegState(isDead))
879  .addReg(leaOutReg, RegState::Kill, X86::sub_16bit);
880 
881  if (LV) {
882  // Update live variables
883  LV->getVarInfo(leaInReg).Kills.push_back(NewMI);
884  LV->getVarInfo(leaOutReg).Kills.push_back(ExtMI);
885  if (isKill)
886  LV->replaceKillInstruction(Src, MI, *InsMI);
887  if (isDead)
888  LV->replaceKillInstruction(Dest, MI, *ExtMI);
889  }
890 
891  return ExtMI;
892 }
893 
894 /// This method must be implemented by targets that
895 /// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
896 /// may be able to convert a two-address instruction into a true
897 /// three-address instruction on demand. This allows the X86 target (for
898 /// example) to convert ADD and SHL instructions into LEA instructions if they
899 /// would require register copies due to two-addressness.
900 ///
901 /// This method returns a null pointer if the transformation cannot be
902 /// performed, otherwise it returns the new instruction.
903 ///
904 MachineInstr *
906  MachineInstr &MI, LiveVariables *LV) const {
907  // The following opcodes also sets the condition code register(s). Only
908  // convert them to equivalent lea if the condition code register def's
909  // are dead!
910  if (hasLiveCondCodeDef(MI))
911  return nullptr;
912 
913  MachineFunction &MF = *MI.getParent()->getParent();
914  // All instructions input are two-addr instructions. Get the known operands.
915  const MachineOperand &Dest = MI.getOperand(0);
916  const MachineOperand &Src = MI.getOperand(1);
917 
918  MachineInstr *NewMI = nullptr;
919  // FIXME: 16-bit LEA's are really slow on Athlons, but not bad on P4's. When
920  // we have better subtarget support, enable the 16-bit LEA generation here.
921  // 16-bit LEA is also slow on Core2.
922  bool DisableLEA16 = true;
923  bool is64Bit = Subtarget.is64Bit();
924 
925  unsigned MIOpc = MI.getOpcode();
926  switch (MIOpc) {
927  default: return nullptr;
928  case X86::SHL64ri: {
929  assert(MI.getNumOperands() >= 3 && "Unknown shift instruction!");
930  unsigned ShAmt = getTruncatedShiftCount(MI, 2);
931  if (!isTruncatedShiftCountForLEA(ShAmt)) return nullptr;
932 
933  // LEA can't handle RSP.
935  !MF.getRegInfo().constrainRegClass(Src.getReg(),
936  &X86::GR64_NOSPRegClass))
937  return nullptr;
938 
939  NewMI = BuildMI(MF, MI.getDebugLoc(), get(X86::LEA64r))
940  .add(Dest)
941  .addReg(0)
942  .addImm(1ULL << ShAmt)
943  .add(Src)
944  .addImm(0)
945  .addReg(0);
946  break;
947  }
948  case X86::SHL32ri: {
949  assert(MI.getNumOperands() >= 3 && "Unknown shift instruction!");
950  unsigned ShAmt = getTruncatedShiftCount(MI, 2);
951  if (!isTruncatedShiftCountForLEA(ShAmt)) return nullptr;
952 
953  unsigned Opc = is64Bit ? X86::LEA64_32r : X86::LEA32r;
954 
955  // LEA can't handle ESP.
956  bool isKill, isUndef;
957  unsigned SrcReg;
958  MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
959  if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ false,
960  SrcReg, isKill, isUndef, ImplicitOp, LV))
961  return nullptr;
962 
963  MachineInstrBuilder MIB =
964  BuildMI(MF, MI.getDebugLoc(), get(Opc))
965  .add(Dest)
966  .addReg(0)
967  .addImm(1ULL << ShAmt)
968  .addReg(SrcReg, getKillRegState(isKill) | getUndefRegState(isUndef))
969  .addImm(0)
970  .addReg(0);
971  if (ImplicitOp.getReg() != 0)
972  MIB.add(ImplicitOp);
973  NewMI = MIB;
974 
975  break;
976  }
977  case X86::SHL16ri: {
978  assert(MI.getNumOperands() >= 3 && "Unknown shift instruction!");
979  unsigned ShAmt = getTruncatedShiftCount(MI, 2);
980  if (!isTruncatedShiftCountForLEA(ShAmt)) return nullptr;
981 
982  if (DisableLEA16)
983  return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV)
984  : nullptr;
985  NewMI = BuildMI(MF, MI.getDebugLoc(), get(X86::LEA16r))
986  .add(Dest)
987  .addReg(0)
988  .addImm(1ULL << ShAmt)
989  .add(Src)
990  .addImm(0)
991  .addReg(0);
992  break;
993  }
994  case X86::INC64r:
995  case X86::INC32r: {
996  assert(MI.getNumOperands() >= 2 && "Unknown inc instruction!");
997  unsigned Opc = MIOpc == X86::INC64r ? X86::LEA64r
998  : (is64Bit ? X86::LEA64_32r : X86::LEA32r);
999  bool isKill, isUndef;
1000  unsigned SrcReg;
1001  MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1002  if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ false,
1003  SrcReg, isKill, isUndef, ImplicitOp, LV))
1004  return nullptr;
1005 
1006  MachineInstrBuilder MIB =
1007  BuildMI(MF, MI.getDebugLoc(), get(Opc))
1008  .add(Dest)
1009  .addReg(SrcReg,
1010  getKillRegState(isKill) | getUndefRegState(isUndef));
1011  if (ImplicitOp.getReg() != 0)
1012  MIB.add(ImplicitOp);
1013 
1014  NewMI = addOffset(MIB, 1);
1015  break;
1016  }
1017  case X86::INC16r:
1018  if (DisableLEA16)
1019  return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV)
1020  : nullptr;
1021  assert(MI.getNumOperands() >= 2 && "Unknown inc instruction!");
1022  NewMI = addOffset(
1023  BuildMI(MF, MI.getDebugLoc(), get(X86::LEA16r)).add(Dest).add(Src), 1);
1024  break;
1025  case X86::DEC64r:
1026  case X86::DEC32r: {
1027  assert(MI.getNumOperands() >= 2 && "Unknown dec instruction!");
1028  unsigned Opc = MIOpc == X86::DEC64r ? X86::LEA64r
1029  : (is64Bit ? X86::LEA64_32r : X86::LEA32r);
1030 
1031  bool isKill, isUndef;
1032  unsigned SrcReg;
1033  MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1034  if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ false,
1035  SrcReg, isKill, isUndef, ImplicitOp, LV))
1036  return nullptr;
1037 
1038  MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1039  .add(Dest)
1040  .addReg(SrcReg, getUndefRegState(isUndef) |
1041  getKillRegState(isKill));
1042  if (ImplicitOp.getReg() != 0)
1043  MIB.add(ImplicitOp);
1044 
1045  NewMI = addOffset(MIB, -1);
1046 
1047  break;
1048  }
1049  case X86::DEC16r:
1050  if (DisableLEA16)
1051  return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV)
1052  : nullptr;
1053  assert(MI.getNumOperands() >= 2 && "Unknown dec instruction!");
1054  NewMI = addOffset(
1055  BuildMI(MF, MI.getDebugLoc(), get(X86::LEA16r)).add(Dest).add(Src), -1);
1056  break;
1057  case X86::ADD64rr:
1058  case X86::ADD64rr_DB:
1059  case X86::ADD32rr:
1060  case X86::ADD32rr_DB: {
1061  assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1062  unsigned Opc;
1063  if (MIOpc == X86::ADD64rr || MIOpc == X86::ADD64rr_DB)
1064  Opc = X86::LEA64r;
1065  else
1066  Opc = is64Bit ? X86::LEA64_32r : X86::LEA32r;
1067 
1068  bool isKill, isUndef;
1069  unsigned SrcReg;
1070  MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1071  if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ true,
1072  SrcReg, isKill, isUndef, ImplicitOp, LV))
1073  return nullptr;
1074 
1075  const MachineOperand &Src2 = MI.getOperand(2);
1076  bool isKill2, isUndef2;
1077  unsigned SrcReg2;
1078  MachineOperand ImplicitOp2 = MachineOperand::CreateReg(0, false);
1079  if (!classifyLEAReg(MI, Src2, Opc, /*AllowSP=*/ false,
1080  SrcReg2, isKill2, isUndef2, ImplicitOp2, LV))
1081  return nullptr;
1082 
1083  MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc)).add(Dest);
1084  if (ImplicitOp.getReg() != 0)
1085  MIB.add(ImplicitOp);
1086  if (ImplicitOp2.getReg() != 0)
1087  MIB.add(ImplicitOp2);
1088 
1089  NewMI = addRegReg(MIB, SrcReg, isKill, SrcReg2, isKill2);
1090 
1091  // Preserve undefness of the operands.
1092  NewMI->getOperand(1).setIsUndef(isUndef);
1093  NewMI->getOperand(3).setIsUndef(isUndef2);
1094 
1095  if (LV && Src2.isKill())
1096  LV->replaceKillInstruction(SrcReg2, MI, *NewMI);
1097  break;
1098  }
1099  case X86::ADD16rr:
1100  case X86::ADD16rr_DB: {
1101  if (DisableLEA16)
1102  return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV)
1103  : nullptr;
1104  assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1105  unsigned Src2 = MI.getOperand(2).getReg();
1106  bool isKill2 = MI.getOperand(2).isKill();
1107  NewMI = addRegReg(BuildMI(MF, MI.getDebugLoc(), get(X86::LEA16r)).add(Dest),
1108  Src.getReg(), Src.isKill(), Src2, isKill2);
1109 
1110  // Preserve undefness of the operands.
1111  bool isUndef = MI.getOperand(1).isUndef();
1112  bool isUndef2 = MI.getOperand(2).isUndef();
1113  NewMI->getOperand(1).setIsUndef(isUndef);
1114  NewMI->getOperand(3).setIsUndef(isUndef2);
1115 
1116  if (LV && isKill2)
1117  LV->replaceKillInstruction(Src2, MI, *NewMI);
1118  break;
1119  }
1120  case X86::ADD64ri32:
1121  case X86::ADD64ri8:
1122  case X86::ADD64ri32_DB:
1123  case X86::ADD64ri8_DB:
1124  assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1125  NewMI = addOffset(
1126  BuildMI(MF, MI.getDebugLoc(), get(X86::LEA64r)).add(Dest).add(Src),
1127  MI.getOperand(2));
1128  break;
1129  case X86::ADD32ri:
1130  case X86::ADD32ri8:
1131  case X86::ADD32ri_DB:
1132  case X86::ADD32ri8_DB: {
1133  assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1134  unsigned Opc = is64Bit ? X86::LEA64_32r : X86::LEA32r;
1135 
1136  bool isKill, isUndef;
1137  unsigned SrcReg;
1138  MachineOperand ImplicitOp = MachineOperand::CreateReg(0, false);
1139  if (!classifyLEAReg(MI, Src, Opc, /*AllowSP=*/ true,
1140  SrcReg, isKill, isUndef, ImplicitOp, LV))
1141  return nullptr;
1142 
1143  MachineInstrBuilder MIB = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1144  .add(Dest)
1145  .addReg(SrcReg, getUndefRegState(isUndef) |
1146  getKillRegState(isKill));
1147  if (ImplicitOp.getReg() != 0)
1148  MIB.add(ImplicitOp);
1149 
1150  NewMI = addOffset(MIB, MI.getOperand(2));
1151  break;
1152  }
1153  case X86::ADD16ri:
1154  case X86::ADD16ri8:
1155  case X86::ADD16ri_DB:
1156  case X86::ADD16ri8_DB:
1157  if (DisableLEA16)
1158  return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MI, LV)
1159  : nullptr;
1160  assert(MI.getNumOperands() >= 3 && "Unknown add instruction!");
1161  NewMI = addOffset(
1162  BuildMI(MF, MI.getDebugLoc(), get(X86::LEA16r)).add(Dest).add(Src),
1163  MI.getOperand(2));
1164  break;
1165 
1166  case X86::VMOVDQU8Z128rmk:
1167  case X86::VMOVDQU8Z256rmk:
1168  case X86::VMOVDQU8Zrmk:
1169  case X86::VMOVDQU16Z128rmk:
1170  case X86::VMOVDQU16Z256rmk:
1171  case X86::VMOVDQU16Zrmk:
1172  case X86::VMOVDQU32Z128rmk: case X86::VMOVDQA32Z128rmk:
1173  case X86::VMOVDQU32Z256rmk: case X86::VMOVDQA32Z256rmk:
1174  case X86::VMOVDQU32Zrmk: case X86::VMOVDQA32Zrmk:
1175  case X86::VMOVDQU64Z128rmk: case X86::VMOVDQA64Z128rmk:
1176  case X86::VMOVDQU64Z256rmk: case X86::VMOVDQA64Z256rmk:
1177  case X86::VMOVDQU64Zrmk: case X86::VMOVDQA64Zrmk:
1178  case X86::VMOVUPDZ128rmk: case X86::VMOVAPDZ128rmk:
1179  case X86::VMOVUPDZ256rmk: case X86::VMOVAPDZ256rmk:
1180  case X86::VMOVUPDZrmk: case X86::VMOVAPDZrmk:
1181  case X86::VMOVUPSZ128rmk: case X86::VMOVAPSZ128rmk:
1182  case X86::VMOVUPSZ256rmk: case X86::VMOVAPSZ256rmk:
1183  case X86::VMOVUPSZrmk: case X86::VMOVAPSZrmk: {
1184  unsigned Opc;
1185  switch (MIOpc) {
1186  default: llvm_unreachable("Unreachable!");
1187  case X86::VMOVDQU8Z128rmk: Opc = X86::VPBLENDMBZ128rmk; break;
1188  case X86::VMOVDQU8Z256rmk: Opc = X86::VPBLENDMBZ256rmk; break;
1189  case X86::VMOVDQU8Zrmk: Opc = X86::VPBLENDMBZrmk; break;
1190  case X86::VMOVDQU16Z128rmk: Opc = X86::VPBLENDMWZ128rmk; break;
1191  case X86::VMOVDQU16Z256rmk: Opc = X86::VPBLENDMWZ256rmk; break;
1192  case X86::VMOVDQU16Zrmk: Opc = X86::VPBLENDMWZrmk; break;
1193  case X86::VMOVDQU32Z128rmk: Opc = X86::VPBLENDMDZ128rmk; break;
1194  case X86::VMOVDQU32Z256rmk: Opc = X86::VPBLENDMDZ256rmk; break;
1195  case X86::VMOVDQU32Zrmk: Opc = X86::VPBLENDMDZrmk; break;
1196  case X86::VMOVDQU64Z128rmk: Opc = X86::VPBLENDMQZ128rmk; break;
1197  case X86::VMOVDQU64Z256rmk: Opc = X86::VPBLENDMQZ256rmk; break;
1198  case X86::VMOVDQU64Zrmk: Opc = X86::VPBLENDMQZrmk; break;
1199  case X86::VMOVUPDZ128rmk: Opc = X86::VBLENDMPDZ128rmk; break;
1200  case X86::VMOVUPDZ256rmk: Opc = X86::VBLENDMPDZ256rmk; break;
1201  case X86::VMOVUPDZrmk: Opc = X86::VBLENDMPDZrmk; break;
1202  case X86::VMOVUPSZ128rmk: Opc = X86::VBLENDMPSZ128rmk; break;
1203  case X86::VMOVUPSZ256rmk: Opc = X86::VBLENDMPSZ256rmk; break;
1204  case X86::VMOVUPSZrmk: Opc = X86::VBLENDMPSZrmk; break;
1205  case X86::VMOVDQA32Z128rmk: Opc = X86::VPBLENDMDZ128rmk; break;
1206  case X86::VMOVDQA32Z256rmk: Opc = X86::VPBLENDMDZ256rmk; break;
1207  case X86::VMOVDQA32Zrmk: Opc = X86::VPBLENDMDZrmk; break;
1208  case X86::VMOVDQA64Z128rmk: Opc = X86::VPBLENDMQZ128rmk; break;
1209  case X86::VMOVDQA64Z256rmk: Opc = X86::VPBLENDMQZ256rmk; break;
1210  case X86::VMOVDQA64Zrmk: Opc = X86::VPBLENDMQZrmk; break;
1211  case X86::VMOVAPDZ128rmk: Opc = X86::VBLENDMPDZ128rmk; break;
1212  case X86::VMOVAPDZ256rmk: Opc = X86::VBLENDMPDZ256rmk; break;
1213  case X86::VMOVAPDZrmk: Opc = X86::VBLENDMPDZrmk; break;
1214  case X86::VMOVAPSZ128rmk: Opc = X86::VBLENDMPSZ128rmk; break;
1215  case X86::VMOVAPSZ256rmk: Opc = X86::VBLENDMPSZ256rmk; break;
1216  case X86::VMOVAPSZrmk: Opc = X86::VBLENDMPSZrmk; break;
1217  }
1218 
1219  NewMI = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1220  .add(Dest)
1221  .add(MI.getOperand(2))
1222  .add(Src)
1223  .add(MI.getOperand(3))
1224  .add(MI.getOperand(4))
1225  .add(MI.getOperand(5))
1226  .add(MI.getOperand(6))
1227  .add(MI.getOperand(7));
1228  break;
1229  }
1230  case X86::VMOVDQU8Z128rrk:
1231  case X86::VMOVDQU8Z256rrk:
1232  case X86::VMOVDQU8Zrrk:
1233  case X86::VMOVDQU16Z128rrk:
1234  case X86::VMOVDQU16Z256rrk:
1235  case X86::VMOVDQU16Zrrk:
1236  case X86::VMOVDQU32Z128rrk: case X86::VMOVDQA32Z128rrk:
1237  case X86::VMOVDQU32Z256rrk: case X86::VMOVDQA32Z256rrk:
1238  case X86::VMOVDQU32Zrrk: case X86::VMOVDQA32Zrrk:
1239  case X86::VMOVDQU64Z128rrk: case X86::VMOVDQA64Z128rrk:
1240  case X86::VMOVDQU64Z256rrk: case X86::VMOVDQA64Z256rrk:
1241  case X86::VMOVDQU64Zrrk: case X86::VMOVDQA64Zrrk:
1242  case X86::VMOVUPDZ128rrk: case X86::VMOVAPDZ128rrk:
1243  case X86::VMOVUPDZ256rrk: case X86::VMOVAPDZ256rrk:
1244  case X86::VMOVUPDZrrk: case X86::VMOVAPDZrrk:
1245  case X86::VMOVUPSZ128rrk: case X86::VMOVAPSZ128rrk:
1246  case X86::VMOVUPSZ256rrk: case X86::VMOVAPSZ256rrk:
1247  case X86::VMOVUPSZrrk: case X86::VMOVAPSZrrk: {
1248  unsigned Opc;
1249  switch (MIOpc) {
1250  default: llvm_unreachable("Unreachable!");
1251  case X86::VMOVDQU8Z128rrk: Opc = X86::VPBLENDMBZ128rrk; break;
1252  case X86::VMOVDQU8Z256rrk: Opc = X86::VPBLENDMBZ256rrk; break;
1253  case X86::VMOVDQU8Zrrk: Opc = X86::VPBLENDMBZrrk; break;
1254  case X86::VMOVDQU16Z128rrk: Opc = X86::VPBLENDMWZ128rrk; break;
1255  case X86::VMOVDQU16Z256rrk: Opc = X86::VPBLENDMWZ256rrk; break;
1256  case X86::VMOVDQU16Zrrk: Opc = X86::VPBLENDMWZrrk; break;
1257  case X86::VMOVDQU32Z128rrk: Opc = X86::VPBLENDMDZ128rrk; break;
1258  case X86::VMOVDQU32Z256rrk: Opc = X86::VPBLENDMDZ256rrk; break;
1259  case X86::VMOVDQU32Zrrk: Opc = X86::VPBLENDMDZrrk; break;
1260  case X86::VMOVDQU64Z128rrk: Opc = X86::VPBLENDMQZ128rrk; break;
1261  case X86::VMOVDQU64Z256rrk: Opc = X86::VPBLENDMQZ256rrk; break;
1262  case X86::VMOVDQU64Zrrk: Opc = X86::VPBLENDMQZrrk; break;
1263  case X86::VMOVUPDZ128rrk: Opc = X86::VBLENDMPDZ128rrk; break;
1264  case X86::VMOVUPDZ256rrk: Opc = X86::VBLENDMPDZ256rrk; break;
1265  case X86::VMOVUPDZrrk: Opc = X86::VBLENDMPDZrrk; break;
1266  case X86::VMOVUPSZ128rrk: Opc = X86::VBLENDMPSZ128rrk; break;
1267  case X86::VMOVUPSZ256rrk: Opc = X86::VBLENDMPSZ256rrk; break;
1268  case X86::VMOVUPSZrrk: Opc = X86::VBLENDMPSZrrk; break;
1269  case X86::VMOVDQA32Z128rrk: Opc = X86::VPBLENDMDZ128rrk; break;
1270  case X86::VMOVDQA32Z256rrk: Opc = X86::VPBLENDMDZ256rrk; break;
1271  case X86::VMOVDQA32Zrrk: Opc = X86::VPBLENDMDZrrk; break;
1272  case X86::VMOVDQA64Z128rrk: Opc = X86::VPBLENDMQZ128rrk; break;
1273  case X86::VMOVDQA64Z256rrk: Opc = X86::VPBLENDMQZ256rrk; break;
1274  case X86::VMOVDQA64Zrrk: Opc = X86::VPBLENDMQZrrk; break;
1275  case X86::VMOVAPDZ128rrk: Opc = X86::VBLENDMPDZ128rrk; break;
1276  case X86::VMOVAPDZ256rrk: Opc = X86::VBLENDMPDZ256rrk; break;
1277  case X86::VMOVAPDZrrk: Opc = X86::VBLENDMPDZrrk; break;
1278  case X86::VMOVAPSZ128rrk: Opc = X86::VBLENDMPSZ128rrk; break;
1279  case X86::VMOVAPSZ256rrk: Opc = X86::VBLENDMPSZ256rrk; break;
1280  case X86::VMOVAPSZrrk: Opc = X86::VBLENDMPSZrrk; break;
1281  }
1282 
1283  NewMI = BuildMI(MF, MI.getDebugLoc(), get(Opc))
1284  .add(Dest)
1285  .add(MI.getOperand(2))
1286  .add(Src)
1287  .add(MI.getOperand(3));
1288  break;
1289  }
1290  }
1291 
1292  if (!NewMI) return nullptr;
1293 
1294  if (LV) { // Update live variables
1295  if (Src.isKill())
1296  LV->replaceKillInstruction(Src.getReg(), MI, *NewMI);
1297  if (Dest.isDead())
1298  LV->replaceKillInstruction(Dest.getReg(), MI, *NewMI);
1299  }
1300 
1301  MFI->insert(MI.getIterator(), NewMI); // Insert the new inst
1302  return NewMI;
1303 }
1304 
1305 /// This determines which of three possible cases of a three source commute
1306 /// the source indexes correspond to taking into account any mask operands.
1307 /// All prevents commuting a passthru operand. Returns -1 if the commute isn't
1308 /// possible.
1309 /// Case 0 - Possible to commute the first and second operands.
1310 /// Case 1 - Possible to commute the first and third operands.
1311 /// Case 2 - Possible to commute the second and third operands.
1312 static unsigned getThreeSrcCommuteCase(uint64_t TSFlags, unsigned SrcOpIdx1,
1313  unsigned SrcOpIdx2) {
1314  // Put the lowest index to SrcOpIdx1 to simplify the checks below.
1315  if (SrcOpIdx1 > SrcOpIdx2)
1316  std::swap(SrcOpIdx1, SrcOpIdx2);
1317 
1318  unsigned Op1 = 1, Op2 = 2, Op3 = 3;
1319  if (X86II::isKMasked(TSFlags)) {
1320  Op2++;
1321  Op3++;
1322  }
1323 
1324  if (SrcOpIdx1 == Op1 && SrcOpIdx2 == Op2)
1325  return 0;
1326  if (SrcOpIdx1 == Op1 && SrcOpIdx2 == Op3)
1327  return 1;
1328  if (SrcOpIdx1 == Op2 && SrcOpIdx2 == Op3)
1329  return 2;
1330  llvm_unreachable("Unknown three src commute case.");
1331 }
1332 
1334  const MachineInstr &MI, unsigned SrcOpIdx1, unsigned SrcOpIdx2,
1335  const X86InstrFMA3Group &FMA3Group) const {
1336 
1337  unsigned Opc = MI.getOpcode();
1338 
1339  // TODO: Commuting the 1st operand of FMA*_Int requires some additional
1340  // analysis. The commute optimization is legal only if all users of FMA*_Int
1341  // use only the lowest element of the FMA*_Int instruction. Such analysis are
1342  // not implemented yet. So, just return 0 in that case.
1343  // When such analysis are available this place will be the right place for
1344  // calling it.
1345  assert(!(FMA3Group.isIntrinsic() && (SrcOpIdx1 == 1 || SrcOpIdx2 == 1)) &&
1346  "Intrinsic instructions can't commute operand 1");
1347 
1348  // Determine which case this commute is or if it can't be done.
1349  unsigned Case = getThreeSrcCommuteCase(MI.getDesc().TSFlags, SrcOpIdx1,
1350  SrcOpIdx2);
1351  assert(Case < 3 && "Unexpected case number!");
1352 
1353  // Define the FMA forms mapping array that helps to map input FMA form
1354  // to output FMA form to preserve the operation semantics after
1355  // commuting the operands.
1356  const unsigned Form132Index = 0;
1357  const unsigned Form213Index = 1;
1358  const unsigned Form231Index = 2;
1359  static const unsigned FormMapping[][3] = {
1360  // 0: SrcOpIdx1 == 1 && SrcOpIdx2 == 2;
1361  // FMA132 A, C, b; ==> FMA231 C, A, b;
1362  // FMA213 B, A, c; ==> FMA213 A, B, c;
1363  // FMA231 C, A, b; ==> FMA132 A, C, b;
1364  { Form231Index, Form213Index, Form132Index },
1365  // 1: SrcOpIdx1 == 1 && SrcOpIdx2 == 3;
1366  // FMA132 A, c, B; ==> FMA132 B, c, A;
1367  // FMA213 B, a, C; ==> FMA231 C, a, B;
1368  // FMA231 C, a, B; ==> FMA213 B, a, C;
1369  { Form132Index, Form231Index, Form213Index },
1370  // 2: SrcOpIdx1 == 2 && SrcOpIdx2 == 3;
1371  // FMA132 a, C, B; ==> FMA213 a, B, C;
1372  // FMA213 b, A, C; ==> FMA132 b, C, A;
1373  // FMA231 c, A, B; ==> FMA231 c, B, A;
1374  { Form213Index, Form132Index, Form231Index }
1375  };
1376 
1377  unsigned FMAForms[3];
1378  FMAForms[0] = FMA3Group.get132Opcode();
1379  FMAForms[1] = FMA3Group.get213Opcode();
1380  FMAForms[2] = FMA3Group.get231Opcode();
1381  unsigned FormIndex;
1382  for (FormIndex = 0; FormIndex < 3; FormIndex++)
1383  if (Opc == FMAForms[FormIndex])
1384  break;
1385 
1386  // Everything is ready, just adjust the FMA opcode and return it.
1387  FormIndex = FormMapping[Case][FormIndex];
1388  return FMAForms[FormIndex];
1389 }
1390 
1391 static void commuteVPTERNLOG(MachineInstr &MI, unsigned SrcOpIdx1,
1392  unsigned SrcOpIdx2) {
1393  // Determine which case this commute is or if it can't be done.
1394  unsigned Case = getThreeSrcCommuteCase(MI.getDesc().TSFlags, SrcOpIdx1,
1395  SrcOpIdx2);
1396  assert(Case < 3 && "Unexpected case value!");
1397 
1398  // For each case we need to swap two pairs of bits in the final immediate.
1399  static const uint8_t SwapMasks[3][4] = {
1400  { 0x04, 0x10, 0x08, 0x20 }, // Swap bits 2/4 and 3/5.
1401  { 0x02, 0x10, 0x08, 0x40 }, // Swap bits 1/4 and 3/6.
1402  { 0x02, 0x04, 0x20, 0x40 }, // Swap bits 1/2 and 5/6.
1403  };
1404 
1405  uint8_t Imm = MI.getOperand(MI.getNumOperands()-1).getImm();
1406  // Clear out the bits we are swapping.
1407  uint8_t NewImm = Imm & ~(SwapMasks[Case][0] | SwapMasks[Case][1] |
1408  SwapMasks[Case][2] | SwapMasks[Case][3]);
1409  // If the immediate had a bit of the pair set, then set the opposite bit.
1410  if (Imm & SwapMasks[Case][0]) NewImm |= SwapMasks[Case][1];
1411  if (Imm & SwapMasks[Case][1]) NewImm |= SwapMasks[Case][0];
1412  if (Imm & SwapMasks[Case][2]) NewImm |= SwapMasks[Case][3];
1413  if (Imm & SwapMasks[Case][3]) NewImm |= SwapMasks[Case][2];
1414  MI.getOperand(MI.getNumOperands()-1).setImm(NewImm);
1415 }
1416 
1417 // Returns true if this is a VPERMI2 or VPERMT2 instruction that can be
1418 // commuted.
1419 static bool isCommutableVPERMV3Instruction(unsigned Opcode) {
1420 #define VPERM_CASES(Suffix) \
1421  case X86::VPERMI2##Suffix##128rr: case X86::VPERMT2##Suffix##128rr: \
1422  case X86::VPERMI2##Suffix##256rr: case X86::VPERMT2##Suffix##256rr: \
1423  case X86::VPERMI2##Suffix##rr: case X86::VPERMT2##Suffix##rr: \
1424  case X86::VPERMI2##Suffix##128rm: case X86::VPERMT2##Suffix##128rm: \
1425  case X86::VPERMI2##Suffix##256rm: case X86::VPERMT2##Suffix##256rm: \
1426  case X86::VPERMI2##Suffix##rm: case X86::VPERMT2##Suffix##rm: \
1427  case X86::VPERMI2##Suffix##128rrkz: case X86::VPERMT2##Suffix##128rrkz: \
1428  case X86::VPERMI2##Suffix##256rrkz: case X86::VPERMT2##Suffix##256rrkz: \
1429  case X86::VPERMI2##Suffix##rrkz: case X86::VPERMT2##Suffix##rrkz: \
1430  case X86::VPERMI2##Suffix##128rmkz: case X86::VPERMT2##Suffix##128rmkz: \
1431  case X86::VPERMI2##Suffix##256rmkz: case X86::VPERMT2##Suffix##256rmkz: \
1432  case X86::VPERMI2##Suffix##rmkz: case X86::VPERMT2##Suffix##rmkz:
1433 
1434 #define VPERM_CASES_BROADCAST(Suffix) \
1435  VPERM_CASES(Suffix) \
1436  case X86::VPERMI2##Suffix##128rmb: case X86::VPERMT2##Suffix##128rmb: \
1437  case X86::VPERMI2##Suffix##256rmb: case X86::VPERMT2##Suffix##256rmb: \
1438  case X86::VPERMI2##Suffix##rmb: case X86::VPERMT2##Suffix##rmb: \
1439  case X86::VPERMI2##Suffix##128rmbkz: case X86::VPERMT2##Suffix##128rmbkz: \
1440  case X86::VPERMI2##Suffix##256rmbkz: case X86::VPERMT2##Suffix##256rmbkz: \
1441  case X86::VPERMI2##Suffix##rmbkz: case X86::VPERMT2##Suffix##rmbkz:
1442 
1443  switch (Opcode) {
1444  default: return false;
1445  VPERM_CASES(B)
1450  VPERM_CASES(W)
1451  return true;
1452  }
1453 #undef VPERM_CASES_BROADCAST
1454 #undef VPERM_CASES
1455 }
1456 
1457 // Returns commuted opcode for VPERMI2 and VPERMT2 instructions by switching
1458 // from the I opcode to the T opcode and vice versa.
1459 static unsigned getCommutedVPERMV3Opcode(unsigned Opcode) {
1460 #define VPERM_CASES(Orig, New) \
1461  case X86::Orig##128rr: return X86::New##128rr; \
1462  case X86::Orig##128rrkz: return X86::New##128rrkz; \
1463  case X86::Orig##128rm: return X86::New##128rm; \
1464  case X86::Orig##128rmkz: return X86::New##128rmkz; \
1465  case X86::Orig##256rr: return X86::New##256rr; \
1466  case X86::Orig##256rrkz: return X86::New##256rrkz; \
1467  case X86::Orig##256rm: return X86::New##256rm; \
1468  case X86::Orig##256rmkz: return X86::New##256rmkz; \
1469  case X86::Orig##rr: return X86::New##rr; \
1470  case X86::Orig##rrkz: return X86::New##rrkz; \
1471  case X86::Orig##rm: return X86::New##rm; \
1472  case X86::Orig##rmkz: return X86::New##rmkz;
1473 
1474 #define VPERM_CASES_BROADCAST(Orig, New) \
1475  VPERM_CASES(Orig, New) \
1476  case X86::Orig##128rmb: return X86::New##128rmb; \
1477  case X86::Orig##128rmbkz: return X86::New##128rmbkz; \
1478  case X86::Orig##256rmb: return X86::New##256rmb; \
1479  case X86::Orig##256rmbkz: return X86::New##256rmbkz; \
1480  case X86::Orig##rmb: return X86::New##rmb; \
1481  case X86::Orig##rmbkz: return X86::New##rmbkz;
1482 
1483  switch (Opcode) {
1484  VPERM_CASES(VPERMI2B, VPERMT2B)
1485  VPERM_CASES_BROADCAST(VPERMI2D, VPERMT2D)
1486  VPERM_CASES_BROADCAST(VPERMI2PD, VPERMT2PD)
1487  VPERM_CASES_BROADCAST(VPERMI2PS, VPERMT2PS)
1488  VPERM_CASES_BROADCAST(VPERMI2Q, VPERMT2Q)
1489  VPERM_CASES(VPERMI2W, VPERMT2W)
1490  VPERM_CASES(VPERMT2B, VPERMI2B)
1491  VPERM_CASES_BROADCAST(VPERMT2D, VPERMI2D)
1492  VPERM_CASES_BROADCAST(VPERMT2PD, VPERMI2PD)
1493  VPERM_CASES_BROADCAST(VPERMT2PS, VPERMI2PS)
1494  VPERM_CASES_BROADCAST(VPERMT2Q, VPERMI2Q)
1495  VPERM_CASES(VPERMT2W, VPERMI2W)
1496  }
1497 
1498  llvm_unreachable("Unreachable!");
1499 #undef VPERM_CASES_BROADCAST
1500 #undef VPERM_CASES
1501 }
1502 
1504  unsigned OpIdx1,
1505  unsigned OpIdx2) const {
1506  auto cloneIfNew = [NewMI](MachineInstr &MI) -> MachineInstr & {
1507  if (NewMI)
1508  return *MI.getParent()->getParent()->CloneMachineInstr(&MI);
1509  return MI;
1510  };
1511 
1512  switch (MI.getOpcode()) {
1513  case X86::SHRD16rri8: // A = SHRD16rri8 B, C, I -> A = SHLD16rri8 C, B, (16-I)
1514  case X86::SHLD16rri8: // A = SHLD16rri8 B, C, I -> A = SHRD16rri8 C, B, (16-I)
1515  case X86::SHRD32rri8: // A = SHRD32rri8 B, C, I -> A = SHLD32rri8 C, B, (32-I)
1516  case X86::SHLD32rri8: // A = SHLD32rri8 B, C, I -> A = SHRD32rri8 C, B, (32-I)
1517  case X86::SHRD64rri8: // A = SHRD64rri8 B, C, I -> A = SHLD64rri8 C, B, (64-I)
1518  case X86::SHLD64rri8:{// A = SHLD64rri8 B, C, I -> A = SHRD64rri8 C, B, (64-I)
1519  unsigned Opc;
1520  unsigned Size;
1521  switch (MI.getOpcode()) {
1522  default: llvm_unreachable("Unreachable!");
1523  case X86::SHRD16rri8: Size = 16; Opc = X86::SHLD16rri8; break;
1524  case X86::SHLD16rri8: Size = 16; Opc = X86::SHRD16rri8; break;
1525  case X86::SHRD32rri8: Size = 32; Opc = X86::SHLD32rri8; break;
1526  case X86::SHLD32rri8: Size = 32; Opc = X86::SHRD32rri8; break;
1527  case X86::SHRD64rri8: Size = 64; Opc = X86::SHLD64rri8; break;
1528  case X86::SHLD64rri8: Size = 64; Opc = X86::SHRD64rri8; break;
1529  }
1530  unsigned Amt = MI.getOperand(3).getImm();
1531  auto &WorkingMI = cloneIfNew(MI);
1532  WorkingMI.setDesc(get(Opc));
1533  WorkingMI.getOperand(3).setImm(Size - Amt);
1534  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1535  OpIdx1, OpIdx2);
1536  }
1537  case X86::PFSUBrr:
1538  case X86::PFSUBRrr: {
1539  // PFSUB x, y: x = x - y
1540  // PFSUBR x, y: x = y - x
1541  unsigned Opc =
1542  (X86::PFSUBRrr == MI.getOpcode() ? X86::PFSUBrr : X86::PFSUBRrr);
1543  auto &WorkingMI = cloneIfNew(MI);
1544  WorkingMI.setDesc(get(Opc));
1545  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1546  OpIdx1, OpIdx2);
1547  }
1548  case X86::BLENDPDrri:
1549  case X86::BLENDPSrri:
1550  case X86::VBLENDPDrri:
1551  case X86::VBLENDPSrri:
1552  // If we're optimizing for size, try to use MOVSD/MOVSS.
1553  if (MI.getParent()->getParent()->getFunction().optForSize()) {
1554  unsigned Mask, Opc;
1555  switch (MI.getOpcode()) {
1556  default: llvm_unreachable("Unreachable!");
1557  case X86::BLENDPDrri: Opc = X86::MOVSDrr; Mask = 0x03; break;
1558  case X86::BLENDPSrri: Opc = X86::MOVSSrr; Mask = 0x0F; break;
1559  case X86::VBLENDPDrri: Opc = X86::VMOVSDrr; Mask = 0x03; break;
1560  case X86::VBLENDPSrri: Opc = X86::VMOVSSrr; Mask = 0x0F; break;
1561  }
1562  if ((MI.getOperand(3).getImm() ^ Mask) == 1) {
1563  auto &WorkingMI = cloneIfNew(MI);
1564  WorkingMI.setDesc(get(Opc));
1565  WorkingMI.RemoveOperand(3);
1566  return TargetInstrInfo::commuteInstructionImpl(WorkingMI,
1567  /*NewMI=*/false,
1568  OpIdx1, OpIdx2);
1569  }
1570  }
1572  case X86::PBLENDWrri:
1573  case X86::VBLENDPDYrri:
1574  case X86::VBLENDPSYrri:
1575  case X86::VPBLENDDrri:
1576  case X86::VPBLENDWrri:
1577  case X86::VPBLENDDYrri:
1578  case X86::VPBLENDWYrri:{
1579  unsigned Mask;
1580  switch (MI.getOpcode()) {
1581  default: llvm_unreachable("Unreachable!");
1582  case X86::BLENDPDrri: Mask = 0x03; break;
1583  case X86::BLENDPSrri: Mask = 0x0F; break;
1584  case X86::PBLENDWrri: Mask = 0xFF; break;
1585  case X86::VBLENDPDrri: Mask = 0x03; break;
1586  case X86::VBLENDPSrri: Mask = 0x0F; break;
1587  case X86::VBLENDPDYrri: Mask = 0x0F; break;
1588  case X86::VBLENDPSYrri: Mask = 0xFF; break;
1589  case X86::VPBLENDDrri: Mask = 0x0F; break;
1590  case X86::VPBLENDWrri: Mask = 0xFF; break;
1591  case X86::VPBLENDDYrri: Mask = 0xFF; break;
1592  case X86::VPBLENDWYrri: Mask = 0xFF; break;
1593  }
1594  // Only the least significant bits of Imm are used.
1595  unsigned Imm = MI.getOperand(3).getImm() & Mask;
1596  auto &WorkingMI = cloneIfNew(MI);
1597  WorkingMI.getOperand(3).setImm(Mask ^ Imm);
1598  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1599  OpIdx1, OpIdx2);
1600  }
1601  case X86::MOVSDrr:
1602  case X86::MOVSSrr:
1603  case X86::VMOVSDrr:
1604  case X86::VMOVSSrr:{
1605  // On SSE41 or later we can commute a MOVSS/MOVSD to a BLENDPS/BLENDPD.
1606  assert(Subtarget.hasSSE41() && "Commuting MOVSD/MOVSS requires SSE41!");
1607 
1608  unsigned Mask, Opc;
1609  switch (MI.getOpcode()) {
1610  default: llvm_unreachable("Unreachable!");
1611  case X86::MOVSDrr: Opc = X86::BLENDPDrri; Mask = 0x02; break;
1612  case X86::MOVSSrr: Opc = X86::BLENDPSrri; Mask = 0x0E; break;
1613  case X86::VMOVSDrr: Opc = X86::VBLENDPDrri; Mask = 0x02; break;
1614  case X86::VMOVSSrr: Opc = X86::VBLENDPSrri; Mask = 0x0E; break;
1615  }
1616 
1617  auto &WorkingMI = cloneIfNew(MI);
1618  WorkingMI.setDesc(get(Opc));
1619  WorkingMI.addOperand(MachineOperand::CreateImm(Mask));
1620  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1621  OpIdx1, OpIdx2);
1622  }
1623  case X86::PCLMULQDQrr:
1624  case X86::VPCLMULQDQrr:
1625  case X86::VPCLMULQDQYrr:
1626  case X86::VPCLMULQDQZrr:
1627  case X86::VPCLMULQDQZ128rr:
1628  case X86::VPCLMULQDQZ256rr: {
1629  // SRC1 64bits = Imm[0] ? SRC1[127:64] : SRC1[63:0]
1630  // SRC2 64bits = Imm[4] ? SRC2[127:64] : SRC2[63:0]
1631  unsigned Imm = MI.getOperand(3).getImm();
1632  unsigned Src1Hi = Imm & 0x01;
1633  unsigned Src2Hi = Imm & 0x10;
1634  auto &WorkingMI = cloneIfNew(MI);
1635  WorkingMI.getOperand(3).setImm((Src1Hi << 4) | (Src2Hi >> 4));
1636  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1637  OpIdx1, OpIdx2);
1638  }
1639  case X86::VPCMPBZ128rri: case X86::VPCMPUBZ128rri:
1640  case X86::VPCMPBZ256rri: case X86::VPCMPUBZ256rri:
1641  case X86::VPCMPBZrri: case X86::VPCMPUBZrri:
1642  case X86::VPCMPDZ128rri: case X86::VPCMPUDZ128rri:
1643  case X86::VPCMPDZ256rri: case X86::VPCMPUDZ256rri:
1644  case X86::VPCMPDZrri: case X86::VPCMPUDZrri:
1645  case X86::VPCMPQZ128rri: case X86::VPCMPUQZ128rri:
1646  case X86::VPCMPQZ256rri: case X86::VPCMPUQZ256rri:
1647  case X86::VPCMPQZrri: case X86::VPCMPUQZrri:
1648  case X86::VPCMPWZ128rri: case X86::VPCMPUWZ128rri:
1649  case X86::VPCMPWZ256rri: case X86::VPCMPUWZ256rri:
1650  case X86::VPCMPWZrri: case X86::VPCMPUWZrri:
1651  case X86::VPCMPBZ128rrik: case X86::VPCMPUBZ128rrik:
1652  case X86::VPCMPBZ256rrik: case X86::VPCMPUBZ256rrik:
1653  case X86::VPCMPBZrrik: case X86::VPCMPUBZrrik:
1654  case X86::VPCMPDZ128rrik: case X86::VPCMPUDZ128rrik:
1655  case X86::VPCMPDZ256rrik: case X86::VPCMPUDZ256rrik:
1656  case X86::VPCMPDZrrik: case X86::VPCMPUDZrrik:
1657  case X86::VPCMPQZ128rrik: case X86::VPCMPUQZ128rrik:
1658  case X86::VPCMPQZ256rrik: case X86::VPCMPUQZ256rrik:
1659  case X86::VPCMPQZrrik: case X86::VPCMPUQZrrik:
1660  case X86::VPCMPWZ128rrik: case X86::VPCMPUWZ128rrik:
1661  case X86::VPCMPWZ256rrik: case X86::VPCMPUWZ256rrik:
1662  case X86::VPCMPWZrrik: case X86::VPCMPUWZrrik: {
1663  // Flip comparison mode immediate (if necessary).
1664  unsigned Imm = MI.getOperand(MI.getNumOperands() - 1).getImm() & 0x7;
1665  Imm = X86::getSwappedVPCMPImm(Imm);
1666  auto &WorkingMI = cloneIfNew(MI);
1667  WorkingMI.getOperand(MI.getNumOperands() - 1).setImm(Imm);
1668  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1669  OpIdx1, OpIdx2);
1670  }
1671  case X86::VPCOMBri: case X86::VPCOMUBri:
1672  case X86::VPCOMDri: case X86::VPCOMUDri:
1673  case X86::VPCOMQri: case X86::VPCOMUQri:
1674  case X86::VPCOMWri: case X86::VPCOMUWri: {
1675  // Flip comparison mode immediate (if necessary).
1676  unsigned Imm = MI.getOperand(3).getImm() & 0x7;
1677  Imm = X86::getSwappedVPCOMImm(Imm);
1678  auto &WorkingMI = cloneIfNew(MI);
1679  WorkingMI.getOperand(3).setImm(Imm);
1680  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1681  OpIdx1, OpIdx2);
1682  }
1683  case X86::VPERM2F128rr:
1684  case X86::VPERM2I128rr: {
1685  // Flip permute source immediate.
1686  // Imm & 0x02: lo = if set, select Op1.lo/hi else Op0.lo/hi.
1687  // Imm & 0x20: hi = if set, select Op1.lo/hi else Op0.lo/hi.
1688  unsigned Imm = MI.getOperand(3).getImm() & 0xFF;
1689  auto &WorkingMI = cloneIfNew(MI);
1690  WorkingMI.getOperand(3).setImm(Imm ^ 0x22);
1691  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1692  OpIdx1, OpIdx2);
1693  }
1694  case X86::MOVHLPSrr:
1695  case X86::UNPCKHPDrr: {
1696  assert(Subtarget.hasSSE2() && "Commuting MOVHLP/UNPCKHPD requires SSE2!");
1697 
1698  unsigned Opc = MI.getOpcode();
1699  switch (Opc) {
1700  default: llvm_unreachable("Unreachable!");
1701  case X86::MOVHLPSrr: Opc = X86::UNPCKHPDrr; break;
1702  case X86::UNPCKHPDrr: Opc = X86::MOVHLPSrr; break;
1703  }
1704  auto &WorkingMI = cloneIfNew(MI);
1705  WorkingMI.setDesc(get(Opc));
1706  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1707  OpIdx1, OpIdx2);
1708  }
1709  case X86::CMOVB16rr: case X86::CMOVB32rr: case X86::CMOVB64rr:
1710  case X86::CMOVAE16rr: case X86::CMOVAE32rr: case X86::CMOVAE64rr:
1711  case X86::CMOVE16rr: case X86::CMOVE32rr: case X86::CMOVE64rr:
1712  case X86::CMOVNE16rr: case X86::CMOVNE32rr: case X86::CMOVNE64rr:
1713  case X86::CMOVBE16rr: case X86::CMOVBE32rr: case X86::CMOVBE64rr:
1714  case X86::CMOVA16rr: case X86::CMOVA32rr: case X86::CMOVA64rr:
1715  case X86::CMOVL16rr: case X86::CMOVL32rr: case X86::CMOVL64rr:
1716  case X86::CMOVGE16rr: case X86::CMOVGE32rr: case X86::CMOVGE64rr:
1717  case X86::CMOVLE16rr: case X86::CMOVLE32rr: case X86::CMOVLE64rr:
1718  case X86::CMOVG16rr: case X86::CMOVG32rr: case X86::CMOVG64rr:
1719  case X86::CMOVS16rr: case X86::CMOVS32rr: case X86::CMOVS64rr:
1720  case X86::CMOVNS16rr: case X86::CMOVNS32rr: case X86::CMOVNS64rr:
1721  case X86::CMOVP16rr: case X86::CMOVP32rr: case X86::CMOVP64rr:
1722  case X86::CMOVNP16rr: case X86::CMOVNP32rr: case X86::CMOVNP64rr:
1723  case X86::CMOVO16rr: case X86::CMOVO32rr: case X86::CMOVO64rr:
1724  case X86::CMOVNO16rr: case X86::CMOVNO32rr: case X86::CMOVNO64rr: {
1725  unsigned Opc;
1726  switch (MI.getOpcode()) {
1727  default: llvm_unreachable("Unreachable!");
1728  case X86::CMOVB16rr: Opc = X86::CMOVAE16rr; break;
1729  case X86::CMOVB32rr: Opc = X86::CMOVAE32rr; break;
1730  case X86::CMOVB64rr: Opc = X86::CMOVAE64rr; break;
1731  case X86::CMOVAE16rr: Opc = X86::CMOVB16rr; break;
1732  case X86::CMOVAE32rr: Opc = X86::CMOVB32rr; break;
1733  case X86::CMOVAE64rr: Opc = X86::CMOVB64rr; break;
1734  case X86::CMOVE16rr: Opc = X86::CMOVNE16rr; break;
1735  case X86::CMOVE32rr: Opc = X86::CMOVNE32rr; break;
1736  case X86::CMOVE64rr: Opc = X86::CMOVNE64rr; break;
1737  case X86::CMOVNE16rr: Opc = X86::CMOVE16rr; break;
1738  case X86::CMOVNE32rr: Opc = X86::CMOVE32rr; break;
1739  case X86::CMOVNE64rr: Opc = X86::CMOVE64rr; break;
1740  case X86::CMOVBE16rr: Opc = X86::CMOVA16rr; break;
1741  case X86::CMOVBE32rr: Opc = X86::CMOVA32rr; break;
1742  case X86::CMOVBE64rr: Opc = X86::CMOVA64rr; break;
1743  case X86::CMOVA16rr: Opc = X86::CMOVBE16rr; break;
1744  case X86::CMOVA32rr: Opc = X86::CMOVBE32rr; break;
1745  case X86::CMOVA64rr: Opc = X86::CMOVBE64rr; break;
1746  case X86::CMOVL16rr: Opc = X86::CMOVGE16rr; break;
1747  case X86::CMOVL32rr: Opc = X86::CMOVGE32rr; break;
1748  case X86::CMOVL64rr: Opc = X86::CMOVGE64rr; break;
1749  case X86::CMOVGE16rr: Opc = X86::CMOVL16rr; break;
1750  case X86::CMOVGE32rr: Opc = X86::CMOVL32rr; break;
1751  case X86::CMOVGE64rr: Opc = X86::CMOVL64rr; break;
1752  case X86::CMOVLE16rr: Opc = X86::CMOVG16rr; break;
1753  case X86::CMOVLE32rr: Opc = X86::CMOVG32rr; break;
1754  case X86::CMOVLE64rr: Opc = X86::CMOVG64rr; break;
1755  case X86::CMOVG16rr: Opc = X86::CMOVLE16rr; break;
1756  case X86::CMOVG32rr: Opc = X86::CMOVLE32rr; break;
1757  case X86::CMOVG64rr: Opc = X86::CMOVLE64rr; break;
1758  case X86::CMOVS16rr: Opc = X86::CMOVNS16rr; break;
1759  case X86::CMOVS32rr: Opc = X86::CMOVNS32rr; break;
1760  case X86::CMOVS64rr: Opc = X86::CMOVNS64rr; break;
1761  case X86::CMOVNS16rr: Opc = X86::CMOVS16rr; break;
1762  case X86::CMOVNS32rr: Opc = X86::CMOVS32rr; break;
1763  case X86::CMOVNS64rr: Opc = X86::CMOVS64rr; break;
1764  case X86::CMOVP16rr: Opc = X86::CMOVNP16rr; break;
1765  case X86::CMOVP32rr: Opc = X86::CMOVNP32rr; break;
1766  case X86::CMOVP64rr: Opc = X86::CMOVNP64rr; break;
1767  case X86::CMOVNP16rr: Opc = X86::CMOVP16rr; break;
1768  case X86::CMOVNP32rr: Opc = X86::CMOVP32rr; break;
1769  case X86::CMOVNP64rr: Opc = X86::CMOVP64rr; break;
1770  case X86::CMOVO16rr: Opc = X86::CMOVNO16rr; break;
1771  case X86::CMOVO32rr: Opc = X86::CMOVNO32rr; break;
1772  case X86::CMOVO64rr: Opc = X86::CMOVNO64rr; break;
1773  case X86::CMOVNO16rr: Opc = X86::CMOVO16rr; break;
1774  case X86::CMOVNO32rr: Opc = X86::CMOVO32rr; break;
1775  case X86::CMOVNO64rr: Opc = X86::CMOVO64rr; break;
1776  }
1777  auto &WorkingMI = cloneIfNew(MI);
1778  WorkingMI.setDesc(get(Opc));
1779  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1780  OpIdx1, OpIdx2);
1781  }
1782  case X86::VPTERNLOGDZrri: case X86::VPTERNLOGDZrmi:
1783  case X86::VPTERNLOGDZ128rri: case X86::VPTERNLOGDZ128rmi:
1784  case X86::VPTERNLOGDZ256rri: case X86::VPTERNLOGDZ256rmi:
1785  case X86::VPTERNLOGQZrri: case X86::VPTERNLOGQZrmi:
1786  case X86::VPTERNLOGQZ128rri: case X86::VPTERNLOGQZ128rmi:
1787  case X86::VPTERNLOGQZ256rri: case X86::VPTERNLOGQZ256rmi:
1788  case X86::VPTERNLOGDZrrik:
1789  case X86::VPTERNLOGDZ128rrik:
1790  case X86::VPTERNLOGDZ256rrik:
1791  case X86::VPTERNLOGQZrrik:
1792  case X86::VPTERNLOGQZ128rrik:
1793  case X86::VPTERNLOGQZ256rrik:
1794  case X86::VPTERNLOGDZrrikz: case X86::VPTERNLOGDZrmikz:
1795  case X86::VPTERNLOGDZ128rrikz: case X86::VPTERNLOGDZ128rmikz:
1796  case X86::VPTERNLOGDZ256rrikz: case X86::VPTERNLOGDZ256rmikz:
1797  case X86::VPTERNLOGQZrrikz: case X86::VPTERNLOGQZrmikz:
1798  case X86::VPTERNLOGQZ128rrikz: case X86::VPTERNLOGQZ128rmikz:
1799  case X86::VPTERNLOGQZ256rrikz: case X86::VPTERNLOGQZ256rmikz:
1800  case X86::VPTERNLOGDZ128rmbi:
1801  case X86::VPTERNLOGDZ256rmbi:
1802  case X86::VPTERNLOGDZrmbi:
1803  case X86::VPTERNLOGQZ128rmbi:
1804  case X86::VPTERNLOGQZ256rmbi:
1805  case X86::VPTERNLOGQZrmbi:
1806  case X86::VPTERNLOGDZ128rmbikz:
1807  case X86::VPTERNLOGDZ256rmbikz:
1808  case X86::VPTERNLOGDZrmbikz:
1809  case X86::VPTERNLOGQZ128rmbikz:
1810  case X86::VPTERNLOGQZ256rmbikz:
1811  case X86::VPTERNLOGQZrmbikz: {
1812  auto &WorkingMI = cloneIfNew(MI);
1813  commuteVPTERNLOG(WorkingMI, OpIdx1, OpIdx2);
1814  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1815  OpIdx1, OpIdx2);
1816  }
1817  default: {
1819  unsigned Opc = getCommutedVPERMV3Opcode(MI.getOpcode());
1820  auto &WorkingMI = cloneIfNew(MI);
1821  WorkingMI.setDesc(get(Opc));
1822  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1823  OpIdx1, OpIdx2);
1824  }
1825 
1826  const X86InstrFMA3Group *FMA3Group = getFMA3Group(MI.getOpcode(),
1827  MI.getDesc().TSFlags);
1828  if (FMA3Group) {
1829  unsigned Opc =
1830  getFMA3OpcodeToCommuteOperands(MI, OpIdx1, OpIdx2, *FMA3Group);
1831  auto &WorkingMI = cloneIfNew(MI);
1832  WorkingMI.setDesc(get(Opc));
1833  return TargetInstrInfo::commuteInstructionImpl(WorkingMI, /*NewMI=*/false,
1834  OpIdx1, OpIdx2);
1835  }
1836 
1837  return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
1838  }
1839  }
1840 }
1841 
1842 bool
1843 X86InstrInfo::findThreeSrcCommutedOpIndices(const MachineInstr &MI,
1844  unsigned &SrcOpIdx1,
1845  unsigned &SrcOpIdx2,
1846  bool IsIntrinsic) const {
1847  uint64_t TSFlags = MI.getDesc().TSFlags;
1848 
1849  unsigned FirstCommutableVecOp = 1;
1850  unsigned LastCommutableVecOp = 3;
1851  unsigned KMaskOp = -1U;
1852  if (X86II::isKMasked(TSFlags)) {
1853  // For k-zero-masked operations it is Ok to commute the first vector
1854  // operand.
1855  // For regular k-masked operations a conservative choice is done as the
1856  // elements of the first vector operand, for which the corresponding bit
1857  // in the k-mask operand is set to 0, are copied to the result of the
1858  // instruction.
1859  // TODO/FIXME: The commute still may be legal if it is known that the
1860  // k-mask operand is set to either all ones or all zeroes.
1861  // It is also Ok to commute the 1st operand if all users of MI use only
1862  // the elements enabled by the k-mask operand. For example,
1863  // v4 = VFMADD213PSZrk v1, k, v2, v3; // v1[i] = k[i] ? v2[i]*v1[i]+v3[i]
1864  // : v1[i];
1865  // VMOVAPSZmrk <mem_addr>, k, v4; // this is the ONLY user of v4 ->
1866  // // Ok, to commute v1 in FMADD213PSZrk.
1867 
1868  // The k-mask operand has index = 2 for masked and zero-masked operations.
1869  KMaskOp = 2;
1870 
1871  // The operand with index = 1 is used as a source for those elements for
1872  // which the corresponding bit in the k-mask is set to 0.
1873  if (X86II::isKMergeMasked(TSFlags))
1874  FirstCommutableVecOp = 3;
1875 
1876  LastCommutableVecOp++;
1877  } else if (IsIntrinsic) {
1878  // Commuting the first operand of an intrinsic instruction isn't possible
1879  // unless we can prove that only the lowest element of the result is used.
1880  FirstCommutableVecOp = 2;
1881  }
1882 
1883  if (isMem(MI, LastCommutableVecOp))
1884  LastCommutableVecOp--;
1885 
1886  // Only the first RegOpsNum operands are commutable.
1887  // Also, the value 'CommuteAnyOperandIndex' is valid here as it means
1888  // that the operand is not specified/fixed.
1889  if (SrcOpIdx1 != CommuteAnyOperandIndex &&
1890  (SrcOpIdx1 < FirstCommutableVecOp || SrcOpIdx1 > LastCommutableVecOp ||
1891  SrcOpIdx1 == KMaskOp))
1892  return false;
1893  if (SrcOpIdx2 != CommuteAnyOperandIndex &&
1894  (SrcOpIdx2 < FirstCommutableVecOp || SrcOpIdx2 > LastCommutableVecOp ||
1895  SrcOpIdx2 == KMaskOp))
1896  return false;
1897 
1898  // Look for two different register operands assumed to be commutable
1899  // regardless of the FMA opcode. The FMA opcode is adjusted later.
1900  if (SrcOpIdx1 == CommuteAnyOperandIndex ||
1901  SrcOpIdx2 == CommuteAnyOperandIndex) {
1902  unsigned CommutableOpIdx1 = SrcOpIdx1;
1903  unsigned CommutableOpIdx2 = SrcOpIdx2;
1904 
1905  // At least one of operands to be commuted is not specified and
1906  // this method is free to choose appropriate commutable operands.
1907  if (SrcOpIdx1 == SrcOpIdx2)
1908  // Both of operands are not fixed. By default set one of commutable
1909  // operands to the last register operand of the instruction.
1910  CommutableOpIdx2 = LastCommutableVecOp;
1911  else if (SrcOpIdx2 == CommuteAnyOperandIndex)
1912  // Only one of operands is not fixed.
1913  CommutableOpIdx2 = SrcOpIdx1;
1914 
1915  // CommutableOpIdx2 is well defined now. Let's choose another commutable
1916  // operand and assign its index to CommutableOpIdx1.
1917  unsigned Op2Reg = MI.getOperand(CommutableOpIdx2).getReg();
1918  for (CommutableOpIdx1 = LastCommutableVecOp;
1919  CommutableOpIdx1 >= FirstCommutableVecOp; CommutableOpIdx1--) {
1920  // Just ignore and skip the k-mask operand.
1921  if (CommutableOpIdx1 == KMaskOp)
1922  continue;
1923 
1924  // The commuted operands must have different registers.
1925  // Otherwise, the commute transformation does not change anything and
1926  // is useless then.
1927  if (Op2Reg != MI.getOperand(CommutableOpIdx1).getReg())
1928  break;
1929  }
1930 
1931  // No appropriate commutable operands were found.
1932  if (CommutableOpIdx1 < FirstCommutableVecOp)
1933  return false;
1934 
1935  // Assign the found pair of commutable indices to SrcOpIdx1 and SrcOpidx2
1936  // to return those values.
1937  if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
1938  CommutableOpIdx1, CommutableOpIdx2))
1939  return false;
1940  }
1941 
1942  return true;
1943 }
1944 
1946  unsigned &SrcOpIdx2) const {
1947  const MCInstrDesc &Desc = MI.getDesc();
1948  if (!Desc.isCommutable())
1949  return false;
1950 
1951  switch (MI.getOpcode()) {
1952  case X86::CMPSDrr:
1953  case X86::CMPSSrr:
1954  case X86::CMPPDrri:
1955  case X86::CMPPSrri:
1956  case X86::VCMPSDrr:
1957  case X86::VCMPSSrr:
1958  case X86::VCMPPDrri:
1959  case X86::VCMPPSrri:
1960  case X86::VCMPPDYrri:
1961  case X86::VCMPPSYrri:
1962  case X86::VCMPSDZrr:
1963  case X86::VCMPSSZrr:
1964  case X86::VCMPPDZrri:
1965  case X86::VCMPPSZrri:
1966  case X86::VCMPPDZ128rri:
1967  case X86::VCMPPSZ128rri:
1968  case X86::VCMPPDZ256rri:
1969  case X86::VCMPPSZ256rri: {
1970  // Float comparison can be safely commuted for
1971  // Ordered/Unordered/Equal/NotEqual tests
1972  unsigned Imm = MI.getOperand(3).getImm() & 0x7;
1973  switch (Imm) {
1974  case 0x00: // EQUAL
1975  case 0x03: // UNORDERED
1976  case 0x04: // NOT EQUAL
1977  case 0x07: // ORDERED
1978  // The indices of the commutable operands are 1 and 2.
1979  // Assign them to the returned operand indices here.
1980  return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 1, 2);
1981  }
1982  return false;
1983  }
1984  case X86::MOVSDrr:
1985  case X86::MOVSSrr:
1986  case X86::VMOVSDrr:
1987  case X86::VMOVSSrr:
1988  if (Subtarget.hasSSE41())
1989  return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
1990  return false;
1991  case X86::MOVHLPSrr:
1992  case X86::UNPCKHPDrr:
1993  if (Subtarget.hasSSE2())
1994  return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
1995  return false;
1996  case X86::VPTERNLOGDZrri: case X86::VPTERNLOGDZrmi:
1997  case X86::VPTERNLOGDZ128rri: case X86::VPTERNLOGDZ128rmi:
1998  case X86::VPTERNLOGDZ256rri: case X86::VPTERNLOGDZ256rmi:
1999  case X86::VPTERNLOGQZrri: case X86::VPTERNLOGQZrmi:
2000  case X86::VPTERNLOGQZ128rri: case X86::VPTERNLOGQZ128rmi:
2001  case X86::VPTERNLOGQZ256rri: case X86::VPTERNLOGQZ256rmi:
2002  case X86::VPTERNLOGDZrrik:
2003  case X86::VPTERNLOGDZ128rrik:
2004  case X86::VPTERNLOGDZ256rrik:
2005  case X86::VPTERNLOGQZrrik:
2006  case X86::VPTERNLOGQZ128rrik:
2007  case X86::VPTERNLOGQZ256rrik:
2008  case X86::VPTERNLOGDZrrikz: case X86::VPTERNLOGDZrmikz:
2009  case X86::VPTERNLOGDZ128rrikz: case X86::VPTERNLOGDZ128rmikz:
2010  case X86::VPTERNLOGDZ256rrikz: case X86::VPTERNLOGDZ256rmikz:
2011  case X86::VPTERNLOGQZrrikz: case X86::VPTERNLOGQZrmikz:
2012  case X86::VPTERNLOGQZ128rrikz: case X86::VPTERNLOGQZ128rmikz:
2013  case X86::VPTERNLOGQZ256rrikz: case X86::VPTERNLOGQZ256rmikz:
2014  case X86::VPTERNLOGDZ128rmbi:
2015  case X86::VPTERNLOGDZ256rmbi:
2016  case X86::VPTERNLOGDZrmbi:
2017  case X86::VPTERNLOGQZ128rmbi:
2018  case X86::VPTERNLOGQZ256rmbi:
2019  case X86::VPTERNLOGQZrmbi:
2020  case X86::VPTERNLOGDZ128rmbikz:
2021  case X86::VPTERNLOGDZ256rmbikz:
2022  case X86::VPTERNLOGDZrmbikz:
2023  case X86::VPTERNLOGQZ128rmbikz:
2024  case X86::VPTERNLOGQZ256rmbikz:
2025  case X86::VPTERNLOGQZrmbikz:
2026  return findThreeSrcCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2027  case X86::VPMADD52HUQZ128r:
2028  case X86::VPMADD52HUQZ128rk:
2029  case X86::VPMADD52HUQZ128rkz:
2030  case X86::VPMADD52HUQZ256r:
2031  case X86::VPMADD52HUQZ256rk:
2032  case X86::VPMADD52HUQZ256rkz:
2033  case X86::VPMADD52HUQZr:
2034  case X86::VPMADD52HUQZrk:
2035  case X86::VPMADD52HUQZrkz:
2036  case X86::VPMADD52LUQZ128r:
2037  case X86::VPMADD52LUQZ128rk:
2038  case X86::VPMADD52LUQZ128rkz:
2039  case X86::VPMADD52LUQZ256r:
2040  case X86::VPMADD52LUQZ256rk:
2041  case X86::VPMADD52LUQZ256rkz:
2042  case X86::VPMADD52LUQZr:
2043  case X86::VPMADD52LUQZrk:
2044  case X86::VPMADD52LUQZrkz: {
2045  unsigned CommutableOpIdx1 = 2;
2046  unsigned CommutableOpIdx2 = 3;
2047  if (X86II::isKMasked(Desc.TSFlags)) {
2048  // Skip the mask register.
2049  ++CommutableOpIdx1;
2050  ++CommutableOpIdx2;
2051  }
2052  if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
2053  CommutableOpIdx1, CommutableOpIdx2))
2054  return false;
2055  if (!MI.getOperand(SrcOpIdx1).isReg() ||
2056  !MI.getOperand(SrcOpIdx2).isReg())
2057  // No idea.
2058  return false;
2059  return true;
2060  }
2061 
2062  default:
2063  const X86InstrFMA3Group *FMA3Group = getFMA3Group(MI.getOpcode(),
2064  MI.getDesc().TSFlags);
2065  if (FMA3Group)
2066  return findThreeSrcCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2,
2067  FMA3Group->isIntrinsic());
2068 
2069  // Handled masked instructions since we need to skip over the mask input
2070  // and the preserved input.
2071  if (X86II::isKMasked(Desc.TSFlags)) {
2072  // First assume that the first input is the mask operand and skip past it.
2073  unsigned CommutableOpIdx1 = Desc.getNumDefs() + 1;
2074  unsigned CommutableOpIdx2 = Desc.getNumDefs() + 2;
2075  // Check if the first input is tied. If there isn't one then we only
2076  // need to skip the mask operand which we did above.
2077  if ((MI.getDesc().getOperandConstraint(Desc.getNumDefs(),
2078  MCOI::TIED_TO) != -1)) {
2079  // If this is zero masking instruction with a tied operand, we need to
2080  // move the first index back to the first input since this must
2081  // be a 3 input instruction and we want the first two non-mask inputs.
2082  // Otherwise this is a 2 input instruction with a preserved input and
2083  // mask, so we need to move the indices to skip one more input.
2084  if (X86II::isKMergeMasked(Desc.TSFlags)) {
2085  ++CommutableOpIdx1;
2086  ++CommutableOpIdx2;
2087  } else {
2088  --CommutableOpIdx1;
2089  }
2090  }
2091 
2092  if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
2093  CommutableOpIdx1, CommutableOpIdx2))
2094  return false;
2095 
2096  if (!MI.getOperand(SrcOpIdx1).isReg() ||
2097  !MI.getOperand(SrcOpIdx2).isReg())
2098  // No idea.
2099  return false;
2100  return true;
2101  }
2102 
2103  return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
2104  }
2105  return false;
2106 }
2107 
2109  switch (BrOpc) {
2110  default: return X86::COND_INVALID;
2111  case X86::JE_1: return X86::COND_E;
2112  case X86::JNE_1: return X86::COND_NE;
2113  case X86::JL_1: return X86::COND_L;
2114  case X86::JLE_1: return X86::COND_LE;
2115  case X86::JG_1: return X86::COND_G;
2116  case X86::JGE_1: return X86::COND_GE;
2117  case X86::JB_1: return X86::COND_B;
2118  case X86::JBE_1: return X86::COND_BE;
2119  case X86::JA_1: return X86::COND_A;
2120  case X86::JAE_1: return X86::COND_AE;
2121  case X86::JS_1: return X86::COND_S;
2122  case X86::JNS_1: return X86::COND_NS;
2123  case X86::JP_1: return X86::COND_P;
2124  case X86::JNP_1: return X86::COND_NP;
2125  case X86::JO_1: return X86::COND_O;
2126  case X86::JNO_1: return X86::COND_NO;
2127  }
2128 }
2129 
2130 /// Return condition code of a SET opcode.
2132  switch (Opc) {
2133  default: return X86::COND_INVALID;
2134  case X86::SETAr: case X86::SETAm: return X86::COND_A;
2135  case X86::SETAEr: case X86::SETAEm: return X86::COND_AE;
2136  case X86::SETBr: case X86::SETBm: return X86::COND_B;
2137  case X86::SETBEr: case X86::SETBEm: return X86::COND_BE;
2138  case X86::SETEr: case X86::SETEm: return X86::COND_E;
2139  case X86::SETGr: case X86::SETGm: return X86::COND_G;
2140  case X86::SETGEr: case X86::SETGEm: return X86::COND_GE;
2141  case X86::SETLr: case X86::SETLm: return X86::COND_L;
2142  case X86::SETLEr: case X86::SETLEm: return X86::COND_LE;
2143  case X86::SETNEr: case X86::SETNEm: return X86::COND_NE;
2144  case X86::SETNOr: case X86::SETNOm: return X86::COND_NO;
2145  case X86::SETNPr: case X86::SETNPm: return X86::COND_NP;
2146  case X86::SETNSr: case X86::SETNSm: return X86::COND_NS;
2147  case X86::SETOr: case X86::SETOm: return X86::COND_O;
2148  case X86::SETPr: case X86::SETPm: return X86::COND_P;
2149  case X86::SETSr: case X86::SETSm: return X86::COND_S;
2150  }
2151 }
2152 
2153 /// Return condition code of a CMov opcode.
2155  switch (Opc) {
2156  default: return X86::COND_INVALID;
2157  case X86::CMOVA16rm: case X86::CMOVA16rr: case X86::CMOVA32rm:
2158  case X86::CMOVA32rr: case X86::CMOVA64rm: case X86::CMOVA64rr:
2159  return X86::COND_A;
2160  case X86::CMOVAE16rm: case X86::CMOVAE16rr: case X86::CMOVAE32rm:
2161  case X86::CMOVAE32rr: case X86::CMOVAE64rm: case X86::CMOVAE64rr:
2162  return X86::COND_AE;
2163  case X86::CMOVB16rm: case X86::CMOVB16rr: case X86::CMOVB32rm:
2164  case X86::CMOVB32rr: case X86::CMOVB64rm: case X86::CMOVB64rr:
2165  return X86::COND_B;
2166  case X86::CMOVBE16rm: case X86::CMOVBE16rr: case X86::CMOVBE32rm:
2167  case X86::CMOVBE32rr: case X86::CMOVBE64rm: case X86::CMOVBE64rr:
2168  return X86::COND_BE;
2169  case X86::CMOVE16rm: case X86::CMOVE16rr: case X86::CMOVE32rm:
2170  case X86::CMOVE32rr: case X86::CMOVE64rm: case X86::CMOVE64rr:
2171  return X86::COND_E;
2172  case X86::CMOVG16rm: case X86::CMOVG16rr: case X86::CMOVG32rm:
2173  case X86::CMOVG32rr: case X86::CMOVG64rm: case X86::CMOVG64rr:
2174  return X86::COND_G;
2175  case X86::CMOVGE16rm: case X86::CMOVGE16rr: case X86::CMOVGE32rm:
2176  case X86::CMOVGE32rr: case X86::CMOVGE64rm: case X86::CMOVGE64rr:
2177  return X86::COND_GE;
2178  case X86::CMOVL16rm: case X86::CMOVL16rr: case X86::CMOVL32rm:
2179  case X86::CMOVL32rr: case X86::CMOVL64rm: case X86::CMOVL64rr:
2180  return X86::COND_L;
2181  case X86::CMOVLE16rm: case X86::CMOVLE16rr: case X86::CMOVLE32rm:
2182  case X86::CMOVLE32rr: case X86::CMOVLE64rm: case X86::CMOVLE64rr:
2183  return X86::COND_LE;
2184  case X86::CMOVNE16rm: case X86::CMOVNE16rr: case X86::CMOVNE32rm:
2185  case X86::CMOVNE32rr: case X86::CMOVNE64rm: case X86::CMOVNE64rr:
2186  return X86::COND_NE;
2187  case X86::CMOVNO16rm: case X86::CMOVNO16rr: case X86::CMOVNO32rm:
2188  case X86::CMOVNO32rr: case X86::CMOVNO64rm: case X86::CMOVNO64rr:
2189  return X86::COND_NO;
2190  case X86::CMOVNP16rm: case X86::CMOVNP16rr: case X86::CMOVNP32rm:
2191  case X86::CMOVNP32rr: case X86::CMOVNP64rm: case X86::CMOVNP64rr:
2192  return X86::COND_NP;
2193  case X86::CMOVNS16rm: case X86::CMOVNS16rr: case X86::CMOVNS32rm:
2194  case X86::CMOVNS32rr: case X86::CMOVNS64rm: case X86::CMOVNS64rr:
2195  return X86::COND_NS;
2196  case X86::CMOVO16rm: case X86::CMOVO16rr: case X86::CMOVO32rm:
2197  case X86::CMOVO32rr: case X86::CMOVO64rm: case X86::CMOVO64rr:
2198  return X86::COND_O;
2199  case X86::CMOVP16rm: case X86::CMOVP16rr: case X86::CMOVP32rm:
2200  case X86::CMOVP32rr: case X86::CMOVP64rm: case X86::CMOVP64rr:
2201  return X86::COND_P;
2202  case X86::CMOVS16rm: case X86::CMOVS16rr: case X86::CMOVS32rm:
2203  case X86::CMOVS32rr: case X86::CMOVS64rm: case X86::CMOVS64rr:
2204  return X86::COND_S;
2205  }
2206 }
2207 
2209  switch (CC) {
2210  default: llvm_unreachable("Illegal condition code!");
2211  case X86::COND_E: return X86::JE_1;
2212  case X86::COND_NE: return X86::JNE_1;
2213  case X86::COND_L: return X86::JL_1;
2214  case X86::COND_LE: return X86::JLE_1;
2215  case X86::COND_G: return X86::JG_1;
2216  case X86::COND_GE: return X86::JGE_1;
2217  case X86::COND_B: return X86::JB_1;
2218  case X86::COND_BE: return X86::JBE_1;
2219  case X86::COND_A: return X86::JA_1;
2220  case X86::COND_AE: return X86::JAE_1;
2221  case X86::COND_S: return X86::JS_1;
2222  case X86::COND_NS: return X86::JNS_1;
2223  case X86::COND_P: return X86::JP_1;
2224  case X86::COND_NP: return X86::JNP_1;
2225  case X86::COND_O: return X86::JO_1;
2226  case X86::COND_NO: return X86::JNO_1;
2227  }
2228 }
2229 
2230 /// Return the inverse of the specified condition,
2231 /// e.g. turning COND_E to COND_NE.
2233  switch (CC) {
2234  default: llvm_unreachable("Illegal condition code!");
2235  case X86::COND_E: return X86::COND_NE;
2236  case X86::COND_NE: return X86::COND_E;
2237  case X86::COND_L: return X86::COND_GE;
2238  case X86::COND_LE: return X86::COND_G;
2239  case X86::COND_G: return X86::COND_LE;
2240  case X86::COND_GE: return X86::COND_L;
2241  case X86::COND_B: return X86::COND_AE;
2242  case X86::COND_BE: return X86::COND_A;
2243  case X86::COND_A: return X86::COND_BE;
2244  case X86::COND_AE: return X86::COND_B;
2245  case X86::COND_S: return X86::COND_NS;
2246  case X86::COND_NS: return X86::COND_S;
2247  case X86::COND_P: return X86::COND_NP;
2248  case X86::COND_NP: return X86::COND_P;
2249  case X86::COND_O: return X86::COND_NO;
2250  case X86::COND_NO: return X86::COND_O;
2253  }
2254 }
2255 
2256 /// Assuming the flags are set by MI(a,b), return the condition code if we
2257 /// modify the instructions such that flags are set by MI(b,a).
2259  switch (CC) {
2260  default: return X86::COND_INVALID;
2261  case X86::COND_E: return X86::COND_E;
2262  case X86::COND_NE: return X86::COND_NE;
2263  case X86::COND_L: return X86::COND_G;
2264  case X86::COND_LE: return X86::COND_GE;
2265  case X86::COND_G: return X86::COND_L;
2266  case X86::COND_GE: return X86::COND_LE;
2267  case X86::COND_B: return X86::COND_A;
2268  case X86::COND_BE: return X86::COND_AE;
2269  case X86::COND_A: return X86::COND_B;
2270  case X86::COND_AE: return X86::COND_BE;
2271  }
2272 }
2273 
2274 std::pair<X86::CondCode, bool>
2277  bool NeedSwap = false;
2278  switch (Predicate) {
2279  default: break;
2280  // Floating-point Predicates
2281  case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
2282  case CmpInst::FCMP_OLT: NeedSwap = true; LLVM_FALLTHROUGH;
2283  case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
2284  case CmpInst::FCMP_OLE: NeedSwap = true; LLVM_FALLTHROUGH;
2285  case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
2286  case CmpInst::FCMP_UGT: NeedSwap = true; LLVM_FALLTHROUGH;
2287  case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
2288  case CmpInst::FCMP_UGE: NeedSwap = true; LLVM_FALLTHROUGH;
2289  case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
2290  case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
2291  case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
2292  case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
2294  case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
2295 
2296  // Integer Predicates
2297  case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
2298  case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
2299  case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
2300  case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
2301  case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
2302  case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
2303  case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
2304  case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
2305  case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
2306  case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
2307  }
2308 
2309  return std::make_pair(CC, NeedSwap);
2310 }
2311 
2312 /// Return a set opcode for the given condition and
2313 /// whether it has memory operand.
2314 unsigned X86::getSETFromCond(CondCode CC, bool HasMemoryOperand) {
2315  static const uint16_t Opc[16][2] = {
2316  { X86::SETAr, X86::SETAm },
2317  { X86::SETAEr, X86::SETAEm },
2318  { X86::SETBr, X86::SETBm },
2319  { X86::SETBEr, X86::SETBEm },
2320  { X86::SETEr, X86::SETEm },
2321  { X86::SETGr, X86::SETGm },
2322  { X86::SETGEr, X86::SETGEm },
2323  { X86::SETLr, X86::SETLm },
2324  { X86::SETLEr, X86::SETLEm },
2325  { X86::SETNEr, X86::SETNEm },
2326  { X86::SETNOr, X86::SETNOm },
2327  { X86::SETNPr, X86::SETNPm },
2328  { X86::SETNSr, X86::SETNSm },
2329  { X86::SETOr, X86::SETOm },
2330  { X86::SETPr, X86::SETPm },
2331  { X86::SETSr, X86::SETSm }
2332  };
2333 
2334  assert(CC <= LAST_VALID_COND && "Can only handle standard cond codes");
2335  return Opc[CC][HasMemoryOperand ? 1 : 0];
2336 }
2337 
2338 /// Return a cmov opcode for the given condition,
2339 /// register size in bytes, and operand type.
2340 unsigned X86::getCMovFromCond(CondCode CC, unsigned RegBytes,
2341  bool HasMemoryOperand) {
2342  static const uint16_t Opc[32][3] = {
2343  { X86::CMOVA16rr, X86::CMOVA32rr, X86::CMOVA64rr },
2344  { X86::CMOVAE16rr, X86::CMOVAE32rr, X86::CMOVAE64rr },
2345  { X86::CMOVB16rr, X86::CMOVB32rr, X86::CMOVB64rr },
2346  { X86::CMOVBE16rr, X86::CMOVBE32rr, X86::CMOVBE64rr },
2347  { X86::CMOVE16rr, X86::CMOVE32rr, X86::CMOVE64rr },
2348  { X86::CMOVG16rr, X86::CMOVG32rr, X86::CMOVG64rr },
2349  { X86::CMOVGE16rr, X86::CMOVGE32rr, X86::CMOVGE64rr },
2350  { X86::CMOVL16rr, X86::CMOVL32rr, X86::CMOVL64rr },
2351  { X86::CMOVLE16rr, X86::CMOVLE32rr, X86::CMOVLE64rr },
2352  { X86::CMOVNE16rr, X86::CMOVNE32rr, X86::CMOVNE64rr },
2353  { X86::CMOVNO16rr, X86::CMOVNO32rr, X86::CMOVNO64rr },
2354  { X86::CMOVNP16rr, X86::CMOVNP32rr, X86::CMOVNP64rr },
2355  { X86::CMOVNS16rr, X86::CMOVNS32rr, X86::CMOVNS64rr },
2356  { X86::CMOVO16rr, X86::CMOVO32rr, X86::CMOVO64rr },
2357  { X86::CMOVP16rr, X86::CMOVP32rr, X86::CMOVP64rr },
2358  { X86::CMOVS16rr, X86::CMOVS32rr, X86::CMOVS64rr },
2359  { X86::CMOVA16rm, X86::CMOVA32rm, X86::CMOVA64rm },
2360  { X86::CMOVAE16rm, X86::CMOVAE32rm, X86::CMOVAE64rm },
2361  { X86::CMOVB16rm, X86::CMOVB32rm, X86::CMOVB64rm },
2362  { X86::CMOVBE16rm, X86::CMOVBE32rm, X86::CMOVBE64rm },
2363  { X86::CMOVE16rm, X86::CMOVE32rm, X86::CMOVE64rm },
2364  { X86::CMOVG16rm, X86::CMOVG32rm, X86::CMOVG64rm },
2365  { X86::CMOVGE16rm, X86::CMOVGE32rm, X86::CMOVGE64rm },
2366  { X86::CMOVL16rm, X86::CMOVL32rm, X86::CMOVL64rm },
2367  { X86::CMOVLE16rm, X86::CMOVLE32rm, X86::CMOVLE64rm },
2368  { X86::CMOVNE16rm, X86::CMOVNE32rm, X86::CMOVNE64rm },
2369  { X86::CMOVNO16rm, X86::CMOVNO32rm, X86::CMOVNO64rm },
2370  { X86::CMOVNP16rm, X86::CMOVNP32rm, X86::CMOVNP64rm },
2371  { X86::CMOVNS16rm, X86::CMOVNS32rm, X86::CMOVNS64rm },
2372  { X86::CMOVO16rm, X86::CMOVO32rm, X86::CMOVO64rm },
2373  { X86::CMOVP16rm, X86::CMOVP32rm, X86::CMOVP64rm },
2374  { X86::CMOVS16rm, X86::CMOVS32rm, X86::CMOVS64rm }
2375  };
2376 
2377  assert(CC < 16 && "Can only handle standard cond codes");
2378  unsigned Idx = HasMemoryOperand ? 16+CC : CC;
2379  switch(RegBytes) {
2380  default: llvm_unreachable("Illegal register size!");
2381  case 2: return Opc[Idx][0];
2382  case 4: return Opc[Idx][1];
2383  case 8: return Opc[Idx][2];
2384  }
2385 }
2386 
2387 /// Get the VPCMP immediate for the given condition.
2389  switch (CC) {
2390  default: llvm_unreachable("Unexpected SETCC condition");
2391  case ISD::SETNE: return 4;
2392  case ISD::SETEQ: return 0;
2393  case ISD::SETULT:
2394  case ISD::SETLT: return 1;
2395  case ISD::SETUGT:
2396  case ISD::SETGT: return 6;
2397  case ISD::SETUGE:
2398  case ISD::SETGE: return 5;
2399  case ISD::SETULE:
2400  case ISD::SETLE: return 2;
2401  }
2402 }
2403 
2404 /// Get the VPCMP immediate if the opcodes are swapped.
2405 unsigned X86::getSwappedVPCMPImm(unsigned Imm) {
2406  switch (Imm) {
2407  default: llvm_unreachable("Unreachable!");
2408  case 0x01: Imm = 0x06; break; // LT -> NLE
2409  case 0x02: Imm = 0x05; break; // LE -> NLT
2410  case 0x05: Imm = 0x02; break; // NLT -> LE
2411  case 0x06: Imm = 0x01; break; // NLE -> LT
2412  case 0x00: // EQ
2413  case 0x03: // FALSE
2414  case 0x04: // NE
2415  case 0x07: // TRUE
2416  break;
2417  }
2418 
2419  return Imm;
2420 }
2421 
2422 /// Get the VPCOM immediate if the opcodes are swapped.
2423 unsigned X86::getSwappedVPCOMImm(unsigned Imm) {
2424  switch (Imm) {
2425  default: llvm_unreachable("Unreachable!");
2426  case 0x00: Imm = 0x02; break; // LT -> GT
2427  case 0x01: Imm = 0x03; break; // LE -> GE
2428  case 0x02: Imm = 0x00; break; // GT -> LT
2429  case 0x03: Imm = 0x01; break; // GE -> LE
2430  case 0x04: // EQ
2431  case 0x05: // NE
2432  case 0x06: // FALSE
2433  case 0x07: // TRUE
2434  break;
2435  }
2436 
2437  return Imm;
2438 }
2439 
2441  if (!MI.isTerminator()) return false;
2442 
2443  // Conditional branch is a special case.
2444  if (MI.isBranch() && !MI.isBarrier())
2445  return true;
2446  if (!MI.isPredicable())
2447  return true;
2448  return !isPredicated(MI);
2449 }
2450 
2452  switch (MI.getOpcode()) {
2453  case X86::TCRETURNdi:
2454  case X86::TCRETURNri:
2455  case X86::TCRETURNmi:
2456  case X86::TCRETURNdi64:
2457  case X86::TCRETURNri64:
2458  case X86::TCRETURNmi64:
2459  return true;
2460  default:
2461  return false;
2462  }
2463 }
2464 
2466  SmallVectorImpl<MachineOperand> &BranchCond,
2467  const MachineInstr &TailCall) const {
2468  if (TailCall.getOpcode() != X86::TCRETURNdi &&
2469  TailCall.getOpcode() != X86::TCRETURNdi64) {
2470  // Only direct calls can be done with a conditional branch.
2471  return false;
2472  }
2473 
2474  const MachineFunction *MF = TailCall.getParent()->getParent();
2475  if (Subtarget.isTargetWin64() && MF->hasWinCFI()) {
2476  // Conditional tail calls confuse the Win64 unwinder.
2477  return false;
2478  }
2479 
2480  assert(BranchCond.size() == 1);
2481  if (BranchCond[0].getImm() > X86::LAST_VALID_COND) {
2482  // Can't make a conditional tail call with this condition.
2483  return false;
2484  }
2485 
2487  if (X86FI->getTCReturnAddrDelta() != 0 ||
2488  TailCall.getOperand(1).getImm() != 0) {
2489  // A conditional tail call cannot do any stack adjustment.
2490  return false;
2491  }
2492 
2493  return true;
2494 }
2495 
2498  const MachineInstr &TailCall) const {
2499  assert(canMakeTailCallConditional(BranchCond, TailCall));
2500 
2502  while (I != MBB.begin()) {
2503  --I;
2504  if (I->isDebugInstr())
2505  continue;
2506  if (!I->isBranch())
2507  assert(0 && "Can't find the branch to replace!");
2508 
2509  X86::CondCode CC = X86::getCondFromBranchOpc(I->getOpcode());
2510  assert(BranchCond.size() == 1);
2511  if (CC != BranchCond[0].getImm())
2512  continue;
2513 
2514  break;
2515  }
2516 
2517  unsigned Opc = TailCall.getOpcode() == X86::TCRETURNdi ? X86::TCRETURNdicc
2518  : X86::TCRETURNdi64cc;
2519 
2520  auto MIB = BuildMI(MBB, I, MBB.findDebugLoc(I), get(Opc));
2521  MIB->addOperand(TailCall.getOperand(0)); // Destination.
2522  MIB.addImm(0); // Stack offset (not used).
2523  MIB->addOperand(BranchCond[0]); // Condition.
2524  MIB.copyImplicitOps(TailCall); // Regmask and (imp-used) parameters.
2525 
2526  // Add implicit uses and defs of all live regs potentially clobbered by the
2527  // call. This way they still appear live across the call.
2528  LivePhysRegs LiveRegs(getRegisterInfo());
2529  LiveRegs.addLiveOuts(MBB);
2531  LiveRegs.stepForward(*MIB, Clobbers);
2532  for (const auto &C : Clobbers) {
2533  MIB.addReg(C.first, RegState::Implicit);
2534  MIB.addReg(C.first, RegState::Implicit | RegState::Define);
2535  }
2536 
2537  I->eraseFromParent();
2538 }
2539 
2540 // Given a MBB and its TBB, find the FBB which was a fallthrough MBB (it may
2541 // not be a fallthrough MBB now due to layout changes). Return nullptr if the
2542 // fallthrough MBB cannot be identified.
2544  MachineBasicBlock *TBB) {
2545  // Look for non-EHPad successors other than TBB. If we find exactly one, it
2546  // is the fallthrough MBB. If we find zero, then TBB is both the target MBB
2547  // and fallthrough MBB. If we find more than one, we cannot identify the
2548  // fallthrough MBB and should return nullptr.
2549  MachineBasicBlock *FallthroughBB = nullptr;
2550  for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI) {
2551  if ((*SI)->isEHPad() || (*SI == TBB && FallthroughBB))
2552  continue;
2553  // Return a nullptr if we found more than one fallthrough successor.
2554  if (FallthroughBB && FallthroughBB != TBB)
2555  return nullptr;
2556  FallthroughBB = *SI;
2557  }
2558  return FallthroughBB;
2559 }
2560 
2561 bool X86InstrInfo::AnalyzeBranchImpl(
2564  SmallVectorImpl<MachineInstr *> &CondBranches, bool AllowModify) const {
2565 
2566  // Start from the bottom of the block and work up, examining the
2567  // terminator instructions.
2569  MachineBasicBlock::iterator UnCondBrIter = MBB.end();
2570  while (I != MBB.begin()) {
2571  --I;
2572  if (I->isDebugInstr())
2573  continue;
2574 
2575  // Working from the bottom, when we see a non-terminator instruction, we're
2576  // done.
2577  if (!isUnpredicatedTerminator(*I))
2578  break;
2579 
2580  // A terminator that isn't a branch can't easily be handled by this
2581  // analysis.
2582  if (!I->isBranch())
2583  return true;
2584 
2585  // Handle unconditional branches.
2586  if (I->getOpcode() == X86::JMP_1) {
2587  UnCondBrIter = I;
2588 
2589  if (!AllowModify) {
2590  TBB = I->getOperand(0).getMBB();
2591  continue;
2592  }
2593 
2594  // If the block has any instructions after a JMP, delete them.
2595  while (std::next(I) != MBB.end())
2596  std::next(I)->eraseFromParent();
2597 
2598  Cond.clear();
2599  FBB = nullptr;
2600 
2601  // Delete the JMP if it's equivalent to a fall-through.
2602  if (MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
2603  TBB = nullptr;
2604  I->eraseFromParent();
2605  I = MBB.end();
2606  UnCondBrIter = MBB.end();
2607  continue;
2608  }
2609 
2610  // TBB is used to indicate the unconditional destination.
2611  TBB = I->getOperand(0).getMBB();
2612  continue;
2613  }
2614 
2615  // Handle conditional branches.
2616  X86::CondCode BranchCode = X86::getCondFromBranchOpc(I->getOpcode());
2617  if (BranchCode == X86::COND_INVALID)
2618  return true; // Can't handle indirect branch.
2619 
2620  // Working from the bottom, handle the first conditional branch.
2621  if (Cond.empty()) {
2622  MachineBasicBlock *TargetBB = I->getOperand(0).getMBB();
2623  if (AllowModify && UnCondBrIter != MBB.end() &&
2624  MBB.isLayoutSuccessor(TargetBB)) {
2625  // If we can modify the code and it ends in something like:
2626  //
2627  // jCC L1
2628  // jmp L2
2629  // L1:
2630  // ...
2631  // L2:
2632  //
2633  // Then we can change this to:
2634  //
2635  // jnCC L2
2636  // L1:
2637  // ...
2638  // L2:
2639  //
2640  // Which is a bit more efficient.
2641  // We conditionally jump to the fall-through block.
2642  BranchCode = GetOppositeBranchCondition(BranchCode);
2643  unsigned JNCC = GetCondBranchFromCond(BranchCode);
2644  MachineBasicBlock::iterator OldInst = I;
2645 
2646  BuildMI(MBB, UnCondBrIter, MBB.findDebugLoc(I), get(JNCC))
2647  .addMBB(UnCondBrIter->getOperand(0).getMBB());
2648  BuildMI(MBB, UnCondBrIter, MBB.findDebugLoc(I), get(X86::JMP_1))
2649  .addMBB(TargetBB);
2650 
2651  OldInst->eraseFromParent();
2652  UnCondBrIter->eraseFromParent();
2653 
2654  // Restart the analysis.
2655  UnCondBrIter = MBB.end();
2656  I = MBB.end();
2657  continue;
2658  }
2659 
2660  FBB = TBB;
2661  TBB = I->getOperand(0).getMBB();
2662  Cond.push_back(MachineOperand::CreateImm(BranchCode));
2663  CondBranches.push_back(&*I);
2664  continue;
2665  }
2666 
2667  // Handle subsequent conditional branches. Only handle the case where all
2668  // conditional branches branch to the same destination and their condition
2669  // opcodes fit one of the special multi-branch idioms.
2670  assert(Cond.size() == 1);
2671  assert(TBB);
2672 
2673  // If the conditions are the same, we can leave them alone.
2674  X86::CondCode OldBranchCode = (X86::CondCode)Cond[0].getImm();
2675  auto NewTBB = I->getOperand(0).getMBB();
2676  if (OldBranchCode == BranchCode && TBB == NewTBB)
2677  continue;
2678 
2679  // If they differ, see if they fit one of the known patterns. Theoretically,
2680  // we could handle more patterns here, but we shouldn't expect to see them
2681  // if instruction selection has done a reasonable job.
2682  if (TBB == NewTBB &&
2683  ((OldBranchCode == X86::COND_P && BranchCode == X86::COND_NE) ||
2684  (OldBranchCode == X86::COND_NE && BranchCode == X86::COND_P))) {
2685  BranchCode = X86::COND_NE_OR_P;
2686  } else if ((OldBranchCode == X86::COND_NP && BranchCode == X86::COND_NE) ||
2687  (OldBranchCode == X86::COND_E && BranchCode == X86::COND_P)) {
2688  if (NewTBB != (FBB ? FBB : getFallThroughMBB(&MBB, TBB)))
2689  return true;
2690 
2691  // X86::COND_E_AND_NP usually has two different branch destinations.
2692  //
2693  // JP B1
2694  // JE B2
2695  // JMP B1
2696  // B1:
2697  // B2:
2698  //
2699  // Here this condition branches to B2 only if NP && E. It has another
2700  // equivalent form:
2701  //
2702  // JNE B1
2703  // JNP B2
2704  // JMP B1
2705  // B1:
2706  // B2:
2707  //
2708  // Similarly it branches to B2 only if E && NP. That is why this condition
2709  // is named with COND_E_AND_NP.
2710  BranchCode = X86::COND_E_AND_NP;
2711  } else
2712  return true;
2713 
2714  // Update the MachineOperand.
2715  Cond[0].setImm(BranchCode);
2716  CondBranches.push_back(&*I);
2717  }
2718 
2719  return false;
2720 }
2721 
2723  MachineBasicBlock *&TBB,
2724  MachineBasicBlock *&FBB,
2726  bool AllowModify) const {
2727  SmallVector<MachineInstr *, 4> CondBranches;
2728  return AnalyzeBranchImpl(MBB, TBB, FBB, Cond, CondBranches, AllowModify);
2729 }
2730 
2732  MachineBranchPredicate &MBP,
2733  bool AllowModify) const {
2734  using namespace std::placeholders;
2735 
2737  SmallVector<MachineInstr *, 4> CondBranches;
2738  if (AnalyzeBranchImpl(MBB, MBP.TrueDest, MBP.FalseDest, Cond, CondBranches,
2739  AllowModify))
2740  return true;
2741 
2742  if (Cond.size() != 1)
2743  return true;
2744 
2745  assert(MBP.TrueDest && "expected!");
2746 
2747  if (!MBP.FalseDest)
2748  MBP.FalseDest = MBB.getNextNode();
2749 
2751 
2752  MachineInstr *ConditionDef = nullptr;
2753  bool SingleUseCondition = true;
2754 
2755  for (auto I = std::next(MBB.rbegin()), E = MBB.rend(); I != E; ++I) {
2756  if (I->modifiesRegister(X86::EFLAGS, TRI)) {
2757  ConditionDef = &*I;
2758  break;
2759  }
2760 
2761  if (I->readsRegister(X86::EFLAGS, TRI))
2762  SingleUseCondition = false;
2763  }
2764 
2765  if (!ConditionDef)
2766  return true;
2767 
2768  if (SingleUseCondition) {
2769  for (auto *Succ : MBB.successors())
2770  if (Succ->isLiveIn(X86::EFLAGS))
2771  SingleUseCondition = false;
2772  }
2773 
2774  MBP.ConditionDef = ConditionDef;
2775  MBP.SingleUseCondition = SingleUseCondition;
2776 
2777  // Currently we only recognize the simple pattern:
2778  //
2779  // test %reg, %reg
2780  // je %label
2781  //
2782  const unsigned TestOpcode =
2783  Subtarget.is64Bit() ? X86::TEST64rr : X86::TEST32rr;
2784 
2785  if (ConditionDef->getOpcode() == TestOpcode &&
2786  ConditionDef->getNumOperands() == 3 &&
2787  ConditionDef->getOperand(0).isIdenticalTo(ConditionDef->getOperand(1)) &&
2788  (Cond[0].getImm() == X86::COND_NE || Cond[0].getImm() == X86::COND_E)) {
2789  MBP.LHS = ConditionDef->getOperand(0);
2790  MBP.RHS = MachineOperand::CreateImm(0);
2791  MBP.Predicate = Cond[0].getImm() == X86::COND_NE
2794  return false;
2795  }
2796 
2797  return true;
2798 }
2799 
2801  int *BytesRemoved) const {
2802  assert(!BytesRemoved && "code size not handled");
2803 
2805  unsigned Count = 0;
2806 
2807  while (I != MBB.begin()) {
2808  --I;
2809  if (I->isDebugInstr())
2810  continue;
2811  if (I->getOpcode() != X86::JMP_1 &&
2812  X86::getCondFromBranchOpc(I->getOpcode()) == X86::COND_INVALID)
2813  break;
2814  // Remove the branch.
2815  I->eraseFromParent();
2816  I = MBB.end();
2817  ++Count;
2818  }
2819 
2820  return Count;
2821 }
2822 
2824  MachineBasicBlock *TBB,
2825  MachineBasicBlock *FBB,
2827  const DebugLoc &DL,
2828  int *BytesAdded) const {
2829  // Shouldn't be a fall through.
2830  assert(TBB && "insertBranch must not be told to insert a fallthrough");
2831  assert((Cond.size() == 1 || Cond.size() == 0) &&
2832  "X86 branch conditions have one component!");
2833  assert(!BytesAdded && "code size not handled");
2834 
2835  if (Cond.empty()) {
2836  // Unconditional branch?
2837  assert(!FBB && "Unconditional branch with multiple successors!");
2838  BuildMI(&MBB, DL, get(X86::JMP_1)).addMBB(TBB);
2839  return 1;
2840  }
2841 
2842  // If FBB is null, it is implied to be a fall-through block.
2843  bool FallThru = FBB == nullptr;
2844 
2845  // Conditional branch.
2846  unsigned Count = 0;
2847  X86::CondCode CC = (X86::CondCode)Cond[0].getImm();
2848  switch (CC) {
2849  case X86::COND_NE_OR_P:
2850  // Synthesize NE_OR_P with two branches.
2851  BuildMI(&MBB, DL, get(X86::JNE_1)).addMBB(TBB);
2852  ++Count;
2853  BuildMI(&MBB, DL, get(X86::JP_1)).addMBB(TBB);
2854  ++Count;
2855  break;
2856  case X86::COND_E_AND_NP:
2857  // Use the next block of MBB as FBB if it is null.
2858  if (FBB == nullptr) {
2859  FBB = getFallThroughMBB(&MBB, TBB);
2860  assert(FBB && "MBB cannot be the last block in function when the false "
2861  "body is a fall-through.");
2862  }
2863  // Synthesize COND_E_AND_NP with two branches.
2864  BuildMI(&MBB, DL, get(X86::JNE_1)).addMBB(FBB);
2865  ++Count;
2866  BuildMI(&MBB, DL, get(X86::JNP_1)).addMBB(TBB);
2867  ++Count;
2868  break;
2869  default: {
2870  unsigned Opc = GetCondBranchFromCond(CC);
2871  BuildMI(&MBB, DL, get(Opc)).addMBB(TBB);
2872  ++Count;
2873  }
2874  }
2875  if (!FallThru) {
2876  // Two-way Conditional branch. Insert the second branch.
2877  BuildMI(&MBB, DL, get(X86::JMP_1)).addMBB(FBB);
2878  ++Count;
2879  }
2880  return Count;
2881 }
2882 
2883 bool X86InstrInfo::
2886  unsigned TrueReg, unsigned FalseReg,
2887  int &CondCycles, int &TrueCycles, int &FalseCycles) const {
2888  // Not all subtargets have cmov instructions.
2889  if (!Subtarget.hasCMov())
2890  return false;
2891  if (Cond.size() != 1)
2892  return false;
2893  // We cannot do the composite conditions, at least not in SSA form.
2894  if ((X86::CondCode)Cond[0].getImm() > X86::COND_S)
2895  return false;
2896 
2897  // Check register classes.
2898  const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2899  const TargetRegisterClass *RC =
2900  RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
2901  if (!RC)
2902  return false;
2903 
2904  // We have cmov instructions for 16, 32, and 64 bit general purpose registers.
2905  if (X86::GR16RegClass.hasSubClassEq(RC) ||
2906  X86::GR32RegClass.hasSubClassEq(RC) ||
2907  X86::GR64RegClass.hasSubClassEq(RC)) {
2908  // This latency applies to Pentium M, Merom, Wolfdale, Nehalem, and Sandy
2909  // Bridge. Probably Ivy Bridge as well.
2910  CondCycles = 2;
2911  TrueCycles = 2;
2912  FalseCycles = 2;
2913  return true;
2914  }
2915 
2916  // Can't do vectors.
2917  return false;
2918 }
2919 
2922  const DebugLoc &DL, unsigned DstReg,
2923  ArrayRef<MachineOperand> Cond, unsigned TrueReg,
2924  unsigned FalseReg) const {
2927  const TargetRegisterClass &RC = *MRI.getRegClass(DstReg);
2928  assert(Cond.size() == 1 && "Invalid Cond array");
2929  unsigned Opc = getCMovFromCond((X86::CondCode)Cond[0].getImm(),
2930  TRI.getRegSizeInBits(RC) / 8,
2931  false /*HasMemoryOperand*/);
2932  BuildMI(MBB, I, DL, get(Opc), DstReg).addReg(FalseReg).addReg(TrueReg);
2933 }
2934 
2935 /// Test if the given register is a physical h register.
2936 static bool isHReg(unsigned Reg) {
2937  return X86::GR8_ABCD_HRegClass.contains(Reg);
2938 }
2939 
2940 // Try and copy between VR128/VR64 and GR64 registers.
2941 static unsigned CopyToFromAsymmetricReg(unsigned DestReg, unsigned SrcReg,
2942  const X86Subtarget &Subtarget) {
2943  bool HasAVX = Subtarget.hasAVX();
2944  bool HasAVX512 = Subtarget.hasAVX512();
2945 
2946  // SrcReg(MaskReg) -> DestReg(GR64)
2947  // SrcReg(MaskReg) -> DestReg(GR32)
2948 
2949  // All KMASK RegClasses hold the same k registers, can be tested against anyone.
2950  if (X86::VK16RegClass.contains(SrcReg)) {
2951  if (X86::GR64RegClass.contains(DestReg)) {
2952  assert(Subtarget.hasBWI());
2953  return X86::KMOVQrk;
2954  }
2955  if (X86::GR32RegClass.contains(DestReg))
2956  return Subtarget.hasBWI() ? X86::KMOVDrk : X86::KMOVWrk;
2957  }
2958 
2959  // SrcReg(GR64) -> DestReg(MaskReg)
2960  // SrcReg(GR32) -> DestReg(MaskReg)
2961 
2962  // All KMASK RegClasses hold the same k registers, can be tested against anyone.
2963  if (X86::VK16RegClass.contains(DestReg)) {
2964  if (X86::GR64RegClass.contains(SrcReg)) {
2965  assert(Subtarget.hasBWI());
2966  return X86::KMOVQkr;
2967  }
2968  if (X86::GR32RegClass.contains(SrcReg))
2969  return Subtarget.hasBWI() ? X86::KMOVDkr : X86::KMOVWkr;
2970  }
2971 
2972 
2973  // SrcReg(VR128) -> DestReg(GR64)
2974  // SrcReg(VR64) -> DestReg(GR64)
2975  // SrcReg(GR64) -> DestReg(VR128)
2976  // SrcReg(GR64) -> DestReg(VR64)
2977 
2978  if (X86::GR64RegClass.contains(DestReg)) {
2979  if (X86::VR128XRegClass.contains(SrcReg))
2980  // Copy from a VR128 register to a GR64 register.
2981  return HasAVX512 ? X86::VMOVPQIto64Zrr :
2982  HasAVX ? X86::VMOVPQIto64rr :
2983  X86::MOVPQIto64rr;
2984  if (X86::VR64RegClass.contains(SrcReg))
2985  // Copy from a VR64 register to a GR64 register.
2986  return X86::MMX_MOVD64from64rr;
2987  } else if (X86::GR64RegClass.contains(SrcReg)) {
2988  // Copy from a GR64 register to a VR128 register.
2989  if (X86::VR128XRegClass.contains(DestReg))
2990  return HasAVX512 ? X86::VMOV64toPQIZrr :
2991  HasAVX ? X86::VMOV64toPQIrr :
2992  X86::MOV64toPQIrr;
2993  // Copy from a GR64 register to a VR64 register.
2994  if (X86::VR64RegClass.contains(DestReg))
2995  return X86::MMX_MOVD64to64rr;
2996  }
2997 
2998  // SrcReg(FR32) -> DestReg(GR32)
2999  // SrcReg(GR32) -> DestReg(FR32)
3000 
3001  if (X86::GR32RegClass.contains(DestReg) &&
3002  X86::FR32XRegClass.contains(SrcReg))
3003  // Copy from a FR32 register to a GR32 register.
3004  return HasAVX512 ? X86::VMOVSS2DIZrr :
3005  HasAVX ? X86::VMOVSS2DIrr :
3006  X86::MOVSS2DIrr;
3007 
3008  if (X86::FR32XRegClass.contains(DestReg) &&
3009  X86::GR32RegClass.contains(SrcReg))
3010  // Copy from a GR32 register to a FR32 register.
3011  return HasAVX512 ? X86::VMOVDI2SSZrr :
3012  HasAVX ? X86::VMOVDI2SSrr :
3013  X86::MOVDI2SSrr;
3014  return 0;
3015 }
3016 
3019  const DebugLoc &DL, unsigned DestReg,
3020  unsigned SrcReg, bool KillSrc) const {
3021  // First deal with the normal symmetric copies.
3022  bool HasAVX = Subtarget.hasAVX();
3023  bool HasVLX = Subtarget.hasVLX();
3024  unsigned Opc = 0;
3025  if (X86::GR64RegClass.contains(DestReg, SrcReg))
3026  Opc = X86::MOV64rr;
3027  else if (X86::GR32RegClass.contains(DestReg, SrcReg))
3028  Opc = X86::MOV32rr;
3029  else if (X86::GR16RegClass.contains(DestReg, SrcReg))
3030  Opc = X86::MOV16rr;
3031  else if (X86::GR8RegClass.contains(DestReg, SrcReg)) {
3032  // Copying to or from a physical H register on x86-64 requires a NOREX
3033  // move. Otherwise use a normal move.
3034  if ((isHReg(DestReg) || isHReg(SrcReg)) &&
3035  Subtarget.is64Bit()) {
3036  Opc = X86::MOV8rr_NOREX;
3037  // Both operands must be encodable without an REX prefix.
3038  assert(X86::GR8_NOREXRegClass.contains(SrcReg, DestReg) &&
3039  "8-bit H register can not be copied outside GR8_NOREX");
3040  } else
3041  Opc = X86::MOV8rr;
3042  }
3043  else if (X86::VR64RegClass.contains(DestReg, SrcReg))
3044  Opc = X86::MMX_MOVQ64rr;
3045  else if (X86::VR128XRegClass.contains(DestReg, SrcReg)) {
3046  if (HasVLX)
3047  Opc = X86::VMOVAPSZ128rr;
3048  else if (X86::VR128RegClass.contains(DestReg, SrcReg))
3049  Opc = HasAVX ? X86::VMOVAPSrr : X86::MOVAPSrr;
3050  else {
3051  // If this an extended register and we don't have VLX we need to use a
3052  // 512-bit move.
3053  Opc = X86::VMOVAPSZrr;
3055  DestReg = TRI->getMatchingSuperReg(DestReg, X86::sub_xmm,
3056  &X86::VR512RegClass);
3057  SrcReg = TRI->getMatchingSuperReg(SrcReg, X86::sub_xmm,
3058  &X86::VR512RegClass);
3059  }
3060  } else if (X86::VR256XRegClass.contains(DestReg, SrcReg)) {
3061  if (HasVLX)
3062  Opc = X86::VMOVAPSZ256rr;
3063  else if (X86::VR256RegClass.contains(DestReg, SrcReg))
3064  Opc = X86::VMOVAPSYrr;
3065  else {
3066  // If this an extended register and we don't have VLX we need to use a
3067  // 512-bit move.
3068  Opc = X86::VMOVAPSZrr;
3070  DestReg = TRI->getMatchingSuperReg(DestReg, X86::sub_ymm,
3071  &X86::VR512RegClass);
3072  SrcReg = TRI->getMatchingSuperReg(SrcReg, X86::sub_ymm,
3073  &X86::VR512RegClass);
3074  }
3075  } else if (X86::VR512RegClass.contains(DestReg, SrcReg))
3076  Opc = X86::VMOVAPSZrr;
3077  // All KMASK RegClasses hold the same k registers, can be tested against anyone.
3078  else if (X86::VK16RegClass.contains(DestReg, SrcReg))
3079  Opc = Subtarget.hasBWI() ? X86::KMOVQkk : X86::KMOVWkk;
3080  if (!Opc)
3081  Opc = CopyToFromAsymmetricReg(DestReg, SrcReg, Subtarget);
3082 
3083  if (Opc) {
3084  BuildMI(MBB, MI, DL, get(Opc), DestReg)
3085  .addReg(SrcReg, getKillRegState(KillSrc));
3086  return;
3087  }
3088 
3089  if (SrcReg == X86::EFLAGS || DestReg == X86::EFLAGS) {
3090  // FIXME: We use a fatal error here because historically LLVM has tried
3091  // lower some of these physreg copies and we want to ensure we get
3092  // reasonable bug reports if someone encounters a case no other testing
3093  // found. This path should be removed after the LLVM 7 release.
3094  report_fatal_error("Unable to copy EFLAGS physical register!");
3095  }
3096 
3097  LLVM_DEBUG(dbgs() << "Cannot copy " << RI.getName(SrcReg) << " to "
3098  << RI.getName(DestReg) << '\n');
3099  llvm_unreachable("Cannot emit physreg copy instruction");
3100 }
3101 
3103  const MachineOperand *&Src,
3104  const MachineOperand *&Dest) const {
3105  if (MI.isMoveReg()) {
3106  Dest = &MI.getOperand(0);
3107  Src = &MI.getOperand(1);
3108  return true;
3109  }
3110  return false;
3111 }
3112 
3113 static unsigned getLoadStoreRegOpcode(unsigned Reg,
3114  const TargetRegisterClass *RC,
3115  bool isStackAligned,
3116  const X86Subtarget &STI,
3117  bool load) {
3118  bool HasAVX = STI.hasAVX();
3119  bool HasAVX512 = STI.hasAVX512();
3120  bool HasVLX = STI.hasVLX();
3121 
3122  switch (STI.getRegisterInfo()->getSpillSize(*RC)) {
3123  default:
3124  llvm_unreachable("Unknown spill size");
3125  case 1:
3126  assert(X86::GR8RegClass.hasSubClassEq(RC) && "Unknown 1-byte regclass");
3127  if (STI.is64Bit())
3128  // Copying to or from a physical H register on x86-64 requires a NOREX
3129  // move. Otherwise use a normal move.
3130  if (isHReg(Reg) || X86::GR8_ABCD_HRegClass.hasSubClassEq(RC))
3131  return load ? X86::MOV8rm_NOREX : X86::MOV8mr_NOREX;
3132  return load ? X86::MOV8rm : X86::MOV8mr;
3133  case 2:
3134  if (X86::VK16RegClass.hasSubClassEq(RC))
3135  return load ? X86::KMOVWkm : X86::KMOVWmk;
3136  assert(X86::GR16RegClass.hasSubClassEq(RC) && "Unknown 2-byte regclass");
3137  return load ? X86::MOV16rm : X86::MOV16mr;
3138  case 4:
3139  if (X86::GR32RegClass.hasSubClassEq(RC))
3140  return load ? X86::MOV32rm : X86::MOV32mr;
3141  if (X86::FR32XRegClass.hasSubClassEq(RC))
3142  return load ?
3143  (HasAVX512 ? X86::VMOVSSZrm : HasAVX ? X86::VMOVSSrm : X86::MOVSSrm) :
3144  (HasAVX512 ? X86::VMOVSSZmr : HasAVX ? X86::VMOVSSmr : X86::MOVSSmr);
3145  if (X86::RFP32RegClass.hasSubClassEq(RC))
3146  return load ? X86::LD_Fp32m : X86::ST_Fp32m;
3147  if (X86::VK32RegClass.hasSubClassEq(RC)) {
3148  assert(STI.hasBWI() && "KMOVD requires BWI");
3149  return load ? X86::KMOVDkm : X86::KMOVDmk;
3150  }
3151  llvm_unreachable("Unknown 4-byte regclass");
3152  case 8:
3153  if (X86::GR64RegClass.hasSubClassEq(RC))
3154  return load ? X86::MOV64rm : X86::MOV64mr;
3155  if (X86::FR64XRegClass.hasSubClassEq(RC))
3156  return load ?
3157  (HasAVX512 ? X86::VMOVSDZrm : HasAVX ? X86::VMOVSDrm : X86::MOVSDrm) :
3158  (HasAVX512 ? X86::VMOVSDZmr : HasAVX ? X86::VMOVSDmr : X86::MOVSDmr);
3159  if (X86::VR64RegClass.hasSubClassEq(RC))
3160  return load ? X86::MMX_MOVQ64rm : X86::MMX_MOVQ64mr;
3161  if (X86::RFP64RegClass.hasSubClassEq(RC))
3162  return load ? X86::LD_Fp64m : X86::ST_Fp64m;
3163  if (X86::VK64RegClass.hasSubClassEq(RC)) {
3164  assert(STI.hasBWI() && "KMOVQ requires BWI");
3165  return load ? X86::KMOVQkm : X86::KMOVQmk;
3166  }
3167  llvm_unreachable("Unknown 8-byte regclass");
3168  case 10:
3169  assert(X86::RFP80RegClass.hasSubClassEq(RC) && "Unknown 10-byte regclass");
3170  return load ? X86::LD_Fp80m : X86::ST_FpP80m;
3171  case 16: {
3172  if (X86::VR128XRegClass.hasSubClassEq(RC)) {
3173  // If stack is realigned we can use aligned stores.
3174  if (isStackAligned)
3175  return load ?
3176  (HasVLX ? X86::VMOVAPSZ128rm :
3177  HasAVX512 ? X86::VMOVAPSZ128rm_NOVLX :
3178  HasAVX ? X86::VMOVAPSrm :
3179  X86::MOVAPSrm):
3180  (HasVLX ? X86::VMOVAPSZ128mr :
3181  HasAVX512 ? X86::VMOVAPSZ128mr_NOVLX :
3182  HasAVX ? X86::VMOVAPSmr :
3183  X86::MOVAPSmr);
3184  else
3185  return load ?
3186  (HasVLX ? X86::VMOVUPSZ128rm :
3187  HasAVX512 ? X86::VMOVUPSZ128rm_NOVLX :
3188  HasAVX ? X86::VMOVUPSrm :
3189  X86::MOVUPSrm):
3190  (HasVLX ? X86::VMOVUPSZ128mr :
3191  HasAVX512 ? X86::VMOVUPSZ128mr_NOVLX :
3192  HasAVX ? X86::VMOVUPSmr :
3193  X86::MOVUPSmr);
3194  }
3195  if (X86::BNDRRegClass.hasSubClassEq(RC)) {
3196  if (STI.is64Bit())
3197  return load ? X86::BNDMOV64rm : X86::BNDMOV64mr;
3198  else
3199  return load ? X86::BNDMOV32rm : X86::BNDMOV32mr;
3200  }
3201  llvm_unreachable("Unknown 16-byte regclass");
3202  }
3203  case 32:
3204  assert(X86::VR256XRegClass.hasSubClassEq(RC) && "Unknown 32-byte regclass");
3205  // If stack is realigned we can use aligned stores.
3206  if (isStackAligned)
3207  return load ?
3208  (HasVLX ? X86::VMOVAPSZ256rm :
3209  HasAVX512 ? X86::VMOVAPSZ256rm_NOVLX :
3210  X86::VMOVAPSYrm) :
3211  (HasVLX ? X86::VMOVAPSZ256mr :
3212  HasAVX512 ? X86::VMOVAPSZ256mr_NOVLX :
3213  X86::VMOVAPSYmr);
3214  else
3215  return load ?
3216  (HasVLX ? X86::VMOVUPSZ256rm :
3217  HasAVX512 ? X86::VMOVUPSZ256rm_NOVLX :
3218  X86::VMOVUPSYrm) :
3219  (HasVLX ? X86::VMOVUPSZ256mr :
3220  HasAVX512 ? X86::VMOVUPSZ256mr_NOVLX :
3221  X86::VMOVUPSYmr);
3222  case 64:
3223  assert(X86::VR512RegClass.hasSubClassEq(RC) && "Unknown 64-byte regclass");
3224  assert(STI.hasAVX512() && "Using 512-bit register requires AVX512");
3225  if (isStackAligned)
3226  return load ? X86::VMOVAPSZrm : X86::VMOVAPSZmr;
3227  else
3228  return load ? X86::VMOVUPSZrm : X86::VMOVUPSZmr;
3229  }
3230 }
3231 
3232 bool X86InstrInfo::getMemOpBaseRegImmOfs(MachineInstr &MemOp, unsigned &BaseReg,
3233  int64_t &Offset,
3234  const TargetRegisterInfo *TRI) const {
3235  const MCInstrDesc &Desc = MemOp.getDesc();
3236  int MemRefBegin = X86II::getMemoryOperandNo(Desc.TSFlags);
3237  if (MemRefBegin < 0)
3238  return false;
3239 
3240  MemRefBegin += X86II::getOperandBias(Desc);
3241 
3242  MachineOperand &BaseMO = MemOp.getOperand(MemRefBegin + X86::AddrBaseReg);
3243  if (!BaseMO.isReg()) // Can be an MO_FrameIndex
3244  return false;
3245 
3246  BaseReg = BaseMO.getReg();
3247  if (MemOp.getOperand(MemRefBegin + X86::AddrScaleAmt).getImm() != 1)
3248  return false;
3249 
3250  if (MemOp.getOperand(MemRefBegin + X86::AddrIndexReg).getReg() !=
3251  X86::NoRegister)
3252  return false;
3253 
3254  const MachineOperand &DispMO = MemOp.getOperand(MemRefBegin + X86::AddrDisp);
3255 
3256  // Displacement can be symbolic
3257  if (!DispMO.isImm())
3258  return false;
3259 
3260  Offset = DispMO.getImm();
3261 
3262  return true;
3263 }
3264 
3265 static unsigned getStoreRegOpcode(unsigned SrcReg,
3266  const TargetRegisterClass *RC,
3267  bool isStackAligned,
3268  const X86Subtarget &STI) {
3269  return getLoadStoreRegOpcode(SrcReg, RC, isStackAligned, STI, false);
3270 }
3271 
3272 
3273 static unsigned getLoadRegOpcode(unsigned DestReg,
3274  const TargetRegisterClass *RC,
3275  bool isStackAligned,
3276  const X86Subtarget &STI) {
3277  return getLoadStoreRegOpcode(DestReg, RC, isStackAligned, STI, true);
3278 }
3279 
3282  unsigned SrcReg, bool isKill, int FrameIdx,
3283  const TargetRegisterClass *RC,
3284  const TargetRegisterInfo *TRI) const {
3285  const MachineFunction &MF = *MBB.getParent();
3286  assert(MF.getFrameInfo().getObjectSize(FrameIdx) >= TRI->getSpillSize(*RC) &&
3287  "Stack slot too small for store");
3288  unsigned Alignment = std::max<uint32_t>(TRI->getSpillSize(*RC), 16);
3289  bool isAligned =
3290  (Subtarget.getFrameLowering()->getStackAlignment() >= Alignment) ||
3291  RI.canRealignStack(MF);
3292  unsigned Opc = getStoreRegOpcode(SrcReg, RC, isAligned, Subtarget);
3293  DebugLoc DL = MBB.findDebugLoc(MI);
3294  addFrameReference(BuildMI(MBB, MI, DL, get(Opc)), FrameIdx)
3295  .addReg(SrcReg, getKillRegState(isKill));
3296 }
3297 
3299  bool isKill,
3301  const TargetRegisterClass *RC,
3302  MachineInstr::mmo_iterator MMOBegin,
3304  SmallVectorImpl<MachineInstr*> &NewMIs) const {
3306  unsigned Alignment = std::max<uint32_t>(TRI.getSpillSize(*RC), 16);
3307  bool isAligned = MMOBegin != MMOEnd &&
3308  (*MMOBegin)->getAlignment() >= Alignment;
3309  unsigned Opc = getStoreRegOpcode(SrcReg, RC, isAligned, Subtarget);
3310  DebugLoc DL;
3311  MachineInstrBuilder MIB = BuildMI(MF, DL, get(Opc));
3312  for (unsigned i = 0, e = Addr.size(); i != e; ++i)
3313  MIB.add(Addr[i]);
3314  MIB.addReg(SrcReg, getKillRegState(isKill));
3315  (*MIB).setMemRefs(MMOBegin, MMOEnd);
3316  NewMIs.push_back(MIB);
3317 }
3318 
3319 
3322  unsigned DestReg, int FrameIdx,
3323  const TargetRegisterClass *RC,
3324  const TargetRegisterInfo *TRI) const {
3325  const MachineFunction &MF = *MBB.getParent();
3326  unsigned Alignment = std::max<uint32_t>(TRI->getSpillSize(*RC), 16);
3327  bool isAligned =
3328  (Subtarget.getFrameLowering()->getStackAlignment() >= Alignment) ||
3329  RI.canRealignStack(MF);
3330  unsigned Opc = getLoadRegOpcode(DestReg, RC, isAligned, Subtarget);
3331  DebugLoc DL = MBB.findDebugLoc(MI);
3332  addFrameReference(BuildMI(MBB, MI, DL, get(Opc), DestReg), FrameIdx);
3333 }
3334 
3337  const TargetRegisterClass *RC,
3338  MachineInstr::mmo_iterator MMOBegin,
3340  SmallVectorImpl<MachineInstr*> &NewMIs) const {
3342  unsigned Alignment = std::max<uint32_t>(TRI.getSpillSize(*RC), 16);
3343  bool isAligned = MMOBegin != MMOEnd &&
3344  (*MMOBegin)->getAlignment() >= Alignment;
3345  unsigned Opc = getLoadRegOpcode(DestReg, RC, isAligned, Subtarget);
3346  DebugLoc DL;
3347  MachineInstrBuilder MIB = BuildMI(MF, DL, get(Opc), DestReg);
3348  for (unsigned i = 0, e = Addr.size(); i != e; ++i)
3349  MIB.add(Addr[i]);
3350  (*MIB).setMemRefs(MMOBegin, MMOEnd);
3351  NewMIs.push_back(MIB);
3352 }
3353 
3354 bool X86InstrInfo::analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
3355  unsigned &SrcReg2, int &CmpMask,
3356  int &CmpValue) const {
3357  switch (MI.getOpcode()) {
3358  default: break;
3359  case X86::CMP64ri32:
3360  case X86::CMP64ri8:
3361  case X86::CMP32ri:
3362  case X86::CMP32ri8:
3363  case X86::CMP16ri:
3364  case X86::CMP16ri8:
3365  case X86::CMP8ri:
3366  SrcReg = MI.getOperand(0).getReg();
3367  SrcReg2 = 0;
3368  if (MI.getOperand(1).isImm()) {
3369  CmpMask = ~0;
3370  CmpValue = MI.getOperand(1).getImm();
3371  } else {
3372  CmpMask = CmpValue = 0;
3373  }
3374  return true;
3375  // A SUB can be used to perform comparison.
3376  case X86::SUB64rm:
3377  case X86::SUB32rm:
3378  case X86::SUB16rm:
3379  case X86::SUB8rm:
3380  SrcReg = MI.getOperand(1).getReg();
3381  SrcReg2 = 0;
3382  CmpMask = 0;
3383  CmpValue = 0;
3384  return true;
3385  case X86::SUB64rr:
3386  case X86::SUB32rr:
3387  case X86::SUB16rr:
3388  case X86::SUB8rr:
3389  SrcReg = MI.getOperand(1).getReg();
3390  SrcReg2 = MI.getOperand(2).getReg();
3391  CmpMask = 0;
3392  CmpValue = 0;
3393  return true;
3394  case X86::SUB64ri32:
3395  case X86::SUB64ri8:
3396  case X86::SUB32ri:
3397  case X86::SUB32ri8:
3398  case X86::SUB16ri:
3399  case X86::SUB16ri8:
3400  case X86::SUB8ri:
3401  SrcReg = MI.getOperand(1).getReg();
3402  SrcReg2 = 0;
3403  if (MI.getOperand(2).isImm()) {
3404  CmpMask = ~0;
3405  CmpValue = MI.getOperand(2).getImm();
3406  } else {
3407  CmpMask = CmpValue = 0;
3408  }
3409  return true;
3410  case X86::CMP64rr:
3411  case X86::CMP32rr:
3412  case X86::CMP16rr:
3413  case X86::CMP8rr:
3414  SrcReg = MI.getOperand(0).getReg();
3415  SrcReg2 = MI.getOperand(1).getReg();
3416  CmpMask = 0;
3417  CmpValue = 0;
3418  return true;
3419  case X86::TEST8rr:
3420  case X86::TEST16rr:
3421  case X86::TEST32rr:
3422  case X86::TEST64rr:
3423  SrcReg = MI.getOperand(0).getReg();
3424  if (MI.getOperand(1).getReg() != SrcReg)
3425  return false;
3426  // Compare against zero.
3427  SrcReg2 = 0;
3428  CmpMask = ~0;
3429  CmpValue = 0;
3430  return true;
3431  }
3432  return false;
3433 }
3434 
3435 /// Check whether the first instruction, whose only
3436 /// purpose is to update flags, can be made redundant.
3437 /// CMPrr can be made redundant by SUBrr if the operands are the same.
3438 /// This function can be extended later on.
3439 /// SrcReg, SrcRegs: register operands for FlagI.
3440 /// ImmValue: immediate for FlagI if it takes an immediate.
3441 inline static bool isRedundantFlagInstr(MachineInstr &FlagI, unsigned SrcReg,
3442  unsigned SrcReg2, int ImmMask,
3443  int ImmValue, MachineInstr &OI) {
3444  if (((FlagI.getOpcode() == X86::CMP64rr && OI.getOpcode() == X86::SUB64rr) ||
3445  (FlagI.getOpcode() == X86::CMP32rr && OI.getOpcode() == X86::SUB32rr) ||
3446  (FlagI.getOpcode() == X86::CMP16rr && OI.getOpcode() == X86::SUB16rr) ||
3447  (FlagI.getOpcode() == X86::CMP8rr && OI.getOpcode() == X86::SUB8rr)) &&
3448  ((OI.getOperand(1).getReg() == SrcReg &&
3449  OI.getOperand(2).getReg() == SrcReg2) ||
3450  (OI.getOperand(1).getReg() == SrcReg2 &&
3451  OI.getOperand(2).getReg() == SrcReg)))
3452  return true;
3453 
3454  if (ImmMask != 0 &&
3455  ((FlagI.getOpcode() == X86::CMP64ri32 &&
3456  OI.getOpcode() == X86::SUB64ri32) ||
3457  (FlagI.getOpcode() == X86::CMP64ri8 &&
3458  OI.getOpcode() == X86::SUB64ri8) ||
3459  (FlagI.getOpcode() == X86::CMP32ri && OI.getOpcode() == X86::SUB32ri) ||
3460  (FlagI.getOpcode() == X86::CMP32ri8 &&
3461  OI.getOpcode() == X86::SUB32ri8) ||
3462  (FlagI.getOpcode() == X86::CMP16ri && OI.getOpcode() == X86::SUB16ri) ||
3463  (FlagI.getOpcode() == X86::CMP16ri8 &&
3464  OI.getOpcode() == X86::SUB16ri8) ||
3465  (FlagI.getOpcode() == X86::CMP8ri && OI.getOpcode() == X86::SUB8ri)) &&
3466  OI.getOperand(1).getReg() == SrcReg &&
3467  OI.getOperand(2).getImm() == ImmValue)
3468  return true;
3469  return false;
3470 }
3471 
3472 /// Check whether the definition can be converted
3473 /// to remove a comparison against zero.
3474 inline static bool isDefConvertible(MachineInstr &MI) {
3475  switch (MI.getOpcode()) {
3476  default: return false;
3477 
3478  // The shift instructions only modify ZF if their shift count is non-zero.
3479  // N.B.: The processor truncates the shift count depending on the encoding.
3480  case X86::SAR8ri: case X86::SAR16ri: case X86::SAR32ri:case X86::SAR64ri:
3481  case X86::SHR8ri: case X86::SHR16ri: case X86::SHR32ri:case X86::SHR64ri:
3482  return getTruncatedShiftCount(MI, 2) != 0;
3483 
3484  // Some left shift instructions can be turned into LEA instructions but only
3485  // if their flags aren't used. Avoid transforming such instructions.
3486  case X86::SHL8ri: case X86::SHL16ri: case X86::SHL32ri:case X86::SHL64ri:{
3487  unsigned ShAmt = getTruncatedShiftCount(MI, 2);
3488  if (isTruncatedShiftCountForLEA(ShAmt)) return false;
3489  return ShAmt != 0;
3490  }
3491 
3492  case X86::SHRD16rri8:case X86::SHRD32rri8:case X86::SHRD64rri8:
3493  case X86::SHLD16rri8:case X86::SHLD32rri8:case X86::SHLD64rri8:
3494  return getTruncatedShiftCount(MI, 3) != 0;
3495 
3496  case X86::SUB64ri32: case X86::SUB64ri8: case X86::SUB32ri:
3497  case X86::SUB32ri8: case X86::SUB16ri: case X86::SUB16ri8:
3498  case X86::SUB8ri: case X86::SUB64rr: case X86::SUB32rr:
3499  case X86::SUB16rr: case X86::SUB8rr: case X86::SUB64rm:
3500  case X86::SUB32rm: case X86::SUB16rm: case X86::SUB8rm:
3501  case X86::DEC64r: case X86::DEC32r: case X86::DEC16r: case X86::DEC8r:
3502  case X86::ADD64ri32: case X86::ADD64ri8: case X86::ADD32ri:
3503  case X86::ADD32ri8: case X86::ADD16ri: case X86::ADD16ri8:
3504  case X86::ADD8ri: case X86::ADD64rr: case X86::ADD32rr:
3505  case X86::ADD16rr: case X86::ADD8rr: case X86::ADD64rm:
3506  case X86::ADD32rm: case X86::ADD16rm: case X86::ADD8rm:
3507  case X86::INC64r: case X86::INC32r: case X86::INC16r: case X86::INC8r:
3508  case X86::AND64ri32: case X86::AND64ri8: case X86::AND32ri:
3509  case X86::AND32ri8: case X86::AND16ri: case X86::AND16ri8:
3510  case X86::AND8ri: case X86::AND64rr: case X86::AND32rr:
3511  case X86::AND16rr: case X86::AND8rr: case X86::AND64rm:
3512  case X86::AND32rm: case X86::AND16rm: case X86::AND8rm:
3513  case X86::XOR64ri32: case X86::XOR64ri8: case X86::XOR32ri:
3514  case X86::XOR32ri8: case X86::XOR16ri: case X86::XOR16ri8:
3515  case X86::XOR8ri: case X86::XOR64rr: case X86::XOR32rr:
3516  case X86::XOR16rr: case X86::XOR8rr: case X86::XOR64rm:
3517  case X86::XOR32rm: case X86::XOR16rm: case X86::XOR8rm:
3518  case X86::OR64ri32: case X86::OR64ri8: case X86::OR32ri:
3519  case X86::OR32ri8: case X86::OR16ri: case X86::OR16ri8:
3520  case X86::OR8ri: case X86::OR64rr: case X86::OR32rr:
3521  case X86::OR16rr: case X86::OR8rr: case X86::OR64rm:
3522  case X86::OR32rm: case X86::OR16rm: case X86::OR8rm:
3523  case X86::ADC64ri32: case X86::ADC64ri8: case X86::ADC32ri:
3524  case X86::ADC32ri8: case X86::ADC16ri: case X86::ADC16ri8:
3525  case X86::ADC8ri: case X86::ADC64rr: case X86::ADC32rr:
3526  case X86::ADC16rr: case X86::ADC8rr: case X86::ADC64rm:
3527  case X86::ADC32rm: case X86::ADC16rm: case X86::ADC8rm:
3528  case X86::SBB64ri32: case X86::SBB64ri8: case X86::SBB32ri:
3529  case X86::SBB32ri8: case X86::SBB16ri: case X86::SBB16ri8:
3530  case X86::SBB8ri: case X86::SBB64rr: case X86::SBB32rr:
3531  case X86::SBB16rr: case X86::SBB8rr: case X86::SBB64rm:
3532  case X86::SBB32rm: case X86::SBB16rm: case X86::SBB8rm:
3533  case X86::NEG8r: case X86::NEG16r: case X86::NEG32r: case X86::NEG64r:
3534  case X86::SAR8r1: case X86::SAR16r1: case X86::SAR32r1:case X86::SAR64r1:
3535  case X86::SHR8r1: case X86::SHR16r1: case X86::SHR32r1:case X86::SHR64r1:
3536  case X86::SHL8r1: case X86::SHL16r1: case X86::SHL32r1:case X86::SHL64r1:
3537  case X86::ANDN32rr: case X86::ANDN32rm:
3538  case X86::ANDN64rr: case X86::ANDN64rm:
3539  case X86::BEXTR32rr: case X86::BEXTR64rr:
3540  case X86::BEXTR32rm: case X86::BEXTR64rm:
3541  case X86::BLSI32rr: case X86::BLSI32rm:
3542  case X86::BLSI64rr: case X86::BLSI64rm:
3543  case X86::BLSMSK32rr:case X86::BLSMSK32rm:
3544  case X86::BLSMSK64rr:case X86::BLSMSK64rm:
3545  case X86::BLSR32rr: case X86::BLSR32rm:
3546  case X86::BLSR64rr: case X86::BLSR64rm:
3547  case X86::BZHI32rr: case X86::BZHI32rm:
3548  case X86::BZHI64rr: case X86::BZHI64rm:
3549  case X86::LZCNT16rr: case X86::LZCNT16rm:
3550  case X86::LZCNT32rr: case X86::LZCNT32rm:
3551  case X86::LZCNT64rr: case X86::LZCNT64rm:
3552  case X86::POPCNT16rr:case X86::POPCNT16rm:
3553  case X86::POPCNT32rr:case X86::POPCNT32rm:
3554  case X86::POPCNT64rr:case X86::POPCNT64rm:
3555  case X86::TZCNT16rr: case X86::TZCNT16rm:
3556  case X86::TZCNT32rr: case X86::TZCNT32rm:
3557  case X86::TZCNT64rr: case X86::TZCNT64rm:
3558  case X86::BEXTRI32ri: case X86::BEXTRI32mi:
3559  case X86::BEXTRI64ri: case X86::BEXTRI64mi:
3560  case X86::BLCFILL32rr: case X86::BLCFILL32rm:
3561  case X86::BLCFILL64rr: case X86::BLCFILL64rm:
3562  case X86::BLCI32rr: case X86::BLCI32rm:
3563  case X86::BLCI64rr: case X86::BLCI64rm:
3564  case X86::BLCIC32rr: case X86::BLCIC32rm:
3565  case X86::BLCIC64rr: case X86::BLCIC64rm:
3566  case X86::BLCMSK32rr: case X86::BLCMSK32rm:
3567  case X86::BLCMSK64rr: case X86::BLCMSK64rm:
3568  case X86::BLCS32rr: case X86::BLCS32rm:
3569  case X86::BLCS64rr: case X86::BLCS64rm:
3570  case X86::BLSFILL32rr: case X86::BLSFILL32rm:
3571  case X86::BLSFILL64rr: case X86::BLSFILL64rm:
3572  case X86::BLSIC32rr: case X86::BLSIC32rm:
3573  case X86::BLSIC64rr: case X86::BLSIC64rm:
3574  return true;
3575  }
3576 }
3577 
3578 /// Check whether the use can be converted to remove a comparison against zero.
3580  switch (MI.getOpcode()) {
3581  default: return X86::COND_INVALID;
3582  case X86::LZCNT16rr: case X86::LZCNT16rm:
3583  case X86::LZCNT32rr: case X86::LZCNT32rm:
3584  case X86::LZCNT64rr: case X86::LZCNT64rm:
3585  return X86::COND_B;
3586  case X86::POPCNT16rr:case X86::POPCNT16rm:
3587  case X86::POPCNT32rr:case X86::POPCNT32rm:
3588  case X86::POPCNT64rr:case X86::POPCNT64rm:
3589  return X86::COND_E;
3590  case X86::TZCNT16rr: case X86::TZCNT16rm:
3591  case X86::TZCNT32rr: case X86::TZCNT32rm:
3592  case X86::TZCNT64rr: case X86::TZCNT64rm:
3593  return X86::COND_B;
3594  case X86::BSF16rr:
3595  case X86::BSF16rm:
3596  case X86::BSF32rr:
3597  case X86::BSF32rm:
3598  case X86::BSF64rr:
3599  case X86::BSF64rm:
3600  return X86::COND_E;
3601  }
3602 }
3603 
3604 /// Check if there exists an earlier instruction that
3605 /// operates on the same source operands and sets flags in the same way as
3606 /// Compare; remove Compare if possible.
3607 bool X86InstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, unsigned SrcReg,
3608  unsigned SrcReg2, int CmpMask,
3609  int CmpValue,
3610  const MachineRegisterInfo *MRI) const {
3611  // Check whether we can replace SUB with CMP.
3612  unsigned NewOpcode = 0;
3613  switch (CmpInstr.getOpcode()) {
3614  default: break;
3615  case X86::SUB64ri32:
3616  case X86::SUB64ri8:
3617  case X86::SUB32ri:
3618  case X86::SUB32ri8:
3619  case X86::SUB16ri:
3620  case X86::SUB16ri8:
3621  case X86::SUB8ri:
3622  case X86::SUB64rm:
3623  case X86::SUB32rm:
3624  case X86::SUB16rm:
3625  case X86::SUB8rm:
3626  case X86::SUB64rr:
3627  case X86::SUB32rr:
3628  case X86::SUB16rr:
3629  case X86::SUB8rr: {
3630  if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
3631  return false;
3632  // There is no use of the destination register, we can replace SUB with CMP.
3633  switch (CmpInstr.getOpcode()) {
3634  default: llvm_unreachable("Unreachable!");
3635  case X86::SUB64rm: NewOpcode = X86::CMP64rm; break;
3636  case X86::SUB32rm: NewOpcode = X86::CMP32rm; break;
3637  case X86::SUB16rm: NewOpcode = X86::CMP16rm; break;
3638  case X86::SUB8rm: NewOpcode = X86::CMP8rm; break;
3639  case X86::SUB64rr: NewOpcode = X86::CMP64rr; break;
3640  case X86::SUB32rr: NewOpcode = X86::CMP32rr; break;
3641  case X86::SUB16rr: NewOpcode = X86::CMP16rr; break;
3642  case X86::SUB8rr: NewOpcode = X86::CMP8rr; break;
3643  case X86::SUB64ri32: NewOpcode = X86::CMP64ri32; break;
3644  case X86::SUB64ri8: NewOpcode = X86::CMP64ri8; break;
3645  case X86::SUB32ri: NewOpcode = X86::CMP32ri; break;
3646  case X86::SUB32ri8: NewOpcode = X86::CMP32ri8; break;
3647  case X86::SUB16ri: NewOpcode = X86::CMP16ri; break;
3648  case X86::SUB16ri8: NewOpcode = X86::CMP16ri8; break;
3649  case X86::SUB8ri: NewOpcode = X86::CMP8ri; break;
3650  }
3651  CmpInstr.setDesc(get(NewOpcode));
3652  CmpInstr.RemoveOperand(0);
3653  // Fall through to optimize Cmp if Cmp is CMPrr or CMPri.
3654  if (NewOpcode == X86::CMP64rm || NewOpcode == X86::CMP32rm ||
3655  NewOpcode == X86::CMP16rm || NewOpcode == X86::CMP8rm)
3656  return false;
3657  }
3658  }
3659 
3660  // Get the unique definition of SrcReg.
3661  MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
3662  if (!MI) return false;
3663 
3664  // CmpInstr is the first instruction of the BB.
3665  MachineBasicBlock::iterator I = CmpInstr, Def = MI;
3666 
3667  // If we are comparing against zero, check whether we can use MI to update
3668  // EFLAGS. If MI is not in the same BB as CmpInstr, do not optimize.
3669  bool IsCmpZero = (CmpMask != 0 && CmpValue == 0);
3670  if (IsCmpZero && MI->getParent() != CmpInstr.getParent())
3671  return false;
3672 
3673  // If we have a use of the source register between the def and our compare
3674  // instruction we can eliminate the compare iff the use sets EFLAGS in the
3675  // right way.
3676  bool ShouldUpdateCC = false;
3678  if (IsCmpZero && !isDefConvertible(*MI)) {
3679  // Scan forward from the use until we hit the use we're looking for or the
3680  // compare instruction.
3681  for (MachineBasicBlock::iterator J = MI;; ++J) {
3682  // Do we have a convertible instruction?
3683  NewCC = isUseDefConvertible(*J);
3684  if (NewCC != X86::COND_INVALID && J->getOperand(1).isReg() &&
3685  J->getOperand(1).getReg() == SrcReg) {
3686  assert(J->definesRegister(X86::EFLAGS) && "Must be an EFLAGS def!");
3687  ShouldUpdateCC = true; // Update CC later on.
3688  // This is not a def of SrcReg, but still a def of EFLAGS. Keep going
3689  // with the new def.
3690  Def = J;
3691  MI = &*Def;
3692  break;
3693  }
3694 
3695  if (J == I)
3696  return false;
3697  }
3698  }
3699 
3700  // We are searching for an earlier instruction that can make CmpInstr
3701  // redundant and that instruction will be saved in Sub.
3702  MachineInstr *Sub = nullptr;
3704 
3705  // We iterate backward, starting from the instruction before CmpInstr and
3706  // stop when reaching the definition of a source register or done with the BB.
3707  // RI points to the instruction before CmpInstr.
3708  // If the definition is in this basic block, RE points to the definition;
3709  // otherwise, RE is the rend of the basic block.
3711  RI = ++I.getReverse(),
3712  RE = CmpInstr.getParent() == MI->getParent()
3713  ? Def.getReverse() /* points to MI */
3714  : CmpInstr.getParent()->rend();
3715  MachineInstr *Movr0Inst = nullptr;
3716  for (; RI != RE; ++RI) {
3717  MachineInstr &Instr = *RI;
3718  // Check whether CmpInstr can be made redundant by the current instruction.
3719  if (!IsCmpZero && isRedundantFlagInstr(CmpInstr, SrcReg, SrcReg2, CmpMask,
3720  CmpValue, Instr)) {
3721  Sub = &Instr;
3722  break;
3723  }
3724 
3725  if (Instr.modifiesRegister(X86::EFLAGS, TRI) ||
3726  Instr.readsRegister(X86::EFLAGS, TRI)) {
3727  // This instruction modifies or uses EFLAGS.
3728 
3729  // MOV32r0 etc. are implemented with xor which clobbers condition code.
3730  // They are safe to move up, if the definition to EFLAGS is dead and
3731  // earlier instructions do not read or write EFLAGS.
3732  if (!Movr0Inst && Instr.getOpcode() == X86::MOV32r0 &&
3733  Instr.registerDefIsDead(X86::EFLAGS, TRI)) {
3734  Movr0Inst = &Instr;
3735  continue;
3736  }
3737 
3738  // We can't remove CmpInstr.
3739  return false;
3740  }
3741  }
3742 
3743  // Return false if no candidates exist.
3744  if (!IsCmpZero && !Sub)
3745  return false;
3746 
3747  bool IsSwapped = (SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
3748  Sub->getOperand(2).getReg() == SrcReg);
3749 
3750  // Scan forward from the instruction after CmpInstr for uses of EFLAGS.
3751  // It is safe to remove CmpInstr if EFLAGS is redefined or killed.
3752  // If we are done with the basic block, we need to check whether EFLAGS is
3753  // live-out.
3754  bool IsSafe = false;
3755  SmallVector<std::pair<MachineInstr*, unsigned /*NewOpc*/>, 4> OpsToUpdate;
3756  MachineBasicBlock::iterator E = CmpInstr.getParent()->end();
3757  for (++I; I != E; ++I) {
3758  const MachineInstr &Instr = *I;
3759  bool ModifyEFLAGS = Instr.modifiesRegister(X86::EFLAGS, TRI);
3760  bool UseEFLAGS = Instr.readsRegister(X86::EFLAGS, TRI);
3761  // We should check the usage if this instruction uses and updates EFLAGS.
3762  if (!UseEFLAGS && ModifyEFLAGS) {
3763  // It is safe to remove CmpInstr if EFLAGS is updated again.
3764  IsSafe = true;
3765  break;
3766  }
3767  if (!UseEFLAGS && !ModifyEFLAGS)
3768  continue;
3769 
3770  // EFLAGS is used by this instruction.
3772  bool OpcIsSET = false;
3773  if (IsCmpZero || IsSwapped) {
3774  // We decode the condition code from opcode.
3775  if (Instr.isBranch())
3776  OldCC = X86::getCondFromBranchOpc(Instr.getOpcode());
3777  else {
3778  OldCC = X86::getCondFromSETOpc(Instr.getOpcode());
3779  if (OldCC != X86::COND_INVALID)
3780  OpcIsSET = true;
3781  else
3782  OldCC = X86::getCondFromCMovOpc(Instr.getOpcode());
3783  }
3784  if (OldCC == X86::COND_INVALID) return false;
3785  }
3786  X86::CondCode ReplacementCC = X86::COND_INVALID;
3787  if (IsCmpZero) {
3788  switch (OldCC) {
3789  default: break;
3790  case X86::COND_A: case X86::COND_AE:
3791  case X86::COND_B: case X86::COND_BE:
3792  case X86::COND_G: case X86::COND_GE:
3793  case X86::COND_L: case X86::COND_LE:
3794  case X86::COND_O: case X86::COND_NO:
3795  // CF and OF are used, we can't perform this optimization.
3796  return false;
3797  }
3798 
3799  // If we're updating the condition code check if we have to reverse the
3800  // condition.
3801  if (ShouldUpdateCC)
3802  switch (OldCC) {
3803  default:
3804  return false;
3805  case X86::COND_E:
3806  ReplacementCC = NewCC;
3807  break;
3808  case X86::COND_NE:
3809  ReplacementCC = GetOppositeBranchCondition(NewCC);
3810  break;
3811  }
3812  } else if (IsSwapped) {
3813  // If we have SUB(r1, r2) and CMP(r2, r1), the condition code needs
3814  // to be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
3815  // We swap the condition code and synthesize the new opcode.
3816  ReplacementCC = getSwappedCondition(OldCC);
3817  if (ReplacementCC == X86::COND_INVALID) return false;
3818  }
3819 
3820  if ((ShouldUpdateCC || IsSwapped) && ReplacementCC != OldCC) {
3821  // Synthesize the new opcode.
3822  bool HasMemoryOperand = Instr.hasOneMemOperand();
3823  unsigned NewOpc;
3824  if (Instr.isBranch())
3825  NewOpc = GetCondBranchFromCond(ReplacementCC);
3826  else if(OpcIsSET)
3827  NewOpc = getSETFromCond(ReplacementCC, HasMemoryOperand);
3828  else {
3829  unsigned DstReg = Instr.getOperand(0).getReg();
3830  const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
3831  NewOpc = getCMovFromCond(ReplacementCC, TRI->getRegSizeInBits(*DstRC)/8,
3832  HasMemoryOperand);
3833  }
3834 
3835  // Push the MachineInstr to OpsToUpdate.
3836  // If it is safe to remove CmpInstr, the condition code of these
3837  // instructions will be modified.
3838  OpsToUpdate.push_back(std::make_pair(&*I, NewOpc));
3839  }
3840  if (ModifyEFLAGS || Instr.killsRegister(X86::EFLAGS, TRI)) {
3841  // It is safe to remove CmpInstr if EFLAGS is updated again or killed.
3842  IsSafe = true;
3843  break;
3844  }
3845  }
3846 
3847  // If EFLAGS is not killed nor re-defined, we should check whether it is
3848  // live-out. If it is live-out, do not optimize.
3849  if ((IsCmpZero || IsSwapped) && !IsSafe) {
3850  MachineBasicBlock *MBB = CmpInstr.getParent();
3851  for (MachineBasicBlock *Successor : MBB->successors())
3852  if (Successor->isLiveIn(X86::EFLAGS))
3853  return false;
3854  }
3855 
3856  // The instruction to be updated is either Sub or MI.
3857  Sub = IsCmpZero ? MI : Sub;
3858  // Move Movr0Inst to the appropriate place before Sub.
3859  if (Movr0Inst) {
3860  // Look backwards until we find a def that doesn't use the current EFLAGS.
3861  Def = Sub;
3863  InsertE = Sub->getParent()->rend();
3864  for (; InsertI != InsertE; ++InsertI) {
3865  MachineInstr *Instr = &*InsertI;
3866  if (!Instr->readsRegister(X86::EFLAGS, TRI) &&
3867  Instr->modifiesRegister(X86::EFLAGS, TRI)) {
3868  Sub->getParent()->remove(Movr0Inst);
3869  Instr->getParent()->insert(MachineBasicBlock::iterator(Instr),
3870  Movr0Inst);
3871  break;
3872  }
3873  }
3874  if (InsertI == InsertE)
3875  return false;
3876  }
3877 
3878  // Make sure Sub instruction defines EFLAGS and mark the def live.
3879  unsigned i = 0, e = Sub->getNumOperands();
3880  for (; i != e; ++i) {
3881  MachineOperand &MO = Sub->getOperand(i);
3882  if (MO.isReg() && MO.isDef() && MO.getReg() == X86::EFLAGS) {
3883  MO.setIsDead(false);
3884  break;
3885  }
3886  }
3887  assert(i != e && "Unable to locate a def EFLAGS operand");
3888 
3889  CmpInstr.eraseFromParent();
3890 
3891  // Modify the condition code of instructions in OpsToUpdate.
3892  for (auto &Op : OpsToUpdate)
3893  Op.first->setDesc(get(Op.second));
3894  return true;
3895 }
3896 
3897 /// Try to remove the load by folding it to a register
3898 /// operand at the use. We fold the load instructions if load defines a virtual
3899 /// register, the virtual register is used once in the same BB, and the
3900 /// instructions in-between do not load or store, and have no side effects.
3902  const MachineRegisterInfo *MRI,
3903  unsigned &FoldAsLoadDefReg,
3904  MachineInstr *&DefMI) const {
3905  // Check whether we can move DefMI here.
3906  DefMI = MRI->getVRegDef(FoldAsLoadDefReg);
3907  assert(DefMI);
3908  bool SawStore = false;
3909  if (!DefMI->isSafeToMove(nullptr, SawStore))
3910  return nullptr;
3911 
3912  // Collect information about virtual register operands of MI.
3913  SmallVector<unsigned, 1> SrcOperandIds;
3914  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
3915  MachineOperand &MO = MI.getOperand(i);
3916  if (!MO.isReg())
3917  continue;
3918  unsigned Reg = MO.getReg();
3919  if (Reg != FoldAsLoadDefReg)
3920  continue;
3921  // Do not fold if we have a subreg use or a def.
3922  if (MO.getSubReg() || MO.isDef())
3923  return nullptr;
3924  SrcOperandIds.push_back(i);
3925  }
3926  if (SrcOperandIds.empty())
3927  return nullptr;
3928 
3929  // Check whether we can fold the def into SrcOperandId.
3930  if (MachineInstr *FoldMI = foldMemoryOperand(MI, SrcOperandIds, *DefMI)) {
3931  FoldAsLoadDefReg = 0;
3932  return FoldMI;
3933  }
3934 
3935  return nullptr;
3936 }
3937 
3938 /// Expand a single-def pseudo instruction to a two-addr
3939 /// instruction with two undef reads of the register being defined.
3940 /// This is used for mapping:
3941 /// %xmm4 = V_SET0
3942 /// to:
3943 /// %xmm4 = PXORrr undef %xmm4, undef %xmm4
3944 ///
3946  const MCInstrDesc &Desc) {
3947  assert(Desc.getNumOperands() == 3 && "Expected two-addr instruction.");
3948  unsigned Reg = MIB->getOperand(0).getReg();
3949  MIB->setDesc(Desc);
3950 
3951  // MachineInstr::addOperand() will insert explicit operands before any
3952  // implicit operands.
3953  MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef);
3954  // But we don't trust that.
3955  assert(MIB->getOperand(1).getReg() == Reg &&
3956  MIB->getOperand(2).getReg() == Reg && "Misplaced operand");
3957  return true;
3958 }
3959 
3960 /// Expand a single-def pseudo instruction to a two-addr
3961 /// instruction with two %k0 reads.
3962 /// This is used for mapping:
3963 /// %k4 = K_SET1
3964 /// to:
3965 /// %k4 = KXNORrr %k0, %k0
3967  const MCInstrDesc &Desc, unsigned Reg) {
3968  assert(Desc.getNumOperands() == 3 && "Expected two-addr instruction.");
3969  MIB->setDesc(Desc);
3970  MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef);
3971  return true;
3972 }
3973 
3975  bool MinusOne) {
3976  MachineBasicBlock &MBB = *MIB->getParent();
3977  DebugLoc DL = MIB->getDebugLoc();
3978  unsigned Reg = MIB->getOperand(0).getReg();
3979 
3980  // Insert the XOR.
3981  BuildMI(MBB, MIB.getInstr(), DL, TII.get(X86::XOR32rr), Reg)
3982  .addReg(Reg, RegState::Undef)
3983  .addReg(Reg, RegState::Undef);
3984 
3985  // Turn the pseudo into an INC or DEC.
3986  MIB->setDesc(TII.get(MinusOne ? X86::DEC32r : X86::INC32r));
3987  MIB.addReg(Reg);
3988 
3989  return true;
3990 }
3991 
3993  const TargetInstrInfo &TII,
3994  const X86Subtarget &Subtarget) {
3995  MachineBasicBlock &MBB = *MIB->getParent();
3996  DebugLoc DL = MIB->getDebugLoc();
3997  int64_t Imm = MIB->getOperand(1).getImm();
3998  assert(Imm != 0 && "Using push/pop for 0 is not efficient.");
4000 
4001  int StackAdjustment;
4002 
4003  if (Subtarget.is64Bit()) {
4004  assert(MIB->getOpcode() == X86::MOV64ImmSExti8 ||
4005  MIB->getOpcode() == X86::MOV32ImmSExti8);
4006 
4007  // Can't use push/pop lowering if the function might write to the red zone.
4008  X86MachineFunctionInfo *X86FI =
4010  if (X86FI->getUsesRedZone()) {
4011  MIB->setDesc(TII.get(MIB->getOpcode() ==
4012  X86::MOV32ImmSExti8 ? X86::MOV32ri : X86::MOV64ri));
4013  return true;
4014  }
4015 
4016  // 64-bit mode doesn't have 32-bit push/pop, so use 64-bit operations and
4017  // widen the register if necessary.
4018  StackAdjustment = 8;
4019  BuildMI(MBB, I, DL, TII.get(X86::PUSH64i8)).addImm(Imm);
4020  MIB->setDesc(TII.get(X86::POP64r));
4021  MIB->getOperand(0)
4023  } else {
4024  assert(MIB->getOpcode() == X86::MOV32ImmSExti8);
4025  StackAdjustment = 4;
4026  BuildMI(MBB, I, DL, TII.get(X86::PUSH32i8)).addImm(Imm);
4027  MIB->setDesc(TII.get(X86::POP32r));
4028  }
4029 
4030  // Build CFI if necessary.
4031  MachineFunction &MF = *MBB.getParent();
4032  const X86FrameLowering *TFL = Subtarget.getFrameLowering();
4033  bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
4034  bool NeedsDwarfCFI =
4035  !IsWin64Prologue &&
4037  bool EmitCFI = !TFL->hasFP(MF) && NeedsDwarfCFI;
4038  if (EmitCFI) {
4039  TFL->BuildCFI(MBB, I, DL,
4040  MCCFIInstruction::createAdjustCfaOffset(nullptr, StackAdjustment));
4041  TFL->BuildCFI(MBB, std::next(I), DL,
4042  MCCFIInstruction::createAdjustCfaOffset(nullptr, -StackAdjustment));
4043  }
4044 
4045  return true;
4046 }
4047 
4048 // LoadStackGuard has so far only been implemented for 64-bit MachO. Different
4049 // code sequence is needed for other targets.
4051  const TargetInstrInfo &TII) {
4052  MachineBasicBlock &MBB = *MIB->getParent();
4053  DebugLoc DL = MIB->getDebugLoc();
4054  unsigned Reg = MIB->getOperand(0).getReg();
4055  const GlobalValue *GV =
4056  cast<GlobalValue>((*MIB->memoperands_begin())->getValue());
4057  auto Flags = MachineMemOperand::MOLoad |
4061  MachinePointerInfo::getGOT(*MBB.getParent()), Flags, 8, 8);
4063 
4064  BuildMI(MBB, I, DL, TII.get(X86::MOV64rm), Reg).addReg(X86::RIP).addImm(1)
4066  .addMemOperand(MMO);
4067  MIB->setDebugLoc(DL);
4068  MIB->setDesc(TII.get(X86::MOV64rm));
4069  MIB.addReg(Reg, RegState::Kill).addImm(1).addReg(0).addImm(0).addReg(0);
4070 }
4071 
4073  MachineBasicBlock &MBB = *MIB->getParent();
4074  MachineFunction &MF = *MBB.getParent();
4075  const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>();
4076  const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4077  unsigned XorOp =
4078  MIB->getOpcode() == X86::XOR64_FP ? X86::XOR64rr : X86::XOR32rr;
4079  MIB->setDesc(TII.get(XorOp));
4080  MIB.addReg(TRI->getFrameRegister(MF), RegState::Undef);
4081  return true;
4082 }
4083 
4084 // This is used to handle spills for 128/256-bit registers when we have AVX512,
4085 // but not VLX. If it uses an extended register we need to use an instruction
4086 // that loads the lower 128/256-bit, but is available with only AVX512F.
4088  const TargetRegisterInfo *TRI,
4089  const MCInstrDesc &LoadDesc,
4090  const MCInstrDesc &BroadcastDesc,
4091  unsigned SubIdx) {
4092  unsigned DestReg = MIB->getOperand(0).getReg();
4093  // Check if DestReg is XMM16-31 or YMM16-31.
4094  if (TRI->getEncodingValue(DestReg) < 16) {
4095  // We can use a normal VEX encoded load.
4096  MIB->setDesc(LoadDesc);
4097  } else {
4098  // Use a 128/256-bit VBROADCAST instruction.
4099  MIB->setDesc(BroadcastDesc);
4100  // Change the destination to a 512-bit register.
4101  DestReg = TRI->getMatchingSuperReg(DestReg, SubIdx, &X86::VR512RegClass);
4102  MIB->getOperand(0).setReg(DestReg);
4103  }
4104  return true;
4105 }
4106 
4107 // This is used to handle spills for 128/256-bit registers when we have AVX512,
4108 // but not VLX. If it uses an extended register we need to use an instruction
4109 // that stores the lower 128/256-bit, but is available with only AVX512F.
4111  const TargetRegisterInfo *TRI,
4112  const MCInstrDesc &StoreDesc,
4113  const MCInstrDesc &ExtractDesc,
4114  unsigned SubIdx) {
4115  unsigned SrcReg = MIB->getOperand(X86::AddrNumOperands).getReg();
4116  // Check if DestReg is XMM16-31 or YMM16-31.
4117  if (TRI->getEncodingValue(SrcReg) < 16) {
4118  // We can use a normal VEX encoded store.
4119  MIB->setDesc(StoreDesc);
4120  } else {
4121  // Use a VEXTRACTF instruction.
4122  MIB->setDesc(ExtractDesc);
4123  // Change the destination to a 512-bit register.
4124  SrcReg = TRI->getMatchingSuperReg(SrcReg, SubIdx, &X86::VR512RegClass);
4125  MIB->getOperand(X86::AddrNumOperands).setReg(SrcReg);
4126  MIB.addImm(0x0); // Append immediate to extract from the lower bits.
4127  }
4128 
4129  return true;
4130 }
4132  bool HasAVX = Subtarget.hasAVX();
4133  MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
4134  switch (MI.getOpcode()) {
4135  case X86::MOV32r0:
4136  return Expand2AddrUndef(MIB, get(X86::XOR32rr));
4137  case X86::MOV32r1:
4138  return expandMOV32r1(MIB, *this, /*MinusOne=*/ false);
4139  case X86::MOV32r_1:
4140  return expandMOV32r1(MIB, *this, /*MinusOne=*/ true);
4141  case X86::MOV32ImmSExti8:
4142  case X86::MOV64ImmSExti8:
4143  return ExpandMOVImmSExti8(MIB, *this, Subtarget);
4144  case X86::SETB_C8r:
4145  return Expand2AddrUndef(MIB, get(X86::SBB8rr));
4146  case X86::SETB_C16r:
4147  return Expand2AddrUndef(MIB, get(X86::SBB16rr));
4148  case X86::SETB_C32r:
4149  return Expand2AddrUndef(MIB, get(X86::SBB32rr));
4150  case X86::SETB_C64r:
4151  return Expand2AddrUndef(MIB, get(X86::SBB64rr));
4152  case X86::MMX_SET0:
4153  return Expand2AddrUndef(MIB, get(X86::MMX_PXORirr));
4154  case X86::V_SET0:
4155  case X86::FsFLD0SS:
4156  case X86::FsFLD0SD:
4157  return Expand2AddrUndef(MIB, get(HasAVX ? X86::VXORPSrr : X86::XORPSrr));
4158  case X86::AVX_SET0: {
4159  assert(HasAVX && "AVX not supported");
4161  unsigned SrcReg = MIB->getOperand(0).getReg();
4162  unsigned XReg = TRI->getSubReg(SrcReg, X86::sub_xmm);
4163  MIB->getOperand(0).setReg(XReg);
4164  Expand2AddrUndef(MIB, get(X86::VXORPSrr));
4165  MIB.addReg(SrcReg, RegState::ImplicitDefine);
4166  return true;
4167  }
4168  case X86::AVX512_128_SET0:
4169  case X86::AVX512_FsFLD0SS:
4170  case X86::AVX512_FsFLD0SD: {
4171  bool HasVLX = Subtarget.hasVLX();
4172  unsigned SrcReg = MIB->getOperand(0).getReg();
4174  if (HasVLX || TRI->getEncodingValue(SrcReg) < 16)
4175  return Expand2AddrUndef(MIB,
4176  get(HasVLX ? X86::VPXORDZ128rr : X86::VXORPSrr));
4177  // Extended register without VLX. Use a larger XOR.
4178  SrcReg =
4179  TRI->getMatchingSuperReg(SrcReg, X86::sub_xmm, &X86::VR512RegClass);
4180  MIB->getOperand(0).setReg(SrcReg);
4181  return Expand2AddrUndef(MIB, get(X86::VPXORDZrr));
4182  }
4183  case X86::AVX512_256_SET0:
4184  case X86::AVX512_512_SET0: {
4185  bool HasVLX = Subtarget.hasVLX();
4186  unsigned SrcReg = MIB->getOperand(0).getReg();
4188  if (HasVLX || TRI->getEncodingValue(SrcReg) < 16) {
4189  unsigned XReg = TRI->getSubReg(SrcReg, X86::sub_xmm);
4190  MIB->getOperand(0).setReg(XReg);
4191  Expand2AddrUndef(MIB,
4192  get(HasVLX ? X86::VPXORDZ128rr : X86::VXORPSrr));
4193  MIB.addReg(SrcReg, RegState::ImplicitDefine);
4194  return true;
4195  }
4196  return Expand2AddrUndef(MIB, get(X86::VPXORDZrr));
4197  }
4198  case X86::V_SETALLONES:
4199  return Expand2AddrUndef(MIB, get(HasAVX ? X86::VPCMPEQDrr : X86::PCMPEQDrr));
4200  case X86::AVX2_SETALLONES:
4201  return Expand2AddrUndef(MIB, get(X86::VPCMPEQDYrr));
4202  case X86::AVX1_SETALLONES: {
4203  unsigned Reg = MIB->getOperand(0).getReg();
4204  // VCMPPSYrri with an immediate 0xf should produce VCMPTRUEPS.
4205  MIB->setDesc(get(X86::VCMPPSYrri));
4206  MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef).addImm(0xf);
4207  return true;
4208  }
4209  case X86::AVX512_512_SETALLONES: {
4210  unsigned Reg = MIB->getOperand(0).getReg();
4211  MIB->setDesc(get(X86::VPTERNLOGDZrri));
4212  // VPTERNLOGD needs 3 register inputs and an immediate.
4213  // 0xff will return 1s for any input.
4214  MIB.addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef)
4215  .addReg(Reg, RegState::Undef).addImm(0xff);
4216  return true;
4217  }
4218  case X86::AVX512_512_SEXT_MASK_32:
4219  case X86::AVX512_512_SEXT_MASK_64: {
4220  unsigned Reg = MIB->getOperand(0).getReg();
4221  unsigned MaskReg = MIB->getOperand(1).getReg();
4222  unsigned MaskState = getRegState(MIB->getOperand(1));
4223  unsigned Opc = (MI.getOpcode() == X86::AVX512_512_SEXT_MASK_64) ?
4224  X86::VPTERNLOGQZrrikz : X86::VPTERNLOGDZrrikz;
4225  MI.RemoveOperand(1);
4226  MIB->setDesc(get(Opc));
4227  // VPTERNLOG needs 3 register inputs and an immediate.
4228  // 0xff will return 1s for any input.
4229  MIB.addReg(Reg, RegState::Undef).addReg(MaskReg, MaskState)
4230  .addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef).addImm(0xff);
4231  return true;
4232  }
4233  case X86::VMOVAPSZ128rm_NOVLX:
4234  return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVAPSrm),
4235  get(X86::VBROADCASTF32X4rm), X86::sub_xmm);
4236  case X86::VMOVUPSZ128rm_NOVLX:
4237  return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVUPSrm),
4238  get(X86::VBROADCASTF32X4rm), X86::sub_xmm);
4239  case X86::VMOVAPSZ256rm_NOVLX:
4240  return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVAPSYrm),
4241  get(X86::VBROADCASTF64X4rm), X86::sub_ymm);
4242  case X86::VMOVUPSZ256rm_NOVLX:
4243  return expandNOVLXLoad(MIB, &getRegisterInfo(), get(X86::VMOVUPSYrm),
4244  get(X86::VBROADCASTF64X4rm), X86::sub_ymm);
4245  case X86::VMOVAPSZ128mr_NOVLX:
4246  return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVAPSmr),
4247  get(X86::VEXTRACTF32x4Zmr), X86::sub_xmm);
4248  case X86::VMOVUPSZ128mr_NOVLX:
4249  return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVUPSmr),
4250  get(X86::VEXTRACTF32x4Zmr), X86::sub_xmm);
4251  case X86::VMOVAPSZ256mr_NOVLX:
4252  return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVAPSYmr),
4253  get(X86::VEXTRACTF64x4Zmr), X86::sub_ymm);
4254  case X86::VMOVUPSZ256mr_NOVLX:
4255  return expandNOVLXStore(MIB, &getRegisterInfo(), get(X86::VMOVUPSYmr),
4256  get(X86::VEXTRACTF64x4Zmr), X86::sub_ymm);
4257  case X86::MOV32ri64:
4258  MI.setDesc(get(X86::MOV32ri));
4259  return true;
4260 
4261  // KNL does not recognize dependency-breaking idioms for mask registers,
4262  // so kxnor %k1, %k1, %k2 has a RAW dependence on %k1.
4263  // Using %k0 as the undef input register is a performance heuristic based
4264  // on the assumption that %k0 is used less frequently than the other mask
4265  // registers, since it is not usable as a write mask.
4266  // FIXME: A more advanced approach would be to choose the best input mask
4267  // register based on context.
4268  case X86::KSET0W: return Expand2AddrKreg(MIB, get(X86::KXORWrr), X86::K0);
4269  case X86::KSET0D: return Expand2AddrKreg(MIB, get(X86::KXORDrr), X86::K0);
4270  case X86::KSET0Q: return Expand2AddrKreg(MIB, get(X86::KXORQrr), X86::K0);
4271  case X86::KSET1W: return Expand2AddrKreg(MIB, get(X86::KXNORWrr), X86::K0);
4272  case X86::KSET1D: return Expand2AddrKreg(MIB, get(X86::KXNORDrr), X86::K0);
4273  case X86::KSET1Q: return Expand2AddrKreg(MIB, get(X86::KXNORQrr), X86::K0);
4274  case TargetOpcode::LOAD_STACK_GUARD:
4275  expandLoadStackGuard(MIB, *this);
4276  return true;
4277  case X86::XOR64_FP:
4278  case X86::XOR32_FP:
4279  return expandXorFP(MIB, *this);
4280  }
4281  return false;
4282 }
4283 
4284 /// Return true for all instructions that only update
4285 /// the first 32 or 64-bits of the destination register and leave the rest
4286 /// unmodified. This can be used to avoid folding loads if the instructions
4287 /// only update part of the destination register, and the non-updated part is
4288 /// not needed. e.g. cvtss2sd, sqrtss. Unfolding the load from these
4289 /// instructions breaks the partial register dependency and it can improve
4290 /// performance. e.g.:
4291 ///
4292 /// movss (%rdi), %xmm0
4293 /// cvtss2sd %xmm0, %xmm0
4294 ///
4295 /// Instead of
4296 /// cvtss2sd (%rdi), %xmm0
4297 ///
4298 /// FIXME: This should be turned into a TSFlags.
4299 ///
4300 static bool hasPartialRegUpdate(unsigned Opcode,
4301  const X86Subtarget &Subtarget) {
4302  switch (Opcode) {
4303  case X86::CVTSI2SSrr:
4304  case X86::CVTSI2SSrm:
4305  case X86::CVTSI642SSrr:
4306  case X86::CVTSI642SSrm:
4307  case X86::CVTSI2SDrr:
4308  case X86::CVTSI2SDrm:
4309  case X86::CVTSI642SDrr:
4310  case X86::CVTSI642SDrm:
4311  case X86::CVTSD2SSrr:
4312  case X86::CVTSD2SSrm:
4313  case X86::CVTSS2SDrr:
4314  case X86::CVTSS2SDrm:
4315  case X86::MOVHPDrm:
4316  case X86::MOVHPSrm:
4317  case X86::MOVLPDrm:
4318  case X86::MOVLPSrm:
4319  case X86::RCPSSr:
4320  case X86::RCPSSm:
4321  case X86::RCPSSr_Int:
4322  case X86::RCPSSm_Int:
4323  case X86::ROUNDSDr:
4324  case X86::ROUNDSDm:
4325  case X86::ROUNDSSr:
4326  case X86::ROUNDSSm:
4327  case X86::RSQRTSSr:
4328  case X86::RSQRTSSm:
4329  case X86::RSQRTSSr_Int:
4330  case X86::RSQRTSSm_Int:
4331  case X86::SQRTSSr:
4332  case X86::SQRTSSm:
4333  case X86::SQRTSSr_Int:
4334  case X86::SQRTSSm_Int:
4335  case X86::SQRTSDr:
4336  case X86::SQRTSDm:
4337  case X86::SQRTSDr_Int:
4338  case X86::SQRTSDm_Int:
4339  return true;
4340  // GPR
4341  case X86::POPCNT32rm:
4342  case X86::POPCNT32rr:
4343  case X86::POPCNT64rm:
4344  case X86::POPCNT64rr:
4345  return Subtarget.hasPOPCNTFalseDeps();
4346  case X86::LZCNT32rm:
4347  case X86::LZCNT32rr:
4348  case X86::LZCNT64rm:
4349  case X86::LZCNT64rr:
4350  case X86::TZCNT32rm:
4351  case X86::TZCNT32rr:
4352  case X86::TZCNT64rm:
4353  case X86::TZCNT64rr:
4354  return Subtarget.hasLZCNTFalseDeps();
4355  }
4356 
4357  return false;
4358 }
4359 
4360 /// Inform the BreakFalseDeps pass how many idle
4361 /// instructions we would like before a partial register update.
4363  const MachineInstr &MI, unsigned OpNum,
4364  const TargetRegisterInfo *TRI) const {
4365  if (OpNum != 0 || !hasPartialRegUpdate(MI.getOpcode(), Subtarget))
4366  return 0;
4367 
4368  // If MI is marked as reading Reg, the partial register update is wanted.
4369  const MachineOperand &MO = MI.getOperand(0);
4370  unsigned Reg = MO.getReg();
4372  if (MO.readsReg() || MI.readsVirtualRegister(Reg))
4373  return 0;
4374  } else {
4375  if (MI.readsRegister(Reg, TRI))
4376  return 0;
4377  }
4378 
4379  // If any instructions in the clearance range are reading Reg, insert a
4380  // dependency breaking instruction, which is inexpensive and is likely to
4381  // be hidden in other instruction's cycles.
4383 }
4384 
4385 // Return true for any instruction the copies the high bits of the first source
4386 // operand into the unused high bits of the destination operand.
4387 static bool hasUndefRegUpdate(unsigned Opcode) {
4388  switch (Opcode) {
4389  case X86::VCVTSI2SSrr:
4390  case X86::VCVTSI2SSrm:
4391  case X86::VCVTSI2SSrr_Int:
4392  case X86::VCVTSI2SSrm_Int:
4393  case X86::VCVTSI642SSrr:
4394  case X86::VCVTSI642SSrm:
4395  case X86::VCVTSI642SSrr_Int:
4396  case X86::VCVTSI642SSrm_Int:
4397  case X86::VCVTSI2SDrr:
4398  case X86::VCVTSI2SDrm:
4399  case X86::VCVTSI2SDrr_Int:
4400  case X86::VCVTSI2SDrm_Int:
4401  case X86::VCVTSI642SDrr:
4402  case X86::VCVTSI642SDrm:
4403  case X86::VCVTSI642SDrr_Int:
4404  case X86::VCVTSI642SDrm_Int:
4405  case X86::VCVTSD2SSrr:
4406  case X86::VCVTSD2SSrm:
4407  case X86::VCVTSD2SSrr_Int:
4408  case X86::VCVTSD2SSrm_Int:
4409  case X86::VCVTSS2SDrr:
4410  case X86::VCVTSS2SDrm:
4411  case X86::VCVTSS2SDrr_Int:
4412  case X86::VCVTSS2SDrm_Int:
4413  case X86::VRCPSSr:
4414  case X86::VRCPSSr_Int:
4415  case X86::VRCPSSm:
4416  case X86::VRCPSSm_Int:
4417  case X86::VROUNDSDr:
4418  case X86::VROUNDSDm:
4419  case X86::VROUNDSDr_Int:
4420  case X86::VROUNDSDm_Int:
4421  case X86::VROUNDSSr:
4422  case X86::VROUNDSSm:
4423  case X86::VROUNDSSr_Int:
4424  case X86::VROUNDSSm_Int:
4425  case X86::VRSQRTSSr:
4426  case X86::VRSQRTSSr_Int:
4427  case X86::VRSQRTSSm:
4428  case X86::VRSQRTSSm_Int:
4429  case X86::VSQRTSSr:
4430  case X86::VSQRTSSr_Int:
4431  case X86::VSQRTSSm:
4432  case X86::VSQRTSSm_Int:
4433  case X86::VSQRTSDr:
4434  case X86::VSQRTSDr_Int:
4435  case X86::VSQRTSDm:
4436  case X86::VSQRTSDm_Int:
4437  // AVX-512
4438  case X86::VCVTSI2SSZrr:
4439  case X86::VCVTSI2SSZrm:
4440  case X86::VCVTSI2SSZrr_Int:
4441  case X86::VCVTSI2SSZrrb_Int:
4442  case X86::VCVTSI2SSZrm_Int:
4443  case X86::VCVTSI642SSZrr:
4444  case X86::VCVTSI642SSZrm:
4445  case X86::VCVTSI642SSZrr_Int:
4446  case X86::VCVTSI642SSZrrb_Int:
4447  case X86::VCVTSI642SSZrm_Int:
4448  case X86::VCVTSI2SDZrr:
4449  case X86::VCVTSI2SDZrm:
4450  case X86::VCVTSI2SDZrr_Int:
4451  case X86::VCVTSI2SDZrrb_Int:
4452  case X86::VCVTSI2SDZrm_Int:
4453  case X86::VCVTSI642SDZrr:
4454  case X86::VCVTSI642SDZrm:
4455  case X86::VCVTSI642SDZrr_Int:
4456  case X86::VCVTSI642SDZrrb_Int:
4457  case X86::VCVTSI642SDZrm_Int:
4458  case X86::VCVTUSI2SSZrr:
4459  case X86::VCVTUSI2SSZrm:
4460  case X86::VCVTUSI2SSZrr_Int:
4461  case X86::VCVTUSI2SSZrrb_Int:
4462  case X86::VCVTUSI2SSZrm_Int:
4463  case X86::VCVTUSI642SSZrr:
4464  case X86::VCVTUSI642SSZrm:
4465  case X86::VCVTUSI642SSZrr_Int:
4466  case X86::VCVTUSI642SSZrrb_Int:
4467  case X86::VCVTUSI642SSZrm_Int:
4468  case X86::VCVTUSI2SDZrr:
4469  case X86::VCVTUSI2SDZrm:
4470  case X86::VCVTUSI2SDZrr_Int:
4471  case X86::VCVTUSI2SDZrm_Int:
4472  case X86::VCVTUSI642SDZrr:
4473  case X86::VCVTUSI642SDZrm:
4474  case X86::VCVTUSI642SDZrr_Int:
4475  case X86::VCVTUSI642SDZrrb_Int:
4476  case X86::VCVTUSI642SDZrm_Int:
4477  case X86::VCVTSD2SSZrr:
4478  case X86::VCVTSD2SSZrr_Int:
4479  case X86::VCVTSD2SSZrrb_Int:
4480  case X86::VCVTSD2SSZrm:
4481  case X86::VCVTSD2SSZrm_Int:
4482  case X86::VCVTSS2SDZrr:
4483  case X86::VCVTSS2SDZrr_Int:
4484  case X86::VCVTSS2SDZrrb_Int:
4485  case X86::VCVTSS2SDZrm:
4486  case X86::VCVTSS2SDZrm_Int:
4487  case X86::VGETEXPSDZr:
4488  case X86::VGETEXPSDZrb:
4489  case X86::VGETEXPSDZm:
4490  case X86::VGETEXPSSZr:
4491  case X86::VGETEXPSSZrb:
4492  case X86::VGETEXPSSZm:
4493  case X86::VGETMANTSDZrri:
4494  case X86::VGETMANTSDZrrib:
4495  case X86::VGETMANTSDZrmi:
4496  case X86::VGETMANTSSZrri:
4497  case X86::VGETMANTSSZrrib:
4498  case X86::VGETMANTSSZrmi:
4499  case X86::VRNDSCALESDZr:
4500  case X86::VRNDSCALESDZr_Int:
4501  case X86::VRNDSCALESDZrb_Int:
4502  case X86::VRNDSCALESDZm:
4503  case X86::VRNDSCALESDZm_Int:
4504  case X86::VRNDSCALESSZr:
4505  case X86::VRNDSCALESSZr_Int:
4506  case X86::VRNDSCALESSZrb_Int:
4507  case X86::VRNDSCALESSZm:
4508  case X86::VRNDSCALESSZm_Int:
4509  case X86::VRCP14SDZrr:
4510  case X86::VRCP14SDZrm:
4511  case X86::VRCP14SSZrr:
4512  case X86::VRCP14SSZrm:
4513  case X86::VRCP28SDZr:
4514  case X86::VRCP28SDZrb:
4515  case X86::VRCP28SDZm:
4516  case X86::VRCP28SSZr:
4517  case X86::VRCP28SSZrb:
4518  case X86::VRCP28SSZm:
4519  case X86::VREDUCESSZrmi:
4520  case X86::VREDUCESSZrri:
4521  case X86::VREDUCESSZrrib:
4522  case X86::VRSQRT14SDZrr:
4523  case X86::VRSQRT14SDZrm:
4524  case X86::VRSQRT14SSZrr:
4525  case X86::VRSQRT14SSZrm:
4526  case X86::VRSQRT28SDZr:
4527  case X86::VRSQRT28SDZrb:
4528  case X86::VRSQRT28SDZm:
4529  case X86::VRSQRT28SSZr:
4530  case X86::VRSQRT28SSZrb:
4531  case X86::VRSQRT28SSZm:
4532  case X86::VSQRTSSZr:
4533  case X86::VSQRTSSZr_Int:
4534  case X86::VSQRTSSZrb_Int:
4535  case X86::VSQRTSSZm:
4536  case X86::VSQRTSSZm_Int:
4537  case X86::VSQRTSDZr:
4538  case X86::VSQRTSDZr_Int:
4539  case X86::VSQRTSDZrb_Int:
4540  case X86::VSQRTSDZm:
4541  case X86::VSQRTSDZm_Int:
4542  return true;
4543  }
4544 
4545  return false;
4546 }
4547 
4548 /// Inform the BreakFalseDeps pass how many idle instructions we would like
4549 /// before certain undef register reads.
4550 ///
4551 /// This catches the VCVTSI2SD family of instructions:
4552 ///
4553 /// vcvtsi2sdq %rax, undef %xmm0, %xmm14
4554 ///
4555 /// We should to be careful *not* to catch VXOR idioms which are presumably
4556 /// handled specially in the pipeline:
4557 ///
4558 /// vxorps undef %xmm1, undef %xmm1, %xmm1
4559 ///
4560 /// Like getPartialRegUpdateClearance, this makes a strong assumption that the
4561 /// high bits that are passed-through are not live.
4562 unsigned
4564  const TargetRegisterInfo *TRI) const {
4565  if (!hasUndefRegUpdate(MI.getOpcode()))
4566  return 0;
4567 
4568  // Set the OpNum parameter to the first source operand.
4569  OpNum = 1;
4570 
4571  const MachineOperand &MO = MI.getOperand(OpNum);
4573  return UndefRegClearance;
4574  }
4575  return 0;
4576 }
4577 
4579  MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const {
4580  unsigned Reg = MI.getOperand(OpNum).getReg();
4581  // If MI kills this register, the false dependence is already broken.
4582  if (MI.killsRegister(Reg, TRI))
4583  return;
4584 
4585  if (X86::VR128RegClass.contains(Reg)) {
4586  // These instructions are all floating point domain, so xorps is the best
4587  // choice.
4588  unsigned Opc = Subtarget.hasAVX() ? X86::VXORPSrr : X86::XORPSrr;
4589  BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(Opc), Reg)
4590  .addReg(Reg, RegState::Undef)
4591  .addReg(Reg, RegState::Undef);
4592  MI.addRegisterKilled(Reg, TRI, true);
4593  } else if (X86::VR256RegClass.contains(Reg)) {
4594  // Use vxorps to clear the full ymm register.
4595  // It wants to read and write the xmm sub-register.
4596  unsigned XReg = TRI->getSubReg(Reg, X86::sub_xmm);
4597  BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::VXORPSrr), XReg)
4598  .addReg(XReg, RegState::Undef)
4599  .addReg(XReg, RegState::Undef)
4601  MI.addRegisterKilled(Reg, TRI, true);
4602  } else if (X86::GR64RegClass.contains(Reg)) {
4603  // Using XOR32rr because it has shorter encoding and zeros up the upper bits
4604  // as well.
4605  unsigned XReg = TRI->getSubReg(Reg, X86::sub_32bit);
4606  BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::XOR32rr), XReg)
4607  .addReg(XReg, RegState::Undef)
4608  .addReg(XReg, RegState::Undef)
4610  MI.addRegisterKilled(Reg, TRI, true);
4611  } else if (X86::GR32RegClass.contains(Reg)) {
4612  BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(X86::XOR32rr), Reg)
4613  .addReg(Reg, RegState::Undef)
4614  .addReg(Reg, RegState::Undef);
4615  MI.addRegisterKilled(Reg, TRI, true);
4616  }
4617 }
4618 
4620  int PtrOffset = 0) {
4621  unsigned NumAddrOps = MOs.size();
4622 
4623  if (NumAddrOps < 4) {
4624  // FrameIndex only - add an immediate offset (whether its zero or not).
4625  for (unsigned i = 0; i != NumAddrOps; ++i)
4626  MIB.add(MOs[i]);
4627  addOffset(MIB, PtrOffset);
4628  } else {
4629  // General Memory Addressing - we need to add any offset to an existing
4630  // offset.
4631  assert(MOs.size() == 5 && "Unexpected memory operand list length");
4632  for (unsigned i = 0; i != NumAddrOps; ++i) {
4633  const MachineOperand &MO = MOs[i];
4634  if (i == 3 && PtrOffset != 0) {
4635  MIB.addDisp(MO, PtrOffset);
4636  } else {
4637  MIB.add(MO);
4638  }
4639  }
4640  }
4641 }
4642 
4643 static MachineInstr *FuseTwoAddrInst(MachineFunction &MF, unsigned Opcode,
4645  MachineBasicBlock::iterator InsertPt,
4646  MachineInstr &MI,
4647  const TargetInstrInfo &TII) {
4648  // Create the base instruction with the memory operand as the first part.
4649  // Omit the implicit operands, something BuildMI can't do.
4650  MachineInstr *NewMI =
4651  MF.CreateMachineInstr(TII.get(Opcode), MI.getDebugLoc(), true);
4652  MachineInstrBuilder MIB(MF, NewMI);
4653  addOperands(MIB, MOs);
4654 
4655  // Loop over the rest of the ri operands, converting them over.
4656  unsigned NumOps = MI.getDesc().getNumOperands() - 2;
4657  for (unsigned i = 0; i != NumOps; ++i) {
4658  MachineOperand &MO = MI.getOperand(i + 2);
4659  MIB.add(MO);
4660  }
4661  for (unsigned i = NumOps + 2, e = MI.getNumOperands(); i != e; ++i) {
4662  MachineOperand &MO = MI.getOperand(i);
4663  MIB.add(MO);
4664  }
4665 
4666  MachineBasicBlock *MBB = InsertPt->getParent();
4667  MBB->insert(InsertPt, NewMI);
4668 
4669  return MIB;
4670 }
4671 
4672 static MachineInstr *FuseInst(MachineFunction &MF, unsigned Opcode,
4673  unsigned OpNo, ArrayRef<MachineOperand> MOs,
4674  MachineBasicBlock::iterator InsertPt,
4675  MachineInstr &MI, const TargetInstrInfo &TII,
4676  int PtrOffset = 0) {
4677  // Omit the implicit operands, something BuildMI can't do.
4678  MachineInstr *NewMI =
4679  MF.CreateMachineInstr(TII.get(Opcode), MI.getDebugLoc(), true);
4680  MachineInstrBuilder MIB(MF, NewMI);
4681 
4682  for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
4683  MachineOperand &MO = MI.getOperand(i);
4684  if (i == OpNo) {
4685  assert(MO.isReg() && "Expected to fold into reg operand!");
4686  addOperands(MIB, MOs, PtrOffset);
4687  } else {
4688  MIB.add(MO);
4689  }
4690  }
4691 
4692  MachineBasicBlock *MBB = InsertPt->getParent();
4693  MBB->insert(InsertPt, NewMI);
4694 
4695  return MIB;
4696 }
4697 
4698 static MachineInstr *MakeM0Inst(const TargetInstrInfo &TII, unsigned Opcode,
4700  MachineBasicBlock::iterator InsertPt,
4701  MachineInstr &MI) {
4702  MachineInstrBuilder MIB = BuildMI(*InsertPt->getParent(), InsertPt,
4703  MI.getDebugLoc(), TII.get(Opcode));
4704  addOperands(MIB, MOs);
4705  return MIB.addImm(0);
4706 }
4707 
4708 MachineInstr *X86InstrInfo::foldMemoryOperandCustom(
4709  MachineFunction &MF, MachineInstr &MI, unsigned OpNum,
4711  unsigned Size, unsigned Align) const {
4712  switch (MI.getOpcode()) {
4713  case X86::INSERTPSrr:
4714  case X86::VINSERTPSrr:
4715  case X86::VINSERTPSZrr:
4716  // Attempt to convert the load of inserted vector into a fold load
4717  // of a single float.
4718  if (OpNum == 2) {
4719  unsigned Imm = MI.getOperand(MI.getNumOperands() - 1).getImm();
4720  unsigned ZMask = Imm & 15;
4721  unsigned DstIdx = (Imm >> 4) & 3;
4722  unsigned SrcIdx = (Imm >> 6) & 3;
4723 
4725  const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum, &RI, MF);
4726  unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
4727  if (Size <= RCSize && 4 <= Align) {
4728  int PtrOffset = SrcIdx * 4;
4729  unsigned NewImm = (DstIdx << 4) | ZMask;
4730  unsigned NewOpCode =
4731  (MI.getOpcode() == X86::VINSERTPSZrr) ? X86::VINSERTPSZrm :
4732  (MI.getOpcode() == X86::VINSERTPSrr) ? X86::VINSERTPSrm :
4733  X86::INSERTPSrm;
4734  MachineInstr *NewMI =
4735  FuseInst(MF, NewOpCode, OpNum, MOs, InsertPt, MI, *this, PtrOffset);
4736  NewMI->getOperand(NewMI->getNumOperands() - 1).setImm(NewImm);
4737  return NewMI;
4738  }
4739  }
4740  break;
4741  case X86::MOVHLPSrr:
4742  case X86::VMOVHLPSrr:
4743  case X86::VMOVHLPSZrr:
4744  // Move the upper 64-bits of the second operand to the lower 64-bits.
4745  // To fold the load, adjust the pointer to the upper and use (V)MOVLPS.
4746  // TODO: In most cases AVX doesn't have a 8-byte alignment requirement.
4747  if (OpNum == 2) {
4749  const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum, &RI, MF);
4750  unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
4751  if (Size <= RCSize && 8 <= Align) {
4752  unsigned NewOpCode =
4753  (MI.getOpcode() == X86::VMOVHLPSZrr) ? X86::VMOVLPSZ128rm :
4754  (MI.getOpcode() == X86::VMOVHLPSrr) ? X86::VMOVLPSrm :
4755  X86::MOVLPSrm;
4756  MachineInstr *NewMI =
4757  FuseInst(MF, NewOpCode, OpNum, MOs, InsertPt, MI, *this, 8);
4758  return NewMI;
4759  }
4760  }
4761  break;
4762  };
4763 
4764  return nullptr;
4765 }
4766 
4768  if (MF.getFunction().optForSize() || !hasUndefRegUpdate(MI.getOpcode()) ||
4769  !MI.getOperand(1).isReg())
4770  return false;
4771 
4772  // The are two cases we need to handle depending on where in the pipeline
4773  // the folding attempt is being made.
4774  // -Register has the undef flag set.
4775  // -Register is produced by the IMPLICIT_DEF instruction.
4776 
4777  if (MI.getOperand(1).isUndef())
4778  return true;
4779 
4780  MachineRegisterInfo &RegInfo = MF.getRegInfo();
4781  MachineInstr *VRegDef = RegInfo.getUniqueVRegDef(MI.getOperand(1).getReg());
4782  return VRegDef && VRegDef->isImplicitDef();
4783 }
4784 
4785 
4787  MachineFunction &MF, MachineInstr &MI, unsigned OpNum,
4789  unsigned Size, unsigned Align, bool AllowCommute) const {
4790  bool isSlowTwoMemOps = Subtarget.slowTwoMemOps();
4791  bool isTwoAddrFold = false;
4792 
4793  // For CPUs that favor the register form of a call or push,
4794  // do not fold loads into calls or pushes, unless optimizing for size
4795  // aggressively.
4796  if (isSlowTwoMemOps && !MF.getFunction().optForMinSize() &&
4797  (MI.getOpcode() == X86::CALL32r || MI.getOpcode() == X86::CALL64r ||
4798  MI.getOpcode() == X86::PUSH16r || MI.getOpcode() == X86::PUSH32r ||
4799  MI.getOpcode() == X86::PUSH64r))
4800  return nullptr;
4801 
4802  // Avoid partial and undef register update stalls unless optimizing for size.
4803  if (!MF.getFunction().optForSize() &&
4804  (hasPartialRegUpdate(MI.getOpcode(), Subtarget) ||
4806  return nullptr;
4807 
4808  unsigned NumOps = MI.getDesc().getNumOperands();
4809  bool isTwoAddr =
4810  NumOps > 1 && MI.getDesc().getOperandConstraint(1, MCOI::TIED_TO) != -1;
4811 
4812  // FIXME: AsmPrinter doesn't know how to handle
4813  // X86II::MO_GOT_ABSOLUTE_ADDRESS after folding.
4814  if (MI.getOpcode() == X86::ADD32ri &&
4816  return nullptr;
4817 
4818  // GOTTPOFF relocation loads can only be folded into add instructions.
4819  // FIXME: Need to exclude other relocations that only support specific
4820  // instructions.
4821  if (MOs.size() == X86::AddrNumOperands &&
4822  MOs[X86::AddrDisp].getTargetFlags() == X86II::MO_GOTTPOFF &&
4823  MI.getOpcode() != X86::ADD64rr)
4824  return nullptr;
4825 
4826  MachineInstr *NewMI = nullptr;
4827 
4828  // Attempt to fold any custom cases we have.
4829  if (MachineInstr *CustomMI =
4830  foldMemoryOperandCustom(MF, MI, OpNum, MOs, InsertPt, Size, Align))
4831  return CustomMI;
4832 
4833  const X86MemoryFoldTableEntry *I = nullptr;
4834 
4835  // Folding a memory location into the two-address part of a two-address
4836  // instruction is different than folding it other places. It requires
4837  // replacing the *two* registers with the memory location.
4838  if (isTwoAddr && NumOps >= 2 && OpNum < 2 && MI.getOperand(0).isReg() &&
4839  MI.getOperand(1).isReg() &&
4840  MI.getOperand(0).getReg() == MI.getOperand(1).getReg()) {
4842  isTwoAddrFold = true;
4843  } else {
4844  if (OpNum == 0) {
4845  if (MI.getOpcode() == X86::MOV32r0) {
4846  NewMI = MakeM0Inst(*this, X86::MOV32mi, MOs, InsertPt, MI);
4847  if (NewMI)
4848  return NewMI;
4849  }
4850  }
4851 
4852  I = lookupFoldTable(MI.getOpcode(), OpNum);
4853  }
4854 
4855  if (I != nullptr) {
4856  unsigned Opcode = I->DstOp;
4857  unsigned MinAlign = (I->Flags & TB_ALIGN_MASK) >> TB_ALIGN_SHIFT;
4858  if (Align < MinAlign)
4859  return nullptr;
4860  bool NarrowToMOV32rm = false;
4861  if (Size) {
4863  const TargetRegisterClass *RC = getRegClass(MI.getDesc(), OpNum,
4864  &RI, MF);
4865  unsigned RCSize = TRI.getRegSizeInBits(*RC) / 8;
4866  if (Size < RCSize) {
4867  // Check if it's safe to fold the load. If the size of the object is
4868  // narrower than the load width, then it's not.
4869  if (Opcode != X86::MOV64rm || RCSize != 8 || Size != 4)
4870  return nullptr;
4871  // If this is a 64-bit load, but the spill slot is 32, then we can do
4872  // a 32-bit load which is implicitly zero-extended. This likely is
4873  // due to live interval analysis remat'ing a load from stack slot.
4874  if (MI.getOperand(0).getSubReg() || MI.getOperand(1).getSubReg())
4875  return nullptr;
4876  Opcode = X86::MOV32rm;
4877  NarrowToMOV32rm = true;
4878  }
4879  }
4880 
4881  if (isTwoAddrFold)
4882  NewMI = FuseTwoAddrInst(MF, Opcode, MOs, InsertPt, MI, *this);
4883  else
4884  NewMI = FuseInst(MF, Opcode, OpNum, MOs, InsertPt, MI, *this);
4885 
4886  if (NarrowToMOV32rm) {
4887  // If this is the special case where we use a MOV32rm to load a 32-bit
4888  // value and zero-extend the top bits. Change the destination register
4889  // to a 32-bit one.
4890  unsigned DstReg = NewMI->getOperand(0).getReg();
4892  NewMI->getOperand(0).setReg(RI.getSubReg(DstReg, X86::sub_32bit));
4893  else
4894  NewMI->getOperand(0).setSubReg(X86::sub_32bit);
4895  }
4896  return NewMI;
4897  }
4898 
4899  // If the instruction and target operand are commutable, commute the
4900  // instruction and try again.
4901  if (AllowCommute) {
4902  unsigned CommuteOpIdx1 = OpNum, CommuteOpIdx2 = CommuteAnyOperandIndex;
4903  if (findCommutedOpIndices(MI, CommuteOpIdx1, CommuteOpIdx2)) {
4904  bool HasDef = MI.getDesc().getNumDefs();
4905  unsigned Reg0 = HasDef ? MI.getOperand(0).getReg() : 0;
4906  unsigned Reg1 = MI.getOperand(CommuteOpIdx1).getReg();
4907  unsigned Reg2 = MI.getOperand(CommuteOpIdx2).getReg();
4908  bool Tied1 =
4909  0 == MI.getDesc().getOperandConstraint(CommuteOpIdx1, MCOI::TIED_TO);
4910  bool Tied2 =
4911  0 == MI.getDesc().getOperandConstraint(CommuteOpIdx2, MCOI::TIED_TO);
4912 
4913  // If either of the commutable operands are tied to the destination
4914  // then we can not commute + fold.
4915  if ((HasDef && Reg0 == Reg1 && Tied1) ||
4916  (HasDef && Reg0 == Reg2 && Tied2))
4917  return nullptr;
4918 
4919  MachineInstr *CommutedMI =
4920  commuteInstruction(MI, false, CommuteOpIdx1, CommuteOpIdx2);
4921  if (!CommutedMI) {
4922  // Unable to commute.
4923  return nullptr;
4924  }
4925  if (CommutedMI != &MI) {
4926  // New instruction. We can't fold from this.
4927  CommutedMI->eraseFromParent();
4928  return nullptr;
4929  }
4930 
4931  // Attempt to fold with the commuted version of the instruction.
4932  NewMI = foldMemoryOperandImpl(MF, MI, CommuteOpIdx2, MOs, InsertPt,
4933  Size, Align, /*AllowCommute=*/false);
4934  if (NewMI)
4935  return NewMI;
4936 
4937  // Folding failed again - undo the commute before returning.
4938  MachineInstr *UncommutedMI =
4939  commuteInstruction(MI, false, CommuteOpIdx1, CommuteOpIdx2);
4940  if (!UncommutedMI) {
4941  // Unable to commute.
4942  return nullptr;
4943  }
4944  if (UncommutedMI != &MI) {
4945  // New instruction. It doesn't need to be kept.
4946  UncommutedMI->eraseFromParent();
4947  return nullptr;
4948  }
4949 
4950  // Return here to prevent duplicate fuse failure report.
4951  return nullptr;
4952  }
4953  }
4954 
4955  // No fusion
4956  if (PrintFailedFusing && !MI.isCopy())
4957  dbgs() << "We failed to fuse operand " << OpNum << " in " << MI;
4958  return nullptr;
4959 }
4960 
4961 MachineInstr *
4963  ArrayRef<unsigned> Ops,
4964  MachineBasicBlock::iterator InsertPt,
4965  int FrameIndex, LiveIntervals *LIS) const {
4966  // Check switch flag
4967  if (NoFusing)
4968  return nullptr;
4969 
4970  // Avoid partial and undef register update stalls unless optimizing for size.
4971  if (!MF.getFunction().optForSize() &&
4972  (hasPartialRegUpdate(MI.getOpcode(), Subtarget) ||
4974  return nullptr;
4975 
4976  // Don't fold subreg spills, or reloads that use a high subreg.
4977  for (auto Op : Ops) {
4978  MachineOperand &MO = MI.getOperand(Op);
4979  auto SubReg = MO.getSubReg();
4980  if (SubReg && (MO.isDef() || SubReg == X86::sub_8bit_hi))
4981  return nullptr;
4982  }
4983 
4984  const MachineFrameInfo &MFI = MF.getFrameInfo();
4985  unsigned Size = MFI.getObjectSize(FrameIndex);
4986  unsigned Alignment = MFI.getObjectAlignment(FrameIndex);
4987  // If the function stack isn't realigned we don't want to fold instructions
4988  // that need increased alignment.
4989  if (!RI.needsStackRealignment(MF))
4990  Alignment =
4991  std::min(Alignment, Subtarget.getFrameLowering()->getStackAlignment());
4992  if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
4993  unsigned NewOpc = 0;
4994  unsigned RCSize = 0;
4995  switch (MI.getOpcode()) {
4996  default: return nullptr;
4997  case X86::TEST8rr: NewOpc = X86::CMP8ri; RCSize = 1; break;
4998  case X86::TEST16rr: NewOpc = X86::CMP16ri8; RCSize = 2; break;
4999  case X86::TEST32rr: NewOpc = X86::CMP32ri8; RCSize = 4; break;
5000  case X86::TEST64rr: NewOpc = X86::CMP64ri8; RCSize = 8; break;
5001  }
5002  // Check if it's safe to fold the load. If the size of the object is
5003  // narrower than the load width, then it's not.
5004  if (Size < RCSize)
5005  return nullptr;
5006  // Change to CMPXXri r, 0 first.
5007  MI.setDesc(get(NewOpc));
5008  MI.getOperand(1).ChangeToImmediate(0);
5009  } else if (Ops.size() != 1)
5010  return nullptr;
5011 
5012  return foldMemoryOperandImpl(MF, MI, Ops[0],
5013  MachineOperand::CreateFI(FrameIndex), InsertPt,
5014  Size, Alignment, /*AllowCommute=*/true);
5015 }
5016 
5017 /// Check if \p LoadMI is a partial register load that we can't fold into \p MI
5018 /// because the latter uses contents that wouldn't be defined in the folded
5019 /// version. For instance, this transformation isn't legal:
5020 /// movss (%rdi), %xmm0
5021 /// addps %xmm0, %xmm0
5022 /// ->
5023 /// addps (%rdi), %xmm0
5024 ///
5025 /// But this one is:
5026 /// movss (%rdi), %xmm0
5027 /// addss %xmm0, %xmm0
5028 /// ->
5029 /// addss (%rdi), %xmm0
5030 ///
5032  const MachineInstr &UserMI,
5033  const MachineFunction &MF) {
5034  unsigned Opc = LoadMI.getOpcode();
5035  unsigned UserOpc = UserMI.getOpcode();
5037  const TargetRegisterClass *RC =
5038  MF.getRegInfo().getRegClass(LoadMI.getOperand(0).getReg());
5039  unsigned RegSize = TRI.getRegSizeInBits(*RC);
5040 
5041  if ((Opc == X86::MOVSSrm || Opc == X86::VMOVSSrm || Opc == X86::VMOVSSZrm) &&
5042  RegSize > 32) {
5043  // These instructions only load 32 bits, we can't fold them if the
5044  // destination register is wider than 32 bits (4 bytes), and its user
5045  // instruction isn't scalar (SS).
5046  switch (UserOpc) {
5047  case X86::ADDSSrr_Int: case X86::VADDSSrr_Int: case X86::VADDSSZrr_Int:
5048  case X86::CMPSSrr_Int: case X86::VCMPSSrr_Int: case X86::VCMPSSZrr_Int:
5049  case X86::DIVSSrr_Int: case X86::VDIVSSrr_Int: case X86::VDIVSSZrr_Int:
5050  case X86::MAXSSrr_Int: case X86::VMAXSSrr_Int: case X86::VMAXSSZrr_Int:
5051  case X86::MINSSrr_Int: case X86::VMINSSrr_Int: case X86::VMINSSZrr_Int:
5052  case X86::MULSSrr_Int: case X86::VMULSSrr_Int: case X86::VMULSSZrr_Int:
5053  case X86::SUBSSrr_Int: case X86::VSUBSSrr_Int: case X86::VSUBSSZrr_Int:
5054  case X86::VADDSSZrr_Intk: case X86::VADDSSZrr_Intkz:
5055  case X86::VDIVSSZrr_Intk: case X86::VDIVSSZrr_Intkz:
5056  case X86::VMAXSSZrr_Intk: case X86::VMAXSSZrr_Intkz:
5057  case X86::VMINSSZrr_Intk: case X86::VMINSSZrr_Intkz:
5058  case X86::VMULSSZrr_Intk: case X86::VMULSSZrr_Intkz:
5059  case X86::VSUBSSZrr_Intk: case X86::VSUBSSZrr_Intkz:
5060  case X86::VFMADDSS4rr_Int: case X86::VFNMADDSS4rr_Int:
5061  case X86::VFMSUBSS4rr_Int: case X86::VFNMSUBSS4rr_Int:
5062  case X86::VFMADD132SSr_Int: case X86::VFNMADD132SSr_Int:
5063  case X86::VFMADD213SSr_Int: case X86::VFNMADD213SSr_Int:
5064  case X86::VFMADD231SSr_Int: case X86::VFNMADD231SSr_Int:
5065  case X86::VFMSUB132SSr_Int: case X86::VFNMSUB132SSr_Int:
5066  case X86::VFMSUB213SSr_Int: case X86::VFNMSUB213SSr_Int:
5067  case X86::VFMSUB231SSr_Int: case X86::VFNMSUB231SSr_Int:
5068  case X86::VFMADD132SSZr_Int: case X86::VFNMADD132SSZr_Int:
5069  case X86::VFMADD213SSZr_Int: case X86::VFNMADD213SSZr_Int:
5070  case X86::VFMADD231SSZr_Int: case X86::VFNMADD231SSZr_Int:
5071  case X86::VFMSUB132SSZr_Int: case X86::VFNMSUB132SSZr_Int:
5072  case X86::VFMSUB213SSZr_Int: case X86::VFNMSUB213SSZr_Int:
5073  case X86::VFMSUB231SSZr_Int: case X86::VFNMSUB231SSZr_Int:
5074  case X86::VFMADD132SSZr_Intk: case X86::VFNMADD132SSZr_Intk:
5075  case X86::VFMADD213SSZr_Intk: case X86::VFNMADD213SSZr_Intk:
5076  case X86::VFMADD231SSZr_Intk: case X86::VFNMADD231SSZr_Intk:
5077  case X86::VFMSUB132SSZr_Intk: case X86::VFNMSUB132SSZr_Intk:
5078  case X86::VFMSUB213SSZr_Intk: case X86::VFNMSUB213SSZr_Intk:
5079  case X86::VFMSUB231SSZr_Intk: case X86::VFNMSUB231SSZr_Intk:
5080  case X86::VFMADD132SSZr_Intkz: case X86::VFNMADD132SSZr_Intkz:
5081  case X86::VFMADD213SSZr_Intkz: case X86::VFNMADD213SSZr_Intkz:
5082  case X86::VFMADD231SSZr_Intkz: case X86::VFNMADD231SSZr_Intkz:
5083  case X86::VFMSUB132SSZr_Intkz: case X86::VFNMSUB132SSZr_Intkz:
5084  case X86::VFMSUB213SSZr_Intkz: case X86::VFNMSUB213SSZr_Intkz:
5085  case X86::VFMSUB231SSZr_Intkz: case X86::VFNMSUB231SSZr_Intkz:
5086  return false;
5087  default:
5088  return true;
5089  }
5090  }
5091 
5092  if ((Opc == X86::MOVSDrm || Opc == X86::VMOVSDrm || Opc == X86::VMOVSDZrm) &&
5093  RegSize > 64) {
5094  // These instructions only load 64 bits, we can't fold them if the
5095  // destination register is wider than 64 bits (8 bytes), and its user
5096  // instruction isn't scalar (SD).
5097  switch (UserOpc) {
5098  case X86::ADDSDrr_Int: case X86::VADDSDrr_Int: case X86::VADDSDZrr_Int:
5099  case X86::CMPSDrr_Int: case X86::VCMPSDrr_Int: case X86::VCMPSDZrr_Int:
5100  case X86::DIVSDrr_Int: case X86::VDIVSDrr_Int: case X86::VDIVSDZrr_Int:
5101  case X86::MAXSDrr_Int: case X86::VMAXSDrr_Int: case X86::VMAXSDZrr_Int:
5102  case X86::MINSDrr_Int: case X86::VMINSDrr_Int: case X86::VMINSDZrr_Int:
5103  case X86::MULSDrr_Int: case X86::VMULSDrr_Int: case X86::VMULSDZrr_Int:
5104  case X86::SUBSDrr_Int: case X86::VSUBSDrr_Int: case X86::VSUBSDZrr_Int:
5105  case X86::VADDSDZrr_Intk: case X86::VADDSDZrr_Intkz:
5106  case X86::VDIVSDZrr_Intk: case X86::VDIVSDZrr_Intkz:
5107  case X86::VMAXSDZrr_Intk: case X86::VMAXSDZrr_Intkz:
5108  case X86::VMINSDZrr_Intk: case X86::VMINSDZrr_Intkz:
5109  case X86::VMULSDZrr_Intk: case X86::VMULSDZrr_Intkz:
5110  case X86::VSUBSDZrr_Intk: case X86::VSUBSDZrr_Intkz:
5111  case X86::VFMADDSD4rr_Int: case X86::VFNMADDSD4rr_Int:
5112  case X86::VFMSUBSD4rr_Int: case X86::VFNMSUBSD4rr_Int:
5113  case X86::VFMADD132SDr_Int: case X86::VFNMADD132SDr_Int:
5114  case X86::VFMADD213SDr_Int: case X86::VFNMADD213SDr_Int:
5115  case X86::VFMADD231SDr_Int: case X86::VFNMADD231SDr_Int:
5116  case X86::VFMSUB132SDr_Int: case X86::VFNMSUB132SDr_Int:
5117  case X86::VFMSUB213SDr_Int: case X86::VFNMSUB213SDr_Int:
5118  case X86::VFMSUB231SDr_Int: case X86::VFNMSUB231SDr_Int:
5119  case X86::VFMADD132SDZr_Int: case X86::VFNMADD132SDZr_Int:
5120  case X86::VFMADD213SDZr_Int: case X86::VFNMADD213SDZr_Int:
5121  case X86::VFMADD231SDZr_Int: case X86::VFNMADD231SDZr_Int:
5122  case X86::VFMSUB132SDZr_Int: case X86::VFNMSUB132SDZr_Int:
5123  case X86::VFMSUB213SDZr_Int: case X86::VFNMSUB213SDZr_Int:
5124  case X86::VFMSUB231SDZr_Int: case X86::VFNMSUB231SDZr_Int:
5125  case X86::VFMADD132SDZr_Intk: case X86::VFNMADD132SDZr_Intk:
5126  case X86::VFMADD213SDZr_Intk: case X86::VFNMADD213SDZr_Intk:
5127  case X86::VFMADD231SDZr_Intk: case X86::VFNMADD231SDZr_Intk:
5128  case X86::VFMSUB132SDZr_Intk: case X86::VFNMSUB132SDZr_Intk:
5129  case X86::VFMSUB213SDZr_Intk: case X86::VFNMSUB213SDZr_Intk:
5130  case X86::VFMSUB231SDZr_Intk: case X86::VFNMSUB231SDZr_Intk:
5131  case X86::VFMADD132SDZr_Intkz: case X86::VFNMADD132SDZr_Intkz:
5132  case X86::VFMADD213SDZr_Intkz: case X86::VFNMADD213SDZr_Intkz:
5133  case X86::VFMADD231SDZr_Intkz: case X86::VFNMADD231SDZr_Intkz:
5134  case X86::VFMSUB132SDZr_Intkz: case X86::VFNMSUB132SDZr_Intkz:
5135  case X86::VFMSUB213SDZr_Intkz: case X86::VFNMSUB213SDZr_Intkz:
5136  case X86::VFMSUB231SDZr_Intkz: case X86::VFNMSUB231SDZr_Intkz:
5137  return false;
5138  default:
5139  return true;
5140  }
5141  }
5142 
5143  return false;
5144 }
5145 
5148  MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
5149  LiveIntervals *LIS) const {
5150 
5151  // TODO: Support the case where LoadMI loads a wide register, but MI
5152  // only uses a subreg.
5153  for (auto Op : Ops) {
5154  if (MI.getOperand(Op).getSubReg())
5155  return nullptr;
5156  }
5157 
5158  // If loading from a FrameIndex, fold directly from the FrameIndex.
5159  unsigned NumOps = LoadMI.getDesc().getNumOperands();
5160  int FrameIndex;
5161  if (isLoadFromStackSlot(LoadMI, FrameIndex)) {
5162  if (isNonFoldablePartialRegisterLoad(LoadMI, MI, MF))
5163  return nullptr;
5164  return foldMemoryOperandImpl(MF, MI, Ops, InsertPt, FrameIndex, LIS);
5165  }
5166 
5167  // Check switch flag
5168  if (NoFusing) return nullptr;
5169 
5170  // Avoid partial and undef register update stalls unless optimizing for size.
5171  if (!MF.getFunction().optForSize() &&
5172  (hasPartialRegUpdate(MI.getOpcode(), Subtarget) ||
5174  return nullptr;
5175 
5176  // Determine the alignment of the load.
5177  unsigned Alignment = 0;
5178  if (LoadMI.hasOneMemOperand())
5179  Alignment = (*LoadMI.memoperands_begin())->getAlignment();
5180  else
5181  switch (LoadMI.getOpcode()) {
5182  case X86::AVX512_512_SET0:
5183  case X86::AVX512_512_SETALLONES:
5184  Alignment = 64;
5185  break;
5186  case X86::AVX2_SETALLONES:
5187  case X86::AVX1_SETALLONES:
5188  case X86::AVX_SET0:
5189  case X86::AVX512_256_SET0:
5190  Alignment = 32;
5191  break;
5192  case X86::V_SET0:
5193  case X86::V_SETALLONES:
5194  case X86::AVX512_128_SET0:
5195  Alignment = 16;
5196  break;
5197  case X86::MMX_SET0:
5198  case X86::FsFLD0SD:
5199  case X86::AVX512_FsFLD0SD:
5200  Alignment = 8;
5201  break;
5202  case X86::FsFLD0SS:
5203  case X86::AVX512_FsFLD0SS:
5204  Alignment = 4;
5205  break;
5206  default:
5207  return nullptr;
5208  }
5209  if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
5210  unsigned NewOpc = 0;
5211  switch (MI.getOpcode()) {
5212  default: return nullptr;
5213  case X86::TEST8rr: NewOpc = X86::CMP8ri; break;
5214  case X86::TEST16rr: NewOpc = X86::CMP16ri8; break;
5215  case X86::TEST32rr: NewOpc = X86::CMP32ri8; break;
5216  case X86::TEST64rr: NewOpc = X86::CMP64ri8; break;
5217  }
5218  // Change to CMPXXri r, 0 first.
5219  MI.setDesc(get(NewOpc));
5220  MI.getOperand(1).ChangeToImmediate(0);
5221  } else if (Ops.size() != 1)
5222  return nullptr;
5223 
5224  // Make sure the subregisters match.
5225  // Otherwise we risk changing the size of the load.
5226  if (LoadMI.getOperand(0).getSubReg() != MI.getOperand(Ops[0]).getSubReg())
5227  return nullptr;
5228 
5230  switch (LoadMI.getOpcode()) {
5231  case X86::MMX_SET0:
5232  case X86::V_SET0:
5233  case X86::V_SETALLONES:
5234  case X86::AVX2_SETALLONES:
5235  case X86::AVX1_SETALLONES:
5236  case X86::AVX_SET0:
5237  case X86::AVX512_128_SET0:
5238  case X86::AVX512_256_SET0:
5239  case X86::AVX512_512_SET0:
5240  case X86::AVX512_512_SETALLONES:
5241  case X86::FsFLD0SD:
5242  case X86::AVX512_FsFLD0SD:
5243  case X86::FsFLD0SS:
5244  case X86::AVX512_FsFLD0SS: {
5245  // Folding a V_SET0 or V_SETALLONES as a load, to ease register pressure.
5246  // Create a constant-pool entry and operands to load from it.
5247 
5248  // Medium and large mode can't fold loads this way.
5249  if (MF.getTarget().getCodeModel() != CodeModel::Small &&
5251  return nullptr;
5252 
5253  // x86-32 PIC requires a PIC base register for constant pools.
5254  unsigned PICBase = 0;
5255  if (MF.getTarget().isPositionIndependent()) {
5256  if (Subtarget.is64Bit())
5257  PICBase = X86::RIP;
5258  else
5259  // FIXME: PICBase = getGlobalBaseReg(&MF);
5260  // This doesn't work for several reasons.
5261  // 1. GlobalBaseReg may have been spilled.
5262  // 2. It may not be live at MI.
5263  return nullptr;
5264  }
5265 
5266  // Create a constant-pool entry.
5267  MachineConstantPool &MCP = *MF.getConstantPool();
5268  Type *Ty;
5269  unsigned Opc = LoadMI.getOpcode();
5270  if (Opc == X86::FsFLD0SS || Opc == X86::AVX512_FsFLD0SS)
5272  else if (Opc == X86::FsFLD0SD || Opc == X86::AVX512_FsFLD0SD)
5274  else if (Opc == X86::AVX512_512_SET0 || Opc == X86::AVX512_512_SETALLONES)
5276  else if (Opc == X86::AVX2_SETALLONES || Opc == X86::AVX_SET0 ||
5277  Opc == X86::AVX512_256_SET0 || Opc == X86::AVX1_SETALLONES)
5279  else if (Opc == X86::MMX_SET0)
5281  else
5283 
5284  bool IsAllOnes = (Opc == X86::V_SETALLONES || Opc == X86::AVX2_SETALLONES ||
5285  Opc == X86::AVX512_512_SETALLONES ||
5286  Opc == X86::AVX1_SETALLONES);
5287  const Constant *C = IsAllOnes ? Constant::getAllOnesValue(Ty) :
5289  unsigned CPI = MCP.getConstantPoolIndex(C, Alignment);
5290 
5291  // Create operands to load from the constant pool entry.
5292  MOs.push_back(MachineOperand::CreateReg(PICBase, false));
5294  MOs.push_back(MachineOperand::CreateReg(0, false));
5295  MOs.push_back(MachineOperand::CreateCPI(CPI, 0));
5296  MOs.push_back(MachineOperand::CreateReg(0, false));
5297  break;
5298  }
5299  default: {
5300  if (isNonFoldablePartialRegisterLoad(LoadMI, MI, MF))
5301  return nullptr;
5302 
5303  // Folding a normal load. Just copy the load's address operands.
5304  MOs.append(LoadMI.operands_begin() + NumOps - X86::AddrNumOperands,
5305  LoadMI.operands_begin() + NumOps);
5306  break;
5307  }
5308  }
5309  return foldMemoryOperandImpl(MF, MI, Ops[0], MOs, InsertPt,
5310  /*Size=*/0, Alignment, /*AllowCommute=*/true);
5311 }
5312 
5314  MachineFunction &MF, MachineInstr &MI, unsigned Reg, bool UnfoldLoad,
5315  bool UnfoldStore, SmallVectorImpl<MachineInstr *> &NewMIs) const {
5317  if (I == nullptr)
5318  return false;
5319  unsigned Opc = I->DstOp;
5320  unsigned Index = I->Flags & TB_INDEX_MASK;
5321  bool FoldedLoad = I->