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