LLVM 24.0.0git
TargetLowering.h
Go to the documentation of this file.
1//===- llvm/CodeGen/TargetLowering.h - Target Lowering 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/// \file
10/// This file describes how to lower LLVM code to machine code. This has two
11/// main components:
12///
13/// 1. Which ValueTypes are natively supported by the target.
14/// 2. Which operations are supported for supported ValueTypes.
15/// 3. Cost thresholds for alternative implementations of certain operations.
16///
17/// In addition it has a few other components, like information about FP
18/// immediates.
19///
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_CODEGEN_TARGETLOWERING_H
23#define LLVM_CODEGEN_TARGETLOWERING_H
24
25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/StringRef.h"
42#include "llvm/IR/Attributes.h"
43#include "llvm/IR/CallingConv.h"
44#include "llvm/IR/DataLayout.h"
46#include "llvm/IR/Function.h"
47#include "llvm/IR/InlineAsm.h"
48#include "llvm/IR/Instruction.h"
51#include "llvm/IR/Type.h"
58#include <algorithm>
59#include <cassert>
60#include <climits>
61#include <cstdint>
62#include <map>
63#include <string>
64#include <utility>
65#include <vector>
66
67namespace llvm {
68
69class AssumptionCache;
70class CCState;
71class CCValAssign;
74class Constant;
75enum class ExceptionHandling : int;
76class FastISel;
78class GlobalValue;
79class Loop;
81class IntrinsicInst;
82class IRBuilderBase;
83struct KnownBits;
84class LLVMContext;
86class MachineFunction;
87class MachineInstr;
89class MachineLoop;
91class MCContext;
92class MCExpr;
93class Module;
96class TargetMachine;
97class MCRegisterClass;
101class Value;
102class VPIntrinsic;
103
104namespace Sched {
105
107 None, // No preference
108 Source, // Follow source order.
109 RegPressure, // Scheduling for lowest register pressure.
110 Hybrid, // Scheduling for both latency and register pressure.
111 ILP, // Scheduling for ILP in low register pressure mode.
112 VLIW, // Scheduling for VLIW targets.
113 Fast, // Fast suboptimal list scheduling
114 Linearize, // Linearize DAG, no scheduling
115 Last = Linearize // Marker for the last Sched::Preference
116};
117
118} // end namespace Sched
119
120// MemOp models a memory operation, either memset or memcpy/memmove.
121struct MemOp {
122private:
123 enum class MemOpKind {
124 Memset,
125 MemsetWithZero, // memset the memory with zeros
126 Memcpy, // copy memory from source to destination, source and destination do
127 // not overlap
128 MemcpyStrSrc, // memcpy source is an in-register constant, so it does not
129 // need to be loaded
130 Memmove, // memmove: like memcpy, but source and destination regions may
131 // overlap
132 };
133
134 // Shared
135 uint64_t Size;
136 bool DstAlignCanChange; // true if destination alignment can satisfy any
137 // constraint.
138 Align DstAlign; // Specified alignment of the memory operation.
139
140 bool IsVolatile;
141 MemOpKind Kind;
142 Align SrcAlign; // Inferred alignment of the source or default value if the
143 // memory operation does not need to load the value.
144public:
145 static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
146 Align SrcAlign, bool IsVolatile,
147 bool MemcpyStrSrc = false) {
148 MemOp Op;
149 Op.Size = Size;
150 Op.DstAlignCanChange = DstAlignCanChange;
151 Op.DstAlign = DstAlign;
152 Op.IsVolatile = IsVolatile;
153 Op.Kind = MemcpyStrSrc ? MemOpKind::MemcpyStrSrc : MemOpKind::Memcpy;
154 Op.SrcAlign = SrcAlign;
155 return Op;
156 }
157
158 static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
159 Align SrcAlign, bool IsVolatile) {
160 MemOp Op;
161 Op.Size = Size;
162 Op.DstAlignCanChange = DstAlignCanChange;
163 Op.DstAlign = DstAlign;
164 Op.IsVolatile = IsVolatile;
165 Op.Kind = MemOpKind::Memmove;
166 Op.SrcAlign = SrcAlign;
167 return Op;
168 }
169
170 static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
171 bool IsZeroMemset, bool IsVolatile) {
172 MemOp Op;
173 Op.Size = Size;
174 Op.DstAlignCanChange = DstAlignCanChange;
175 Op.DstAlign = DstAlign;
176 Op.IsVolatile = IsVolatile;
177 Op.Kind = IsZeroMemset ? MemOpKind::MemsetWithZero : MemOpKind::Memset;
178 return Op;
179 }
180
181 uint64_t size() const { return Size; }
183 assert(!DstAlignCanChange);
184 return DstAlign;
185 }
186 bool isFixedDstAlign() const { return !DstAlignCanChange; }
187 bool isVolatile() const { return IsVolatile; }
188 bool isMemset() const {
189 return Kind == MemOpKind::Memset || Kind == MemOpKind::MemsetWithZero;
190 }
191 bool isMemcpy() const {
192 return Kind == MemOpKind::Memcpy || Kind == MemOpKind::MemcpyStrSrc;
193 }
194 bool isMemmove() const { return Kind == MemOpKind::Memmove; }
195 bool isMemcpyOrMemmove() const { return isMemcpy() || isMemmove(); }
197 return isMemcpyOrMemmove() && !DstAlignCanChange;
198 }
199 bool isZeroMemset() const { return Kind == MemOpKind::MemsetWithZero; }
200 bool isMemcpyStrSrc() const { return Kind == MemOpKind::MemcpyStrSrc; }
202 assert(isMemcpyOrMemmove() && "Must be a memcpy or memmove");
203 return SrcAlign;
204 }
205 bool isSrcAligned(Align AlignCheck) const {
206 return isMemset() || llvm::isAligned(AlignCheck, SrcAlign.value());
207 }
208 bool isDstAligned(Align AlignCheck) const {
209 return DstAlignCanChange || llvm::isAligned(AlignCheck, DstAlign.value());
210 }
211 bool isAligned(Align AlignCheck) const {
212 return isSrcAligned(AlignCheck) && isDstAligned(AlignCheck);
213 }
214};
215
216/// This base class for TargetLowering contains the SelectionDAG-independent
217/// parts that can be used from the rest of CodeGen.
219public:
220 /// This enum indicates whether operations are valid for a target, and if not,
221 /// what action should be used to make them valid.
223 Legal, // The target natively supports this operation.
224 Promote, // This operation should be executed in a larger type.
225 Expand, // Try to expand this to other ops, otherwise use a libcall.
226 LibCall, // Don't try to expand this to other ops, always use a libcall.
227 Custom // Use the LowerOperation hook to implement custom lowering.
228 };
229
230 /// This enum indicates whether a types are legal for a target, and if not,
231 /// what action should be used to make them valid.
233 TypeLegal, // The target natively supports this type.
234 TypePromoteInteger, // Replace this integer with a larger one.
235 TypeExpandInteger, // Split this integer into two of half the size.
236 TypeSoftenFloat, // Convert this float to a same size integer type.
237 TypeExpandFloat, // Split this float into two of half the size.
238 TypeScalarizeVector, // Replace this one-element vector with its element.
239 TypeSplitVector, // Split this vector into two of half the size.
240 TypeWidenVector, // This vector should be widened into a larger vector.
241 TypeSoftPromoteHalf, // Soften half to i16 and use float to do arithmetic.
242 TypeScalarizeScalableVector, // This action is explicitly left
243 // unimplemented. While it is theoretically
244 // possible to legalize operations on scalable
245 // types with a loop that handles the vscale *
246 // #lanes of the vector, this is non-trivial at
247 // SelectionDAG level and these types are
248 // better to be widened or promoted.
249 };
250
251 /// LegalizeKind holds the legalization kind that needs to happen to EVT
252 /// in order to type-legalize it.
253 using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
254
255 /// Enum that describes how the target represents true/false values.
257 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
258 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
259 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
260 };
261
262 /// Enum that describes what type of support for selects the target has.
264 ScalarValSelect, // The target supports scalar selects (ex: cmov).
265 ScalarCondVectorVal, // The target supports selects with a scalar condition
266 // and vector values (ex: cmov).
267 VectorMaskSelect // The target supports vector selects with a vector
268 // mask (ex: x86 blends).
269 };
270
271 /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
272 /// to, if at all. Exists because different targets have different levels of
273 /// support for these atomic instructions, and also have different options
274 /// w.r.t. what they should expand to.
276 None, // Don't expand the instruction.
277 CastToInteger, // Cast the atomic instruction to another type, e.g. from
278 // floating-point to integer type.
279 LLSC, // Expand the instruction into loadlinked/storeconditional; used
280 // by ARM/AArch64/PowerPC.
281 LLOnly, // Expand the (load) instruction into just a load-linked, which has
282 // greater atomic guarantees than a normal load.
283 CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
284 MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
285 BitTestIntrinsic, // Use a target-specific intrinsic for special bit
286 // operations; used by X86.
287 CmpArithIntrinsic, // Use a target-specific intrinsic for special compare
288 // operations; used by X86.
289 Expand, // Generic expansion in terms of other atomic operations.
290 CustomExpand, // Custom target-specific expansion using TLI hooks.
291
292 // Rewrite to a non-atomic form for use in a known non-preemptible
293 // environment.
295 };
296
297 /// Enum that specifies when a multiplication should be expanded.
298 enum class MulExpansionKind {
299 Always, // Always expand the instruction.
300 OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
301 // or custom.
302 };
303
304 /// Enum that specifies when a float negation is beneficial.
305 enum class NegatibleCost {
306 Cheaper = 0, // Negated expression is cheaper.
307 Neutral = 1, // Negated expression has the same cost.
308 Expensive = 2 // Negated expression is more expensive.
309 };
310
311 /// Enum that specifies how expensive lowering an EXTRACT_SUBVECTOR is.
313 Free = 0, // Lowers to no instruction at all, e.g. a subregister copy.
314 Cheap = 1, // Lowers to at most one instruction, and may still be free if
315 // the target can fold the extract into the instruction
316 // consuming it (e.g. a widening op that reads the high half of
317 // a register).
318 Expensive = 2 // Needs a shuffle sequence that cannot be folded away.
319 };
320
321 /// Enum of different potentially desirable ways to fold (and/or (setcc ...),
322 /// (setcc ...)).
324 None = 0, // No fold is preferable.
325 AddAnd = 1, // Fold with `Add` op and `And` op is preferable.
326 NotAnd = 2, // Fold with `Not` op and `And` op is preferable.
327 ABS = 4, // Fold with `llvm.abs` op is preferable.
328 };
329
331 public:
334 /// Original unlegalized argument type.
336 /// Same as OrigTy, or partially legalized for soft float libcalls.
338 bool IsSExt : 1;
339 bool IsZExt : 1;
340 bool IsNoExt : 1;
341 bool IsInReg : 1;
342 bool IsSRet : 1;
343 bool IsNest : 1;
344 bool IsByVal : 1;
345 bool IsByRef : 1;
346 bool IsInAlloca : 1;
348 bool IsReturned : 1;
349 bool IsSwiftSelf : 1;
350 bool IsSwiftAsync : 1;
351 bool IsSwiftError : 1;
353 MaybeAlign Alignment = std::nullopt;
354 Type *IndirectType = nullptr;
355
362
365
367
369
370 LLVM_ABI void setAttributes(const CallBase *Call, unsigned ArgIdx);
371 LLVM_ABI void setAttributes(const AttributeList &Attrs, unsigned ArgIdx);
372 };
373 using ArgListTy = std::vector<ArgListEntry>;
374
376 switch (Content) {
378 // Extend by adding rubbish bits.
379 return ISD::ANY_EXTEND;
381 // Extend by adding zero bits.
382 return ISD::ZERO_EXTEND;
384 // Extend by copying the sign bit.
385 return ISD::SIGN_EXTEND;
386 }
387 llvm_unreachable("Invalid content kind");
388 }
389
390 explicit TargetLoweringBase(const TargetMachine &TM,
391 const TargetSubtargetInfo &STI);
395
396 /// Return true if the target support strict float operation
397 bool isStrictFPEnabled() const {
398 return IsStrictFPEnabled;
399 }
400
401protected:
402 /// Initialize all of the actions to default values.
403 void initActions();
404
405public:
406 const TargetMachine &getTargetMachine() const { return TM; }
407
408 virtual bool useSoftFloat() const { return false; }
409
410 /// Return the pointer type for the given address space, defaults to
411 /// the pointer type from the data layout.
412 /// FIXME: The default needs to be removed once all the code is updated.
413 virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
414 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
415 }
416
417 /// Return the in-memory pointer type for the given address space, defaults to
418 /// the pointer type from the data layout.
419 /// FIXME: The default needs to be removed once all the code is updated.
420 virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS = 0) const {
421 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
422 }
423
424 /// Return the type for frame index, which is determined by
425 /// the alloca address space specified through the data layout.
427 return getPointerTy(DL, DL.getAllocaAddrSpace());
428 }
429
430 /// Return the type for code pointers, which is determined by the program
431 /// address space specified through the data layout.
433 return getPointerTy(DL, DL.getProgramAddressSpace());
434 }
435
436 /// Return the type for operands of fence.
437 /// TODO: Let fence operands be of i32 type and remove this.
438 virtual MVT getFenceOperandTy(const DataLayout &DL) const {
439 return getPointerTy(DL);
440 }
441
442 /// Return the type to use for a scalar shift opcode, given the shifted amount
443 /// type. Targets should return a legal type if the input type is legal.
444 /// Targets can return a type that is too small if the input type is illegal.
445 virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
446
447 /// Returns the type for the shift amount of a shift opcode. For vectors,
448 /// returns the input type. For scalars, calls getScalarShiftAmountTy.
449 /// If getScalarShiftAmountTy type cannot represent all possible shift
450 /// amounts, returns MVT::i32.
451 EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const;
452
453 /// Return the preferred type to use for a shift opcode, given the shifted
454 /// amount type is \p ShiftValueTy.
456 virtual LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const {
457 return ShiftValueTy;
458 }
459
460 /// Returns the type to be used for the index operand vector operations. By
461 /// default we assume it will have the same size as an address space 0
462 /// pointer.
463 virtual unsigned getVectorIdxWidth(const DataLayout &DL) const {
464 return DL.getPointerSizeInBits(0);
465 }
466
467 /// Returns the type to be used for the index operand of:
468 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
469 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
473
474 /// Returns the type to be used for the index operand of:
475 /// G_INSERT_VECTOR_ELT, G_EXTRACT_VECTOR_ELT,
476 /// G_INSERT_SUBVECTOR, and G_EXTRACT_SUBVECTOR
479 }
480
481 /// Returns the type to be used for the EVL/AVL operand of VP nodes:
482 /// ISD::VP_UDIV, ISD::VP_SDIV, etc. It must be a legal scalar integer type,
483 /// and must be at least as large as i32. The EVL is implicitly zero-extended
484 /// to any larger type.
485 virtual MVT getVPExplicitVectorLengthTy() const { return MVT::i32; }
486
487 /// This callback is used to inspect load/store instructions and add
488 /// target-specific MachineMemOperand flags to them. The default
489 /// implementation does nothing.
493
494 /// This callback is used to inspect load/store SDNode.
495 /// The default implementation does nothing.
500
501 MachineMemOperand::Flags getLoadMemOperandFlags(
502 const LoadInst &LI, const DataLayout &DL, AssumptionCache *AC = nullptr,
503 const TargetLibraryInfo *LibInfo = nullptr,
505 MachineMemOperand::Flags getStoreMemOperandFlags(const StoreInst &SI,
506 const DataLayout &DL) const;
507 MachineMemOperand::Flags getAtomicMemOperandFlags(const Instruction &AI,
508 const DataLayout &DL) const;
510 getVPIntrinsicMemOperandFlags(const VPIntrinsic &VPIntrin) const;
511
512 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
513 return true;
514 }
515
516 /// Return true if the @llvm.get.active.lane.mask intrinsic should be expanded
517 /// using generic code in SelectionDAGBuilder.
518 virtual bool shouldExpandGetActiveLaneMask(EVT VT, EVT OpVT) const {
519 return true;
520 }
521
522 virtual bool shouldExpandGetVectorLength(EVT CountVT, unsigned VF,
523 bool IsScalable) const {
524 return true;
525 }
526
527 /// Return the minimum number of bits required to hold the maximum possible
528 /// number of trailing zero vector elements.
529 unsigned getBitWidthForCttzElements(EVT RetVT, ElementCount EC,
530 bool ZeroIsPoison,
531 const ConstantRange *VScaleRange) const;
532
533 // Return true if op(vecreduce(x), vecreduce(y)) should be reassociated to
534 // vecreduce(op(x, y)) for the reduction opcode RedOpc.
535 virtual bool shouldReassociateReduction(unsigned RedOpc, EVT VT) const {
536 return true;
537 }
538
539 /// Return true if it is profitable to convert a select of FP constants into
540 /// a constant pool load whose address depends on the select condition. The
541 /// parameter may be used to differentiate a select with FP compare from
542 /// integer compare.
543 virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
544 return true;
545 }
546
547 /// Does the target have multiple (allocatable) condition registers that
548 /// can be used to store the results of comparisons for use by selects
549 /// and conditional branches. With multiple condition registers, the code
550 /// generator will not aggressively sink comparisons into the blocks of their
551 /// users. \p VT is the type of the condition value, e.g. the type of the
552 /// result of a comparison.
553 virtual bool hasMultipleConditionRegisters(EVT VT) const { return false; }
554
555 /// Return true if the target has BitExtract instructions.
556 bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
557
558 /// Return the preferred vector type legalization action.
561 // The default action for one element vectors is to scalarize
563 return TypeScalarizeVector;
564 // The default action for an odd-width vector is to widen.
565 if (!VT.isPow2VectorType())
566 return TypeWidenVector;
567 // The default action for other vectors is to promote
568 return TypePromoteInteger;
569 }
570
571 // Return true if, for soft-promoted half, the half type should be passed to
572 // and returned from functions as f32. The default behavior is to pass as
573 // i16. If soft-promoted half is not used, this function is ignored and
574 // values are always passed and returned as f32.
575 virtual bool useFPRegsForHalfType() const { return false; }
576
577 // There are two general methods for expanding a BUILD_VECTOR node:
578 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
579 // them together.
580 // 2. Build the vector on the stack and then load it.
581 // If this function returns true, then method (1) will be used, subject to
582 // the constraint that all of the necessary shuffles are legal (as determined
583 // by isShuffleMaskLegal). If this function returns false, then method (2) is
584 // always used. The vector type, and the number of defined values, are
585 // provided.
586 virtual bool
588 unsigned DefinedValues) const {
589 return DefinedValues < 3;
590 }
591
592 /// Return true if integer divide is usually cheaper than a sequence of
593 /// several shifts, adds, and multiplies for this target.
594 /// The definition of "cheaper" may depend on whether we're optimizing
595 /// for speed or for size.
596 virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
597
598 /// Return true if the target can handle a standalone remainder operation.
599 virtual bool hasStandaloneRem(EVT VT) const {
600 return true;
601 }
602
603 /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
604 virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
605 // Default behavior is to replace SQRT(X) with X*RSQRT(X).
606 return false;
607 }
608
609 /// Reciprocal estimate status values used by the functions below.
614 };
615
616 /// Return a ReciprocalEstimate enum value for a square root of the given type
617 /// based on the function's attributes. If the operation is not overridden by
618 /// the function's attributes, "Unspecified" is returned and target defaults
619 /// are expected to be used for instruction selection.
620 int getRecipEstimateSqrtEnabled(EVT VT, const Function &F) const;
621
622 /// Return a ReciprocalEstimate enum value for a division of the given type
623 /// based on the function's attributes. If the operation is not overridden by
624 /// the function's attributes, "Unspecified" is returned and target defaults
625 /// are expected to be used for instruction selection.
626 int getRecipEstimateDivEnabled(EVT VT, const Function &MF) const;
627
628 /// Return the refinement step count for a square root of the given type based
629 /// on the function's attributes. If the operation is not overridden by
630 /// the function's attributes, "Unspecified" is returned and target defaults
631 /// are expected to be used for instruction selection.
632 int getSqrtRefinementSteps(EVT VT, const Function &MF) const;
633
634 /// Return the refinement step count for a division of the given type based
635 /// on the function's attributes. If the operation is not overridden by
636 /// the function's attributes, "Unspecified" is returned and target defaults
637 /// are expected to be used for instruction selection.
638 int getDivRefinementSteps(EVT VT, const Function &MF) const;
639
640 /// Returns true if target has indicated at least one type should be bypassed.
641 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
642
643 /// Returns map of slow types for division or remainder with corresponding
644 /// fast types
646 return BypassSlowDivWidths;
647 }
648
649 /// Return true if Flow Control is an expensive operation that should be
650 /// avoided.
651 bool isJumpExpensive() const { return JumpIsExpensive; }
652
653 // Costs parameters used by
654 // SelectionDAGBuilder::shouldKeepJumpConditionsTogether.
655 // shouldKeepJumpConditionsTogether will use these parameter value to
656 // determine if two conditions in the form `br (and/or cond1, cond2)` should
657 // be split into two branches or left as one.
658 //
659 // BaseCost is the cost threshold (in latency). If the estimated latency of
660 // computing both `cond1` and `cond2` is below the cost of just computing
661 // `cond1` + BaseCost, the two conditions will be kept together. Otherwise
662 // they will be split.
663 //
664 // LikelyBias increases BaseCost if branch probability info indicates that it
665 // is likely that both `cond1` and `cond2` will be computed.
666 //
667 // UnlikelyBias decreases BaseCost if branch probability info indicates that
668 // it is likely that both `cond1` and `cond2` will be computed.
669 //
670 // Set any field to -1 to make it ignored (setting BaseCost to -1 results in
671 // `shouldKeepJumpConditionsTogether` always returning false).
677 // Return params for deciding if we should keep two branch conditions merged
678 // or split them into two separate branches.
679 // Arg0: The binary op joining the two conditions (and/or).
680 // Arg1: The first condition (cond1)
681 // Arg2: The second condition (cond2)
682 // Arg3: The containing function.
683 virtual CondMergingParams
685 const Value *, const Function *) const {
686 // -1 will always result in splitting.
687 return {-1, -1, -1};
688 }
689
690 /// Return true if selects are only cheaper than branches if the branch is
691 /// unlikely to be predicted right.
695
696 virtual bool fallBackToDAGISel(const Instruction &Inst) const {
697 return false;
698 }
699
700 /// Return true if the following transform is beneficial:
701 /// fold (conv (load x)) -> (load (conv*)x)
702 /// On architectures that don't natively support some vector loads
703 /// efficiently, casting the load to a smaller vector of larger types and
704 /// loading is more efficient, however, this can be undone by optimizations in
705 /// dag combiner.
706 virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
707 const SelectionDAG &DAG,
708 const MachineMemOperand &MMO) const;
709
710 /// Return true if the following transform is beneficial:
711 /// (store (y (conv x)), y*)) -> (store x, (x*))
712 virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT,
713 const SelectionDAG &DAG,
714 const MachineMemOperand &MMO) const {
715 // Default to the same logic as loads.
716 return isLoadBitCastBeneficial(StoreVT, BitcastVT, DAG, MMO);
717 }
718
719 /// Return true if it is expected to be cheaper to do a store of vector
720 /// constant with the given size and type for the address space than to
721 /// store the individual scalar element constants.
722 virtual bool storeOfVectorConstantIsCheap(bool IsZero, EVT MemVT,
723 unsigned NumElem,
724 unsigned AddrSpace) const {
725 return IsZero;
726 }
727
728 /// Allow store merging for the specified type after legalization in addition
729 /// to before legalization. This may transform stores that do not exist
730 /// earlier (for example, stores created from intrinsics).
731 virtual bool mergeStoresAfterLegalization(EVT MemVT) const {
732 return true;
733 }
734
735 /// Returns if it's reasonable to merge stores to MemVT size.
736 virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
737 const MachineFunction &MF) const {
738 return true;
739 }
740
741 /// Return true if it is cheap to speculate a call to intrinsic cttz.
742 virtual bool isCheapToSpeculateCttz(Type *Ty) const {
743 return false;
744 }
745
746 /// Return true if it is cheap to speculate a call to intrinsic ctlz.
747 virtual bool isCheapToSpeculateCtlz(Type *Ty) const {
748 return false;
749 }
750
751 /// Return true if ctlz instruction is fast.
752 virtual bool isCtlzFast() const {
753 return false;
754 }
755
756 /// Return true if ctpop instruction is fast.
757 virtual bool isCtpopFast(EVT VT) const {
758 return isOperationLegal(ISD::CTPOP, VT);
759 }
760
761 /// Return the maximum number of "x & (x - 1)" operations that can be done
762 /// instead of deferring to a custom CTPOP.
763 virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const {
764 return 1;
765 }
766
767 /// Return true if instruction generated for equality comparison is folded
768 /// with instruction generated for signed comparison.
769 virtual bool isEqualityCmpFoldedWithSignedCmp() const { return true; }
770
771 /// Return true if the heuristic to prefer icmp eq zero should be used in code
772 /// gen prepare.
773 virtual bool preferZeroCompareBranch() const { return false; }
774
775 /// Return true if it is cheaper to split the store of a merged int val
776 /// from a pair of smaller values into multiple stores.
777 virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
778 return false;
779 }
780
781 /// Return if the target supports combining a
782 /// chain like:
783 /// \code
784 /// %andResult = and %val1, #mask
785 /// %icmpResult = icmp %andResult, 0
786 /// \endcode
787 /// into a single machine instruction of a form like:
788 /// \code
789 /// cc = test %register, #mask
790 /// \endcode
791 virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
792 return false;
793 }
794
795 /// Return true if it is valid to merge the TargetMMOFlags in two SDNodes.
796 virtual bool
798 const MemSDNode &NodeY) const {
799 return true;
800 }
801
802 /// Use bitwise logic to make pairs of compares more efficient. For example:
803 /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
804 /// This should be true when it takes more than one instruction to lower
805 /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
806 /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
807 virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
808 return false;
809 }
810
811 /// Return the preferred operand type if the target has a quick way to compare
812 /// integer values of the given size. Assume that any legal integer type can
813 /// be compared efficiently. Targets may override this to allow illegal wide
814 /// types to return a vector type if there is support to compare that type.
815 virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
816 MVT VT = MVT::getIntegerVT(NumBits);
818 }
819
820 /// Return true if the target should transform:
821 /// (X & Y) == Y ---> (~X & Y) == 0
822 /// (X & Y) != Y ---> (~X & Y) != 0
823 ///
824 /// This may be profitable if the target has a bitwise and-not operation that
825 /// sets comparison flags. A target may want to limit the transformation based
826 /// on the type of Y or if Y is a constant.
827 ///
828 /// Note that the transform will not occur if Y is known to be a power-of-2
829 /// because a mask and compare of a single bit can be handled by inverting the
830 /// predicate, for example:
831 /// (X & 8) == 8 ---> (X & 8) != 0
832 virtual bool hasAndNotCompare(SDValue Y) const {
833 return false;
834 }
835
836 /// Return true if the target has a bitwise and-not operation:
837 /// X = ~A & B
838 /// This can be used to simplify select or other instructions.
839 virtual bool hasAndNot(SDValue X) const {
840 // If the target has the more complex version of this operation, assume that
841 // it has this operation too.
842 return hasAndNotCompare(X);
843 }
844
845 /// Return true if the target has a bit-test instruction:
846 /// (X & (1 << Y)) ==/!= 0
847 /// This knowledge can be used to prevent breaking the pattern,
848 /// or creating it if it could be recognized.
849 virtual bool hasBitTest(SDValue X, SDValue Y) const { return false; }
850
851 /// There are two ways to clear extreme bits (either low or high):
852 /// Mask: x & (-1 << y) (the instcombine canonical form)
853 /// Shifts: x >> y << y
854 /// Return true if the variant with 2 variable shifts is preferred.
855 /// Return false if there is no preference.
857 // By default, let's assume that no one prefers shifts.
858 return false;
859 }
860
861 /// Return true if it is profitable to fold a pair of shifts into a mask.
862 /// This is usually true on most targets. But some targets, like Thumb1,
863 /// have immediate shift instructions, but no immediate "and" instruction;
864 /// this makes the fold unprofitable.
865 virtual bool shouldFoldConstantShiftPairToMask(const SDNode *N) const {
866 return true;
867 }
868
869 /// Should we tranform the IR-optimal check for whether given truncation
870 /// down into KeptBits would be truncating or not:
871 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
872 /// Into it's more traditional form:
873 /// ((%x << C) a>> C) dstcond %x
874 /// Return true if we should transform.
875 /// Return false if there is no preference.
877 unsigned KeptBits) const {
878 // By default, let's assume that no one prefers shifts.
879 return false;
880 }
881
882 /// Given the pattern
883 /// (X & (C l>>/<< Y)) ==/!= 0
884 /// return true if it should be transformed into:
885 /// ((X <</l>> Y) & C) ==/!= 0
886 /// WARNING: if 'X' is a constant, the fold may deadlock!
887 /// FIXME: we could avoid passing XC, but we can't use isConstOrConstSplat()
888 /// here because it can end up being not linked in.
891 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
892 SelectionDAG &DAG) const {
893 if (hasBitTest(X, Y)) {
894 // One interesting pattern that we'd want to form is 'bit test':
895 // ((1 << Y) & C) ==/!= 0
896 // But we also need to be careful not to try to reverse that fold.
897
898 // Is this '1 << Y' ?
899 if (OldShiftOpcode == ISD::SHL && CC->isOne())
900 return false; // Keep the 'bit test' pattern.
901
902 // Will it be '1 << Y' after the transform ?
903 if (XC && NewShiftOpcode == ISD::SHL && XC->isOne())
904 return true; // Do form the 'bit test' pattern.
905 }
906
907 // If 'X' is a constant, and we transform, then we will immediately
908 // try to undo the fold, thus causing endless combine loop.
909 // So by default, let's assume everyone prefers the fold
910 // iff 'X' is not a constant.
911 return !XC;
912 }
913
914 // Return true if its desirable to perform the following transform:
915 // (fmul C, (uitofp Pow2))
916 // -> (bitcast_to_FP (add (bitcast_to_INT C), Log2(Pow2) << mantissa))
917 // (fdiv C, (uitofp Pow2))
918 // -> (bitcast_to_FP (sub (bitcast_to_INT C), Log2(Pow2) << mantissa))
919 //
920 // This is only queried after we have verified the transform will be bitwise
921 // equals.
922 //
923 // SDNode *N : The FDiv/FMul node we want to transform.
924 // SDValue FPConst: The Float constant operand in `N`.
925 // SDValue IntPow2: The Integer power of 2 operand in `N`.
927 SDValue IntPow2) const {
928 // Default to avoiding fdiv which is often very expensive.
929 return N->getOpcode() == ISD::FDIV;
930 }
931
932 // Given:
933 // (icmp eq/ne (and X, C0), (shift X, C1))
934 // or
935 // (icmp eq/ne X, (rotate X, C1))
936
937 // If C0 is a mask or shifted mask and the shift amt (C1) isolates the
938 // remaining bits (i.e something like `(x64 & UINT32_MAX) == (x64 >> 32)`)
939 // Do we prefer the shift to be shift-right, shift-left, or rotate.
940 // Note: It's only valid to convert between the rotate and shift versions iff
941 // the shift-amt (`C1`) divides the bit width.
942 // If ShiftOpc (current Opcode) is returned, do nothing.
944 EVT VT, unsigned ShiftOpc, bool MayTransformRotate,
945 const APInt &ShiftOrRotateAmt,
946 const std::optional<APInt> &AndMask) const {
947 return ShiftOpc;
948 }
949
950 /// These two forms are equivalent:
951 /// sub %y, (xor %x, -1)
952 /// add (add %x, 1), %y
953 /// The variant with two add's is IR-canonical.
954 /// Some targets may prefer one to the other.
955 virtual bool preferIncOfAddToSubOfNot(EVT VT) const {
956 // By default, let's assume that everyone prefers the form with two add's.
957 return true;
958 }
959
960 // By default prefer folding (abs (sub nsw x, y)) -> abds(x, y). Some targets
961 // may want to avoid this to prevent loss of sub_nsw pattern.
962 virtual bool preferABDSToABSWithNSW(EVT VT) const {
963 return true;
964 }
965
966 // Return true if the target wants to transform Op(Splat(X)) -> Splat(Op(X))
967 virtual bool preferScalarizeSplat(SDNode *N) const { return true; }
968
969 // Return true if the target wants to transform:
970 // (TruncVT truncate(sext_in_reg(VT X, ExtVT))
971 // -> (TruncVT sext_in_reg(truncate(VT X), ExtVT))
972 // Some targets might prefer pre-sextinreg to improve truncation/saturation.
973 virtual bool preferSextInRegOfTruncate(EVT TruncVT, EVT VT, EVT ExtVT) const {
974 return true;
975 }
976
977 /// Return true if the target wants to use the optimization that
978 /// turns ext(promotableInst1(...(promotableInstN(load)))) into
979 /// promotedInst1(...(promotedInstN(ext(load)))).
981
982 /// Return true if the target can combine store(extractelement VectorTy,
983 /// Idx).
984 /// \p Cost[out] gives the cost of that transformation when this is true.
985 virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
986 unsigned &Cost) const {
987 return false;
988 }
989
990 /// Return true if the target shall perform extract vector element and store
991 /// given that the vector is known to be splat of constant.
992 /// \p Index[out] gives the index of the vector element to be extracted when
993 /// this is true.
995 Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const {
996 return false;
997 }
998
999 /// Return true if inserting a scalar into a variable element of an undef
1000 /// vector is more efficiently handled by splatting the scalar instead.
1001 virtual bool shouldSplatInsEltVarIndex(EVT) const {
1002 return false;
1003 }
1004
1005 /// Return true if target always benefits from combining into FMA for a
1006 /// given value type. This must typically return false on targets where FMA
1007 /// takes more cycles to execute than FADD.
1008 virtual bool enableAggressiveFMAFusion(EVT VT) const { return false; }
1009
1010 /// Return true if target always benefits from combining into FMA for a
1011 /// given value type. This must typically return false on targets where FMA
1012 /// takes more cycles to execute than FADD.
1013 virtual bool enableAggressiveFMAFusion(LLT Ty) const { return false; }
1014
1015 /// Return the ValueType of the result of SETCC operations.
1016 virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
1017 EVT VT) const;
1018
1019 /// Return the integer type returned by comparison libcalls. Comparison
1020 /// libcalls include floating point comparison calls, and Ordered/Unordered
1021 /// check calls on floating point numbers.
1023 return Type::getInt32Ty(Ctx);
1024 }
1025
1026 /// For targets without i1 registers, this gives the nature of the high-bits
1027 /// of boolean values held in types wider than i1.
1028 ///
1029 /// "Boolean values" are special true/false values produced by nodes like
1030 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
1031 /// Not to be confused with general values promoted from i1. Some cpus
1032 /// distinguish between vectors of boolean and scalars; the isVec parameter
1033 /// selects between the two kinds. For example on X86 a scalar boolean should
1034 /// be zero extended from i1, while the elements of a vector of booleans
1035 /// should be sign extended from i1.
1036 ///
1037 /// Some cpus also treat floating point types the same way as they treat
1038 /// vectors instead of the way they treat scalars.
1039 BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
1040 if (isVec)
1041 return BooleanVectorContents;
1042 return isFloat ? BooleanFloatContents : BooleanContents;
1043 }
1044
1046 return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
1047 }
1048
1049 /// Promote the given target boolean to a target boolean of the given type.
1050 /// A target boolean is an integer value, not necessarily of type i1, the bits
1051 /// of which conform to getBooleanContents.
1052 ///
1053 /// ValVT is the type of values that produced the boolean.
1055 EVT ValVT) const {
1056 SDLoc dl(Bool);
1057 EVT BoolVT =
1058 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ValVT);
1060 return DAG.getNode(ExtendCode, dl, BoolVT, Bool);
1061 }
1062
1063 /// Return target scheduling preference.
1065 return SchedPreferenceInfo;
1066 }
1067
1068 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
1069 /// for different nodes. This function returns the preference (or none) for
1070 /// the given node.
1072 return Sched::None;
1073 }
1074
1075 /// Return the register class that should be used for the specified value
1076 /// type.
1077 virtual const TargetRegisterClass *getRegClassFor(MVT VT, bool isDivergent = false) const {
1078 (void)isDivergent;
1079 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
1080 assert(RC && "This value type is not natively supported!");
1081 return RC;
1082 }
1083
1084 /// Allows target to decide about the register class of the
1085 /// specific value that is live outside the defining block.
1086 /// Returns true if the value needs uniform register class.
1088 const Value *) const {
1089 return false;
1090 }
1091
1092 /// Return the 'representative' register class for the specified value
1093 /// type.
1094 ///
1095 /// The 'representative' register class is the largest legal super-reg
1096 /// register class for the register class of the value type. For example, on
1097 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
1098 /// register class is GR64 on x86_64.
1099 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
1100 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
1101 return RC;
1102 }
1103
1104 /// Return the cost of the 'representative' register class for the specified
1105 /// value type.
1107 return RepRegClassCostForVT[VT.SimpleTy];
1108 }
1109
1110 /// Return the preferred strategy to legalize tihs SHIFT instruction, with
1111 /// \p ExpansionFactor being the recursion depth - how many expansion needed.
1117 virtual ShiftLegalizationStrategy
1119 unsigned ExpansionFactor) const {
1120 if (ExpansionFactor == 1)
1123 }
1124
1125 /// Return true if the target has native support for the specified value type.
1126 /// This means that it has a register that directly holds it without
1127 /// promotions or expansions.
1128 bool isTypeLegal(EVT VT) const {
1129 assert(!VT.isSimple() ||
1130 (unsigned)VT.getSimpleVT().SimpleTy < std::size(RegClassForVT));
1131 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
1132 }
1133
1135 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
1136 /// that indicates how instruction selection should deal with the type.
1137 LegalizeTypeAction ValueTypeActions[MVT::VALUETYPE_SIZE];
1138
1139 public:
1140 ValueTypeActionImpl() { llvm::fill(ValueTypeActions, TypeLegal); }
1141
1143 return ValueTypeActions[VT.SimpleTy];
1144 }
1145
1147 ValueTypeActions[VT.SimpleTy] = Action;
1148 }
1149 };
1150
1152 return ValueTypeActions;
1153 }
1154
1155 /// Return pair that represents the legalization kind (first) that needs to
1156 /// happen to EVT (second) in order to type-legalize it.
1157 ///
1158 /// First: how we should legalize values of this type, either it is already
1159 /// legal (return 'Legal') or we need to promote it to a larger type (return
1160 /// 'Promote'), or we need to expand it into multiple registers of smaller
1161 /// integer type (return 'Expand'). 'Custom' is not an option.
1162 ///
1163 /// Second: for types supported by the target, this is an identity function.
1164 /// For types that must be promoted to larger types, this returns the larger
1165 /// type to promote to. For integer types that are larger than the largest
1166 /// integer register, this contains one step in the expansion to get to the
1167 /// smaller register. For illegal floating point types, this returns the
1168 /// integer type to transform to.
1169 LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
1170
1171 /// Return how we should legalize values of this type, either it is already
1172 /// legal (return 'Legal') or we need to promote it to a larger type (return
1173 /// 'Promote'), or we need to expand it into multiple registers of smaller
1174 /// integer type (return 'Expand'). 'Custom' is not an option.
1176 return getTypeConversion(Context, VT).first;
1177 }
1179 return ValueTypeActions.getTypeAction(VT);
1180 }
1181
1182 /// For types supported by the target, this is an identity function. For
1183 /// types that must be promoted to larger types, this returns the larger type
1184 /// to promote to. For integer types that are larger than the largest integer
1185 /// register, this contains one step in the expansion to get to the smaller
1186 /// register. For illegal floating point types, this returns the integer type
1187 /// to transform to.
1188 virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
1189 return getTypeConversion(Context, VT).second;
1190 }
1191
1192 /// Perform getTypeToTransformTo repeatedly until a legal type is obtained.
1193 /// Useful for vector operations that might take multiple steps to legalize.
1195 EVT LegalVT = getTypeToTransformTo(Context, VT);
1196 while (LegalVT != VT) {
1197 VT = LegalVT;
1198 LegalVT = getTypeToTransformTo(Context, VT);
1199 }
1200 return LegalVT;
1201 }
1202
1203 /// For types supported by the target, this is an identity function. For
1204 /// types that must be expanded (i.e. integer types that are larger than the
1205 /// largest integer register or illegal floating point types), this returns
1206 /// the largest legal type it will be expanded to.
1207 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
1208 assert(!VT.isVector());
1209 while (true) {
1210 switch (getTypeAction(Context, VT)) {
1211 case TypeLegal:
1212 return VT;
1213 case TypeExpandInteger:
1214 VT = getTypeToTransformTo(Context, VT);
1215 break;
1216 default:
1217 llvm_unreachable("Type is not legal nor is it to be expanded!");
1218 }
1219 }
1220 }
1221
1222 /// Vector types are broken down into some number of legal first class types.
1223 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
1224 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
1225 /// turns into 4 EVT::i32 values with both PPC and X86.
1226 ///
1227 /// This method returns the number of registers needed, and the VT for each
1228 /// register. It also returns the VT and quantity of the intermediate values
1229 /// before they are promoted/expanded.
1231 EVT &IntermediateVT,
1232 unsigned &NumIntermediates,
1233 MVT &RegisterVT) const {
1234 return getVectorTypeBreakdownImpl(Context, VT, IntermediateVT,
1235 NumIntermediates, RegisterVT,
1236 /*ForCallingConv=*/false);
1237 }
1238
1239 /// Return true if fixed-length, non-power-of-two vectors should be broken
1240 /// down into legal vector parts instead of scalars for internal values.
1242 return false;
1243 }
1244
1245 bool shouldUseDynamicVectorTypeBreakdown(EVT VT, bool ForCallingConv) const {
1246 return preferVectorizedNonPowerOfTwoTypeBreakdown() && !ForCallingConv &&
1247 VT.isFixedLengthVector() &&
1249 }
1250
1251 /// Certain targets such as MIPS require that some types such as vectors are
1252 /// always broken down into scalars in some contexts. This occurs even if the
1253 /// vector type is legal.
1255 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
1256 unsigned &NumIntermediates, MVT &RegisterVT) const {
1257 return getVectorTypeBreakdownImpl(Context, VT, IntermediateVT,
1258 NumIntermediates, RegisterVT,
1259 /*ForCallingConv=*/true);
1260 }
1261
1263 unsigned opc = 0; // target opcode
1264 EVT memVT; // memory VT
1265
1266 // value representing memory location
1268
1269 // Fallback address space for use if ptrVal is nullptr. std::nullopt means
1270 // unknown address space.
1271 std::optional<unsigned> fallbackAddressSpace;
1272
1273 int offset = 0; // offset off of ptrVal
1274 uint64_t size = 0; // the size of the memory location
1275 // (taken from memVT if zero)
1276 MaybeAlign align = Align(1); // alignment
1277
1282 IntrinsicInfo() = default;
1283 };
1284
1285 /// Given an intrinsic, checks if on the target the intrinsic will need to map
1286 /// to a MemIntrinsicNode (touches memory). If this is the case, it stores
1287 /// the intrinsic information into the IntrinsicInfo vector passed to the
1288 /// function. The vector may contain multiple entries for intrinsics that
1289 /// access multiple memory locations.
1291 const CallBase &I, MachineFunction &MF,
1292 unsigned Intrinsic) const {}
1293
1294 /// Returns true if the target can instruction select the specified FP
1295 /// immediate natively. If false, the legalizer will materialize the FP
1296 /// immediate as a load from a constant pool.
1297 virtual bool isFPImmLegal(const APFloat & /*Imm*/, EVT /*VT*/,
1298 bool ForCodeSize = false) const {
1299 return false;
1300 }
1301
1302 /// Targets can use this to indicate that they only support *some*
1303 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
1304 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
1305 /// legal.
1306 virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
1307 return true;
1308 }
1309
1310 /// Returns true if the operation can trap for the value type.
1311 ///
1312 /// VT must be a legal type. By default, we optimistically assume most
1313 /// operations don't trap except for integer divide and remainder.
1314 virtual bool canOpTrap(unsigned Op, EVT VT) const;
1315
1316 /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
1317 /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
1318 /// constant pool entry.
1320 EVT /*VT*/) const {
1321 return false;
1322 }
1323
1324 /// How to legalize this custom operation?
1326 return Legal;
1327 }
1328
1329 /// Return how this operation should be treated: either it is legal, needs to
1330 /// be promoted to a larger size, needs to be expanded to some other code
1331 /// sequence, or the target has a custom expander for it.
1333 // If a target-specific SDNode requires legalization, require the target
1334 // to provide custom legalization for it.
1335 if (Op >= std::size(OpActions[0]))
1336 return Custom;
1337 if (VT.isExtended())
1338 return Expand;
1339 return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
1340 }
1341
1342 /// Custom method defined by each target to indicate if an operation which
1343 /// may require a scale is supported natively by the target.
1344 /// If not, the operation is illegal.
1345 virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
1346 unsigned Scale) const {
1347 return false;
1348 }
1349
1350 /// Some fixed point operations may be natively supported by the target but
1351 /// only for specific scales. This method allows for checking
1352 /// if the width is supported by the target for a given operation that may
1353 /// depend on scale.
1355 unsigned Scale) const {
1356 auto Action = getOperationAction(Op, VT);
1357 if (Action != Legal)
1358 return Action;
1359
1360 // This operation is supported in this type but may only work on specific
1361 // scales.
1362 bool Supported;
1363 switch (Op) {
1364 default:
1365 llvm_unreachable("Unexpected fixed point operation.");
1366 case ISD::SMULFIX:
1367 case ISD::SMULFIXSAT:
1368 case ISD::UMULFIX:
1369 case ISD::UMULFIXSAT:
1370 case ISD::SDIVFIX:
1371 case ISD::SDIVFIXSAT:
1372 case ISD::UDIVFIX:
1373 case ISD::UDIVFIXSAT:
1374 Supported = isSupportedFixedPointOperation(Op, VT, Scale);
1375 break;
1376 }
1377
1378 return Supported ? Action : Expand;
1379 }
1380
1381 // If Op is a strict floating-point operation, return the result
1382 // of getOperationAction for the equivalent non-strict operation.
1384 unsigned EqOpc;
1385 switch (Op) {
1386 default: llvm_unreachable("Unexpected FP pseudo-opcode");
1387#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1388 case ISD::STRICT_##DAGN: EqOpc = ISD::DAGN; break;
1389#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1390 case ISD::STRICT_##DAGN: EqOpc = ISD::SETCC; break;
1391#include "llvm/IR/ConstrainedOps.def"
1392 }
1393
1394 return getOperationAction(EqOpc, VT);
1395 }
1396
1397 /// Return true if the specified operation is legal on this target or can be
1398 /// made legal with custom lowering. This is used to help guide high-level
1399 /// lowering decisions. LegalOnly is an optional convenience for code paths
1400 /// traversed pre and post legalisation.
1402 bool LegalOnly = false) const {
1403 if (LegalOnly)
1404 return isOperationLegal(Op, VT);
1405
1406 return (VT == MVT::Other || isTypeLegal(VT)) &&
1407 (getOperationAction(Op, VT) == Legal ||
1408 getOperationAction(Op, VT) == Custom);
1409 }
1410
1411 /// Return true if the specified operation is legal on this target or can be
1412 /// made legal using promotion. This is used to help guide high-level lowering
1413 /// decisions. LegalOnly is an optional convenience for code paths traversed
1414 /// pre and post legalisation.
1416 bool LegalOnly = false) const {
1417 if (LegalOnly)
1418 return isOperationLegal(Op, VT);
1419
1420 return (VT == MVT::Other || isTypeLegal(VT)) &&
1421 (getOperationAction(Op, VT) == Legal ||
1422 getOperationAction(Op, VT) == Promote);
1423 }
1424
1425 /// Return true if the specified operation is legal on this target or can be
1426 /// made legal with custom lowering or using promotion. This is used to help
1427 /// guide high-level lowering decisions. LegalOnly is an optional convenience
1428 /// for code paths traversed pre and post legalisation.
1430 bool LegalOnly = false) const {
1431 if (LegalOnly)
1432 return isOperationLegal(Op, VT);
1433
1434 return (VT == MVT::Other || isTypeLegal(VT)) &&
1435 (getOperationAction(Op, VT) == Legal ||
1436 getOperationAction(Op, VT) == Custom ||
1437 getOperationAction(Op, VT) == Promote);
1438 }
1439
1440 /// Return true if the operation uses custom lowering, regardless of whether
1441 /// the type is legal or not.
1442 bool isOperationCustom(unsigned Op, EVT VT) const {
1443 return getOperationAction(Op, VT) == Custom;
1444 }
1445
1446 /// Return true if lowering to a jump table is allowed.
1447 virtual bool areJTsAllowed(const Function *Fn) const {
1448 if (Fn->getFnAttribute("no-jump-tables").getValueAsBool())
1449 return false;
1450
1451 return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1453 }
1454
1455 /// Check whether the range [Low,High] fits in a machine word.
1456 bool rangeFitsInWord(const APInt &Low, const APInt &High,
1457 const DataLayout &DL) const {
1458 // FIXME: Using the pointer type doesn't seem ideal.
1459 uint64_t BW = DL.getIndexSizeInBits(0u);
1460 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
1461 return Range <= BW;
1462 }
1463
1464 /// Return true if lowering to a jump table is suitable for a set of case
1465 /// clusters which may contain \p NumCases cases, \p Range range of values.
1466 virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
1468 BlockFrequencyInfo *BFI) const;
1469
1470 /// Returns preferred type for switch condition.
1471 virtual MVT getPreferredSwitchConditionType(LLVMContext &Context,
1472 EVT ConditionVT) const;
1473
1474 /// Return true if lowering to a bit test is suitable for a set of case
1475 /// clusters which contains \p NumDests unique destinations, \p Low and
1476 /// \p High as its lowest and highest case values, and expects \p NumCmps
1477 /// case value comparisons. Check if the number of destinations, comparison
1478 /// metric, and range are all suitable.
1481 const APInt &Low, const APInt &High, const DataLayout &DL) const {
1482 // FIXME: I don't think NumCmps is the correct metric: a single case and a
1483 // range of cases both require only one branch to lower. Just looking at the
1484 // number of clusters and destinations should be enough to decide whether to
1485 // build bit tests.
1486
1487 // To lower a range with bit tests, the range must fit the bitwidth of a
1488 // machine word.
1489 if (!rangeFitsInWord(Low, High, DL))
1490 return false;
1491
1492 unsigned NumDests = DestCmps.size();
1493 unsigned NumCmps = 0;
1494 unsigned int MaxBitTestEntry = 0;
1495 for (auto &DestCmp : DestCmps) {
1496 NumCmps += DestCmp.second;
1497 if (DestCmp.second > MaxBitTestEntry)
1498 MaxBitTestEntry = DestCmp.second;
1499 }
1500
1501 // Comparisons might be cheaper for small number of comparisons, which can
1502 // be Arch Target specific.
1503 if (MaxBitTestEntry < getMinimumBitTestCmps())
1504 return false;
1505
1506 // Decide whether it's profitable to lower this range with bit tests. Each
1507 // destination requires a bit test and branch, and there is an overall range
1508 // check branch. For a small number of clusters, separate comparisons might
1509 // be cheaper, and for many destinations, splitting the range might be
1510 // better.
1511 return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
1512 (NumDests == 3 && NumCmps >= 6);
1513 }
1514
1515 /// Return true if the specified operation is illegal on this target or
1516 /// unlikely to be made legal with custom lowering. This is used to help guide
1517 /// high-level lowering decisions.
1518 bool isOperationExpand(unsigned Op, EVT VT) const {
1519 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
1520 }
1521
1522 /// Return true if the specified operation is legal on this target.
1523 bool isOperationLegal(unsigned Op, EVT VT) const {
1524 return (VT == MVT::Other || isTypeLegal(VT)) &&
1525 getOperationAction(Op, VT) == Legal;
1526 }
1527
1528 bool isOperationExpandOrLibCall(unsigned Op, EVT VT) const {
1529 return isOperationExpand(Op, VT) || getOperationAction(Op, VT) == LibCall;
1530 }
1531
1532 /// Returns an alternative action to use when the coarser lookups (configured
1533 /// through `setLoadExtAction` and `setAtomicLoadExtAction`) yield
1534 /// `LegalizeAction::Custom`. Allows targets to use builtin behaviors (e.g.
1535 /// Legal, Promote) specialized by Alignment and AddrSpace, rather than just
1536 /// types.
1537 virtual LegalizeAction
1538 getCustomLoadAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace,
1539 unsigned ExtType, bool Atomic) const {
1541 }
1542
1543 /// Return how this load with extension should be treated: either it is legal,
1544 /// needs to be promoted to a larger size, needs to be expanded to some other
1545 /// code sequence, or the target has a custom expander for it.
1546 LegalizeAction getLoadAction(EVT ValVT, EVT MemVT, Align Alignment,
1547 unsigned AddrSpace, unsigned ExtType,
1548 bool Atomic) const {
1549 if (ValVT.isExtended() || MemVT.isExtended())
1550 return Expand;
1551 unsigned ValI = (unsigned)ValVT.getSimpleVT().SimpleTy;
1552 unsigned MemI = (unsigned)MemVT.getSimpleVT().SimpleTy;
1554 MemI < MVT::VALUETYPE_SIZE && "Table isn't big enough!");
1555 unsigned Shift = 4 * ExtType;
1556
1557 LegalizeAction Action;
1558 if (Atomic) {
1559 Action =
1560 (LegalizeAction)((AtomicLoadExtActions[ValI][MemI] >> Shift) & 0xf);
1561 assert((Action == Legal || Action == Expand) &&
1562 "Unsupported atomic load extension action.");
1563 } else {
1564 Action = (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
1565 }
1566
1567 if (Action == LegalizeAction::Custom) {
1568 return getCustomLoadAction(ValVT, MemVT, Alignment, AddrSpace, ExtType,
1569 Atomic);
1570 }
1571
1572 return Action;
1573 }
1574
1575 /// Return true if the specified load with extension is legal on this target.
1576 bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace,
1577 unsigned ExtType, bool Atomic) const {
1578 return getLoadAction(ValVT, MemVT, Alignment, AddrSpace, ExtType, Atomic) ==
1579 Legal;
1580 }
1581
1582 /// Return true if the specified load with extension is legal or custom
1583 /// on this target.
1584 bool isLoadLegalOrCustom(EVT ValVT, EVT MemVT, Align Alignment,
1585 unsigned AddrSpace, unsigned ExtType,
1586 bool Atomic) const {
1587 LegalizeAction Action =
1588 getLoadAction(ValVT, MemVT, Alignment, AddrSpace, ExtType, Atomic);
1589 return Action == Legal || Action == Custom;
1590 }
1591
1592 /// Returns an alternative action to use when the coarser lookups (configured
1593 /// through `setTruncStoreAction` yield
1594 /// `LegalizeAction::Custom`. Allows targets to use builtin behaviors (e.g.
1595 /// Legal, Promote) specialized by Alignment and AddrSpace, rather than just
1596 /// types.
1598 Align Alignment,
1599 unsigned AddrSpace) const {
1601 }
1602
1603 /// Return how this store with truncation should be treated: either it is
1604 /// legal, needs to be promoted to a larger size, needs to be expanded to some
1605 /// other code sequence, or the target has a custom expander for it.
1607 unsigned AddrSpace) const {
1608 if (ValVT.isExtended() || MemVT.isExtended())
1609 return Expand;
1610 unsigned ValI = (unsigned)ValVT.getSimpleVT().SimpleTy;
1611 unsigned MemI = (unsigned)MemVT.getSimpleVT().SimpleTy;
1613 "Table isn't big enough!");
1614
1615 LegalizeAction Action = TruncStoreActions[ValI][MemI];
1616
1617 if (Action == LegalizeAction::Custom) {
1618 return getCustomTruncStoreAction(ValVT, MemVT, Alignment, AddrSpace);
1619 }
1620
1621 return Action;
1622 }
1623
1624 /// Return true if the specified store with truncation is legal on this
1625 /// target.
1626 bool isTruncStoreLegal(EVT ValVT, EVT MemVT, Align Alignment,
1627 unsigned AddrSpace) const {
1628 return isTypeLegal(ValVT) &&
1629 getTruncStoreAction(ValVT, MemVT, Alignment, AddrSpace) == Legal;
1630 }
1631
1632 /// Return true if the specified store with truncation has solution on this
1633 /// target.
1634 bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT, Align Alignment,
1635 unsigned AddrSpace) const {
1636 if (!isTypeLegal(ValVT))
1637 return false;
1638
1639 LegalizeAction Action =
1640 getTruncStoreAction(ValVT, MemVT, Alignment, AddrSpace);
1641 return (Action == Legal || Action == Custom);
1642 }
1643
1644 virtual bool canCombineTruncStore(EVT ValVT, EVT MemVT, Align Alignment,
1645 unsigned AddrSpace, bool LegalOnly) const {
1646 if (LegalOnly)
1647 return isTruncStoreLegal(ValVT, MemVT, Alignment, AddrSpace);
1648
1649 return isTruncStoreLegalOrCustom(ValVT, MemVT, Alignment, AddrSpace);
1650 }
1651
1652 /// Return how the indexed load should be treated: either it is legal, needs
1653 /// to be promoted to a larger size, needs to be expanded to some other code
1654 /// sequence, or the target has a custom expander for it.
1655 LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
1656 return getIndexedModeAction(IdxMode, VT, IMAB_Load);
1657 }
1658
1659 /// Return true if the specified indexed load is legal on this target.
1660 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
1661 return VT.isSimple() &&
1662 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1663 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1664 }
1665
1666 /// Return how the indexed store should be treated: either it is legal, needs
1667 /// to be promoted to a larger size, needs to be expanded to some other code
1668 /// sequence, or the target has a custom expander for it.
1669 LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
1670 return getIndexedModeAction(IdxMode, VT, IMAB_Store);
1671 }
1672
1673 /// Return true if the specified indexed load is legal on this target.
1674 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
1675 return VT.isSimple() &&
1676 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1677 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1678 }
1679
1680 /// Return how the indexed load should be treated: either it is legal, needs
1681 /// to be promoted to a larger size, needs to be expanded to some other code
1682 /// sequence, or the target has a custom expander for it.
1683 LegalizeAction getIndexedMaskedLoadAction(unsigned IdxMode, MVT VT) const {
1684 return getIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad);
1685 }
1686
1687 /// Return true if the specified indexed load is legal on this target.
1688 bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const {
1689 return VT.isSimple() &&
1690 (getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1692 }
1693
1694 /// Return how the indexed store should be treated: either it is legal, needs
1695 /// to be promoted to a larger size, needs to be expanded to some other code
1696 /// sequence, or the target has a custom expander for it.
1697 LegalizeAction getIndexedMaskedStoreAction(unsigned IdxMode, MVT VT) const {
1698 return getIndexedModeAction(IdxMode, VT, IMAB_MaskedStore);
1699 }
1700
1701 /// Return true if the specified indexed load is legal on this target.
1702 bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const {
1703 return VT.isSimple() &&
1704 (getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1706 }
1707
1708 /// Returns true if the index type for a masked gather/scatter requires
1709 /// extending
1710 virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const { return false; }
1711
1712 // Returns true if Extend can be folded into the index of a masked gathers/scatters
1713 // on this target.
1714 virtual bool shouldRemoveExtendFromGSIndex(SDValue Extend, EVT DataVT) const {
1715 return false;
1716 }
1717
1718 // Return true if the target supports a scatter/gather instruction with
1719 // indices which are scaled by the particular value. Note that all targets
1720 // must by definition support scale of 1.
1722 uint64_t ElemSize) const {
1723 // MGATHER/MSCATTER are only required to support scaling by one or by the
1724 // element size.
1725 if (Scale != ElemSize && Scale != 1)
1726 return false;
1727 return true;
1728 }
1729
1730 /// Return how the condition code should be treated: either it is legal, needs
1731 /// to be expanded to some other code sequence, or the target has a custom
1732 /// expander for it.
1735 assert((unsigned)CC < std::size(CondCodeActions) &&
1736 ((unsigned)VT.SimpleTy >> 3) < std::size(CondCodeActions[0]) &&
1737 "Table isn't big enough!");
1738 // See setCondCodeAction for how this is encoded.
1739 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1740 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
1741 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
1742 assert(Action != Promote && "Can't promote condition code!");
1743 return Action;
1744 }
1745
1746 /// Return true if the specified condition code is legal for a comparison of
1747 /// the specified types on this target.
1748 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
1749 return getCondCodeAction(CC, VT) == Legal;
1750 }
1751
1752 /// Return true if the specified condition code is legal or custom for a
1753 /// comparison of the specified types on this target.
1755 return getCondCodeAction(CC, VT) == Legal ||
1756 getCondCodeAction(CC, VT) == Custom;
1757 }
1758
1759 /// Return how a PARTIAL_REDUCE_U/SMLA node with Acc type AccVT and Input type
1760 /// InputVT should be treated. Either it's legal, needs to be promoted to a
1761 /// larger size, needs to be expanded to some other code sequence, or the
1762 /// target has a custom expander for it.
1764 EVT InputVT) const {
1767 PartialReduceActionTypes Key = {Opc, AccVT.getSimpleVT().SimpleTy,
1768 InputVT.getSimpleVT().SimpleTy};
1769 auto It = PartialReduceMLAActions.find(Key);
1770 return It != PartialReduceMLAActions.end() ? It->second : Expand;
1771 }
1772
1773 /// Return true if a PARTIAL_REDUCE_U/SMLA node with the specified types is
1774 /// legal or custom for this target.
1776 EVT InputVT) const {
1777 LegalizeAction Action = getPartialReduceMLAAction(Opc, AccVT, InputVT);
1778 return Action == Legal || Action == Custom;
1779 }
1780
1781 /// Return how a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the
1782 /// given interleave factor and VT should be handled.
1784 EVT VT) const {
1786 VectorInterleaveActionKey Key = {Opc, Factor, VT.getSimpleVT().SimpleTy};
1787 auto It = VectorInterleaveActions.find(Key);
1788 return It != VectorInterleaveActions.end() ? It->second : Expand;
1789 }
1790
1791 /// Return true if a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the
1792 /// given interleave factor and fragment type is legal or custom.
1793 bool isVectorInterleaveLegalOrCustom(unsigned Opc, unsigned Factor,
1794 EVT VT) const {
1795 LegalizeAction Action = getVectorInterleaveAction(Opc, Factor, VT);
1796 return Action == Legal || Action == Custom;
1797 }
1798
1799 /// If the action for this operation is to promote, this method returns the
1800 /// ValueType to promote to.
1801 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
1803 "This operation isn't promoted!");
1804
1805 // See if this has an explicit type specified.
1806 std::map<std::pair<unsigned, MVT::SimpleValueType>,
1808 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1809 if (PTTI != PromoteToType.end()) return PTTI->second;
1810
1811 assert((VT.isInteger() || VT.isFloatingPoint()) &&
1812 "Cannot autopromote this type, add it with AddPromotedToType.");
1813
1814 uint64_t VTBits = VT.getScalarSizeInBits();
1815 MVT NVT = VT;
1816 do {
1817 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1818 assert(NVT.isInteger() == VT.isInteger() &&
1819 NVT.isFloatingPoint() == VT.isFloatingPoint() &&
1820 "Didn't find type to promote to!");
1821 } while (VTBits >= NVT.getScalarSizeInBits() || !isTypeLegal(NVT) ||
1822 getOperationAction(Op, NVT) == Promote);
1823 return NVT;
1824 }
1825
1827 bool AllowUnknown = false) const {
1828 return getValueType(DL, Ty, AllowUnknown);
1829 }
1830
1831 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1832 /// operations except for the pointer size. If AllowUnknown is true, this
1833 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1834 /// otherwise it will assert.
1836 bool AllowUnknown = false) const {
1837 // Lower scalar pointers to native pointer types.
1838 if (auto *PTy = dyn_cast<PointerType>(Ty))
1839 return getPointerTy(DL, PTy->getAddressSpace());
1840
1841 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1842 Type *EltTy = VTy->getElementType();
1843 // Lower vectors of pointers to native pointer types.
1844 EVT EltVT;
1845 if (auto *PTy = dyn_cast<PointerType>(EltTy))
1846 EltVT = getPointerTy(DL, PTy->getAddressSpace());
1847 else
1848 EltVT = EVT::getEVT(EltTy, false);
1849 return EVT::getVectorVT(Ty->getContext(), EltVT, VTy->getElementCount());
1850 }
1851
1852 return EVT::getEVT(Ty, AllowUnknown);
1853 }
1854
1856 bool AllowUnknown = false) const {
1857 // Lower scalar pointers to native pointer types.
1858 if (auto *PTy = dyn_cast<PointerType>(Ty))
1859 return getPointerMemTy(DL, PTy->getAddressSpace());
1860
1861 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1862 Type *EltTy = VTy->getElementType();
1863 EVT EltVT;
1864 if (auto *PTy = dyn_cast<PointerType>(EltTy))
1865 EltVT = getPointerMemTy(DL, PTy->getAddressSpace());
1866 else
1867 EltVT = EVT::getEVT(EltTy, false);
1868 return EVT::getVectorVT(Ty->getContext(), EltVT, VTy->getElementCount());
1869 }
1870
1871 return getValueType(DL, Ty, AllowUnknown);
1872 }
1873
1874
1875 /// Return the MVT corresponding to this LLVM type. See getValueType.
1877 bool AllowUnknown = false) const {
1878 return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1879 }
1880
1881 /// Returns the desired alignment for ByVal or InAlloca aggregate function
1882 /// arguments in the caller parameter area.
1883 virtual Align getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1884
1885 /// Return the type of registers that this ValueType will eventually require.
1886 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1887 return getRegisterTypeImpl(Context, VT, /*ForCallingConv=*/false);
1888 }
1889
1890 /// Return the number of registers that this ValueType will eventually
1891 /// require.
1892 ///
1893 /// This is one for any types promoted to live in larger registers, but may be
1894 /// more than one for types (like i64) that are split into pieces. For types
1895 /// like i140, which are first promoted then expanded, it is the number of
1896 /// registers needed to hold all the bits of the original type. For an i140
1897 /// on a 32 bit machine this means 5 registers.
1898 ///
1899 /// RegisterVT may be passed as a way to override the default settings, for
1900 /// instance with i128 inline assembly operands on SystemZ.
1901 virtual unsigned
1903 std::optional<MVT> RegisterVT = std::nullopt) const {
1904 return getNumRegistersImpl(Context, VT, /*ForCallingConv=*/false);
1905 }
1906
1907 /// Certain combinations of ABIs, Targets and features require that types
1908 /// are legal for some operations and not for other operations.
1909 /// For MIPS all vector types must be passed through the integer register set.
1911 CallingConv::ID CC, EVT VT) const {
1912 return getRegisterTypeImpl(Context, VT, /*ForCallingConv=*/true);
1913 }
1914
1915 /// Certain targets require unusual breakdowns of certain types. For MIPS,
1916 /// this occurs when a vector type is used, as vector are passed through the
1917 /// integer register set.
1919 CallingConv::ID CC,
1920 EVT VT) const {
1921 return getNumRegistersImpl(Context, VT, /*ForCallingConv=*/true);
1922 }
1923
1924 /// Certain targets have context sensitive alignment requirements, where one
1925 /// type has the alignment requirement of another type.
1927 const DataLayout &DL) const {
1928 return DL.getABITypeAlign(ArgTy);
1929 }
1930
1931 /// If true, then instruction selection should seek to shrink the FP constant
1932 /// of the specified type to a smaller type in order to save space and / or
1933 /// reduce runtime.
1934 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1935
1936 /// Return true if it is profitable to reduce a load to a smaller type.
1937 /// \p ByteOffset is only set if we know the pointer offset at compile time
1938 /// otherwise we should assume that additional pointer math is required.
1939 /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
1940 /// Example: (i16 (trunc (srl (i32 (load x)), 16)) -> i16 load x+2
1942 SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT,
1943 std::optional<unsigned> ByteOffset = std::nullopt) const {
1944 // By default, assume that it is cheaper to extract a subvector from a wide
1945 // vector load rather than creating multiple narrow vector loads.
1946 if (NewVT.isVector() && !SDValue(Load, 0).hasOneUse())
1947 return false;
1948
1949 return true;
1950 }
1951
1952 /// Return true (the default) if it is profitable to remove a sext_inreg(x)
1953 /// where the sext is redundant, and use x directly.
1954 virtual bool shouldRemoveRedundantExtend(SDValue Op) const { return true; }
1955
1956 /// Indicates if any padding is guaranteed to go at the most significant bits
1957 /// when storing the type to memory and the type size isn't equal to the store
1958 /// size.
1960 return VT.isScalarInteger() && !VT.isByteSized();
1961 }
1962
1963 /// When splitting a value of the specified type into parts, does the Lo
1964 /// or Hi part come first? This usually follows the endianness, except
1965 /// for ppcf128, where the Hi part always comes first.
1967 return DL.isBigEndian() || VT == MVT::ppcf128;
1968 }
1969
1970 /// If true, the target has custom DAG combine transformations that it can
1971 /// perform for the specified node.
1973 assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
1974 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1975 }
1976
1979 }
1980
1981 /// Returns the size of the platform's va_list object.
1982 virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1983 return getPointerTy(DL).getSizeInBits();
1984 }
1985
1986 /// Get maximum # of store operations permitted for llvm.memset
1987 ///
1988 /// This function returns the maximum number of store operations permitted
1989 /// to replace a call to llvm.memset. The value is set by the target at the
1990 /// performance threshold for such a replacement. If OptSize is true,
1991 /// return the limit for functions that have OptSize attribute.
1992 unsigned getMaxStoresPerMemset(bool OptSize) const;
1993
1994 /// Get maximum # of store operations permitted for llvm.memcpy
1995 ///
1996 /// This function returns the maximum number of store operations permitted
1997 /// to replace a call to llvm.memcpy. The value is set by the target at the
1998 /// performance threshold for such a replacement. If OptSize is true,
1999 /// return the limit for functions that have OptSize attribute.
2000 unsigned getMaxStoresPerMemcpy(bool OptSize) const;
2001
2002 /// \brief Get maximum # of store operations to be glued together
2003 ///
2004 /// This function returns the maximum number of store operations permitted
2005 /// to glue together during lowering of llvm.memcpy. The value is set by
2006 // the target at the performance threshold for such a replacement.
2007 virtual unsigned getMaxGluedStoresPerMemcpy() const {
2009 }
2010
2011 /// Get maximum # of load operations permitted for memcmp
2012 ///
2013 /// This function returns the maximum number of load operations permitted
2014 /// to replace a call to memcmp. The value is set by the target at the
2015 /// performance threshold for such a replacement. If OptSize is true,
2016 /// return the limit for functions that have OptSize attribute.
2017 unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
2019 }
2020
2021 /// Get maximum # of store operations permitted for llvm.memmove
2022 ///
2023 /// This function returns the maximum number of store operations permitted
2024 /// to replace a call to llvm.memmove. The value is set by the target at the
2025 /// performance threshold for such a replacement. If OptSize is true,
2026 /// return the limit for functions that have OptSize attribute.
2027 unsigned getMaxStoresPerMemmove(bool OptSize) const;
2028
2029 /// Determine if the target supports unaligned memory accesses.
2030 ///
2031 /// This function returns true if the target allows unaligned memory accesses
2032 /// of the specified type in the given address space. If true, it also returns
2033 /// a relative speed of the unaligned memory access in the last argument by
2034 /// reference. The higher the speed number the faster the operation comparing
2035 /// to a number returned by another such call. This is used, for example, in
2036 /// situations where an array copy/move/set is converted to a sequence of
2037 /// store operations. Its use helps to ensure that such replacements don't
2038 /// generate code that causes an alignment error (trap) on the target machine.
2040 EVT, unsigned AddrSpace = 0, Align Alignment = Align(1),
2042 unsigned * /*Fast*/ = nullptr) const {
2043 return false;
2044 }
2045
2046 /// LLT handling variant.
2048 LLT, unsigned AddrSpace = 0, Align Alignment = Align(1),
2050 unsigned * /*Fast*/ = nullptr) const {
2051 return false;
2052 }
2053
2054 /// This function returns true if the memory access is aligned or if the
2055 /// target allows this specific unaligned memory access. If the access is
2056 /// allowed, the optional final parameter returns a relative speed of the
2057 /// access (as defined by the target).
2058 bool allowsMemoryAccessForAlignment(
2059 LLVMContext &Context, const DataLayout &DL, EVT VT,
2060 unsigned AddrSpace = 0, Align Alignment = Align(1),
2062 unsigned *Fast = nullptr) const;
2063
2064 /// Return true if the memory access of this type is aligned or if the target
2065 /// allows this specific unaligned access for the given MachineMemOperand.
2066 /// If the access is allowed, the optional final parameter returns a relative
2067 /// speed of the access (as defined by the target).
2068 bool allowsMemoryAccessForAlignment(LLVMContext &Context,
2069 const DataLayout &DL, EVT VT,
2070 const MachineMemOperand &MMO,
2071 unsigned *Fast = nullptr) const;
2072
2073 /// Return true if the target supports a memory access of this type for the
2074 /// given address space and alignment. If the access is allowed, the optional
2075 /// final parameter returns the relative speed of the access (as defined by
2076 /// the target).
2077 virtual bool
2078 allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
2079 unsigned AddrSpace = 0, Align Alignment = Align(1),
2081 unsigned *Fast = nullptr) const;
2082
2083 /// Return true if the target supports a memory access of this type for the
2084 /// given MachineMemOperand. If the access is allowed, the optional
2085 /// final parameter returns the relative access speed (as defined by the
2086 /// target).
2087 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
2088 const MachineMemOperand &MMO,
2089 unsigned *Fast = nullptr) const;
2090
2091 /// LLT handling variant.
2092 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, LLT Ty,
2093 const MachineMemOperand &MMO,
2094 unsigned *Fast = nullptr) const;
2095
2096 /// Returns the target specific optimal type for load and store operations as
2097 /// a result of memset, memcpy, and memmove lowering.
2098 /// It returns EVT::Other if the type should be determined using generic
2099 /// target-independent logic.
2100 virtual EVT
2102 const AttributeList & /*FuncAttributes*/) const {
2103 return MVT::Other;
2104 }
2105
2106 /// LLT returning variant.
2107 virtual LLT
2109 const AttributeList & /*FuncAttributes*/) const {
2110 return LLT();
2111 }
2112
2113 /// Returns true if it's safe to use load / store of the specified type to
2114 /// expand memcpy / memset inline.
2115 ///
2116 /// This is mostly true for all types except for some special cases. For
2117 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
2118 /// fstpl which also does type conversion. Note the specified type doesn't
2119 /// have to be legal as the hook is used before type legalization.
2120 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
2121
2122 /// Return lower limit for number of blocks in a jump table.
2123 virtual unsigned getMinimumJumpTableEntries() const;
2124
2125 /// Return lower limit of the density in a jump table.
2126 unsigned getMinimumJumpTableDensity(bool OptForSize) const;
2127
2128 /// Return upper limit for number of entries in a jump table.
2129 /// Zero if no limit.
2130 unsigned getMaximumJumpTableSize() const;
2131
2132 virtual bool isJumpTableRelative() const;
2133
2134 /// Retuen the minimum of largest number of comparisons in BitTest.
2135 unsigned getMinimumBitTestCmps() const;
2136
2137 /// Return maximum known-legal store size, which can be guaranteed for
2138 /// scalable vectors.
2140 return MaximumLegalStoreInBits;
2141 }
2142
2143 /// If a physical register, this specifies the register that
2144 /// llvm.savestack/llvm.restorestack should save and restore.
2146 return StackPointerRegisterToSaveRestore;
2147 }
2148
2149 /// If a physical register, this returns the register that receives the
2150 /// exception address on entry to an EH pad.
2151 virtual Register
2153 const Constant *PersonalityFn) const {
2154 return Register();
2155 }
2156
2157 /// If a physical register, this returns the register that receives the
2158 /// exception typeid on entry to a landing pad.
2159 virtual Register
2161 const Constant *PersonalityFn) const {
2162 return Register();
2163 }
2164
2165 virtual bool needsFixedCatchObjects() const {
2166 reportFatalUsageError("Funclet EH is not implemented for this target");
2167 }
2168
2169 /// Return the minimum stack alignment of an argument.
2171 return MinStackArgumentAlignment;
2172 }
2173
2174 /// Return the minimum function alignment.
2175 Align getMinFunctionAlignment() const { return MinFunctionAlignment; }
2176
2177 /// Return the preferred function alignment.
2178 Align getPrefFunctionAlignment() const { return PrefFunctionAlignment; }
2179
2180 /// Return the preferred loop alignment. \p BlockToAlign, when non-null, is
2181 /// the block that will actually be aligned; after loop rotation this need not
2182 /// be the LoopInfo header. Targets whose alignment depends on the block
2183 /// contents should use it. Callers that are not aligning a particular block,
2184 /// such as llvm-exegesis and ARM constant islands, leave it null.
2185 virtual Align
2186 getPrefLoopAlignment(MachineLoop *ML = nullptr,
2187 const MachineBasicBlock *BlockToAlign = nullptr) const;
2188
2189 /// Return the maximum amount of bytes allowed to be emitted when padding for
2190 /// alignment
2191 virtual unsigned
2192 getMaxPermittedBytesForAlignment(MachineBasicBlock *MBB) const;
2193
2194 /// Should loops be aligned even when the function is marked OptSize (but not
2195 /// MinSize).
2196 virtual bool alignLoopsWithOptSize() const { return false; }
2197
2198 /// If the target has a standard location for the stack protector guard,
2199 /// returns the address of that location. Otherwise, returns nullptr.
2200 /// DEPRECATED: please override useLoadStackGuardNode and customize
2201 /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
2202 virtual Value *getIRStackGuard(IRBuilderBase &IRB,
2203 const LibcallLoweringInfo &Libcalls) const;
2204
2205 /// Inserts necessary declarations for SSP (stack protection) purpose.
2206 /// Should be used only when getIRStackGuard returns nullptr.
2207 virtual void insertSSPDeclarations(Module &M,
2208 const LibcallLoweringInfo &Libcalls) const;
2209
2210 /// Return the variable that's previously inserted by insertSSPDeclarations,
2211 /// if any, otherwise return nullptr. Should be used only when
2212 /// getIRStackGuard returns nullptr.
2213 virtual Value *getSDagStackGuard(const Module &M,
2214 const LibcallLoweringInfo &Libcalls) const;
2215
2216 /// If this function returns true, stack protection checks should mix the
2217 /// frame pointer (or whichever pointer is used to address locals) into the
2218 /// stack guard value before checking it. getIRStackGuard must return nullptr
2219 /// if this returns true.
2220 virtual bool useStackGuardMixFP() const { return false; }
2221
2222 /// If the target has a standard stack protection check function that
2223 /// performs validation and error handling, returns the function. Otherwise,
2224 /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
2225 /// Should be used only when getIRStackGuard returns nullptr.
2226 Function *getSSPStackGuardCheck(const Module &M,
2227 const LibcallLoweringInfo &Libcalls) const;
2228
2229protected:
2230 Value *getDefaultSafeStackPointerLocation(IRBuilderBase &IRB,
2231 bool UseTLS) const;
2232
2233public:
2234 /// Returns the target-specific address of the unsafe stack pointer.
2235 virtual Value *
2236 getSafeStackPointerLocation(IRBuilderBase &IRB,
2237 const LibcallLoweringInfo &Libcalls) const;
2238
2239 /// Returns the name of the symbol used to emit stack probes or the empty
2240 /// string if not applicable.
2241 virtual bool hasStackProbeSymbol(const MachineFunction &MF) const { return false; }
2242
2243 virtual bool hasInlineStackProbe(const MachineFunction &MF) const { return false; }
2244
2246 return "";
2247 }
2248
2249 /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
2250 /// are happy to sink it into basic blocks. A cast may be free, but not
2251 /// necessarily a no-op. e.g. a free truncate from a 64-bit to 32-bit pointer.
2252 virtual bool isFreeAddrSpaceCast(const DataLayout &DL, unsigned SrcAS,
2253 unsigned DestAS) const;
2254
2255 /// Return true if the pointer arguments to CI should be aligned by aligning
2256 /// the object whose address is being passed. If so then MinSize is set to the
2257 /// minimum size the object must be to be aligned and PrefAlign is set to the
2258 /// preferred alignment.
2259 virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
2260 Align & /*PrefAlign*/) const {
2261 return false;
2262 }
2263
2264 //===--------------------------------------------------------------------===//
2265 /// \name Helpers for TargetTransformInfo implementations
2266 /// @{
2267
2268 /// Get the ISD node that corresponds to the Instruction class opcode.
2269 int InstructionOpcodeToISD(unsigned Opcode) const;
2270
2271 /// Get the ISD node that corresponds to the Intrinsic ID. Returns
2272 /// ISD::DELETED_NODE by default for an unsupported Intrinsic ID.
2273 int IntrinsicIDToISD(Intrinsic::ID ID) const;
2274
2275 /// @}
2276
2277 //===--------------------------------------------------------------------===//
2278 /// \name Helpers for atomic expansion.
2279 /// @{
2280
2281 /// Returns the maximum atomic operation size (in bits) supported by
2282 /// the backend. Atomic operations greater than this size (as well
2283 /// as ones that are not naturally aligned), will be expanded by
2284 /// AtomicExpandPass into an __atomic_* library call.
2286 return MaxAtomicSizeInBitsSupported;
2287 }
2288
2289 /// Returns the size in bits of the maximum div/rem the backend supports.
2290 /// Larger operations will be expanded by ExpandIRInsts.
2292 return MaxDivRemBitWidthSupported;
2293 }
2294
2295 /// Returns the size in bits of the maximum fp to/from int conversion the
2296 /// backend supports. Larger operations will be expanded by ExpandIRInsts.
2298 return MaxLargeFPConvertBitWidthSupported;
2299 }
2300
2301 /// Returns the size of the smallest cmpxchg or ll/sc instruction
2302 /// the backend supports. Any smaller operations are widened in
2303 /// AtomicExpandPass.
2304 ///
2305 /// Note that *unlike* operations above the maximum size, atomic ops
2306 /// are still natively supported below the minimum; they just
2307 /// require a more complex expansion.
2308 unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
2309
2310 /// Return true if the target supports an atomic access of \p SizeInBytes
2311 /// bytes at the given \p Alignment. The default implementation only allows
2312 /// naturally aligned atomics, unless setSupportsUnalignedAtomics(true) was
2313 /// called.
2314 virtual bool isAtomicAlignmentSupported(Align Alignment,
2315 uint64_t SizeInBytes) const {
2316 return SupportsUnalignedAtomics || Alignment.value() >= SizeInBytes;
2317 }
2318
2319 /// Whether AtomicExpandPass should automatically insert fences and reduce
2320 /// ordering for this atomic. This should be true for most architectures with
2321 /// weak memory ordering. Defaults to false.
2322 virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
2323 return false;
2324 }
2325
2326 /// Whether AtomicExpandPass should automatically insert a seq_cst trailing
2327 /// fence without reducing the ordering for this atomic store. Defaults to
2328 /// false.
2329 virtual bool
2331 return false;
2332 }
2333
2334 // The memory ordering that AtomicExpandPass should assign to a atomic
2335 // instruction that it has lowered by adding fences. This can be used
2336 // to "fold" one of the fences into the atomic instruction.
2337 virtual AtomicOrdering
2341
2342 // Whether to issue an atomic load for the initial word value before the
2343 // atomicrmw/cmpxchg emulation loop.
2344 // TODO: For correctness, an atomic load should be issued for all targets.
2345 // Remove this API once this is achieved
2347 return true;
2348 }
2349
2350 /// Perform a load-linked operation on Addr, returning a "Value *" with the
2351 /// corresponding pointee type. This may entail some non-trivial operations to
2352 /// truncate or reconstruct types that will be illegal in the backend. See
2353 /// ARMISelLowering for an example implementation.
2354 virtual Value *emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
2355 Value *Addr, AtomicOrdering Ord) const {
2356 llvm_unreachable("Load linked unimplemented on this target");
2357 }
2358
2359 /// Perform a store-conditional operation to Addr. Return the status of the
2360 /// store. This should be 0 if the store succeeded, non-zero otherwise.
2362 Value *Addr, AtomicOrdering Ord) const {
2363 llvm_unreachable("Store conditional unimplemented on this target");
2364 }
2365
2366 /// Perform a masked atomicrmw using a target-specific intrinsic. This
2367 /// represents the core LL/SC loop which will be lowered at a late stage by
2368 /// the backend. The target-specific intrinsic returns the loaded value and
2369 /// is not responsible for masking and shifting the result.
2371 AtomicRMWInst *AI,
2372 Value *AlignedAddr, Value *Incr,
2373 Value *Mask, Value *ShiftAmt,
2374 AtomicOrdering Ord) const {
2375 llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
2376 }
2377
2378 /// Perform a atomicrmw expansion using a target-specific way. This is
2379 /// expected to be called when masked atomicrmw and bit test atomicrmw don't
2380 /// work, and the target supports another way to lower atomicrmw.
2381 virtual void emitExpandAtomicRMW(AtomicRMWInst *AI) const {
2383 "Generic atomicrmw expansion unimplemented on this target");
2384 }
2385
2386 /// Perform a atomic store using a target-specific way.
2387 virtual void emitExpandAtomicStore(StoreInst *SI) const {
2389 "Generic atomic store expansion unimplemented on this target");
2390 }
2391
2392 /// Perform a atomic load using a target-specific way.
2393 virtual void emitExpandAtomicLoad(LoadInst *LI) const {
2395 "Generic atomic load expansion unimplemented on this target");
2396 }
2397
2398 /// Perform a cmpxchg expansion using a target-specific method.
2400 llvm_unreachable("Generic cmpxchg expansion unimplemented on this target");
2401 }
2402
2403 /// Perform a bit test atomicrmw using a target-specific intrinsic. This
2404 /// represents the combined bit test intrinsic which will be lowered at a late
2405 /// stage by the backend.
2408 "Bit test atomicrmw expansion unimplemented on this target");
2409 }
2410
2411 /// Perform a atomicrmw which the result is only used by comparison, using a
2412 /// target-specific intrinsic. This represents the combined atomic and compare
2413 /// intrinsic which will be lowered at a late stage by the backend.
2416 "Compare arith atomicrmw expansion unimplemented on this target");
2417 }
2418
2419 /// Perform a masked cmpxchg using a target-specific intrinsic. This
2420 /// represents the core LL/SC loop which will be lowered at a late stage by
2421 /// the backend. The target-specific intrinsic returns the loaded value and
2422 /// is not responsible for masking and shifting the result.
2424 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
2425 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
2426 llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
2427 }
2428
2429 //===--------------------------------------------------------------------===//
2430 /// \name KCFI check lowering.
2431 /// @{
2432
2435 const TargetInstrInfo *TII) const {
2436 llvm_unreachable("KCFI is not supported on this target");
2437 }
2438
2439 /// @}
2440
2441 //===--------------------------------------------------------------------===//
2442 /// \name Speculative load lowering.
2443 /// @{
2444
2445 /// Emit code to check if a speculative load of the given size from Ptr is
2446 /// safe. Returns a Value* representing the check result (i1), or nullptr
2447 /// to use the default lowering (which returns false). Targets can override
2448 /// to provide their own safety check (e.g., alignment-based page boundary
2449 /// check).
2450 /// \param Builder IRBuilder positioned at the intrinsic call site
2451 /// \param Ptr the pointer operand
2452 /// \param Size the size in bytes (constant or runtime value for scalable)
2454 Value *Size) const {
2455 return nullptr;
2456 }
2457
2458 /// @}
2459
2460 /// Inserts in the IR a target-specific intrinsic specifying a fence.
2461 /// It is called by AtomicExpandPass before expanding an
2462 /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
2463 /// if shouldInsertFencesForAtomic returns true.
2464 ///
2465 /// Inst is the original atomic instruction, prior to other expansions that
2466 /// may be performed.
2467 ///
2468 /// This function should either return a nullptr, or a pointer to an IR-level
2469 /// Instruction*. Even complex fence sequences can be represented by a
2470 /// single Instruction* through an intrinsic to be lowered later.
2471 ///
2472 /// The default implementation emits an IR fence before any release (or
2473 /// stronger) operation that stores, and after any acquire (or stronger)
2474 /// operation. This is generally a correct implementation, but backends may
2475 /// override if they wish to use alternative schemes (e.g. the PowerPC
2476 /// standard ABI uses a fence before a seq_cst load instead of after a
2477 /// seq_cst store).
2478 /// @{
2479 virtual Instruction *emitLeadingFence(IRBuilderBase &Builder,
2480 Instruction *Inst,
2481 AtomicOrdering Ord) const;
2482
2483 virtual Instruction *emitTrailingFence(IRBuilderBase &Builder,
2484 Instruction *Inst,
2485 AtomicOrdering Ord) const;
2486 /// @}
2487
2488 // Emits code that executes when the comparison result in the ll/sc
2489 // expansion of a cmpxchg instruction is such that the store-conditional will
2490 // not execute. This makes it possible to balance out the load-linked with
2491 // a dedicated instruction, if desired.
2492 // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
2493 // be unnecessarily held, except if clrex, inserted by this hook, is executed.
2494 virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilderBase &Builder) const {}
2495
2496 /// Returns true if arguments should be sign-extended in lib calls.
2497 virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const {
2498 return IsSigned;
2499 }
2500
2501 /// Returns true if arguments should be extended in lib calls.
2502 virtual bool shouldExtendTypeInLibCall(EVT Type) const {
2503 return true;
2504 }
2505
2506 /// Returns how the given (atomic) load should be expanded by the
2507 /// IR-level AtomicExpand pass.
2511
2512 /// Returns how the given (atomic) load should be cast by the IR-level
2513 /// AtomicExpand pass.
2519
2520 /// Returns how the given (atomic) store should be expanded by the IR-level
2521 /// AtomicExpand pass into. For instance AtomicExpansionKind::CustomExpand
2522 /// will try to use an atomicrmw xchg.
2526
2527 /// Returns how the given (atomic) store should be cast by the IR-level
2528 /// AtomicExpand pass into. For instance AtomicExpansionKind::CastToInteger
2529 /// will try to cast the operands to integer values.
2531 if (SI->getValueOperand()->getType()->isFloatingPointTy())
2534 }
2535
2536 /// Returns how the given atomic cmpxchg should be expanded by the IR-level
2537 /// AtomicExpand pass.
2538 virtual AtomicExpansionKind
2542
2543 /// Returns how the IR-level AtomicExpand pass should expand the given
2544 /// AtomicRMW, if at all. By default, elementwise operations are expanded and
2545 /// floating-point operations use are expanded to a compare-exchange loop.
2546 virtual AtomicExpansionKind
2548 if (RMW->isElementwise())
2550 if (RMW->isFloatingPointOperation())
2552 if (RMW->getType()->isVectorTy())
2555 }
2556
2557 /// Returns how the given atomic atomicrmw should be cast by the IR-level
2558 /// AtomicExpand pass.
2559 virtual AtomicExpansionKind
2561 Type *ValTy = RMWI->getValOperand()->getType();
2562 if (RMWI->getOperation() == AtomicRMWInst::Xchg &&
2563 (ValTy->isFloatingPointTy() || ValTy->isPointerTy() ||
2564 ValTy->isVectorTy()))
2566
2568 }
2569
2570 /// On some platforms, an AtomicRMW that never actually modifies the value
2571 /// (such as fetch_add of 0) can be turned into a fence followed by an
2572 /// atomic load. This may sound useless, but it makes it possible for the
2573 /// processor to keep the cacheline shared, dramatically improving
2574 /// performance. And such idempotent RMWs are useful for implementing some
2575 /// kinds of locks, see for example (justification + benchmarks):
2576 /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
2577 /// This method tries doing that transformation, returning the atomic load if
2578 /// it succeeds, and nullptr otherwise.
2579 /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
2580 /// another round of expansion.
2581 virtual LoadInst *
2583 return nullptr;
2584 }
2585
2586 /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
2587 /// SIGN_EXTEND, or ANY_EXTEND).
2589 return ISD::ZERO_EXTEND;
2590 }
2591
2592 /// Returns how the platform's atomic compare and swap expects its comparison
2593 /// value to be extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND). This is
2594 /// separate from getExtendForAtomicOps, which is concerned with the
2595 /// sign-extension of the instruction's output, whereas here we are concerned
2596 /// with the sign-extension of the input. For targets with compare-and-swap
2597 /// instructions (or sub-word comparisons in their LL/SC loop expansions),
2598 /// the input can be ANY_EXTEND, but the output will still have a specific
2599 /// extension.
2601 return ISD::ANY_EXTEND;
2602 }
2603
2604 /// Returns how the platform's atomic rmw operations expect their input
2605 /// argument to be extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND).
2607 return ISD::ANY_EXTEND;
2608 }
2609
2610 /// @}
2611
2612 /// Returns true if we should normalize
2613 /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
2614 /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
2615 /// that it saves us from materializing N0 and N1 in an integer register.
2616 /// Targets that are able to perform and/or on flags should return false here.
2617 /// \p VT is the type of the select (and X and Y). \p CCVT is the type of its
2618 /// condition (N0 and N1).
2620 EVT CCVT) const {
2621 // If a target has multiple condition registers, then it likely has logical
2622 // operations on those registers.
2624 return false;
2625 // Only do the transform if the value won't be split into multiple
2626 // registers.
2627 LegalizeTypeAction Action = getTypeAction(Context, VT);
2628 return Action != TypeExpandInteger && Action != TypeExpandFloat &&
2629 Action != TypeSplitVector;
2630 }
2631
2632 virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
2633
2634 /// Return true if a select of constants (select Cond, C1, C2) should be
2635 /// transformed into simple math ops with the condition value. For example:
2636 /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
2637 virtual bool convertSelectOfConstantsToMath(EVT VT) const {
2638 return false;
2639 }
2640
2641 /// Return true if it is profitable to transform an integer
2642 /// multiplication-by-constant into simpler operations like shifts and adds.
2643 /// This may be true if the target does not directly support the
2644 /// multiplication operation for the specified type or the sequence of simpler
2645 /// ops is faster than the multiply.
2647 EVT VT, SDValue C) const {
2648 return false;
2649 }
2650
2651 /// Return true if it may be profitable to transform
2652 /// (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
2653 /// This may not be true if c1 and c2 can be represented as immediates but
2654 /// c1*c2 cannot, for example.
2655 /// The target should check if c1, c2 and c1*c2 can be represented as
2656 /// immediates, or have to be materialized into registers. If it is not sure
2657 /// about some cases, a default true can be returned to let the DAGCombiner
2658 /// decide.
2659 /// AddNode is (add x, c1), and ConstNode is c2.
2661 SDValue ConstNode) const {
2662 return true;
2663 }
2664
2665 /// Return true if it is more correct/profitable to use strict FP_TO_INT
2666 /// conversion operations - canonicalizing the FP source value instead of
2667 /// converting all cases and then selecting based on value.
2668 /// This may be true if the target throws exceptions for out of bounds
2669 /// conversions or has fast FP CMOV.
2670 virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
2671 bool IsSigned) const {
2672 return false;
2673 }
2674
2675 /// Return true if it is beneficial to expand an @llvm.powi.* intrinsic.
2676 /// If not optimizing for size, expanding @llvm.powi.* intrinsics is always
2677 /// considered beneficial.
2678 /// If optimizing for size, expansion is only considered beneficial for upto
2679 /// 5 multiplies and a divide (if the exponent is negative).
2680 bool isBeneficialToExpandPowI(int64_t Exponent, bool OptForSize) const {
2681 if (Exponent < 0)
2682 Exponent = -Exponent;
2683 uint64_t E = static_cast<uint64_t>(Exponent);
2684 return !OptForSize || (llvm::popcount(E) + Log2_64(E) < 7);
2685 }
2686
2687 //===--------------------------------------------------------------------===//
2688 // TargetLowering Configuration Methods - These methods should be invoked by
2689 // the derived class constructor to configure this object for the target.
2690 //
2691protected:
2692 /// Specify how the target extends the result of integer and floating point
2693 /// boolean values from i1 to a wider type. See getBooleanContents.
2695 BooleanContents = Ty;
2696 BooleanFloatContents = Ty;
2697 }
2698
2699 /// Specify how the target extends the result of integer and floating point
2700 /// boolean values from i1 to a wider type. See getBooleanContents.
2702 BooleanContents = IntTy;
2703 BooleanFloatContents = FloatTy;
2704 }
2705
2706 /// Specify how the target extends the result of a vector boolean value from a
2707 /// vector of i1 to a wider type. See getBooleanContents.
2709 BooleanVectorContents = Ty;
2710 }
2711
2712 /// Specify the target scheduling preference.
2714 SchedPreferenceInfo = Pref;
2715 }
2716
2717 /// Indicate the minimum number of blocks to generate jump tables.
2718 void setMinimumJumpTableEntries(unsigned Val);
2719
2720 /// Indicate the maximum number of entries in jump tables.
2721 /// Set to zero to generate unlimited jump tables.
2722 void setMaximumJumpTableSize(unsigned);
2723
2724 /// Set the minimum of largest of number of comparisons to generate BitTest.
2725 void setMinimumBitTestCmps(unsigned Val);
2726
2727 /// If set to a physical register, this specifies the register that
2728 /// llvm.savestack/llvm.restorestack should save and restore.
2730 StackPointerRegisterToSaveRestore = R;
2731 }
2732
2733 /// Tells the code generator that the target has BitExtract instructions.
2734 /// The code generator will aggressively sink "shift"s into the blocks of
2735 /// their users if the users will generate "and" instructions which can be
2736 /// combined with "shift" to BitExtract instructions.
2737 void setHasExtractBitsInsn(bool hasExtractInsn = true) {
2738 HasExtractBitsInsn = hasExtractInsn;
2739 }
2740
2741 /// Tells the code generator not to expand logic operations on comparison
2742 /// predicates into separate sequences that increase the amount of flow
2743 /// control.
2744 void setJumpIsExpensive(bool isExpensive = true);
2745
2746 /// Tells the code generator which bitwidths to bypass.
2747 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
2748 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
2749 }
2750
2751 /// Add the specified register class as an available regclass for the
2752 /// specified value type. This indicates the selector can handle values of
2753 /// that class natively.
2755 assert((unsigned)VT.SimpleTy < std::size(RegClassForVT));
2756 RegClassForVT[VT.SimpleTy] = RC;
2757 }
2758
2759 /// Return the largest legal super-reg register class of the register class
2760 /// for the specified type and its associated "cost".
2761 virtual std::pair<const TargetRegisterClass *, uint8_t>
2762 findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
2763
2764 /// Once all of the register classes are added, this allows us to compute
2765 /// derived properties we expose.
2766 void computeRegisterProperties(const TargetRegisterInfo *TRI);
2767
2768 /// Indicate that the specified operation does not work with the specified
2769 /// type and indicate what to do about it. Note that VT may refer to either
2770 /// the type of a result or that of an operand of Op.
2771 void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action) {
2772 assert(Op < std::size(OpActions[0]) && "Table isn't big enough!");
2773 OpActions[(unsigned)VT.SimpleTy][Op] = Action;
2774 }
2776 LegalizeAction Action) {
2777 for (auto Op : Ops)
2778 setOperationAction(Op, VT, Action);
2779 }
2781 LegalizeAction Action) {
2782 for (auto VT : VTs)
2783 setOperationAction(Ops, VT, Action);
2784 }
2785
2786 /// Indicate that the specified load with extension does not work with the
2787 /// specified type and indicate what to do about it.
2788 void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
2789 LegalizeAction Action) {
2790 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
2791 MemVT.isValid() && "Table isn't big enough!");
2792 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2793 unsigned Shift = 4 * ExtType;
2794 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
2795 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
2796 }
2797 void setLoadExtAction(ArrayRef<unsigned> ExtTypes, MVT ValVT, MVT MemVT,
2798 LegalizeAction Action) {
2799 for (auto ExtType : ExtTypes)
2800 setLoadExtAction(ExtType, ValVT, MemVT, Action);
2801 }
2803 ArrayRef<MVT> MemVTs, LegalizeAction Action) {
2804 for (auto MemVT : MemVTs)
2805 setLoadExtAction(ExtTypes, ValVT, MemVT, Action);
2806 }
2807
2808 /// Let target indicate that an extending atomic load of the specified type
2809 /// is legal.
2810 void setAtomicLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
2811 LegalizeAction Action) {
2812 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
2813 MemVT.isValid() && "Table isn't big enough!");
2814 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2815 unsigned Shift = 4 * ExtType;
2816 AtomicLoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &=
2817 ~((uint16_t)0xF << Shift);
2818 AtomicLoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |=
2819 ((uint16_t)Action << Shift);
2820 }
2822 LegalizeAction Action) {
2823 for (auto ExtType : ExtTypes)
2824 setAtomicLoadExtAction(ExtType, ValVT, MemVT, Action);
2825 }
2827 ArrayRef<MVT> MemVTs, LegalizeAction Action) {
2828 for (auto MemVT : MemVTs)
2829 setAtomicLoadExtAction(ExtTypes, ValVT, MemVT, Action);
2830 }
2831
2832 /// Indicate that the specified truncating store does not work with the
2833 /// specified type and indicate what to do about it.
2834 void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action) {
2835 assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
2836 TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
2837 }
2838
2839 /// Indicate that the specified indexed load does or does not work with the
2840 /// specified type and indicate what to do abort it.
2841 ///
2842 /// NOTE: All indexed mode loads are initialized to Expand in
2843 /// TargetLowering.cpp
2845 LegalizeAction Action) {
2846 for (auto IdxMode : IdxModes)
2847 setIndexedModeAction(IdxMode, VT, IMAB_Load, Action);
2848 }
2849
2851 LegalizeAction Action) {
2852 for (auto VT : VTs)
2853 setIndexedLoadAction(IdxModes, VT, Action);
2854 }
2855
2856 /// Indicate that the specified indexed store does or does not work with the
2857 /// specified type and indicate what to do about it.
2858 ///
2859 /// NOTE: All indexed mode stores are initialized to Expand in
2860 /// TargetLowering.cpp
2862 LegalizeAction Action) {
2863 for (auto IdxMode : IdxModes)
2864 setIndexedModeAction(IdxMode, VT, IMAB_Store, Action);
2865 }
2866
2868 LegalizeAction Action) {
2869 for (auto VT : VTs)
2870 setIndexedStoreAction(IdxModes, VT, Action);
2871 }
2872
2873 /// Indicate that the specified indexed masked load does or does not work with
2874 /// the specified type and indicate what to do about it.
2875 ///
2876 /// NOTE: All indexed mode masked loads are initialized to Expand in
2877 /// TargetLowering.cpp
2878 void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT,
2879 LegalizeAction Action) {
2880 setIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad, Action);
2881 }
2882
2883 /// Indicate that the specified indexed masked store does or does not work
2884 /// with the specified type and indicate what to do about it.
2885 ///
2886 /// NOTE: All indexed mode masked stores are initialized to Expand in
2887 /// TargetLowering.cpp
2888 void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT,
2889 LegalizeAction Action) {
2890 setIndexedModeAction(IdxMode, VT, IMAB_MaskedStore, Action);
2891 }
2892
2893 /// Indicate that the specified condition code is or isn't supported on the
2894 /// target and indicate what to do about it.
2896 LegalizeAction Action) {
2897 for (auto CC : CCs) {
2898 assert(VT.isValid() && (unsigned)CC < std::size(CondCodeActions) &&
2899 "Table isn't big enough!");
2900 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2901 /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the
2902 /// 32-bit value and the upper 29 bits index into the second dimension of
2903 /// the array to select what 32-bit value to use.
2904 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
2905 CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
2906 CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
2907 }
2908 }
2910 LegalizeAction Action) {
2911 for (auto VT : VTs)
2912 setCondCodeAction(CCs, VT, Action);
2913 }
2914
2915 /// Indicate how a PARTIAL_REDUCE_U/SMLA node with Acc type AccVT and Input
2916 /// type InputVT should be treated by the target. Either it's legal, needs to
2917 /// be promoted to a larger size, needs to be expanded to some other code
2918 /// sequence, or the target has a custom expander for it.
2919 void setPartialReduceMLAAction(unsigned Opc, MVT AccVT, MVT InputVT,
2920 LegalizeAction Action) {
2923 assert(AccVT.isValid() && InputVT.isValid() &&
2924 "setPartialReduceMLAAction types aren't valid");
2925 PartialReduceActionTypes Key = {Opc, AccVT.SimpleTy, InputVT.SimpleTy};
2926 PartialReduceMLAActions[Key] = Action;
2927 }
2929 MVT InputVT, LegalizeAction Action) {
2930 for (unsigned Opc : Opcodes)
2931 setPartialReduceMLAAction(Opc, AccVT, InputVT, Action);
2932 }
2933
2934 /// Indicate how a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the
2935 /// given interleave factor Factor and type VT should be treated.
2936 void setVectorInterleaveAction(unsigned Opc, unsigned Factor, MVT VT,
2937 LegalizeAction Action) {
2939 VectorInterleaveActionKey Key = {Opc, Factor, VT.SimpleTy};
2940 VectorInterleaveActions[Key] = Action;
2941 }
2942
2944 ArrayRef<unsigned> Factors, MVT VT,
2945 LegalizeAction Action) {
2946 for (unsigned Opc : Opcodes)
2947 for (unsigned Factor : Factors)
2948 setVectorInterleaveAction(Opc, Factor, VT, Action);
2949 }
2950
2951 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
2952 /// to trying a larger integer/fp until it can find one that works. If that
2953 /// default is insufficient, this method can be used by the target to override
2954 /// the default.
2955 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2956 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
2957 }
2958
2959 /// Convenience method to set an operation to Promote and specify the type
2960 /// in a single call.
2961 void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2962 setOperationAction(Opc, OrigVT, Promote);
2963 AddPromotedToType(Opc, OrigVT, DestVT);
2964 }
2966 MVT DestVT) {
2967 for (auto Op : Ops) {
2968 setOperationAction(Op, OrigVT, Promote);
2969 AddPromotedToType(Op, OrigVT, DestVT);
2970 }
2971 }
2972
2973 /// Targets should invoke this method for each target independent node that
2974 /// they want to provide a custom DAG combiner for by implementing the
2975 /// PerformDAGCombine virtual method.
2977 for (auto NT : NTs) {
2978 assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
2979 TargetDAGCombineArray[NT >> 3] |= 1 << (NT & 7);
2980 }
2981 }
2982
2983 /// Set the target's minimum function alignment.
2985 MinFunctionAlignment = Alignment;
2986 }
2987
2988 /// Set the target's preferred function alignment. This should be set if
2989 /// there is a performance benefit to higher-than-minimum alignment
2991 PrefFunctionAlignment = Alignment;
2992 }
2993
2994 /// Set the target's preferred loop alignment. Default alignment is one, it
2995 /// means the target does not care about loop alignment. The target may also
2996 /// override getPrefLoopAlignment to provide per-loop values.
2997 void setPrefLoopAlignment(Align Alignment) { PrefLoopAlignment = Alignment; }
2998 void setMaxBytesForAlignment(unsigned MaxBytes) {
2999 MaxBytesForAlignment = MaxBytes;
3000 }
3001
3002 /// Set the minimum stack alignment of an argument.
3004 MinStackArgumentAlignment = Alignment;
3005 }
3006
3007 /// Set the maximum atomic operation size supported by the
3008 /// backend. Atomic operations greater than this size (as well as
3009 /// ones that are not naturally aligned), will be expanded by
3010 /// AtomicExpandPass into an __atomic_* library call.
3011 void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
3012 MaxAtomicSizeInBitsSupported = SizeInBits;
3013 }
3014
3015 /// Set the size in bits of the maximum div/rem the backend supports.
3016 /// Larger operations will be expanded by ExpandIRInsts.
3017 void setMaxDivRemBitWidthSupported(unsigned SizeInBits) {
3018 MaxDivRemBitWidthSupported = SizeInBits;
3019 }
3020
3021 /// Set the size in bits of the maximum fp to/from int conversion the backend
3022 /// supports. Larger operations will be expanded by ExpandIRInsts.
3023 void setMaxLargeFPConvertBitWidthSupported(unsigned SizeInBits) {
3024 MaxLargeFPConvertBitWidthSupported = SizeInBits;
3025 }
3026
3027 /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
3028 void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
3029 MinCmpXchgSizeInBits = SizeInBits;
3030 }
3031
3032 /// Sets whether unaligned atomic operations are supported.
3033 void setSupportsUnalignedAtomics(bool UnalignedSupported) {
3034 SupportsUnalignedAtomics = UnalignedSupported;
3035 }
3036
3037public:
3038 //===--------------------------------------------------------------------===//
3039 // Addressing mode description hooks (used by LSR etc).
3040 //
3041
3042 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
3043 /// instructions reading the address. This allows as much computation as
3044 /// possible to be done in the address mode for that operand. This hook lets
3045 /// targets also pass back when this should be done on intrinsics which
3046 /// load/store.
3047 virtual bool getAddrModeArguments(const IntrinsicInst * /*I*/,
3048 SmallVectorImpl<Value *> & /*Ops*/,
3049 Type *& /*AccessTy*/) const {
3050 return false;
3051 }
3052
3053 /// This represents an addressing mode of:
3054 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*vscale
3055 /// If BaseGV is null, there is no BaseGV.
3056 /// If BaseOffs is zero, there is no base offset.
3057 /// If HasBaseReg is false, there is no base register.
3058 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
3059 /// no scale.
3060 /// If ScalableOffset is zero, there is no scalable offset.
3061 struct AddrMode {
3063 int64_t BaseOffs = 0;
3064 bool HasBaseReg = false;
3065 int64_t Scale = 0;
3066 int64_t ScalableOffset = 0;
3067 AddrMode() = default;
3068 };
3069
3070 /// Return true if the addressing mode represented by AM is legal for this
3071 /// target, for a load/store of the specified type.
3072 ///
3073 /// The type may be VoidTy, in which case only return true if the addressing
3074 /// mode is legal for a load/store of any legal type. TODO: Handle
3075 /// pre/postinc as well.
3076 ///
3077 /// If the address space cannot be determined, it will be -1.
3078 ///
3079 /// TODO: Remove default argument
3080 virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
3081 Type *Ty, unsigned AddrSpace,
3082 Instruction *I = nullptr) const;
3083
3084 /// Returns true if the targets addressing mode can target thread local
3085 /// storage (TLS).
3086 virtual bool addressingModeSupportsTLS(const GlobalValue &) const {
3087 return false;
3088 }
3089
3090 /// Return the prefered common base offset.
3091 virtual int64_t getPreferredLargeGEPBaseOffset(int64_t MinOffset,
3092 int64_t MaxOffset) const {
3093 return 0;
3094 }
3095
3096 /// Return true if the specified immediate is legal icmp immediate, that is
3097 /// the target has icmp instructions which can compare a register against the
3098 /// immediate without having to materialize the immediate into a register.
3099 virtual bool isLegalICmpImmediate(int64_t) const {
3100 return true;
3101 }
3102
3103 /// Return true if the specified immediate is legal add immediate, that is the
3104 /// target has add instructions which can add a register with the immediate
3105 /// without having to materialize the immediate into a register.
3106 virtual bool isLegalAddImmediate(int64_t) const {
3107 return true;
3108 }
3109
3110 /// Return true if adding the specified scalable immediate is legal, that is
3111 /// the target has add instructions which can add a register with the
3112 /// immediate (multiplied by vscale) without having to materialize the
3113 /// immediate into a register.
3114 virtual bool isLegalAddScalableImmediate(int64_t) const { return false; }
3115
3116 /// Return true if the specified immediate is legal for the value input of a
3117 /// store instruction.
3118 virtual bool isLegalStoreImmediate(int64_t Value) const {
3119 // Default implementation assumes that at least 0 works since it is likely
3120 // that a zero register exists or a zero immediate is allowed.
3121 return Value == 0;
3122 }
3123
3124 /// Given a shuffle vector SVI representing a vector splat, return a new
3125 /// scalar type of size equal to SVI's scalar type if the new type is more
3126 /// profitable. Returns nullptr otherwise. For example under MVE float splats
3127 /// are converted to integer to prevent the need to move from SPR to GPR
3128 /// registers.
3130 return nullptr;
3131 }
3132
3133 /// Given a set in interconnected phis of type 'From' that are loaded/stored
3134 /// or bitcast to type 'To', return true if the set should be converted to
3135 /// 'To'.
3136 virtual bool shouldConvertPhiType(Type *From, Type *To) const {
3137 return (From->isIntegerTy() || From->isFloatingPointTy()) &&
3138 (To->isIntegerTy() || To->isFloatingPointTy());
3139 }
3140
3141 /// Returns true if the opcode is a commutative binary operation.
3142 virtual bool isCommutativeBinOp(unsigned Opcode) const {
3143 // FIXME: This should get its info from the td file.
3144 switch (Opcode) {
3145 case ISD::ADD:
3146 case ISD::SMIN:
3147 case ISD::SMAX:
3148 case ISD::UMIN:
3149 case ISD::UMAX:
3150 case ISD::MUL:
3151 case ISD::CLMUL:
3152 case ISD::CLMULH:
3153 case ISD::CLMULR:
3154 case ISD::MULHU:
3155 case ISD::MULHS:
3156 case ISD::SMUL_LOHI:
3157 case ISD::UMUL_LOHI:
3158 case ISD::FADD:
3159 case ISD::FMUL:
3160 case ISD::AND:
3161 case ISD::OR:
3162 case ISD::XOR:
3163 case ISD::SADDO:
3164 case ISD::UADDO:
3165 case ISD::ADDC:
3166 case ISD::ADDE:
3167 case ISD::SADDSAT:
3168 case ISD::UADDSAT:
3169 case ISD::FMINNUM:
3170 case ISD::FMAXNUM:
3171 case ISD::FMINNUM_IEEE:
3172 case ISD::FMAXNUM_IEEE:
3173 case ISD::FMINIMUM:
3174 case ISD::FMAXIMUM:
3175 case ISD::FMINIMUMNUM:
3176 case ISD::FMAXIMUMNUM:
3177 case ISD::AVGFLOORS:
3178 case ISD::AVGFLOORU:
3179 case ISD::AVGCEILS:
3180 case ISD::AVGCEILU:
3181 case ISD::ABDS:
3182 case ISD::ABDU:
3183 return true;
3184 default: return false;
3185 }
3186 }
3187
3188 /// Return true if the node is a math/logic binary operator.
3189 virtual bool isBinOp(unsigned Opcode) const {
3190 // A commutative binop must be a binop.
3191 if (isCommutativeBinOp(Opcode))
3192 return true;
3193 // These are non-commutative binops.
3194 switch (Opcode) {
3195 case ISD::SUB:
3196 case ISD::SHL:
3197 case ISD::SRL:
3198 case ISD::SRA:
3199 case ISD::ROTL:
3200 case ISD::ROTR:
3201 case ISD::SDIV:
3202 case ISD::UDIV:
3203 case ISD::SREM:
3204 case ISD::UREM:
3205 case ISD::SSUBSAT:
3206 case ISD::USUBSAT:
3207 case ISD::AVGSUBFLOORS:
3208 case ISD::AVGSUBFLOORU:
3209 case ISD::FSUB:
3210 case ISD::FDIV:
3211 case ISD::FREM:
3212 case ISD::PSEUDO_FMIN:
3213 case ISD::PSEUDO_FMAX:
3214 return true;
3215 default:
3216 return false;
3217 }
3218 }
3219
3220 /// Return true if it's free to truncate a value of type FromTy to type
3221 /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
3222 /// by referencing its sub-register AX.
3223 /// Targets must return false when FromTy <= ToTy.
3224 virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
3225 return false;
3226 }
3227
3228 /// Return true if a truncation from FromTy to ToTy is permitted when deciding
3229 /// whether a call is in tail position. Typically this means that both results
3230 /// would be assigned to the same register or stack slot, but it could mean
3231 /// the target performs adequate checks of its own before proceeding with the
3232 /// tail call. Targets must return false when FromTy <= ToTy.
3233 virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
3234 return false;
3235 }
3236
3237 virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const { return false; }
3238 virtual bool isTruncateFree(LLT FromTy, LLT ToTy, LLVMContext &Ctx) const {
3239 return isTruncateFree(getApproximateEVTForLLT(FromTy, Ctx),
3240 getApproximateEVTForLLT(ToTy, Ctx));
3241 }
3242
3243 /// Return true if truncating the specific node Val to type VT2 is free.
3244 virtual bool isTruncateFree(SDValue Val, EVT VT2) const {
3245 // Fallback to type matching.
3246 return isTruncateFree(Val.getValueType(), VT2);
3247 }
3248
3249 virtual bool isProfitableToHoist(Instruction *I) const { return true; }
3250
3251 /// Return true if the extension represented by \p I is free.
3252 /// Unlikely the is[Z|FP]ExtFree family which is based on types,
3253 /// this method can use the context provided by \p I to decide
3254 /// whether or not \p I is free.
3255 /// This method extends the behavior of the is[Z|FP]ExtFree family.
3256 /// In other words, if is[Z|FP]Free returns true, then this method
3257 /// returns true as well. The converse is not true.
3258 /// The target can perform the adequate checks by overriding isExtFreeImpl.
3259 /// \pre \p I must be a sign, zero, or fp extension.
3260 bool isExtFree(const Instruction *I) const {
3261 switch (I->getOpcode()) {
3262 case Instruction::FPExt:
3263 if (isFPExtFree(EVT::getEVT(I->getType()),
3264 EVT::getEVT(I->getOperand(0)->getType())))
3265 return true;
3266 break;
3267 case Instruction::ZExt:
3268 if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
3269 return true;
3270 break;
3271 case Instruction::SExt:
3272 break;
3273 default:
3274 llvm_unreachable("Instruction is not an extension");
3275 }
3276 return isExtFreeImpl(I);
3277 }
3278
3279 /// Return true if \p Load and \p Ext can form an ExtLoad.
3280 /// For example, in AArch64
3281 /// %L = load i8, i8* %ptr
3282 /// %E = zext i8 %L to i32
3283 /// can be lowered into one load instruction
3284 /// ldrb w0, [x0]
3285 bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
3286 const DataLayout &DL) const {
3287 EVT VT = getValueType(DL, Ext->getType());
3288 EVT LoadVT = getValueType(DL, Load->getType());
3289
3290 // If the load has other users and the truncate is not free, the ext
3291 // probably isn't free.
3292 if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
3293 !isTruncateFree(Ext->getType(), Load->getType()))
3294 return false;
3295
3296 // Check whether the target supports casts folded into loads.
3297 unsigned LType;
3298 if (isa<ZExtInst>(Ext))
3299 LType = ISD::ZEXTLOAD;
3300 else {
3301 assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
3302 LType = ISD::SEXTLOAD;
3303 }
3304
3305 return isLoadLegal(VT, LoadVT, Load->getAlign(),
3306 Load->getPointerAddressSpace(), LType, false);
3307 }
3308
3309 /// Return true if any actual instruction that defines a value of type FromTy
3310 /// implicitly zero-extends the value to ToTy in the result register.
3311 ///
3312 /// The function should return true when it is likely that the truncate can
3313 /// be freely folded with an instruction defining a value of FromTy. If
3314 /// the defining instruction is unknown (because you're looking at a
3315 /// function argument, PHI, etc.) then the target may require an
3316 /// explicit truncate, which is not necessarily free, but this function
3317 /// does not deal with those cases.
3318 /// Targets must return false when FromTy >= ToTy.
3319 virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
3320 return false;
3321 }
3322
3323 virtual bool isZExtFree(EVT FromTy, EVT ToTy) const { return false; }
3324 virtual bool isZExtFree(LLT FromTy, LLT ToTy, LLVMContext &Ctx) const {
3325 return isZExtFree(getApproximateEVTForLLT(FromTy, Ctx),
3326 getApproximateEVTForLLT(ToTy, Ctx));
3327 }
3328
3329 /// Return true if zero-extending the specific node Val to type VT2 is free
3330 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
3331 /// because it's folded such as X86 zero-extending loads).
3332 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
3333 return isZExtFree(Val.getValueType(), VT2);
3334 }
3335
3336 /// Return true is an anyext is free from FromTy to ToTy. Usually true for
3337 /// scalar types when not trying to pack elements into vector lanes.
3338 virtual bool isAnyExtFree(EVT FromTy, EVT ToTy) const {
3339 return !FromTy.isVector();
3340 }
3341
3342 /// Return true if sign-extension from FromTy to ToTy is cheaper than
3343 /// zero-extension.
3344 virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
3345 return false;
3346 }
3347
3348 /// Return true if this constant should be sign extended when promoting to
3349 /// a larger type.
3350 virtual bool signExtendConstant(const ConstantInt *C) const { return false; }
3351
3352 /// Try to optimize extending or truncating conversion instructions (like
3353 /// zext, trunc, fptoui, uitofp) for the target.
3354 virtual bool
3356 const TargetTransformInfo &TTI) const {
3357 return false;
3358 }
3359
3360 /// Return true if the target supplies and combines to a paired load
3361 /// two loaded values of type LoadedType next to each other in memory.
3362 /// RequiredAlignment gives the minimal alignment constraints that must be met
3363 /// to be able to select this paired load.
3364 ///
3365 /// This information is *not* used to generate actual paired loads, but it is
3366 /// used to generate a sequence of loads that is easier to combine into a
3367 /// paired load.
3368 /// For instance, something like this:
3369 /// a = load i64* addr
3370 /// b = trunc i64 a to i32
3371 /// c = lshr i64 a, 32
3372 /// d = trunc i64 c to i32
3373 /// will be optimized into:
3374 /// b = load i32* addr1
3375 /// d = load i32* addr2
3376 /// Where addr1 = addr2 +/- sizeof(i32).
3377 ///
3378 /// In other words, unless the target performs a post-isel load combining,
3379 /// this information should not be provided because it will generate more
3380 /// loads.
3381 virtual bool hasPairedLoad(EVT /*LoadedType*/,
3382 Align & /*RequiredAlignment*/) const {
3383 return false;
3384 }
3385
3386 /// Return true if the target has a vector blend instruction.
3387 virtual bool hasVectorBlend() const { return false; }
3388
3389 /// Get the maximum supported factor for interleaved memory accesses.
3390 /// Default to be the minimum interleave factor: 2.
3391 virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
3392
3393 /// Lower an interleaved load to target specific intrinsics. Return
3394 /// true on success.
3395 ///
3396 /// \p Load is the vector load instruction. Can be either a plain load
3397 /// instruction or a vp.load intrinsic.
3398 /// \p Mask is a per-segment (i.e. number of lanes equal to that of one
3399 /// component being interwoven) mask. Can be nullptr, in which case the
3400 /// result is uncondiitional.
3401 /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
3402 /// \p Indices is the corresponding indices for each shufflevector.
3403 /// \p Factor is the interleave factor.
3404 /// \p GapMask is a mask with zeros for components / fields that may not be
3405 /// accessed.
3408 ArrayRef<unsigned> Indices, unsigned Factor,
3409 const APInt &GapMask) const {
3410 return false;
3411 }
3412
3413 /// Lower an interleaved store to target specific intrinsics. Return
3414 /// true on success.
3415 ///
3416 /// \p SI is the vector store instruction. Can be either a plain store
3417 /// or a vp.store.
3418 /// \p Mask is a per-segment (i.e. number of lanes equal to that of one
3419 /// component being interwoven) mask. Can be nullptr, in which case the
3420 /// result is unconditional.
3421 /// \p SVI is the shufflevector to RE-interleave the stored vector.
3422 /// \p Factor is the interleave factor.
3423 /// \p GapMask is a mask with zeros for components / fields that may not be
3424 /// accessed.
3426 ShuffleVectorInst *SVI, unsigned Factor,
3427 const APInt &GapMask) const {
3428 return false;
3429 }
3430
3431 /// Lower a deinterleave intrinsic to a target specific load intrinsic.
3432 /// Return true on success. Currently only supports
3433 /// llvm.vector.deinterleave{2,3,5,7}
3434 ///
3435 /// \p Load is the accompanying load instruction. Can be either a plain load
3436 /// instruction or a vp.load intrinsic.
3437 /// \p DI represents the deinterleaveN intrinsic.
3438 /// \p GapMask is a mask with zeros for components / fields that may not be
3439 /// accessed.
3441 IntrinsicInst *DI,
3442 const APInt &GapMask) const {
3443 return false;
3444 }
3445
3446 /// Lower an interleave intrinsic to a target specific store intrinsic.
3447 /// Return true on success. Currently only supports
3448 /// llvm.vector.interleave{2,3,5,7}
3449 ///
3450 /// \p Store is the accompanying store instruction. Can be either a plain
3451 /// store or a vp.store intrinsic.
3452 /// \p Mask is a per-segment (i.e. number of lanes equal to that of one
3453 /// component being interwoven) mask. Can be nullptr, in which case the
3454 /// result is uncondiitional.
3455 /// \p InterleaveValues contains the interleaved values.
3456 virtual bool
3458 ArrayRef<Value *> InterleaveValues) const {
3459 return false;
3460 }
3461
3462 /// Return true if an fpext operation is free (for instance, because
3463 /// single-precision floating-point numbers are implicitly extended to
3464 /// double-precision).
3465 virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
3466 assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
3467 "invalid fpext types");
3468 return false;
3469 }
3470
3471 /// Return true if an fpext operation input to an \p Opcode operation is free
3472 /// (for instance, because half-precision floating-point numbers are
3473 /// implicitly extended to float-precision) for an FMA instruction.
3474 virtual bool isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
3475 LLT DestTy, LLT SrcTy) const {
3476 return false;
3477 }
3478
3479 /// Return true if an fpext operation input to an \p Opcode operation is free
3480 /// (for instance, because half-precision floating-point numbers are
3481 /// implicitly extended to float-precision) for an FMA instruction.
3482 virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
3483 EVT DestVT, EVT SrcVT) const {
3484 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
3485 "invalid fpext types");
3486 return isFPExtFree(DestVT, SrcVT);
3487 }
3488
3489 /// Return true if folding a vector load into ExtVal (a sign, zero, or any
3490 /// extend node) is profitable.
3491 virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
3492
3493 /// Return true if an fneg operation is free to the point where it is never
3494 /// worthwhile to replace it with a bitwise operation.
3495 virtual bool isFNegFree(EVT VT) const {
3496 assert(VT.isFloatingPoint());
3497 return false;
3498 }
3499
3500 /// Return true if an fabs operation is free to the point where it is never
3501 /// worthwhile to replace it with a bitwise operation.
3502 virtual bool isFAbsFree(EVT VT) const {
3503 assert(VT.isFloatingPoint());
3504 return false;
3505 }
3506
3507 /// Return true if an FMA operation is faster than a pair of fmul and fadd
3508 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
3509 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
3510 ///
3511 /// NOTE: This may be called before legalization on types for which FMAs are
3512 /// not legal, but should return true if those types will eventually legalize
3513 /// to types that support FMAs. After legalization, it will only be called on
3514 /// types that support FMAs (via Legal or Custom actions)
3515 ///
3516 /// Targets that care about soft float support should return false when soft
3517 /// float code is being generated (i.e. use-soft-float).
3519 EVT) const {
3520 return false;
3521 }
3522
3523 /// Return true if an FMA operation is faster than a pair of fmul and fadd
3524 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
3525 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
3526 ///
3527 /// NOTE: This may be called before legalization on types for which FMAs are
3528 /// not legal, but should return true if those types will eventually legalize
3529 /// to types that support FMAs. After legalization, it will only be called on
3530 /// types that support FMAs (via Legal or Custom actions)
3532 LLT) const {
3533 return false;
3534 }
3535
3536 /// IR version
3537 virtual bool isFMAFasterThanFMulAndFAdd(const Function &F, Type *) const {
3538 return false;
3539 }
3540
3541 /// Returns true if \p MI can be combined with another instruction to
3542 /// form TargetOpcode::G_FMAD. \p N may be an TargetOpcode::G_FADD,
3543 /// TargetOpcode::G_FSUB, or an TargetOpcode::G_FMUL which will be
3544 /// distributed into an fadd/fsub.
3545 virtual bool isFMADLegal(const MachineInstr &MI, LLT Ty) const {
3546 assert((MI.getOpcode() == TargetOpcode::G_FADD ||
3547 MI.getOpcode() == TargetOpcode::G_FSUB ||
3548 MI.getOpcode() == TargetOpcode::G_FMUL) &&
3549 "unexpected node in FMAD forming combine");
3550 switch (Ty.getScalarSizeInBits()) {
3551 case 16:
3552 return isOperationLegal(TargetOpcode::G_FMAD, MVT::f16);
3553 case 32:
3554 return isOperationLegal(TargetOpcode::G_FMAD, MVT::f32);
3555 case 64:
3556 return isOperationLegal(TargetOpcode::G_FMAD, MVT::f64);
3557 default:
3558 break;
3559 }
3560
3561 return false;
3562 }
3563
3564 /// Returns true if be combined with to form an ISD::FMAD. \p N may be an
3565 /// ISD::FADD, ISD::FSUB, or an ISD::FMUL which will be distributed into an
3566 /// fadd/fsub.
3567 virtual bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const {
3568 assert((N->getOpcode() == ISD::FADD || N->getOpcode() == ISD::FSUB ||
3569 N->getOpcode() == ISD::FMUL) &&
3570 "unexpected node in FMAD forming combine");
3571 return isOperationLegal(ISD::FMAD, N->getValueType(0));
3572 }
3573
3574 // Return true when the decision to generate FMA's (or FMS, FMLA etc) rather
3575 // than FMUL and ADD is delegated to the machine combiner.
3577 CodeGenOptLevel OptLevel) const {
3578 return false;
3579 }
3580
3581 /// Return true if it's profitable to narrow operations of type SrcVT to
3582 /// DestVT. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
3583 /// i32 to i16.
3584 virtual bool isNarrowingProfitable(SDNode *N, EVT SrcVT, EVT DestVT) const {
3585 return false;
3586 }
3587
3588 /// Return true if pulling a binary operation into a select with an identity
3589 /// constant is profitable. This is the inverse of an IR transform.
3590 /// Example: X + (Cond ? Y : 0) --> Cond ? (X + Y) : X
3591 virtual bool shouldFoldSelectWithIdentityConstant(unsigned BinOpcode, EVT VT,
3592 unsigned SelectOpcode,
3593 SDValue X,
3594 SDValue Y) const {
3595 return false;
3596 }
3597
3598 /// Return true if it is beneficial to convert a load of a constant to
3599 /// just the constant itself.
3600 /// On some targets it might be more efficient to use a combination of
3601 /// arithmetic instructions to materialize the constant instead of loading it
3602 /// from a constant pool.
3604 Type *Ty) const {
3605 return false;
3606 }
3607
3608 /// Return the cost of extracting a subvector of type \p ResVT from a vector
3609 /// of type \p SrcVT, starting at element \p Index.
3610 ///
3611 /// Most callers only create a new EXTRACT_SUBVECTOR when the cost is at most
3612 /// ExtractSubvectorCost::Cheap. This hook exists because EXTRACT_SUBVECTOR
3613 /// usually has custom lowering that depends on the index of the first
3614 /// element, so only the target knows which lowering is cheap.
3616 unsigned Index) const {
3618 }
3619
3620 /// Try to convert an extract element of a vector binary operation into an
3621 /// extract element followed by a scalar operation.
3622 virtual bool shouldScalarizeBinop(SDValue VecOp) const {
3623 return false;
3624 }
3625
3626 /// Return true if extraction of a scalar element from the given vector type
3627 /// at the given index is cheap. For example, if scalar operations occur on
3628 /// the same register file as vector operations, then an extract element may
3629 /// be a sub-register rename rather than an actual instruction.
3630 virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
3631 return false;
3632 }
3633
3634 /// Try to convert math with an overflow comparison into the corresponding DAG
3635 /// node operation. Targets may want to override this independently of whether
3636 /// the operation is legal/custom for the given type because it may obscure
3637 /// matching of other patterns.
3638 virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT,
3639 bool MathUsed) const {
3640 // Form it if it is legal.
3641 if (isOperationLegal(Opcode, VT))
3642 return true;
3643
3644 // TODO: The default logic is inherited from code in CodeGenPrepare.
3645 // The opcode should not make a difference by default?
3646 if (Opcode != ISD::UADDO)
3647 return false;
3648
3649 // Allow the transform as long as we have an integer type that is not
3650 // obviously illegal and unsupported and if the math result is used
3651 // besides the overflow check. On some targets (e.g. SPARC), it is
3652 // not profitable to form on overflow op if the math result has no
3653 // concrete users.
3654 if (VT.isVector())
3655 return false;
3656 return MathUsed && (VT.isSimple() || !isOperationExpand(Opcode, VT));
3657 }
3658
3659 // Return true if the target wants to optimize the mul overflow intrinsic
3660 // for the given \p VT.
3662 EVT VT) const {
3663 return false;
3664 }
3665
3666 // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
3667 // even if the vector itself has multiple uses.
3668 virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
3669 return false;
3670 }
3671
3672 // Return true if CodeGenPrepare should consider splitting large offset of a
3673 // GEP to make the GEP fit into the addressing mode and can be sunk into the
3674 // same blocks of its users.
3675 virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
3676
3677 /// Return true if creating a shift of the type by the given
3678 /// amount is not profitable.
3679 virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const {
3680 return false;
3681 }
3682
3683 // Should we fold (select_cc seteq (and x, y), 0, 0, A) -> (and (sra (shl x))
3684 // A) where y has a single bit set?
3686 const APInt &AndMask) const {
3687 unsigned ShCt = AndMask.getBitWidth() - 1;
3688 return !shouldAvoidTransformToShift(VT, ShCt);
3689 }
3690
3691 /// Does this target require the clearing of high-order bits in a register
3692 /// passed to the fp16 to fp conversion library function.
3693 virtual bool shouldKeepZExtForFP16Conv() const { return false; }
3694
3695 /// Should we generate fp_to_si_sat and fp_to_ui_sat from type FPVT to type
3696 /// VT. Used when folding idioms into a saturating fp-to-int conversion, such
3697 /// as min(max(fptoi)) clamps or NaN-guarded selects.
3698 virtual bool shouldConvertFpToSat(unsigned Op, EVT FPVT, EVT VT) const {
3699 return isOperationLegalOrCustom(Op, VT);
3700 }
3701
3702 /// Should we prefer selects to doing arithmetic on boolean types
3704 return false;
3705 }
3706
3707 /// True if target has some particular form of dealing with pointer arithmetic
3708 /// semantics for pointers with the given value type. False if pointer
3709 /// arithmetic should not be preserved for passes such as instruction
3710 /// selection, and can fallback to regular arithmetic.
3711 /// This should be removed when PTRADD nodes are widely supported by backends.
3712 virtual bool shouldPreservePtrArith(const Function &F, EVT PtrVT) const {
3713 return false;
3714 }
3715
3716 /// True if the target allows transformations of in-bounds pointer
3717 /// arithmetic that cause out-of-bounds intermediate results.
3719 EVT PtrVT) const {
3720 return false;
3721 }
3722
3723 /// Does this target support complex deinterleaving
3724 virtual bool isComplexDeinterleavingSupported() const { return false; }
3725
3726 /// Does this target support complex deinterleaving with the given operation
3727 /// and type
3730 return false;
3731 }
3732
3733 // Get the preferred opcode for FP_TO_XINT nodes.
3734 // By default, this checks if the provded operation is an illegal FP_TO_UINT
3735 // and if so, checks if FP_TO_SINT is legal or custom for use as a
3736 // replacement. If both UINT and SINT conversions are Custom, we choose SINT
3737 // by default because that's the right thing on PPC.
3738 virtual unsigned getPreferredFPToIntOpcode(unsigned Op, EVT FromVT,
3739 EVT ToVT) const {
3740 if (isOperationLegal(Op, ToVT))
3741 return Op;
3742 switch (Op) {
3743 case ISD::FP_TO_UINT:
3745 return ISD::FP_TO_SINT;
3746 break;
3750 break;
3751 default:
3752 break;
3753 }
3754 return Op;
3755 }
3756
3757 /// Create the IR node for the given complex deinterleaving operation.
3758 /// If one cannot be created using all the given inputs, nullptr should be
3759 /// returned.
3762 ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
3763 Value *Accumulator = nullptr) const {
3764 return nullptr;
3765 }
3766
3768 return RuntimeLibcallInfo;
3769 }
3770
3771 const LibcallLoweringInfo &getLibcallLoweringInfo() const { return Libcalls; }
3772
3773 void setLibcallImpl(RTLIB::Libcall Call, RTLIB::LibcallImpl Impl) {
3774 Libcalls.setLibcallImpl(Call, Impl);
3775 }
3776
3777 /// Get the libcall impl routine name for the specified libcall.
3778 RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const {
3779 return Libcalls.getLibcallImpl(Call);
3780 }
3781
3782 /// Get the libcall routine name for the specified libcall.
3783 // FIXME: This should be removed. Only LibcallImpl should have a name.
3784 const char *getLibcallName(RTLIB::Libcall Call) const {
3785 return Libcalls.getLibcallName(Call);
3786 }
3787
3788 /// Get the libcall routine name for the specified libcall implementation
3792
3793 RTLIB::LibcallImpl getMemcpyImpl() const { return Libcalls.getMemcpyImpl(); }
3794
3795 /// Get the CallingConv that should be used for the specified libcall
3796 /// implementation.
3798 return Libcalls.getLibcallImplCallingConv(Call);
3799 }
3800
3801 /// Get the CallingConv that should be used for the specified libcall.
3802 // FIXME: Remove this wrapper and directly use the used LibcallImpl
3804 return Libcalls.getLibcallCallingConv(Call);
3805 }
3806
3807 /// Execute target specific actions to finalize target lowering.
3808 /// This is used to set extra flags in MachineFrameInformation and freezing
3809 /// the set of reserved registers.
3810 /// The default implementation just freezes the set of reserved registers.
3811 virtual void finalizeLowering(MachineFunction &MF) const;
3812
3813 /// Returns true if it's profitable to allow merging store of loads when there
3814 /// are functions calls between the load and the store.
3815 virtual bool shouldMergeStoreOfLoadsOverCall(EVT, EVT) const { return true; }
3816
3817 //===----------------------------------------------------------------------===//
3818 // GlobalISel Hooks
3819 //===----------------------------------------------------------------------===//
3820 /// Check whether or not \p MI needs to be moved close to its uses.
3821 virtual bool shouldLocalize(const MachineInstr &MI, const TargetTransformInfo *TTI) const;
3822
3823
3824private:
3825 const TargetMachine &TM;
3826
3827 /// Tells the code generator that the target has BitExtract instructions.
3828 /// The code generator will aggressively sink "shift"s into the blocks of
3829 /// their users if the users will generate "and" instructions which can be
3830 /// combined with "shift" to BitExtract instructions.
3831 bool HasExtractBitsInsn;
3832
3833 /// Tells the code generator to bypass slow divide or remainder
3834 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
3835 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
3836 /// div/rem when the operands are positive and less than 256.
3837 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
3838
3839 /// Tells the code generator that it shouldn't generate extra flow control
3840 /// instructions and should attempt to combine flow control instructions via
3841 /// predication.
3842 bool JumpIsExpensive;
3843
3844 /// Information about the contents of the high-bits in boolean values held in
3845 /// a type wider than i1. See getBooleanContents.
3846 BooleanContent BooleanContents;
3847
3848 /// Information about the contents of the high-bits in boolean values held in
3849 /// a type wider than i1. See getBooleanContents.
3850 BooleanContent BooleanFloatContents;
3851
3852 /// Information about the contents of the high-bits in boolean vector values
3853 /// when the element type is wider than i1. See getBooleanContents.
3854 BooleanContent BooleanVectorContents;
3855
3856 /// The target scheduling preference: shortest possible total cycles or lowest
3857 /// register usage.
3858 Sched::Preference SchedPreferenceInfo;
3859
3860 /// The minimum alignment that any argument on the stack needs to have.
3861 Align MinStackArgumentAlignment;
3862
3863 /// The minimum function alignment (used when optimizing for size, and to
3864 /// prevent explicitly provided alignment from leading to incorrect code).
3865 Align MinFunctionAlignment;
3866
3867 /// The preferred function alignment (used when alignment unspecified and
3868 /// optimizing for speed).
3869 Align PrefFunctionAlignment;
3870
3871 /// The preferred loop alignment (in log2 bot in bytes).
3872 Align PrefLoopAlignment;
3873 /// The maximum amount of bytes permitted to be emitted for alignment.
3874 unsigned MaxBytesForAlignment;
3875
3876 /// Size in bits of the maximum atomics size the backend supports.
3877 /// Accesses larger than this will be expanded by AtomicExpandPass.
3878 unsigned MaxAtomicSizeInBitsSupported;
3879
3880 /// Size in bits of the maximum div/rem size the backend supports.
3881 /// Larger operations will be expanded by ExpandIRInsts.
3882 unsigned MaxDivRemBitWidthSupported;
3883
3884 /// Size in bits of the maximum fp to/from int conversion size the
3885 /// backend supports. Larger operations will be expanded by
3886 /// ExpandIRInsts.
3887 unsigned MaxLargeFPConvertBitWidthSupported;
3888
3889 /// Size in bits of the minimum cmpxchg or ll/sc operation the
3890 /// backend supports.
3891 unsigned MinCmpXchgSizeInBits;
3892
3893 /// The minimum of largest number of comparisons to use bit test for switch.
3894 unsigned MinimumBitTestCmps;
3895
3896 /// Maximum known-legal store size, which can be guaranteed for scalable
3897 /// vectors.
3898 unsigned MaximumLegalStoreInBits;
3899
3900 /// This indicates if the target supports unaligned atomic operations.
3901 bool SupportsUnalignedAtomics;
3902
3903 /// If set to a physical register, this specifies the register that
3904 /// llvm.savestack/llvm.restorestack should save and restore.
3905 Register StackPointerRegisterToSaveRestore;
3906
3907 /// This indicates the default register class to use for each ValueType the
3908 /// target supports natively.
3909 const TargetRegisterClass *RegClassForVT[MVT::VALUETYPE_SIZE];
3910 uint16_t NumRegistersForVT[MVT::VALUETYPE_SIZE];
3911 MVT RegisterTypeForVT[MVT::VALUETYPE_SIZE];
3912
3913 /// This indicates the "representative" register class to use for each
3914 /// ValueType the target supports natively. This information is used by the
3915 /// scheduler to track register pressure. By default, the representative
3916 /// register class is the largest legal super-reg register class of the
3917 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
3918 /// representative class would be GR32.
3919 const TargetRegisterClass *RepRegClassForVT[MVT::VALUETYPE_SIZE] = {nullptr};
3920
3921 /// This indicates the "cost" of the "representative" register class for each
3922 /// ValueType. The cost is used by the scheduler to approximate register
3923 /// pressure.
3924 uint8_t RepRegClassCostForVT[MVT::VALUETYPE_SIZE];
3925
3926 /// For any value types we are promoting or expanding, this contains the value
3927 /// type that we are changing to. For Expanded types, this contains one step
3928 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
3929 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
3930 /// the same type (e.g. i32 -> i32).
3931 MVT TransformToType[MVT::VALUETYPE_SIZE];
3932
3933 /// For each operation and each value type, keep a LegalizeAction that
3934 /// indicates how instruction selection should deal with the operation. Most
3935 /// operations are Legal (aka, supported natively by the target), but
3936 /// operations that are not should be described. Note that operations on
3937 /// non-legal value types are not described here.
3938 LegalizeAction OpActions[MVT::VALUETYPE_SIZE][ISD::BUILTIN_OP_END];
3939
3940 /// For each load extension type and each value type, keep a LegalizeAction
3941 /// that indicates how instruction selection should deal with a load of a
3942 /// specific value type and extension type. Uses 4-bits to store the action
3943 /// for each of the 4 load ext types.
3944 uint16_t LoadExtActions[MVT::VALUETYPE_SIZE][MVT::VALUETYPE_SIZE];
3945
3946 /// Similar to LoadExtActions, but for atomic loads. Only Legal or Expand
3947 /// (default) values are supported.
3948 uint16_t AtomicLoadExtActions[MVT::VALUETYPE_SIZE][MVT::VALUETYPE_SIZE];
3949
3950 /// For each value type pair keep a LegalizeAction that indicates whether a
3951 /// truncating store of a specific value type and truncating type is legal.
3952 LegalizeAction TruncStoreActions[MVT::VALUETYPE_SIZE][MVT::VALUETYPE_SIZE];
3953
3954 /// For each indexed mode and each value type, keep a quad of LegalizeAction
3955 /// that indicates how instruction selection should deal with the load /
3956 /// store / maskedload / maskedstore.
3957 ///
3958 /// The first dimension is the value_type for the reference. The second
3959 /// dimension represents the various modes for load store.
3960 uint16_t IndexedModeActions[MVT::VALUETYPE_SIZE][ISD::LAST_INDEXED_MODE];
3961
3962 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
3963 /// indicates how instruction selection should deal with the condition code.
3964 ///
3965 /// Because each CC action takes up 4 bits, we need to have the array size be
3966 /// large enough to fit all of the value types. This can be done by rounding
3967 /// up the MVT::VALUETYPE_SIZE value to the next multiple of 8.
3968 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::VALUETYPE_SIZE + 7) / 8];
3969
3971 std::tuple<unsigned, MVT::SimpleValueType, MVT::SimpleValueType>;
3972 /// For each partial reduce opcode, result type and input type combination,
3973 /// keep a LegalizeAction which indicates how instruction selection should
3974 /// deal with this operation.
3975 DenseMap<PartialReduceActionTypes, LegalizeAction> PartialReduceMLAActions;
3976
3978 std::tuple<unsigned, unsigned, MVT::SimpleValueType>;
3979 /// For each vector (de)interleave opcode, interleave factor and fragment
3980 /// type combination, keep the corresponding LegalizeAction.
3981 DenseMap<VectorInterleaveActionKey, LegalizeAction> VectorInterleaveActions;
3982
3983 ValueTypeActionImpl ValueTypeActions;
3984
3985private:
3986 /// Targets can specify ISD nodes that they would like PerformDAGCombine
3987 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
3988 /// array.
3989 unsigned char
3990 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
3991
3992 /// For operations that must be promoted to a specific type, this holds the
3993 /// destination type. This map should be sparse, so don't hold it as an
3994 /// array.
3995 ///
3996 /// Targets add entries to this map with AddPromotedToType(..), clients access
3997 /// this with getTypeToPromoteTo(..).
3998 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
3999 PromoteToType;
4000
4001 /// FIXME: This should not live here; it should come from an analysis.
4002 const RTLIB::RuntimeLibcallsInfo RuntimeLibcallInfo;
4003
4004 /// The list of libcalls that the target will use.
4005 /// FIXME: This should not live here; it should come from an analysis.
4006 LibcallLoweringInfo Libcalls;
4007
4008 /// The bits of IndexedModeActions used to store the legalisation actions
4009 /// We store the data as | ML | MS | L | S | each taking 4 bits.
4010 enum IndexedModeActionsBits {
4011 IMAB_Store = 0,
4012 IMAB_Load = 4,
4013 IMAB_MaskedStore = 8,
4014 IMAB_MaskedLoad = 12
4015 };
4016
4017 void setIndexedModeAction(unsigned IdxMode, MVT VT, unsigned Shift,
4018 LegalizeAction Action) {
4019 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
4020 (unsigned)Action < 0xf && "Table isn't big enough!");
4021 unsigned Ty = (unsigned)VT.SimpleTy;
4022 IndexedModeActions[Ty][IdxMode] &= ~(0xf << Shift);
4023 IndexedModeActions[Ty][IdxMode] |= ((uint16_t)Action) << Shift;
4024 }
4025
4026 LegalizeAction getIndexedModeAction(unsigned IdxMode, MVT VT,
4027 unsigned Shift) const {
4028 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
4029 "Table isn't big enough!");
4030 unsigned Ty = (unsigned)VT.SimpleTy;
4031 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] >> Shift) & 0xf);
4032 }
4033
4034 unsigned getVectorTypeBreakdownImpl(LLVMContext &Context, EVT VT,
4035 EVT &IntermediateVT,
4036 unsigned &NumIntermediates,
4037 MVT &RegisterVT,
4038 bool ForCallingConv) const;
4039
4040 unsigned getVectorTypeBreakdownMVT(MVT VT, MVT &IntermediateVT,
4041 unsigned &NumIntermediates,
4042 MVT &RegisterVT);
4043
4044 /// Return the type of registers that this ValueType will eventually require.
4045 MVT getCachedRegisterType(MVT VT) const {
4046 assert((unsigned)VT.SimpleTy < std::size(RegisterTypeForVT));
4047 return RegisterTypeForVT[VT.SimpleTy];
4048 }
4049
4050 MVT getRegisterTypeImpl(LLVMContext &Context, EVT VT,
4051 bool ForCallingConv) const {
4052 if (VT.isSimple() &&
4053 !shouldUseDynamicVectorTypeBreakdown(VT, ForCallingConv))
4054 return getCachedRegisterType(VT.getSimpleVT());
4055 if (VT.isVector()) {
4056 EVT VT1;
4057 MVT RegisterVT;
4058 unsigned NumIntermediates;
4059 (void)getVectorTypeBreakdownImpl(Context, VT, VT1, NumIntermediates,
4060 RegisterVT, ForCallingConv);
4061 return RegisterVT;
4062 }
4063 if (VT.isInteger()) {
4064 return getRegisterTypeImpl(Context, getTypeToTransformTo(Context, VT),
4065 ForCallingConv);
4066 }
4067 llvm_unreachable("Unsupported extended type!");
4068 }
4069
4070 unsigned getNumRegistersImpl(LLVMContext &Context, EVT VT,
4071 bool ForCallingConv) const {
4072 if (VT.isSimple() &&
4073 !shouldUseDynamicVectorTypeBreakdown(VT, ForCallingConv)) {
4074 assert((unsigned)VT.getSimpleVT().SimpleTy <
4075 std::size(NumRegistersForVT));
4076 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
4077 }
4078 if (VT.isVector()) {
4079 EVT VT1;
4080 MVT VT2;
4081 unsigned NumIntermediates;
4082 return getVectorTypeBreakdownImpl(Context, VT, VT1, NumIntermediates, VT2,
4083 ForCallingConv);
4084 }
4085 if (VT.isInteger()) {
4086 unsigned BitWidth = VT.getSizeInBits();
4087 unsigned RegWidth =
4088 getRegisterTypeImpl(Context, VT, ForCallingConv).getSizeInBits();
4089 return (BitWidth + RegWidth - 1) / RegWidth;
4090 }
4091 llvm_unreachable("Unsupported extended type!");
4092 }
4093
4094protected:
4095 /// Return true if the extension represented by \p I is free.
4096 /// \pre \p I is a sign, zero, or fp extension and
4097 /// is[Z|FP]ExtFree of the related types is not true.
4098 virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
4099
4100 /// Depth that GatherAllAliases should continue looking for chain
4101 /// dependencies when trying to find a more preferable chain. As an
4102 /// approximation, this should be more than the number of consecutive stores
4103 /// expected to be merged.
4105
4106 /// \brief Specify maximum number of store instructions per memset call.
4107 ///
4108 /// When lowering \@llvm.memset this field specifies the maximum number of
4109 /// store operations that may be substituted for the call to memset. Targets
4110 /// must set this value based on the cost threshold for that target. Targets
4111 /// should assume that the memset will be done using as many of the largest
4112 /// store operations first, followed by smaller ones, if necessary, per
4113 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
4114 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
4115 /// store. This only applies to setting a constant array of a constant size.
4117 /// Likewise for functions with the OptSize attribute.
4119
4120 /// \brief Specify maximum number of store instructions per memcpy call.
4121 ///
4122 /// When lowering \@llvm.memcpy this field specifies the maximum number of
4123 /// store operations that may be substituted for a call to memcpy. Targets
4124 /// must set this value based on the cost threshold for that target. Targets
4125 /// should assume that the memcpy will be done using as many of the largest
4126 /// store operations first, followed by smaller ones, if necessary, per
4127 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
4128 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
4129 /// and one 1-byte store. This only applies to copying a constant array of
4130 /// constant size.
4132 /// Likewise for functions with the OptSize attribute.
4134 /// \brief Specify max number of store instructions to glue in inlined memcpy.
4135 ///
4136 /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
4137 /// of store instructions to keep together. This helps in pairing and
4138 // vectorization later on.
4140
4141 /// \brief Specify maximum number of load instructions per memcmp call.
4142 ///
4143 /// When lowering \@llvm.memcmp this field specifies the maximum number of
4144 /// pairs of load operations that may be substituted for a call to memcmp.
4145 /// Targets must set this value based on the cost threshold for that target.
4146 /// Targets should assume that the memcmp will be done using as many of the
4147 /// largest load operations first, followed by smaller ones, if necessary, per
4148 /// alignment restrictions. For example, loading 7 bytes on a 32-bit machine
4149 /// with 32-bit alignment would result in one 4-byte load, a one 2-byte load
4150 /// and one 1-byte load. This only applies to copying a constant array of
4151 /// constant size.
4153 /// Likewise for functions with the OptSize attribute.
4155
4156 /// \brief Specify maximum number of store instructions per memmove call.
4157 ///
4158 /// When lowering \@llvm.memmove this field specifies the maximum number of
4159 /// store instructions that may be substituted for a call to memmove. Targets
4160 /// must set this value based on the cost threshold for that target. Targets
4161 /// should assume that the memmove will be done using as many of the largest
4162 /// store operations first, followed by smaller ones, if necessary, per
4163 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
4164 /// with 8-bit alignment would result in nine 1-byte stores. This only
4165 /// applies to copying a constant array of constant size.
4167 /// Likewise for functions with the OptSize attribute.
4169
4170 /// Tells the code generator that select is more expensive than a branch if
4171 /// the branch is usually predicted right.
4173
4174 /// \see enableExtLdPromotion.
4176
4177 /// Return true if the value types that can be represented by the specified
4178 /// register class are all legal.
4179 bool isLegalRC(const TargetRegisterInfo &TRI,
4180 const TargetRegisterClass &RC) const;
4181
4182 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
4183 /// sequence of memory operands that is recognized by PrologEpilogInserter.
4185 MachineBasicBlock *MBB) const;
4186
4188};
4189
4190/// This class defines information used to lower LLVM code to legal SelectionDAG
4191/// operators that the target instruction selector can accept natively.
4192///
4193/// This class also defines callbacks that targets must implement to lower
4194/// target-specific constructs to SelectionDAG operators.
4196public:
4197 struct DAGCombinerInfo;
4198 struct MakeLibCallOptions;
4199
4202
4203 explicit TargetLowering(const TargetMachine &TM,
4204 const TargetSubtargetInfo &STI);
4206
4207 bool isPositionIndependent() const;
4208
4209 // If set to true, SelectionDAG nodes will be consistently processed in
4210 // topological order. This is a temporary hook until sorting can be
4211 // enabled globally.
4212 virtual bool useTopologicalSorting() const { return false; }
4213
4216 UniformityInfo *UA) const {
4217 return false;
4218 }
4219
4220 // Lets target to control the following reassociation of operands: (op (op x,
4221 // c1), y) -> (op (op x, y), c1) where N0 is (op x, c1) and N1 is y. By
4222 // default consider profitable any case where N0 has single use. This
4223 // behavior reflects the condition replaced by this target hook call in the
4224 // DAGCombiner. Any particular target can implement its own heuristic to
4225 // restrict common combiner.
4227 SDValue N1) const {
4228 return N0.hasOneUse();
4229 }
4230
4231 // Lets target to control the following reassociation of operands: (op (op x,
4232 // c1), y) -> (op (op x, y), c1) where N0 is (op x, c1) and N1 is y. By
4233 // default consider profitable any case where N0 has single use. This
4234 // behavior reflects the condition replaced by this target hook call in the
4235 // combiner. Any particular target can implement its own heuristic to
4236 // restrict common combiner.
4238 Register N1) const {
4239 return MRI.hasOneNonDBGUse(N0);
4240 }
4241
4242 virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
4243 return false;
4244 }
4245
4246 /// Returns true by value, base pointer and offset pointer and addressing mode
4247 /// by reference if the node's address can be legally represented as
4248 /// pre-indexed load / store address.
4249 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
4250 SDValue &/*Offset*/,
4251 ISD::MemIndexedMode &/*AM*/,
4252 SelectionDAG &/*DAG*/) const {
4253 return false;
4254 }
4255
4256 /// Returns true by value, base pointer and offset pointer and addressing mode
4257 /// by reference if this node can be combined with a load / store to form a
4258 /// post-indexed load / store.
4259 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
4260 SDValue &/*Base*/,
4261 SDValue &/*Offset*/,
4262 ISD::MemIndexedMode &/*AM*/,
4263 SelectionDAG &/*DAG*/) const {
4264 return false;
4265 }
4266
4267 /// Returns true if the specified base+offset is a legal indexed addressing
4268 /// mode for this target. \p MI is the load or store instruction that is being
4269 /// considered for transformation.
4271 bool IsPre, MachineRegisterInfo &MRI) const {
4272 return false;
4273 }
4274
4275 /// Return the entry encoding for a jump table in the current function. The
4276 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
4277 virtual unsigned getJumpTableEncoding() const;
4278
4279 virtual MVT getJumpTableRegTy(const DataLayout &DL) const {
4280 return getPointerTy(DL);
4281 }
4282
4283 virtual const MCExpr *
4285 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
4286 MCContext &/*Ctx*/) const {
4287 llvm_unreachable("Need to implement this hook if target has custom JTIs");
4288 }
4289
4290 /// Returns relocation base for the given PIC jumptable.
4291 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
4292 SelectionDAG &DAG) const;
4293
4294 /// This returns the relocation base for the given PIC jumptable, the same as
4295 /// getPICJumpTableRelocBase, but as an MCExpr.
4296 virtual const MCExpr *
4297 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
4298 unsigned JTI, MCContext &Ctx) const;
4299
4300 /// Return true if folding a constant offset with the given GlobalAddress is
4301 /// legal. It is frequently not legal in PIC relocation models.
4302 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
4303
4304 /// On x86, return true if the operand with index OpNo is a CALL or JUMP
4305 /// instruction, which can use either a memory constraint or an address
4306 /// constraint. -fasm-blocks "__asm call foo" lowers to
4307 /// call void asm sideeffect inteldialect "call ${0:P}", "*m..."
4308 ///
4309 /// This function is used by a hack to choose the address constraint,
4310 /// lowering to a direct call.
4311 virtual bool
4313 unsigned OpNo) const {
4314 return false;
4315 }
4316
4318 SDValue &Chain) const;
4319
4320 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
4321 SDValue &NewRHS, ISD::CondCode &CCCode,
4322 const SDLoc &DL, const SDValue OldLHS,
4323 const SDValue OldRHS) const;
4324
4325 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
4326 SDValue &NewRHS, ISD::CondCode &CCCode,
4327 const SDLoc &DL, const SDValue OldLHS,
4328 const SDValue OldRHS, SDValue &Chain,
4329 bool IsSignaling = false) const;
4330
4332 SDValue Chain, MachineMemOperand *MMO,
4333 SDValue &NewLoad, SDValue Ptr,
4334 SDValue PassThru, SDValue Mask) const {
4335 llvm_unreachable("Not Implemented");
4336 }
4337
4339 SDValue Chain, MachineMemOperand *MMO,
4340 SDValue Ptr, SDValue Val,
4341 SDValue Mask) const {
4342 llvm_unreachable("Not Implemented");
4343 }
4344
4345 /// Returns a pair of (return value, chain).
4346 /// It is an error to pass RTLIB::Unsupported as \p LibcallImpl
4347 std::pair<SDValue, SDValue>
4348 makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT,
4349 ArrayRef<SDValue> Ops, MakeLibCallOptions CallOptions,
4350 const SDLoc &dl, SDValue Chain = SDValue()) const;
4351
4352 /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
4353 std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
4354 EVT RetVT, ArrayRef<SDValue> Ops,
4355 MakeLibCallOptions CallOptions,
4356 const SDLoc &dl,
4357 SDValue Chain = SDValue()) const {
4358 return makeLibCall(DAG, getLibcallImpl(LC), RetVT, Ops, CallOptions, dl,
4359 Chain);
4360 }
4361
4362 /// Build a call argument list for \p FuncTy, taking the argument node values
4363 /// from \p Ops and the parameter types and ABI attributes from \p FuncTy and
4364 /// \p FuncAttrs. \p Ops must have one entry per parameter of \p FuncTy.
4365 static ArgListTy getArgListForFunctionType(FunctionType *FuncTy,
4366 const AttributeList &FuncAttrs,
4368
4369 /// Check whether parameters to a call that are passed in callee saved
4370 /// registers are the same as from the calling function. This needs to be
4371 /// checked for tail call eligibility.
4372 bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
4373 const uint32_t *CallerPreservedMask,
4374 const SmallVectorImpl<CCValAssign> &ArgLocs,
4375 const SmallVectorImpl<SDValue> &OutVals) const;
4376
4377 //===--------------------------------------------------------------------===//
4378 // TargetLowering Optimization Methods
4379 //
4380
4381 /// A convenience struct that encapsulates a DAG, and two SDValues for
4382 /// returning information from TargetLowering to its clients that want to
4383 /// combine.
4390
4392 bool LT, bool LO) :
4393 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
4394
4395 bool LegalTypes() const { return LegalTys; }
4396 bool LegalOperations() const { return LegalOps; }
4397
4399 Old = O;
4400 New = N;
4401 return true;
4402 }
4403 };
4404
4405 /// Determines the optimal series of memory ops to replace the memset /
4406 /// memcpy. Return true if the number of memory ops is below the threshold
4407 /// (Limit). Note that this is always the case when Limit is ~0. It returns
4408 /// the types of the sequence of memory ops to perform memset / memcpy by
4409 /// reference. If LargestVT is non-null, the target may set it to the largest
4410 /// EVT that should be used for generating the memset value (e.g., for vector
4411 /// splats). If LargestVT is null or left unchanged, the caller will compute
4412 /// it from MemOps.
4413 virtual bool findOptimalMemOpLowering(LLVMContext &Context,
4414 std::vector<EVT> &MemOps,
4415 unsigned Limit, const MemOp &Op,
4416 unsigned DstAS, unsigned SrcAS,
4417 const AttributeList &FuncAttributes,
4418 EVT *LargestVT = nullptr) const;
4419
4420 /// Check to see if the specified operand of the specified instruction is a
4421 /// constant integer. If so, check to see if there are any bits set in the
4422 /// constant that are not demanded. If so, shrink the constant and return
4423 /// true.
4425 const APInt &DemandedElts,
4426 TargetLoweringOpt &TLO) const;
4427
4428 /// Helper wrapper around ShrinkDemandedConstant, demanding all elements.
4430 TargetLoweringOpt &TLO) const;
4431
4432 // Target hook to do target-specific const optimization, which is called by
4433 // ShrinkDemandedConstant. This function should return true if the target
4434 // doesn't want ShrinkDemandedConstant to further optimize the constant.
4436 const APInt &DemandedBits,
4437 const APInt &DemandedElts,
4438 TargetLoweringOpt &TLO) const {
4439 return false;
4440 }
4441
4442 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
4443 /// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast,
4444 /// but it could be generalized for targets with other types of implicit
4445 /// widening casts.
4446 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
4447 const APInt &DemandedBits,
4448 TargetLoweringOpt &TLO) const;
4449
4450 /// Look at Op. At this point, we know that only the DemandedBits bits of the
4451 /// result of Op are ever used downstream. If we can use this information to
4452 /// simplify Op, create a new simplified DAG node and return true, returning
4453 /// the original and new nodes in Old and New. Otherwise, analyze the
4454 /// expression and return a mask of KnownOne and KnownZero bits for the
4455 /// expression (used to simplify the caller). The KnownZero/One bits may only
4456 /// be accurate for those bits in the Demanded masks.
4457 /// \p AssumeSingleUse When this parameter is true, this function will
4458 /// attempt to simplify \p Op even if there are multiple uses.
4459 /// Callers are responsible for correctly updating the DAG based on the
4460 /// results of this function, because simply replacing TLO.Old
4461 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
4462 /// has multiple uses.
4463 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
4464 const APInt &DemandedElts, KnownBits &Known,
4465 TargetLoweringOpt &TLO, unsigned Depth = 0,
4466 bool AssumeSingleUse = false) const;
4467
4468 /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
4469 /// Adds Op back to the worklist upon success.
4470 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
4471 KnownBits &Known, TargetLoweringOpt &TLO,
4472 unsigned Depth = 0,
4473 bool AssumeSingleUse = false) const;
4474
4475 /// Helper wrapper around SimplifyDemandedBits.
4476 /// Adds Op back to the worklist upon success.
4477 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
4478 DAGCombinerInfo &DCI) const;
4479
4480 /// Helper wrapper around SimplifyDemandedBits.
4481 /// Adds Op back to the worklist upon success.
4482 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
4483 const APInt &DemandedElts,
4484 DAGCombinerInfo &DCI) const;
4485
4486 /// More limited version of SimplifyDemandedBits that can be used to "look
4487 /// through" ops that don't contribute to the DemandedBits/DemandedElts -
4488 /// bitwise ops etc.
4489 SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
4490 const APInt &DemandedElts,
4491 SelectionDAG &DAG,
4492 unsigned Depth = 0) const;
4493
4494 /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
4495 /// elements.
4496 SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
4497 SelectionDAG &DAG,
4498 unsigned Depth = 0) const;
4499
4500 /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
4501 /// bits from only some vector elements.
4502 SDValue SimplifyMultipleUseDemandedVectorElts(SDValue Op,
4503 const APInt &DemandedElts,
4504 SelectionDAG &DAG,
4505 unsigned Depth = 0) const;
4506
4507 /// Look at Vector Op. At this point, we know that only the DemandedElts
4508 /// elements of the result of Op are ever used downstream. If we can use
4509 /// this information to simplify Op, create a new simplified DAG node and
4510 /// return true, storing the original and new nodes in TLO.
4511 /// Otherwise, analyze the expression and return a mask of KnownUndef and
4512 /// KnownZero elements for the expression (used to simplify the caller).
4513 /// The KnownUndef/Zero elements may only be accurate for those bits
4514 /// in the DemandedMask.
4515 /// \p AssumeSingleUse When this parameter is true, this function will
4516 /// attempt to simplify \p Op even if there are multiple uses.
4517 /// Callers are responsible for correctly updating the DAG based on the
4518 /// results of this function, because simply replacing TLO.Old
4519 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
4520 /// has multiple uses.
4521 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
4522 APInt &KnownUndef, APInt &KnownZero,
4523 TargetLoweringOpt &TLO, unsigned Depth = 0,
4524 bool AssumeSingleUse = false) const;
4525
4526 /// Helper wrapper around SimplifyDemandedVectorElts.
4527 /// Adds Op back to the worklist upon success.
4528 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
4529 DAGCombinerInfo &DCI) const;
4530
4531 /// Return true if the target supports simplifying demanded vector elements by
4532 /// converting them to undefs.
4533 virtual bool
4535 const TargetLoweringOpt &TLO) const {
4536 return true;
4537 }
4538
4539 /// If only low elements of a vector are demanded, shrink the operation to the
4540 /// returned size in bits by converting
4541 /// (op x) to insert_subvector (op (extract_subvector x)).
4542 ///
4543 /// The returned size must be a multiple of the element size, greater than or
4544 /// equal to the demanded part of the vector and less than the original
4545 /// vector size. Return 0 to disable shrinking.
4546 virtual unsigned
4548 const APInt &DemandedElts) const {
4549 return 0;
4550 }
4551
4552 /// Determine which of the bits specified in Mask are known to be either zero
4553 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
4554 /// argument allows us to only collect the known bits that are shared by the
4555 /// requested vector elements.
4556 virtual void computeKnownBitsForTargetNode(const SDValue Op,
4558 const APInt &DemandedElts,
4559 const SelectionDAG &DAG,
4560 unsigned Depth = 0) const;
4561
4562 /// Determine which of the bits specified in Mask are known to be either zero
4563 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
4564 /// argument allows us to only collect the known bits that are shared by the
4565 /// requested vector elements. This is for GISel.
4566 virtual void computeKnownBitsForTargetInstr(GISelValueTracking &Analysis,
4568 const APInt &DemandedElts,
4569 const MachineRegisterInfo &MRI,
4570 unsigned Depth = 0) const;
4571
4572 virtual void computeKnownFPClassForTargetInstr(GISelValueTracking &Analysis,
4573 Register R,
4575 const APInt &DemandedElts,
4576 const MachineRegisterInfo &MRI,
4577 unsigned Depth = 0) const;
4578
4579 /// Determine the known alignment for the pointer value \p R. This is can
4580 /// typically be inferred from the number of low known 0 bits. However, for a
4581 /// pointer with a non-integral address space, the alignment value may be
4582 /// independent from the known low bits.
4583 virtual Align computeKnownAlignForTargetInstr(GISelValueTracking &Analysis,
4584 Register R,
4585 const MachineRegisterInfo &MRI,
4586 unsigned Depth = 0) const;
4587
4588 /// Determine known bits of a pointer to a known valid stack object.
4589 /// The default implementation computes low bits based on alignment.
4590 virtual void computeKnownBitsForStackObjectPointer(KnownBits &Known,
4591 const MachineFunction &MF,
4592 Align Alignment) const;
4593
4594 /// This method can be implemented by targets that want to expose additional
4595 /// information about sign bits to the DAG Combiner. The DemandedElts
4596 /// argument allows us to only collect the minimum sign bits that are shared
4597 /// by the requested vector elements.
4598 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
4599 const APInt &DemandedElts,
4600 const SelectionDAG &DAG,
4601 unsigned Depth = 0) const;
4602
4603 /// This method can be implemented by targets that want to expose additional
4604 /// information about sign bits to GlobalISel combiners. The DemandedElts
4605 /// argument allows us to only collect the minimum sign bits that are shared
4606 /// by the requested vector elements.
4607 virtual unsigned computeNumSignBitsForTargetInstr(
4608 GISelValueTracking &Analysis, Register R, const APInt &DemandedElts,
4609 const MachineRegisterInfo &MRI, unsigned Depth = 0) const;
4610
4611 /// Attempt to simplify any target nodes based on the demanded vector
4612 /// elements, returning true on success. Otherwise, analyze the expression and
4613 /// return a mask of KnownUndef and KnownZero elements for the expression
4614 /// (used to simplify the caller). The KnownUndef/Zero elements may only be
4615 /// accurate for those bits in the DemandedMask.
4616 virtual bool SimplifyDemandedVectorEltsForTargetNode(
4617 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
4618 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
4619
4620 /// Attempt to simplify any target nodes based on the demanded bits/elts,
4621 /// returning true on success. Otherwise, analyze the
4622 /// expression and return a mask of KnownOne and KnownZero bits for the
4623 /// expression (used to simplify the caller). The KnownZero/One bits may only
4624 /// be accurate for those bits in the Demanded masks.
4625 virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op,
4626 const APInt &DemandedBits,
4627 const APInt &DemandedElts,
4629 TargetLoweringOpt &TLO,
4630 unsigned Depth = 0) const;
4631
4632 /// More limited version of SimplifyDemandedBits that can be used to "look
4633 /// through" ops that don't contribute to the DemandedBits/DemandedElts -
4634 /// bitwise ops etc.
4635 virtual SDValue SimplifyMultipleUseDemandedBitsForTargetNode(
4636 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4637 SelectionDAG &DAG, unsigned Depth) const;
4638
4639 /// Return true if this function can prove that \p Op is never poison
4640 /// and, \p Kind can be used to track poison and/or undef bits. The
4641 /// DemandedElts argument limits the check to the requested vector elements.
4642 virtual bool isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4643 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4644 UndefPoisonKind Kind, unsigned Depth) const;
4645
4646 /// Return true if Op can create undef or poison from non-undef & non-poison
4647 /// operands. The DemandedElts argument limits the check to the requested
4648 /// vector elements.
4649 virtual bool canCreateUndefOrPoisonForTargetNode(
4650 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4651 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const;
4652
4653 /// Tries to build a legal vector shuffle using the provided parameters
4654 /// or equivalent variations. The Mask argument maybe be modified as the
4655 /// function tries different variations.
4656 /// Returns an empty SDValue if the operation fails.
4657 SDValue buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
4659 SelectionDAG &DAG) const;
4660
4661 /// This method returns the constant pool value that will be loaded by LD.
4662 /// NOTE: You must check for implicit extensions of the constant by LD.
4663 virtual const Constant *getTargetConstantFromLoad(LoadSDNode *LD) const;
4664
4665 /// Determine floating-point class information for a target node. The
4666 /// DemandedElts argument allows us to only collect the known FP classes
4667 /// that are shared by the requested vector elements.
4668 virtual void computeKnownFPClassForTargetNode(const SDValue Op,
4670 const APInt &DemandedElts,
4671 const SelectionDAG &DAG,
4672 unsigned Depth = 0) const;
4673
4674 /// If \p SNaN is false, \returns true if \p Op is known to never be any
4675 /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
4676 /// NaN.
4677 virtual bool isKnownNeverNaNForTargetNode(SDValue Op,
4678 const APInt &DemandedElts,
4679 const SelectionDAG &DAG,
4680 bool SNaN = false,
4681 unsigned Depth = 0) const;
4682
4683 /// Return true if vector \p Op has the same value across all \p DemandedElts,
4684 /// indicating any elements which may be undef in the output \p UndefElts.
4685 virtual bool isSplatValueForTargetNode(SDValue Op, const APInt &DemandedElts,
4686 APInt &UndefElts,
4687 const SelectionDAG &DAG,
4688 unsigned Depth = 0) const;
4689
4690 /// Returns true if the given Opc is considered a canonical constant for the
4691 /// target, which should not be transformed back into a BUILD_VECTOR.
4693 return Op.getOpcode() == ISD::SPLAT_VECTOR ||
4694 Op.getOpcode() == ISD::SPLAT_VECTOR_PARTS;
4695 }
4696
4697 /// Return true if the given select/vselect should be considered canonical and
4698 /// not be transformed. Currently only used for "vselect (not Cond), N1, N2 ->
4699 /// vselect Cond, N2, N1".
4700 virtual bool isTargetCanonicalSelect(SDNode *N) const { return false; }
4701
4703 void *DC; // The DAG Combiner object.
4706
4707 public:
4709
4710 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
4711 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
4712
4713 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
4715 bool isAfterLegalizeDAG() const { return Level >= AfterLegalizeDAG; }
4718
4719 LLVM_ABI void AddToWorklist(SDNode *N);
4720 LLVM_ABI SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To,
4721 bool AddTo = true);
4722 LLVM_ABI SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
4723 LLVM_ABI SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
4724 bool AddTo = true);
4725
4726 LLVM_ABI bool recursivelyDeleteUnusedNodes(SDNode *N);
4727
4728 LLVM_ABI void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
4729 };
4730
4731 /// Return if the N is a constant or constant vector equal to the true value
4732 /// from getBooleanContents().
4733 bool isConstTrueVal(SDValue N) const;
4734
4735 /// Return if the N is a constant or constant vector equal to the false value
4736 /// from getBooleanContents().
4737 bool isConstFalseVal(SDValue N) const;
4738
4739 /// Return if \p N is a True value when extended to \p VT.
4740 bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
4741
4742 /// Try to simplify a setcc built with the specified operands and cc. If it is
4743 /// unable to simplify it, return a null SDValue.
4744 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
4745 bool foldBooleans, DAGCombinerInfo &DCI,
4746 const SDLoc &dl) const;
4747
4748 // For targets which wrap address, unwrap for analysis.
4749 virtual SDValue unwrapAddress(SDValue N) const { return N; }
4750
4751 /// Returns true (and the GlobalValue and the offset) if the node is a
4752 /// GlobalAddress + offset.
4753 virtual bool
4754 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
4755
4756 /// This method will be invoked for all target nodes and for any
4757 /// target-independent nodes that the target has registered with invoke it
4758 /// for.
4759 ///
4760 /// The semantics are as follows:
4761 /// Return Value:
4762 /// SDValue.Val == 0 - No change was made
4763 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
4764 /// otherwise - N should be replaced by the returned Operand.
4765 ///
4766 /// In addition, methods provided by DAGCombinerInfo may be used to perform
4767 /// more complex transformations.
4768 ///
4769 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
4770
4771 /// Return true if it is profitable to move this shift by a constant amount
4772 /// through its operand, adjusting any immediate operands as necessary to
4773 /// preserve semantics. This transformation may not be desirable if it
4774 /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
4775 /// extraction in AArch64). By default, it returns true.
4776 ///
4777 /// @param N the shift node
4778 /// @param Level the current DAGCombine legalization level.
4780 CombineLevel Level) const {
4781 SDValue ShiftLHS = N->getOperand(0);
4782 if (!ShiftLHS->hasOneUse())
4783 return false;
4784 if (ShiftLHS.getOpcode() == ISD::SIGN_EXTEND &&
4785 !ShiftLHS.getOperand(0)->hasOneUse())
4786 return false;
4787 return true;
4788 }
4789
4790 /// fold (A + vscale(C1)) + vscale(C2) -> A + vscale(C1+C2)
4791 /// If (A + vscale(C1)) is used multiple times, the fold results in a
4792 /// redundant addition instruction on the RISC-V architecture, whereas it
4793 /// does not have this effect on other architectures (e.g. AArch64).
4794 /// By default, it returns true.
4795 virtual bool isProfitableToFoldVScaleAdd(SDValue N) const { return true; }
4796
4797 /// GlobalISel - return true if it is profitable to move this shift by a
4798 /// constant amount through its operand, adjusting any immediate operands as
4799 /// necessary to preserve semantics. This transformation may not be desirable
4800 /// if it disrupts a particularly auspicious target-specific tree (e.g.
4801 /// bitfield extraction in AArch64). By default, it returns true.
4802 ///
4803 /// @param MI the shift instruction
4804 /// @param IsAfterLegal true if running after legalization.
4806 bool IsAfterLegal) const {
4807 return true;
4808 }
4809
4810 /// GlobalISel - return true if it's profitable to perform the combine:
4811 /// shl ([sza]ext x), y => zext (shl x, y)
4812 virtual bool isDesirableToPullExtFromShl(const MachineInstr &MI) const {
4813 return true;
4814 }
4815
4816 // Return AndOrSETCCFoldKind::{AddAnd, ABS} if its desirable to try and
4817 // optimize LogicOp(SETCC0, SETCC1). An example (what is implemented as of
4818 // writing this) is:
4819 // With C as a power of 2 and C != 0 and C != INT_MIN:
4820 // AddAnd:
4821 // (icmp eq A, C) | (icmp eq A, -C)
4822 // -> (icmp eq and(add(A, C), ~(C + C)), 0)
4823 // (icmp ne A, C) & (icmp ne A, -C)w
4824 // -> (icmp ne and(add(A, C), ~(C + C)), 0)
4825 // ABS:
4826 // (icmp eq A, C) | (icmp eq A, -C)
4827 // -> (icmp eq Abs(A), C)
4828 // (icmp ne A, C) & (icmp ne A, -C)w
4829 // -> (icmp ne Abs(A), C)
4830 //
4831 // @param LogicOp the logic op
4832 // @param SETCC0 the first of the SETCC nodes
4833 // @param SETCC0 the second of the SETCC nodes
4835 const SDNode *LogicOp, const SDNode *SETCC0, const SDNode *SETCC1) const {
4837 }
4838
4839 /// Return true if it is profitable to combine an XOR of a logical shift
4840 /// to create a logical shift of NOT. This transformation may not be desirable
4841 /// if it disrupts a particularly auspicious target-specific tree (e.g.
4842 /// BIC on ARM/AArch64). By default, it returns true.
4843 virtual bool isDesirableToCommuteXorWithShift(const SDNode *N) const {
4844 return true;
4845 }
4846
4847 /// Return true if the target has native support for the specified value type
4848 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
4849 /// i16 is legal, but undesirable since i16 instruction encodings are longer
4850 /// and some i16 instructions are slow.
4851 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
4852 // By default, assume all legal types are desirable.
4853 return isTypeLegal(VT);
4854 }
4855
4856 /// Overload that takes the specific node being optimized.
4857 virtual bool isTypeDesirableForOp(SDNode *N, EVT VT) const {
4858 return isTypeDesirableForOp(N->getOpcode(), VT);
4859 }
4860
4861 /// Return true if it is profitable for dag combiner to transform a floating
4862 /// point op of specified opcode to a equivalent op of an integer
4863 /// type. e.g. f32 load -> i32 load can be profitable on ARM.
4864 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
4865 EVT /*VT*/) const {
4866 return false;
4867 }
4868
4869 /// This method query the target whether it is beneficial for dag combiner to
4870 /// promote the specified node. If true, it should return the desired
4871 /// promotion type by reference.
4872 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
4873 return false;
4874 }
4875
4876 /// Return true if the target supports swifterror attribute. It optimizes
4877 /// loads and stores to reading and writing a specific register.
4878 virtual bool supportSwiftError() const {
4879 return false;
4880 }
4881
4882 /// Return true if the target supports that a subset of CSRs for the given
4883 /// machine function is handled explicitly via copies.
4884 virtual bool supportSplitCSR(MachineFunction *MF) const {
4885 return false;
4886 }
4887
4888 /// Return true if the target supports kcfi operand bundles.
4889 virtual bool supportKCFIBundles() const { return false; }
4890
4891 /// Return true if the target supports ptrauth operand bundles.
4892 virtual bool supportPtrAuthBundles() const { return false; }
4893
4894 /// Perform necessary initialization to handle a subset of CSRs explicitly
4895 /// via copies. This function is called at the beginning of instruction
4896 /// selection.
4897 virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
4898 llvm_unreachable("Not Implemented");
4899 }
4900
4901 /// Insert explicit copies in entry and exit blocks. We copy a subset of
4902 /// CSRs to virtual registers in the entry block, and copy them back to
4903 /// physical registers in the exit blocks. This function is called at the end
4904 /// of instruction selection.
4906 MachineBasicBlock *Entry,
4907 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
4908 llvm_unreachable("Not Implemented");
4909 }
4910
4911 /// Return the newly negated expression if the cost is not expensive and
4912 /// set the cost in \p Cost to indicate that if it is cheaper or neutral to
4913 /// do the negation.
4914 virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG,
4915 bool LegalOps, bool OptForSize,
4916 NegatibleCost &Cost,
4917 unsigned Depth = 0) const;
4918
4920 SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize,
4921 const NegatibleCost CostThreshold = NegatibleCost::Neutral,
4922 unsigned Depth = 0) const {
4924 SDValue Neg =
4925 getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
4926 if (!Neg)
4927 return SDValue();
4928
4929 if (Cost <= CostThreshold)
4930 return Neg;
4931
4932 // Remove the new created node to avoid the side effect to the DAG.
4933 if (Neg->use_empty())
4934 DAG.RemoveDeadNode(Neg.getNode());
4935 return SDValue();
4936 }
4937
4938 /// This is the helper function to return the newly negated expression only
4939 /// when the cost is cheaper.
4941 bool LegalOps, bool OptForSize,
4942 unsigned Depth = 0) const {
4943 return getCheaperOrNeutralNegatedExpression(Op, DAG, LegalOps, OptForSize,
4945 }
4946
4947 /// This is the helper function to return the newly negated expression if
4948 /// the cost is not expensive.
4950 bool OptForSize, unsigned Depth = 0) const {
4952 return getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
4953 }
4954
4955 //===--------------------------------------------------------------------===//
4956 // Lowering methods - These methods must be implemented by targets so that
4957 // the SelectionDAGBuilder code knows how to lower these.
4958 //
4959
4960 /// Target-specific splitting of values into parts that fit a register
4961 /// storing a legal type
4963 SelectionDAG & DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4964 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4965 return false;
4966 }
4967
4968 /// Target-specific combining of register parts into its original value
4969 virtual SDValue
4971 const SDValue *Parts, unsigned NumParts,
4972 MVT PartVT, EVT ValueVT,
4973 std::optional<CallingConv::ID> CC) const {
4974 return SDValue();
4975 }
4976
4977 /// This hook must be implemented to lower the incoming (formal) arguments,
4978 /// described by the Ins array, into the specified DAG. The implementation
4979 /// should fill in the InVals array with legal-type argument values, and
4980 /// return the resulting token chain value.
4982 SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
4983 const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
4984 SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
4985 llvm_unreachable("Not Implemented");
4986 }
4987
4988 /// Optional target hook to add target-specific actions when entering EH pad
4989 /// blocks. The implementation should return the resulting token chain value.
4990 virtual SDValue lowerEHPadEntry(SDValue Chain, const SDLoc &DL,
4991 SelectionDAG &DAG) const {
4992 return SDValue();
4993 }
4994
4995 virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
4996 ArgListTy &Args) const {}
4997
4998 /// This structure contains the information necessary for lowering
4999 /// pointer-authenticating indirect calls. It is equivalent to the "ptrauth"
5000 /// operand bundle found on the call instruction, if any.
5005
5006 /// This structure contains all information that is necessary for lowering
5007 /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
5008 /// needs to lower a call, and targets will see this struct in their LowerCall
5009 /// implementation.
5012 /// Original unlegalized return type.
5013 Type *OrigRetTy = nullptr;
5014 /// Same as OrigRetTy, or partially legalized for soft float libcalls.
5015 Type *RetTy = nullptr;
5016 bool RetSExt : 1;
5017 bool RetZExt : 1;
5018 bool IsVarArg : 1;
5019 bool IsInReg : 1;
5025 bool NoMerge : 1;
5026
5027 // IsTailCall should be modified by implementations of
5028 // TargetLowering::LowerCall that perform tail call conversions.
5029 bool IsTailCall = false;
5030
5031 // Is Call lowering done post SelectionDAG type legalization.
5033
5034 unsigned NumFixedArgs = -1;
5040 const CallBase *CB = nullptr;
5045 const ConstantInt *CFIType = nullptr;
5048
5049 std::optional<PtrAuthInfo> PAI;
5050
5056
5058 DL = dl;
5059 return *this;
5060 }
5061
5063 Chain = InChain;
5064 return *this;
5065 }
5066
5067 // setCallee with target/module-specific attributes
5069 SDValue Target, ArgListTy &&ArgsList) {
5070 return setLibCallee(CC, ResultType, ResultType, Target,
5071 std::move(ArgsList));
5072 }
5073
5075 Type *OrigResultType, SDValue Target,
5076 ArgListTy &&ArgsList) {
5077 OrigRetTy = OrigResultType;
5078 RetTy = ResultType;
5079 Callee = Target;
5080 CallConv = CC;
5081 NumFixedArgs = ArgsList.size();
5082 Args = std::move(ArgsList);
5083
5084 DAG.getTargetLoweringInfo().markLibCallAttributes(
5085 &(DAG.getMachineFunction()), CC, Args);
5086 return *this;
5087 }
5088
5090 SDValue Target, ArgListTy &&ArgsList,
5091 AttributeSet ResultAttrs = {}) {
5092 RetTy = OrigRetTy = ResultType;
5093 IsInReg = ResultAttrs.hasAttribute(Attribute::InReg);
5094 RetSExt = ResultAttrs.hasAttribute(Attribute::SExt);
5095 RetZExt = ResultAttrs.hasAttribute(Attribute::ZExt);
5096 NoMerge = ResultAttrs.hasAttribute(Attribute::NoMerge);
5097
5098 Callee = Target;
5099 CallConv = CC;
5100 NumFixedArgs = ArgsList.size();
5101 Args = std::move(ArgsList);
5102 return *this;
5103 }
5104
5106 SDValue Target, ArgListTy &&ArgsList,
5107 const CallBase &Call) {
5108 RetTy = OrigRetTy = ResultType;
5109
5110 IsInReg = Call.hasRetAttr(Attribute::InReg);
5112 Call.doesNotReturn() ||
5113 (!isa<InvokeInst>(Call) && isa<UnreachableInst>(Call.getNextNode()));
5114 IsVarArg = FTy->isVarArg();
5115 IsReturnValueUsed = !Call.use_empty();
5116 RetSExt = Call.hasRetAttr(Attribute::SExt);
5117 RetZExt = Call.hasRetAttr(Attribute::ZExt);
5118 NoMerge = Call.hasFnAttr(Attribute::NoMerge);
5119
5120 Callee = Target;
5121
5122 CallConv = Call.getCallingConv();
5123 NumFixedArgs = FTy->getNumParams();
5124 Args = std::move(ArgsList);
5125
5126 CB = &Call;
5127
5128 return *this;
5129 }
5130
5132 IsInReg = Value;
5133 return *this;
5134 }
5135
5138 return *this;
5139 }
5140
5142 IsVarArg = Value;
5143 return *this;
5144 }
5145
5147 IsTailCall = Value;
5148 return *this;
5149 }
5150
5153 return *this;
5154 }
5155
5158 return *this;
5159 }
5160
5162 RetSExt = Value;
5163 return *this;
5164 }
5165
5167 RetZExt = Value;
5168 return *this;
5169 }
5170
5173 return *this;
5174 }
5175
5178 return *this;
5179 }
5180
5182 PAI = Value;
5183 return *this;
5184 }
5185
5188 return *this;
5189 }
5190
5192 CFIType = Type;
5193 return *this;
5194 }
5195
5198 return *this;
5199 }
5200
5202 DeactivationSymbol = Sym;
5203 return *this;
5204 }
5205
5207 return Args;
5208 }
5209 };
5210
5211 /// This structure is used to pass arguments to makeLibCall function.
5213 // By passing type list before soften to makeLibCall, the target hook
5214 // shouldExtendTypeInLibCall can get the original type before soften.
5218
5219 bool IsSigned : 1;
5223 bool IsSoften : 1;
5224
5228
5230 IsSigned = Value;
5231 return *this;
5232 }
5233
5236 return *this;
5237 }
5238
5241 return *this;
5242 }
5243
5246 return *this;
5247 }
5248
5250 OpsVTBeforeSoften = OpsVT;
5251 RetVTBeforeSoften = RetVT;
5252 IsSoften = true;
5253 return *this;
5254 }
5255
5256 /// Override the argument type for an operand. Leave the type as null to use
5257 /// the type from the operand's node.
5259 OpsTypeOverrides = OpsTypes;
5260 return *this;
5261 }
5262 };
5263
5264 /// This function lowers an abstract call to a function into an actual call.
5265 /// This returns a pair of operands. The first element is the return value
5266 /// for the function (if RetTy is not VoidTy). The second element is the
5267 /// outgoing token chain. It calls LowerCall to do the actual lowering.
5268 std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
5269
5270 /// This hook must be implemented to lower calls into the specified
5271 /// DAG. The outgoing arguments to the call are described by the Outs array,
5272 /// and the values to be returned by the call are described by the Ins
5273 /// array. The implementation should fill in the InVals array with legal-type
5274 /// return values from the call, and return the resulting token chain value.
5275 virtual SDValue
5277 SmallVectorImpl<SDValue> &/*InVals*/) const {
5278 llvm_unreachable("Not Implemented");
5279 }
5280
5281 /// Target-specific cleanup for formal ByVal parameters.
5282 virtual void HandleByVal(CCState *, unsigned &, Align) const {}
5283
5284 /// This hook should be implemented to check whether the return values
5285 /// described by the Outs array can fit into the return registers. If false
5286 /// is returned, an sret-demotion is performed.
5287 virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
5288 MachineFunction &/*MF*/, bool /*isVarArg*/,
5289 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
5290 LLVMContext &/*Context*/, const Type *RetTy) const
5291 {
5292 // Return true by default to get preexisting behavior.
5293 return true;
5294 }
5295
5296 /// Annotate a stack object pointer with known-bits assertions.
5297 SDValue annotateStackObjectPointer(SDValue Ptr, SelectionDAG &DAG,
5298 const SDLoc &DL, Align Alignment) const;
5299
5300 /// This hook must be implemented to lower outgoing return values, described
5301 /// by the Outs array, into the specified DAG. The implementation should
5302 /// return the resulting token chain value.
5303 virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
5304 bool /*isVarArg*/,
5305 const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
5306 const SmallVectorImpl<SDValue> & /*OutVals*/,
5307 const SDLoc & /*dl*/,
5308 SelectionDAG & /*DAG*/) const {
5309 llvm_unreachable("Not Implemented");
5310 }
5311
5312 /// Return true if result of the specified node is used by a return node
5313 /// only. It also compute and return the input chain for the tail call.
5314 ///
5315 /// This is used to determine whether it is possible to codegen a libcall as
5316 /// tail call at legalization time.
5317 virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
5318 return false;
5319 }
5320
5321 /// Return true if the target may be able emit the call instruction as a tail
5322 /// call. This is used by optimization passes to determine if it's profitable
5323 /// to duplicate return instructions to enable tailcall optimization.
5324 virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
5325 return false;
5326 }
5327
5328 /// Return the register ID of the name passed in. Used by named register
5329 /// global variables extension. There is no target-independent behaviour
5330 /// so the default action is to bail.
5331 virtual Register getRegisterByName(const char* RegName, LLT Ty,
5332 const MachineFunction &MF) const {
5333 reportFatalUsageError("Named registers not implemented for this target");
5334 }
5335
5336 /// Return the type that should be used to zero or sign extend a
5337 /// zeroext/signext integer return value. FIXME: Some C calling conventions
5338 /// require the return type to be promoted, but this is not true all the time,
5339 /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
5340 /// conventions. The frontend should handle this and include all of the
5341 /// necessary information.
5343 ISD::NodeType /*ExtendKind*/) const {
5344 EVT MinVT = getRegisterType(Context, MVT::i32);
5345 return VT.bitsLT(MinVT) ? MinVT : VT;
5346 }
5347
5348 /// For some targets, an LLVM struct type must be broken down into multiple
5349 /// simple types, but the calling convention specifies that the entire struct
5350 /// must be passed in a block of consecutive registers.
5351 virtual bool
5353 bool isVarArg,
5354 const DataLayout &DL) const {
5355 return false;
5356 }
5357
5358 /// For most targets, an LLVM type must be broken down into multiple
5359 /// smaller types. Usually the halves are ordered according to the endianness
5360 /// but for some platform that would break. So this method will default to
5361 /// matching the endianness but can be overridden.
5362 virtual bool
5364 return DL.isLittleEndian();
5365 }
5366
5367 /// Returns a 0 terminated array of registers that can be safely used as
5368 /// scratch registers.
5370 return nullptr;
5371 }
5372
5373 /// Returns a 0 terminated array of rounding control registers that can be
5374 /// attached into strict FP call.
5378
5379 /// This callback is used to prepare for a volatile or atomic load.
5380 /// It takes a chain node as input and returns the chain for the load itself.
5381 ///
5382 /// Having a callback like this is necessary for targets like SystemZ,
5383 /// which allows a CPU to reuse the result of a previous load indefinitely,
5384 /// even if a cache-coherent store is performed by another CPU. The default
5385 /// implementation does nothing.
5387 SelectionDAG &DAG) const {
5388 return Chain;
5389 }
5390
5391 /// This callback is invoked by the type legalizer to legalize nodes with an
5392 /// illegal operand type but legal result types. It replaces the
5393 /// LowerOperation callback in the type Legalizer. The reason we can not do
5394 /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
5395 /// use this callback.
5396 ///
5397 /// TODO: Consider merging with ReplaceNodeResults.
5398 ///
5399 /// The target places new result values for the node in Results (their number
5400 /// and types must exactly match those of the original return values of
5401 /// the node), or leaves Results empty, which indicates that the node is not
5402 /// to be custom lowered after all.
5403 /// The default implementation calls LowerOperation.
5404 virtual void LowerOperationWrapper(SDNode *N,
5406 SelectionDAG &DAG) const;
5407
5408 /// This callback is invoked for operations that are unsupported by the
5409 /// target, which are registered to use 'custom' lowering, and whose defined
5410 /// values are all legal. If the target has no operations that require custom
5411 /// lowering, it need not implement this. The default implementation of this
5412 /// aborts.
5413 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
5414
5415 /// This callback is invoked when a node result type is illegal for the
5416 /// target, and the operation was registered to use 'custom' lowering for that
5417 /// result type. The target places new result values for the node in Results
5418 /// (their number and types must exactly match those of the original return
5419 /// values of the node), or leaves Results empty, which indicates that the
5420 /// node is not to be custom lowered after all.
5421 ///
5422 /// If the target has no operations that require custom lowering, it need not
5423 /// implement this. The default implementation aborts.
5424 virtual void ReplaceNodeResults(SDNode * /*N*/,
5425 SmallVectorImpl<SDValue> &/*Results*/,
5426 SelectionDAG &/*DAG*/) const {
5427 llvm_unreachable("ReplaceNodeResults not implemented for this target!");
5428 }
5429
5430 /// This method returns the name of a target specific DAG node.
5431 virtual const char *getTargetNodeName(unsigned Opcode) const;
5432
5433 /// This method returns a target specific FastISel object, or null if the
5434 /// target does not support "fast" ISel.
5436 const TargetLibraryInfo *,
5437 const LibcallLoweringInfo *) const {
5438 return nullptr;
5439 }
5440
5441 //===--------------------------------------------------------------------===//
5442 // Inline Asm Support hooks
5443 //
5444
5446 C_Register, // Constraint represents specific register(s).
5447 C_RegisterClass, // Constraint represents any of register(s) in class.
5448 C_Memory, // Memory constraint.
5449 C_Address, // Address constraint.
5450 C_Immediate, // Requires an immediate.
5451 C_Other, // Something else.
5452 C_Unknown // Unsupported constraint.
5453 };
5454
5456 // Generic weights.
5457 CW_Invalid = -1, // No match.
5458 CW_Okay = 0, // Acceptable.
5459 CW_Good = 1, // Good weight.
5460 CW_Better = 2, // Better weight.
5461 CW_Best = 3, // Best weight.
5462
5463 // Well-known weights.
5464 CW_SpecificReg = CW_Okay, // Specific register operands.
5465 CW_Register = CW_Good, // Register operands.
5466 CW_Memory = CW_Better, // Memory operands.
5467 CW_Constant = CW_Best, // Constant operand.
5468 CW_Default = CW_Okay // Default or don't know type.
5469 };
5470
5471 /// This contains information for each constraint that we are lowering.
5473 /// This contains the actual string for the code, like "m". TargetLowering
5474 /// picks the 'best' code from ConstraintInfo::Codes that most closely
5475 /// matches the operand.
5476 std::string ConstraintCode;
5477
5478 /// Information about the constraint code, e.g. Register, RegisterClass,
5479 /// Memory, Other, Unknown.
5481
5482 /// If this is the result output operand or a clobber, this is null,
5483 /// otherwise it is the incoming operand to the CallInst. This gets
5484 /// modified as the asm is processed.
5486
5487 /// The ValueType for the operand value.
5488 MVT ConstraintVT = MVT::Other;
5489
5490 /// Copy constructor for copying from a ConstraintInfo.
5493
5494 /// Return true of this is an input operand that is a matching constraint
5495 /// like "4".
5496 LLVM_ABI bool isMatchingInputConstraint() const;
5497
5498 /// If this is an input matching constraint, this method returns the output
5499 /// operand it matches.
5500 LLVM_ABI unsigned getMatchedOperand() const;
5501 };
5502
5503 using AsmOperandInfoVector = std::vector<AsmOperandInfo>;
5504
5505 /// Split up the constraint string from the inline assembly value into the
5506 /// specific constraints and their prefixes, and also tie in the associated
5507 /// operand values. If this returns an empty vector, and if the constraint
5508 /// string itself isn't empty, there was an error parsing.
5510 const TargetRegisterInfo *TRI,
5511 const CallBase &Call) const;
5512
5513 /// Examine constraint type and operand type and determine a weight value.
5514 /// The operand object must already have been set up with the operand type.
5516 AsmOperandInfo &info, int maIndex) const;
5517
5518 /// Examine constraint string and operand type and determine a weight value.
5519 /// The operand object must already have been set up with the operand type.
5521 AsmOperandInfo &info, const char *constraint) const;
5522
5523 /// Determines the constraint code and constraint type to use for the specific
5524 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
5525 /// If the actual operand being passed in is available, it can be passed in as
5526 /// Op, otherwise an empty SDValue can be passed.
5527 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
5528 SDValue Op,
5529 SelectionDAG *DAG = nullptr) const;
5530
5531 /// Given a constraint, return the type of constraint it is for this target.
5532 virtual ConstraintType getConstraintType(StringRef Constraint) const;
5533
5534 using ConstraintPair = std::pair<StringRef, TargetLowering::ConstraintType>;
5536 /// Given an OpInfo with list of constraints codes as strings, return a
5537 /// sorted Vector of pairs of constraint codes and their types in priority of
5538 /// what we'd prefer to lower them as. This may contain immediates that
5539 /// cannot be lowered, but it is meant to be a machine agnostic order of
5540 /// preferences.
5542
5543 /// Given a physical register constraint (e.g. {edx}), return the register
5544 /// number and the register class for the register.
5545 ///
5546 /// Given a register class constraint, like 'r', if this corresponds directly
5547 /// to an LLVM register class, return a register of 0 and the register class
5548 /// pointer.
5549 ///
5550 /// This should only be used for C_Register constraints. On error, this
5551 /// returns a register number of 0 and a null register class pointer.
5552 virtual std::pair<unsigned, const TargetRegisterClass *>
5554 StringRef Constraint, MVT VT) const;
5555
5557 getInlineAsmMemConstraint(StringRef ConstraintCode) const {
5558 if (ConstraintCode == "m")
5560 if (ConstraintCode == "o")
5562 if (ConstraintCode == "X")
5564 if (ConstraintCode == "p")
5567 }
5568
5569 /// Try to replace an X constraint, which matches anything, with another that
5570 /// has more specific requirements based on the type of the corresponding
5571 /// operand. This returns null if there is no replacement to make.
5572 virtual const char *LowerXConstraint(EVT ConstraintVT) const;
5573
5574 /// Lower the specified operand into the Ops vector. If it is invalid, don't
5575 /// add anything to Ops.
5576 virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint,
5577 std::vector<SDValue> &Ops,
5578 SelectionDAG &DAG) const;
5579
5580 // Lower custom output constraints. If invalid, return SDValue().
5581 virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Glue,
5582 const SDLoc &DL,
5583 const AsmOperandInfo &OpInfo,
5584 SelectionDAG &DAG) const;
5585
5586 // Targets may override this function to collect operands from the CallInst
5587 // and for example, lower them into the SelectionDAG operands.
5588 virtual void CollectTargetIntrinsicOperands(const CallInst &I,
5590 SelectionDAG &DAG) const;
5591
5592 //===--------------------------------------------------------------------===//
5593 // Div utility functions
5594 //
5595
5596 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
5597 bool IsAfterLegalTypes,
5598 SmallVectorImpl<SDNode *> &Created) const;
5599 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
5600 bool IsAfterLegalTypes,
5601 SmallVectorImpl<SDNode *> &Created) const;
5602 // Build sdiv by power-of-2 with conditional move instructions
5603 SDValue buildSDIVPow2WithCMov(SDNode *N, const APInt &Divisor,
5604 SelectionDAG &DAG,
5605 SmallVectorImpl<SDNode *> &Created) const;
5606
5607 /// Targets may override this function to provide custom SDIV lowering for
5608 /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
5609 /// assumes SDIV is expensive and replaces it with a series of other integer
5610 /// operations.
5611 virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
5612 SelectionDAG &DAG,
5613 SmallVectorImpl<SDNode *> &Created) const;
5614
5615 /// Targets may override this function to provide custom SREM lowering for
5616 /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
5617 /// assumes SREM is expensive and replaces it with a series of other integer
5618 /// operations.
5619 virtual SDValue BuildSREMPow2(SDNode *N, const APInt &Divisor,
5620 SelectionDAG &DAG,
5621 SmallVectorImpl<SDNode *> &Created) const;
5622
5623 /// Indicate whether this target prefers to combine FDIVs with the same
5624 /// divisor. If the transform should never be done, return zero. If the
5625 /// transform should be done, return the minimum number of divisor uses
5626 /// that must exist.
5627 virtual unsigned combineRepeatedFPDivisors() const {
5628 return 0;
5629 }
5630
5631 /// Hooks for building estimates in place of slower divisions and square
5632 /// roots.
5633
5634 /// Return either a square root or its reciprocal estimate value for the input
5635 /// operand.
5636 /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
5637 /// 'Enabled' as set by a potential default override attribute.
5638 /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
5639 /// refinement iterations required to generate a sufficient (though not
5640 /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
5641 /// The boolean UseOneConstNR output is used to select a Newton-Raphson
5642 /// algorithm implementation that uses either one or two constants.
5643 /// The boolean Reciprocal is used to select whether the estimate is for the
5644 /// square root of the input operand or the reciprocal of its square root.
5645 /// A target may choose to implement its own refinement within this function.
5646 /// If that's true, then return '0' as the number of RefinementSteps to avoid
5647 /// any further refinement of the estimate.
5648 /// An empty SDValue return means no estimate sequence can be created.
5650 int Enabled, int &RefinementSteps,
5651 bool &UseOneConstNR, bool Reciprocal) const {
5652 return SDValue();
5653 }
5654
5655 /// Try to convert the fminnum/fmaxnum to a compare/select sequence. This is
5656 /// required for correctness since InstCombine might have canonicalized a
5657 /// fcmp+select sequence to a FMINNUM/FMAXNUM intrinsic. If we were to fall
5658 /// through to the default expansion/soften to libcall, we might introduce a
5659 /// link-time dependency on libm into a file that originally did not have one.
5660 SDValue createSelectForFMINNUM_FMAXNUM(SDNode *Node, SelectionDAG &DAG) const;
5661
5662 /// Return a reciprocal estimate value for the input operand.
5663 /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
5664 /// 'Enabled' as set by a potential default override attribute.
5665 /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
5666 /// refinement iterations required to generate a sufficient (though not
5667 /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
5668 /// A target may choose to implement its own refinement within this function.
5669 /// If that's true, then return '0' as the number of RefinementSteps to avoid
5670 /// any further refinement of the estimate.
5671 /// An empty SDValue return means no estimate sequence can be created.
5673 int Enabled, int &RefinementSteps) const {
5674 return SDValue();
5675 }
5676
5677 /// Return a target-dependent comparison result if the input operand is
5678 /// suitable for use with a square root estimate calculation. For example, the
5679 /// comparison may check if the operand is NAN, INF, zero, normal, etc. The
5680 /// result should be used as the condition operand for a select or branch.
5681 virtual SDValue getSqrtInputTest(SDValue Operand, SelectionDAG &DAG,
5682 const DenormalMode &Mode,
5683 SDNodeFlags Flags = {}) const;
5684
5685 /// Return a target-dependent result if the input operand is not suitable for
5686 /// use with a square root estimate calculation.
5688 SelectionDAG &DAG) const {
5689 return DAG.getConstantFP(0.0, SDLoc(Operand), Operand.getValueType());
5690 }
5691
5692 //===--------------------------------------------------------------------===//
5693 // Legalization utility functions
5694 //
5695
5696 /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
5697 /// respectively, each computing an n/2-bit part of the result.
5698 /// \param Result A vector that will be filled with the parts of the result
5699 /// in little-endian order.
5700 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
5701 /// if you want to control how low bits are extracted from the LHS.
5702 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
5703 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
5704 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
5705 /// \returns true if the node has been expanded, false if it has not
5706 bool expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, SDValue LHS,
5707 SDValue RHS, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
5708 SelectionDAG &DAG, MulExpansionKind Kind,
5709 SDValue LL = SDValue(), SDValue LH = SDValue(),
5710 SDValue RL = SDValue(), SDValue RH = SDValue()) const;
5711
5712 /// Expand a MUL into two nodes. One that computes the high bits of
5713 /// the result and one that computes the low bits.
5714 /// \param HiLoVT The value type to use for the Lo and Hi nodes.
5715 /// \param LL Low bits of the LHS of the MUL. You can use this parameter
5716 /// if you want to control how low bits are extracted from the LHS.
5717 /// \param LH High bits of the LHS of the MUL. See LL for meaning.
5718 /// \param RL Low bits of the RHS of the MUL. See LL for meaning
5719 /// \param RH High bits of the RHS of the MUL. See LL for meaning.
5720 /// \returns true if the node has been expanded. false if it has not
5721 bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
5722 SelectionDAG &DAG, MulExpansionKind Kind,
5723 SDValue LL = SDValue(), SDValue LH = SDValue(),
5724 SDValue RL = SDValue(), SDValue RH = SDValue()) const;
5725
5726 /// Attempt to expand an n-bit div/rem/divrem by constant using an n/2-bit
5727 /// algorithm. First, attempt to expand the division using a n/2-bit urem by
5728 /// constant and other arithmetic ops. The n/2-bit urem by constant will be
5729 /// expanded by DAGCombiner. As this is not possible for all constant
5730 /// divisors, this method falls back to an implementation of the magic
5731 /// algorithm using n/2-bit operations.
5732 /// \param N Node to expand
5733 /// \param Result A vector that will be filled with the lo and high parts of
5734 /// the results. For *DIVREM, this will be the quotient parts followed
5735 /// by the remainder parts.
5736 /// \param HiLoVT The value type to use for the Lo and Hi parts. Should be
5737 /// half of VT.
5738 /// \param LL Low bits of the LHS of the operation. You can use this
5739 /// parameter if you want to control how low bits are extracted from
5740 /// the LHS.
5741 /// \param LH High bits of the LHS of the operation. See LL for meaning.
5742 /// \returns true if the node has been expanded, false if it has not.
5743 bool expandDIVREMByConstant(SDNode *N, SmallVectorImpl<SDValue> &Result,
5744 EVT HiLoVT, SelectionDAG &DAG,
5745 SDValue LL = SDValue(),
5746 SDValue LH = SDValue()) const;
5747
5748 /// Expand funnel shift.
5749 /// \param N Node to expand
5750 /// \returns The expansion if successful, SDValue() otherwise
5751 SDValue expandFunnelShift(SDNode *N, SelectionDAG &DAG) const;
5752
5753 /// Expand carryless multiply.
5754 /// \param N Node to expand
5755 /// \returns The expansion if successful, SDValue() otherwise
5756 SDValue expandCLMUL(SDNode *N, SelectionDAG &DAG) const;
5757
5758 /// Expand parallel bit extract (compress).
5759 /// \param N Node to expand
5760 /// \returns The expansion if successful, SDValue() otherwise
5761 SDValue expandPEXT(SDNode *N, SelectionDAG &DAG) const;
5762
5763 /// Expand parallel bit deposit (expand).
5764 /// \param N Node to expand
5765 /// \returns The expansion if successful, SDValue() otherwise
5766 SDValue expandPDEP(SDNode *N, SelectionDAG &DAG) const;
5767
5768 /// Expand rotations.
5769 /// \param N Node to expand
5770 /// \param AllowVectorOps expand vector rotate, this should only be performed
5771 /// if the legalization is happening outside of LegalizeVectorOps
5772 /// \returns The expansion if successful, SDValue() otherwise
5773 SDValue expandROT(SDNode *N, bool AllowVectorOps, SelectionDAG &DAG) const;
5774
5775 /// Expand shift-by-parts.
5776 /// \param N Node to expand
5777 /// \param Lo lower-output-part after conversion
5778 /// \param Hi upper-output-part after conversion
5779 void expandShiftParts(SDNode *N, SDValue &Lo, SDValue &Hi,
5780 SelectionDAG &DAG) const;
5781
5782 /// Expand float(f32) to SINT(i64) conversion
5783 /// \param N Node to expand
5784 /// \param Result output after conversion
5785 /// \returns True, if the expansion was successful, false otherwise
5786 bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
5787
5788 /// Expand float to UINT conversion
5789 /// \param N Node to expand
5790 /// \param Result output after conversion
5791 /// \param Chain output chain after conversion
5792 /// \returns True, if the expansion was successful, false otherwise
5793 bool expandFP_TO_UINT(SDNode *N, SDValue &Result, SDValue &Chain,
5794 SelectionDAG &DAG) const;
5795
5796 /// Expand UINT(i64) to double(f64) conversion
5797 /// \param N Node to expand
5798 /// \param Result output after conversion
5799 /// \param Chain output chain after conversion
5800 /// \returns True, if the expansion was successful, false otherwise
5801 bool expandUINT_TO_FP(SDNode *N, SDValue &Result, SDValue &Chain,
5802 SelectionDAG &DAG) const;
5803
5804 /// Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
5805 SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const;
5806
5807 /// Expand fminimum/fmaximum into multiple comparison with selects.
5808 SDValue expandFMINIMUM_FMAXIMUM(SDNode *N, SelectionDAG &DAG) const;
5809
5810 /// Expand fminimumnum/fmaximumnum into multiple comparison with selects.
5811 SDValue expandFMINIMUMNUM_FMAXIMUMNUM(SDNode *N, SelectionDAG &DAG) const;
5812
5813 /// Expand FP_TO_[US]INT_SAT into FP_TO_[US]INT and selects or min/max.
5814 /// \param N Node to expand
5815 /// \returns The expansion result
5816 SDValue expandFP_TO_INT_SAT(SDNode *N, SelectionDAG &DAG) const;
5817
5818 /// Truncate Op to ResultVT. If the result is exact, leave it alone. If it is
5819 /// not exact, force the result to be odd.
5820 /// \param ResultVT The type of result.
5821 /// \param Op The value to round.
5822 /// \returns The expansion result
5823 SDValue expandRoundInexactToOdd(EVT ResultVT, SDValue Op, const SDLoc &DL,
5824 SelectionDAG &DAG) const;
5825
5826 /// Expand round(fp) to fp conversion
5827 /// \param N Node to expand
5828 /// \returns The expansion result
5829 SDValue expandFP_ROUND(SDNode *Node, SelectionDAG &DAG) const;
5830
5831 /// Expand check for floating point class.
5832 /// \param ResultVT The type of intrinsic call result.
5833 /// \param Op The tested value.
5834 /// \param Test The test to perform.
5835 /// \param Flags The optimization flags.
5836 /// \returns The expansion result or SDValue() if it fails.
5837 SDValue expandIS_FPCLASS(EVT ResultVT, SDValue Op, FPClassTest Test,
5838 SDNodeFlags Flags, const SDLoc &DL,
5839 SelectionDAG &DAG) const;
5840
5841 /// Expand FCANONICALIZE to FMUL with 1.
5842 /// \param NodeNode to expand
5843 /// \returns The expansion result
5844 SDValue expandFCANONICALIZE(SDNode *Node, SelectionDAG &DAG) const;
5845
5846 /// Expand CONVERT_TO_ARBITRARY_FP using bit manipulation.
5847 /// \param Node Node to expand.
5848 /// \returns The expansion result, or SDValue() if fails.
5849 SDValue expandCONVERT_TO_ARBITRARY_FP(SDNode *Node, SelectionDAG &DAG) const;
5850
5851 /// Expand CONVERT_FROM_ARBITRARY_FP using bit manipulation.
5852 /// \param Node Node to expand.
5853 /// \returns The expansion result, or SDValue() if fails.
5854 SDValue expandCONVERT_FROM_ARBITRARY_FP(SDNode *Node,
5855 SelectionDAG &DAG) const;
5856
5857 /// Expand CTPOP nodes. Expands vector/scalar CTPOP nodes,
5858 /// vector nodes can only succeed if all operations are legal/custom.
5859 /// \param N Node to expand
5860 /// \returns The expansion result or SDValue() if it fails.
5861 SDValue expandCTPOP(SDNode *N, SelectionDAG &DAG) const;
5862
5863 /// Expand CTLZ/CTLZ_ZERO_POISON nodes. Expands vector/scalar CTLZ nodes,
5864 /// vector nodes can only succeed if all operations are legal/custom.
5865 /// \param N Node to expand
5866 /// \returns The expansion result or SDValue() if it fails.
5867 SDValue expandCTLZ(SDNode *N, SelectionDAG &DAG) const;
5868
5869 /// Expand CTLS (count leading sign bits) nodes.
5870 /// CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
5871 /// \param N Node to expand
5872 /// \returns The expansion result or SDValue() if it fails.
5873 SDValue expandCTLS(SDNode *N, SelectionDAG &DAG) const;
5874
5875 /// Expand CTTZ via Table Lookup.
5876 /// \param N Node to expand
5877 /// \returns The expansion result or SDValue() if it fails.
5878 SDValue CTTZTableLookup(SDNode *N, SelectionDAG &DAG, const SDLoc &DL, EVT VT,
5879 SDValue Op, unsigned NumBitsPerElt) const;
5880
5881 /// Expand CTTZ/CTTZ_ZERO_POISON nodes. Expands vector/scalar CTTZ nodes,
5882 /// vector nodes can only succeed if all operations are legal/custom.
5883 /// \param N Node to expand
5884 /// \returns The expansion result or SDValue() if it fails.
5885 SDValue expandCTTZ(SDNode *N, SelectionDAG &DAG) const;
5886
5887 /// Expand VP_CTTZ_ELTS/VP_CTTZ_ELTS_ZERO_POISON nodes.
5888 /// \param N Node to expand
5889 /// \returns The expansion result or SDValue() if it fails.
5890 SDValue expandVPCTTZElements(SDNode *N, SelectionDAG &DAG) const;
5891
5892 /// Expand VECTOR_MATCH nodes.
5893 /// \param N Node to expand
5894 /// \returns The expansion result or SDValue() if it fails.
5895 SDValue expandVectorMatch(SDNode *N, SelectionDAG &DAG) const;
5896
5897 /// Expand VECTOR_FIND_LAST_ACTIVE nodes
5898 /// \param N Node to expand
5899 /// \returns The expansion result or SDValue() if it fails.
5900 SDValue expandVectorFindLastActive(SDNode *N, SelectionDAG &DAG) const;
5901
5902 /// Expand GET_ACTIVE_LANE_MASK nodes
5903 /// \param N Node to expand
5904 /// \returns The expansion result or SDValue() if it fails.
5905 SDValue expandGetActiveLaneMask(SDNode *N, SelectionDAG &DAG) const;
5906
5907 /// Expand LOOP_DEPENDENCE_MASK nodes
5908 /// \param N Node to expand
5909 /// \returns The expansion result or SDValue() if it fails.
5910 SDValue expandLoopDependenceMask(SDNode *N, SelectionDAG &DAG) const;
5911
5912 /// Expand ABS nodes. Expands vector/scalar ABS nodes,
5913 /// vector nodes can only succeed if all operations are legal/custom.
5914 /// (ABS x) -> (XOR (ADD x, (SRA x, type_size)), (SRA x, type_size))
5915 /// \param N Node to expand
5916 /// \param IsNegative indicate negated abs
5917 /// \returns The expansion result or SDValue() if it fails.
5918 SDValue expandABS(SDNode *N, SelectionDAG &DAG,
5919 bool IsNegative = false) const;
5920
5921 /// Expand ABDS/ABDU nodes. Expands vector/scalar ABDS/ABDU nodes.
5922 /// \param N Node to expand
5923 /// \returns The expansion result or SDValue() if it fails.
5924 SDValue expandABD(SDNode *N, SelectionDAG &DAG) const;
5925
5926 /// Expand vector/scalar AVGCEILS/AVGCEILU/AVGFLOORS/AVGFLOORU nodes.
5927 /// \param N Node to expand
5928 /// \returns The expansion result or SDValue() if it fails.
5929 SDValue expandAVG(SDNode *N, SelectionDAG &DAG) const;
5930
5931 /// Expand BSWAP nodes. Expands scalar/vector BSWAP nodes with i16/i32/i64
5932 /// scalar types. Returns SDValue() if expand fails.
5933 /// \param N Node to expand
5934 /// \returns The expansion result or SDValue() if it fails.
5935 SDValue expandBSWAP(SDNode *N, SelectionDAG &DAG) const;
5936
5937 /// Expand BITREVERSE nodes. Expands scalar/vector BITREVERSE nodes.
5938 /// Returns SDValue() if expand fails.
5939 /// \param N Node to expand
5940 /// \returns The expansion result or SDValue() if it fails.
5941 SDValue expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const;
5942
5943 /// Turn load of vector type into a load of the individual elements.
5944 /// \param LD load to expand
5945 /// \returns BUILD_VECTOR and TokenFactor nodes.
5946 std::pair<SDValue, SDValue> scalarizeVectorLoad(LoadSDNode *LD,
5947 SelectionDAG &DAG) const;
5948
5949 // Turn a store of a vector type into stores of the individual elements.
5950 /// \param ST Store with a vector value type
5951 /// \returns TokenFactor of the individual store chains.
5953
5954 /// Expands an unaligned load to 2 half-size loads for an integer, and
5955 /// possibly more for vectors.
5956 std::pair<SDValue, SDValue> expandUnalignedLoad(LoadSDNode *LD,
5957 SelectionDAG &DAG) const;
5958
5959 /// Expands an unaligned store to 2 half-size stores for integer values, and
5960 /// possibly more for vectors.
5961 SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const;
5962
5963 /// Increments memory address \p Addr according to the type of the value
5964 /// \p DataVT that should be stored. If the data is stored in compressed
5965 /// form, the memory address should be incremented according to the number of
5966 /// the stored elements. This number is equal to the number of '1's bits
5967 /// in the \p Mask.
5968 /// \p DataVT is a vector type. \p Mask is a vector value.
5969 /// \p DataVT and \p Mask have the same number of vector elements.
5970 SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL,
5971 EVT DataVT, SelectionDAG &DAG,
5972 bool IsCompressedMemory) const;
5973
5974 /// Get a pointer to vector element \p Idx located in memory for a vector of
5975 /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
5976 /// bounds the returned pointer is unspecified, but will be within the vector
5977 /// bounds. \p PtrArithFlags can be used to mark that arithmetic within the
5978 /// vector in memory is known to not wrap or to be inbounds.
5979 SDValue getVectorElementPointer(
5980 SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, SDValue Index,
5981 const SDNodeFlags PtrArithFlags = SDNodeFlags()) const;
5982
5983 /// Get a pointer to vector element \p Idx located in memory for a vector of
5984 /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
5985 /// bounds the returned pointer is unspecified, but will be within the vector
5986 /// bounds. \p VecPtr is guaranteed to point to the beginning of a memory
5987 /// location large enough for the vector.
5989 EVT VecVT, SDValue Index) const {
5990 return getVectorElementPointer(DAG, VecPtr, VecVT, Index,
5993 }
5994
5995 /// Get a pointer to a sub-vector of type \p SubVecVT at index \p Idx located
5996 /// in memory for a vector of type \p VecVT starting at a base address of
5997 /// \p VecPtr. If \p Idx plus the size of \p SubVecVT is out of bounds the
5998 /// returned pointer is unspecified, but the value returned will be such that
5999 /// the entire subvector would be within the vector bounds. \p PtrArithFlags
6000 /// can be used to mark that arithmetic within the vector in memory is known
6001 /// to not wrap or to be inbounds.
6002 SDValue
6003 getVectorSubVecPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
6004 EVT SubVecVT, SDValue Index,
6005 const SDNodeFlags PtrArithFlags = SDNodeFlags()) const;
6006
6007 /// Method for building the DAG expansion of ISD::[US][MIN|MAX]. This
6008 /// method accepts integers as its arguments.
6009 SDValue expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const;
6010
6011 /// Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT. This
6012 /// method accepts integers as its arguments.
6013 SDValue expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const;
6014
6015 /// Method for building the DAG expansion of ISD::[US]CMP. This
6016 /// method accepts integers as its arguments
6017 SDValue expandCMP(SDNode *Node, SelectionDAG &DAG) const;
6018
6019 /// Method for building the DAG expansion of ISD::[US]SHLSAT. This
6020 /// method accepts integers as its arguments.
6021 SDValue expandShlSat(SDNode *Node, SelectionDAG &DAG) const;
6022
6023 /// Method for building the DAG expansion of ISD::[U|S]MULFIX[SAT]. This
6024 /// method accepts integers as its arguments.
6025 SDValue expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const;
6026
6027 /// Method for building the DAG expansion of ISD::[US]DIVFIX[SAT]. This
6028 /// method accepts integers as its arguments.
6029 /// Note: This method may fail if the division could not be performed
6030 /// within the type. Clients must retry with a wider type if this happens.
6031 SDValue expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
6033 unsigned Scale, SelectionDAG &DAG) const;
6034
6035 /// Method for building the DAG expansion of ISD::U(ADD|SUB)O. Expansion
6036 /// always suceeds and populates the Result and Overflow arguments.
6037 void expandUADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
6038 SelectionDAG &DAG) const;
6039
6040 /// Method for building the DAG expansion of ISD::S(ADD|SUB)O. Expansion
6041 /// always suceeds and populates the Result and Overflow arguments.
6042 void expandSADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
6043 SelectionDAG &DAG) const;
6044
6045 /// Method for building the DAG expansion of ISD::[US]MULO. Returns whether
6046 /// expansion was successful and populates the Result and Overflow arguments.
6047 bool expandMULO(SDNode *Node, SDValue &Result, SDValue &Overflow,
6048 SelectionDAG &DAG) const;
6049
6050 // Expand ISD::MULH[SU]. Can expand to MUL_LOHI or wide MUL if available.
6051 SDValue expandMULH(SDNode *Node, SelectionDAG &DAG) const;
6052
6053 /// Calculate the product twice the width of LHS and RHS. If HiLHS/HiRHS are
6054 /// non-null they will be included in the multiplication. The expansion works
6055 /// by splitting the 2 inputs into 4 pieces that we can multiply and add
6056 /// together without neding MULH or MUL_LOHI.
6057 void forceExpandMultiply(SelectionDAG &DAG, const SDLoc &dl, bool Signed,
6059 SDValue HiLHS = SDValue(),
6060 SDValue HiRHS = SDValue()) const;
6061
6062 /// Calculate full product of LHS and RHS either via a libcall or through
6063 /// brute force expansion of the multiplication. The expansion works by
6064 /// splitting the 2 inputs into 4 pieces that we can multiply and add together
6065 /// without needing MULH or MUL_LOHI.
6066 void forceExpandWideMUL(SelectionDAG &DAG, const SDLoc &dl, bool Signed,
6067 const SDValue LHS, const SDValue RHS, SDValue &Lo,
6068 SDValue &Hi) const;
6069
6070 /// Expand a VECREDUCE_* into an explicit calculation. If Count is specified,
6071 /// only the first Count elements of the vector are used.
6072 SDValue expandVecReduce(SDNode *Node, SelectionDAG &DAG) const;
6073
6074 /// Expand a VECREDUCE_SEQ_* into an explicit ordered calculation.
6075 SDValue expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const;
6076
6077 /// Expand an SREM or UREM using SDIV/UDIV or SDIVREM/UDIVREM, if legal.
6078 /// Returns true if the expansion was successful.
6079 bool expandREM(SDNode *Node, SDValue &Result, SelectionDAG &DAG) const;
6080
6081 /// Method for building the DAG expansion of ISD::VECTOR_SPLICE. This
6082 /// method accepts vectors as its arguments.
6083 SDValue expandVectorSplice(SDNode *Node, SelectionDAG &DAG) const;
6084
6085 /// Expand a VECTOR_INTERLEAVE without introducing wider vector types.
6086 void expandVectorInterleave(SDNode *Node, SmallVectorImpl<SDValue> &Results,
6087 SelectionDAG &DAG) const;
6088
6089 /// Expand a VECTOR_DEINTERLEAVE without introducing wider vector types.
6090 void expandVectorDeinterleave(SDNode *Node, SmallVectorImpl<SDValue> &Results,
6091 SelectionDAG &DAG) const;
6092
6093 /// Expand a vector VECTOR_COMPRESS into a sequence of extract element, store
6094 /// temporarily, advance store position, before re-loading the final vector.
6095 SDValue expandVECTOR_COMPRESS(SDNode *Node, SelectionDAG &DAG) const;
6096
6097 /// Expand a CTTZ_ELTS or CTTZ_ELTS_ZERO_POISON by calculating (VL - i) for
6098 /// each active lane (i), getting the maximum and subtracting it from VL.
6099 SDValue expandCttzElts(SDNode *Node, SelectionDAG &DAG) const;
6100
6101 /// Expands PARTIAL_REDUCE_S/UMLA nodes to a series of simpler operations,
6102 /// consisting of zext/sext, extract_subvector, mul and add operations.
6103 SDValue expandPartialReduceMLA(SDNode *Node, SelectionDAG &DAG) const;
6104
6105 /// Expands a node with multiple results to an FP or vector libcall. The
6106 /// libcall is expected to take all the operands of the \p Node followed by
6107 /// output pointers for each of the results. \p CallRetResNo can be optionally
6108 /// set to indicate that one of the results comes from the libcall's return
6109 /// value.
6110 bool expandMultipleResultFPLibCall(
6111 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
6113 std::optional<unsigned> CallRetResNo = {}) const;
6114
6115 /// Legalize a SETCC with given LHS and RHS and condition code CC on the
6116 /// current target.
6117 ///
6118 /// If the SETCC has been legalized using AND / OR, then the legalized node
6119 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
6120 /// will be set to false.
6121 ///
6122 /// If the SETCC has been legalized by using getSetCCSwappedOperands(), then
6123 /// the values of LHS and RHS will be swapped, CC will be set to the new
6124 /// condition, and NeedInvert will be set to false.
6125 ///
6126 /// If the SETCC has been legalized using the inverse condcode, then LHS and
6127 /// RHS will be unchanged, CC will set to the inverted condcode, and
6128 /// NeedInvert will be set to true. The caller must invert the result of the
6129 /// SETCC with SelectionDAG::getLogicalNOT() or take equivalent action to swap
6130 /// the effect of a true/false result.
6131 ///
6132 /// \returns true if the SETCC has been legalized, false if it hasn't.
6133 bool LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, SDValue &LHS,
6134 SDValue &RHS, SDValue &CC, bool &NeedInvert,
6135 const SDLoc &dl, SDValue &Chain,
6136 bool IsSignaling = false) const;
6137
6138 //===--------------------------------------------------------------------===//
6139 // Instruction Emitting Hooks
6140 //
6141
6142 /// This method should be implemented by targets that mark instructions with
6143 /// the 'usesCustomInserter' flag. These instructions are special in various
6144 /// ways, which require special support to insert. The specified MachineInstr
6145 /// is created but not inserted into any basic blocks, and this method is
6146 /// called to expand it into a sequence of instructions, potentially also
6147 /// creating new basic blocks and control flow.
6148 /// As long as the returned basic block is different (i.e., we created a new
6149 /// one), the custom inserter is free to modify the rest of \p MBB.
6150 virtual MachineBasicBlock *
6151 EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const;
6152
6153 /// This method should be implemented by targets that mark instructions with
6154 /// the 'hasPostISelHook' flag. These instructions must be adjusted after
6155 /// instruction selection by target hooks. e.g. To fill in optional defs for
6156 /// ARM 's' setting instructions.
6157 virtual void AdjustInstrPostInstrSelection(MachineInstr &MI,
6158 SDNode *Node) const;
6159
6160 /// If this function returns true, SelectionDAGBuilder emits a
6161 /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
6162 virtual bool useLoadStackGuardNode(const Module &M) const { return false; }
6163
6165 const SDLoc &DL) const {
6166 llvm_unreachable("not implemented for this target");
6167 }
6168
6169 /// Lower TLS global address SDNode for target independent emulated TLS model.
6170 virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
6171 SelectionDAG &DAG) const;
6172
6173 /// Expands target specific indirect branch for the case of JumpTable
6174 /// expansion.
6175 virtual SDValue expandIndirectJTBranch(const SDLoc &dl, SDValue Value,
6176 SDValue Addr, int JTI,
6177 SelectionDAG &DAG) const;
6178
6179 // seteq(x, 0) -> truncate(srl(ctlz(zext(x)), log2(#bits)))
6180 // If we're comparing for equality to zero and isCtlzFast is true, expose the
6181 // fact that this can be implemented as a ctlz/srl pair, so that the dag
6182 // combiner can fold the new nodes.
6183 SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const;
6184
6185 // Return true if `X & Y eq/ne 0` is preferable to `X & Y ne/eq Y`
6187 return true;
6188 }
6189
6190 // Expand vector operation by dividing it into smaller length operations and
6191 // joining their results. SDValue() is returned when expansion did not happen.
6192 SDValue expandVectorNaryOpBySplitting(SDNode *Node, SelectionDAG &DAG) const;
6193
6194 /// Replace an extraction of a load with a narrowed load.
6195 ///
6196 /// \param ResultVT type of the result extraction.
6197 /// \param InVecVT type of the input vector to with bitcasts resolved.
6198 /// \param EltNo index of the vector element to load.
6199 /// \param OriginalLoad vector load that to be replaced.
6200 /// \returns \p ResultVT Load on success SDValue() on failure.
6201 SDValue scalarizeExtractedVectorLoad(EVT ResultVT, const SDLoc &DL,
6202 EVT InVecVT, SDValue EltNo,
6203 LoadSDNode *OriginalLoad,
6204 SelectionDAG &DAG) const;
6205
6206protected:
6207 void setTypeIdForCallsiteInfo(const CallBase *CB, MachineFunction &MF,
6208 MachineFunction::CallSiteInfo &CSInfo) const;
6209
6210private:
6211 SDValue foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
6212 const SDLoc &DL, DAGCombinerInfo &DCI) const;
6213 SDValue foldSetCCWithOr(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
6214 const SDLoc &DL, DAGCombinerInfo &DCI) const;
6215 SDValue foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
6216 const SDLoc &DL, DAGCombinerInfo &DCI) const;
6217
6218 SDValue optimizeSetCCOfSignedTruncationCheck(EVT SCCVT, SDValue N0,
6220 DAGCombinerInfo &DCI,
6221 const SDLoc &DL) const;
6222
6223 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
6224 SDValue optimizeSetCCByHoistingAndByConstFromLogicalShift(
6225 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
6226 DAGCombinerInfo &DCI, const SDLoc &DL) const;
6227
6228 SDValue prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
6229 SDValue CompTargetNode, ISD::CondCode Cond,
6230 DAGCombinerInfo &DCI, const SDLoc &DL,
6231 SmallVectorImpl<SDNode *> &Created) const;
6232 SDValue buildUREMEqFold(EVT SETCCVT, SDValue REMNode, SDValue CompTargetNode,
6233 ISD::CondCode Cond, DAGCombinerInfo &DCI,
6234 const SDLoc &DL) const;
6235
6236 SDValue prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
6237 SDValue CompTargetNode, ISD::CondCode Cond,
6238 DAGCombinerInfo &DCI, const SDLoc &DL,
6239 SmallVectorImpl<SDNode *> &Created) const;
6240 SDValue buildSREMEqFold(EVT SETCCVT, SDValue REMNode, SDValue CompTargetNode,
6241 ISD::CondCode Cond, DAGCombinerInfo &DCI,
6242 const SDLoc &DL) const;
6243
6244 bool expandUDIVREMByConstantViaUREMDecomposition(
6245 SDNode *N, APInt Divisor, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
6246 SelectionDAG &DAG, SDValue LL, SDValue LH) const;
6247
6248 bool expandUDIVREMByConstantViaUMulHiMagic(SDNode *N, const APInt &Divisor,
6250 EVT HiLoVT, SelectionDAG &DAG,
6251 SDValue LL, SDValue LH) const;
6252};
6253
6254/// Given an LLVM IR type and return type attributes, compute the return value
6255/// EVTs and flags, and optionally also the offsets, if the return value is
6256/// being lowered to memory.
6257LLVM_ABI void GetReturnInfo(CallingConv::ID CC, Type *ReturnType,
6258 AttributeList attr,
6259 SmallVectorImpl<ISD::OutputArg> &Outs,
6260 const TargetLowering &TLI, const DataLayout &DL);
6261
6262} // end namespace llvm
6263
6264#endif // LLVM_CODEGEN_TARGETLOWERING_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis Results
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
block Block Frequency Analysis
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_READONLY
Definition Compiler.h:338
This file defines the DenseMap class.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, const APInt &Demanded)
Check to see if the specified operand of the specified instruction is a constant integer.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
lazy value info
Implement a low-level type suitable for MachineInstr level instruction selection.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
const uint64_t BitWidth
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
PowerPC Reduce CR logical Operation
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT, SelectionDAG &DAG)
Scalarize a vector store, bitcasting to TargetVT to determine the scalar type.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
bool isElementwise() const
Return true if this RMW has elementwise vector semantics.
bool isFloatingPointOperation() const
BinOp getOperation() const
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:410
LLVM_ABI bool getValueAsBool() const
Return the attribute's value as a boolean.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
CCState - This class holds information needed while lowering arguments and return values.
CCValAssign - Represent assignment of one arg/retval to a location.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class represents a function call, abstracting a target machine's calling convention.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This class represents a range of values.
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
unsigned size() const
Definition DenseMap.h:718
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:316
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Class to represent function types.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
bool isVarArg() const
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:769
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Class to represent integer types.
A wrapper class for inspecting calls to intrinsic functions.
static LLT integer(unsigned SizeInBits)
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:71
Tracks which library functions to use for a particular subtarget or function.
An instruction for reading from memory.
This class is used to represent ISD::LOAD nodes.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Context object for machine code objects.
Definition MCContext.h:83
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
MCRegisterClass - Base class of TargetRegisterClass.
Machine Value Type.
@ INVALID_SIMPLE_VALUE_TYPE
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
bool isInteger() const
Return true if this is an integer or a vector integer type.
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
ElementCount getVectorElementCount() const
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
bool isValid() const
Return true if this is a valid simple valuetype.
static MVT getIntegerVT(unsigned BitWidth)
Instructions::iterator instr_iterator
Representation of each machine instruction.
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
This is an abstract virtual class for memory operations.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
Analysis providing profile information.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
bool hasOneUse() const
Return true if there is exactly one use of this node.
bool use_empty() const
Return true if there are no uses of this node.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
EVT getValueType() const
Return the ValueType of the referenced return value.
const SDValue & getOperand(unsigned i) const
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
const DataLayout & getDataLayout() const
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVMContext * getContext() const
This instruction constructs a fixed permutation of two input vectors.
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.
An instruction for storing to memory.
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Multiway switch.
TargetInstrInfo - Interface to description of machine instruction set.
Provides information about what library functions are available for the current target.
ArgListEntry(Value *Val, SDValue Node=SDValue())
ArgListEntry(Value *Val, SDValue Node, Type *Ty)
Type * Ty
Same as OrigTy, or partially legalized for soft float libcalls.
Type * OrigTy
Original unlegalized argument type.
LegalizeTypeAction getTypeAction(MVT VT) const
void setTypeAction(MVT VT, LegalizeTypeAction Action)
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
virtual Value * emitStoreConditional(IRBuilderBase &Builder, Value *Val, Value *Addr, AtomicOrdering Ord) const
Perform a store-conditional operation to Addr.
virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT) const
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
bool isOperationExpand(unsigned Op, EVT VT) const
Return true if the specified operation is illegal on this target or unlikely to be made legal with cu...
EVT getMemValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
virtual IntegerType * getCmpLibcallReturnType(LLVMContext &Ctx) const
Return the integer type returned by comparison libcalls.
virtual bool enableAggressiveFMAFusion(LLT Ty) const
Return true if target always benefits from combining into FMA for a given value type.
virtual void emitBitTestAtomicRMWIntrinsic(AtomicRMWInst *AI) const
Perform a bit test atomicrmw using a target-specific intrinsic.
void setOperationAction(ArrayRef< unsigned > Ops, ArrayRef< MVT > VTs, LegalizeAction Action)
virtual bool requiresUniformRegister(MachineFunction &MF, const Value *) const
Allows target to decide about the register class of the specific value that is live outside the defin...
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
virtual unsigned getVaListSizeInBits(const DataLayout &DL) const
Returns the size of the platform's va_list object.
virtual bool lowerDeinterleaveIntrinsicToLoad(Instruction *Load, Value *Mask, IntrinsicInst *DI, const APInt &GapMask) const
Lower a deinterleave intrinsic to a target specific load intrinsic.
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
virtual bool preferSextInRegOfTruncate(EVT TruncVT, EVT VT, EVT ExtVT) const
virtual bool decomposeMulByConstant(LLVMContext &Context, EVT VT, SDValue C) const
Return true if it is profitable to transform an integer multiplication-by-constant into simpler opera...
void setMaxDivRemBitWidthSupported(unsigned SizeInBits)
Set the size in bits of the maximum div/rem the backend supports.
virtual bool hasAndNot(SDValue X) const
Return true if the target has a bitwise and-not operation: X = ~A & B This can be used to simplify se...
ReciprocalEstimate
Reciprocal estimate status values used by the functions below.
bool PredictableSelectIsExpensive
Tells the code generator that select is more expensive than a branch if the branch is usually predict...
virtual bool isShuffleMaskLegal(ArrayRef< int >, EVT) const
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations,...
virtual bool isAtomicAlignmentSupported(Align Alignment, uint64_t SizeInBytes) const
Return true if the target supports an atomic access of SizeInBytes bytes at the given Alignment.
virtual bool enableAggressiveFMAFusion(EVT VT) const
Return true if target always benefits from combining into FMA for a given value type.
virtual bool isComplexDeinterleavingOperationSupported(ComplexDeinterleavingOperation Operation, Type *Ty) const
Does this target support complex deinterleaving with the given operation and type.
virtual bool shouldRemoveRedundantExtend(SDValue Op) const
Return true (the default) if it is profitable to remove a sext_inreg(x) where the sext is redundant,...
bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
SDValue promoteTargetBoolean(SelectionDAG &DAG, SDValue Bool, EVT ValVT) const
Promote the given target boolean to a target boolean of the given type.
virtual bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const
Returns true if be combined with to form an ISD::FMAD.
virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT, std::optional< unsigned > ByteOffset=std::nullopt) const
Return true if it is profitable to reduce a load to a smaller type.
virtual bool hasStandaloneRem(EVT VT) const
Return true if the target can handle a standalone remainder operation.
virtual bool isExtFreeImpl(const Instruction *I) const
Return true if the extension represented by I is free.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
LegalizeAction
This enum indicates whether operations are valid for a target, and if not, what action should be used...
virtual bool shouldExpandBuildVectorWithShuffles(EVT, unsigned DefinedValues) const
LegalizeAction getIndexedMaskedStoreAction(unsigned IdxMode, MVT VT) const
Return how the indexed store should be treated: either it is legal, needs to be promoted to a larger ...
virtual bool isSelectSupported(SelectSupportKind) const
CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const
Get the CallingConv that should be used for the specified libcall.
unsigned MaxStoresPerMemcpyOptSize
Likewise for functions with the OptSize attribute.
MachineBasicBlock * emitPatchPoint(MachineInstr &MI, MachineBasicBlock *MBB) const
Replace/modify any TargetFrameIndex operands with a targte-dependent sequence of memory operands that...
virtual bool isEqualityCmpFoldedWithSignedCmp() const
Return true if instruction generated for equality comparison is folded with instruction generated for...
virtual bool preferSelectsOverBooleanArithmetic(EVT VT) const
Should we prefer selects to doing arithmetic on boolean types.
virtual bool isLegalICmpImmediate(int64_t) const
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const
Use bitwise logic to make pairs of compares more efficient.
void setAtomicLoadExtAction(ArrayRef< unsigned > ExtTypes, MVT ValVT, ArrayRef< MVT > MemVTs, LegalizeAction Action)
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT, bool MathUsed) const
Try to convert math with an overflow comparison into the corresponding DAG node operation.
ShiftLegalizationStrategy
Return the preferred strategy to legalize tihs SHIFT instruction, with ExpansionFactor being the recu...
virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const
Return true if folding a vector load into ExtVal (a sign, zero, or any extend node) is profitable.
virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const
Return if the target supports combining a chain like:
virtual Value * createComplexDeinterleavingIR(IRBuilderBase &B, ComplexDeinterleavingOperation OperationType, ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB, Value *Accumulator=nullptr) const
Create the IR node for the given complex deinterleaving operation.
virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const
Return true if it is beneficial to convert a load of a constant to just the constant itself.
virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT, unsigned Scale) const
Custom method defined by each target to indicate if an operation which may require a scale is support...
void setLoadExtAction(ArrayRef< unsigned > ExtTypes, MVT ValVT, MVT MemVT, LegalizeAction Action)
unsigned getMaximumLegalStoreInBits() const
Return maximum known-legal store size, which can be guaranteed for scalable vectors.
virtual bool shouldOptimizeMulOverflowWithZeroHighBits(LLVMContext &Context, EVT VT) const
virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *RMW) const
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
virtual Sched::Preference getSchedulingPreference(SDNode *) const
Some scheduler, e.g.
virtual MachineInstr * EmitKCFICheck(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator &MBBI, const TargetInstrInfo *TII) const
void setMinStackArgumentAlignment(Align Alignment)
Set the minimum stack alignment of an argument.
bool isExtLoad(const LoadInst *Load, const Instruction *Ext, const DataLayout &DL) const
Return true if Load and Ext can form an ExtLoad.
LegalizeTypeAction getTypeAction(MVT VT) const
virtual bool isLegalScaleForGatherScatter(uint64_t Scale, uint64_t ElemSize) const
EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
virtual bool shouldInsertFencesForAtomic(const Instruction *I) const
Whether AtomicExpandPass should automatically insert fences and reduce ordering for this atomic.
virtual AtomicOrdering atomicOperationOrderAfterFenceSplit(const Instruction *I) const
MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
bool isOperationExpandOrLibCall(unsigned Op, EVT VT) const
virtual bool allowsMisalignedMemoryAccesses(LLT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
LLT handling variant.
virtual bool isSafeMemOpType(MVT) const
Returns true if it's safe to use load / store of the specified type to expand memcpy / memset inline.
virtual void emitExpandAtomicCmpXchg(AtomicCmpXchgInst *CI) const
Perform a cmpxchg expansion using a target-specific method.
virtual ISD::NodeType getExtendForAtomicRMWArg(unsigned Op) const
Returns how the platform's atomic rmw operations expect their input argument to be extended (ZERO_EXT...
const TargetMachine & getTargetMachine() const
unsigned MaxLoadsPerMemcmp
Specify maximum number of load instructions per memcmp call.
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
bool rangeFitsInWord(const APInt &Low, const APInt &High, const DataLayout &DL) const
Check whether the range [Low,High] fits in a machine word.
virtual bool isCtpopFast(EVT VT) const
Return true if ctpop instruction is fast.
virtual MachineMemOperand::Flags getTargetMMOFlags(const Instruction &I) const
This callback is used to inspect load/store instructions and add target-specific MachineMemOperand fl...
virtual Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception typeid on entry to a la...
unsigned MaxGluedStoresPerMemcpy
Specify max number of store instructions to glue in inlined memcpy.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
bool isPaddedAtMostSignificantBitsWhenStored(EVT VT) const
Indicates if any padding is guaranteed to go at the most significant bits when storing the type to me...
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
Convenience method to set an operation to Promote and specify the type in a single call.
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
virtual bool useStackGuardMixFP() const
If this function returns true, stack protection checks should mix the frame pointer (or whichever poi...
unsigned getMinCmpXchgSizeInBits() const
Returns the size of the smallest cmpxchg or ll/sc instruction the backend supports.
virtual Value * emitMaskedAtomicRMWIntrinsic(IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const
Perform a masked atomicrmw using a target-specific intrinsic.
virtual bool areJTsAllowed(const Function *Fn) const
Return true if lowering to a jump table is allowed.
virtual LegalizeAction getCustomTruncStoreAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Returns an alternative action to use when the coarser lookups (configured through setTruncStoreAction...
bool enableExtLdPromotion() const
Return true if the target wants to use the optimization that turns ext(promotableInst1(....
virtual bool isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, LLT DestTy, LLT SrcTy) const
Return true if an fpext operation input to an Opcode operation is free (for instance,...
void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT, LegalizeAction Action)
Indicate that the specified indexed masked load does or does not work with the specified type and ind...
void setMaxBytesForAlignment(unsigned MaxBytes)
bool isOperationLegalOrPromote(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal using promotion.
void setHasExtractBitsInsn(bool hasExtractInsn=true)
Tells the code generator that the target has BitExtract instructions.
void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth)
Tells the code generator which bitwidths to bypass.
virtual bool hasBitTest(SDValue X, SDValue Y) const
Return true if the target has a bit-test instruction: (X & (1 << Y)) ==/!= 0 This knowledge can be us...
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
virtual AtomicExpansionKind shouldExpandAtomicCmpXchgInIR(const AtomicCmpXchgInst *AI) const
Returns how the given atomic cmpxchg should be expanded by the IR-level AtomicExpand pass.
virtual bool needsFixedCatchObjects() const
virtual bool isAnyExtFree(EVT FromTy, EVT ToTy) const
Return true is an anyext is free from FromTy to ToTy.
EVT getLegalTypeToTransformTo(LLVMContext &Context, EVT VT) const
Perform getTypeToTransformTo repeatedly until a legal type is obtained.
virtual Value * emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy, Value *Addr, AtomicOrdering Ord) const
Perform a load-linked operation on Addr, returning a "Value *" with the corresponding pointee type.
void setMaxLargeFPConvertBitWidthSupported(unsigned SizeInBits)
Set the size in bits of the maximum fp to/from int conversion the backend supports.
const LibcallLoweringInfo & getLibcallLoweringInfo() const
virtual unsigned getNumRegisters(LLVMContext &Context, EVT VT, std::optional< MVT > RegisterVT=std::nullopt) const
Return the number of registers that this ValueType will eventually require.
virtual bool isCheapToSpeculateCttz(Type *Ty) const
Return true if it is cheap to speculate a call to intrinsic cttz.
unsigned getMinimumBitTestCmps() const
Retuen the minimum of largest number of comparisons in BitTest.
bool isJumpExpensive() const
Return true if Flow Control is an expensive operation that should be avoided.
virtual bool useFPRegsForHalfType() const
LegalizeAction getCondCodeAction(ISD::CondCode CC, MVT VT) const
Return how the condition code should be treated: either it is legal, needs to be expanded to some oth...
bool hasExtractBitsInsn() const
Return true if the target has BitExtract instructions.
virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT, const SelectionDAG &DAG, const MachineMemOperand &MMO) const
Return true if the following transform is beneficial: fold (conv (load x)) -> (load (conv*)x) On arch...
LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const
Return how the indexed store should be treated: either it is legal, needs to be promoted to a larger ...
void setIndexedLoadAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed load does or does not work with the specified type and indicate w...
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall implementation.
void setPrefLoopAlignment(Align Alignment)
Set the target's preferred loop alignment.
virtual bool areTwoSDNodeTargetMMOFlagsMergeable(const MemSDNode &NodeX, const MemSDNode &NodeY) const
Return true if it is valid to merge the TargetMMOFlags in two SDNodes.
virtual bool isCommutativeBinOp(unsigned Opcode) const
Returns true if the opcode is a commutative binary operation.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
virtual bool isFPImmLegal(const APFloat &, EVT, bool ForCodeSize=false) const
Returns true if the target can instruction select the specified FP immediate natively.
LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Return how this store with truncation should be treated: either it is legal, needs to be promoted to ...
virtual unsigned getPreferredFPToIntOpcode(unsigned Op, EVT FromVT, EVT ToVT) const
virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const
Return true if extraction of a scalar element from the given vector type at the given index is cheap.
virtual Value * emitCanLoadSpeculatively(IRBuilderBase &Builder, Value *Ptr, Value *Size) const
Emit code to check if a speculative load of the given size from Ptr is safe.
void setOperationAction(ArrayRef< unsigned > Ops, MVT VT, LegalizeAction Action)
virtual bool optimizeFMulOrFDivAsShiftAddBitcast(SDNode *N, SDValue FPConst, SDValue IntPow2) const
SelectSupportKind
Enum that describes what type of support for selects the target has.
RTLIB::LibcallImpl getMemcpyImpl() const
LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const
Return how the indexed load should be treated: either it is legal, needs to be promoted to a larger s...
virtual bool shouldTransformSignedTruncationCheck(EVT XVT, unsigned KeptBits) const
Should we tranform the IR-optimal check for whether given truncation down into KeptBits would be trun...
virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, EVT DestVT, EVT SrcVT) const
Return true if an fpext operation input to an Opcode operation is free (for instance,...
bool isLegalRC(const TargetRegisterInfo &TRI, const TargetRegisterClass &RC) const
Return true if the value types that can be represented by the specified register class are all legal.
virtual TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const
Return the preferred vector type legalization action.
virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const
Return true if a truncation from FromTy to ToTy is permitted when deciding whether a call is in tail ...
void setAtomicLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Let target indicate that an extending atomic load of the specified type is legal.
virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const
Returns true if the index type for a masked gather/scatter requires extending.
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
virtual StringRef getStackProbeSymbolName(const MachineFunction &MF) const
LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT, unsigned Scale) const
Some fixed point operations may be natively supported by the target but only for specific scales.
virtual bool preferScalarizeSplat(SDNode *N) const
void setVectorInterleaveAction(unsigned Opc, unsigned Factor, MVT VT, LegalizeAction Action)
Indicate how a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the given interleave factor Factor ...
bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
virtual ISD::NodeType getExtendForAtomicOps() const
Returns how the platform's atomic operations are extended (ZERO_EXTEND, SIGN_EXTEND,...
Sched::Preference getSchedulingPreference() const
Return target scheduling preference.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
virtual LLT getOptimalMemOpLLT(const MemOp &Op, const AttributeList &) const
LLT returning variant.
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not.
virtual ExtractSubvectorCost getExtractSubvectorCost(EVT ResVT, EVT SrcVT, unsigned Index) const
Return the cost of extracting a subvector of type ResVT from a vector of type SrcVT,...
virtual void emitExpandAtomicRMW(AtomicRMWInst *AI) const
Perform a atomicrmw expansion using a target-specific way.
unsigned MaxStoresPerMemsetOptSize
Likewise for functions with the OptSize attribute.
virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const
Return true if it is profitable to convert a select of FP constants into a constant pool load whose a...
bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const
When splitting a value of the specified type into parts, does the Lo or Hi part come first?
virtual bool hasStackProbeSymbol(const MachineFunction &MF) const
Returns the name of the symbol used to emit stack probes or the empty string if not applicable.
bool isSlowDivBypassed() const
Returns true if target has indicated at least one type should be bypassed.
virtual Align getABIAlignmentForCallingConv(Type *ArgTy, const DataLayout &DL) const
Certain targets have context sensitive alignment requirements, where one type has the alignment requi...
virtual bool isMulAddWithConstProfitable(SDValue AddNode, SDValue ConstNode) const
Return true if it may be profitable to transform (mul (add x, c1), c2) -> (add (mul x,...
virtual bool shouldExtendTypeInLibCall(EVT Type) const
Returns true if arguments should be extended in lib calls.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
void setVectorInterleaveAction(ArrayRef< unsigned > Opcodes, ArrayRef< unsigned > Factors, MVT VT, LegalizeAction Action)
bool isPartialReduceMLALegalOrCustom(unsigned Opc, EVT AccVT, EVT InputVT) const
Return true if a PARTIAL_REDUCE_U/SMLA node with the specified types is legal or custom for this targ...
virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const
Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
unsigned MaxStoresPerMemmove
Specify maximum number of store instructions per memmove call.
virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context, EVT VT, EVT CCVT) const
Returns true if we should normalize select(N0&N1, X, Y) => select(N0, select(N1, X,...
bool isSuitableForBitTests(const DenseMap< const BasicBlock *, unsigned int > &DestCmps, const APInt &Low, const APInt &High, const DataLayout &DL) const
Return true if lowering to a bit test is suitable for a set of case clusters which contains NumDests ...
virtual bool shouldExpandGetActiveLaneMask(EVT VT, EVT OpVT) const
Return true if the @llvm.get.active.lane.mask intrinsic should be expanded using generic code in Sele...
virtual bool shallExtractConstSplatVectorElementToStore(Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const
Return true if the target shall perform extract vector element and store given that the vector is kno...
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual bool hasMultipleConditionRegisters(EVT VT) const
Does the target have multiple (allocatable) condition registers that can be used to store the results...
unsigned getMaxExpandSizeMemcmp(bool OptSize) const
Get maximum # of load operations permitted for memcmp.
bool isStrictFPEnabled() const
Return true if the target support strict float operation.
virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const
Return true if creating a shift of the type by the given amount is not profitable.
virtual bool shouldPreservePtrArith(const Function &F, EVT PtrVT) const
True if target has some particular form of dealing with pointer arithmetic semantics for pointers wit...
virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const
Return true if an fpext operation is free (for instance, because single-precision floating-point numb...
virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const
Return the ValueType of the result of SETCC operations.
virtual bool lowerInterleavedStore(Instruction *Store, Value *Mask, ShuffleVectorInst *SVI, unsigned Factor, const APInt &GapMask) const
Lower an interleaved store to target specific intrinsics.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
unsigned MaxStoresPerMemmoveOptSize
Likewise for functions with the OptSize attribute.
virtual bool shouldFoldSelectWithSingleBitTest(EVT VT, const APInt &AndMask) const
MVT getSimpleValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the MVT corresponding to this LLVM type. See getValueType.
BooleanContent getBooleanContents(bool isVec, bool isFloat) const
For targets without i1 registers, this gives the nature of the high-bits of boolean values held in ty...
bool isVectorInterleaveLegalOrCustom(unsigned Opc, unsigned Factor, EVT VT) const
Return true if a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the given interleave factor and f...
LegalizeAction getVectorInterleaveAction(unsigned Opc, unsigned Factor, EVT VT) const
Return how a VECTOR_INTERLEAVE or VECTOR_DEINTERLEAVE node with the given interleave factor and VT sh...
virtual bool shouldReassociateReduction(unsigned RedOpc, EVT VT) const
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
virtual CondMergingParams getJumpConditionMergingParams(Instruction::BinaryOps, const Value *, const Value *, const Function *) const
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal for a comparison of the specified types on this ...
virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const
Return true if the target can combine store(extractelement VectorTy,Idx).
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual bool shouldFoldConstantShiftPairToMask(const SDNode *N) const
Return true if it is profitable to fold a pair of shifts into a mask.
MVT getProgramPointerTy(const DataLayout &DL) const
Return the type for code pointers, which is determined by the program address space specified through...
void setIndexedStoreAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed store does or does not work with the specified type and indicate ...
ExtractSubvectorCost
Enum that specifies how expensive lowering an EXTRACT_SUBVECTOR is.
virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilderBase &Builder) const
void setSupportsUnalignedAtomics(bool UnalignedSupported)
Sets whether unaligned atomic operations are supported.
void setLoadExtAction(ArrayRef< unsigned > ExtTypes, MVT ValVT, ArrayRef< MVT > MemVTs, LegalizeAction Action)
virtual void emitExpandAtomicStore(StoreInst *SI) const
Perform a atomic store using a target-specific way.
virtual bool preferIncOfAddToSubOfNot(EVT VT) const
These two forms are equivalent: sub y, (xor x, -1) add (add x, 1), y The variant with two add's is IR...
virtual bool ShouldShrinkFPConstant(EVT) const
If true, then instruction selection should seek to shrink the FP constant of the specified type to a ...
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
unsigned getMaxDivRemBitWidthSupported() const
Returns the size in bits of the maximum div/rem the backend supports.
virtual bool isLegalAddImmediate(int64_t) const
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
virtual unsigned getMaxSupportedInterleaveFactor() const
Get the maximum supported factor for interleaved memory accesses.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
virtual bool shouldKeepZExtForFP16Conv() const
Does this target require the clearing of high-order bits in a register passed to the fp16 to fp conve...
virtual AtomicExpansionKind shouldCastAtomicRMWIInIR(AtomicRMWInst *RMWI) const
Returns how the given atomic atomicrmw should be cast by the IR-level AtomicExpand pass.
void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT, LegalizeAction Action)
Indicate that the specified indexed masked store does or does not work with the specified type and in...
virtual bool canTransformPtrArithOutOfBounds(const Function &F, EVT PtrVT) const
True if the target allows transformations of in-bounds pointer arithmetic that cause out-of-bounds in...
virtual bool shouldConsiderGEPOffsetSplit() const
const ValueTypeActionImpl & getValueTypeActions() const
virtual bool canCombineTruncStore(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, bool LegalOnly) const
TargetLoweringBase(const TargetMachine &TM, const TargetSubtargetInfo &STI)
NOTE: The TargetMachine owns TLOF.
unsigned MaxStoresPerMemset
Specify maximum number of store instructions per memset call.
virtual bool isTruncateFree(SDValue Val, EVT VT2) const
Return true if truncating the specific node Val to type VT2 is free.
virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const
virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const
Return the maximum number of "x & (x - 1)" operations that can be done instead of deferring to a cust...
virtual bool shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, unsigned OldShiftOpcode, unsigned NewShiftOpcode, SelectionDAG &DAG) const
Given the pattern (X & (C l>>/<< Y)) ==/!= 0 return true if it should be transformed into: ((X <</l>>...
virtual bool shouldInsertTrailingSeqCstFenceForAtomicStore(const Instruction *I) const
Whether AtomicExpandPass should automatically insert a seq_cst trailing fence without reducing the or...
virtual bool isFNegFree(EVT VT) const
Return true if an fneg operation is free to the point where it is never worthwhile to replace it with...
void setPartialReduceMLAAction(unsigned Opc, MVT AccVT, MVT InputVT, LegalizeAction Action)
Indicate how a PARTIAL_REDUCE_U/SMLA node with Acc type AccVT and Input type InputVT should be treate...
virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const
Returns how the given (atomic) load should be expanded by the IR-level AtomicExpand pass.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
bool isExtFree(const Instruction *I) const
Return true if the extension represented by I is free.
virtual MVT getFenceOperandTy(const DataLayout &DL) const
Return the type for operands of fence.
virtual Value * emitMaskedAtomicCmpXchgIntrinsic(IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const
Perform a masked cmpxchg using a target-specific intrinsic.
virtual bool isZExtFree(EVT FromTy, EVT ToTy) const
virtual ISD::NodeType getExtendForAtomicCmpSwapArg() const
Returns how the platform's atomic compare and swap expects its comparison value to be extended (ZERO_...
virtual bool shouldFoldSelectWithIdentityConstant(unsigned BinOpcode, EVT VT, unsigned SelectOpcode, SDValue X, SDValue Y) const
Return true if pulling a binary operation into a select with an identity constant is profitable.
BooleanContent
Enum that describes how the target represents true/false values.
virtual bool shouldExpandGetVectorLength(EVT CountVT, unsigned VF, bool IsScalable) const
virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const
Return true if integer divide is usually cheaper than a sequence of several shifts,...
virtual ShiftLegalizationStrategy preferredShiftLegalizationStrategy(SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const
virtual uint8_t getRepRegClassCostFor(MVT VT) const
Return the cost of the 'representative' register class for the specified value type.
virtual bool isZExtFree(LLT FromTy, LLT ToTy, LLVMContext &Ctx) const
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
LegalizeAction getPartialReduceMLAAction(unsigned Opc, EVT AccVT, EVT InputVT) const
Return how a PARTIAL_REDUCE_U/SMLA node with Acc type AccVT and Input type InputVT should be treated.
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
virtual bool mergeStoresAfterLegalization(EVT MemVT) const
Allow store merging for the specified type after legalization in addition to before legalization.
unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Vector types are broken down into some number of legal first class types.
virtual bool shouldIssueAtomicLoadForAtomicEmulationLoop(void) const
virtual bool shouldMergeStoreOfLoadsOverCall(EVT, EVT) const
Returns true if it's profitable to allow merging store of loads when there are functions calls betwee...
virtual bool isProfitableToHoist(Instruction *I) const
unsigned getGatherAllAliasesMaxDepth() const
virtual LegalizeAction getCustomOperationAction(SDNode &Op) const
How to legalize this custom operation?
virtual bool isFMAFasterThanFMulAndFAdd(const Function &F, Type *) const
IR version.
virtual bool hasAndNotCompare(SDValue Y) const
Return true if the target should transform: (X & Y) == Y ---> (~X & Y) == 0 (X & Y) !...
virtual bool storeOfVectorConstantIsCheap(bool IsZero, EVT MemVT, unsigned NumElem, unsigned AddrSpace) const
Return true if it is expected to be cheaper to do a store of vector constant with the given size and ...
unsigned MaxLoadsPerMemcmpOptSize
Likewise for functions with the OptSize attribute.
virtual MVT hasFastEqualityCompare(unsigned NumBits) const
Return the preferred operand type if the target has a quick way to compare integer values of the give...
virtual const TargetRegisterClass * getRepRegClassFor(MVT VT) const
Return the 'representative' register class for the specified value type.
virtual bool isNarrowingProfitable(SDNode *N, EVT SrcVT, EVT DestVT) const
Return true if it's profitable to narrow operations of type SrcVT to DestVT.
LegalizeAction getLoadAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return how this load with extension should be treated: either it is legal, needs to be promoted to a ...
virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const
Return true if it is cheaper to split the store of a merged int val from a pair of smaller values int...
bool shouldUseDynamicVectorTypeBreakdown(EVT VT, bool ForCallingConv) const
TargetLoweringBase(const TargetLoweringBase &)=delete
virtual unsigned getMaxGluedStoresPerMemcpy() const
Get maximum # of store operations to be glued together.
virtual bool isBinOp(unsigned Opcode) const
Return true if the node is a math/logic binary operator.
virtual bool shouldFoldMaskToVariableShiftPair(SDValue X) const
There are two ways to clear extreme bits (either low or high): Mask: x & (-1 << y) (the instcombine c...
virtual bool alignLoopsWithOptSize() const
Should loops be aligned even when the function is marked OptSize (but not MinSize).
unsigned getMaxAtomicSizeInBitsSupported() const
Returns the maximum atomic operation size (in bits) supported by the backend.
bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
void setMinCmpXchgSizeInBits(unsigned SizeInBits)
Sets the minimum cmpxchg or ll/sc size supported by the backend.
virtual bool canMergeStoresTo(unsigned AS, EVT MemVT, const MachineFunction &MF) const
Returns if it's reasonable to merge stores to MemVT size.
void setPartialReduceMLAAction(ArrayRef< unsigned > Opcodes, MVT AccVT, MVT InputVT, LegalizeAction Action)
LegalizeAction getStrictFPOperationAction(unsigned Op, EVT VT) const
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
virtual bool preferABDSToABSWithNSW(EVT VT) const
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
virtual bool getAddrModeArguments(const IntrinsicInst *, SmallVectorImpl< Value * > &, Type *&) const
CodeGenPrepare sinks address calculations into the same BB as Load/Store instructions reading the add...
virtual bool hasInlineStackProbe(const MachineFunction &MF) const
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setCondCodeAction(ArrayRef< ISD::CondCode > CCs, MVT VT, LegalizeAction Action)
Indicate that the specified condition code is or isn't supported on the target and indicate what to d...
void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
const DenseMap< unsigned int, unsigned int > & getBypassSlowDivWidths() const
Returns map of slow types for division or remainder with corresponding fast types.
void setOperationPromotedToType(ArrayRef< unsigned > Ops, MVT OrigVT, MVT DestVT)
unsigned getMaxLargeFPConvertBitWidthSupported() const
Returns the size in bits of the maximum fp to/from int conversion the backend supports.
virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, LLT) const
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const
bool isTruncStoreLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Return true if the specified store with truncation is legal on this target.
virtual bool isCheapToSpeculateCtlz(Type *Ty) const
Return true if it is cheap to speculate a call to intrinsic ctlz.
virtual void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &Infos, const CallBase &I, MachineFunction &MF, unsigned Intrinsic) const
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
virtual bool signExtendConstant(const ConstantInt *C) const
Return true if this constant should be sign extended when promoting to a larger type.
virtual bool lowerInterleaveIntrinsicToStore(Instruction *Store, Value *Mask, ArrayRef< Value * > InterleaveValues) const
Lower an interleave intrinsic to a target specific store intrinsic.
virtual bool isTruncateFree(LLT FromTy, LLT ToTy, LLVMContext &Ctx) const
AndOrSETCCFoldKind
Enum of different potentially desirable ways to fold (and/or (setcc ...), (setcc ....
virtual bool shouldScalarizeBinop(SDValue VecOp) const
Try to convert an extract element of a vector binary operation into an extract element followed by a ...
Align getPrefFunctionAlignment() const
Return the preferred function alignment.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Get the libcall impl routine name for the specified libcall.
virtual void emitExpandAtomicLoad(LoadInst *LI) const
Perform a atomic load using a target-specific way.
Align getMinFunctionAlignment() const
Return the minimum function alignment.
virtual AtomicExpansionKind shouldExpandAtomicStoreInIR(StoreInst *SI) const
Returns how the given (atomic) store should be expanded by the IR-level AtomicExpand pass into.
virtual bool preferVectorizedNonPowerOfTwoTypeBreakdown() const
Return true if fixed-length, non-power-of-two vectors should be broken down into legal vector parts i...
static StringRef getLibcallImplName(RTLIB::LibcallImpl Call)
Get the libcall routine name for the specified libcall implementation.
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
virtual bool isCtlzFast() const
Return true if ctlz instruction is fast.
virtual bool useSoftFloat() const
virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT, const SelectionDAG &DAG, const MachineMemOperand &MMO) const
Return true if the following transform is beneficial: (store (y (conv x)), y*)) -> (store x,...
BooleanContent getBooleanContents(EVT Type) const
virtual LegalizeAction getCustomLoadAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Returns an alternative action to use when the coarser lookups (configured through setLoadExtAction an...
bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const
Return true if the specified indexed load is legal on this target.
virtual int64_t getPreferredLargeGEPBaseOffset(int64_t MinOffset, int64_t MaxOffset) const
Return the prefered common base offset.
virtual bool isVectorClearMaskLegal(ArrayRef< int >, EVT) const
Similar to isShuffleMaskLegal.
LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const
Return pair that represents the legalization kind (first) that needs to happen to EVT (second) in ord...
Align getMinStackArgumentAlignment() const
Return the minimum stack alignment of an argument.
virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT, bool IsSigned) const
Return true if it is more correct/profitable to use strict FP_TO_INT conversion operations - canonica...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
bool hasTargetDAGCombine(ISD::NodeType NT) const
If true, the target has custom DAG combine transformations that it can perform for the specified node...
void setLibcallImpl(RTLIB::Libcall Call, RTLIB::LibcallImpl Impl)
virtual bool fallBackToDAGISel(const Instruction &Inst) const
unsigned GatherAllAliasesMaxDepth
Depth that GatherAllAliases should continue looking for chain dependencies when trying to find a more...
virtual bool shouldSplatInsEltVarIndex(EVT) const
Return true if inserting a scalar into a variable element of an undef vector is more efficiently hand...
LegalizeAction getIndexedMaskedLoadAction(unsigned IdxMode, MVT VT) const
Return how the indexed load should be treated: either it is legal, needs to be promoted to a larger s...
NegatibleCost
Enum that specifies when a float negation is beneficial.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual unsigned preferedOpcodeForCmpEqPiecesOfOperand(EVT VT, unsigned ShiftOpc, bool MayTransformRotate, const APInt &ShiftOrRotateAmt, const std::optional< APInt > &AndMask) const
virtual void emitCmpArithAtomicRMWIntrinsic(AtomicRMWInst *AI) const
Perform a atomicrmw which the result is only used by comparison, using a target-specific intrinsic.
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
virtual bool isFMADLegal(const MachineInstr &MI, LLT Ty) const
Returns true if MI can be combined with another instruction to form TargetOpcode::G_FMAD.
void setCondCodeAction(ArrayRef< ISD::CondCode > CCs, ArrayRef< MVT > VTs, LegalizeAction Action)
const char * getLibcallName(RTLIB::Libcall Call) const
Get the libcall routine name for the specified libcall.
virtual bool isLegalAddScalableImmediate(int64_t) const
Return true if adding the specified scalable immediate is legal, that is the target has add instructi...
std::vector< ArgListEntry > ArgListTy
virtual bool shouldAlignPointerArgs(CallInst *, unsigned &, Align &) const
Return true if the pointer arguments to CI should be aligned by aligning the object whose address is ...
virtual bool hasVectorBlend() const
Return true if the target has a vector blend instruction.
virtual AtomicExpansionKind shouldCastAtomicStoreInIR(StoreInst *SI) const
Returns how the given (atomic) store should be cast by the IR-level AtomicExpand pass into.
bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Return true if the specified store with truncation has solution on this target.
void setIndexedStoreAction(ArrayRef< unsigned > IdxModes, ArrayRef< MVT > VTs, LegalizeAction Action)
virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const
virtual Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception address on entry to an ...
virtual MachineMemOperand::Flags getTargetMMOFlags(const MemSDNode &Node) const
This callback is used to inspect load/store SDNode.
virtual EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &) const
Returns the target specific optimal type for load and store operations as a result of memset,...
virtual Type * shouldConvertSplatType(ShuffleVectorInst *SVI) const
Given a shuffle vector SVI representing a vector splat, return a new scalar type of size equal to SVI...
virtual bool isZExtFree(SDValue Val, EVT VT2) const
Return true if zero-extending the specific node Val to type VT2 is free (either because it's implicit...
void setAtomicLoadExtAction(ArrayRef< unsigned > ExtTypes, MVT ValVT, MVT MemVT, LegalizeAction Action)
virtual bool shouldRemoveExtendFromGSIndex(SDValue Extend, EVT DataVT) const
virtual LLVM_READONLY LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const
Return the preferred type to use for a shift opcode, given the shifted amount type is ShiftValueTy.
bool isBeneficialToExpandPowI(int64_t Exponent, bool OptForSize) const
Return true if it is beneficial to expand an @llvm.powi.
LLT getVectorIdxLLT(const DataLayout &DL) const
Returns the type to be used for the index operand of: G_INSERT_VECTOR_ELT, G_EXTRACT_VECTOR_ELT,...
virtual EVT getAsmOperandValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
void setIndexedLoadAction(ArrayRef< unsigned > IdxModes, ArrayRef< MVT > VTs, LegalizeAction Action)
virtual AtomicExpansionKind shouldCastAtomicLoadInIR(LoadInst *LI) const
Returns how the given (atomic) load should be cast by the IR-level AtomicExpand pass.
bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal or custom for a comparison of the specified type...
virtual bool isComplexDeinterleavingSupported() const
Does this target support complex deinterleaving.
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
MVT getFrameIndexTy(const DataLayout &DL) const
Return the type for frame index, which is determined by the alloca address space specified through th...
virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal on this target.
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
virtual bool addressingModeSupportsTLS(const GlobalValue &) const
Returns true if the targets addressing mode can target thread local storage (TLS).
bool isLoadLegalOrCustom(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal or custom on this target.
virtual bool shouldConvertPhiType(Type *From, Type *To) const
Given a set in interconnected phis of type 'From' that are loaded/stored or bitcast to type 'To',...
virtual bool isFAbsFree(EVT VT) const
Return true if an fabs operation is free to the point where it is never worthwhile to replace it with...
virtual bool isLegalStoreImmediate(int64_t Value) const
Return true if the specified immediate is legal for the value input of a store instruction.
virtual bool preferZeroCompareBranch() const
Return true if the heuristic to prefer icmp eq zero should be used in code gen prepare.
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
virtual bool lowerInterleavedLoad(Instruction *Load, Value *Mask, ArrayRef< ShuffleVectorInst * > Shuffles, ArrayRef< unsigned > Indices, unsigned Factor, const APInt &GapMask) const
Lower an interleaved load to target specific intrinsics.
virtual unsigned getVectorIdxWidth(const DataLayout &DL) const
Returns the type to be used for the index operand vector operations.
MVT getTypeToPromoteTo(unsigned Op, MVT VT) const
If the action for this operation is to promote, this method returns the ValueType to promote to.
virtual bool generateFMAsInMachineCombiner(EVT VT, CodeGenOptLevel OptLevel) const
virtual LoadInst * lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const
On some platforms, an AtomicRMW that never actually modifies the value (such as fetch_add of 0) can b...
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace, Instruction *I=nullptr) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
virtual bool hasPairedLoad(EVT, Align &) const
Return true if the target supplies and combines to a paired load two loaded values of type LoadedType...
virtual bool convertSelectOfConstantsToMath(EVT VT) const
Return true if a select of constants (select Cond, C1, C2) should be transformed into simple math ops...
bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool optimizeExtendOrTruncateConversion(Instruction *I, Loop *L, const TargetTransformInfo &TTI) const
Try to optimize extending or truncating conversion instructions (like zext, trunc,...
virtual MVT getVPExplicitVectorLengthTy() const
Returns the type to be used for the EVL/AVL operand of VP nodes: ISD::VP_UDIV, ISD::VP_SDIV,...
std::pair< LegalizeTypeAction, EVT > LegalizeKind
LegalizeKind holds the legalization kind that needs to happen to EVT in order to type-legalize it.
TargetLoweringBase & operator=(const TargetLoweringBase &)=delete
MulExpansionKind
Enum that specifies when a multiplication should be expanded.
static ISD::NodeType getExtendForContent(BooleanContent Content)
const RTLIB::RuntimeLibcallsInfo & getRuntimeLibcallsInfo() const
virtual bool shouldConvertFpToSat(unsigned Op, EVT FPVT, EVT VT) const
Should we generate fp_to_si_sat and fp_to_ui_sat from type FPVT to type VT.
virtual bool supportKCFIBundles() const
Return true if the target supports kcfi operand bundles.
virtual ConstraintWeight getMultipleConstraintMatchWeight(AsmOperandInfo &info, int maIndex) const
Examine constraint type and operand type and determine a weight value.
SmallVector< ConstraintPair > ConstraintGroup
virtual SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps, bool &UseOneConstNR, bool Reciprocal) const
Hooks for building estimates in place of slower divisions and square roots.
virtual bool isDesirableToCommuteWithShift(const MachineInstr &MI, bool IsAfterLegal) const
GlobalISel - return true if it is profitable to move this shift by a constant amount through its oper...
virtual bool supportPtrAuthBundles() const
Return true if the target supports ptrauth operand bundles.
virtual void ReplaceNodeResults(SDNode *, SmallVectorImpl< SDValue > &, SelectionDAG &) const
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
virtual bool isUsedByReturnOnly(SDNode *, SDValue &) const
Return true if result of the specified node is used by a return node only.
virtual bool supportSwiftError() const
Return true if the target supports swifterror attribute.
virtual SDValue visitMaskedLoad(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, MachineMemOperand *MMO, SDValue &NewLoad, SDValue Ptr, SDValue PassThru, SDValue Mask) const
virtual unsigned getPreferredShrunkVectorSizeInBits(SDValue Op, const APInt &DemandedElts) const
If only low elements of a vector are demanded, shrink the operation to the returned size in bits by c...
SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, unsigned Depth=0) const
This is the helper function to return the newly negated expression if the cost is not expensive.
virtual bool isProfitableToFoldVScaleAdd(SDValue N) const
fold (A + vscale(C1)) + vscale(C2) -> A + vscale(C1+C2) If (A + vscale(C1)) is used multiple times,...
virtual bool isReassocProfitable(SelectionDAG &DAG, SDValue N0, SDValue N1) const
virtual bool isTypeDesirableForOp(SDNode *N, EVT VT) const
Overload that takes the specific node being optimized.
virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT, ISD::NodeType) const
Return the type that should be used to zero or sign extend a zeroext/signext integer return value.
SDValue getCheaperOrNeutralNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, const NegatibleCost CostThreshold=NegatibleCost::Neutral, unsigned Depth=0) const
virtual Register getRegisterByName(const char *RegName, LLT Ty, const MachineFunction &MF) const
Return the register ID of the name passed in.
virtual InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const
virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, TargetLoweringOpt &TLO) const
std::vector< AsmOperandInfo > AsmOperandInfoVector
virtual bool isTargetCanonicalConstantNode(SDValue Op) const
Returns true if the given Opc is considered a canonical constant for the target, which should not be ...
virtual bool isTargetCanonicalSelect(SDNode *N) const
Return true if the given select/vselect should be considered canonical and not be transformed.
SDValue getCheaperNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, unsigned Depth=0) const
This is the helper function to return the newly negated expression only when the cost is cheaper.
virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL, SelectionDAG &DAG) const
This callback is used to prepare for a volatile or atomic load.
virtual SDValue emitStackGuardMixFP(SelectionDAG &DAG, SDValue Val, const SDLoc &DL) const
virtual SDValue lowerEHPadEntry(SDValue Chain, const SDLoc &DL, SelectionDAG &DAG) const
Optional target hook to add target-specific actions when entering EH pad blocks.
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual SDValue unwrapAddress(SDValue N) const
virtual bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, std::optional< CallingConv::ID > CC) const
Target-specific splitting of values into parts that fit a register storing a legal type.
virtual bool IsDesirableToPromoteOp(SDValue, EVT &) const
This method query the target whether it is beneficial for dag combiner to promote the specified node.
virtual SDValue joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, std::optional< CallingConv::ID > CC) const
Target-specific combining of register parts into its original value.
virtual void insertCopiesSplitCSR(MachineBasicBlock *Entry, const SmallVectorImpl< MachineBasicBlock * > &Exits) const
Insert explicit copies in entry and exit blocks.
virtual SDValue LowerCall(CallLoweringInfo &, SmallVectorImpl< SDValue > &) const
This hook must be implemented to lower calls into the specified DAG.
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is 'desirable' to us...
~TargetLowering() override
TargetLowering & operator=(const TargetLowering &)=delete
virtual bool isDesirableToPullExtFromShl(const MachineInstr &MI) const
GlobalISel - return true if it's profitable to perform the combine: shl ([sza]ext x),...
bool isPositionIndependent() const
std::pair< StringRef, TargetLowering::ConstraintType > ConstraintPair
virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, NegatibleCost &Cost, unsigned Depth=0) const
Return the newly negated expression if the cost is not expensive and set the cost in Cost to indicate...
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
virtual bool isIndexingLegal(MachineInstr &MI, Register Base, Register Offset, bool IsPre, MachineRegisterInfo &MRI) const
Returns true if the specified base+offset is a legal indexed addressing mode for this target.
ConstraintGroup getConstraintPreferences(AsmOperandInfo &OpInfo) const
Given an OpInfo with list of constraints codes as strings, return a sorted Vector of pairs of constra...
virtual void initializeSplitCSR(MachineBasicBlock *Entry) const
Perform necessary initialization to handle a subset of CSRs explicitly via copies.
virtual bool isSDNodeSourceOfDivergence(const SDNode *N, FunctionLoweringInfo *FLI, UniformityInfo *UA) const
virtual SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &RefinementSteps) const
Return a reciprocal estimate value for the input operand.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
virtual bool isSDNodeAlwaysUniform(const SDNode *N) const
virtual bool isDesirableToCommuteXorWithShift(const SDNode *N) const
Return true if it is profitable to combine an XOR of a logical shift to create a logical shift of NOT...
TargetLowering(const TargetLowering &)=delete
virtual bool shouldSimplifyDemandedVectorElts(SDValue Op, const TargetLoweringOpt &TLO) const
Return true if the target supports simplifying demanded vector elements by converting them to undefs.
virtual SDValue LowerFormalArguments(SDValue, CallingConv::ID, bool, const SmallVectorImpl< ISD::InputArg > &, const SDLoc &, SelectionDAG &, SmallVectorImpl< SDValue > &) const
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array,...
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
virtual SDValue getSqrtResultForDenormInput(SDValue Operand, SelectionDAG &DAG) const
Return a target-dependent result if the input operand is not suitable for use with a square root esti...
virtual bool getPostIndexedAddressParts(SDNode *, SDNode *, SDValue &, SDValue &, ISD::MemIndexedMode &, SelectionDAG &) const
Returns true by value, base pointer and offset pointer and addressing mode by reference if this node ...
virtual bool shouldSplitFunctionArgumentsAsLittleEndian(const DataLayout &DL) const
For most targets, an LLVM type must be broken down into multiple smaller types.
virtual ArrayRef< MCPhysReg > getRoundingControlRegisters() const
Returns a 0 terminated array of rounding control registers that can be attached into strict FP call.
virtual SDValue LowerReturn(SDValue, CallingConv::ID, bool, const SmallVectorImpl< ISD::OutputArg > &, const SmallVectorImpl< SDValue > &, const SDLoc &, SelectionDAG &) const
This hook must be implemented to lower outgoing return values, described by the Outs array,...
virtual bool functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv, bool isVarArg, const DataLayout &DL) const
For some targets, an LLVM struct type must be broken down into multiple simple types,...
virtual bool isDesirableToCommuteWithShift(const SDNode *N, CombineLevel Level) const
Return true if it is profitable to move this shift by a constant amount through its operand,...
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
virtual SDValue visitMaskedStore(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, MachineMemOperand *MMO, SDValue Ptr, SDValue Val, SDValue Mask) const
virtual const MCExpr * LowerCustomJumpTableEntry(const MachineJumpTableInfo *, const MachineBasicBlock *, unsigned, MCContext &) const
virtual bool useTopologicalSorting() const
virtual bool useLoadStackGuardNode(const Module &M) const
If this function returns true, SelectionDAGBuilder emits a LOAD_STACK_GUARD node when it is lowering ...
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
It is an error to pass RTLIB::UNKNOWN_LIBCALL as LC.
virtual FastISel * createFastISel(FunctionLoweringInfo &, const TargetLibraryInfo *, const LibcallLoweringInfo *) const
This method returns a target specific FastISel object, or null if the target does not support "fast" ...
virtual unsigned combineRepeatedFPDivisors() const
Indicate whether this target prefers to combine FDIVs with the same divisor.
virtual AndOrSETCCFoldKind isDesirableToCombineLogicOpOfSETCC(const SDNode *LogicOp, const SDNode *SETCC0, const SDNode *SETCC1) const
virtual void HandleByVal(CCState *, unsigned &, Align) const
Target-specific cleanup for formal ByVal parameters.
virtual const MCPhysReg * getScratchRegisters(CallingConv::ID CC) const
Returns a 0 terminated array of registers that can be safely used as scratch registers.
virtual bool getPreIndexedAddressParts(SDNode *, SDValue &, SDValue &, ISD::MemIndexedMode &, SelectionDAG &) const
Returns true by value, base pointer and offset pointer and addressing mode by reference if the node's...
SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, SDValue Index, const SDNodeFlags PtrArithFlags=SDNodeFlags()) const
Get a pointer to vector element Idx located in memory for a vector of type VecVT starting at a base a...
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
virtual bool supportSplitCSR(MachineFunction *MF) const
Return true if the target supports that a subset of CSRs for the given machine function is handled ex...
virtual bool isReassocProfitable(MachineRegisterInfo &MRI, Register N0, Register N1) const
virtual bool mayBeEmittedAsTailCall(const CallInst *) const
Return true if the target may be able emit the call instruction as a tail call.
virtual bool isInlineAsmTargetBranch(const SmallVectorImpl< StringRef > &AsmStrs, unsigned OpNo) const
On x86, return true if the operand with index OpNo is a CALL or JUMP instruction, which can use eithe...
SDValue getInboundsVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, SDValue Index) const
Get a pointer to vector element Idx located in memory for a vector of type VecVT starting at a base a...
virtual MVT getJumpTableRegTy(const DataLayout &DL) const
virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC, ArgListTy &Args) const
virtual bool CanLowerReturn(CallingConv::ID, MachineFunction &, bool, const SmallVectorImpl< ISD::OutputArg > &, LLVMContext &, const Type *RetTy) const
This hook should be implemented to check whether the return values described by the Outs array can fi...
virtual bool isXAndYEqZeroPreferableToXAndYEqY(ISD::CondCode, EVT) const
virtual bool isDesirableToTransformToIntegerOp(unsigned, EVT) const
Return true if it is profitable for dag combiner to transform a floating point op of specified opcode...
Primary interface to the complete machine description for the target machine.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
This is the common base class for vector predication intrinsics.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
CallInst * Call
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ AVGSUBFLOORS
AVGSUBFLOORS/AVGSUBFLOORU - Averaging subtract - Subtract two integers using an integer of type i[N+1...
Definition ISDOpcodes.h:733
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:397
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:296
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:527
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ SMULFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:403
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:879
@ PSEUDO_FMIN
PSEUDO_FMIN is strictly equivalent to op0 olt op1 ?
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:796
@ SDIVFIX
RESULT = [US]DIVFIX(LHS, RHS, SCALE) - Perform fixed point division on 2 integers with the same width...
Definition ISDOpcodes.h:410
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:870
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:725
@ PARTIAL_REDUCE_FMLA
@ BRIND
BRIND - Indirect branch.
@ BR_JT
BR_JT - Jumptable branch.
@ VECTOR_INTERLEAVE
VECTOR_INTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor to...
Definition ISDOpcodes.h:640
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:682
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:714
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:787
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Perform floating-point minimumNumber or maximumNumber on two values,...
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:876
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:745
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:416
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:483
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:482
@ FMINIMUM
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:952
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:757
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:720
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:306
@ SPLAT_VECTOR_PARTS
SPLAT_VECTOR_PARTS(SCALAR1, SCALAR2, ...) - Returns a vector with the scalar values joined together a...
Definition ISDOpcodes.h:691
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ VECTOR_DEINTERLEAVE
VECTOR_DEINTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor ...
Definition ISDOpcodes.h:629
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:740
static const int LAST_LOADEXT_TYPE
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:61
This namespace contains all of the command line option processing machinery.
Definition CodeGenData.h:33
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:577
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
LLVM_ABI void GetReturnInfo(CallingConv::ID CC, Type *ReturnType, AttributeList attr, SmallVectorImpl< ISD::OutputArg > &Outs, const TargetLowering &TLI, const DataLayout &DL)
Given an LLVM IR type and return type attributes, compute the return value EVTs and flags,...
InstructionCost Cost
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
LLVM_ABI bool isConstTrueVal(const TargetLowering &TLI, int64_t Val, bool IsVector, bool IsFP)
Returns true if given the TargetLowering's boolean contents information, the value Val contains a tru...
Definition Utils.cpp:1606
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:227
@ Default
-O2, -Os, -Oz
Definition CodeGen.h:230
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
LLVM_ABI EVT getApproximateEVTForLLT(LLT Ty, LLVMContext &Ctx)
TargetTransformInfo TTI
CombineLevel
Definition DAGCombine.h:15
@ AfterLegalizeDAG
Definition DAGCombine.h:19
@ AfterLegalizeVectorOps
Definition DAGCombine.h:18
@ BeforeLegalizeTypes
Definition DAGCombine.h:16
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
LLVM_ABI bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, bool ReturnsFirstArg=false)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition Analysis.cpp:656
DWARFExpression::Operation Op
LLVM_ABI bool isConstFalseVal(const TargetLowering &TLI, int64_t Val, bool IsVector, bool IsFP)
Definition Utils.cpp:1619
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
ExceptionHandling
Definition CodeGen.h:54
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Represent subnormal handling kind for floating point instruction inputs and outputs.
Extended Value Type.
Definition ValueTypes.h:35
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition ValueTypes.h:266
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
bool isFixedLengthVector() const
Definition ValueTypes.h:199
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
bool isExtended() const
Test if the given EVT is extended (as opposed to being simple).
Definition ValueTypes.h:150
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
ConstraintInfo()=default
Default constructor.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
bool isDstAligned(Align AlignCheck) const
bool isFixedDstAlign() const
uint64_t size() const
static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign, bool IsZeroMemset, bool IsVolatile)
Align getDstAlign() const
bool isMemcpyStrSrc() const
bool isAligned(Align AlignCheck) const
static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile, bool MemcpyStrSrc=false)
bool isSrcAligned(Align AlignCheck) const
bool isMemcpyOrMemmoveWithFixedDstAlign() const
bool isMemcpyOrMemmove() const
bool isMemmove() const
bool isMemset() const
bool isMemcpy() const
static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile)
bool isZeroMemset() const
bool isVolatile() const
Align getSrcAlign() const
A simple container for information about the supported runtime calls.
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
These are IR-level optimization flags that may be propagated to SDNodes.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
std::optional< unsigned > fallbackAddressSpace
PointerUnion< const Value *, const PseudoSourceValue * > ptrVal
This contains information for each constraint that we are lowering.
AsmOperandInfo(InlineAsm::ConstraintInfo Info)
Copy constructor for copying from a ConstraintInfo.
MVT ConstraintVT
The ValueType for the operand value.
TargetLowering::ConstraintType ConstraintType
Information about the constraint code, e.g.
std::string ConstraintCode
This contains the actual string for the code, like "m".
Value * CallOperandVal
If this is the result output operand or a clobber, this is null, otherwise it is the incoming operand...
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setConvergent(bool Value=true)
CallLoweringInfo & setIsPostTypeLegalization(bool Value=true)
CallLoweringInfo & setDeactivationSymbol(GlobalValue *Sym)
CallLoweringInfo & setCallee(Type *ResultType, FunctionType *FTy, SDValue Target, ArgListTy &&ArgsList, const CallBase &Call)
CallLoweringInfo & setCFIType(const ConstantInt *Type)
CallLoweringInfo & setInRegister(bool Value=true)
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
SmallVector< ISD::InputArg, 32 > Ins
CallLoweringInfo & setVarArg(bool Value=true)
Type * OrigRetTy
Original unlegalized return type.
std::optional< PtrAuthInfo > PAI
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setIsPatchPoint(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, Type *OrigResultType, SDValue Target, ArgListTy &&ArgsList)
CallLoweringInfo & setTailCall(bool Value=true)
CallLoweringInfo & setIsPreallocated(bool Value=true)
CallLoweringInfo & setSExtResult(bool Value=true)
CallLoweringInfo & setNoReturn(bool Value=true)
CallLoweringInfo & setConvergenceControlToken(SDValue Token)
SmallVector< ISD::OutputArg, 32 > Outs
Type * RetTy
Same as OrigRetTy, or partially legalized for soft float libcalls.
CallLoweringInfo & setChain(SDValue InChain)
CallLoweringInfo & setPtrAuth(PtrAuthInfo Value)
CallLoweringInfo & setCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList, AttributeSet ResultAttrs={})
DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
This structure is used to pass arguments to makeLibCall function.
MakeLibCallOptions & setIsPostTypeLegalization(bool Value=true)
MakeLibCallOptions & setDiscardResult(bool Value=true)
MakeLibCallOptions & setTypeListBeforeSoften(ArrayRef< EVT > OpsVT, EVT RetVT)
MakeLibCallOptions & setIsSigned(bool Value=true)
MakeLibCallOptions & setNoReturn(bool Value=true)
MakeLibCallOptions & setOpsTypeOverrides(ArrayRef< Type * > OpsTypes)
Override the argument type for an operand.
This structure contains the information necessary for lowering pointer-authenticating indirect calls.
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...
TargetLoweringOpt(SelectionDAG &InDAG, bool LT, bool LO)