LLVM 22.0.0git
TargetInstrInfo.h
Go to the documentation of this file.
1//===- llvm/CodeGen/TargetInstrInfo.h - Instruction Info --------*- 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 describes the target machine instruction set to the code generator.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CODEGEN_TARGETINSTRINFO_H
14#define LLVM_CODEGEN_TARGETINSTRINFO_H
15
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/Uniformity.h"
31#include "llvm/MC/MCInstrInfo.h"
36#include <array>
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <utility>
41#include <vector>
42
43namespace llvm {
44
45class DFAPacketizer;
47class LiveIntervals;
48class LiveVariables;
49class MachineLoop;
53class MCAsmInfo;
54class MCInst;
55struct MCSchedModel;
56class Module;
57class ScheduleDAG;
58class ScheduleDAGMI;
60class SDNode;
61class SelectionDAG;
62class SMSchedule;
64class RegScavenger;
69enum class MachineTraceStrategy;
70
71template <class T> class SmallVectorImpl;
72
73using ParamLoadedValue = std::pair<MachineOperand, DIExpression*>;
74
78
80 : Destination(&Dest), Source(&Src) {}
81};
82
83/// Used to describe a register and immediate addition.
84struct RegImmPair {
86 int64_t Imm;
87
88 RegImmPair(Register Reg, int64_t Imm) : Reg(Reg), Imm(Imm) {}
89};
90
91/// Used to describe addressing mode similar to ExtAddrMode in CodeGenPrepare.
92/// It holds the register values, the scale value and the displacement.
93/// It also holds a descriptor for the expression used to calculate the address
94/// from the operands.
96 enum class Formula {
97 Basic = 0, // BaseReg + ScaledReg * Scale + Displacement
98 SExtScaledReg = 1, // BaseReg + sext(ScaledReg) * Scale + Displacement
99 ZExtScaledReg = 2 // BaseReg + zext(ScaledReg) * Scale + Displacement
100 };
101
104 int64_t Scale = 0;
105 int64_t Displacement = 0;
107 ExtAddrMode() = default;
108};
109
110//---------------------------------------------------------------------------
111///
112/// TargetInstrInfo - Interface to description of machine instruction set
113///
115protected:
116 /// Subtarget specific sub-array of MCInstrInfo's RegClassByHwModeTables
117 /// (i.e. the table for the active HwMode). This should be indexed by
118 /// MCOperandInfo's RegClass field for LookupRegClassByHwMode operands.
119 const int16_t *const RegClassByHwMode;
120
121 TargetInstrInfo(unsigned CFSetupOpcode = ~0u, unsigned CFDestroyOpcode = ~0u,
122 unsigned CatchRetOpcode = ~0u, unsigned ReturnOpcode = ~0u,
123 const int16_t *const RegClassByHwModeTable = nullptr)
124 : RegClassByHwMode(RegClassByHwModeTable),
125 CallFrameSetupOpcode(CFSetupOpcode),
126 CallFrameDestroyOpcode(CFDestroyOpcode), CatchRetOpcode(CatchRetOpcode),
127 ReturnOpcode(ReturnOpcode) {}
128
129public:
133
134 static bool isGenericOpcode(unsigned Opc) {
135 return Opc <= TargetOpcode::GENERIC_OP_END;
136 }
137
138 static bool isGenericAtomicRMWOpcode(unsigned Opc) {
139 return Opc >= TargetOpcode::GENERIC_ATOMICRMW_OP_START &&
140 Opc <= TargetOpcode::GENERIC_ATOMICRMW_OP_END;
141 }
142
143 /// \returns the subtarget appropriate RegClassID for \p OpInfo
144 ///
145 /// Note this shadows a version of getOpRegClassID in MCInstrInfo which takes
146 /// an additional argument for the subtarget's HwMode, since TargetInstrInfo
147 /// is owned by a subtarget in CodeGen but MCInstrInfo is a TargetMachine
148 /// constant.
149 int16_t getOpRegClassID(const MCOperandInfo &OpInfo) const {
150 if (OpInfo.isLookupRegClassByHwMode())
151 return RegClassByHwMode[OpInfo.RegClass];
152 return OpInfo.RegClass;
153 }
154
155 /// Given a machine instruction descriptor, returns the register
156 /// class constraint for OpNum, or NULL.
157 virtual const TargetRegisterClass *
158 getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
159 const TargetRegisterInfo *TRI) const;
160
161 /// Returns true if MI is an instruction we are unable to reason about
162 /// (like a call or something with unmodeled side effects).
163 virtual bool isGlobalMemoryObject(const MachineInstr *MI) const;
164
165 /// Return true if the instruction is trivially rematerializable, meaning it
166 /// has no side effects and requires no operands that aren't always available.
167 /// This means the only allowed uses are constants and unallocatable physical
168 /// registers so that the instructions result is independent of the place
169 /// in the function.
172 return false;
173 for (const MachineOperand &MO : MI.all_uses()) {
174 if (MO.getReg().isVirtual())
175 return false;
176 }
177 return true;
178 }
179
180 /// Return true if the instruction would be materializable at a point
181 /// in the containing function where all virtual register uses were
182 /// known to be live and available in registers.
183 bool isReMaterializable(const MachineInstr &MI) const {
184 return (MI.getOpcode() == TargetOpcode::IMPLICIT_DEF &&
185 MI.getNumOperands() == 1) ||
186 (MI.getDesc().isRematerializable() && isReMaterializableImpl(MI));
187 }
188
189 /// Given \p MO is a PhysReg use return if it can be ignored for the purpose
190 /// of instruction rematerialization or sinking.
191 virtual bool isIgnorableUse(const MachineOperand &MO) const {
192 return false;
193 }
194
195 virtual bool isSafeToSink(MachineInstr &MI, MachineBasicBlock *SuccToSinkTo,
196 MachineCycleInfo *CI) const {
197 return true;
198 }
199
200 /// For a "cheap" instruction which doesn't enable additional sinking,
201 /// should MachineSink break a critical edge to sink it anyways?
203 return false;
204 }
205
206protected:
207 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
208 /// set, this hook lets the target specify whether the instruction is actually
209 /// rematerializable, taking into consideration its operands. This
210 /// predicate must return false if the instruction has any side effects other
211 /// than producing a value.
212 virtual bool isReMaterializableImpl(const MachineInstr &MI) const;
213
214 /// This method commutes the operands of the given machine instruction MI.
215 /// The operands to be commuted are specified by their indices OpIdx1 and
216 /// OpIdx2.
217 ///
218 /// If a target has any instructions that are commutable but require
219 /// converting to different instructions or making non-trivial changes
220 /// to commute them, this method can be overloaded to do that.
221 /// The default implementation simply swaps the commutable operands.
222 ///
223 /// If NewMI is false, MI is modified in place and returned; otherwise, a
224 /// new machine instruction is created and returned.
225 ///
226 /// Do not call this method for a non-commutable instruction.
227 /// Even though the instruction is commutable, the method may still
228 /// fail to commute the operands, null pointer is returned in such cases.
229 virtual MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
230 unsigned OpIdx1,
231 unsigned OpIdx2) const;
232
233 /// Assigns the (CommutableOpIdx1, CommutableOpIdx2) pair of commutable
234 /// operand indices to (ResultIdx1, ResultIdx2).
235 /// One or both input values of the pair: (ResultIdx1, ResultIdx2) may be
236 /// predefined to some indices or be undefined (designated by the special
237 /// value 'CommuteAnyOperandIndex').
238 /// The predefined result indices cannot be re-defined.
239 /// The function returns true iff after the result pair redefinition
240 /// the fixed result pair is equal to or equivalent to the source pair of
241 /// indices: (CommutableOpIdx1, CommutableOpIdx2). It is assumed here that
242 /// the pairs (x,y) and (y,x) are equivalent.
243 static bool fixCommutedOpIndices(unsigned &ResultIdx1, unsigned &ResultIdx2,
244 unsigned CommutableOpIdx1,
245 unsigned CommutableOpIdx2);
246
247public:
248 /// These methods return the opcode of the frame setup/destroy instructions
249 /// if they exist (-1 otherwise). Some targets use pseudo instructions in
250 /// order to abstract away the difference between operating with a frame
251 /// pointer and operating without, through the use of these two instructions.
252 /// A FrameSetup MI in MF implies MFI::AdjustsStack.
253 ///
254 unsigned getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
255 unsigned getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
256
257 /// Returns true if the argument is a frame pseudo instruction.
258 bool isFrameInstr(const MachineInstr &I) const {
259 return I.getOpcode() == getCallFrameSetupOpcode() ||
260 I.getOpcode() == getCallFrameDestroyOpcode();
261 }
262
263 /// Returns true if the argument is a frame setup pseudo instruction.
264 bool isFrameSetup(const MachineInstr &I) const {
265 return I.getOpcode() == getCallFrameSetupOpcode();
266 }
267
268 /// Returns size of the frame associated with the given frame instruction.
269 /// For frame setup instruction this is frame that is set up space set up
270 /// after the instruction. For frame destroy instruction this is the frame
271 /// freed by the caller.
272 /// Note, in some cases a call frame (or a part of it) may be prepared prior
273 /// to the frame setup instruction. It occurs in the calls that involve
274 /// inalloca arguments. This function reports only the size of the frame part
275 /// that is set up between the frame setup and destroy pseudo instructions.
276 int64_t getFrameSize(const MachineInstr &I) const {
277 assert(isFrameInstr(I) && "Not a frame instruction");
278 assert(I.getOperand(0).getImm() >= 0);
279 return I.getOperand(0).getImm();
280 }
281
282 /// Returns the total frame size, which is made up of the space set up inside
283 /// the pair of frame start-stop instructions and the space that is set up
284 /// prior to the pair.
285 int64_t getFrameTotalSize(const MachineInstr &I) const {
286 if (isFrameSetup(I)) {
287 assert(I.getOperand(1).getImm() >= 0 &&
288 "Frame size must not be negative");
289 return getFrameSize(I) + I.getOperand(1).getImm();
290 }
291 return getFrameSize(I);
292 }
293
294 unsigned getCatchReturnOpcode() const { return CatchRetOpcode; }
295 unsigned getReturnOpcode() const { return ReturnOpcode; }
296
297 /// Returns the actual stack pointer adjustment made by an instruction
298 /// as part of a call sequence. By default, only call frame setup/destroy
299 /// instructions adjust the stack, but targets may want to override this
300 /// to enable more fine-grained adjustment, or adjust by a different value.
301 virtual int getSPAdjust(const MachineInstr &MI) const;
302
303 /// Return true if the instruction is a "coalescable" extension instruction.
304 /// That is, it's like a copy where it's legal for the source to overlap the
305 /// destination. e.g. X86::MOVSX64rr32. If this returns true, then it's
306 /// expected the pre-extension value is available as a subreg of the result
307 /// register. This also returns the sub-register index in SubIdx.
308 virtual bool isCoalescableExtInstr(const MachineInstr &MI, Register &SrcReg,
309 Register &DstReg, unsigned &SubIdx) const {
310 return false;
311 }
312
313 /// If the specified machine instruction is a direct
314 /// load from a stack slot, return the virtual or physical register number of
315 /// the destination along with the FrameIndex of the loaded stack slot. If
316 /// not, return 0. This predicate must return 0 if the instruction has
317 /// any side effects other than loading from the stack slot.
319 int &FrameIndex) const {
320 return 0;
321 }
322
323 /// Optional extension of isLoadFromStackSlot that returns the number of
324 /// bytes loaded from the stack. This must be implemented if a backend
325 /// supports partial stack slot spills/loads to further disambiguate
326 /// what the load does.
328 int &FrameIndex,
329 TypeSize &MemBytes) const {
330 MemBytes = TypeSize::getZero();
331 return isLoadFromStackSlot(MI, FrameIndex);
332 }
333
334 /// Check for post-frame ptr elimination stack locations as well.
335 /// This uses a heuristic so it isn't reliable for correctness.
337 int &FrameIndex) const {
338 return 0;
339 }
340
341 /// If the specified machine instruction has a load from a stack slot,
342 /// return true along with the FrameIndices of the loaded stack slot and the
343 /// machine mem operands containing the reference.
344 /// If not, return false. Unlike isLoadFromStackSlot, this returns true for
345 /// any instructions that loads from the stack. This is just a hint, as some
346 /// cases may be missed.
347 virtual bool hasLoadFromStackSlot(
348 const MachineInstr &MI,
350
351 /// If the specified machine instruction is a direct
352 /// store to a stack slot, return the virtual or physical register number of
353 /// the source reg along with the FrameIndex of the loaded stack slot. If
354 /// not, return 0. This predicate must return 0 if the instruction has
355 /// any side effects other than storing to the stack slot.
357 int &FrameIndex) const {
358 return 0;
359 }
360
361 /// Optional extension of isStoreToStackSlot that returns the number of
362 /// bytes stored to the stack. This must be implemented if a backend
363 /// supports partial stack slot spills/loads to further disambiguate
364 /// what the store does.
366 int &FrameIndex,
367 TypeSize &MemBytes) const {
368 MemBytes = TypeSize::getZero();
369 return isStoreToStackSlot(MI, FrameIndex);
370 }
371
372 /// Check for post-frame ptr elimination stack locations as well.
373 /// This uses a heuristic, so it isn't reliable for correctness.
375 int &FrameIndex) const {
376 return 0;
377 }
378
379 /// If the specified machine instruction has a store to a stack slot,
380 /// return true along with the FrameIndices of the loaded stack slot and the
381 /// machine mem operands containing the reference.
382 /// If not, return false. Unlike isStoreToStackSlot,
383 /// this returns true for any instructions that stores to the
384 /// stack. This is just a hint, as some cases may be missed.
385 virtual bool hasStoreToStackSlot(
386 const MachineInstr &MI,
388
389 /// Return true if the specified machine instruction
390 /// is a copy of one stack slot to another and has no other effect.
391 /// Provide the identity of the two frame indices.
392 virtual bool isStackSlotCopy(const MachineInstr &MI, int &DestFrameIndex,
393 int &SrcFrameIndex) const {
394 return false;
395 }
396
397 /// Compute the size in bytes and offset within a stack slot of a spilled
398 /// register or subregister.
399 ///
400 /// \param [out] Size in bytes of the spilled value.
401 /// \param [out] Offset in bytes within the stack slot.
402 /// \returns true if both Size and Offset are successfully computed.
403 ///
404 /// Not all subregisters have computable spill slots. For example,
405 /// subregisters registers may not be byte-sized, and a pair of discontiguous
406 /// subregisters has no single offset.
407 ///
408 /// Targets with nontrivial bigendian implementations may need to override
409 /// this, particularly to support spilled vector registers.
410 virtual bool getStackSlotRange(const TargetRegisterClass *RC, unsigned SubIdx,
411 unsigned &Size, unsigned &Offset,
412 const MachineFunction &MF) const;
413
414 /// Return true if the given instruction is terminator that is unspillable,
415 /// according to isUnspillableTerminatorImpl.
417 return MI->isTerminator() && isUnspillableTerminatorImpl(MI);
418 }
419
420 /// Returns the size in bytes of the specified MachineInstr, or ~0U
421 /// when this function is not implemented by a target.
422 virtual unsigned getInstSizeInBytes(const MachineInstr &MI) const {
423 return ~0U;
424 }
425
426 /// Return true if the instruction is as cheap as a move instruction.
427 ///
428 /// Targets for different archs need to override this, and different
429 /// micro-architectures can also be finely tuned inside.
430 virtual bool isAsCheapAsAMove(const MachineInstr &MI) const {
431 return MI.isAsCheapAsAMove();
432 }
433
434 /// Return true if the instruction should be sunk by MachineSink.
435 ///
436 /// MachineSink determines on its own whether the instruction is safe to sink;
437 /// this gives the target a hook to override the default behavior with regards
438 /// to which instructions should be sunk.
439 virtual bool shouldSink(const MachineInstr &MI) const { return true; }
440
441 /// Return false if the instruction should not be hoisted by MachineLICM.
442 ///
443 /// MachineLICM determines on its own whether the instruction is safe to
444 /// hoist; this gives the target a hook to extend this assessment and prevent
445 /// an instruction being hoisted from a given loop for target specific
446 /// reasons.
447 virtual bool shouldHoist(const MachineInstr &MI,
448 const MachineLoop *FromLoop) const {
449 return true;
450 }
451
452 /// Re-issue the specified 'original' instruction at the
453 /// specific location targeting a new destination register.
454 /// The register in Orig->getOperand(0).getReg() will be substituted by
455 /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
456 /// SubIdx.
457 virtual void reMaterialize(MachineBasicBlock &MBB,
459 unsigned SubIdx, const MachineInstr &Orig,
460 const TargetRegisterInfo &TRI) const;
461
462 /// Clones instruction or the whole instruction bundle \p Orig and
463 /// insert into \p MBB before \p InsertBefore. The target may update operands
464 /// that are required to be unique.
465 ///
466 /// \p Orig must not return true for MachineInstr::isNotDuplicable().
467 virtual MachineInstr &duplicate(MachineBasicBlock &MBB,
468 MachineBasicBlock::iterator InsertBefore,
469 const MachineInstr &Orig) const;
470
471 /// This method must be implemented by targets that
472 /// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
473 /// may be able to convert a two-address instruction into one or more true
474 /// three-address instructions on demand. This allows the X86 target (for
475 /// example) to convert ADD and SHL instructions into LEA instructions if they
476 /// would require register copies due to two-addressness.
477 ///
478 /// This method returns a null pointer if the transformation cannot be
479 /// performed, otherwise it returns the last new instruction.
480 ///
481 /// If \p LIS is not nullptr, the LiveIntervals info should be updated for
482 /// replacing \p MI with new instructions, even though this function does not
483 /// remove MI.
485 LiveVariables *LV,
486 LiveIntervals *LIS) const {
487 return nullptr;
488 }
489
490 // This constant can be used as an input value of operand index passed to
491 // the method findCommutedOpIndices() to tell the method that the
492 // corresponding operand index is not pre-defined and that the method
493 // can pick any commutable operand.
494 static const unsigned CommuteAnyOperandIndex = ~0U;
495
496 /// This method commutes the operands of the given machine instruction MI.
497 ///
498 /// The operands to be commuted are specified by their indices OpIdx1 and
499 /// OpIdx2. OpIdx1 and OpIdx2 arguments may be set to a special value
500 /// 'CommuteAnyOperandIndex', which means that the method is free to choose
501 /// any arbitrarily chosen commutable operand. If both arguments are set to
502 /// 'CommuteAnyOperandIndex' then the method looks for 2 different commutable
503 /// operands; then commutes them if such operands could be found.
504 ///
505 /// If NewMI is false, MI is modified in place and returned; otherwise, a
506 /// new machine instruction is created and returned.
507 ///
508 /// Do not call this method for a non-commutable instruction or
509 /// for non-commuable operands.
510 /// Even though the instruction is commutable, the method may still
511 /// fail to commute the operands, null pointer is returned in such cases.
513 commuteInstruction(MachineInstr &MI, bool NewMI = false,
514 unsigned OpIdx1 = CommuteAnyOperandIndex,
515 unsigned OpIdx2 = CommuteAnyOperandIndex) const;
516
517 /// Returns true iff the routine could find two commutable operands in the
518 /// given machine instruction.
519 /// The 'SrcOpIdx1' and 'SrcOpIdx2' are INPUT and OUTPUT arguments.
520 /// If any of the INPUT values is set to the special value
521 /// 'CommuteAnyOperandIndex' then the method arbitrarily picks a commutable
522 /// operand, then returns its index in the corresponding argument.
523 /// If both of INPUT values are set to 'CommuteAnyOperandIndex' then method
524 /// looks for 2 commutable operands.
525 /// If INPUT values refer to some operands of MI, then the method simply
526 /// returns true if the corresponding operands are commutable and returns
527 /// false otherwise.
528 ///
529 /// For example, calling this method this way:
530 /// unsigned Op1 = 1, Op2 = CommuteAnyOperandIndex;
531 /// findCommutedOpIndices(MI, Op1, Op2);
532 /// can be interpreted as a query asking to find an operand that would be
533 /// commutable with the operand#1.
534 virtual bool findCommutedOpIndices(const MachineInstr &MI,
535 unsigned &SrcOpIdx1,
536 unsigned &SrcOpIdx2) const;
537
538 /// Returns true if the target has a preference on the operands order of
539 /// the given machine instruction. And specify if \p Commute is required to
540 /// get the desired operands order.
541 virtual bool hasCommutePreference(MachineInstr &MI, bool &Commute) const {
542 return false;
543 }
544
545 /// If possible, converts the instruction to a simplified/canonical form.
546 /// Returns true if the instruction was modified.
547 ///
548 /// This function is only called after register allocation. The MI will be
549 /// modified in place. This is called by passes such as
550 /// MachineCopyPropagation, where their mutation of the MI operands may
551 /// expose opportunities to convert the instruction to a simpler form (e.g.
552 /// a load of 0).
553 virtual bool simplifyInstruction(MachineInstr &MI) const { return false; }
554
555 /// A pair composed of a register and a sub-register index.
556 /// Used to give some type checking when modeling Reg:SubReg.
559 unsigned SubReg;
560
562 : Reg(Reg), SubReg(SubReg) {}
563
564 bool operator==(const RegSubRegPair& P) const {
565 return Reg == P.Reg && SubReg == P.SubReg;
566 }
567 bool operator!=(const RegSubRegPair& P) const {
568 return !(*this == P);
569 }
570 };
571
572 /// A pair composed of a pair of a register and a sub-register index,
573 /// and another sub-register index.
574 /// Used to give some type checking when modeling Reg:SubReg1, SubReg2.
576 unsigned SubIdx;
577
579 unsigned SubIdx = 0)
581 };
582
583 /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
584 /// and \p DefIdx.
585 /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
586 /// the list is modeled as <Reg:SubReg, SubIdx>. Operands with the undef
587 /// flag are not added to this list.
588 /// E.g., REG_SEQUENCE %1:sub1, sub0, %2, sub1 would produce
589 /// two elements:
590 /// - %1:sub1, sub0
591 /// - %2<:0>, sub1
592 ///
593 /// \returns true if it is possible to build such an input sequence
594 /// with the pair \p MI, \p DefIdx. False otherwise.
595 ///
596 /// \pre MI.isRegSequence() or MI.isRegSequenceLike().
597 ///
598 /// \note The generic implementation does not provide any support for
599 /// MI.isRegSequenceLike(). In other words, one has to override
600 /// getRegSequenceLikeInputs for target specific instructions.
601 bool
602 getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx,
603 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const;
604
605 /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
606 /// and \p DefIdx.
607 /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
608 /// E.g., EXTRACT_SUBREG %1:sub1, sub0, sub1 would produce:
609 /// - %1:sub1, sub0
610 ///
611 /// \returns true if it is possible to build such an input sequence
612 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
613 /// False otherwise.
614 ///
615 /// \pre MI.isExtractSubreg() or MI.isExtractSubregLike().
616 ///
617 /// \note The generic implementation does not provide any support for
618 /// MI.isExtractSubregLike(). In other words, one has to override
619 /// getExtractSubregLikeInputs for target specific instructions.
620 bool getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx,
621 RegSubRegPairAndIdx &InputReg) const;
622
623 /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
624 /// and \p DefIdx.
625 /// \p [out] BaseReg and \p [out] InsertedReg contain
626 /// the equivalent inputs of INSERT_SUBREG.
627 /// E.g., INSERT_SUBREG %0:sub0, %1:sub1, sub3 would produce:
628 /// - BaseReg: %0:sub0
629 /// - InsertedReg: %1:sub1, sub3
630 ///
631 /// \returns true if it is possible to build such an input sequence
632 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
633 /// False otherwise.
634 ///
635 /// \pre MI.isInsertSubreg() or MI.isInsertSubregLike().
636 ///
637 /// \note The generic implementation does not provide any support for
638 /// MI.isInsertSubregLike(). In other words, one has to override
639 /// getInsertSubregLikeInputs for target specific instructions.
640 bool getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx,
641 RegSubRegPair &BaseReg,
642 RegSubRegPairAndIdx &InsertedReg) const;
643
644 /// Return true if two machine instructions would produce identical values.
645 /// By default, this is only true when the two instructions
646 /// are deemed identical except for defs. If this function is called when the
647 /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
648 /// aggressive checks.
649 virtual bool produceSameValue(const MachineInstr &MI0,
650 const MachineInstr &MI1,
651 const MachineRegisterInfo *MRI = nullptr) const;
652
653 /// \returns true if a branch from an instruction with opcode \p BranchOpc
654 /// bytes is capable of jumping to a position \p BrOffset bytes away.
655 virtual bool isBranchOffsetInRange(unsigned BranchOpc,
656 int64_t BrOffset) const {
657 llvm_unreachable("target did not implement");
658 }
659
660 /// \returns The block that branch instruction \p MI jumps to.
662 llvm_unreachable("target did not implement");
663 }
664
665 /// Insert an unconditional indirect branch at the end of \p MBB to \p
666 /// NewDestBB. Optionally, insert the clobbered register restoring in \p
667 /// RestoreBB. \p BrOffset indicates the offset of \p NewDestBB relative to
668 /// the offset of the position to insert the new branch.
670 MachineBasicBlock &NewDestBB,
671 MachineBasicBlock &RestoreBB,
672 const DebugLoc &DL, int64_t BrOffset = 0,
673 RegScavenger *RS = nullptr) const {
674 llvm_unreachable("target did not implement");
675 }
676
677 /// Analyze the branching code at the end of MBB, returning
678 /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
679 /// implemented for a target). Upon success, this returns false and returns
680 /// with the following information in various cases:
681 ///
682 /// 1. If this block ends with no branches (it just falls through to its succ)
683 /// just return false, leaving TBB/FBB null.
684 /// 2. If this block ends with only an unconditional branch, it sets TBB to be
685 /// the destination block.
686 /// 3. If this block ends with a conditional branch and it falls through to a
687 /// successor block, it sets TBB to be the branch destination block and a
688 /// list of operands that evaluate the condition. These operands can be
689 /// passed to other TargetInstrInfo methods to create new branches.
690 /// 4. If this block ends with a conditional branch followed by an
691 /// unconditional branch, it returns the 'true' destination in TBB, the
692 /// 'false' destination in FBB, and a list of operands that evaluate the
693 /// condition. These operands can be passed to other TargetInstrInfo
694 /// methods to create new branches.
695 ///
696 /// Note that removeBranch and insertBranch must be implemented to support
697 /// cases where this method returns success.
698 ///
699 /// If AllowModify is true, then this routine is allowed to modify the basic
700 /// block (e.g. delete instructions after the unconditional branch).
701 ///
702 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
703 /// before calling this function.
705 MachineBasicBlock *&FBB,
707 bool AllowModify = false) const {
708 return true;
709 }
710
711 /// Represents a predicate at the MachineFunction level. The control flow a
712 /// MachineBranchPredicate represents is:
713 ///
714 /// Reg = LHS `Predicate` RHS == ConditionDef
715 /// if Reg then goto TrueDest else goto FalseDest
716 ///
719 PRED_EQ, // True if two values are equal
720 PRED_NE, // True if two values are not equal
721 PRED_INVALID // Sentinel value
722 };
723
730
731 /// SingleUseCondition is true if ConditionDef is dead except for the
732 /// branch(es) at the end of the basic block.
733 ///
734 bool SingleUseCondition = false;
735
736 explicit MachineBranchPredicate() = default;
737 };
738
739 /// Analyze the branching code at the end of MBB and parse it into the
740 /// MachineBranchPredicate structure if possible. Returns false on success
741 /// and true on failure.
742 ///
743 /// If AllowModify is true, then this routine is allowed to modify the basic
744 /// block (e.g. delete instructions after the unconditional branch).
745 ///
748 bool AllowModify = false) const {
749 return true;
750 }
751
752 /// Remove the branching code at the end of the specific MBB.
753 /// This is only invoked in cases where analyzeBranch returns success. It
754 /// returns the number of instructions that were removed.
755 /// If \p BytesRemoved is non-null, report the change in code size from the
756 /// removed instructions.
758 int *BytesRemoved = nullptr) const {
759 llvm_unreachable("Target didn't implement TargetInstrInfo::removeBranch!");
760 }
761
762 /// Insert branch code into the end of the specified MachineBasicBlock. The
763 /// operands to this method are the same as those returned by analyzeBranch.
764 /// This is only invoked in cases where analyzeBranch returns success. It
765 /// returns the number of instructions inserted. If \p BytesAdded is non-null,
766 /// report the change in code size from the added instructions.
767 ///
768 /// It is also invoked by tail merging to add unconditional branches in
769 /// cases where analyzeBranch doesn't apply because there was no original
770 /// branch to analyze. At least this much must be implemented, else tail
771 /// merging needs to be disabled.
772 ///
773 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
774 /// before calling this function.
778 const DebugLoc &DL,
779 int *BytesAdded = nullptr) const {
780 llvm_unreachable("Target didn't implement TargetInstrInfo::insertBranch!");
781 }
782
784 MachineBasicBlock *DestBB,
785 const DebugLoc &DL,
786 int *BytesAdded = nullptr) const {
787 return insertBranch(MBB, DestBB, nullptr, ArrayRef<MachineOperand>(), DL,
788 BytesAdded);
789 }
790
791 /// Object returned by analyzeLoopForPipelining. Allows software pipelining
792 /// implementations to query attributes of the loop being pipelined and to
793 /// apply target-specific updates to the loop once pipelining is complete.
795 public:
797 /// Return true if the given instruction should not be pipelined and should
798 /// be ignored. An example could be a loop comparison, or induction variable
799 /// update with no users being pipelined.
800 virtual bool shouldIgnoreForPipelining(const MachineInstr *MI) const = 0;
801
802 /// Return true if the proposed schedule should used. Otherwise return
803 /// false to not pipeline the loop. This function should be used to ensure
804 /// that pipelined loops meet target-specific quality heuristics.
806 return true;
807 }
808
809 /// Create a condition to determine if the trip count of the loop is greater
810 /// than TC, where TC is always one more than for the previous prologue or
811 /// 0 if this is being called for the outermost prologue.
812 ///
813 /// If the trip count is statically known to be greater than TC, return
814 /// true. If the trip count is statically known to be not greater than TC,
815 /// return false. Otherwise return nullopt and fill out Cond with the test
816 /// condition.
817 ///
818 /// Note: This hook is guaranteed to be called from the innermost to the
819 /// outermost prologue of the loop being software pipelined.
820 virtual std::optional<bool>
823
824 /// Create a condition to determine if the remaining trip count for a phase
825 /// is greater than TC. Some instructions such as comparisons may be
826 /// inserted at the bottom of MBB. All instructions expanded for the
827 /// phase must be inserted in MBB before calling this function.
828 /// LastStage0Insts is the map from the original instructions scheduled at
829 /// stage#0 to the expanded instructions for the last iteration of the
830 /// kernel. LastStage0Insts is intended to obtain the instruction that
831 /// refers the latest loop counter value.
832 ///
833 /// MBB can also be a predecessor of the prologue block. Then
834 /// LastStage0Insts must be empty and the compared value is the initial
835 /// value of the trip count.
840 "Target didn't implement "
841 "PipelinerLoopInfo::createRemainingIterationsGreaterCondition!");
842 }
843
844 /// Modify the loop such that the trip count is
845 /// OriginalTC + TripCountAdjust.
846 virtual void adjustTripCount(int TripCountAdjust) = 0;
847
848 /// Called when the loop's preheader has been modified to NewPreheader.
849 virtual void setPreheader(MachineBasicBlock *NewPreheader) = 0;
850
851 /// Called when the loop is being removed. Any instructions in the preheader
852 /// should be removed.
853 ///
854 /// Once this function is called, no other functions on this object are
855 /// valid; the loop has been removed.
856 virtual void disposed(LiveIntervals *LIS = nullptr) {}
857
858 /// Return true if the target can expand pipelined schedule with modulo
859 /// variable expansion.
860 virtual bool isMVEExpanderSupported() { return false; }
861 };
862
863 /// Analyze loop L, which must be a single-basic-block loop, and if the
864 /// conditions can be understood enough produce a PipelinerLoopInfo object.
865 virtual std::unique_ptr<PipelinerLoopInfo>
867 return nullptr;
868 }
869
870 /// Analyze the loop code, return true if it cannot be understood. Upon
871 /// success, this function returns false and returns information about the
872 /// induction variable and compare instruction used at the end.
873 virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst,
874 MachineInstr *&CmpInst) const {
875 return true;
876 }
877
878 /// Generate code to reduce the loop iteration by one and check if the loop
879 /// is finished. Return the value/register of the new loop count. We need
880 /// this function when peeling off one or more iterations of a loop. This
881 /// function assumes the nth iteration is peeled first.
883 MachineBasicBlock &PreHeader,
884 MachineInstr *IndVar, MachineInstr &Cmp,
887 unsigned Iter, unsigned MaxIter) const {
888 llvm_unreachable("Target didn't implement ReduceLoopCount");
889 }
890
891 /// Delete the instruction OldInst and everything after it, replacing it with
892 /// an unconditional branch to NewDest. This is used by the tail merging pass.
893 virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
894 MachineBasicBlock *NewDest) const;
895
896 /// Return true if it's legal to split the given basic
897 /// block at the specified instruction (i.e. instruction would be the start
898 /// of a new basic block).
901 return true;
902 }
903
904 /// Return true if it's profitable to predicate
905 /// instructions with accumulated instruction latency of "NumCycles"
906 /// of the specified basic block, where the probability of the instructions
907 /// being executed is given by Probability, and Confidence is a measure
908 /// of our confidence that it will be properly predicted.
909 virtual bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
910 unsigned ExtraPredCycles,
911 BranchProbability Probability) const {
912 return false;
913 }
914
915 /// Second variant of isProfitableToIfCvt. This one
916 /// checks for the case where two basic blocks from true and false path
917 /// of a if-then-else (diamond) are predicated on mutually exclusive
918 /// predicates, where the probability of the true path being taken is given
919 /// by Probability, and Confidence is a measure of our confidence that it
920 /// will be properly predicted.
921 virtual bool isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned NumTCycles,
922 unsigned ExtraTCycles,
923 MachineBasicBlock &FMBB, unsigned NumFCycles,
924 unsigned ExtraFCycles,
925 BranchProbability Probability) const {
926 return false;
927 }
928
929 /// Return true if it's profitable for if-converter to duplicate instructions
930 /// of specified accumulated instruction latencies in the specified MBB to
931 /// enable if-conversion.
932 /// The probability of the instructions being executed is given by
933 /// Probability, and Confidence is a measure of our confidence that it
934 /// will be properly predicted.
936 unsigned NumCycles,
937 BranchProbability Probability) const {
938 return false;
939 }
940
941 /// Return the increase in code size needed to predicate a contiguous run of
942 /// NumInsts instructions.
944 unsigned NumInsts) const {
945 return 0;
946 }
947
948 /// Return an estimate for the code size reduction (in bytes) which will be
949 /// caused by removing the given branch instruction during if-conversion.
950 virtual unsigned predictBranchSizeForIfCvt(MachineInstr &MI) const {
951 return getInstSizeInBytes(MI);
952 }
953
954 /// Return true if it's profitable to unpredicate
955 /// one side of a 'diamond', i.e. two sides of if-else predicated on mutually
956 /// exclusive predicates.
957 /// e.g.
958 /// subeq r0, r1, #1
959 /// addne r0, r1, #1
960 /// =>
961 /// sub r0, r1, #1
962 /// addne r0, r1, #1
963 ///
964 /// This may be profitable is conditional instructions are always executed.
966 MachineBasicBlock &FMBB) const {
967 return false;
968 }
969
970 /// Return true if it is possible to insert a select
971 /// instruction that chooses between TrueReg and FalseReg based on the
972 /// condition code in Cond.
973 ///
974 /// When successful, also return the latency in cycles from TrueReg,
975 /// FalseReg, and Cond to the destination register. In most cases, a select
976 /// instruction will be 1 cycle, so CondCycles = TrueCycles = FalseCycles = 1
977 ///
978 /// Some x86 implementations have 2-cycle cmov instructions.
979 ///
980 /// @param MBB Block where select instruction would be inserted.
981 /// @param Cond Condition returned by analyzeBranch.
982 /// @param DstReg Virtual dest register that the result should write to.
983 /// @param TrueReg Virtual register to select when Cond is true.
984 /// @param FalseReg Virtual register to select when Cond is false.
985 /// @param CondCycles Latency from Cond+Branch to select output.
986 /// @param TrueCycles Latency from TrueReg to select output.
987 /// @param FalseCycles Latency from FalseReg to select output.
990 Register TrueReg, Register FalseReg,
991 int &CondCycles, int &TrueCycles,
992 int &FalseCycles) const {
993 return false;
994 }
995
996 /// Insert a select instruction into MBB before I that will copy TrueReg to
997 /// DstReg when Cond is true, and FalseReg to DstReg when Cond is false.
998 ///
999 /// This function can only be called after canInsertSelect() returned true.
1000 /// The condition in Cond comes from analyzeBranch, and it can be assumed
1001 /// that the same flags or registers required by Cond are available at the
1002 /// insertion point.
1003 ///
1004 /// @param MBB Block where select instruction should be inserted.
1005 /// @param I Insertion point.
1006 /// @param DL Source location for debugging.
1007 /// @param DstReg Virtual register to be defined by select instruction.
1008 /// @param Cond Condition as computed by analyzeBranch.
1009 /// @param TrueReg Virtual register to copy when Cond is true.
1010 /// @param FalseReg Virtual register to copy when Cons is false.
1014 Register TrueReg, Register FalseReg) const {
1015 llvm_unreachable("Target didn't implement TargetInstrInfo::insertSelect!");
1016 }
1017
1018 /// Analyze the given select instruction, returning true if
1019 /// it cannot be understood. It is assumed that MI->isSelect() is true.
1020 ///
1021 /// When successful, return the controlling condition and the operands that
1022 /// determine the true and false result values.
1023 ///
1024 /// Result = SELECT Cond, TrueOp, FalseOp
1025 ///
1026 /// Some targets can optimize select instructions, for example by predicating
1027 /// the instruction defining one of the operands. Such targets should set
1028 /// Optimizable.
1029 ///
1030 /// @param MI Select instruction to analyze.
1031 /// @param Cond Condition controlling the select.
1032 /// @param TrueOp Operand number of the value selected when Cond is true.
1033 /// @param FalseOp Operand number of the value selected when Cond is false.
1034 /// @param Optimizable Returned as true if MI is optimizable.
1035 /// @returns False on success.
1036 virtual bool analyzeSelect(const MachineInstr &MI,
1038 unsigned &TrueOp, unsigned &FalseOp,
1039 bool &Optimizable) const {
1040 assert(MI.getDesc().isSelect() && "MI must be a select instruction");
1041 return true;
1042 }
1043
1044 /// Given a select instruction that was understood by
1045 /// analyzeSelect and returned Optimizable = true, attempt to optimize MI by
1046 /// merging it with one of its operands. Returns NULL on failure.
1047 ///
1048 /// When successful, returns the new select instruction. The client is
1049 /// responsible for deleting MI.
1050 ///
1051 /// If both sides of the select can be optimized, PreferFalse is used to pick
1052 /// a side.
1053 ///
1054 /// @param MI Optimizable select instruction.
1055 /// @param NewMIs Set that record all MIs in the basic block up to \p
1056 /// MI. Has to be updated with any newly created MI or deleted ones.
1057 /// @param PreferFalse Try to optimize FalseOp instead of TrueOp.
1058 /// @returns Optimized instruction or NULL.
1061 bool PreferFalse = false) const {
1062 // This function must be implemented if Optimizable is ever set.
1063 llvm_unreachable("Target must implement TargetInstrInfo::optimizeSelect!");
1064 }
1065
1066 /// Emit instructions to copy a pair of physical registers.
1067 ///
1068 /// This function should support copies within any legal register class as
1069 /// well as any cross-class copies created during instruction selection.
1070 ///
1071 /// The source and destination registers may overlap, which may require a
1072 /// careful implementation when multiple copy instructions are required for
1073 /// large registers. See for example the ARM target.
1074 ///
1075 /// If RenamableDest is true, the copy instruction's destination operand is
1076 /// marked renamable.
1077 /// If RenamableSrc is true, the copy instruction's source operand is
1078 /// marked renamable.
1081 Register DestReg, Register SrcReg, bool KillSrc,
1082 bool RenamableDest = false,
1083 bool RenamableSrc = false) const {
1084 llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg!");
1085 }
1086
1087 /// Allow targets to tell MachineVerifier whether a specific register
1088 /// MachineOperand can be used as part of PC-relative addressing.
1089 /// PC-relative addressing modes in many CISC architectures contain
1090 /// (non-PC) registers as offsets or scaling values, which inherently
1091 /// tags the corresponding MachineOperand with OPERAND_PCREL.
1092 ///
1093 /// @param MO The MachineOperand in question. MO.isReg() should always
1094 /// be true.
1095 /// @return Whether this operand is allowed to be used PC-relatively.
1096 virtual bool isPCRelRegisterOperandLegal(const MachineOperand &MO) const {
1097 return false;
1098 }
1099
1100 /// Return an index for MachineJumpTableInfo if \p insn is an indirect jump
1101 /// using a jump table, otherwise -1.
1102 virtual int getJumpTableIndex(const MachineInstr &MI) const { return -1; }
1103
1104protected:
1105 /// Target-dependent implementation for IsCopyInstr.
1106 /// If the specific machine instruction is a instruction that moves/copies
1107 /// value from one register to another register return destination and source
1108 /// registers as machine operands.
1109 virtual std::optional<DestSourcePair>
1111 return std::nullopt;
1112 }
1113
1114 virtual std::optional<DestSourcePair>
1116 return std::nullopt;
1117 }
1118
1119 /// Return true if the given terminator MI is not expected to spill. This
1120 /// sets the live interval as not spillable and adjusts phi node lowering to
1121 /// not introduce copies after the terminator. Use with care, these are
1122 /// currently used for hardware loop intrinsics in very controlled situations,
1123 /// created prior to registry allocation in loops that only have single phi
1124 /// users for the terminators value. They may run out of registers if not used
1125 /// carefully.
1126 virtual bool isUnspillableTerminatorImpl(const MachineInstr *MI) const {
1127 return false;
1128 }
1129
1130public:
1131 /// If the specific machine instruction is a instruction that moves/copies
1132 /// value from one register to another register return destination and source
1133 /// registers as machine operands.
1134 /// For COPY-instruction the method naturally returns destination and source
1135 /// registers as machine operands, for all other instructions the method calls
1136 /// target-dependent implementation.
1137 std::optional<DestSourcePair> isCopyInstr(const MachineInstr &MI) const {
1138 if (MI.isCopy()) {
1139 return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
1140 }
1141 return isCopyInstrImpl(MI);
1142 }
1143
1144 // Similar to `isCopyInstr`, but adds non-copy semantics on MIR, but
1145 // ultimately generates a copy instruction.
1146 std::optional<DestSourcePair> isCopyLikeInstr(const MachineInstr &MI) const {
1147 if (auto IsCopyInstr = isCopyInstr(MI))
1148 return IsCopyInstr;
1149 return isCopyLikeInstrImpl(MI);
1150 }
1151
1152 bool isFullCopyInstr(const MachineInstr &MI) const {
1153 auto DestSrc = isCopyInstr(MI);
1154 if (!DestSrc)
1155 return false;
1156
1157 const MachineOperand *DestRegOp = DestSrc->Destination;
1158 const MachineOperand *SrcRegOp = DestSrc->Source;
1159 return !DestRegOp->getSubReg() && !SrcRegOp->getSubReg();
1160 }
1161
1162 /// If the specific machine instruction is an instruction that adds an
1163 /// immediate value and a register, and stores the result in the given
1164 /// register \c Reg, return a pair of the source register and the offset
1165 /// which has been added.
1166 virtual std::optional<RegImmPair> isAddImmediate(const MachineInstr &MI,
1167 Register Reg) const {
1168 return std::nullopt;
1169 }
1170
1171 /// Returns true if MI is an instruction that defines Reg to have a constant
1172 /// value and the value is recorded in ImmVal. The ImmVal is a result that
1173 /// should be interpreted as modulo size of Reg.
1175 const Register Reg,
1176 int64_t &ImmVal) const {
1177 return false;
1178 }
1179
1180 /// Store the specified register of the given register class to the specified
1181 /// stack frame index. The store instruction is to be added to the given
1182 /// machine basic block before the specified machine instruction. If isKill
1183 /// is true, the register operand is the last use and must be marked kill. If
1184 /// \p SrcReg is being directly spilled as part of assigning a virtual
1185 /// register, \p VReg is the register being assigned. This additional register
1186 /// argument is needed for certain targets when invoked from RegAllocFast to
1187 /// map the spilled physical register to its virtual register. A null register
1188 /// can be passed elsewhere. The \p Flags is used to set appropriate machine
1189 /// flags on the spill instruction e.g. FrameSetup flag on a callee saved
1190 /// register spill instruction, part of prologue, during the frame lowering.
1193 bool isKill, int FrameIndex, const TargetRegisterClass *RC,
1194 const TargetRegisterInfo *TRI, Register VReg,
1196 llvm_unreachable("Target didn't implement "
1197 "TargetInstrInfo::storeRegToStackSlot!");
1198 }
1199
1200 /// Load the specified register of the given register class from the specified
1201 /// stack frame index. The load instruction is to be added to the given
1202 /// machine basic block before the specified machine instruction. If \p
1203 /// DestReg is being directly reloaded as part of assigning a virtual
1204 /// register, \p VReg is the register being assigned. This additional register
1205 /// argument is needed for certain targets when invoked from RegAllocFast to
1206 /// map the loaded physical register to its virtual register. A null register
1207 /// can be passed elsewhere. The \p Flags is used to set appropriate machine
1208 /// flags on the spill instruction e.g. FrameDestroy flag on a callee saved
1209 /// register reload instruction, part of epilogue, during the frame lowering.
1212 int FrameIndex, const TargetRegisterClass *RC,
1213 const TargetRegisterInfo *TRI, Register VReg,
1215 llvm_unreachable("Target didn't implement "
1216 "TargetInstrInfo::loadRegFromStackSlot!");
1217 }
1218
1219 /// This function is called for all pseudo instructions
1220 /// that remain after register allocation. Many pseudo instructions are
1221 /// created to help register allocation. This is the place to convert them
1222 /// into real instructions. The target can edit MI in place, or it can insert
1223 /// new instructions and erase MI. The function should return true if
1224 /// anything was changed.
1225 virtual bool expandPostRAPseudo(MachineInstr &MI) const { return false; }
1226
1227 /// Check whether the target can fold a load that feeds a subreg operand
1228 /// (or a subreg operand that feeds a store).
1229 /// For example, X86 may want to return true if it can fold
1230 /// movl (%esp), %eax
1231 /// subb, %al, ...
1232 /// Into:
1233 /// subb (%esp), ...
1234 ///
1235 /// Ideally, we'd like the target implementation of foldMemoryOperand() to
1236 /// reject subregs - but since this behavior used to be enforced in the
1237 /// target-independent code, moving this responsibility to the targets
1238 /// has the potential of causing nasty silent breakage in out-of-tree targets.
1239 virtual bool isSubregFoldable() const { return false; }
1240
1241 /// For a patchpoint, stackmap, or statepoint intrinsic, return the range of
1242 /// operands which can't be folded into stack references. Operands outside
1243 /// of the range are most likely foldable but it is not guaranteed.
1244 /// These instructions are unique in that stack references for some operands
1245 /// have the same execution cost (e.g. none) as the unfolded register forms.
1246 /// The ranged return is guaranteed to include all operands which can't be
1247 /// folded at zero cost.
1248 virtual std::pair<unsigned, unsigned>
1249 getPatchpointUnfoldableRange(const MachineInstr &MI) const;
1250
1251 /// Attempt to fold a load or store of the specified stack
1252 /// slot into the specified machine instruction for the specified operand(s).
1253 /// If this is possible, a new instruction is returned with the specified
1254 /// operand folded, otherwise NULL is returned.
1255 /// The new instruction is inserted before MI, and the client is responsible
1256 /// for removing the old instruction.
1257 /// If VRM is passed, the assigned physregs can be inspected by target to
1258 /// decide on using an opcode (note that those assignments can still change).
1259 MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
1260 int FI,
1261 LiveIntervals *LIS = nullptr,
1262 VirtRegMap *VRM = nullptr) const;
1263
1264 /// Same as the previous version except it allows folding of any load and
1265 /// store from / to any address, not just from a specific stack slot.
1266 MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
1267 MachineInstr &LoadMI,
1268 LiveIntervals *LIS = nullptr) const;
1269
1270 /// This function defines the logic to lower COPY instruction to
1271 /// target specific instruction(s).
1272 void lowerCopy(MachineInstr *MI, const TargetRegisterInfo *TRI) const;
1273
1274 /// Return true when there is potentially a faster code sequence
1275 /// for an instruction chain ending in \p Root. All potential patterns are
1276 /// returned in the \p Pattern vector. Pattern should be sorted in priority
1277 /// order since the pattern evaluator stops checking as soon as it finds a
1278 /// faster sequence.
1279 /// \param Root - Instruction that could be combined with one of its operands
1280 /// \param Patterns - Vector of possible combination patterns
1281 virtual bool getMachineCombinerPatterns(MachineInstr &Root,
1282 SmallVectorImpl<unsigned> &Patterns,
1283 bool DoRegPressureReduce) const;
1284
1285 /// Return true if target supports reassociation of instructions in machine
1286 /// combiner pass to reduce register pressure for a given BB.
1287 virtual bool
1289 const RegisterClassInfo *RegClassInfo) const {
1290 return false;
1291 }
1292
1293 /// Fix up the placeholder we may add in genAlternativeCodeSequence().
1294 virtual void
1296 SmallVectorImpl<MachineInstr *> &InsInstrs) const {}
1297
1298 /// Return true when a code sequence can improve throughput. It
1299 /// should be called only for instructions in loops.
1300 /// \param Pattern - combiner pattern
1301 virtual bool isThroughputPattern(unsigned Pattern) const;
1302
1303 /// Return the objective of a combiner pattern.
1304 /// \param Pattern - combiner pattern
1305 virtual CombinerObjective getCombinerObjective(unsigned Pattern) const;
1306
1307 /// Return true if the input \P Inst is part of a chain of dependent ops
1308 /// that are suitable for reassociation, otherwise return false.
1309 /// If the instruction's operands must be commuted to have a previous
1310 /// instruction of the same type define the first source operand, \P Commuted
1311 /// will be set to true.
1312 bool isReassociationCandidate(const MachineInstr &Inst, bool &Commuted) const;
1313
1314 /// Return true when \P Inst is both associative and commutative. If \P Invert
1315 /// is true, then the inverse of \P Inst operation must be tested.
1317 bool Invert = false) const {
1318 return false;
1319 }
1320
1321 /// Find chains of accumulations that can be rewritten as a tree for increased
1322 /// ILP.
1323 bool getAccumulatorReassociationPatterns(
1324 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns) const;
1325
1326 /// Find the chain of accumulator instructions in \P MBB and return them in
1327 /// \P Chain.
1328 void getAccumulatorChain(MachineInstr *CurrentInstr,
1329 SmallVectorImpl<Register> &Chain) const;
1330
1331 /// Return true when \P OpCode is an instruction which performs
1332 /// accumulation into one of its operand registers.
1333 virtual bool isAccumulationOpcode(unsigned Opcode) const { return false; }
1334
1335 /// Returns an opcode which defines the accumulator used by \P Opcode.
1336 virtual unsigned getAccumulationStartOpcode(unsigned Opcode) const {
1337 llvm_unreachable("Function not implemented for target!");
1338 return 0;
1339 }
1340
1341 /// Returns the opcode that should be use to reduce accumulation registers.
1342 virtual unsigned
1343 getReduceOpcodeForAccumulator(unsigned int AccumulatorOpCode) const {
1344 llvm_unreachable("Function not implemented for target!");
1345 return 0;
1346 }
1347
1348 /// Reduces branches of the accumulator tree into a single register.
1349 void reduceAccumulatorTree(SmallVectorImpl<Register> &RegistersToReduce,
1351 MachineFunction &MF, MachineInstr &Root,
1353 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
1354 Register ResultReg) const;
1355
1356 /// Return the inverse operation opcode if it exists for \P Opcode (e.g. add
1357 /// for sub and vice versa).
1358 virtual std::optional<unsigned> getInverseOpcode(unsigned Opcode) const {
1359 return std::nullopt;
1360 }
1361
1362 /// Return true when \P Opcode1 or its inversion is equal to \P Opcode2.
1363 bool areOpcodesEqualOrInverse(unsigned Opcode1, unsigned Opcode2) const;
1364
1365 /// Return true when \P Inst has reassociable operands in the same \P MBB.
1366 virtual bool hasReassociableOperands(const MachineInstr &Inst,
1367 const MachineBasicBlock *MBB) const;
1368
1369 /// Return true when \P Inst has reassociable sibling.
1370 virtual bool hasReassociableSibling(const MachineInstr &Inst,
1371 bool &Commuted) const;
1372
1373 /// When getMachineCombinerPatterns() finds patterns, this function generates
1374 /// the instructions that could replace the original code sequence. The client
1375 /// has to decide whether the actual replacement is beneficial or not.
1376 /// \param Root - Instruction that could be combined with one of its operands
1377 /// \param Pattern - Combination pattern for Root
1378 /// \param InsInstrs - Vector of new instructions that implement P
1379 /// \param DelInstrs - Old instructions, including Root, that could be
1380 /// replaced by InsInstr
1381 /// \param InstIdxForVirtReg - map of virtual register to instruction in
1382 /// InsInstr that defines it
1383 virtual void genAlternativeCodeSequence(
1384 MachineInstr &Root, unsigned Pattern,
1387 DenseMap<Register, unsigned> &InstIdxForVirtReg) const;
1388
1389 /// When calculate the latency of the root instruction, accumulate the
1390 /// latency of the sequence to the root latency.
1391 /// \param Root - Instruction that could be combined with one of its operands
1393 return true;
1394 }
1395
1396 /// The returned array encodes the operand index for each parameter because
1397 /// the operands may be commuted; the operand indices for associative
1398 /// operations might also be target-specific. Each element specifies the index
1399 /// of {Prev, A, B, X, Y}.
1400 virtual void
1401 getReassociateOperandIndices(const MachineInstr &Root, unsigned Pattern,
1402 std::array<unsigned, 5> &OperandIndices) const;
1403
1404 /// Attempt to reassociate \P Root and \P Prev according to \P Pattern to
1405 /// reduce critical path length.
1406 void reassociateOps(MachineInstr &Root, MachineInstr &Prev, unsigned Pattern,
1410 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const;
1411
1412 /// Reassociation of some instructions requires inverse operations (e.g.
1413 /// (X + A) - Y => (X - Y) + A). This method returns a pair of new opcodes
1414 /// (new root opcode, new prev opcode) that must be used to reassociate \P
1415 /// Root and \P Prev accoring to \P Pattern.
1416 std::pair<unsigned, unsigned>
1417 getReassociationOpcodes(unsigned Pattern, const MachineInstr &Root,
1418 const MachineInstr &Prev) const;
1419
1420 /// The limit on resource length extension we accept in MachineCombiner Pass.
1421 virtual int getExtendResourceLenLimit() const { return 0; }
1422
1423 /// This is an architecture-specific helper function of reassociateOps.
1424 /// Set special operand attributes for new instructions after reassociation.
1425 virtual void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2,
1426 MachineInstr &NewMI1,
1427 MachineInstr &NewMI2) const {}
1428
1429 /// Return true when a target supports MachineCombiner.
1430 virtual bool useMachineCombiner() const { return false; }
1431
1432 /// Return a strategy that MachineCombiner must use when creating traces.
1433 virtual MachineTraceStrategy getMachineCombinerTraceStrategy() const;
1434
1435 /// Return true if the given SDNode can be copied during scheduling
1436 /// even if it has glue.
1437 virtual bool canCopyGluedNodeDuringSchedule(SDNode *N) const { return false; }
1438
1439protected:
1440 /// Target-dependent implementation for foldMemoryOperand.
1441 /// Target-independent code in foldMemoryOperand will
1442 /// take care of adding a MachineMemOperand to the newly created instruction.
1443 /// The instruction and any auxiliary instructions necessary will be inserted
1444 /// at InsertPt.
1445 virtual MachineInstr *
1448 MachineBasicBlock::iterator InsertPt, int FrameIndex,
1449 LiveIntervals *LIS = nullptr,
1450 VirtRegMap *VRM = nullptr) const {
1451 return nullptr;
1452 }
1453
1454 /// Target-dependent implementation for foldMemoryOperand.
1455 /// Target-independent code in foldMemoryOperand will
1456 /// take care of adding a MachineMemOperand to the newly created instruction.
1457 /// The instruction and any auxiliary instructions necessary will be inserted
1458 /// at InsertPt.
1461 MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI,
1462 LiveIntervals *LIS = nullptr) const {
1463 return nullptr;
1464 }
1465
1466 /// Target-dependent implementation of getRegSequenceInputs.
1467 ///
1468 /// \returns true if it is possible to build the equivalent
1469 /// REG_SEQUENCE inputs with the pair \p MI, \p DefIdx. False otherwise.
1470 ///
1471 /// \pre MI.isRegSequenceLike().
1472 ///
1473 /// \see TargetInstrInfo::getRegSequenceInputs.
1475 const MachineInstr &MI, unsigned DefIdx,
1476 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
1477 return false;
1478 }
1479
1480 /// Target-dependent implementation of getExtractSubregInputs.
1481 ///
1482 /// \returns true if it is possible to build the equivalent
1483 /// EXTRACT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
1484 ///
1485 /// \pre MI.isExtractSubregLike().
1486 ///
1487 /// \see TargetInstrInfo::getExtractSubregInputs.
1489 unsigned DefIdx,
1490 RegSubRegPairAndIdx &InputReg) const {
1491 return false;
1492 }
1493
1494 /// Target-dependent implementation of getInsertSubregInputs.
1495 ///
1496 /// \returns true if it is possible to build the equivalent
1497 /// INSERT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
1498 ///
1499 /// \pre MI.isInsertSubregLike().
1500 ///
1501 /// \see TargetInstrInfo::getInsertSubregInputs.
1502 virtual bool
1504 RegSubRegPair &BaseReg,
1505 RegSubRegPairAndIdx &InsertedReg) const {
1506 return false;
1507 }
1508
1509public:
1510 /// unfoldMemoryOperand - Separate a single instruction which folded a load or
1511 /// a store or a load and a store into two or more instruction. If this is
1512 /// possible, returns true as well as the new instructions by reference.
1513 virtual bool
1515 bool UnfoldLoad, bool UnfoldStore,
1516 SmallVectorImpl<MachineInstr *> &NewMIs) const {
1517 return false;
1518 }
1519
1521 SmallVectorImpl<SDNode *> &NewNodes) const {
1522 return false;
1523 }
1524
1525 /// Returns the opcode of the would be new
1526 /// instruction after load / store are unfolded from an instruction of the
1527 /// specified opcode. It returns zero if the specified unfolding is not
1528 /// possible. If LoadRegIndex is non-null, it is filled in with the operand
1529 /// index of the operand which will hold the register holding the loaded
1530 /// value.
1531 virtual unsigned
1532 getOpcodeAfterMemoryUnfold(unsigned Opc, bool UnfoldLoad, bool UnfoldStore,
1533 unsigned *LoadRegIndex = nullptr) const {
1534 return 0;
1535 }
1536
1537 /// This is used by the pre-regalloc scheduler to determine if two loads are
1538 /// loading from the same base address. It should only return true if the base
1539 /// pointers are the same and the only differences between the two addresses
1540 /// are the offset. It also returns the offsets by reference.
1541 virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1542 int64_t &Offset1,
1543 int64_t &Offset2) const {
1544 return false;
1545 }
1546
1547 /// This is a used by the pre-regalloc scheduler to determine (in conjunction
1548 /// with areLoadsFromSameBasePtr) if two loads should be scheduled together.
1549 /// On some targets if two loads are loading from
1550 /// addresses in the same cache line, it's better if they are scheduled
1551 /// together. This function takes two integers that represent the load offsets
1552 /// from the common base address. It returns true if it decides it's desirable
1553 /// to schedule the two loads together. "NumLoads" is the number of loads that
1554 /// have already been scheduled after Load1.
1555 virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1556 int64_t Offset1, int64_t Offset2,
1557 unsigned NumLoads) const {
1558 return false;
1559 }
1560
1561 /// Get the base operand and byte offset of an instruction that reads/writes
1562 /// memory. This is a convenience function for callers that are only prepared
1563 /// to handle a single base operand.
1564 /// FIXME: Move Offset and OffsetIsScalable to some ElementCount-style
1565 /// abstraction that supports negative offsets.
1566 bool getMemOperandWithOffset(const MachineInstr &MI,
1567 const MachineOperand *&BaseOp, int64_t &Offset,
1568 bool &OffsetIsScalable,
1569 const TargetRegisterInfo *TRI) const;
1570
1571 /// Get zero or more base operands and the byte offset of an instruction that
1572 /// reads/writes memory. Note that there may be zero base operands if the
1573 /// instruction accesses a constant address.
1574 /// It returns false if MI does not read/write memory.
1575 /// It returns false if base operands and offset could not be determined.
1576 /// It is not guaranteed to always recognize base operands and offsets in all
1577 /// cases.
1578 /// FIXME: Move Offset and OffsetIsScalable to some ElementCount-style
1579 /// abstraction that supports negative offsets.
1582 int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width,
1583 const TargetRegisterInfo *TRI) const {
1584 return false;
1585 }
1586
1587 /// Return true if the instruction contains a base register and offset. If
1588 /// true, the function also sets the operand position in the instruction
1589 /// for the base register and offset.
1591 unsigned &BasePos,
1592 unsigned &OffsetPos) const {
1593 return false;
1594 }
1595
1596 /// Target dependent implementation to get the values constituting the address
1597 /// MachineInstr that is accessing memory. These values are returned as a
1598 /// struct ExtAddrMode which contains all relevant information to make up the
1599 /// address.
1600 virtual std::optional<ExtAddrMode>
1602 const TargetRegisterInfo *TRI) const {
1603 return std::nullopt;
1604 }
1605
1606 /// Check if it's possible and beneficial to fold the addressing computation
1607 /// `AddrI` into the addressing mode of the load/store instruction `MemI`. The
1608 /// memory instruction is a user of the virtual register `Reg`, which in turn
1609 /// is the ultimate destination of zero or more COPY instructions from the
1610 /// output register of `AddrI`.
1611 /// Return the adddressing mode after folding in `AM`.
1613 const MachineInstr &AddrI,
1614 ExtAddrMode &AM) const {
1615 return false;
1616 }
1617
1618 /// Emit a load/store instruction with the same value register as `MemI`, but
1619 /// using the address from `AM`. The addressing mode must have been obtained
1620 /// from `canFoldIntoAddr` for the same memory instruction.
1622 const ExtAddrMode &AM) const {
1623 llvm_unreachable("target did not implement emitLdStWithAddr()");
1624 }
1625
1626 /// Returns true if MI's Def is NullValueReg, and the MI
1627 /// does not change the Zero value. i.e. cases such as rax = shr rax, X where
1628 /// NullValueReg = rax. Note that if the NullValueReg is non-zero, this
1629 /// function can return true even if becomes zero. Specifically cases such as
1630 /// NullValueReg = shl NullValueReg, 63.
1632 const Register NullValueReg,
1633 const TargetRegisterInfo *TRI) const {
1634 return false;
1635 }
1636
1637 /// If the instruction is an increment of a constant value, return the amount.
1638 virtual bool getIncrementValue(const MachineInstr &MI, int &Value) const {
1639 return false;
1640 }
1641
1642 /// Returns true if the two given memory operations should be scheduled
1643 /// adjacent. Note that you have to add:
1644 /// DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
1645 /// or
1646 /// DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
1647 /// to TargetMachine::createMachineScheduler() to have an effect.
1648 ///
1649 /// \p BaseOps1 and \p BaseOps2 are memory operands of two memory operations.
1650 /// \p Offset1 and \p Offset2 are the byte offsets for the memory
1651 /// operations.
1652 /// \p OffsetIsScalable1 and \p OffsetIsScalable2 indicate if the offset is
1653 /// scaled by a runtime quantity.
1654 /// \p ClusterSize is the number of operations in the resulting load/store
1655 /// cluster if this hook returns true.
1656 /// \p NumBytes is the number of bytes that will be loaded from all the
1657 /// clustered loads if this hook returns true.
1659 int64_t Offset1, bool OffsetIsScalable1,
1661 int64_t Offset2, bool OffsetIsScalable2,
1662 unsigned ClusterSize,
1663 unsigned NumBytes) const {
1664 llvm_unreachable("target did not implement shouldClusterMemOps()");
1665 }
1666
1667 /// Reverses the branch condition of the specified condition list,
1668 /// returning false on success and true if it cannot be reversed.
1669 virtual bool
1673
1674 /// Insert a noop into the instruction stream at the specified point.
1675 virtual void insertNoop(MachineBasicBlock &MBB,
1677
1678 /// Insert noops into the instruction stream at the specified point.
1679 virtual void insertNoops(MachineBasicBlock &MBB,
1681 unsigned Quantity) const;
1682
1683 /// Return the noop instruction to use for a noop.
1684 virtual MCInst getNop() const;
1685
1686 /// Return true for post-incremented instructions.
1687 virtual bool isPostIncrement(const MachineInstr &MI) const { return false; }
1688
1689 /// Returns true if the instruction is already predicated.
1690 virtual bool isPredicated(const MachineInstr &MI) const { return false; }
1691
1692 /// Assumes the instruction is already predicated and returns true if the
1693 /// instruction can be predicated again.
1694 virtual bool canPredicatePredicatedInstr(const MachineInstr &MI) const {
1695 assert(isPredicated(MI) && "Instruction is not predicated");
1696 return false;
1697 }
1698
1699 // Returns a MIRPrinter comment for this machine operand.
1700 virtual std::string
1701 createMIROperandComment(const MachineInstr &MI, const MachineOperand &Op,
1702 unsigned OpIdx, const TargetRegisterInfo *TRI) const;
1703
1704 /// Returns true if the instruction is a
1705 /// terminator instruction that has not been predicated.
1706 bool isUnpredicatedTerminator(const MachineInstr &MI) const;
1707
1708 /// Returns true if MI is an unconditional tail call.
1709 virtual bool isUnconditionalTailCall(const MachineInstr &MI) const {
1710 return false;
1711 }
1712
1713 /// Returns true if the tail call can be made conditional on BranchCond.
1715 const MachineInstr &TailCall) const {
1716 return false;
1717 }
1718
1719 /// Replace the conditional branch in MBB with a conditional tail call.
1722 const MachineInstr &TailCall) const {
1723 llvm_unreachable("Target didn't implement replaceBranchWithTailCall!");
1724 }
1725
1726 /// Convert the instruction into a predicated instruction.
1727 /// It returns true if the operation was successful.
1728 virtual bool PredicateInstruction(MachineInstr &MI,
1729 ArrayRef<MachineOperand> Pred) const;
1730
1731 /// Returns true if the first specified predicate
1732 /// subsumes the second, e.g. GE subsumes GT.
1734 ArrayRef<MachineOperand> Pred2) const {
1735 return false;
1736 }
1737
1738 /// If the specified instruction defines any predicate
1739 /// or condition code register(s) used for predication, returns true as well
1740 /// as the definition predicate(s) by reference.
1741 /// SkipDead should be set to false at any point that dead
1742 /// predicate instructions should be considered as being defined.
1743 /// A dead predicate instruction is one that is guaranteed to be removed
1744 /// after a call to PredicateInstruction.
1746 std::vector<MachineOperand> &Pred,
1747 bool SkipDead) const {
1748 return false;
1749 }
1750
1751 /// Return true if the specified instruction can be predicated.
1752 /// By default, this returns true for every instruction with a
1753 /// PredicateOperand.
1754 virtual bool isPredicable(const MachineInstr &MI) const {
1755 return MI.getDesc().isPredicable();
1756 }
1757
1758 /// Return true if it's safe to move a machine
1759 /// instruction that defines the specified register class.
1760 virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
1761 return true;
1762 }
1763
1764 /// Test if the given instruction should be considered a scheduling boundary.
1765 /// This primarily includes labels and terminators.
1766 virtual bool isSchedulingBoundary(const MachineInstr &MI,
1767 const MachineBasicBlock *MBB,
1768 const MachineFunction &MF) const;
1769
1770 /// Measure the specified inline asm to determine an approximation of its
1771 /// length.
1772 virtual unsigned getInlineAsmLength(
1773 const char *Str, const MCAsmInfo &MAI,
1774 const TargetSubtargetInfo *STI = nullptr) const;
1775
1776 /// Allocate and return a hazard recognizer to use for this target when
1777 /// scheduling the machine instructions before register allocation.
1778 virtual ScheduleHazardRecognizer *
1779 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
1780 const ScheduleDAG *DAG) const;
1781
1782 /// Allocate and return a hazard recognizer to use for this target when
1783 /// scheduling the machine instructions before register allocation.
1784 virtual ScheduleHazardRecognizer *
1785 CreateTargetMIHazardRecognizer(const InstrItineraryData *,
1786 const ScheduleDAGMI *DAG) const;
1787
1788 /// Allocate and return a hazard recognizer to use for this target when
1789 /// scheduling the machine instructions after register allocation.
1790 virtual ScheduleHazardRecognizer *
1791 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *,
1792 const ScheduleDAG *DAG) const;
1793
1794 /// Allocate and return a hazard recognizer to use for by non-scheduling
1795 /// passes.
1796 virtual ScheduleHazardRecognizer *
1798 return nullptr;
1799 }
1800
1801 /// Provide a global flag for disabling the PreRA hazard recognizer that
1802 /// targets may choose to honor.
1803 bool usePreRAHazardRecognizer() const;
1804
1805 /// For a comparison instruction, return the source registers
1806 /// in SrcReg and SrcReg2 if having two register operands, and the value it
1807 /// compares against in CmpValue. Return true if the comparison instruction
1808 /// can be analyzed.
1809 virtual bool analyzeCompare(const MachineInstr &MI, Register &SrcReg,
1810 Register &SrcReg2, int64_t &Mask,
1811 int64_t &Value) const {
1812 return false;
1813 }
1814
1815 /// See if the comparison instruction can be converted
1816 /// into something more efficient. E.g., on ARM most instructions can set the
1817 /// flags register, obviating the need for a separate CMP.
1818 virtual bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
1819 Register SrcReg2, int64_t Mask,
1820 int64_t Value,
1821 const MachineRegisterInfo *MRI) const {
1822 return false;
1823 }
1824 virtual bool optimizeCondBranch(MachineInstr &MI) const { return false; }
1825
1826 /// Try to remove the load by folding it to a register operand at the use.
1827 /// We fold the load instructions if and only if the
1828 /// def and use are in the same BB. We only look at one load and see
1829 /// whether it can be folded into MI. FoldAsLoadDefReg is the virtual register
1830 /// defined by the load we are trying to fold. DefMI returns the machine
1831 /// instruction that defines FoldAsLoadDefReg, and the function returns
1832 /// the machine instruction generated due to folding.
1833 virtual MachineInstr *optimizeLoadInstr(MachineInstr &MI,
1834 const MachineRegisterInfo *MRI,
1835 Register &FoldAsLoadDefReg,
1836 MachineInstr *&DefMI) const;
1837
1838 /// 'Reg' is known to be defined by a move immediate instruction,
1839 /// try to fold the immediate into the use instruction.
1840 /// If MRI->hasOneNonDBGUse(Reg) is true, and this function returns true,
1841 /// then the caller may assume that DefMI has been erased from its parent
1842 /// block. The caller may assume that it will not be erased by this
1843 /// function otherwise.
1846 return false;
1847 }
1848
1849 /// Return the number of u-operations the given machine
1850 /// instruction will be decoded to on the target cpu. The itinerary's
1851 /// IssueWidth is the number of microops that can be dispatched each
1852 /// cycle. An instruction with zero microops takes no dispatch resources.
1853 virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
1854 const MachineInstr &MI) const;
1855
1856 /// Return true for pseudo instructions that don't consume any
1857 /// machine resources in their current form. These are common cases that the
1858 /// scheduler should consider free, rather than conservatively handling them
1859 /// as instructions with no itinerary.
1860 bool isZeroCost(unsigned Opcode) const {
1861 return Opcode <= TargetOpcode::COPY;
1862 }
1863
1864 virtual std::optional<unsigned>
1865 getOperandLatency(const InstrItineraryData *ItinData, SDNode *DefNode,
1866 unsigned DefIdx, SDNode *UseNode, unsigned UseIdx) const;
1867
1868 /// Compute and return the use operand latency of a given pair of def and use.
1869 /// In most cases, the static scheduling itinerary was enough to determine the
1870 /// operand latency. But it may not be possible for instructions with variable
1871 /// number of defs / uses.
1872 ///
1873 /// This is a raw interface to the itinerary that may be directly overridden
1874 /// by a target. Use computeOperandLatency to get the best estimate of
1875 /// latency.
1876 virtual std::optional<unsigned>
1877 getOperandLatency(const InstrItineraryData *ItinData,
1878 const MachineInstr &DefMI, unsigned DefIdx,
1879 const MachineInstr &UseMI, unsigned UseIdx) const;
1880
1881 /// Compute the instruction latency of a given instruction.
1882 /// If the instruction has higher cost when predicated, it's returned via
1883 /// PredCost.
1884 virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
1885 const MachineInstr &MI,
1886 unsigned *PredCost = nullptr) const;
1887
1888 virtual unsigned getPredicationCost(const MachineInstr &MI) const;
1889
1890 virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
1891 SDNode *Node) const;
1892
1893 /// Return the default expected latency for a def based on its opcode.
1894 unsigned defaultDefLatency(const MCSchedModel &SchedModel,
1895 const MachineInstr &DefMI) const;
1896
1897 /// Return true if this opcode has high latency to its result.
1898 virtual bool isHighLatencyDef(int opc) const { return false; }
1899
1900 /// Compute operand latency between a def of 'Reg'
1901 /// and a use in the current loop. Return true if the target considered
1902 /// it 'high'. This is used by optimization passes such as machine LICM to
1903 /// determine whether it makes sense to hoist an instruction out even in a
1904 /// high register pressure situation.
1905 virtual bool hasHighOperandLatency(const TargetSchedModel &SchedModel,
1906 const MachineRegisterInfo *MRI,
1907 const MachineInstr &DefMI, unsigned DefIdx,
1908 const MachineInstr &UseMI,
1909 unsigned UseIdx) const {
1910 return false;
1911 }
1912
1913 /// Compute operand latency of a def of 'Reg'. Return true
1914 /// if the target considered it 'low'.
1915 virtual bool hasLowDefLatency(const TargetSchedModel &SchedModel,
1916 const MachineInstr &DefMI,
1917 unsigned DefIdx) const;
1918
1919 /// Perform target-specific instruction verification.
1920 virtual bool verifyInstruction(const MachineInstr &MI,
1921 StringRef &ErrInfo) const {
1922 return true;
1923 }
1924
1925 /// Return the current execution domain and bit mask of
1926 /// possible domains for instruction.
1927 ///
1928 /// Some micro-architectures have multiple execution domains, and multiple
1929 /// opcodes that perform the same operation in different domains. For
1930 /// example, the x86 architecture provides the por, orps, and orpd
1931 /// instructions that all do the same thing. There is a latency penalty if a
1932 /// register is written in one domain and read in another.
1933 ///
1934 /// This function returns a pair (domain, mask) containing the execution
1935 /// domain of MI, and a bit mask of possible domains. The setExecutionDomain
1936 /// function can be used to change the opcode to one of the domains in the
1937 /// bit mask. Instructions whose execution domain can't be changed should
1938 /// return a 0 mask.
1939 ///
1940 /// The execution domain numbers don't have any special meaning except domain
1941 /// 0 is used for instructions that are not associated with any interesting
1942 /// execution domain.
1943 ///
1944 virtual std::pair<uint16_t, uint16_t>
1946 return std::make_pair(0, 0);
1947 }
1948
1949 /// Change the opcode of MI to execute in Domain.
1950 ///
1951 /// The bit (1 << Domain) must be set in the mask returned from
1952 /// getExecutionDomain(MI).
1953 virtual void setExecutionDomain(MachineInstr &MI, unsigned Domain) const {}
1954
1955 /// Returns the preferred minimum clearance
1956 /// before an instruction with an unwanted partial register update.
1957 ///
1958 /// Some instructions only write part of a register, and implicitly need to
1959 /// read the other parts of the register. This may cause unwanted stalls
1960 /// preventing otherwise unrelated instructions from executing in parallel in
1961 /// an out-of-order CPU.
1962 ///
1963 /// For example, the x86 instruction cvtsi2ss writes its result to bits
1964 /// [31:0] of the destination xmm register. Bits [127:32] are unaffected, so
1965 /// the instruction needs to wait for the old value of the register to become
1966 /// available:
1967 ///
1968 /// addps %xmm1, %xmm0
1969 /// movaps %xmm0, (%rax)
1970 /// cvtsi2ss %rbx, %xmm0
1971 ///
1972 /// In the code above, the cvtsi2ss instruction needs to wait for the addps
1973 /// instruction before it can issue, even though the high bits of %xmm0
1974 /// probably aren't needed.
1975 ///
1976 /// This hook returns the preferred clearance before MI, measured in
1977 /// instructions. Other defs of MI's operand OpNum are avoided in the last N
1978 /// instructions before MI. It should only return a positive value for
1979 /// unwanted dependencies. If the old bits of the defined register have
1980 /// useful values, or if MI is determined to otherwise read the dependency,
1981 /// the hook should return 0.
1982 ///
1983 /// The unwanted dependency may be handled by:
1984 ///
1985 /// 1. Allocating the same register for an MI def and use. That makes the
1986 /// unwanted dependency identical to a required dependency.
1987 ///
1988 /// 2. Allocating a register for the def that has no defs in the previous N
1989 /// instructions.
1990 ///
1991 /// 3. Calling breakPartialRegDependency() with the same arguments. This
1992 /// allows the target to insert a dependency breaking instruction.
1993 ///
1994 virtual unsigned
1996 const TargetRegisterInfo *TRI) const {
1997 // The default implementation returns 0 for no partial register dependency.
1998 return 0;
1999 }
2000
2001 /// Return the minimum clearance before an instruction that reads an
2002 /// unused register.
2003 ///
2004 /// For example, AVX instructions may copy part of a register operand into
2005 /// the unused high bits of the destination register.
2006 ///
2007 /// vcvtsi2sdq %rax, undef %xmm0, %xmm14
2008 ///
2009 /// In the code above, vcvtsi2sdq copies %xmm0[127:64] into %xmm14 creating a
2010 /// false dependence on any previous write to %xmm0.
2011 ///
2012 /// This hook works similarly to getPartialRegUpdateClearance, except that it
2013 /// does not take an operand index. Instead sets \p OpNum to the index of the
2014 /// unused register.
2015 virtual unsigned getUndefRegClearance(const MachineInstr &MI, unsigned OpNum,
2016 const TargetRegisterInfo *TRI) const {
2017 // The default implementation returns 0 for no undef register dependency.
2018 return 0;
2019 }
2020
2021 /// Insert a dependency-breaking instruction
2022 /// before MI to eliminate an unwanted dependency on OpNum.
2023 ///
2024 /// If it wasn't possible to avoid a def in the last N instructions before MI
2025 /// (see getPartialRegUpdateClearance), this hook will be called to break the
2026 /// unwanted dependency.
2027 ///
2028 /// On x86, an xorps instruction can be used as a dependency breaker:
2029 ///
2030 /// addps %xmm1, %xmm0
2031 /// movaps %xmm0, (%rax)
2032 /// xorps %xmm0, %xmm0
2033 /// cvtsi2ss %rbx, %xmm0
2034 ///
2035 /// An <imp-kill> operand should be added to MI if an instruction was
2036 /// inserted. This ties the instructions together in the post-ra scheduler.
2037 ///
2038 virtual void breakPartialRegDependency(MachineInstr &MI, unsigned OpNum,
2039 const TargetRegisterInfo *TRI) const {}
2040
2041 /// Create machine specific model for scheduling.
2042 virtual DFAPacketizer *
2044 return nullptr;
2045 }
2046
2047 /// Sometimes, it is possible for the target
2048 /// to tell, even without aliasing information, that two MIs access different
2049 /// memory addresses. This function returns true if two MIs access different
2050 /// memory addresses and false otherwise.
2051 ///
2052 /// Assumes any physical registers used to compute addresses have the same
2053 /// value for both instructions. (This is the most useful assumption for
2054 /// post-RA scheduling.)
2055 ///
2056 /// See also MachineInstr::mayAlias, which is implemented on top of this
2057 /// function.
2058 virtual bool
2060 const MachineInstr &MIb) const {
2061 assert(MIa.mayLoadOrStore() &&
2062 "MIa must load from or modify a memory location");
2063 assert(MIb.mayLoadOrStore() &&
2064 "MIb must load from or modify a memory location");
2065 return false;
2066 }
2067
2068 /// Return the value to use for the MachineCSE's LookAheadLimit,
2069 /// which is a heuristic used for CSE'ing phys reg defs.
2070 virtual unsigned getMachineCSELookAheadLimit() const {
2071 // The default lookahead is small to prevent unprofitable quadratic
2072 // behavior.
2073 return 5;
2074 }
2075
2076 /// Return the maximal number of alias checks on memory operands. For
2077 /// instructions with more than one memory operands, the alias check on a
2078 /// single MachineInstr pair has quadratic overhead and results in
2079 /// unacceptable performance in the worst case. The limit here is to clamp
2080 /// that maximal checks performed. Usually, that's the product of memory
2081 /// operand numbers from that pair of MachineInstr to be checked. For
2082 /// instance, with two MachineInstrs with 4 and 5 memory operands
2083 /// correspondingly, a total of 20 checks are required. With this limit set to
2084 /// 16, their alias check is skipped. We choose to limit the product instead
2085 /// of the individual instruction as targets may have special MachineInstrs
2086 /// with a considerably high number of memory operands, such as `ldm` in ARM.
2087 /// Setting this limit per MachineInstr would result in either too high
2088 /// overhead or too rigid restriction.
2089 virtual unsigned getMemOperandAACheckLimit() const { return 16; }
2090
2091 /// Return an array that contains the ids of the target indices (used for the
2092 /// TargetIndex machine operand) and their names.
2093 ///
2094 /// MIR Serialization is able to serialize only the target indices that are
2095 /// defined by this method.
2098 return {};
2099 }
2100
2101 /// Decompose the machine operand's target flags into two values - the direct
2102 /// target flag value and any of bit flags that are applied.
2103 virtual std::pair<unsigned, unsigned>
2105 return std::make_pair(0u, 0u);
2106 }
2107
2108 /// Return an array that contains the direct target flag values and their
2109 /// names.
2110 ///
2111 /// MIR Serialization is able to serialize only the target flags that are
2112 /// defined by this method.
2115 return {};
2116 }
2117
2118 /// Return an array that contains the bitmask target flag values and their
2119 /// names.
2120 ///
2121 /// MIR Serialization is able to serialize only the target flags that are
2122 /// defined by this method.
2125 return {};
2126 }
2127
2128 /// Return an array that contains the MMO target flag values and their
2129 /// names.
2130 ///
2131 /// MIR Serialization is able to serialize only the MMO target flags that are
2132 /// defined by this method.
2135 return {};
2136 }
2137
2138 /// Determines whether \p Inst is a tail call instruction. Override this
2139 /// method on targets that do not properly set MCID::Return and MCID::Call on
2140 /// tail call instructions."
2141 virtual bool isTailCall(const MachineInstr &Inst) const {
2142 return Inst.isReturn() && Inst.isCall();
2143 }
2144
2145 /// True if the instruction is bound to the top of its basic block and no
2146 /// other instructions shall be inserted before it. This can be implemented
2147 /// to prevent register allocator to insert spills for \p Reg before such
2148 /// instructions.
2150 Register Reg = Register()) const {
2151 return false;
2152 }
2153
2154 /// Allows targets to use appropriate copy instruction while spilitting live
2155 /// range of a register in register allocation.
2157 const MachineFunction &MF) const {
2158 return TargetOpcode::COPY;
2159 }
2160
2161 /// During PHI eleimination lets target to make necessary checks and
2162 /// insert the copy to the PHI destination register in a target specific
2163 /// manner.
2166 const DebugLoc &DL, Register Src, Register Dst) const {
2167 return BuildMI(MBB, InsPt, DL, get(TargetOpcode::COPY), Dst)
2168 .addReg(Src);
2169 }
2170
2171 /// During PHI eleimination lets target to make necessary checks and
2172 /// insert the copy to the PHI destination register in a target specific
2173 /// manner.
2176 const DebugLoc &DL, Register Src,
2177 unsigned SrcSubReg,
2178 Register Dst) const {
2179 return BuildMI(MBB, InsPt, DL, get(TargetOpcode::COPY), Dst)
2180 .addReg(Src, 0, SrcSubReg);
2181 }
2182
2183 /// Returns a \p outliner::OutlinedFunction struct containing target-specific
2184 /// information for a set of outlining candidates. Returns std::nullopt if the
2185 /// candidates are not suitable for outlining. \p MinRepeats is the minimum
2186 /// number of times the instruction sequence must be repeated.
2187 virtual std::optional<std::unique_ptr<outliner::OutlinedFunction>>
2189 const MachineModuleInfo &MMI,
2190 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
2191 unsigned MinRepeats) const {
2193 "Target didn't implement TargetInstrInfo::getOutliningCandidateInfo!");
2194 }
2195
2196 /// Optional target hook to create the LLVM IR attributes for the outlined
2197 /// function. If overridden, the overriding function must call the default
2198 /// implementation.
2199 virtual void mergeOutliningCandidateAttributes(
2200 Function &F, std::vector<outliner::Candidate> &Candidates) const;
2201
2202protected:
2203 /// Target-dependent implementation for getOutliningTypeImpl.
2204 virtual outliner::InstrType
2206 MachineBasicBlock::iterator &MIT, unsigned Flags) const {
2208 "Target didn't implement TargetInstrInfo::getOutliningTypeImpl!");
2209 }
2210
2211public:
2212 /// Returns how or if \p MIT should be outlined. \p Flags is the
2213 /// target-specific information returned by isMBBSafeToOutlineFrom.
2214 outliner::InstrType getOutliningType(const MachineModuleInfo &MMI,
2216 unsigned Flags) const;
2217
2218 /// Optional target hook that returns true if \p MBB is safe to outline from,
2219 /// and returns any target-specific information in \p Flags.
2220 virtual bool isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
2221 unsigned &Flags) const;
2222
2223 /// Optional target hook which partitions \p MBB into outlinable ranges for
2224 /// instruction mapping purposes. Each range is defined by two iterators:
2225 /// [start, end).
2226 ///
2227 /// Ranges are expected to be ordered top-down. That is, ranges closer to the
2228 /// top of the block should come before ranges closer to the end of the block.
2229 ///
2230 /// Ranges cannot overlap.
2231 ///
2232 /// If an entire block is mappable, then its range is [MBB.begin(), MBB.end())
2233 ///
2234 /// All instructions not present in an outlinable range are considered
2235 /// illegal.
2236 virtual SmallVector<
2237 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
2238 getOutlinableRanges(MachineBasicBlock &MBB, unsigned &Flags) const {
2239 return {std::make_pair(MBB.begin(), MBB.end())};
2240 }
2241
2242 /// Insert a custom frame for outlined functions.
2244 const outliner::OutlinedFunction &OF) const {
2246 "Target didn't implement TargetInstrInfo::buildOutlinedFrame!");
2247 }
2248
2249 /// Insert a call to an outlined function into the program.
2250 /// Returns an iterator to the spot where we inserted the call. This must be
2251 /// implemented by the target.
2255 outliner::Candidate &C) const {
2257 "Target didn't implement TargetInstrInfo::insertOutlinedCall!");
2258 }
2259
2260 /// Insert an architecture-specific instruction to clear a register. If you
2261 /// need to avoid sideeffects (e.g. avoid XOR on x86, which sets EFLAGS), set
2262 /// \p AllowSideEffects to \p false.
2265 DebugLoc &DL,
2266 bool AllowSideEffects = true) const {
2267#if 0
2268 // FIXME: This should exist once all platforms that use stack protectors
2269 // implements it.
2271 "Target didn't implement TargetInstrInfo::buildClearRegister!");
2272#endif
2273 }
2274
2275 /// Return true if the function can safely be outlined from.
2276 /// A function \p MF is considered safe for outlining if an outlined function
2277 /// produced from instructions in F will produce a program which produces the
2278 /// same output for any set of given inputs.
2280 bool OutlineFromLinkOnceODRs) const {
2281 llvm_unreachable("Target didn't implement "
2282 "TargetInstrInfo::isFunctionSafeToOutlineFrom!");
2283 }
2284
2285 /// Return true if the function should be outlined from by default.
2287 return false;
2288 }
2289
2290 /// Return true if the function is a viable candidate for machine function
2291 /// splitting. The criteria for if a function can be split may vary by target.
2292 virtual bool isFunctionSafeToSplit(const MachineFunction &MF) const;
2293
2294 /// Return true if the MachineBasicBlock can safely be split to the cold
2295 /// section. On AArch64, certain instructions may cause a block to be unsafe
2296 /// to split to the cold section.
2297 virtual bool isMBBSafeToSplitToCold(const MachineBasicBlock &MBB) const {
2298 return true;
2299 }
2300
2301 /// Produce the expression describing the \p MI loading a value into
2302 /// the physical register \p Reg. This hook should only be used with
2303 /// \p MIs belonging to VReg-less functions.
2304 virtual std::optional<ParamLoadedValue>
2305 describeLoadedValue(const MachineInstr &MI, Register Reg) const;
2306
2307 /// Given the generic extension instruction \p ExtMI, returns true if this
2308 /// extension is a likely candidate for being folded into an another
2309 /// instruction.
2311 MachineRegisterInfo &MRI) const {
2312 return false;
2313 }
2314
2315 /// Return MIR formatter to format/parse MIR operands. Target can override
2316 /// this virtual function and return target specific MIR formatter.
2317 virtual const MIRFormatter *getMIRFormatter() const {
2318 if (!Formatter)
2319 Formatter = std::make_unique<MIRFormatter>();
2320 return Formatter.get();
2321 }
2322
2323 /// Returns the target-specific default value for tail duplication.
2324 /// This value will be used if the tail-dup-placement-threshold argument is
2325 /// not provided.
2326 virtual unsigned getTailDuplicateSize(CodeGenOptLevel OptLevel) const {
2327 return OptLevel >= CodeGenOptLevel::Aggressive ? 4 : 2;
2328 }
2329
2330 /// Returns the target-specific default value for tail merging.
2331 /// This value will be used if the tail-merge-size argument is not provided.
2332 virtual unsigned getTailMergeSize(const MachineFunction &MF) const {
2333 return 3;
2334 }
2335
2336 /// Returns the callee operand from the given \p MI.
2337 virtual const MachineOperand &getCalleeOperand(const MachineInstr &MI) const {
2338 return MI.getOperand(0);
2339 }
2340
2341 /// Return the uniformity behavior of the given instruction.
2342 virtual InstructionUniformity
2346
2347 /// Returns true if the given \p MI defines a TargetIndex operand that can be
2348 /// tracked by their offset, can have values, and can have debug info
2349 /// associated with it. If so, sets \p Index and \p Offset of the target index
2350 /// operand.
2351 virtual bool isExplicitTargetIndexDef(const MachineInstr &MI, int &Index,
2352 int64_t &Offset) const {
2353 return false;
2354 }
2355
2356 // Get the call frame size just before MI.
2357 unsigned getCallFrameSizeAt(MachineInstr &MI) const;
2358
2359 /// Fills in the necessary MachineOperands to refer to a frame index.
2360 /// The best way to understand this is to print `asm(""::"m"(x));` after
2361 /// finalize-isel. Example:
2362 /// INLINEASM ... 262190 /* mem:m */, %stack.0.x.addr, 1, $noreg, 0, $noreg
2363 /// we would add placeholders for: ^ ^ ^ ^
2365 int FI) const {
2366 llvm_unreachable("unknown number of operands necessary");
2367 }
2368
2369private:
2370 mutable std::unique_ptr<MIRFormatter> Formatter;
2371 unsigned CallFrameSetupOpcode, CallFrameDestroyOpcode;
2372 unsigned CatchRetOpcode;
2373 unsigned ReturnOpcode;
2374};
2375
2376/// Provide DenseMapInfo for TargetInstrInfo::RegSubRegPair.
2380
2382 return TargetInstrInfo::RegSubRegPair(RegInfo::getEmptyKey(),
2383 SubRegInfo::getEmptyKey());
2384 }
2385
2387 return TargetInstrInfo::RegSubRegPair(RegInfo::getTombstoneKey(),
2388 SubRegInfo::getTombstoneKey());
2389 }
2390
2391 /// Reuse getHashValue implementation from
2392 /// std::pair<unsigned, unsigned>.
2393 static unsigned getHashValue(const TargetInstrInfo::RegSubRegPair &Val) {
2395 std::make_pair(Val.Reg, Val.SubReg));
2396 }
2397
2400 return LHS == RHS;
2401 }
2402};
2403
2404} // end namespace llvm
2405
2406#endif // LLVM_CODEGEN_TARGETINSTRINFO_H
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
static const TargetRegisterClass * getRegClass(const MachineInstr &MI, Register Reg)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
SmallVector< int16_t, MAX_SRC_OPERANDS_NUM > OperandIndices
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
#define LLVM_ABI
Definition Compiler.h:213
DXIL Forward Handle Accesses
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
Contains all data structures shared between the outliner implemented in MachineOutliner....
TargetInstrInfo::RegSubRegPair RegSubRegPair
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
MachineInstr unsigned OpIdx
#define P(N)
TargetInstrInfo::RegSubRegPairAndIdx RegSubRegPairAndIdx
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
static unsigned getInstSizeInBytes(const MachineInstr &MI, const SystemZInstrInfo *TII)
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
This class is the base class for the comparison instructions.
Definition InstrTypes.h:666
A debug info location.
Definition DebugLoc.h:124
Itinerary data supplied by a subtarget to be used by a target.
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:64
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
Describe properties that are true of each instruction in the target description file.
Interface to description of machine instruction set.
Definition MCInstrInfo.h:27
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:90
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition MCInstrDesc.h:87
MIRFormater - Interface to format MIR operand based on target.
MachineInstrBundleIterator< MachineInstr > iterator
Representation of each machine instruction.
bool isReturn(QueryType Type=AnyInBundle) const
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
bool isCall(QueryType Type=AnyInBundle) const
A description of a memory reference used in the backend.
This class contains meta information specific to a module.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
static MachineOperand CreateImm(int64_t Val)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Wrapper class representing virtual and physical registers.
Definition Register.h:19
Represents one node in the SelectionDAG.
This class represents the scheduled code.
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
HazardRecognizer - This determines whether or not an instruction can be issued this cycle,...
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
This class builds the dependence graph for the instructions in a loop, and attempts to schedule the i...
Object returned by analyzeLoopForPipelining.
virtual bool isMVEExpanderSupported()
Return true if the target can expand pipelined schedule with modulo variable expansion.
virtual void createRemainingIterationsGreaterCondition(int TC, MachineBasicBlock &MBB, SmallVectorImpl< MachineOperand > &Cond, DenseMap< MachineInstr *, MachineInstr * > &LastStage0Insts)
Create a condition to determine if the remaining trip count for a phase is greater than TC.
virtual void adjustTripCount(int TripCountAdjust)=0
Modify the loop such that the trip count is OriginalTC + TripCountAdjust.
virtual void disposed(LiveIntervals *LIS=nullptr)
Called when the loop is being removed.
virtual bool shouldIgnoreForPipelining(const MachineInstr *MI) const =0
Return true if the given instruction should not be pipelined and should be ignored.
virtual void setPreheader(MachineBasicBlock *NewPreheader)=0
Called when the loop's preheader has been modified to NewPreheader.
virtual bool shouldUseSchedule(SwingSchedulerDAG &SSD, SMSchedule &SMS)
Return true if the proposed schedule should used.
virtual std::optional< bool > createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB, SmallVectorImpl< MachineOperand > &Cond)=0
Create a condition to determine if the trip count of the loop is greater than TC, where TC is always ...
TargetInstrInfo - Interface to description of machine instruction set.
virtual SmallVector< std::pair< MachineBasicBlock::iterator, MachineBasicBlock::iterator > > getOutlinableRanges(MachineBasicBlock &MBB, unsigned &Flags) const
Optional target hook which partitions MBB into outlinable ranges for instruction mapping purposes.
virtual bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, unsigned ExtraPredCycles, BranchProbability Probability) const
Return true if it's profitable to predicate instructions with accumulated instruction latency of "Num...
virtual bool isBasicBlockPrologue(const MachineInstr &MI, Register Reg=Register()) const
True if the instruction is bound to the top of its basic block and no other instructions shall be ins...
virtual bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const
Reverses the branch condition of the specified condition list, returning false on success and true if...
virtual unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const
Remove the branching code at the end of the specific MBB.
virtual std::unique_ptr< PipelinerLoopInfo > analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const
Analyze loop L, which must be a single-basic-block loop, and if the conditions can be understood enou...
virtual bool ClobbersPredicate(MachineInstr &MI, std::vector< MachineOperand > &Pred, bool SkipDead) const
If the specified instruction defines any predicate or condition code register(s) used for predication...
virtual MachineInstr * foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI, ArrayRef< unsigned > Ops, MachineBasicBlock::iterator InsertPt, int FrameIndex, LiveIntervals *LIS=nullptr, VirtRegMap *VRM=nullptr) const
Target-dependent implementation for foldMemoryOperand.
virtual bool canPredicatePredicatedInstr(const MachineInstr &MI) const
Assumes the instruction is already predicated and returns true if the instruction can be predicated a...
virtual void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2, MachineInstr &NewMI1, MachineInstr &NewMI2) const
This is an architecture-specific helper function of reassociateOps.
bool isZeroCost(unsigned Opcode) const
Return true for pseudo instructions that don't consume any machine resources in their current form.
virtual void buildClearRegister(Register Reg, MachineBasicBlock &MBB, MachineBasicBlock::iterator Iter, DebugLoc &DL, bool AllowSideEffects=true) const
Insert an architecture-specific instruction to clear a register.
virtual void getFrameIndexOperands(SmallVectorImpl< MachineOperand > &Ops, int FI) const
Fills in the necessary MachineOperands to refer to a frame index.
virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
virtual bool isExtendLikelyToBeFolded(MachineInstr &ExtMI, MachineRegisterInfo &MRI) const
Given the generic extension instruction ExtMI, returns true if this extension is a likely candidate f...
virtual bool isSafeToSink(MachineInstr &MI, MachineBasicBlock *SuccToSinkTo, MachineCycleInfo *CI) const
virtual std::optional< DestSourcePair > isCopyLikeInstrImpl(const MachineInstr &MI) const
virtual unsigned getPartialRegUpdateClearance(const MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const
Returns the preferred minimum clearance before an instruction with an unwanted partial register updat...
virtual bool canMakeTailCallConditional(SmallVectorImpl< MachineOperand > &Cond, const MachineInstr &TailCall) const
Returns true if the tail call can be made conditional on BranchCond.
virtual DFAPacketizer * CreateTargetScheduleState(const TargetSubtargetInfo &) const
Create machine specific model for scheduling.
virtual unsigned reduceLoopCount(MachineBasicBlock &MBB, MachineBasicBlock &PreHeader, MachineInstr *IndVar, MachineInstr &Cmp, SmallVectorImpl< MachineOperand > &Cond, SmallVectorImpl< MachineInstr * > &PrevInsts, unsigned Iter, unsigned MaxIter) const
Generate code to reduce the loop iteration by one and check if the loop is finished.
virtual bool isPostIncrement(const MachineInstr &MI) const
Return true for post-incremented instructions.
bool isTriviallyReMaterializable(const MachineInstr &MI) const
Return true if the instruction is trivially rematerializable, meaning it has no side effects and requ...
virtual bool isCoalescableExtInstr(const MachineInstr &MI, Register &SrcReg, Register &DstReg, unsigned &SubIdx) const
Return true if the instruction is a "coalescable" extension instruction.
virtual void insertIndirectBranch(MachineBasicBlock &MBB, MachineBasicBlock &NewDestBB, MachineBasicBlock &RestoreBB, const DebugLoc &DL, int64_t BrOffset=0, RegScavenger *RS=nullptr) const
Insert an unconditional indirect branch at the end of MBB to NewDestBB.
virtual ArrayRef< std::pair< MachineMemOperand::Flags, const char * > > getSerializableMachineMemOperandTargetFlags() const
Return an array that contains the MMO target flag values and their names.
virtual bool getBaseAndOffsetPosition(const MachineInstr &MI, unsigned &BasePos, unsigned &OffsetPos) const
Return true if the instruction contains a base register and offset.
int16_t getOpRegClassID(const MCOperandInfo &OpInfo) const
virtual unsigned getOpcodeAfterMemoryUnfold(unsigned Opc, bool UnfoldLoad, bool UnfoldStore, unsigned *LoadRegIndex=nullptr) const
Returns the opcode of the would be new instruction after load / store are unfolded from an instructio...
virtual outliner::InstrType getOutliningTypeImpl(const MachineModuleInfo &MMI, MachineBasicBlock::iterator &MIT, unsigned Flags) const
Target-dependent implementation for getOutliningTypeImpl.
virtual bool analyzeBranchPredicate(MachineBasicBlock &MBB, MachineBranchPredicate &MBP, bool AllowModify=false) const
Analyze the branching code at the end of MBB and parse it into the MachineBranchPredicate structure i...
virtual bool getInsertSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const
Target-dependent implementation of getInsertSubregInputs.
virtual bool shouldOutlineFromFunctionByDefault(MachineFunction &MF) const
Return true if the function should be outlined from by default.
virtual MachineInstr * optimizeSelect(MachineInstr &MI, SmallPtrSetImpl< MachineInstr * > &NewMIs, bool PreferFalse=false) const
Given a select instruction that was understood by analyzeSelect and returned Optimizable = true,...
virtual bool canFoldIntoAddrMode(const MachineInstr &MemI, Register Reg, const MachineInstr &AddrI, ExtAddrMode &AM) const
Check if it's possible and beneficial to fold the addressing computation AddrI into the addressing mo...
virtual const MIRFormatter * getMIRFormatter() const
Return MIR formatter to format/parse MIR operands.
bool isReMaterializable(const MachineInstr &MI) const
Return true if the instruction would be materializable at a point in the containing function where al...
virtual bool shouldReduceRegisterPressure(const MachineBasicBlock *MBB, const RegisterClassInfo *RegClassInfo) const
Return true if target supports reassociation of instructions in machine combiner pass to reduce regis...
virtual ArrayRef< std::pair< int, const char * > > getSerializableTargetIndices() const
Return an array that contains the ids of the target indices (used for the TargetIndex machine operand...
bool isFullCopyInstr(const MachineInstr &MI) const
virtual unsigned getUndefRegClearance(const MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const
Return the minimum clearance before an instruction that reads an unused register.
virtual bool findCommutedOpIndices(const MachineInstr &MI, unsigned &SrcOpIdx1, unsigned &SrcOpIdx2) const
Returns true iff the routine could find two commutable operands in the given machine instruction.
virtual bool preservesZeroValueInReg(const MachineInstr *MI, const Register NullValueReg, const TargetRegisterInfo *TRI) const
Returns true if MI's Def is NullValueReg, and the MI does not change the Zero value.
virtual bool verifyInstruction(const MachineInstr &MI, StringRef &ErrInfo) const
Perform target-specific instruction verification.
virtual void finalizeInsInstrs(MachineInstr &Root, unsigned &Pattern, SmallVectorImpl< MachineInstr * > &InsInstrs) const
Fix up the placeholder we may add in genAlternativeCodeSequence().
virtual bool isUnconditionalTailCall(const MachineInstr &MI) const
Returns true if MI is an unconditional tail call.
virtual bool hasHighOperandLatency(const TargetSchedModel &SchedModel, const MachineRegisterInfo *MRI, const MachineInstr &DefMI, unsigned DefIdx, const MachineInstr &UseMI, unsigned UseIdx) const
Compute operand latency between a def of 'Reg' and a use in the current loop.
bool isUnspillableTerminator(const MachineInstr *MI) const
Return true if the given instruction is terminator that is unspillable, according to isUnspillableTer...
virtual bool isProfitableToUnpredicate(MachineBasicBlock &TMBB, MachineBasicBlock &FMBB) const
Return true if it's profitable to unpredicate one side of a 'diamond', i.e.
virtual bool useMachineCombiner() const
Return true when a target supports MachineCombiner.
virtual bool SubsumesPredicate(ArrayRef< MachineOperand > Pred1, ArrayRef< MachineOperand > Pred2) const
Returns true if the first specified predicate subsumes the second, e.g.
bool isFrameInstr(const MachineInstr &I) const
Returns true if the argument is a frame pseudo instruction.
virtual void breakPartialRegDependency(MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const
Insert a dependency-breaking instruction before MI to eliminate an unwanted dependency on OpNum.
virtual bool getRegSequenceLikeInputs(const MachineInstr &MI, unsigned DefIdx, SmallVectorImpl< RegSubRegPairAndIdx > &InputRegs) const
Target-dependent implementation of getRegSequenceInputs.
virtual bool isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned NumTCycles, unsigned ExtraTCycles, MachineBasicBlock &FMBB, unsigned NumFCycles, unsigned ExtraFCycles, BranchProbability Probability) const
Second variant of isProfitableToIfCvt.
virtual int getExtendResourceLenLimit() const
The limit on resource length extension we accept in MachineCombiner Pass.
virtual ScheduleHazardRecognizer * CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const
Allocate and return a hazard recognizer to use for by non-scheduling passes.
virtual void insertSelect(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DstReg, ArrayRef< MachineOperand > Cond, Register TrueReg, Register FalseReg) const
Insert a select instruction into MBB before I that will copy TrueReg to DstReg when Cond is true,...
virtual bool shouldBreakCriticalEdgeToSink(MachineInstr &MI) const
For a "cheap" instruction which doesn't enable additional sinking, should MachineSink break a critica...
virtual bool areMemAccessesTriviallyDisjoint(const MachineInstr &MIa, const MachineInstr &MIb) const
Sometimes, it is possible for the target to tell, even without aliasing information,...
virtual bool isBranchOffsetInRange(unsigned BranchOpc, int64_t BrOffset) const
unsigned getReturnOpcode() const
virtual bool isIgnorableUse(const MachineOperand &MO) const
Given MO is a PhysReg use return if it can be ignored for the purpose of instruction rematerializatio...
virtual unsigned getReduceOpcodeForAccumulator(unsigned int AccumulatorOpCode) const
Returns the opcode that should be use to reduce accumulation registers.
virtual Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const
If the specified machine instruction is a direct load from a stack slot, return the virtual or physic...
virtual bool shouldClusterMemOps(ArrayRef< const MachineOperand * > BaseOps1, int64_t Offset1, bool OffsetIsScalable1, ArrayRef< const MachineOperand * > BaseOps2, int64_t Offset2, bool OffsetIsScalable2, unsigned ClusterSize, unsigned NumBytes) const
Returns true if the two given memory operations should be scheduled adjacent.
virtual unsigned getLiveRangeSplitOpcode(Register Reg, const MachineFunction &MF) const
Allows targets to use appropriate copy instruction while spilitting live range of a register in regis...
virtual void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const
Store the specified register of the given register class to the specified stack frame index.
virtual bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t Mask, int64_t Value, const MachineRegisterInfo *MRI) const
See if the comparison instruction can be converted into something more efficient.
virtual unsigned getMemOperandAACheckLimit() const
Return the maximal number of alias checks on memory operands.
virtual bool isFunctionSafeToOutlineFrom(MachineFunction &MF, bool OutlineFromLinkOnceODRs) const
Return true if the function can safely be outlined from.
virtual bool isMBBSafeToSplitToCold(const MachineBasicBlock &MBB) const
Return true if the MachineBasicBlock can safely be split to the cold section.
virtual void buildOutlinedFrame(MachineBasicBlock &MBB, MachineFunction &MF, const outliner::OutlinedFunction &OF) const
Insert a custom frame for outlined functions.
virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2, int64_t Offset1, int64_t Offset2, unsigned NumLoads) const
This is a used by the pre-regalloc scheduler to determine (in conjunction with areLoadsFromSameBasePt...
virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const
Insert branch code into the end of the specified MachineBasicBlock.
virtual void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, Register DestReg, Register SrcReg, bool KillSrc, bool RenamableDest=false, bool RenamableSrc=false) const
Emit instructions to copy a pair of physical registers.
virtual unsigned getAccumulationStartOpcode(unsigned Opcode) const
Returns an opcode which defines the accumulator used by \P Opcode.
virtual bool canCopyGluedNodeDuringSchedule(SDNode *N) const
Return true if the given SDNode can be copied during scheduling even if it has glue.
virtual bool simplifyInstruction(MachineInstr &MI) const
If possible, converts the instruction to a simplified/canonical form.
virtual std::optional< ExtAddrMode > getAddrModeFromMemoryOp(const MachineInstr &MemI, const TargetRegisterInfo *TRI) const
Target dependent implementation to get the values constituting the address MachineInstr that is acces...
virtual std::optional< DestSourcePair > isCopyInstrImpl(const MachineInstr &MI) const
Target-dependent implementation for IsCopyInstr.
virtual MachineInstr * createPHIDestinationCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, Register Dst) const
During PHI eleimination lets target to make necessary checks and insert the copy to the PHI destinati...
virtual bool getConstValDefinedInReg(const MachineInstr &MI, const Register Reg, int64_t &ImmVal) const
Returns true if MI is an instruction that defines Reg to have a constant value and the value is recor...
static bool isGenericOpcode(unsigned Opc)
TargetInstrInfo & operator=(const TargetInstrInfo &)=delete
std::optional< DestSourcePair > isCopyLikeInstr(const MachineInstr &MI) const
virtual ArrayRef< std::pair< unsigned, const char * > > getSerializableBitmaskMachineOperandTargetFlags() const
Return an array that contains the bitmask target flag values and their names.
unsigned getCallFrameSetupOpcode() const
These methods return the opcode of the frame setup/destroy instructions if they exist (-1 otherwise).
virtual bool isSubregFoldable() const
Check whether the target can fold a load that feeds a subreg operand (or a subreg operand that feeds ...
virtual bool isReMaterializableImpl(const MachineInstr &MI) const
For instructions with opcodes for which the M_REMATERIALIZABLE flag is set, this hook lets the target...
virtual Register isStoreToStackSlotPostFE(const MachineInstr &MI, int &FrameIndex) const
Check for post-frame ptr elimination stack locations as well.
virtual Register isLoadFromStackSlotPostFE(const MachineInstr &MI, int &FrameIndex) const
Check for post-frame ptr elimination stack locations as well.
virtual std::pair< uint16_t, uint16_t > getExecutionDomain(const MachineInstr &MI) const
Return the current execution domain and bit mask of possible domains for instruction.
virtual bool optimizeCondBranch(MachineInstr &MI) const
virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst, MachineInstr *&CmpInst) const
Analyze the loop code, return true if it cannot be understood.
unsigned getCatchReturnOpcode() const
virtual unsigned getTailMergeSize(const MachineFunction &MF) const
Returns the target-specific default value for tail merging.
virtual void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const
Load the specified register of the given register class from the specified stack frame index.
virtual InstructionUniformity getInstructionUniformity(const MachineInstr &MI) const
Return the uniformity behavior of the given instruction.
virtual bool isAsCheapAsAMove(const MachineInstr &MI) const
Return true if the instruction is as cheap as a move instruction.
virtual bool isTailCall(const MachineInstr &Inst) const
Determines whether Inst is a tail call instruction.
const int16_t *const RegClassByHwMode
Subtarget specific sub-array of MCInstrInfo's RegClassByHwModeTables (i.e.
virtual const MachineOperand & getCalleeOperand(const MachineInstr &MI) const
Returns the callee operand from the given MI.
virtual Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const
If the specified machine instruction is a direct store to a stack slot, return the virtual or physica...
int64_t getFrameTotalSize(const MachineInstr &I) const
Returns the total frame size, which is made up of the space set up inside the pair of frame start-sto...
MachineInstr * commuteInstruction(MachineInstr &MI, bool NewMI=false, unsigned OpIdx1=CommuteAnyOperandIndex, unsigned OpIdx2=CommuteAnyOperandIndex) const
This method commutes the operands of the given machine instruction MI.
virtual bool foldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, Register Reg, MachineRegisterInfo *MRI) const
'Reg' is known to be defined by a move immediate instruction, try to fold the immediate into the use ...
virtual bool isStackSlotCopy(const MachineInstr &MI, int &DestFrameIndex, int &SrcFrameIndex) const
Return true if the specified machine instruction is a copy of one stack slot to another and has no ot...
virtual int getJumpTableIndex(const MachineInstr &MI) const
Return an index for MachineJumpTableInfo if insn is an indirect jump using a jump table,...
virtual bool isAssociativeAndCommutative(const MachineInstr &Inst, bool Invert=false) const
Return true when \P Inst is both associative and commutative.
virtual bool isExplicitTargetIndexDef(const MachineInstr &MI, int &Index, int64_t &Offset) const
Returns true if the given MI defines a TargetIndex operand that can be tracked by their offset,...
virtual bool unfoldMemoryOperand(MachineFunction &MF, MachineInstr &MI, Register Reg, bool UnfoldLoad, bool UnfoldStore, SmallVectorImpl< MachineInstr * > &NewMIs) const
unfoldMemoryOperand - Separate a single instruction which folded a load or a store or a load and a st...
virtual bool isPCRelRegisterOperandLegal(const MachineOperand &MO) const
Allow targets to tell MachineVerifier whether a specific register MachineOperand can be used as part ...
virtual std::optional< std::unique_ptr< outliner::OutlinedFunction > > getOutliningCandidateInfo(const MachineModuleInfo &MMI, std::vector< outliner::Candidate > &RepeatedSequenceLocs, unsigned MinRepeats) const
Returns a outliner::OutlinedFunction struct containing target-specific information for a set of outli...
virtual MachineInstr * createPHISourceCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const
During PHI eleimination lets target to make necessary checks and insert the copy to the PHI destinati...
virtual MachineBasicBlock::iterator insertOutlinedCall(Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It, MachineFunction &MF, outliner::Candidate &C) const
Insert a call to an outlined function into the program.
virtual std::optional< unsigned > getInverseOpcode(unsigned Opcode) const
Return the inverse operation opcode if it exists for \P Opcode (e.g.
unsigned getCallFrameDestroyOpcode() const
int64_t getFrameSize(const MachineInstr &I) const
Returns size of the frame associated with the given frame instruction.
virtual MachineBasicBlock * getBranchDestBlock(const MachineInstr &MI) const
virtual bool isPredicated(const MachineInstr &MI) const
Returns true if the instruction is already predicated.
virtual void replaceBranchWithTailCall(MachineBasicBlock &MBB, SmallVectorImpl< MachineOperand > &Cond, const MachineInstr &TailCall) const
Replace the conditional branch in MBB with a conditional tail call.
TargetInstrInfo(const TargetInstrInfo &)=delete
virtual unsigned predictBranchSizeForIfCvt(MachineInstr &MI) const
Return an estimate for the code size reduction (in bytes) which will be caused by removing the given ...
virtual ~TargetInstrInfo()
virtual bool isAccumulationOpcode(unsigned Opcode) const
Return true when \P OpCode is an instruction which performs accumulation into one of its operand regi...
bool isFrameSetup(const MachineInstr &I) const
Returns true if the argument is a frame setup pseudo instruction.
virtual unsigned extraSizeToPredicateInstructions(const MachineFunction &MF, unsigned NumInsts) const
Return the increase in code size needed to predicate a contiguous run of NumInsts instructions.
virtual bool accumulateInstrSeqToRootLatency(MachineInstr &Root) const
When calculate the latency of the root instruction, accumulate the latency of the sequence to the roo...
std::optional< DestSourcePair > isCopyInstr(const MachineInstr &MI) const
If the specific machine instruction is a instruction that moves/copies value from one register to ano...
virtual bool analyzeSelect(const MachineInstr &MI, SmallVectorImpl< MachineOperand > &Cond, unsigned &TrueOp, unsigned &FalseOp, bool &Optimizable) const
Analyze the given select instruction, returning true if it cannot be understood.
TargetInstrInfo(unsigned CFSetupOpcode=~0u, unsigned CFDestroyOpcode=~0u, unsigned CatchRetOpcode=~0u, unsigned ReturnOpcode=~0u, const int16_t *const RegClassByHwModeTable=nullptr)
virtual Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex, TypeSize &MemBytes) const
Optional extension of isStoreToStackSlot that returns the number of bytes stored to the stack.
virtual Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex, TypeSize &MemBytes) const
Optional extension of isLoadFromStackSlot that returns the number of bytes loaded from the stack.
virtual bool getMemOperandsWithOffsetWidth(const MachineInstr &MI, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width, const TargetRegisterInfo *TRI) const
Get zero or more base operands and the byte offset of an instruction that reads/writes memory.
virtual unsigned getInstSizeInBytes(const MachineInstr &MI) const
Returns the size in bytes of the specified MachineInstr, or ~0U when this function is not implemented...
virtual bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, BranchProbability Probability) const
Return true if it's profitable for if-converter to duplicate instructions of specified accumulated in...
virtual bool shouldSink(const MachineInstr &MI) const
Return true if the instruction should be sunk by MachineSink.
virtual MachineInstr * convertToThreeAddress(MachineInstr &MI, LiveVariables *LV, LiveIntervals *LIS) const
This method must be implemented by targets that set the M_CONVERTIBLE_TO_3_ADDR flag.
virtual void setExecutionDomain(MachineInstr &MI, unsigned Domain) const
Change the opcode of MI to execute in Domain.
virtual bool isPredicable(const MachineInstr &MI) const
Return true if the specified instruction can be predicated.
virtual std::pair< unsigned, unsigned > decomposeMachineOperandsTargetFlags(unsigned) const
Decompose the machine operand's target flags into two values - the direct target flag value and any o...
virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const
Return true if it's safe to move a machine instruction that defines the specified register class.
virtual bool canInsertSelect(const MachineBasicBlock &MBB, ArrayRef< MachineOperand > Cond, Register DstReg, Register TrueReg, Register FalseReg, int &CondCycles, int &TrueCycles, int &FalseCycles) const
Return true if it is possible to insert a select instruction that chooses between TrueReg and FalseRe...
virtual bool isUnspillableTerminatorImpl(const MachineInstr *MI) const
Return true if the given terminator MI is not expected to spill.
virtual std::optional< RegImmPair > isAddImmediate(const MachineInstr &MI, Register Reg) const
If the specific machine instruction is an instruction that adds an immediate value and a register,...
static bool isGenericAtomicRMWOpcode(unsigned Opc)
virtual bool hasCommutePreference(MachineInstr &MI, bool &Commute) const
Returns true if the target has a preference on the operands order of the given machine instruction.
static const unsigned CommuteAnyOperandIndex
virtual bool isHighLatencyDef(int opc) const
Return true if this opcode has high latency to its result.
virtual MachineInstr * emitLdStWithAddr(MachineInstr &MemI, const ExtAddrMode &AM) const
Emit a load/store instruction with the same value register as MemI, but using the address from AM.
virtual bool expandPostRAPseudo(MachineInstr &MI) const
This function is called for all pseudo instructions that remain after register allocation.
virtual ArrayRef< std::pair< unsigned, const char * > > getSerializableDirectMachineOperandTargetFlags() const
Return an array that contains the direct target flag values and their names.
virtual bool shouldHoist(const MachineInstr &MI, const MachineLoop *FromLoop) const
Return false if the instruction should not be hoisted by MachineLICM.
virtual bool getExtractSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx, RegSubRegPairAndIdx &InputReg) const
Target-dependent implementation of getExtractSubregInputs.
virtual unsigned getTailDuplicateSize(CodeGenOptLevel OptLevel) const
Returns the target-specific default value for tail duplication.
unsigned insertUnconditionalBranch(MachineBasicBlock &MBB, MachineBasicBlock *DestBB, const DebugLoc &DL, int *BytesAdded=nullptr) const
virtual bool getIncrementValue(const MachineInstr &MI, int &Value) const
If the instruction is an increment of a constant value, return the amount.
virtual MachineInstr * foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI, ArrayRef< unsigned > Ops, MachineBasicBlock::iterator InsertPt, MachineInstr &LoadMI, LiveIntervals *LIS=nullptr) const
Target-dependent implementation for foldMemoryOperand.
virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2, int64_t &Offset1, int64_t &Offset2) const
This is used by the pre-regalloc scheduler to determine if two loads are loading from the same base a...
virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N, SmallVectorImpl< SDNode * > &NewNodes) const
virtual bool analyzeCompare(const MachineInstr &MI, Register &SrcReg, Register &SrcReg2, int64_t &Mask, int64_t &Value) const
For a comparison instruction, return the source registers in SrcReg and SrcReg2 if having two registe...
virtual unsigned getMachineCSELookAheadLimit() const
Return the value to use for the MachineCSE's LookAheadLimit, which is a heuristic used for CSE'ing ph...
virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const
Return true if it's legal to split the given basic block at the specified instruction (i....
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Provide an instruction scheduling machine model to CodeGen passes.
TargetSubtargetInfo - Generic base class for all target subtargets.
static constexpr TypeSize getZero()
Definition TypeSize.h:349
LLVM Value Representation.
Definition Value.h:75
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
InstrType
Represents how an instruction should be mapped by the outliner.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:477
MachineTraceStrategy
Strategies for selecting traces.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
CombinerObjective
The combiner's goal may differ based on which pattern it is attempting to optimize.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
DWARFExpression::Operation Op
std::pair< MachineOperand, DIExpression * > ParamLoadedValue
InstructionUniformity
Enum describing how instructions behave with respect to uniformity and divergence,...
Definition Uniformity.h:18
@ Default
The result values are uniform if and only if all operands are uniform.
Definition Uniformity.h:20
GenericCycleInfo< MachineSSAContext > MachineCycleInfo
#define N
static unsigned getHashValue(const TargetInstrInfo::RegSubRegPair &Val)
Reuse getHashValue implementation from std::pair<unsigned, unsigned>.
static TargetInstrInfo::RegSubRegPair getTombstoneKey()
static TargetInstrInfo::RegSubRegPair getEmptyKey()
static bool isEqual(const TargetInstrInfo::RegSubRegPair &LHS, const TargetInstrInfo::RegSubRegPair &RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...
const MachineOperand * Source
DestSourcePair(const MachineOperand &Dest, const MachineOperand &Src)
const MachineOperand * Destination
Used to describe addressing mode similar to ExtAddrMode in CodeGenPrepare.
ExtAddrMode()=default
Machine model for scheduling, bundling, and heuristics.
Definition MCSchedule.h:258
RegImmPair(Register Reg, int64_t Imm)
Represents a predicate at the MachineFunction level.
bool SingleUseCondition
SingleUseCondition is true if ConditionDef is dead except for the branch(es) at the end of the basic ...
A pair composed of a pair of a register and a sub-register index, and another sub-register index.
RegSubRegPairAndIdx(Register Reg=Register(), unsigned SubReg=0, unsigned SubIdx=0)
A pair composed of a register and a sub-register index.
bool operator==(const RegSubRegPair &P) const
RegSubRegPair(Register Reg=Register(), unsigned SubReg=0)
bool operator!=(const RegSubRegPair &P) const
An individual sequence of instructions to be replaced with a call to an outlined function.
The information necessary to create an outlined function for some class of candidate.