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