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