1 //===-- X86InstrInfo.h - X86 Instruction Information ------------*- C++ -*-===//
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 #ifndef LLVM_LIB_TARGET_X86_X86INSTRINFO_H
14 #define LLVM_LIB_TARGET_X86_X86INSTRINFO_H
15 
16 #include "MCTargetDesc/X86BaseInfo.h"
17 #include "X86InstrFMA3Info.h"
18 #include "X86RegisterInfo.h"
19 #include "llvm/CodeGen/ISDOpcodes.h"
20 #include "llvm/CodeGen/TargetInstrInfo.h"
21 #include <vector>
22 
23 #define GET_INSTRINFO_HEADER
24 #include "X86GenInstrInfo.inc"
25 
26 namespace llvm {
27 class X86Subtarget;
28 
29 namespace X86 {
30 
31 enum AsmComments {
32   // For instr that was compressed from EVEX to VEX.
33   AC_EVEX_2_VEX = MachineInstr::TAsmComments
34 };
35 
36 /// Return a pair of condition code for the given predicate and whether
37 /// the instruction operands should be swaped to match the condition code.
38 std::pair<CondCode, bool> getX86ConditionCode(CmpInst::Predicate Predicate);
39 
40 /// Return a cmov opcode for the given register size in bytes, and operand type.
41 unsigned getCMovOpcode(unsigned RegBytes, bool HasMemoryOperand = false);
42 
43 // Turn jCC instruction into condition code.
44 CondCode getCondFromBranch(const MachineInstr &MI);
45 
46 // Turn setCC instruction into condition code.
47 CondCode getCondFromSETCC(const MachineInstr &MI);
48 
49 // Turn CMov instruction into condition code.
50 CondCode getCondFromCMov(const MachineInstr &MI);
51 
52 /// GetOppositeBranchCondition - Return the inverse of the specified cond,
53 /// e.g. turning COND_E to COND_NE.
54 CondCode GetOppositeBranchCondition(CondCode CC);
55 
56 /// Get the VPCMP immediate for the given condition.
57 unsigned getVPCMPImmForCond(ISD::CondCode CC);
58 
59 /// Get the VPCMP immediate if the opcodes are swapped.
60 unsigned getSwappedVPCMPImm(unsigned Imm);
61 
62 /// Get the VPCOM immediate if the opcodes are swapped.
63 unsigned getSwappedVPCOMImm(unsigned Imm);
64 
65 /// Get the VCMP immediate if the opcodes are swapped.
66 unsigned getSwappedVCMPImm(unsigned Imm);
67 
68 /// Check if the instruction is X87 instruction.
69 bool isX87Instruction(MachineInstr &MI);
70 } // namespace X86
71 
72 /// isGlobalStubReference - Return true if the specified TargetFlag operand is
73 /// a reference to a stub for a global, not the global itself.
74 inline static bool isGlobalStubReference(unsigned char TargetFlag) {
75   switch (TargetFlag) {
76   case X86II::MO_DLLIMPORT:               // dllimport stub.
77   case X86II::MO_GOTPCREL:                // rip-relative GOT reference.
78   case X86II::MO_GOTPCREL_NORELAX:        // rip-relative GOT reference.
79   case X86II::MO_GOT:                     // normal GOT reference.
80   case X86II::MO_DARWIN_NONLAZY_PIC_BASE: // Normal $non_lazy_ptr ref.
81   case X86II::MO_DARWIN_NONLAZY:          // Normal $non_lazy_ptr ref.
82   case X86II::MO_COFFSTUB:                // COFF .refptr stub.
83     return true;
84   default:
85     return false;
86   }
87 }
88 
89 /// isGlobalRelativeToPICBase - Return true if the specified global value
90 /// reference is relative to a 32-bit PIC base (X86ISD::GlobalBaseReg).  If this
91 /// is true, the addressing mode has the PIC base register added in (e.g. EBX).
92 inline static bool isGlobalRelativeToPICBase(unsigned char TargetFlag) {
93   switch (TargetFlag) {
94   case X86II::MO_GOTOFF:                  // isPICStyleGOT: local global.
95   case X86II::MO_GOT:                     // isPICStyleGOT: other global.
96   case X86II::MO_PIC_BASE_OFFSET:         // Darwin local global.
97   case X86II::MO_DARWIN_NONLAZY_PIC_BASE: // Darwin/32 external global.
98   case X86II::MO_TLVP:                    // ??? Pretty sure..
99     return true;
100   default:
101     return false;
102   }
103 }
104 
105 inline static bool isScale(const MachineOperand &MO) {
106   return MO.isImm() && (MO.getImm() == 1 || MO.getImm() == 2 ||
107                         MO.getImm() == 4 || MO.getImm() == 8);
108 }
109 
110 inline static bool isLeaMem(const MachineInstr &MI, unsigned Op) {
111   if (MI.getOperand(Op).isFI())
112     return true;
113   return Op + X86::AddrSegmentReg <= MI.getNumOperands() &&
114          MI.getOperand(Op + X86::AddrBaseReg).isReg() &&
115          isScale(MI.getOperand(Op + X86::AddrScaleAmt)) &&
116          MI.getOperand(Op + X86::AddrIndexReg).isReg() &&
117          (MI.getOperand(Op + X86::AddrDisp).isImm() ||
118           MI.getOperand(Op + X86::AddrDisp).isGlobal() ||
119           MI.getOperand(Op + X86::AddrDisp).isCPI() ||
120           MI.getOperand(Op + X86::AddrDisp).isJTI());
121 }
122 
123 inline static bool isMem(const MachineInstr &MI, unsigned Op) {
124   if (MI.getOperand(Op).isFI())
125     return true;
126   return Op + X86::AddrNumOperands <= MI.getNumOperands() &&
127          MI.getOperand(Op + X86::AddrSegmentReg).isReg() && isLeaMem(MI, Op);
128 }
129 
130 class X86InstrInfo final : public X86GenInstrInfo {
131   X86Subtarget &Subtarget;
132   const X86RegisterInfo RI;
133 
134   virtual void anchor();
135 
136   bool AnalyzeBranchImpl(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
137                          MachineBasicBlock *&FBB,
138                          SmallVectorImpl<MachineOperand> &Cond,
139                          SmallVectorImpl<MachineInstr *> &CondBranches,
140                          bool AllowModify) const;
141 
142 public:
143   explicit X86InstrInfo(X86Subtarget &STI);
144 
145   /// getRegisterInfo - TargetInstrInfo is a superset of MRegister info.  As
146   /// such, whenever a client has an instance of instruction info, it should
147   /// always be able to get register info as well (through this method).
148   ///
149   const X86RegisterInfo &getRegisterInfo() const { return RI; }
150 
151   /// Returns the stack pointer adjustment that happens inside the frame
152   /// setup..destroy sequence (e.g. by pushes, or inside the callee).
153   int64_t getFrameAdjustment(const MachineInstr &I) const {
154     assert(isFrameInstr(I));
155     if (isFrameSetup(I))
156       return I.getOperand(2).getImm();
157     return I.getOperand(1).getImm();
158   }
159 
160   /// Sets the stack pointer adjustment made inside the frame made up by this
161   /// instruction.
162   void setFrameAdjustment(MachineInstr &I, int64_t V) const {
163     assert(isFrameInstr(I));
164     if (isFrameSetup(I))
165       I.getOperand(2).setImm(V);
166     else
167       I.getOperand(1).setImm(V);
168   }
169 
170   /// getSPAdjust - This returns the stack pointer adjustment made by
171   /// this instruction. For x86, we need to handle more complex call
172   /// sequences involving PUSHes.
173   int getSPAdjust(const MachineInstr &MI) const override;
174 
175   /// isCoalescableExtInstr - Return true if the instruction is a "coalescable"
176   /// extension instruction. That is, it's like a copy where it's legal for the
177   /// source to overlap the destination. e.g. X86::MOVSX64rr32. If this returns
178   /// true, then it's expected the pre-extension value is available as a subreg
179   /// of the result register. This also returns the sub-register index in
180   /// SubIdx.
181   bool isCoalescableExtInstr(const MachineInstr &MI, Register &SrcReg,
182                              Register &DstReg, unsigned &SubIdx) const override;
183 
184   /// Returns true if the instruction has no behavior (specified or otherwise)
185   /// that is based on the value of any of its register operands
186   ///
187   /// Instructions are considered data invariant even if they set EFLAGS.
188   ///
189   /// A classical example of something that is inherently not data invariant is
190   /// an indirect jump -- the destination is loaded into icache based on the
191   /// bits set in the jump destination register.
192   ///
193   /// FIXME: This should become part of our instruction tables.
194   static bool isDataInvariant(MachineInstr &MI);
195 
196   /// Returns true if the instruction has no behavior (specified or otherwise)
197   /// that is based on the value loaded from memory or the value of any
198   /// non-address register operands.
199   ///
200   /// For example, if the latency of the instruction is dependent on the
201   /// particular bits set in any of the registers *or* any of the bits loaded
202   /// from memory.
203   ///
204   /// Instructions are considered data invariant even if they set EFLAGS.
205   ///
206   /// A classical example of something that is inherently not data invariant is
207   /// an indirect jump -- the destination is loaded into icache based on the
208   /// bits set in the jump destination register.
209   ///
210   /// FIXME: This should become part of our instruction tables.
211   static bool isDataInvariantLoad(MachineInstr &MI);
212 
213   unsigned isLoadFromStackSlot(const MachineInstr &MI,
214                                int &FrameIndex) const override;
215   unsigned isLoadFromStackSlot(const MachineInstr &MI,
216                                int &FrameIndex,
217                                unsigned &MemBytes) const override;
218   /// isLoadFromStackSlotPostFE - Check for post-frame ptr elimination
219   /// stack locations as well.  This uses a heuristic so it isn't
220   /// reliable for correctness.
221   unsigned isLoadFromStackSlotPostFE(const MachineInstr &MI,
222                                      int &FrameIndex) const override;
223 
224   unsigned isStoreToStackSlot(const MachineInstr &MI,
225                               int &FrameIndex) const override;
226   unsigned isStoreToStackSlot(const MachineInstr &MI,
227                               int &FrameIndex,
228                               unsigned &MemBytes) const override;
229   /// isStoreToStackSlotPostFE - Check for post-frame ptr elimination
230   /// stack locations as well.  This uses a heuristic so it isn't
231   /// reliable for correctness.
232   unsigned isStoreToStackSlotPostFE(const MachineInstr &MI,
233                                     int &FrameIndex) const override;
234 
235   bool isReallyTriviallyReMaterializable(const MachineInstr &MI,
236                                          AAResults *AA) const override;
237   void reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
238                      Register DestReg, unsigned SubIdx,
239                      const MachineInstr &Orig,
240                      const TargetRegisterInfo &TRI) const override;
241 
242   /// Given an operand within a MachineInstr, insert preceding code to put it
243   /// into the right format for a particular kind of LEA instruction. This may
244   /// involve using an appropriate super-register instead (with an implicit use
245   /// of the original) or creating a new virtual register and inserting COPY
246   /// instructions to get the data into the right class.
247   ///
248   /// Reference parameters are set to indicate how caller should add this
249   /// operand to the LEA instruction.
250   bool classifyLEAReg(MachineInstr &MI, const MachineOperand &Src,
251                       unsigned LEAOpcode, bool AllowSP, Register &NewSrc,
252                       bool &isKill, MachineOperand &ImplicitOp,
253                       LiveVariables *LV, LiveIntervals *LIS) const;
254 
255   /// convertToThreeAddress - This method must be implemented by targets that
256   /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
257   /// may be able to convert a two-address instruction into a true
258   /// three-address instruction on demand.  This allows the X86 target (for
259   /// example) to convert ADD and SHL instructions into LEA instructions if they
260   /// would require register copies due to two-addressness.
261   ///
262   /// This method returns a null pointer if the transformation cannot be
263   /// performed, otherwise it returns the new instruction.
264   ///
265   MachineInstr *convertToThreeAddress(MachineInstr &MI, LiveVariables *LV,
266                                       LiveIntervals *LIS) const override;
267 
268   /// Returns true iff the routine could find two commutable operands in the
269   /// given machine instruction.
270   /// The 'SrcOpIdx1' and 'SrcOpIdx2' are INPUT and OUTPUT arguments. Their
271   /// input values can be re-defined in this method only if the input values
272   /// are not pre-defined, which is designated by the special value
273   /// 'CommuteAnyOperandIndex' assigned to it.
274   /// If both of indices are pre-defined and refer to some operands, then the
275   /// method simply returns true if the corresponding operands are commutable
276   /// and returns false otherwise.
277   ///
278   /// For example, calling this method this way:
279   ///     unsigned Op1 = 1, Op2 = CommuteAnyOperandIndex;
280   ///     findCommutedOpIndices(MI, Op1, Op2);
281   /// can be interpreted as a query asking to find an operand that would be
282   /// commutable with the operand#1.
283   bool findCommutedOpIndices(const MachineInstr &MI, unsigned &SrcOpIdx1,
284                              unsigned &SrcOpIdx2) const override;
285 
286   /// Returns true if we have preference on the operands order in MI, the
287   /// commute decision is returned in Commute.
288   bool hasCommutePreference(MachineInstr &MI, bool &Commute) const override;
289 
290   /// Returns an adjusted FMA opcode that must be used in FMA instruction that
291   /// performs the same computations as the given \p MI but which has the
292   /// operands \p SrcOpIdx1 and \p SrcOpIdx2 commuted.
293   /// It may return 0 if it is unsafe to commute the operands.
294   /// Note that a machine instruction (instead of its opcode) is passed as the
295   /// first parameter to make it possible to analyze the instruction's uses and
296   /// commute the first operand of FMA even when it seems unsafe when you look
297   /// at the opcode. For example, it is Ok to commute the first operand of
298   /// VFMADD*SD_Int, if ONLY the lowest 64-bit element of the result is used.
299   ///
300   /// The returned FMA opcode may differ from the opcode in the given \p MI.
301   /// For example, commuting the operands #1 and #3 in the following FMA
302   ///     FMA213 #1, #2, #3
303   /// results into instruction with adjusted opcode:
304   ///     FMA231 #3, #2, #1
305   unsigned
306   getFMA3OpcodeToCommuteOperands(const MachineInstr &MI, unsigned SrcOpIdx1,
307                                  unsigned SrcOpIdx2,
308                                  const X86InstrFMA3Group &FMA3Group) const;
309 
310   // Branch analysis.
311   bool isUnconditionalTailCall(const MachineInstr &MI) const override;
312   bool canMakeTailCallConditional(SmallVectorImpl<MachineOperand> &Cond,
313                                   const MachineInstr &TailCall) const override;
314   void replaceBranchWithTailCall(MachineBasicBlock &MBB,
315                                  SmallVectorImpl<MachineOperand> &Cond,
316                                  const MachineInstr &TailCall) const override;
317 
318   bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
319                      MachineBasicBlock *&FBB,
320                      SmallVectorImpl<MachineOperand> &Cond,
321                      bool AllowModify) const override;
322 
323   Optional<ExtAddrMode>
324   getAddrModeFromMemoryOp(const MachineInstr &MemI,
325                           const TargetRegisterInfo *TRI) const override;
326 
327   bool getConstValDefinedInReg(const MachineInstr &MI, const Register Reg,
328                                int64_t &ImmVal) const override;
329 
330   bool preservesZeroValueInReg(const MachineInstr *MI,
331                                const Register NullValueReg,
332                                const TargetRegisterInfo *TRI) const override;
333 
334   bool getMemOperandsWithOffsetWidth(
335       const MachineInstr &LdSt,
336       SmallVectorImpl<const MachineOperand *> &BaseOps, int64_t &Offset,
337       bool &OffsetIsScalable, unsigned &Width,
338       const TargetRegisterInfo *TRI) const override;
339   bool analyzeBranchPredicate(MachineBasicBlock &MBB,
340                               TargetInstrInfo::MachineBranchPredicate &MBP,
341                               bool AllowModify = false) const override;
342 
343   unsigned removeBranch(MachineBasicBlock &MBB,
344                         int *BytesRemoved = nullptr) const override;
345   unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
346                         MachineBasicBlock *FBB, ArrayRef<MachineOperand> Cond,
347                         const DebugLoc &DL,
348                         int *BytesAdded = nullptr) const override;
349   bool canInsertSelect(const MachineBasicBlock &, ArrayRef<MachineOperand> Cond,
350                        Register, Register, Register, int &, int &,
351                        int &) const override;
352   void insertSelect(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
353                     const DebugLoc &DL, Register DstReg,
354                     ArrayRef<MachineOperand> Cond, Register TrueReg,
355                     Register FalseReg) const override;
356   void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
357                    const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg,
358                    bool KillSrc) const override;
359   void storeRegToStackSlot(MachineBasicBlock &MBB,
360                            MachineBasicBlock::iterator MI, Register SrcReg,
361                            bool isKill, int FrameIndex,
362                            const TargetRegisterClass *RC,
363                            const TargetRegisterInfo *TRI) const override;
364 
365   void loadRegFromStackSlot(MachineBasicBlock &MBB,
366                             MachineBasicBlock::iterator MI, Register DestReg,
367                             int FrameIndex, const TargetRegisterClass *RC,
368                             const TargetRegisterInfo *TRI) const override;
369 
370   bool expandPostRAPseudo(MachineInstr &MI) const override;
371 
372   /// Check whether the target can fold a load that feeds a subreg operand
373   /// (or a subreg operand that feeds a store).
374   bool isSubregFoldable() const override { return true; }
375 
376   /// foldMemoryOperand - If this target supports it, fold a load or store of
377   /// the specified stack slot into the specified machine instruction for the
378   /// specified operand(s).  If this is possible, the target should perform the
379   /// folding and return true, otherwise it should return false.  If it folds
380   /// the instruction, it is likely that the MachineInstruction the iterator
381   /// references has been changed.
382   MachineInstr *
383   foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,
384                         ArrayRef<unsigned> Ops,
385                         MachineBasicBlock::iterator InsertPt, int FrameIndex,
386                         LiveIntervals *LIS = nullptr,
387                         VirtRegMap *VRM = nullptr) const override;
388 
389   /// foldMemoryOperand - Same as the previous version except it allows folding
390   /// of any load and store from / to any address, not just from a specific
391   /// stack slot.
392   MachineInstr *foldMemoryOperandImpl(
393       MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
394       MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
395       LiveIntervals *LIS = nullptr) const override;
396 
397   /// unfoldMemoryOperand - Separate a single instruction which folded a load or
398   /// a store or a load and a store into two or more instruction. If this is
399   /// possible, returns true as well as the new instructions by reference.
400   bool
401   unfoldMemoryOperand(MachineFunction &MF, MachineInstr &MI, unsigned Reg,
402                       bool UnfoldLoad, bool UnfoldStore,
403                       SmallVectorImpl<MachineInstr *> &NewMIs) const override;
404 
405   bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
406                            SmallVectorImpl<SDNode *> &NewNodes) const override;
407 
408   /// getOpcodeAfterMemoryUnfold - Returns the opcode of the would be new
409   /// instruction after load / store are unfolded from an instruction of the
410   /// specified opcode. It returns zero if the specified unfolding is not
411   /// possible. If LoadRegIndex is non-null, it is filled in with the operand
412   /// index of the operand which will hold the register holding the loaded
413   /// value.
414   unsigned
415   getOpcodeAfterMemoryUnfold(unsigned Opc, bool UnfoldLoad, bool UnfoldStore,
416                              unsigned *LoadRegIndex = nullptr) const override;
417 
418   /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler
419   /// to determine if two loads are loading from the same base address. It
420   /// should only return true if the base pointers are the same and the
421   /// only differences between the two addresses are the offset. It also returns
422   /// the offsets by reference.
423   bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2, int64_t &Offset1,
424                                int64_t &Offset2) const override;
425 
426   /// isSchedulingBoundary - Overrides the isSchedulingBoundary from
427   ///	Codegen/TargetInstrInfo.cpp to make it capable of identifying ENDBR
428   /// intructions and prevent it from being re-scheduled.
429   bool isSchedulingBoundary(const MachineInstr &MI,
430                             const MachineBasicBlock *MBB,
431                             const MachineFunction &MF) const override;
432 
433   /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
434   /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads
435   /// should be scheduled togther. On some targets if two loads are loading from
436   /// addresses in the same cache line, it's better if they are scheduled
437   /// together. This function takes two integers that represent the load offsets
438   /// from the common base address. It returns true if it decides it's desirable
439   /// to schedule the two loads together. "NumLoads" is the number of loads that
440   /// have already been scheduled after Load1.
441   bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2, int64_t Offset1,
442                                int64_t Offset2,
443                                unsigned NumLoads) const override;
444 
445   MCInst getNop() const override;
446 
447   bool
448   reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const override;
449 
450   /// isSafeToMoveRegClassDefs - Return true if it's safe to move a machine
451   /// instruction that defines the specified register class.
452   bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const override;
453 
454   /// True if MI has a condition code def, e.g. EFLAGS, that is
455   /// not marked dead.
456   bool hasLiveCondCodeDef(MachineInstr &MI) const;
457 
458   /// getGlobalBaseReg - Return a virtual register initialized with the
459   /// the global base register value. Output instructions required to
460   /// initialize the register in the function entry block, if necessary.
461   ///
462   unsigned getGlobalBaseReg(MachineFunction *MF) const;
463 
464   std::pair<uint16_t, uint16_t>
465   getExecutionDomain(const MachineInstr &MI) const override;
466 
467   uint16_t getExecutionDomainCustom(const MachineInstr &MI) const;
468 
469   void setExecutionDomain(MachineInstr &MI, unsigned Domain) const override;
470 
471   bool setExecutionDomainCustom(MachineInstr &MI, unsigned Domain) const;
472 
473   unsigned
474   getPartialRegUpdateClearance(const MachineInstr &MI, unsigned OpNum,
475                                const TargetRegisterInfo *TRI) const override;
476   unsigned getUndefRegClearance(const MachineInstr &MI, unsigned OpNum,
477                                 const TargetRegisterInfo *TRI) const override;
478   void breakPartialRegDependency(MachineInstr &MI, unsigned OpNum,
479                                  const TargetRegisterInfo *TRI) const override;
480 
481   MachineInstr *foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI,
482                                       unsigned OpNum,
483                                       ArrayRef<MachineOperand> MOs,
484                                       MachineBasicBlock::iterator InsertPt,
485                                       unsigned Size, Align Alignment,
486                                       bool AllowCommute) const;
487 
488   bool isHighLatencyDef(int opc) const override;
489 
490   bool hasHighOperandLatency(const TargetSchedModel &SchedModel,
491                              const MachineRegisterInfo *MRI,
492                              const MachineInstr &DefMI, unsigned DefIdx,
493                              const MachineInstr &UseMI,
494                              unsigned UseIdx) const override;
495 
496   bool useMachineCombiner() const override { return true; }
497 
498   bool isAssociativeAndCommutative(const MachineInstr &Inst) const override;
499 
500   bool hasReassociableOperands(const MachineInstr &Inst,
501                                const MachineBasicBlock *MBB) const override;
502 
503   void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2,
504                              MachineInstr &NewMI1,
505                              MachineInstr &NewMI2) const override;
506 
507   /// analyzeCompare - For a comparison instruction, return the source registers
508   /// in SrcReg and SrcReg2 if having two register operands, and the value it
509   /// compares against in CmpValue. Return true if the comparison instruction
510   /// can be analyzed.
511   bool analyzeCompare(const MachineInstr &MI, Register &SrcReg,
512                       Register &SrcReg2, int64_t &CmpMask,
513                       int64_t &CmpValue) const override;
514 
515   /// optimizeCompareInstr - Check if there exists an earlier instruction that
516   /// operates on the same source operands and sets flags in the same way as
517   /// Compare; remove Compare if possible.
518   bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
519                             Register SrcReg2, int64_t CmpMask, int64_t CmpValue,
520                             const MachineRegisterInfo *MRI) const override;
521 
522   /// optimizeLoadInstr - Try to remove the load by folding it to a register
523   /// operand at the use. We fold the load instructions if and only if the
524   /// def and use are in the same BB. We only look at one load and see
525   /// whether it can be folded into MI. FoldAsLoadDefReg is the virtual register
526   /// defined by the load we are trying to fold. DefMI returns the machine
527   /// instruction that defines FoldAsLoadDefReg, and the function returns
528   /// the machine instruction generated due to folding.
529   MachineInstr *optimizeLoadInstr(MachineInstr &MI,
530                                   const MachineRegisterInfo *MRI,
531                                   Register &FoldAsLoadDefReg,
532                                   MachineInstr *&DefMI) const override;
533 
534   std::pair<unsigned, unsigned>
535   decomposeMachineOperandsTargetFlags(unsigned TF) const override;
536 
537   ArrayRef<std::pair<unsigned, const char *>>
538   getSerializableDirectMachineOperandTargetFlags() const override;
539 
540   virtual outliner::OutlinedFunction getOutliningCandidateInfo(
541       std::vector<outliner::Candidate> &RepeatedSequenceLocs) const override;
542 
543   bool isFunctionSafeToOutlineFrom(MachineFunction &MF,
544                                    bool OutlineFromLinkOnceODRs) const override;
545 
546   outliner::InstrType
547   getOutliningType(MachineBasicBlock::iterator &MIT, unsigned Flags) const override;
548 
549   void buildOutlinedFrame(MachineBasicBlock &MBB, MachineFunction &MF,
550                           const outliner::OutlinedFunction &OF) const override;
551 
552   MachineBasicBlock::iterator
553   insertOutlinedCall(Module &M, MachineBasicBlock &MBB,
554                      MachineBasicBlock::iterator &It, MachineFunction &MF,
555                      const outliner::Candidate &C) const override;
556 
557 #define GET_INSTRINFO_HELPER_DECLS
558 #include "X86GenInstrInfo.inc"
559 
560   static bool hasLockPrefix(const MachineInstr &MI) {
561     return MI.getDesc().TSFlags & X86II::LOCK;
562   }
563 
564   Optional<ParamLoadedValue> describeLoadedValue(const MachineInstr &MI,
565                                                  Register Reg) const override;
566 
567 protected:
568   /// Commutes the operands in the given instruction by changing the operands
569   /// order and/or changing the instruction's opcode and/or the immediate value
570   /// operand.
571   ///
572   /// The arguments 'CommuteOpIdx1' and 'CommuteOpIdx2' specify the operands
573   /// to be commuted.
574   ///
575   /// Do not call this method for a non-commutable instruction or
576   /// non-commutable operands.
577   /// Even though the instruction is commutable, the method may still
578   /// fail to commute the operands, null pointer is returned in such cases.
579   MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
580                                        unsigned CommuteOpIdx1,
581                                        unsigned CommuteOpIdx2) const override;
582 
583   /// If the specific machine instruction is a instruction that moves/copies
584   /// value from one register to another register return destination and source
585   /// registers as machine operands.
586   Optional<DestSourcePair>
587   isCopyInstrImpl(const MachineInstr &MI) const override;
588 
589 private:
590   /// This is a helper for convertToThreeAddress for 8 and 16-bit instructions.
591   /// We use 32-bit LEA to form 3-address code by promoting to a 32-bit
592   /// super-register and then truncating back down to a 8/16-bit sub-register.
593   MachineInstr *convertToThreeAddressWithLEA(unsigned MIOpc, MachineInstr &MI,
594                                              LiveVariables *LV,
595                                              LiveIntervals *LIS,
596                                              bool Is8BitOp) const;
597 
598   /// Handles memory folding for special case instructions, for instance those
599   /// requiring custom manipulation of the address.
600   MachineInstr *foldMemoryOperandCustom(MachineFunction &MF, MachineInstr &MI,
601                                         unsigned OpNum,
602                                         ArrayRef<MachineOperand> MOs,
603                                         MachineBasicBlock::iterator InsertPt,
604                                         unsigned Size, Align Alignment) const;
605 
606   /// isFrameOperand - Return true and the FrameIndex if the specified
607   /// operand and follow operands form a reference to the stack frame.
608   bool isFrameOperand(const MachineInstr &MI, unsigned int Op,
609                       int &FrameIndex) const;
610 
611   /// Returns true iff the routine could find two commutable operands in the
612   /// given machine instruction with 3 vector inputs.
613   /// The 'SrcOpIdx1' and 'SrcOpIdx2' are INPUT and OUTPUT arguments. Their
614   /// input values can be re-defined in this method only if the input values
615   /// are not pre-defined, which is designated by the special value
616   /// 'CommuteAnyOperandIndex' assigned to it.
617   /// If both of indices are pre-defined and refer to some operands, then the
618   /// method simply returns true if the corresponding operands are commutable
619   /// and returns false otherwise.
620   ///
621   /// For example, calling this method this way:
622   ///     unsigned Op1 = 1, Op2 = CommuteAnyOperandIndex;
623   ///     findThreeSrcCommutedOpIndices(MI, Op1, Op2);
624   /// can be interpreted as a query asking to find an operand that would be
625   /// commutable with the operand#1.
626   ///
627   /// If IsIntrinsic is set, operand 1 will be ignored for commuting.
628   bool findThreeSrcCommutedOpIndices(const MachineInstr &MI,
629                                      unsigned &SrcOpIdx1,
630                                      unsigned &SrcOpIdx2,
631                                      bool IsIntrinsic = false) const;
632 
633   /// Returns true when instruction \p FlagI produces the same flags as \p OI.
634   /// The caller should pass in the results of calling analyzeCompare on \p OI:
635   /// \p SrcReg, \p SrcReg2, \p ImmMask, \p ImmValue.
636   /// If the flags match \p OI as if it had the input operands swapped then the
637   /// function succeeds and sets \p IsSwapped to true.
638   ///
639   /// Examples of OI, FlagI pairs returning true:
640   ///   CMP %1, 42   and  CMP %1, 42
641   ///   CMP %1, %2   and  %3 = SUB %1, %2
642   ///   TEST %1, %1  and  %2 = SUB %1, 0
643   ///   CMP %1, %2   and  %3 = SUB %2, %1  ; IsSwapped=true
644   bool isRedundantFlagInstr(const MachineInstr &FlagI, Register SrcReg,
645                             Register SrcReg2, int64_t ImmMask, int64_t ImmValue,
646                             const MachineInstr &OI, bool *IsSwapped,
647                             int64_t *ImmDelta) const;
648 };
649 
650 } // namespace llvm
651 
652 #endif
653