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