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