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