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