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