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