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