LLVM 18.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"
41#include "llvm/IR/Attributes.h"
42#include "llvm/IR/CallingConv.h"
43#include "llvm/IR/DataLayout.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/InlineAsm.h"
47#include "llvm/IR/Instruction.h"
49#include "llvm/IR/Type.h"
54#include <algorithm>
55#include <cassert>
56#include <climits>
57#include <cstdint>
58#include <iterator>
59#include <map>
60#include <string>
61#include <utility>
62#include <vector>
63
64namespace llvm {
65
66class AssumptionCache;
67class CCState;
68class CCValAssign;
69class Constant;
70class FastISel;
71class FunctionLoweringInfo;
72class GlobalValue;
73class Loop;
74class GISelKnownBits;
75class IntrinsicInst;
76class IRBuilderBase;
77struct KnownBits;
78class LLVMContext;
79class MachineBasicBlock;
80class MachineFunction;
81class MachineInstr;
82class MachineJumpTableInfo;
83class MachineLoop;
84class MachineRegisterInfo;
85class MCContext;
86class MCExpr;
87class Module;
88class ProfileSummaryInfo;
89class TargetLibraryInfo;
90class TargetMachine;
91class TargetRegisterClass;
92class TargetRegisterInfo;
93class TargetTransformInfo;
94class Value;
95
96namespace Sched {
97
99 None, // No preference
100 Source, // Follow source order.
101 RegPressure, // Scheduling for lowest register pressure.
102 Hybrid, // Scheduling for both latency and register pressure.
103 ILP, // Scheduling for ILP in low register pressure mode.
104 VLIW, // Scheduling for VLIW targets.
105 Fast, // Fast suboptimal list scheduling
106 Linearize // Linearize DAG, no scheduling
108
109} // end namespace Sched
110
111// MemOp models a memory operation, either memset or memcpy/memmove.
112struct MemOp {
113private:
114 // Shared
115 uint64_t Size;
116 bool DstAlignCanChange; // true if destination alignment can satisfy any
117 // constraint.
118 Align DstAlign; // Specified alignment of the memory operation.
119
120 bool AllowOverlap;
121 // memset only
122 bool IsMemset; // If setthis memory operation is a memset.
123 bool ZeroMemset; // If set clears out memory with zeros.
124 // memcpy only
125 bool MemcpyStrSrc; // Indicates whether the memcpy source is an in-register
126 // constant so it does not need to be loaded.
127 Align SrcAlign; // Inferred alignment of the source or default value if the
128 // memory operation does not need to load the value.
129public:
130 static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
131 Align SrcAlign, bool IsVolatile,
132 bool MemcpyStrSrc = false) {
133 MemOp Op;
134 Op.Size = Size;
135 Op.DstAlignCanChange = DstAlignCanChange;
136 Op.DstAlign = DstAlign;
137 Op.AllowOverlap = !IsVolatile;
138 Op.IsMemset = false;
139 Op.ZeroMemset = false;
140 Op.MemcpyStrSrc = MemcpyStrSrc;
141 Op.SrcAlign = SrcAlign;
142 return Op;
143 }
144
145 static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
146 bool IsZeroMemset, bool IsVolatile) {
147 MemOp Op;
148 Op.Size = Size;
149 Op.DstAlignCanChange = DstAlignCanChange;
150 Op.DstAlign = DstAlign;
151 Op.AllowOverlap = !IsVolatile;
152 Op.IsMemset = true;
153 Op.ZeroMemset = IsZeroMemset;
154 Op.MemcpyStrSrc = false;
155 return Op;
156 }
157
158 uint64_t size() const { return Size; }
160 assert(!DstAlignCanChange);
161 return DstAlign;
162 }
163 bool isFixedDstAlign() const { return !DstAlignCanChange; }
164 bool allowOverlap() const { return AllowOverlap; }
165 bool isMemset() const { return IsMemset; }
166 bool isMemcpy() const { return !IsMemset; }
168 return isMemcpy() && !DstAlignCanChange;
169 }
170 bool isZeroMemset() const { return isMemset() && ZeroMemset; }
171 bool isMemcpyStrSrc() const {
172 assert(isMemcpy() && "Must be a memcpy");
173 return MemcpyStrSrc;
174 }
176 assert(isMemcpy() && "Must be a memcpy");
177 return SrcAlign;
178 }
179 bool isSrcAligned(Align AlignCheck) const {
180 return isMemset() || llvm::isAligned(AlignCheck, SrcAlign.value());
181 }
182 bool isDstAligned(Align AlignCheck) const {
183 return DstAlignCanChange || llvm::isAligned(AlignCheck, DstAlign.value());
184 }
185 bool isAligned(Align AlignCheck) const {
186 return isSrcAligned(AlignCheck) && isDstAligned(AlignCheck);
187 }
188};
189
190/// This base class for TargetLowering contains the SelectionDAG-independent
191/// parts that can be used from the rest of CodeGen.
193public:
194 /// This enum indicates whether operations are valid for a target, and if not,
195 /// what action should be used to make them valid.
196 enum LegalizeAction : uint8_t {
197 Legal, // The target natively supports this operation.
198 Promote, // This operation should be executed in a larger type.
199 Expand, // Try to expand this to other ops, otherwise use a libcall.
200 LibCall, // Don't try to expand this to other ops, always use a libcall.
201 Custom // Use the LowerOperation hook to implement custom lowering.
202 };
203
204 /// This enum indicates whether a types are legal for a target, and if not,
205 /// what action should be used to make them valid.
206 enum LegalizeTypeAction : uint8_t {
207 TypeLegal, // The target natively supports this type.
208 TypePromoteInteger, // Replace this integer with a larger one.
209 TypeExpandInteger, // Split this integer into two of half the size.
210 TypeSoftenFloat, // Convert this float to a same size integer type.
211 TypeExpandFloat, // Split this float into two of half the size.
212 TypeScalarizeVector, // Replace this one-element vector with its element.
213 TypeSplitVector, // Split this vector into two of half the size.
214 TypeWidenVector, // This vector should be widened into a larger vector.
215 TypePromoteFloat, // Replace this float with a larger one.
216 TypeSoftPromoteHalf, // Soften half to i16 and use float to do arithmetic.
217 TypeScalarizeScalableVector, // This action is explicitly left unimplemented.
218 // While it is theoretically possible to
219 // legalize operations on scalable types with a
220 // loop that handles the vscale * #lanes of the
221 // vector, this is non-trivial at SelectionDAG
222 // level and these types are better to be
223 // widened or promoted.
224 };
225
226 /// LegalizeKind holds the legalization kind that needs to happen to EVT
227 /// in order to type-legalize it.
228 using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
229
230 /// Enum that describes how the target represents true/false values.
232 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
233 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
234 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
235 };
236
237 /// Enum that describes what type of support for selects the target has.
239 ScalarValSelect, // The target supports scalar selects (ex: cmov).
240 ScalarCondVectorVal, // The target supports selects with a scalar condition
241 // and vector values (ex: cmov).
242 VectorMaskSelect // The target supports vector selects with a vector
243 // mask (ex: x86 blends).
244 };
245
246 /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
247 /// to, if at all. Exists because different targets have different levels of
248 /// support for these atomic instructions, and also have different options
249 /// w.r.t. what they should expand to.
251 None, // Don't expand the instruction.
252 CastToInteger, // Cast the atomic instruction to another type, e.g. from
253 // floating-point to integer type.
254 LLSC, // Expand the instruction into loadlinked/storeconditional; used
255 // by ARM/AArch64.
256 LLOnly, // Expand the (load) instruction into just a load-linked, which has
257 // greater atomic guarantees than a normal load.
258 CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
259 MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
260 BitTestIntrinsic, // Use a target-specific intrinsic for special bit
261 // operations; used by X86.
262 CmpArithIntrinsic,// Use a target-specific intrinsic for special compare
263 // operations; used by X86.
264 Expand, // Generic expansion in terms of other atomic operations.
265
266 // Rewrite to a non-atomic form for use in a known non-preemptible
267 // environment.
269 };
270
271 /// Enum that specifies when a multiplication should be expanded.
272 enum class MulExpansionKind {
273 Always, // Always expand the instruction.
274 OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
275 // or custom.
276 };
277
278 /// Enum that specifies when a float negation is beneficial.
279 enum class NegatibleCost {
280 Cheaper = 0, // Negated expression is cheaper.
281 Neutral = 1, // Negated expression has the same cost.
282 Expensive = 2 // Negated expression is more expensive.
283 };
284
285 /// Enum of different potentially desirable ways to fold (and/or (setcc ...),
286 /// (setcc ...)).
287 enum AndOrSETCCFoldKind : uint8_t {
288 None = 0, // No fold is preferable.
289 AddAnd = 1, // Fold with `Add` op and `And` op is preferable.
290 NotAnd = 2, // Fold with `Not` op and `And` op is preferable.
291 ABS = 4, // Fold with `llvm.abs` op is preferable.
292 };
293
295 public:
296 Value *Val = nullptr;
298 Type *Ty = nullptr;
299 bool IsSExt : 1;
300 bool IsZExt : 1;
301 bool IsInReg : 1;
302 bool IsSRet : 1;
303 bool IsNest : 1;
304 bool IsByVal : 1;
305 bool IsByRef : 1;
306 bool IsInAlloca : 1;
308 bool IsReturned : 1;
309 bool IsSwiftSelf : 1;
310 bool IsSwiftAsync : 1;
311 bool IsSwiftError : 1;
313 MaybeAlign Alignment = std::nullopt;
314 Type *IndirectType = nullptr;
315
321
322 void setAttributes(const CallBase *Call, unsigned ArgIdx);
323 };
324 using ArgListTy = std::vector<ArgListEntry>;
325
326 virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
327 ArgListTy &Args) const {};
328
330 switch (Content) {
332 // Extend by adding rubbish bits.
333 return ISD::ANY_EXTEND;
335 // Extend by adding zero bits.
336 return ISD::ZERO_EXTEND;
338 // Extend by copying the sign bit.
339 return ISD::SIGN_EXTEND;
340 }
341 llvm_unreachable("Invalid content kind");
342 }
343
344 explicit TargetLoweringBase(const TargetMachine &TM);
347 virtual ~TargetLoweringBase() = default;
348
349 /// Return true if the target support strict float operation
350 bool isStrictFPEnabled() const {
351 return IsStrictFPEnabled;
352 }
353
354protected:
355 /// Initialize all of the actions to default values.
356 void initActions();
357
358public:
359 const TargetMachine &getTargetMachine() const { return TM; }
360
361 virtual bool useSoftFloat() const { return false; }
362
363 /// Return the pointer type for the given address space, defaults to
364 /// the pointer type from the data layout.
365 /// FIXME: The default needs to be removed once all the code is updated.
366 virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
367 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
368 }
369
370 /// Return the in-memory pointer type for the given address space, defaults to
371 /// the pointer type from the data layout. FIXME: The default needs to be
372 /// removed once all the code is updated.
373 virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS = 0) const {
374 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
375 }
376
377 /// Return the type for frame index, which is determined by
378 /// the alloca address space specified through the data layout.
380 return getPointerTy(DL, DL.getAllocaAddrSpace());
381 }
382
383 /// Return the type for code pointers, which is determined by the program
384 /// address space specified through the data layout.
386 return getPointerTy(DL, DL.getProgramAddressSpace());
387 }
388
389 /// Return the type for operands of fence.
390 /// TODO: Let fence operands be of i32 type and remove this.
391 virtual MVT getFenceOperandTy(const DataLayout &DL) const {
392 return getPointerTy(DL);
393 }
394
395 /// Return the type to use for a scalar shift opcode, given the shifted amount
396 /// type. Targets should return a legal type if the input type is legal.
397 /// Targets can return a type that is too small if the input type is illegal.
398 virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
399
400 /// Returns the type for the shift amount of a shift opcode. For vectors,
401 /// returns the input type. For scalars, behavior depends on \p LegalTypes. If
402 /// \p LegalTypes is true, calls getScalarShiftAmountTy, otherwise uses
403 /// pointer type. If getScalarShiftAmountTy or pointer type cannot represent
404 /// all possible shift amounts, returns MVT::i32. In general, \p LegalTypes
405 /// should be set to true for calls during type legalization and after type
406 /// legalization has been completed.
407 EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
408 bool LegalTypes = true) const;
409
410 /// Return the preferred type to use for a shift opcode, given the shifted
411 /// amount type is \p ShiftValueTy.
413 virtual LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const {
414 return ShiftValueTy;
415 }
416
417 /// Returns the type to be used for the index operand of:
418 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
419 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
420 virtual MVT getVectorIdxTy(const DataLayout &DL) const {
421 return getPointerTy(DL);
422 }
423
424 /// Returns the type to be used for the EVL/AVL operand of VP nodes:
425 /// ISD::VP_ADD, ISD::VP_SUB, etc. It must be a legal scalar integer type,
426 /// and must be at least as large as i32. The EVL is implicitly zero-extended
427 /// to any larger type.
428 virtual MVT getVPExplicitVectorLengthTy() const { return MVT::i32; }
429
430 /// This callback is used to inspect load/store instructions and add
431 /// target-specific MachineMemOperand flags to them. The default
432 /// implementation does nothing.
435 }
436
437 /// This callback is used to inspect load/store SDNode.
438 /// The default implementation does nothing.
442 }
443
446 AssumptionCache *AC = nullptr,
447 const TargetLibraryInfo *LibInfo = nullptr) const;
449 const DataLayout &DL) const;
451 const DataLayout &DL) const;
452
453 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
454 return true;
455 }
456
457 /// Return true if the @llvm.get.active.lane.mask intrinsic should be expanded
458 /// using generic code in SelectionDAGBuilder.
459 virtual bool shouldExpandGetActiveLaneMask(EVT VT, EVT OpVT) const {
460 return true;
461 }
462
463 virtual bool shouldExpandGetVectorLength(EVT CountVT, unsigned VF,
464 bool IsScalable) const {
465 return true;
466 }
467
468 // Return true if op(vecreduce(x), vecreduce(y)) should be reassociated to
469 // vecreduce(op(x, y)) for the reduction opcode RedOpc.
470 virtual bool shouldReassociateReduction(unsigned RedOpc, EVT VT) const {
471 return true;
472 }
473
474 /// Return true if it is profitable to convert a select of FP constants into
475 /// a constant pool load whose address depends on the select condition. The
476 /// parameter may be used to differentiate a select with FP compare from
477 /// integer compare.
478 virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
479 return true;
480 }
481
482 /// Return true if multiple condition registers are available.
484 return HasMultipleConditionRegisters;
485 }
486
487 /// Return true if the target has BitExtract instructions.
488 bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
489
490 /// Return the preferred vector type legalization action.
493 // The default action for one element vectors is to scalarize
495 return TypeScalarizeVector;
496 // The default action for an odd-width vector is to widen.
497 if (!VT.isPow2VectorType())
498 return TypeWidenVector;
499 // The default action for other vectors is to promote
500 return TypePromoteInteger;
501 }
502
503 // Return true if the half type should be passed around as i16, but promoted
504 // to float around arithmetic. The default behavior is to pass around as
505 // float and convert around loads/stores/bitcasts and other places where
506 // the size matters.
507 virtual bool softPromoteHalfType() const { return false; }
508
509 // There are two general methods for expanding a BUILD_VECTOR node:
510 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
511 // them together.
512 // 2. Build the vector on the stack and then load it.
513 // If this function returns true, then method (1) will be used, subject to
514 // the constraint that all of the necessary shuffles are legal (as determined
515 // by isShuffleMaskLegal). If this function returns false, then method (2) is
516 // always used. The vector type, and the number of defined values, are
517 // provided.
518 virtual bool
520 unsigned DefinedValues) const {
521 return DefinedValues < 3;
522 }
523
524 /// Return true if integer divide is usually cheaper than a sequence of
525 /// several shifts, adds, and multiplies for this target.
526 /// The definition of "cheaper" may depend on whether we're optimizing
527 /// for speed or for size.
528 virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
529
530 /// Return true if the target can handle a standalone remainder operation.
531 virtual bool hasStandaloneRem(EVT VT) const {
532 return true;
533 }
534
535 /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
536 virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
537 // Default behavior is to replace SQRT(X) with X*RSQRT(X).
538 return false;
539 }
540
541 /// Reciprocal estimate status values used by the functions below.
545 Enabled = 1
546 };
547
548 /// Return a ReciprocalEstimate enum value for a square root of the given type
549 /// based on the function's attributes. If the operation is not overridden by
550 /// the function's attributes, "Unspecified" is returned and target defaults
551 /// are expected to be used for instruction selection.
553
554 /// Return a ReciprocalEstimate enum value for a division of the given type
555 /// based on the function's attributes. If the operation is not overridden by
556 /// the function's attributes, "Unspecified" is returned and target defaults
557 /// are expected to be used for instruction selection.
559
560 /// Return the refinement step count for a square root of the given type based
561 /// on the function's attributes. If the operation is not overridden by
562 /// the function's attributes, "Unspecified" is returned and target defaults
563 /// are expected to be used for instruction selection.
564 int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
565
566 /// Return the refinement step count for a division of the given type based
567 /// on the function's attributes. If the operation is not overridden by
568 /// the function's attributes, "Unspecified" is returned and target defaults
569 /// are expected to be used for instruction selection.
570 int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
571
572 /// Returns true if target has indicated at least one type should be bypassed.
573 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
574
575 /// Returns map of slow types for division or remainder with corresponding
576 /// fast types
578 return BypassSlowDivWidths;
579 }
580
581 /// Return true only if vscale must be a power of two.
582 virtual bool isVScaleKnownToBeAPowerOfTwo() const { return false; }
583
584 /// Return true if Flow Control is an expensive operation that should be
585 /// avoided.
586 bool isJumpExpensive() const { return JumpIsExpensive; }
587
588 /// Return true if selects are only cheaper than branches if the branch is
589 /// unlikely to be predicted right.
592 }
593
594 virtual bool fallBackToDAGISel(const Instruction &Inst) const {
595 return false;
596 }
597
598 /// Return true if the following transform is beneficial:
599 /// fold (conv (load x)) -> (load (conv*)x)
600 /// On architectures that don't natively support some vector loads
601 /// efficiently, casting the load to a smaller vector of larger types and
602 /// loading is more efficient, however, this can be undone by optimizations in
603 /// dag combiner.
604 virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
605 const SelectionDAG &DAG,
606 const MachineMemOperand &MMO) const;
607
608 /// Return true if the following transform is beneficial:
609 /// (store (y (conv x)), y*)) -> (store x, (x*))
610 virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT,
611 const SelectionDAG &DAG,
612 const MachineMemOperand &MMO) const {
613 // Default to the same logic as loads.
614 return isLoadBitCastBeneficial(StoreVT, BitcastVT, DAG, MMO);
615 }
616
617 /// Return true if it is expected to be cheaper to do a store of vector
618 /// constant with the given size and type for the address space than to
619 /// store the individual scalar element constants.
620 virtual bool storeOfVectorConstantIsCheap(bool IsZero, EVT MemVT,
621 unsigned NumElem,
622 unsigned AddrSpace) const {
623 return IsZero;
624 }
625
626 /// Allow store merging for the specified type after legalization in addition
627 /// to before legalization. This may transform stores that do not exist
628 /// earlier (for example, stores created from intrinsics).
629 virtual bool mergeStoresAfterLegalization(EVT MemVT) const {
630 return true;
631 }
632
633 /// Returns if it's reasonable to merge stores to MemVT size.
634 virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
635 const MachineFunction &MF) const {
636 return true;
637 }
638
639 /// Return true if it is cheap to speculate a call to intrinsic cttz.
640 virtual bool isCheapToSpeculateCttz(Type *Ty) const {
641 return false;
642 }
643
644 /// Return true if it is cheap to speculate a call to intrinsic ctlz.
645 virtual bool isCheapToSpeculateCtlz(Type *Ty) const {
646 return false;
647 }
648
649 /// Return true if ctlz instruction is fast.
650 virtual bool isCtlzFast() const {
651 return false;
652 }
653
654 /// Return true if ctpop instruction is fast.
655 virtual bool isCtpopFast(EVT VT) const {
656 return isOperationLegal(ISD::CTPOP, VT);
657 }
658
659 /// Return the maximum number of "x & (x - 1)" operations that can be done
660 /// instead of deferring to a custom CTPOP.
661 virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const {
662 return 1;
663 }
664
665 /// Return true if instruction generated for equality comparison is folded
666 /// with instruction generated for signed comparison.
667 virtual bool isEqualityCmpFoldedWithSignedCmp() const { return true; }
668
669 /// Return true if the heuristic to prefer icmp eq zero should be used in code
670 /// gen prepare.
671 virtual bool preferZeroCompareBranch() const { return false; }
672
673 /// Return true if it is cheaper to split the store of a merged int val
674 /// from a pair of smaller values into multiple stores.
675 virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
676 return false;
677 }
678
679 /// Return if the target supports combining a
680 /// chain like:
681 /// \code
682 /// %andResult = and %val1, #mask
683 /// %icmpResult = icmp %andResult, 0
684 /// \endcode
685 /// into a single machine instruction of a form like:
686 /// \code
687 /// cc = test %register, #mask
688 /// \endcode
689 virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
690 return false;
691 }
692
693 /// Return true if it is valid to merge the TargetMMOFlags in two SDNodes.
694 virtual bool
696 const MemSDNode &NodeY) const {
697 return true;
698 }
699
700 /// Use bitwise logic to make pairs of compares more efficient. For example:
701 /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
702 /// This should be true when it takes more than one instruction to lower
703 /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
704 /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
705 virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
706 return false;
707 }
708
709 /// Return the preferred operand type if the target has a quick way to compare
710 /// integer values of the given size. Assume that any legal integer type can
711 /// be compared efficiently. Targets may override this to allow illegal wide
712 /// types to return a vector type if there is support to compare that type.
713 virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
714 MVT VT = MVT::getIntegerVT(NumBits);
716 }
717
718 /// Return true if the target should transform:
719 /// (X & Y) == Y ---> (~X & Y) == 0
720 /// (X & Y) != Y ---> (~X & Y) != 0
721 ///
722 /// This may be profitable if the target has a bitwise and-not operation that
723 /// sets comparison flags. A target may want to limit the transformation based
724 /// on the type of Y or if Y is a constant.
725 ///
726 /// Note that the transform will not occur if Y is known to be a power-of-2
727 /// because a mask and compare of a single bit can be handled by inverting the
728 /// predicate, for example:
729 /// (X & 8) == 8 ---> (X & 8) != 0
730 virtual bool hasAndNotCompare(SDValue Y) const {
731 return false;
732 }
733
734 /// Return true if the target has a bitwise and-not operation:
735 /// X = ~A & B
736 /// This can be used to simplify select or other instructions.
737 virtual bool hasAndNot(SDValue X) const {
738 // If the target has the more complex version of this operation, assume that
739 // it has this operation too.
740 return hasAndNotCompare(X);
741 }
742
743 /// Return true if the target has a bit-test instruction:
744 /// (X & (1 << Y)) ==/!= 0
745 /// This knowledge can be used to prevent breaking the pattern,
746 /// or creating it if it could be recognized.
747 virtual bool hasBitTest(SDValue X, SDValue Y) const { return false; }
748
749 /// There are two ways to clear extreme bits (either low or high):
750 /// Mask: x & (-1 << y) (the instcombine canonical form)
751 /// Shifts: x >> y << y
752 /// Return true if the variant with 2 variable shifts is preferred.
753 /// Return false if there is no preference.
755 // By default, let's assume that no one prefers shifts.
756 return false;
757 }
758
759 /// Return true if it is profitable to fold a pair of shifts into a mask.
760 /// This is usually true on most targets. But some targets, like Thumb1,
761 /// have immediate shift instructions, but no immediate "and" instruction;
762 /// this makes the fold unprofitable.
764 CombineLevel Level) const {
765 return true;
766 }
767
768 /// Should we tranform the IR-optimal check for whether given truncation
769 /// down into KeptBits would be truncating or not:
770 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
771 /// Into it's more traditional form:
772 /// ((%x << C) a>> C) dstcond %x
773 /// Return true if we should transform.
774 /// Return false if there is no preference.
776 unsigned KeptBits) const {
777 // By default, let's assume that no one prefers shifts.
778 return false;
779 }
780
781 /// Given the pattern
782 /// (X & (C l>>/<< Y)) ==/!= 0
783 /// return true if it should be transformed into:
784 /// ((X <</l>> Y) & C) ==/!= 0
785 /// WARNING: if 'X' is a constant, the fold may deadlock!
786 /// FIXME: we could avoid passing XC, but we can't use isConstOrConstSplat()
787 /// here because it can end up being not linked in.
790 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
791 SelectionDAG &DAG) const {
792 if (hasBitTest(X, Y)) {
793 // One interesting pattern that we'd want to form is 'bit test':
794 // ((1 << Y) & C) ==/!= 0
795 // But we also need to be careful not to try to reverse that fold.
796
797 // Is this '1 << Y' ?
798 if (OldShiftOpcode == ISD::SHL && CC->isOne())
799 return false; // Keep the 'bit test' pattern.
800
801 // Will it be '1 << Y' after the transform ?
802 if (XC && NewShiftOpcode == ISD::SHL && XC->isOne())
803 return true; // Do form the 'bit test' pattern.
804 }
805
806 // If 'X' is a constant, and we transform, then we will immediately
807 // try to undo the fold, thus causing endless combine loop.
808 // So by default, let's assume everyone prefers the fold
809 // iff 'X' is not a constant.
810 return !XC;
811 }
812
813 // Return true if its desirable to perform the following transform:
814 // (fmul C, (uitofp Pow2))
815 // -> (bitcast_to_FP (add (bitcast_to_INT C), Log2(Pow2) << mantissa))
816 // (fdiv C, (uitofp Pow2))
817 // -> (bitcast_to_FP (sub (bitcast_to_INT C), Log2(Pow2) << mantissa))
818 //
819 // This is only queried after we have verified the transform will be bitwise
820 // equals.
821 //
822 // SDNode *N : The FDiv/FMul node we want to transform.
823 // SDValue FPConst: The Float constant operand in `N`.
824 // SDValue IntPow2: The Integer power of 2 operand in `N`.
826 SDValue IntPow2) const {
827 // Default to avoiding fdiv which is often very expensive.
828 return N->getOpcode() == ISD::FDIV;
829 }
830
831 /// These two forms are equivalent:
832 /// sub %y, (xor %x, -1)
833 /// add (add %x, 1), %y
834 /// The variant with two add's is IR-canonical.
835 /// Some targets may prefer one to the other.
836 virtual bool preferIncOfAddToSubOfNot(EVT VT) const {
837 // By default, let's assume that everyone prefers the form with two add's.
838 return true;
839 }
840
841 // By default prefer folding (abs (sub nsw x, y)) -> abds(x, y). Some targets
842 // may want to avoid this to prevent loss of sub_nsw pattern.
843 virtual bool preferABDSToABSWithNSW(EVT VT) const {
844 return true;
845 }
846
847 // Return true if the target wants to transform Op(Splat(X)) -> Splat(Op(X))
848 virtual bool preferScalarizeSplat(SDNode *N) const { return true; }
849
850 // Return true if the target wants to transform:
851 // (TruncVT truncate(sext_in_reg(VT X, ExtVT))
852 // -> (TruncVT sext_in_reg(truncate(VT X), ExtVT))
853 // Some targets might prefer pre-sextinreg to improve truncation/saturation.
854 virtual bool preferSextInRegOfTruncate(EVT TruncVT, EVT VT, EVT ExtVT) const {
855 return true;
856 }
857
858 /// Return true if the target wants to use the optimization that
859 /// turns ext(promotableInst1(...(promotableInstN(load)))) into
860 /// promotedInst1(...(promotedInstN(ext(load)))).
862
863 /// Return true if the target can combine store(extractelement VectorTy,
864 /// Idx).
865 /// \p Cost[out] gives the cost of that transformation when this is true.
866 virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
867 unsigned &Cost) const {
868 return false;
869 }
870
871 /// Return true if the target shall perform extract vector element and store
872 /// given that the vector is known to be splat of constant.
873 /// \p Index[out] gives the index of the vector element to be extracted when
874 /// this is true.
876 Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const {
877 return false;
878 }
879
880 /// Return true if inserting a scalar into a variable element of an undef
881 /// vector is more efficiently handled by splatting the scalar instead.
882 virtual bool shouldSplatInsEltVarIndex(EVT) const {
883 return false;
884 }
885
886 /// Return true if target always benefits from combining into FMA for a
887 /// given value type. This must typically return false on targets where FMA
888 /// takes more cycles to execute than FADD.
889 virtual bool enableAggressiveFMAFusion(EVT VT) const { return false; }
890
891 /// Return true if target always benefits from combining into FMA for a
892 /// given value type. This must typically return false on targets where FMA
893 /// takes more cycles to execute than FADD.
894 virtual bool enableAggressiveFMAFusion(LLT Ty) const { return false; }
895
896 /// Return the ValueType of the result of SETCC operations.
897 virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
898 EVT VT) const;
899
900 /// Return the ValueType for comparison libcalls. Comparison libcalls include
901 /// floating point comparison calls, and Ordered/Unordered check calls on
902 /// floating point numbers.
903 virtual
905
906 /// For targets without i1 registers, this gives the nature of the high-bits
907 /// of boolean values held in types wider than i1.
908 ///
909 /// "Boolean values" are special true/false values produced by nodes like
910 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
911 /// Not to be confused with general values promoted from i1. Some cpus
912 /// distinguish between vectors of boolean and scalars; the isVec parameter
913 /// selects between the two kinds. For example on X86 a scalar boolean should
914 /// be zero extended from i1, while the elements of a vector of booleans
915 /// should be sign extended from i1.
916 ///
917 /// Some cpus also treat floating point types the same way as they treat
918 /// vectors instead of the way they treat scalars.
919 BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
920 if (isVec)
921 return BooleanVectorContents;
922 return isFloat ? BooleanFloatContents : BooleanContents;
923 }
924
926 return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
927 }
928
929 /// Promote the given target boolean to a target boolean of the given type.
930 /// A target boolean is an integer value, not necessarily of type i1, the bits
931 /// of which conform to getBooleanContents.
932 ///
933 /// ValVT is the type of values that produced the boolean.
935 EVT ValVT) const {
936 SDLoc dl(Bool);
937 EVT BoolVT =
938 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ValVT);
940 return DAG.getNode(ExtendCode, dl, BoolVT, Bool);
941 }
942
943 /// Return target scheduling preference.
945 return SchedPreferenceInfo;
946 }
947
948 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
949 /// for different nodes. This function returns the preference (or none) for
950 /// the given node.
952 return Sched::None;
953 }
954
955 /// Return the register class that should be used for the specified value
956 /// type.
957 virtual const TargetRegisterClass *getRegClassFor(MVT VT, bool isDivergent = false) const {
958 (void)isDivergent;
959 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
960 assert(RC && "This value type is not natively supported!");
961 return RC;
962 }
963
964 /// Allows target to decide about the register class of the
965 /// specific value that is live outside the defining block.
966 /// Returns true if the value needs uniform register class.
968 const Value *) const {
969 return false;
970 }
971
972 /// Return the 'representative' register class for the specified value
973 /// type.
974 ///
975 /// The 'representative' register class is the largest legal super-reg
976 /// register class for the register class of the value type. For example, on
977 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
978 /// register class is GR64 on x86_64.
979 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
980 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
981 return RC;
982 }
983
984 /// Return the cost of the 'representative' register class for the specified
985 /// value type.
986 virtual uint8_t getRepRegClassCostFor(MVT VT) const {
987 return RepRegClassCostForVT[VT.SimpleTy];
988 }
989
990 /// Return the preferred strategy to legalize tihs SHIFT instruction, with
991 /// \p ExpansionFactor being the recursion depth - how many expansion needed.
996 };
999 unsigned ExpansionFactor) const {
1000 if (ExpansionFactor == 1)
1003 }
1004
1005 /// Return true if the target has native support for the specified value type.
1006 /// This means that it has a register that directly holds it without
1007 /// promotions or expansions.
1008 bool isTypeLegal(EVT VT) const {
1009 assert(!VT.isSimple() ||
1010 (unsigned)VT.getSimpleVT().SimpleTy < std::size(RegClassForVT));
1011 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
1012 }
1013
1015 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
1016 /// that indicates how instruction selection should deal with the type.
1017 LegalizeTypeAction ValueTypeActions[MVT::VALUETYPE_SIZE];
1018
1019 public:
1021 std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
1022 TypeLegal);
1023 }
1024
1026 return ValueTypeActions[VT.SimpleTy];
1027 }
1028
1030 ValueTypeActions[VT.SimpleTy] = Action;
1031 }
1032 };
1033
1035 return ValueTypeActions;
1036 }
1037
1038 /// Return pair that represents the legalization kind (first) that needs to
1039 /// happen to EVT (second) in order to type-legalize it.
1040 ///
1041 /// First: how we should legalize values of this type, either it is already
1042 /// legal (return 'Legal') or we need to promote it to a larger type (return
1043 /// 'Promote'), or we need to expand it into multiple registers of smaller
1044 /// integer type (return 'Expand'). 'Custom' is not an option.
1045 ///
1046 /// Second: for types supported by the target, this is an identity function.
1047 /// For types that must be promoted to larger types, this returns the larger
1048 /// type to promote to. For integer types that are larger than the largest
1049 /// integer register, this contains one step in the expansion to get to the
1050 /// smaller register. For illegal floating point types, this returns the
1051 /// integer type to transform to.
1052 LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
1053
1054 /// Return how we should legalize values of this type, either it is already
1055 /// legal (return 'Legal') or we need to promote it to a larger type (return
1056 /// 'Promote'), or we need to expand it into multiple registers of smaller
1057 /// integer type (return 'Expand'). 'Custom' is not an option.
1059 return getTypeConversion(Context, VT).first;
1060 }
1062 return ValueTypeActions.getTypeAction(VT);
1063 }
1064
1065 /// For types supported by the target, this is an identity function. For
1066 /// types that must be promoted to larger types, this returns the larger type
1067 /// to promote to. For integer types that are larger than the largest integer
1068 /// register, this contains one step in the expansion to get to the smaller
1069 /// register. For illegal floating point types, this returns the integer type
1070 /// to transform to.
1071 virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
1072 return getTypeConversion(Context, VT).second;
1073 }
1074
1075 /// For types supported by the target, this is an identity function. For
1076 /// types that must be expanded (i.e. integer types that are larger than the
1077 /// largest integer register or illegal floating point types), this returns
1078 /// the largest legal type it will be expanded to.
1079 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
1080 assert(!VT.isVector());
1081 while (true) {
1082 switch (getTypeAction(Context, VT)) {
1083 case TypeLegal:
1084 return VT;
1085 case TypeExpandInteger:
1086 VT = getTypeToTransformTo(Context, VT);
1087 break;
1088 default:
1089 llvm_unreachable("Type is not legal nor is it to be expanded!");
1090 }
1091 }
1092 }
1093
1094 /// Vector types are broken down into some number of legal first class types.
1095 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
1096 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
1097 /// turns into 4 EVT::i32 values with both PPC and X86.
1098 ///
1099 /// This method returns the number of registers needed, and the VT for each
1100 /// register. It also returns the VT and quantity of the intermediate values
1101 /// before they are promoted/expanded.
1102 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
1103 EVT &IntermediateVT,
1104 unsigned &NumIntermediates,
1105 MVT &RegisterVT) const;
1106
1107 /// Certain targets such as MIPS require that some types such as vectors are
1108 /// always broken down into scalars in some contexts. This occurs even if the
1109 /// vector type is legal.
1111 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
1112 unsigned &NumIntermediates, MVT &RegisterVT) const {
1113 return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
1114 RegisterVT);
1115 }
1116
1118 unsigned opc = 0; // target opcode
1119 EVT memVT; // memory VT
1120
1121 // value representing memory location
1123
1124 // Fallback address space for use if ptrVal is nullptr. std::nullopt means
1125 // unknown address space.
1126 std::optional<unsigned> fallbackAddressSpace;
1127
1128 int offset = 0; // offset off of ptrVal
1129 uint64_t size = 0; // the size of the memory location
1130 // (taken from memVT if zero)
1131 MaybeAlign align = Align(1); // alignment
1132
1134 IntrinsicInfo() = default;
1135 };
1136
1137 /// Given an intrinsic, checks if on the target the intrinsic will need to map
1138 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
1139 /// true and store the intrinsic information into the IntrinsicInfo that was
1140 /// passed to the function.
1143 unsigned /*Intrinsic*/) const {
1144 return false;
1145 }
1146
1147 /// Returns true if the target can instruction select the specified FP
1148 /// immediate natively. If false, the legalizer will materialize the FP
1149 /// immediate as a load from a constant pool.
1150 virtual bool isFPImmLegal(const APFloat & /*Imm*/, EVT /*VT*/,
1151 bool ForCodeSize = false) const {
1152 return false;
1153 }
1154
1155 /// Targets can use this to indicate that they only support *some*
1156 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
1157 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
1158 /// legal.
1159 virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
1160 return true;
1161 }
1162
1163 /// Returns true if the operation can trap for the value type.
1164 ///
1165 /// VT must be a legal type. By default, we optimistically assume most
1166 /// operations don't trap except for integer divide and remainder.
1167 virtual bool canOpTrap(unsigned Op, EVT VT) const;
1168
1169 /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
1170 /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
1171 /// constant pool entry.
1173 EVT /*VT*/) const {
1174 return false;
1175 }
1176
1177 /// How to legalize this custom operation?
1179 return Legal;
1180 }
1181
1182 /// Return how this operation should be treated: either it is legal, needs to
1183 /// be promoted to a larger size, needs to be expanded to some other code
1184 /// sequence, or the target has a custom expander for it.
1186 if (VT.isExtended()) return Expand;
1187 // If a target-specific SDNode requires legalization, require the target
1188 // to provide custom legalization for it.
1189 if (Op >= std::size(OpActions[0]))
1190 return Custom;
1191 return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
1192 }
1193
1194 /// Custom method defined by each target to indicate if an operation which
1195 /// may require a scale is supported natively by the target.
1196 /// If not, the operation is illegal.
1197 virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
1198 unsigned Scale) const {
1199 return false;
1200 }
1201
1202 /// Some fixed point operations may be natively supported by the target but
1203 /// only for specific scales. This method allows for checking
1204 /// if the width is supported by the target for a given operation that may
1205 /// depend on scale.
1207 unsigned Scale) const {
1208 auto Action = getOperationAction(Op, VT);
1209 if (Action != Legal)
1210 return Action;
1211
1212 // This operation is supported in this type but may only work on specific
1213 // scales.
1214 bool Supported;
1215 switch (Op) {
1216 default:
1217 llvm_unreachable("Unexpected fixed point operation.");
1218 case ISD::SMULFIX:
1219 case ISD::SMULFIXSAT:
1220 case ISD::UMULFIX:
1221 case ISD::UMULFIXSAT:
1222 case ISD::SDIVFIX:
1223 case ISD::SDIVFIXSAT:
1224 case ISD::UDIVFIX:
1225 case ISD::UDIVFIXSAT:
1226 Supported = isSupportedFixedPointOperation(Op, VT, Scale);
1227 break;
1228 }
1229
1230 return Supported ? Action : Expand;
1231 }
1232
1233 // If Op is a strict floating-point operation, return the result
1234 // of getOperationAction for the equivalent non-strict operation.
1236 unsigned EqOpc;
1237 switch (Op) {
1238 default: llvm_unreachable("Unexpected FP pseudo-opcode");
1239#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1240 case ISD::STRICT_##DAGN: EqOpc = ISD::DAGN; break;
1241#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1242 case ISD::STRICT_##DAGN: EqOpc = ISD::SETCC; break;
1243#include "llvm/IR/ConstrainedOps.def"
1244 }
1245
1246 return getOperationAction(EqOpc, VT);
1247 }
1248
1249 /// Return true if the specified operation is legal on this target or can be
1250 /// made legal with custom lowering. This is used to help guide high-level
1251 /// lowering decisions. LegalOnly is an optional convenience for code paths
1252 /// traversed pre and post legalisation.
1254 bool LegalOnly = false) const {
1255 if (LegalOnly)
1256 return isOperationLegal(Op, VT);
1257
1258 return (VT == MVT::Other || isTypeLegal(VT)) &&
1259 (getOperationAction(Op, VT) == Legal ||
1260 getOperationAction(Op, VT) == Custom);
1261 }
1262
1263 /// Return true if the specified operation is legal on this target or can be
1264 /// made legal using promotion. This is used to help guide high-level lowering
1265 /// decisions. LegalOnly is an optional convenience for code paths traversed
1266 /// pre and post legalisation.
1268 bool LegalOnly = false) const {
1269 if (LegalOnly)
1270 return isOperationLegal(Op, VT);
1271
1272 return (VT == MVT::Other || isTypeLegal(VT)) &&
1273 (getOperationAction(Op, VT) == Legal ||
1274 getOperationAction(Op, VT) == Promote);
1275 }
1276
1277 /// Return true if the specified operation is legal on this target or can be
1278 /// made legal with custom lowering or using promotion. This is used to help
1279 /// guide high-level lowering decisions. LegalOnly is an optional convenience
1280 /// for code paths traversed pre and post legalisation.
1282 bool LegalOnly = false) const {
1283 if (LegalOnly)
1284 return isOperationLegal(Op, VT);
1285
1286 return (VT == MVT::Other || isTypeLegal(VT)) &&
1287 (getOperationAction(Op, VT) == Legal ||
1288 getOperationAction(Op, VT) == Custom ||
1289 getOperationAction(Op, VT) == Promote);
1290 }
1291
1292 /// Return true if the operation uses custom lowering, regardless of whether
1293 /// the type is legal or not.
1294 bool isOperationCustom(unsigned Op, EVT VT) const {
1295 return getOperationAction(Op, VT) == Custom;
1296 }
1297
1298 /// Return true if lowering to a jump table is allowed.
1299 virtual bool areJTsAllowed(const Function *Fn) const {
1300 if (Fn->getFnAttribute("no-jump-tables").getValueAsBool())
1301 return false;
1302
1303 return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1305 }
1306
1307 /// Check whether the range [Low,High] fits in a machine word.
1308 bool rangeFitsInWord(const APInt &Low, const APInt &High,
1309 const DataLayout &DL) const {
1310 // FIXME: Using the pointer type doesn't seem ideal.
1311 uint64_t BW = DL.getIndexSizeInBits(0u);
1312 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
1313 return Range <= BW;
1314 }
1315
1316 /// Return true if lowering to a jump table is suitable for a set of case
1317 /// clusters which may contain \p NumCases cases, \p Range range of values.
1318 virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
1319 uint64_t Range, ProfileSummaryInfo *PSI,
1320 BlockFrequencyInfo *BFI) const;
1321
1322 /// Returns preferred type for switch condition.
1324 EVT ConditionVT) const;
1325
1326 /// Return true if lowering to a bit test is suitable for a set of case
1327 /// clusters which contains \p NumDests unique destinations, \p Low and
1328 /// \p High as its lowest and highest case values, and expects \p NumCmps
1329 /// case value comparisons. Check if the number of destinations, comparison
1330 /// metric, and range are all suitable.
1331 bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
1332 const APInt &Low, const APInt &High,
1333 const DataLayout &DL) const {
1334 // FIXME: I don't think NumCmps is the correct metric: a single case and a
1335 // range of cases both require only one branch to lower. Just looking at the
1336 // number of clusters and destinations should be enough to decide whether to
1337 // build bit tests.
1338
1339 // To lower a range with bit tests, the range must fit the bitwidth of a
1340 // machine word.
1341 if (!rangeFitsInWord(Low, High, DL))
1342 return false;
1343
1344 // Decide whether it's profitable to lower this range with bit tests. Each
1345 // destination requires a bit test and branch, and there is an overall range
1346 // check branch. For a small number of clusters, separate comparisons might
1347 // be cheaper, and for many destinations, splitting the range might be
1348 // better.
1349 return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
1350 (NumDests == 3 && NumCmps >= 6);
1351 }
1352
1353 /// Return true if the specified operation is illegal on this target or
1354 /// unlikely to be made legal with custom lowering. This is used to help guide
1355 /// high-level lowering decisions.
1356 bool isOperationExpand(unsigned Op, EVT VT) const {
1357 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
1358 }
1359
1360 /// Return true if the specified operation is legal on this target.
1361 bool isOperationLegal(unsigned Op, EVT VT) const {
1362 return (VT == MVT::Other || isTypeLegal(VT)) &&
1363 getOperationAction(Op, VT) == Legal;
1364 }
1365
1366 /// Return how this load with extension should be treated: either it is legal,
1367 /// needs to be promoted to a larger size, needs to be expanded to some other
1368 /// code sequence, or the target has a custom expander for it.
1369 LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
1370 EVT MemVT) const {
1371 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1372 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1373 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1375 MemI < MVT::VALUETYPE_SIZE && "Table isn't big enough!");
1376 unsigned Shift = 4 * ExtType;
1377 return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
1378 }
1379
1380 /// Return true if the specified load with extension is legal on this target.
1381 bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1382 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
1383 }
1384
1385 /// Return true if the specified load with extension is legal or custom
1386 /// on this target.
1387 bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1388 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
1389 getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
1390 }
1391
1392 /// Return how this store with truncation should be treated: either it is
1393 /// legal, needs to be promoted to a larger size, needs to be expanded to some
1394 /// other code sequence, or the target has a custom expander for it.
1396 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1397 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1398 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1400 "Table isn't big enough!");
1401 return TruncStoreActions[ValI][MemI];
1402 }
1403
1404 /// Return true if the specified store with truncation is legal on this
1405 /// target.
1406 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
1407 return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
1408 }
1409
1410 /// Return true if the specified store with truncation has solution on this
1411 /// target.
1412 bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
1413 return isTypeLegal(ValVT) &&
1414 (getTruncStoreAction(ValVT, MemVT) == Legal ||
1415 getTruncStoreAction(ValVT, MemVT) == Custom);
1416 }
1417
1418 virtual bool canCombineTruncStore(EVT ValVT, EVT MemVT,
1419 bool LegalOnly) const {
1420 if (LegalOnly)
1421 return isTruncStoreLegal(ValVT, MemVT);
1422
1423 return isTruncStoreLegalOrCustom(ValVT, MemVT);
1424 }
1425
1426 /// Return how the indexed load should be treated: either it is legal, needs
1427 /// to be promoted to a larger size, needs to be expanded to some other code
1428 /// sequence, or the target has a custom expander for it.
1429 LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
1430 return getIndexedModeAction(IdxMode, VT, IMAB_Load);
1431 }
1432
1433 /// Return true if the specified indexed load is legal on this target.
1434 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
1435 return VT.isSimple() &&
1436 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1437 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1438 }
1439
1440 /// Return how the indexed store should be treated: either it is legal, needs
1441 /// to be promoted to a larger size, needs to be expanded to some other code
1442 /// sequence, or the target has a custom expander for it.
1443 LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
1444 return getIndexedModeAction(IdxMode, VT, IMAB_Store);
1445 }
1446
1447 /// Return true if the specified indexed load is legal on this target.
1448 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
1449 return VT.isSimple() &&
1450 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1451 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1452 }
1453
1454 /// Return how the indexed load should be treated: either it is legal, needs
1455 /// to be promoted to a larger size, needs to be expanded to some other code
1456 /// sequence, or the target has a custom expander for it.
1457 LegalizeAction getIndexedMaskedLoadAction(unsigned IdxMode, MVT VT) const {
1458 return getIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad);
1459 }
1460
1461 /// Return true if the specified indexed load is legal on this target.
1462 bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const {
1463 return VT.isSimple() &&
1464 (getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1466 }
1467
1468 /// Return how the indexed store should be treated: either it is legal, needs
1469 /// to be promoted to a larger size, needs to be expanded to some other code
1470 /// sequence, or the target has a custom expander for it.
1471 LegalizeAction getIndexedMaskedStoreAction(unsigned IdxMode, MVT VT) const {
1472 return getIndexedModeAction(IdxMode, VT, IMAB_MaskedStore);
1473 }
1474
1475 /// Return true if the specified indexed load is legal on this target.
1476 bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const {
1477 return VT.isSimple() &&
1478 (getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1480 }
1481
1482 /// Returns true if the index type for a masked gather/scatter requires
1483 /// extending
1484 virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const { return false; }
1485
1486 // Returns true if Extend can be folded into the index of a masked gathers/scatters
1487 // on this target.
1488 virtual bool shouldRemoveExtendFromGSIndex(SDValue Extend, EVT DataVT) const {
1489 return false;
1490 }
1491
1492 // Return true if the target supports a scatter/gather instruction with
1493 // indices which are scaled by the particular value. Note that all targets
1494 // must by definition support scale of 1.
1496 uint64_t ElemSize) const {
1497 // MGATHER/MSCATTER are only required to support scaling by one or by the
1498 // element size.
1499 if (Scale != ElemSize && Scale != 1)
1500 return false;
1501 return true;
1502 }
1503
1504 /// Return how the condition code should be treated: either it is legal, needs
1505 /// to be expanded to some other code sequence, or the target has a custom
1506 /// expander for it.
1509 assert((unsigned)CC < std::size(CondCodeActions) &&
1510 ((unsigned)VT.SimpleTy >> 3) < std::size(CondCodeActions[0]) &&
1511 "Table isn't big enough!");
1512 // See setCondCodeAction for how this is encoded.
1513 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1514 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
1515 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
1516 assert(Action != Promote && "Can't promote condition code!");
1517 return Action;
1518 }
1519
1520 /// Return true if the specified condition code is legal on this target.
1522 return getCondCodeAction(CC, VT) == Legal;
1523 }
1524
1525 /// Return true if the specified condition code is legal or custom on this
1526 /// target.
1528 return getCondCodeAction(CC, VT) == Legal ||
1529 getCondCodeAction(CC, VT) == Custom;
1530 }
1531
1532 /// If the action for this operation is to promote, this method returns the
1533 /// ValueType to promote to.
1534 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
1536 "This operation isn't promoted!");
1537
1538 // See if this has an explicit type specified.
1539 std::map<std::pair<unsigned, MVT::SimpleValueType>,
1541 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1542 if (PTTI != PromoteToType.end()) return PTTI->second;
1543
1544 assert((VT.isInteger() || VT.isFloatingPoint()) &&
1545 "Cannot autopromote this type, add it with AddPromotedToType.");
1546
1547 MVT NVT = VT;
1548 do {
1549 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1550 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
1551 "Didn't find type to promote to!");
1552 } while (!isTypeLegal(NVT) ||
1553 getOperationAction(Op, NVT) == Promote);
1554 return NVT;
1555 }
1556
1558 bool AllowUnknown = false) const {
1559 return getValueType(DL, Ty, AllowUnknown);
1560 }
1561
1562 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1563 /// operations except for the pointer size. If AllowUnknown is true, this
1564 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1565 /// otherwise it will assert.
1567 bool AllowUnknown = false) const {
1568 // Lower scalar pointers to native pointer types.
1569 if (auto *PTy = dyn_cast<PointerType>(Ty))
1570 return getPointerTy(DL, PTy->getAddressSpace());
1571
1572 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1573 Type *EltTy = VTy->getElementType();
1574 // Lower vectors of pointers to native pointer types.
1575 if (auto *PTy = dyn_cast<PointerType>(EltTy)) {
1576 EVT PointerTy(getPointerTy(DL, PTy->getAddressSpace()));
1577 EltTy = PointerTy.getTypeForEVT(Ty->getContext());
1578 }
1579 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(EltTy, false),
1580 VTy->getElementCount());
1581 }
1582
1583 return EVT::getEVT(Ty, AllowUnknown);
1584 }
1585
1587 bool AllowUnknown = false) const {
1588 // Lower scalar pointers to native pointer types.
1589 if (auto *PTy = dyn_cast<PointerType>(Ty))
1590 return getPointerMemTy(DL, PTy->getAddressSpace());
1591
1592 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1593 Type *EltTy = VTy->getElementType();
1594 if (auto *PTy = dyn_cast<PointerType>(EltTy)) {
1595 EVT PointerTy(getPointerMemTy(DL, PTy->getAddressSpace()));
1596 EltTy = PointerTy.getTypeForEVT(Ty->getContext());
1597 }
1598 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(EltTy, false),
1599 VTy->getElementCount());
1600 }
1601
1602 return getValueType(DL, Ty, AllowUnknown);
1603 }
1604
1605
1606 /// Return the MVT corresponding to this LLVM type. See getValueType.
1608 bool AllowUnknown = false) const {
1609 return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1610 }
1611
1612 /// Return the desired alignment for ByVal or InAlloca aggregate function
1613 /// arguments in the caller parameter area. This is the actual alignment, not
1614 /// its logarithm.
1615 virtual uint64_t getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1616
1617 /// Return the type of registers that this ValueType will eventually require.
1619 assert((unsigned)VT.SimpleTy < std::size(RegisterTypeForVT));
1620 return RegisterTypeForVT[VT.SimpleTy];
1621 }
1622
1623 /// Return the type of registers that this ValueType will eventually require.
1624 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1625 if (VT.isSimple())
1626 return getRegisterType(VT.getSimpleVT());
1627 if (VT.isVector()) {
1628 EVT VT1;
1629 MVT RegisterVT;
1630 unsigned NumIntermediates;
1631 (void)getVectorTypeBreakdown(Context, VT, VT1,
1632 NumIntermediates, RegisterVT);
1633 return RegisterVT;
1634 }
1635 if (VT.isInteger()) {
1637 }
1638 llvm_unreachable("Unsupported extended type!");
1639 }
1640
1641 /// Return the number of registers that this ValueType will eventually
1642 /// require.
1643 ///
1644 /// This is one for any types promoted to live in larger registers, but may be
1645 /// more than one for types (like i64) that are split into pieces. For types
1646 /// like i140, which are first promoted then expanded, it is the number of
1647 /// registers needed to hold all the bits of the original type. For an i140
1648 /// on a 32 bit machine this means 5 registers.
1649 ///
1650 /// RegisterVT may be passed as a way to override the default settings, for
1651 /// instance with i128 inline assembly operands on SystemZ.
1652 virtual unsigned
1654 std::optional<MVT> RegisterVT = std::nullopt) const {
1655 if (VT.isSimple()) {
1656 assert((unsigned)VT.getSimpleVT().SimpleTy <
1657 std::size(NumRegistersForVT));
1658 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1659 }
1660 if (VT.isVector()) {
1661 EVT VT1;
1662 MVT VT2;
1663 unsigned NumIntermediates;
1664 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1665 }
1666 if (VT.isInteger()) {
1667 unsigned BitWidth = VT.getSizeInBits();
1668 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1669 return (BitWidth + RegWidth - 1) / RegWidth;
1670 }
1671 llvm_unreachable("Unsupported extended type!");
1672 }
1673
1674 /// Certain combinations of ABIs, Targets and features require that types
1675 /// are legal for some operations and not for other operations.
1676 /// For MIPS all vector types must be passed through the integer register set.
1678 CallingConv::ID CC, EVT VT) const {
1679 return getRegisterType(Context, VT);
1680 }
1681
1682 /// Certain targets require unusual breakdowns of certain types. For MIPS,
1683 /// this occurs when a vector type is used, as vector are passed through the
1684 /// integer register set.
1687 EVT VT) const {
1688 return getNumRegisters(Context, VT);
1689 }
1690
1691 /// Certain targets have context sensitive alignment requirements, where one
1692 /// type has the alignment requirement of another type.
1694 const DataLayout &DL) const {
1695 return DL.getABITypeAlign(ArgTy);
1696 }
1697
1698 /// If true, then instruction selection should seek to shrink the FP constant
1699 /// of the specified type to a smaller type in order to save space and / or
1700 /// reduce runtime.
1701 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1702
1703 /// Return true if it is profitable to reduce a load to a smaller type.
1704 /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
1706 EVT NewVT) const {
1707 // By default, assume that it is cheaper to extract a subvector from a wide
1708 // vector load rather than creating multiple narrow vector loads.
1709 if (NewVT.isVector() && !Load->hasOneUse())
1710 return false;
1711
1712 return true;
1713 }
1714
1715 /// Return true (the default) if it is profitable to remove a sext_inreg(x)
1716 /// where the sext is redundant, and use x directly.
1717 virtual bool shouldRemoveRedundantExtend(SDValue Op) const { return true; }
1718
1719 /// When splitting a value of the specified type into parts, does the Lo
1720 /// or Hi part come first? This usually follows the endianness, except
1721 /// for ppcf128, where the Hi part always comes first.
1723 return DL.isBigEndian() || VT == MVT::ppcf128;
1724 }
1725
1726 /// If true, the target has custom DAG combine transformations that it can
1727 /// perform for the specified node.
1729 assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
1730 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1731 }
1732
1735 }
1736
1737 /// Returns the size of the platform's va_list object.
1738 virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1739 return getPointerTy(DL).getSizeInBits();
1740 }
1741
1742 /// Get maximum # of store operations permitted for llvm.memset
1743 ///
1744 /// This function returns the maximum number of store operations permitted
1745 /// to replace a call to llvm.memset. The value is set by the target at the
1746 /// performance threshold for such a replacement. If OptSize is true,
1747 /// return the limit for functions that have OptSize attribute.
1748 unsigned getMaxStoresPerMemset(bool OptSize) const {
1750 }
1751
1752 /// Get maximum # of store operations permitted for llvm.memcpy
1753 ///
1754 /// This function returns the maximum number of store operations permitted
1755 /// to replace a call to llvm.memcpy. The value is set by the target at the
1756 /// performance threshold for such a replacement. If OptSize is true,
1757 /// return the limit for functions that have OptSize attribute.
1758 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1760 }
1761
1762 /// \brief Get maximum # of store operations to be glued together
1763 ///
1764 /// This function returns the maximum number of store operations permitted
1765 /// to glue together during lowering of llvm.memcpy. The value is set by
1766 // the target at the performance threshold for such a replacement.
1767 virtual unsigned getMaxGluedStoresPerMemcpy() const {
1769 }
1770
1771 /// Get maximum # of load operations permitted for memcmp
1772 ///
1773 /// This function returns the maximum number of load operations permitted
1774 /// to replace a call to memcmp. The value is set by the target at the
1775 /// performance threshold for such a replacement. If OptSize is true,
1776 /// return the limit for functions that have OptSize attribute.
1777 unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1779 }
1780
1781 /// Get maximum # of store operations permitted for llvm.memmove
1782 ///
1783 /// This function returns the maximum number of store operations permitted
1784 /// to replace a call to llvm.memmove. The value is set by the target at the
1785 /// performance threshold for such a replacement. If OptSize is true,
1786 /// return the limit for functions that have OptSize attribute.
1787 unsigned getMaxStoresPerMemmove(bool OptSize) const {
1789 }
1790
1791 /// Determine if the target supports unaligned memory accesses.
1792 ///
1793 /// This function returns true if the target allows unaligned memory accesses
1794 /// of the specified type in the given address space. If true, it also returns
1795 /// a relative speed of the unaligned memory access in the last argument by
1796 /// reference. The higher the speed number the faster the operation comparing
1797 /// to a number returned by another such call. This is used, for example, in
1798 /// situations where an array copy/move/set is converted to a sequence of
1799 /// store operations. Its use helps to ensure that such replacements don't
1800 /// generate code that causes an alignment error (trap) on the target machine.
1802 EVT, unsigned AddrSpace = 0, Align Alignment = Align(1),
1804 unsigned * /*Fast*/ = nullptr) const {
1805 return false;
1806 }
1807
1808 /// LLT handling variant.
1810 LLT, unsigned AddrSpace = 0, Align Alignment = Align(1),
1812 unsigned * /*Fast*/ = nullptr) const {
1813 return false;
1814 }
1815
1816 /// This function returns true if the memory access is aligned or if the
1817 /// target allows this specific unaligned memory access. If the access is
1818 /// allowed, the optional final parameter returns a relative speed of the
1819 /// access (as defined by the target).
1821 LLVMContext &Context, const DataLayout &DL, EVT VT,
1822 unsigned AddrSpace = 0, Align Alignment = Align(1),
1824 unsigned *Fast = nullptr) const;
1825
1826 /// Return true if the memory access of this type is aligned or if the target
1827 /// allows this specific unaligned access for the given MachineMemOperand.
1828 /// If the access is allowed, the optional final parameter returns a relative
1829 /// speed of the access (as defined by the target).
1831 const DataLayout &DL, EVT VT,
1832 const MachineMemOperand &MMO,
1833 unsigned *Fast = nullptr) const;
1834
1835 /// Return true if the target supports a memory access of this type for the
1836 /// given address space and alignment. If the access is allowed, the optional
1837 /// final parameter returns the relative speed of the access (as defined by
1838 /// the target).
1839 virtual bool
1840 allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1841 unsigned AddrSpace = 0, Align Alignment = Align(1),
1843 unsigned *Fast = nullptr) const;
1844
1845 /// Return true if the target supports a memory access of this type for the
1846 /// given MachineMemOperand. If the access is allowed, the optional
1847 /// final parameter returns the relative access speed (as defined by the
1848 /// target).
1849 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1850 const MachineMemOperand &MMO,
1851 unsigned *Fast = nullptr) const;
1852
1853 /// LLT handling variant.
1854 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, LLT Ty,
1855 const MachineMemOperand &MMO,
1856 unsigned *Fast = nullptr) const;
1857
1858 /// Returns the target specific optimal type for load and store operations as
1859 /// a result of memset, memcpy, and memmove lowering.
1860 /// It returns EVT::Other if the type should be determined using generic
1861 /// target-independent logic.
1862 virtual EVT
1864 const AttributeList & /*FuncAttributes*/) const {
1865 return MVT::Other;
1866 }
1867
1868 /// LLT returning variant.
1869 virtual LLT
1871 const AttributeList & /*FuncAttributes*/) const {
1872 return LLT();
1873 }
1874
1875 /// Returns true if it's safe to use load / store of the specified type to
1876 /// expand memcpy / memset inline.
1877 ///
1878 /// This is mostly true for all types except for some special cases. For
1879 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1880 /// fstpl which also does type conversion. Note the specified type doesn't
1881 /// have to be legal as the hook is used before type legalization.
1882 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1883
1884 /// Return lower limit for number of blocks in a jump table.
1885 virtual unsigned getMinimumJumpTableEntries() const;
1886
1887 /// Return lower limit of the density in a jump table.
1888 unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1889
1890 /// Return upper limit for number of entries in a jump table.
1891 /// Zero if no limit.
1892 unsigned getMaximumJumpTableSize() const;
1893
1894 virtual bool isJumpTableRelative() const;
1895
1896 /// If a physical register, this specifies the register that
1897 /// llvm.savestack/llvm.restorestack should save and restore.
1899 return StackPointerRegisterToSaveRestore;
1900 }
1901
1902 /// If a physical register, this returns the register that receives the
1903 /// exception address on entry to an EH pad.
1904 virtual Register
1905 getExceptionPointerRegister(const Constant *PersonalityFn) const {
1906 return Register();
1907 }
1908
1909 /// If a physical register, this returns the register that receives the
1910 /// exception typeid on entry to a landing pad.
1911 virtual Register
1912 getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1913 return Register();
1914 }
1915
1916 virtual bool needsFixedCatchObjects() const {
1917 report_fatal_error("Funclet EH is not implemented for this target");
1918 }
1919
1920 /// Return the minimum stack alignment of an argument.
1922 return MinStackArgumentAlignment;
1923 }
1924
1925 /// Return the minimum function alignment.
1926 Align getMinFunctionAlignment() const { return MinFunctionAlignment; }
1927
1928 /// Return the preferred function alignment.
1929 Align getPrefFunctionAlignment() const { return PrefFunctionAlignment; }
1930
1931 /// Return the preferred loop alignment.
1932 virtual Align getPrefLoopAlignment(MachineLoop *ML = nullptr) const;
1933
1934 /// Return the maximum amount of bytes allowed to be emitted when padding for
1935 /// alignment
1936 virtual unsigned
1938
1939 /// Should loops be aligned even when the function is marked OptSize (but not
1940 /// MinSize).
1941 virtual bool alignLoopsWithOptSize() const { return false; }
1942
1943 /// If the target has a standard location for the stack protector guard,
1944 /// returns the address of that location. Otherwise, returns nullptr.
1945 /// DEPRECATED: please override useLoadStackGuardNode and customize
1946 /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
1947 virtual Value *getIRStackGuard(IRBuilderBase &IRB) const;
1948
1949 /// Inserts necessary declarations for SSP (stack protection) purpose.
1950 /// Should be used only when getIRStackGuard returns nullptr.
1951 virtual void insertSSPDeclarations(Module &M) const;
1952
1953 /// Return the variable that's previously inserted by insertSSPDeclarations,
1954 /// if any, otherwise return nullptr. Should be used only when
1955 /// getIRStackGuard returns nullptr.
1956 virtual Value *getSDagStackGuard(const Module &M) const;
1957
1958 /// If this function returns true, stack protection checks should XOR the
1959 /// frame pointer (or whichever pointer is used to address locals) into the
1960 /// stack guard value before checking it. getIRStackGuard must return nullptr
1961 /// if this returns true.
1962 virtual bool useStackGuardXorFP() const { return false; }
1963
1964 /// If the target has a standard stack protection check function that
1965 /// performs validation and error handling, returns the function. Otherwise,
1966 /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1967 /// Should be used only when getIRStackGuard returns nullptr.
1968 virtual Function *getSSPStackGuardCheck(const Module &M) const;
1969
1970 /// \returns true if a constant G_UBFX is legal on the target.
1971 virtual bool isConstantUnsignedBitfieldExtractLegal(unsigned Opc, LLT Ty1,
1972 LLT Ty2) const {
1973 return false;
1974 }
1975
1976protected:
1978 bool UseTLS) const;
1979
1980public:
1981 /// Returns the target-specific address of the unsafe stack pointer.
1982 virtual Value *getSafeStackPointerLocation(IRBuilderBase &IRB) const;
1983
1984 /// Returns the name of the symbol used to emit stack probes or the empty
1985 /// string if not applicable.
1986 virtual bool hasStackProbeSymbol(const MachineFunction &MF) const { return false; }
1987
1988 virtual bool hasInlineStackProbe(const MachineFunction &MF) const { return false; }
1989
1991 return "";
1992 }
1993
1994 /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1995 /// are happy to sink it into basic blocks. A cast may be free, but not
1996 /// necessarily a no-op. e.g. a free truncate from a 64-bit to 32-bit pointer.
1997 virtual bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const;
1998
1999 /// Return true if the pointer arguments to CI should be aligned by aligning
2000 /// the object whose address is being passed. If so then MinSize is set to the
2001 /// minimum size the object must be to be aligned and PrefAlign is set to the
2002 /// preferred alignment.
2003 virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
2004 Align & /*PrefAlign*/) const {
2005 return false;
2006 }
2007
2008 //===--------------------------------------------------------------------===//
2009 /// \name Helpers for TargetTransformInfo implementations
2010 /// @{
2011
2012 /// Get the ISD node that corresponds to the Instruction class opcode.
2013 int InstructionOpcodeToISD(unsigned Opcode) const;
2014
2015 /// @}
2016
2017 //===--------------------------------------------------------------------===//
2018 /// \name Helpers for atomic expansion.
2019 /// @{
2020
2021 /// Returns the maximum atomic operation size (in bits) supported by
2022 /// the backend. Atomic operations greater than this size (as well
2023 /// as ones that are not naturally aligned), will be expanded by
2024 /// AtomicExpandPass into an __atomic_* library call.
2026 return MaxAtomicSizeInBitsSupported;
2027 }
2028
2029 /// Returns the size in bits of the maximum div/rem the backend supports.
2030 /// Larger operations will be expanded by ExpandLargeDivRem.
2032 return MaxDivRemBitWidthSupported;
2033 }
2034
2035 /// Returns the size in bits of the maximum larget fp convert the backend
2036 /// supports. Larger operations will be expanded by ExpandLargeFPConvert.
2038 return MaxLargeFPConvertBitWidthSupported;
2039 }
2040
2041 /// Returns the size of the smallest cmpxchg or ll/sc instruction
2042 /// the backend supports. Any smaller operations are widened in
2043 /// AtomicExpandPass.
2044 ///
2045 /// Note that *unlike* operations above the maximum size, atomic ops
2046 /// are still natively supported below the minimum; they just
2047 /// require a more complex expansion.
2048 unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
2049
2050 /// Whether the target supports unaligned atomic operations.
2051 bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
2052
2053 /// Whether AtomicExpandPass should automatically insert fences and reduce
2054 /// ordering for this atomic. This should be true for most architectures with
2055 /// weak memory ordering. Defaults to false.
2056 virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
2057 return false;
2058 }
2059
2060 /// Whether AtomicExpandPass should automatically insert a trailing fence
2061 /// without reducing the ordering for this atomic. Defaults to false.
2062 virtual bool
2064 return false;
2065 }
2066
2067 /// Perform a load-linked operation on Addr, returning a "Value *" with the
2068 /// corresponding pointee type. This may entail some non-trivial operations to
2069 /// truncate or reconstruct types that will be illegal in the backend. See
2070 /// ARMISelLowering for an example implementation.
2071 virtual Value *emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
2072 Value *Addr, AtomicOrdering Ord) const {
2073 llvm_unreachable("Load linked unimplemented on this target");
2074 }
2075
2076 /// Perform a store-conditional operation to Addr. Return the status of the
2077 /// store. This should be 0 if the store succeeded, non-zero otherwise.
2079 Value *Addr, AtomicOrdering Ord) const {
2080 llvm_unreachable("Store conditional unimplemented on this target");
2081 }
2082
2083 /// Perform a masked atomicrmw using a target-specific intrinsic. This
2084 /// represents the core LL/SC loop which will be lowered at a late stage by
2085 /// the backend. The target-specific intrinsic returns the loaded value and
2086 /// is not responsible for masking and shifting the result.
2088 AtomicRMWInst *AI,
2089 Value *AlignedAddr, Value *Incr,
2090 Value *Mask, Value *ShiftAmt,
2091 AtomicOrdering Ord) const {
2092 llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
2093 }
2094
2095 /// Perform a atomicrmw expansion using a target-specific way. This is
2096 /// expected to be called when masked atomicrmw and bit test atomicrmw don't
2097 /// work, and the target supports another way to lower atomicrmw.
2098 virtual void emitExpandAtomicRMW(AtomicRMWInst *AI) const {
2100 "Generic atomicrmw expansion unimplemented on this target");
2101 }
2102
2103 /// Perform a bit test atomicrmw using a target-specific intrinsic. This
2104 /// represents the combined bit test intrinsic which will be lowered at a late
2105 /// stage by the backend.
2108 "Bit test atomicrmw expansion unimplemented on this target");
2109 }
2110
2111 /// Perform a atomicrmw which the result is only used by comparison, using a
2112 /// target-specific intrinsic. This represents the combined atomic and compare
2113 /// intrinsic which will be lowered at a late stage by the backend.
2116 "Compare arith atomicrmw expansion unimplemented on this target");
2117 }
2118
2119 /// Perform a masked cmpxchg using a target-specific intrinsic. This
2120 /// represents the core LL/SC loop which will be lowered at a late stage by
2121 /// the backend. The target-specific intrinsic returns the loaded value and
2122 /// is not responsible for masking and shifting the result.
2124 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
2125 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
2126 llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
2127 }
2128
2129 //===--------------------------------------------------------------------===//
2130 /// \name KCFI check lowering.
2131 /// @{
2132
2135 const TargetInstrInfo *TII) const {
2136 llvm_unreachable("KCFI is not supported on this target");
2137 }
2138
2139 /// @}
2140
2141 /// Inserts in the IR a target-specific intrinsic specifying a fence.
2142 /// It is called by AtomicExpandPass before expanding an
2143 /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
2144 /// if shouldInsertFencesForAtomic returns true.
2145 ///
2146 /// Inst is the original atomic instruction, prior to other expansions that
2147 /// may be performed.
2148 ///
2149 /// This function should either return a nullptr, or a pointer to an IR-level
2150 /// Instruction*. Even complex fence sequences can be represented by a
2151 /// single Instruction* through an intrinsic to be lowered later.
2152 /// Backends should override this method to produce target-specific intrinsic
2153 /// for their fences.
2154 /// FIXME: Please note that the default implementation here in terms of
2155 /// IR-level fences exists for historical/compatibility reasons and is
2156 /// *unsound* ! Fences cannot, in general, be used to restore sequential
2157 /// consistency. For example, consider the following example:
2158 /// atomic<int> x = y = 0;
2159 /// int r1, r2, r3, r4;
2160 /// Thread 0:
2161 /// x.store(1);
2162 /// Thread 1:
2163 /// y.store(1);
2164 /// Thread 2:
2165 /// r1 = x.load();
2166 /// r2 = y.load();
2167 /// Thread 3:
2168 /// r3 = y.load();
2169 /// r4 = x.load();
2170 /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
2171 /// seq_cst. But if they are lowered to monotonic accesses, no amount of
2172 /// IR-level fences can prevent it.
2173 /// @{
2174 virtual Instruction *emitLeadingFence(IRBuilderBase &Builder,
2175 Instruction *Inst,
2176 AtomicOrdering Ord) const;
2177
2179 Instruction *Inst,
2180 AtomicOrdering Ord) const;
2181 /// @}
2182
2183 // Emits code that executes when the comparison result in the ll/sc
2184 // expansion of a cmpxchg instruction is such that the store-conditional will
2185 // not execute. This makes it possible to balance out the load-linked with
2186 // a dedicated instruction, if desired.
2187 // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
2188 // be unnecessarily held, except if clrex, inserted by this hook, is executed.
2189 virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilderBase &Builder) const {}
2190
2191 /// Returns true if arguments should be sign-extended in lib calls.
2192 virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
2193 return IsSigned;
2194 }
2195
2196 /// Returns true if arguments should be extended in lib calls.
2197 virtual bool shouldExtendTypeInLibCall(EVT Type) const {
2198 return true;
2199 }
2200
2201 /// Returns how the given (atomic) load should be expanded by the
2202 /// IR-level AtomicExpand pass.
2205 }
2206
2207 /// Returns how the given (atomic) load should be cast by the IR-level
2208 /// AtomicExpand pass.
2210 if (LI->getType()->isFloatingPointTy())
2213 }
2214
2215 /// Returns how the given (atomic) store should be expanded by the IR-level
2216 /// AtomicExpand pass into. For instance AtomicExpansionKind::Expand will try
2217 /// to use an atomicrmw xchg.
2220 }
2221
2222 /// Returns how the given (atomic) store should be cast by the IR-level
2223 /// AtomicExpand pass into. For instance AtomicExpansionKind::CastToInteger
2224 /// will try to cast the operands to integer values.
2226 if (SI->getValueOperand()->getType()->isFloatingPointTy())
2229 }
2230
2231 /// Returns how the given atomic cmpxchg should be expanded by the IR-level
2232 /// AtomicExpand pass.
2233 virtual AtomicExpansionKind
2236 }
2237
2238 /// Returns how the IR-level AtomicExpand pass should expand the given
2239 /// AtomicRMW, if at all. Default is to never expand.
2241 return RMW->isFloatingPointOperation() ?
2243 }
2244
2245 /// Returns how the given atomic atomicrmw should be cast by the IR-level
2246 /// AtomicExpand pass.
2247 virtual AtomicExpansionKind
2249 if (RMWI->getOperation() == AtomicRMWInst::Xchg &&
2250 (RMWI->getValOperand()->getType()->isFloatingPointTy() ||
2251 RMWI->getValOperand()->getType()->isPointerTy()))
2253
2255 }
2256
2257 /// On some platforms, an AtomicRMW that never actually modifies the value
2258 /// (such as fetch_add of 0) can be turned into a fence followed by an
2259 /// atomic load. This may sound useless, but it makes it possible for the
2260 /// processor to keep the cacheline shared, dramatically improving
2261 /// performance. And such idempotent RMWs are useful for implementing some
2262 /// kinds of locks, see for example (justification + benchmarks):
2263 /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
2264 /// This method tries doing that transformation, returning the atomic load if
2265 /// it succeeds, and nullptr otherwise.
2266 /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
2267 /// another round of expansion.
2268 virtual LoadInst *
2270 return nullptr;
2271 }
2272
2273 /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
2274 /// SIGN_EXTEND, or ANY_EXTEND).
2276 return ISD::ZERO_EXTEND;
2277 }
2278
2279 /// Returns how the platform's atomic compare and swap expects its comparison
2280 /// value to be extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND). This is
2281 /// separate from getExtendForAtomicOps, which is concerned with the
2282 /// sign-extension of the instruction's output, whereas here we are concerned
2283 /// with the sign-extension of the input. For targets with compare-and-swap
2284 /// instructions (or sub-word comparisons in their LL/SC loop expansions),
2285 /// the input can be ANY_EXTEND, but the output will still have a specific
2286 /// extension.
2288 return ISD::ANY_EXTEND;
2289 }
2290
2291 /// @}
2292
2293 /// Returns true if we should normalize
2294 /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
2295 /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
2296 /// that it saves us from materializing N0 and N1 in an integer register.
2297 /// Targets that are able to perform and/or on flags should return false here.
2299 EVT VT) const {
2300 // If a target has multiple condition registers, then it likely has logical
2301 // operations on those registers.
2303 return false;
2304 // Only do the transform if the value won't be split into multiple
2305 // registers.
2307 return Action != TypeExpandInteger && Action != TypeExpandFloat &&
2308 Action != TypeSplitVector;
2309 }
2310
2311 virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
2312
2313 /// Return true if a select of constants (select Cond, C1, C2) should be
2314 /// transformed into simple math ops with the condition value. For example:
2315 /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
2316 virtual bool convertSelectOfConstantsToMath(EVT VT) const {
2317 return false;
2318 }
2319
2320 /// Return true if it is profitable to transform an integer
2321 /// multiplication-by-constant into simpler operations like shifts and adds.
2322 /// This may be true if the target does not directly support the
2323 /// multiplication operation for the specified type or the sequence of simpler
2324 /// ops is faster than the multiply.
2326 EVT VT, SDValue C) const {
2327 return false;
2328 }
2329
2330 /// Return true if it may be profitable to transform
2331 /// (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
2332 /// This may not be true if c1 and c2 can be represented as immediates but
2333 /// c1*c2 cannot, for example.
2334 /// The target should check if c1, c2 and c1*c2 can be represented as
2335 /// immediates, or have to be materialized into registers. If it is not sure
2336 /// about some cases, a default true can be returned to let the DAGCombiner
2337 /// decide.
2338 /// AddNode is (add x, c1), and ConstNode is c2.
2340 SDValue ConstNode) const {
2341 return true;
2342 }
2343
2344 /// Return true if it is more correct/profitable to use strict FP_TO_INT
2345 /// conversion operations - canonicalizing the FP source value instead of
2346 /// converting all cases and then selecting based on value.
2347 /// This may be true if the target throws exceptions for out of bounds
2348 /// conversions or has fast FP CMOV.
2349 virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
2350 bool IsSigned) const {
2351 return false;
2352 }
2353
2354 /// Return true if it is beneficial to expand an @llvm.powi.* intrinsic.
2355 /// If not optimizing for size, expanding @llvm.powi.* intrinsics is always
2356 /// considered beneficial.
2357 /// If optimizing for size, expansion is only considered beneficial for upto
2358 /// 5 multiplies and a divide (if the exponent is negative).
2359 bool isBeneficialToExpandPowI(int64_t Exponent, bool OptForSize) const {
2360 if (Exponent < 0)
2361 Exponent = -Exponent;
2362 uint64_t E = static_cast<uint64_t>(Exponent);
2363 return !OptForSize || (llvm::popcount(E) + Log2_64(E) < 7);
2364 }
2365
2366 //===--------------------------------------------------------------------===//
2367 // TargetLowering Configuration Methods - These methods should be invoked by
2368 // the derived class constructor to configure this object for the target.
2369 //
2370protected:
2371 /// Specify how the target extends the result of integer and floating point
2372 /// boolean values from i1 to a wider type. See getBooleanContents.
2374 BooleanContents = Ty;
2375 BooleanFloatContents = Ty;
2376 }
2377
2378 /// Specify how the target extends the result of integer and floating point
2379 /// boolean values from i1 to a wider type. See getBooleanContents.
2381 BooleanContents = IntTy;
2382 BooleanFloatContents = FloatTy;
2383 }
2384
2385 /// Specify how the target extends the result of a vector boolean value from a
2386 /// vector of i1 to a wider type. See getBooleanContents.
2388 BooleanVectorContents = Ty;
2389 }
2390
2391 /// Specify the target scheduling preference.
2393 SchedPreferenceInfo = Pref;
2394 }
2395
2396 /// Indicate the minimum number of blocks to generate jump tables.
2397 void setMinimumJumpTableEntries(unsigned Val);
2398
2399 /// Indicate the maximum number of entries in jump tables.
2400 /// Set to zero to generate unlimited jump tables.
2401 void setMaximumJumpTableSize(unsigned);
2402
2403 /// If set to a physical register, this specifies the register that
2404 /// llvm.savestack/llvm.restorestack should save and restore.
2406 StackPointerRegisterToSaveRestore = R;
2407 }
2408
2409 /// Tells the code generator that the target has multiple (allocatable)
2410 /// condition registers that can be used to store the results of comparisons
2411 /// for use by selects and conditional branches. With multiple condition
2412 /// registers, the code generator will not aggressively sink comparisons into
2413 /// the blocks of their users.
2414 void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
2415 HasMultipleConditionRegisters = hasManyRegs;
2416 }
2417
2418 /// Tells the code generator that the target has BitExtract instructions.
2419 /// The code generator will aggressively sink "shift"s into the blocks of
2420 /// their users if the users will generate "and" instructions which can be
2421 /// combined with "shift" to BitExtract instructions.
2422 void setHasExtractBitsInsn(bool hasExtractInsn = true) {
2423 HasExtractBitsInsn = hasExtractInsn;
2424 }
2425
2426 /// Tells the code generator not to expand logic operations on comparison
2427 /// predicates into separate sequences that increase the amount of flow
2428 /// control.
2429 void setJumpIsExpensive(bool isExpensive = true);
2430
2431 /// Tells the code generator which bitwidths to bypass.
2432 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
2433 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
2434 }
2435
2436 /// Add the specified register class as an available regclass for the
2437 /// specified value type. This indicates the selector can handle values of
2438 /// that class natively.
2440 assert((unsigned)VT.SimpleTy < std::size(RegClassForVT));
2441 RegClassForVT[VT.SimpleTy] = RC;
2442 }
2443
2444 /// Return the largest legal super-reg register class of the register class
2445 /// for the specified type and its associated "cost".
2446 virtual std::pair<const TargetRegisterClass *, uint8_t>
2448
2449 /// Once all of the register classes are added, this allows us to compute
2450 /// derived properties we expose.
2452
2453 /// Indicate that the specified operation does not work with the specified
2454 /// type and indicate what to do about it. Note that VT may refer to either
2455 /// the type of a result or that of an operand of Op.
2456 void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action) {
2457 assert(Op < std::size(OpActions[0]) && "Table isn't big enough!");
2458 OpActions[(unsigned)VT.SimpleTy][Op] = Action;
2459 }
2461 LegalizeAction Action) {
2462 for (auto Op : Ops)
2463 setOperationAction(Op, VT, Action);
2464 }
2466 LegalizeAction Action) {
2467 for (auto VT : VTs)
2468 setOperationAction(Ops, VT, Action);
2469 }
2470
2471 /// Indicate that the specified load with extension does not work with the
2472 /// specified type and indicate what to do about it.
2473 void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
2474 LegalizeAction Action) {
2475 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
2476 MemVT.isValid() && "Table isn't big enough!");
2477 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2478 unsigned Shift = 4 * ExtType;
2479 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
2480 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
2481 }
2482 void setLoadExtAction(ArrayRef<unsigned> ExtTypes, MVT ValVT, MVT MemVT,
2483 LegalizeAction Action) {
2484 for (auto ExtType : ExtTypes)
2485 setLoadExtAction(ExtType, ValVT, MemVT, Action);
2486 }
2488 ArrayRef<MVT> MemVTs, LegalizeAction Action) {
2489 for (auto MemVT : MemVTs)
2490 setLoadExtAction(ExtTypes, ValVT, MemVT, Action);
2491 }
2492
2493 /// Indicate that the specified truncating store does not work with the
2494 /// specified type and indicate what to do about it.
2495 void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action) {
2496 assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
2497 TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
2498 }
2499
2500 /// Indicate that the specified indexed load does or does not work with the
2501 /// specified type and indicate what to do abort it.
2502 ///
2503 /// NOTE: All indexed mode loads are initialized to Expand in
2504 /// TargetLowering.cpp
2506 LegalizeAction Action) {
2507 for (auto IdxMode : IdxModes)
2508 setIndexedModeAction(IdxMode, VT, IMAB_Load, Action);
2509 }
2510
2512 LegalizeAction Action) {
2513 for (auto VT : VTs)
2514 setIndexedLoadAction(IdxModes, VT, Action);
2515 }
2516
2517 /// Indicate that the specified indexed store does or does not work with the
2518 /// specified type and indicate what to do about it.
2519 ///
2520 /// NOTE: All indexed mode stores are initialized to Expand in
2521 /// TargetLowering.cpp
2523 LegalizeAction Action) {
2524 for (auto IdxMode : IdxModes)
2525 setIndexedModeAction(IdxMode, VT, IMAB_Store, Action);
2526 }
2527
2529 LegalizeAction Action) {
2530 for (auto VT : VTs)
2531 setIndexedStoreAction(IdxModes, VT, Action);
2532 }
2533
2534 /// Indicate that the specified indexed masked load does or does not work with
2535 /// the specified type and indicate what to do about it.
2536 ///
2537 /// NOTE: All indexed mode masked loads are initialized to Expand in
2538 /// TargetLowering.cpp
2539 void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT,
2540 LegalizeAction Action) {
2541 setIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad, Action);
2542 }
2543
2544 /// Indicate that the specified indexed masked store does or does not work
2545 /// with the specified type and indicate what to do about it.
2546 ///
2547 /// NOTE: All indexed mode masked stores are initialized to Expand in
2548 /// TargetLowering.cpp
2549 void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT,
2550 LegalizeAction Action) {
2551 setIndexedModeAction(IdxMode, VT, IMAB_MaskedStore, Action);
2552 }
2553
2554 /// Indicate that the specified condition code is or isn't supported on the
2555 /// target and indicate what to do about it.
2557 LegalizeAction Action) {
2558 for (auto CC : CCs) {
2559 assert(VT.isValid() && (unsigned)CC < std::size(CondCodeActions) &&
2560 "Table isn't big enough!");
2561 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2562 /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the
2563 /// 32-bit value and the upper 29 bits index into the second dimension of
2564 /// the array to select what 32-bit value to use.
2565 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
2566 CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
2567 CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
2568 }
2569 }
2571 LegalizeAction Action) {
2572 for (auto VT : VTs)
2573 setCondCodeAction(CCs, VT, Action);
2574 }
2575
2576 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
2577 /// to trying a larger integer/fp until it can find one that works. If that
2578 /// default is insufficient, this method can be used by the target to override
2579 /// the default.
2580 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2581 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
2582 }
2583
2584 /// Convenience method to set an operation to Promote and specify the type
2585 /// in a single call.
2586 void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2587 setOperationAction(Opc, OrigVT, Promote);
2588 AddPromotedToType(Opc, OrigVT, DestVT);
2589 }
2591 MVT DestVT) {
2592 for (auto Op : Ops) {
2593 setOperationAction(Op, OrigVT, Promote);
2594 AddPromotedToType(Op, OrigVT, DestVT);
2595 }
2596 }
2597
2598 /// Targets should invoke this method for each target independent node that
2599 /// they want to provide a custom DAG combiner for by implementing the
2600 /// PerformDAGCombine virtual method.
2602 for (auto NT : NTs) {
2603 assert(unsigned(NT >> 3) < std::size(TargetDAGCombineArray));
2604 TargetDAGCombineArray[NT >> 3] |= 1 << (NT & 7);
2605 }
2606 }
2607
2608 /// Set the target's minimum function alignment.
2610 MinFunctionAlignment = Alignment;
2611 }
2612
2613 /// Set the target's preferred function alignment. This should be set if
2614 /// there is a performance benefit to higher-than-minimum alignment
2616 PrefFunctionAlignment = Alignment;
2617 }
2618
2619 /// Set the target's preferred loop alignment. Default alignment is one, it
2620 /// means the target does not care about loop alignment. The target may also
2621 /// override getPrefLoopAlignment to provide per-loop values.
2622 void setPrefLoopAlignment(Align Alignment) { PrefLoopAlignment = Alignment; }
2623 void setMaxBytesForAlignment(unsigned MaxBytes) {
2624 MaxBytesForAlignment = MaxBytes;
2625 }
2626
2627 /// Set the minimum stack alignment of an argument.
2629 MinStackArgumentAlignment = Alignment;
2630 }
2631
2632 /// Set the maximum atomic operation size supported by the
2633 /// backend. Atomic operations greater than this size (as well as
2634 /// ones that are not naturally aligned), will be expanded by
2635 /// AtomicExpandPass into an __atomic_* library call.
2636 void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
2637 MaxAtomicSizeInBitsSupported = SizeInBits;
2638 }
2639
2640 /// Set the size in bits of the maximum div/rem the backend supports.
2641 /// Larger operations will be expanded by ExpandLargeDivRem.
2642 void setMaxDivRemBitWidthSupported(unsigned SizeInBits) {
2643 MaxDivRemBitWidthSupported = SizeInBits;
2644 }
2645
2646 /// Set the size in bits of the maximum fp convert the backend supports.
2647 /// Larger operations will be expanded by ExpandLargeFPConvert.
2648 void setMaxLargeFPConvertBitWidthSupported(unsigned SizeInBits) {
2649 MaxLargeFPConvertBitWidthSupported = SizeInBits;
2650 }
2651
2652 /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
2653 void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
2654 MinCmpXchgSizeInBits = SizeInBits;
2655 }
2656
2657 /// Sets whether unaligned atomic operations are supported.
2658 void setSupportsUnalignedAtomics(bool UnalignedSupported) {
2659 SupportsUnalignedAtomics = UnalignedSupported;
2660 }
2661
2662public:
2663 //===--------------------------------------------------------------------===//
2664 // Addressing mode description hooks (used by LSR etc).
2665 //
2666
2667 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
2668 /// instructions reading the address. This allows as much computation as
2669 /// possible to be done in the address mode for that operand. This hook lets
2670 /// targets also pass back when this should be done on intrinsics which
2671 /// load/store.
2673 SmallVectorImpl<Value*> &/*Ops*/,
2674 Type *&/*AccessTy*/) const {
2675 return false;
2676 }
2677
2678 /// This represents an addressing mode of:
2679 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
2680 /// If BaseGV is null, there is no BaseGV.
2681 /// If BaseOffs is zero, there is no base offset.
2682 /// If HasBaseReg is false, there is no base register.
2683 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
2684 /// no scale.
2685 struct AddrMode {
2687 int64_t BaseOffs = 0;
2688 bool HasBaseReg = false;
2689 int64_t Scale = 0;
2690 AddrMode() = default;
2691 };
2692
2693 /// Return true if the addressing mode represented by AM is legal for this
2694 /// target, for a load/store of the specified type.
2695 ///
2696 /// The type may be VoidTy, in which case only return true if the addressing
2697 /// mode is legal for a load/store of any legal type. TODO: Handle
2698 /// pre/postinc as well.
2699 ///
2700 /// If the address space cannot be determined, it will be -1.
2701 ///
2702 /// TODO: Remove default argument
2703 virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
2704 Type *Ty, unsigned AddrSpace,
2705 Instruction *I = nullptr) const;
2706
2707 /// Return true if the specified immediate is legal icmp immediate, that is
2708 /// the target has icmp instructions which can compare a register against the
2709 /// immediate without having to materialize the immediate into a register.
2710 virtual bool isLegalICmpImmediate(int64_t) const {
2711 return true;
2712 }
2713
2714 /// Return true if the specified immediate is legal add immediate, that is the
2715 /// target has add instructions which can add a register with the immediate
2716 /// without having to materialize the immediate into a register.
2717 virtual bool isLegalAddImmediate(int64_t) const {
2718 return true;
2719 }
2720
2721 /// Return true if the specified immediate is legal for the value input of a
2722 /// store instruction.
2723 virtual bool isLegalStoreImmediate(int64_t Value) const {
2724 // Default implementation assumes that at least 0 works since it is likely
2725 // that a zero register exists or a zero immediate is allowed.
2726 return Value == 0;
2727 }
2728
2729 /// Return true if it's significantly cheaper to shift a vector by a uniform
2730 /// scalar than by an amount which will vary across each lane. On x86 before
2731 /// AVX2 for example, there is a "psllw" instruction for the former case, but
2732 /// no simple instruction for a general "a << b" operation on vectors.
2733 /// This should also apply to lowering for vector funnel shifts (rotates).
2734 virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
2735 return false;
2736 }
2737
2738 /// Given a shuffle vector SVI representing a vector splat, return a new
2739 /// scalar type of size equal to SVI's scalar type if the new type is more
2740 /// profitable. Returns nullptr otherwise. For example under MVE float splats
2741 /// are converted to integer to prevent the need to move from SPR to GPR
2742 /// registers.
2744 return nullptr;
2745 }
2746
2747 /// Given a set in interconnected phis of type 'From' that are loaded/stored
2748 /// or bitcast to type 'To', return true if the set should be converted to
2749 /// 'To'.
2750 virtual bool shouldConvertPhiType(Type *From, Type *To) const {
2751 return (From->isIntegerTy() || From->isFloatingPointTy()) &&
2752 (To->isIntegerTy() || To->isFloatingPointTy());
2753 }
2754
2755 /// Returns true if the opcode is a commutative binary operation.
2756 virtual bool isCommutativeBinOp(unsigned Opcode) const {
2757 // FIXME: This should get its info from the td file.
2758 switch (Opcode) {
2759 case ISD::ADD:
2760 case ISD::SMIN:
2761 case ISD::SMAX:
2762 case ISD::UMIN:
2763 case ISD::UMAX:
2764 case ISD::MUL:
2765 case ISD::MULHU:
2766 case ISD::MULHS:
2767 case ISD::SMUL_LOHI:
2768 case ISD::UMUL_LOHI:
2769 case ISD::FADD:
2770 case ISD::FMUL:
2771 case ISD::AND:
2772 case ISD::OR:
2773 case ISD::XOR:
2774 case ISD::SADDO:
2775 case ISD::UADDO:
2776 case ISD::ADDC:
2777 case ISD::ADDE:
2778 case ISD::SADDSAT:
2779 case ISD::UADDSAT:
2780 case ISD::FMINNUM:
2781 case ISD::FMAXNUM:
2782 case ISD::FMINNUM_IEEE:
2783 case ISD::FMAXNUM_IEEE:
2784 case ISD::FMINIMUM:
2785 case ISD::FMAXIMUM:
2786 case ISD::AVGFLOORS:
2787 case ISD::AVGFLOORU:
2788 case ISD::AVGCEILS:
2789 case ISD::AVGCEILU:
2790 case ISD::ABDS:
2791 case ISD::ABDU:
2792 return true;
2793 default: return false;
2794 }
2795 }
2796
2797 /// Return true if the node is a math/logic binary operator.
2798 virtual bool isBinOp(unsigned Opcode) const {
2799 // A commutative binop must be a binop.
2800 if (isCommutativeBinOp(Opcode))
2801 return true;
2802 // These are non-commutative binops.
2803 switch (Opcode) {
2804 case ISD::SUB:
2805 case ISD::SHL:
2806 case ISD::SRL:
2807 case ISD::SRA:
2808 case ISD::ROTL:
2809 case ISD::ROTR:
2810 case ISD::SDIV:
2811 case ISD::UDIV:
2812 case ISD::SREM:
2813 case ISD::UREM:
2814 case ISD::SSUBSAT:
2815 case ISD::USUBSAT:
2816 case ISD::FSUB:
2817 case ISD::FDIV:
2818 case ISD::FREM:
2819 return true;
2820 default:
2821 return false;
2822 }
2823 }
2824
2825 /// Return true if it's free to truncate a value of type FromTy to type
2826 /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
2827 /// by referencing its sub-register AX.
2828 /// Targets must return false when FromTy <= ToTy.
2829 virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
2830 return false;
2831 }
2832
2833 /// Return true if a truncation from FromTy to ToTy is permitted when deciding
2834 /// whether a call is in tail position. Typically this means that both results
2835 /// would be assigned to the same register or stack slot, but it could mean
2836 /// the target performs adequate checks of its own before proceeding with the
2837 /// tail call. Targets must return false when FromTy <= ToTy.
2838 virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
2839 return false;
2840 }
2841
2842 virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const { return false; }
2843 virtual bool isTruncateFree(LLT FromTy, LLT ToTy, const DataLayout &DL,
2844 LLVMContext &Ctx) const {
2845 return isTruncateFree(getApproximateEVTForLLT(FromTy, DL, Ctx),
2846 getApproximateEVTForLLT(ToTy, DL, Ctx));
2847 }
2848
2849 virtual bool isProfitableToHoist(Instruction *I) const { return true; }
2850
2851 /// Return true if the extension represented by \p I is free.
2852 /// Unlikely the is[Z|FP]ExtFree family which is based on types,
2853 /// this method can use the context provided by \p I to decide
2854 /// whether or not \p I is free.
2855 /// This method extends the behavior of the is[Z|FP]ExtFree family.
2856 /// In other words, if is[Z|FP]Free returns true, then this method
2857 /// returns true as well. The converse is not true.
2858 /// The target can perform the adequate checks by overriding isExtFreeImpl.
2859 /// \pre \p I must be a sign, zero, or fp extension.
2860 bool isExtFree(const Instruction *I) const {
2861 switch (I->getOpcode()) {
2862 case Instruction::FPExt:
2863 if (isFPExtFree(EVT::getEVT(I->getType()),
2864 EVT::getEVT(I->getOperand(0)->getType())))
2865 return true;
2866 break;
2867 case Instruction::ZExt:
2868 if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2869 return true;
2870 break;
2871 case Instruction::SExt:
2872 break;
2873 default:
2874 llvm_unreachable("Instruction is not an extension");
2875 }
2876 return isExtFreeImpl(I);
2877 }
2878
2879 /// Return true if \p Load and \p Ext can form an ExtLoad.
2880 /// For example, in AArch64
2881 /// %L = load i8, i8* %ptr
2882 /// %E = zext i8 %L to i32
2883 /// can be lowered into one load instruction
2884 /// ldrb w0, [x0]
2885 bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2886 const DataLayout &DL) const {
2887 EVT VT = getValueType(DL, Ext->getType());
2888 EVT LoadVT = getValueType(DL, Load->getType());
2889
2890 // If the load has other users and the truncate is not free, the ext
2891 // probably isn't free.
2892 if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
2893 !isTruncateFree(Ext->getType(), Load->getType()))
2894 return false;
2895
2896 // Check whether the target supports casts folded into loads.
2897 unsigned LType;
2898 if (isa<ZExtInst>(Ext))
2899 LType = ISD::ZEXTLOAD;
2900 else {
2901 assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
2902 LType = ISD::SEXTLOAD;
2903 }
2904
2905 return isLoadExtLegal(LType, VT, LoadVT);
2906 }
2907
2908 /// Return true if any actual instruction that defines a value of type FromTy
2909 /// implicitly zero-extends the value to ToTy in the result register.
2910 ///
2911 /// The function should return true when it is likely that the truncate can
2912 /// be freely folded with an instruction defining a value of FromTy. If
2913 /// the defining instruction is unknown (because you're looking at a
2914 /// function argument, PHI, etc.) then the target may require an
2915 /// explicit truncate, which is not necessarily free, but this function
2916 /// does not deal with those cases.
2917 /// Targets must return false when FromTy >= ToTy.
2918 virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2919 return false;
2920 }
2921
2922 virtual bool isZExtFree(EVT FromTy, EVT ToTy) const { return false; }
2923 virtual bool isZExtFree(LLT FromTy, LLT ToTy, const DataLayout &DL,
2924 LLVMContext &Ctx) const {
2925 return isZExtFree(getApproximateEVTForLLT(FromTy, DL, Ctx),
2926 getApproximateEVTForLLT(ToTy, DL, Ctx));
2927 }
2928
2929 /// Return true if zero-extending the specific node Val to type VT2 is free
2930 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2931 /// because it's folded such as X86 zero-extending loads).
2932 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2933 return isZExtFree(Val.getValueType(), VT2);
2934 }
2935
2936 /// Return true if sign-extension from FromTy to ToTy is cheaper than
2937 /// zero-extension.
2938 virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
2939 return false;
2940 }
2941
2942 /// Return true if this constant should be sign extended when promoting to
2943 /// a larger type.
2944 virtual bool signExtendConstant(const ConstantInt *C) const { return false; }
2945
2946 /// Return true if sinking I's operands to the same basic block as I is
2947 /// profitable, e.g. because the operands can be folded into a target
2948 /// instruction during instruction selection. After calling the function
2949 /// \p Ops contains the Uses to sink ordered by dominance (dominating users
2950 /// come first).
2952 SmallVectorImpl<Use *> &Ops) const {
2953 return false;
2954 }
2955
2956 /// Try to optimize extending or truncating conversion instructions (like
2957 /// zext, trunc, fptoui, uitofp) for the target.
2958 virtual bool
2960 const TargetTransformInfo &TTI) const {
2961 return false;
2962 }
2963
2964 /// Return true if the target supplies and combines to a paired load
2965 /// two loaded values of type LoadedType next to each other in memory.
2966 /// RequiredAlignment gives the minimal alignment constraints that must be met
2967 /// to be able to select this paired load.
2968 ///
2969 /// This information is *not* used to generate actual paired loads, but it is
2970 /// used to generate a sequence of loads that is easier to combine into a
2971 /// paired load.
2972 /// For instance, something like this:
2973 /// a = load i64* addr
2974 /// b = trunc i64 a to i32
2975 /// c = lshr i64 a, 32
2976 /// d = trunc i64 c to i32
2977 /// will be optimized into:
2978 /// b = load i32* addr1
2979 /// d = load i32* addr2
2980 /// Where addr1 = addr2 +/- sizeof(i32).
2981 ///
2982 /// In other words, unless the target performs a post-isel load combining,
2983 /// this information should not be provided because it will generate more
2984 /// loads.
2985 virtual bool hasPairedLoad(EVT /*LoadedType*/,
2986 Align & /*RequiredAlignment*/) const {
2987 return false;
2988 }
2989
2990 /// Return true if the target has a vector blend instruction.
2991 virtual bool hasVectorBlend() const { return false; }
2992
2993 /// Get the maximum supported factor for interleaved memory accesses.
2994 /// Default to be the minimum interleave factor: 2.
2995 virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2996
2997 /// Lower an interleaved load to target specific intrinsics. Return
2998 /// true on success.
2999 ///
3000 /// \p LI is the vector load instruction.
3001 /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
3002 /// \p Indices is the corresponding indices for each shufflevector.
3003 /// \p Factor is the interleave factor.
3006 ArrayRef<unsigned> Indices,
3007 unsigned Factor) const {
3008 return false;
3009 }
3010
3011 /// Lower an interleaved store to target specific intrinsics. Return
3012 /// true on success.
3013 ///
3014 /// \p SI is the vector store instruction.
3015 /// \p SVI is the shufflevector to RE-interleave the stored vector.
3016 /// \p Factor is the interleave factor.
3018 unsigned Factor) const {
3019 return false;
3020 }
3021
3022 /// Lower a deinterleave intrinsic to a target specific load intrinsic.
3023 /// Return true on success. Currently only supports
3024 /// llvm.experimental.vector.deinterleave2
3025 ///
3026 /// \p DI is the deinterleave intrinsic.
3027 /// \p LI is the accompanying load instruction
3029 LoadInst *LI) const {
3030 return false;
3031 }
3032
3033 /// Lower an interleave intrinsic to a target specific store intrinsic.
3034 /// Return true on success. Currently only supports
3035 /// llvm.experimental.vector.interleave2
3036 ///
3037 /// \p II is the interleave intrinsic.
3038 /// \p SI is the accompanying store instruction
3040 StoreInst *SI) const {
3041 return false;
3042 }
3043
3044 /// Return true if an fpext operation is free (for instance, because
3045 /// single-precision floating-point numbers are implicitly extended to
3046 /// double-precision).
3047 virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
3048 assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
3049 "invalid fpext types");
3050 return false;
3051 }
3052
3053 /// Return true if an fpext operation input to an \p Opcode operation is free
3054 /// (for instance, because half-precision floating-point numbers are
3055 /// implicitly extended to float-precision) for an FMA instruction.
3056 virtual bool isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
3057 LLT DestTy, LLT SrcTy) const {
3058 return false;
3059 }
3060
3061 /// Return true if an fpext operation input to an \p Opcode operation is free
3062 /// (for instance, because half-precision floating-point numbers are
3063 /// implicitly extended to float-precision) for an FMA instruction.
3064 virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
3065 EVT DestVT, EVT SrcVT) const {
3066 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
3067 "invalid fpext types");
3068 return isFPExtFree(DestVT, SrcVT);
3069 }
3070
3071 /// Return true if folding a vector load into ExtVal (a sign, zero, or any
3072 /// extend node) is profitable.
3073 virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
3074
3075 /// Return true if an fneg operation is free to the point where it is never
3076 /// worthwhile to replace it with a bitwise operation.
3077 virtual bool isFNegFree(EVT VT) const {
3078 assert(VT.isFloatingPoint());
3079 return false;
3080 }
3081
3082 /// Return true if an fabs operation is free to the point where it is never
3083 /// worthwhile to replace it with a bitwise operation.
3084 virtual bool isFAbsFree(EVT VT) const {
3085 assert(VT.isFloatingPoint());
3086 return false;
3087 }
3088
3089 /// Return true if an FMA operation is faster than a pair of fmul and fadd
3090 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
3091 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
3092 ///
3093 /// NOTE: This may be called before legalization on types for which FMAs are
3094 /// not legal, but should return true if those types will eventually legalize
3095 /// to types that support FMAs. After legalization, it will only be called on
3096 /// types that support FMAs (via Legal or Custom actions)
3098 EVT) const {
3099 return false;
3100 }
3101
3102 /// Return true if an FMA operation is faster than a pair of fmul and fadd
3103 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
3104 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
3105 ///
3106 /// NOTE: This may be called before legalization on types for which FMAs are
3107 /// not legal, but should return true if those types will eventually legalize
3108 /// to types that support FMAs. After legalization, it will only be called on
3109 /// types that support FMAs (via Legal or Custom actions)
3111 LLT) const {
3112 return false;
3113 }
3114
3115 /// IR version
3116 virtual bool isFMAFasterThanFMulAndFAdd(const Function &F, Type *) const {
3117 return false;
3118 }
3119
3120 /// Returns true if \p MI can be combined with another instruction to
3121 /// form TargetOpcode::G_FMAD. \p N may be an TargetOpcode::G_FADD,
3122 /// TargetOpcode::G_FSUB, or an TargetOpcode::G_FMUL which will be
3123 /// distributed into an fadd/fsub.
3124 virtual bool isFMADLegal(const MachineInstr &MI, LLT Ty) const {
3125 assert((MI.getOpcode() == TargetOpcode::G_FADD ||
3126 MI.getOpcode() == TargetOpcode::G_FSUB ||
3127 MI.getOpcode() == TargetOpcode::G_FMUL) &&
3128 "unexpected node in FMAD forming combine");
3129 switch (Ty.getScalarSizeInBits()) {
3130 case 16:
3131 return isOperationLegal(TargetOpcode::G_FMAD, MVT::f16);
3132 case 32:
3133 return isOperationLegal(TargetOpcode::G_FMAD, MVT::f32);
3134 case 64:
3135 return isOperationLegal(TargetOpcode::G_FMAD, MVT::f64);
3136 default:
3137 break;
3138 }
3139
3140 return false;
3141 }
3142
3143 /// Returns true if be combined with to form an ISD::FMAD. \p N may be an
3144 /// ISD::FADD, ISD::FSUB, or an ISD::FMUL which will be distributed into an
3145 /// fadd/fsub.
3146 virtual bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const {
3147 assert((N->getOpcode() == ISD::FADD || N->getOpcode() == ISD::FSUB ||
3148 N->getOpcode() == ISD::FMUL) &&
3149 "unexpected node in FMAD forming combine");
3150 return isOperationLegal(ISD::FMAD, N->getValueType(0));
3151 }
3152
3153 // Return true when the decision to generate FMA's (or FMS, FMLA etc) rather
3154 // than FMUL and ADD is delegated to the machine combiner.
3156 CodeGenOptLevel OptLevel) const {
3157 return false;
3158 }
3159
3160 /// Return true if it's profitable to narrow operations of type SrcVT to
3161 /// DestVT. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
3162 /// i32 to i16.
3163 virtual bool isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
3164 return false;
3165 }
3166
3167 /// Return true if pulling a binary operation into a select with an identity
3168 /// constant is profitable. This is the inverse of an IR transform.
3169 /// Example: X + (Cond ? Y : 0) --> Cond ? (X + Y) : X
3170 virtual bool shouldFoldSelectWithIdentityConstant(unsigned BinOpcode,
3171 EVT VT) const {
3172 return false;
3173 }
3174
3175 /// Return true if it is beneficial to convert a load of a constant to
3176 /// just the constant itself.
3177 /// On some targets it might be more efficient to use a combination of
3178 /// arithmetic instructions to materialize the constant instead of loading it
3179 /// from a constant pool.
3181 Type *Ty) const {
3182 return false;
3183 }
3184
3185 /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
3186 /// from this source type with this index. This is needed because
3187 /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
3188 /// the first element, and only the target knows which lowering is cheap.
3189 virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
3190 unsigned Index) const {
3191 return false;
3192 }
3193
3194 /// Try to convert an extract element of a vector binary operation into an
3195 /// extract element followed by a scalar operation.
3196 virtual bool shouldScalarizeBinop(SDValue VecOp) const {
3197 return false;
3198 }
3199
3200 /// Return true if extraction of a scalar element from the given vector type
3201 /// at the given index is cheap. For example, if scalar operations occur on
3202 /// the same register file as vector operations, then an extract element may
3203 /// be a sub-register rename rather than an actual instruction.
3204 virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
3205 return false;
3206 }
3207
3208 /// Try to convert math with an overflow comparison into the corresponding DAG
3209 /// node operation. Targets may want to override this independently of whether
3210 /// the operation is legal/custom for the given type because it may obscure
3211 /// matching of other patterns.
3212 virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT,
3213 bool MathUsed) const {
3214 // TODO: The default logic is inherited from code in CodeGenPrepare.
3215 // The opcode should not make a difference by default?
3216 if (Opcode != ISD::UADDO)
3217 return false;
3218
3219 // Allow the transform as long as we have an integer type that is not
3220 // obviously illegal and unsupported and if the math result is used
3221 // besides the overflow check. On some targets (e.g. SPARC), it is
3222 // not profitable to form on overflow op if the math result has no
3223 // concrete users.
3224 if (VT.isVector())
3225 return false;
3226 return MathUsed && (VT.isSimple() || !isOperationExpand(Opcode, VT));
3227 }
3228
3229 // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
3230 // even if the vector itself has multiple uses.
3231 virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
3232 return false;
3233 }
3234
3235 // Return true if CodeGenPrepare should consider splitting large offset of a
3236 // GEP to make the GEP fit into the addressing mode and can be sunk into the
3237 // same blocks of its users.
3238 virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
3239
3240 /// Return true if creating a shift of the type by the given
3241 /// amount is not profitable.
3242 virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const {
3243 return false;
3244 }
3245
3246 /// Does this target require the clearing of high-order bits in a register
3247 /// passed to the fp16 to fp conversion library function.
3248 virtual bool shouldKeepZExtForFP16Conv() const { return false; }
3249
3250 /// Should we generate fp_to_si_sat and fp_to_ui_sat from type FPVT to type VT
3251 /// from min(max(fptoi)) saturation patterns.
3252 virtual bool shouldConvertFpToSat(unsigned Op, EVT FPVT, EVT VT) const {
3253 return isOperationLegalOrCustom(Op, VT);
3254 }
3255
3256 /// Does this target support complex deinterleaving
3257 virtual bool isComplexDeinterleavingSupported() const { return false; }
3258
3259 /// Does this target support complex deinterleaving with the given operation
3260 /// and type
3263 return false;
3264 }
3265
3266 /// Create the IR node for the given complex deinterleaving operation.
3267 /// If one cannot be created using all the given inputs, nullptr should be
3268 /// returned.
3271 ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
3272 Value *Accumulator = nullptr) const {
3273 return nullptr;
3274 }
3275
3276 //===--------------------------------------------------------------------===//
3277 // Runtime Library hooks
3278 //
3279
3280 /// Rename the default libcall routine name for the specified libcall.
3281 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
3282 LibcallRoutineNames[Call] = Name;
3283 }
3285 for (auto Call : Calls)
3286 setLibcallName(Call, Name);
3287 }
3288
3289 /// Get the libcall routine name for the specified libcall.
3290 const char *getLibcallName(RTLIB::Libcall Call) const {
3291 return LibcallRoutineNames[Call];
3292 }
3293
3294 /// Override the default CondCode to be used to test the result of the
3295 /// comparison libcall against zero.
3297 CmpLibcallCCs[Call] = CC;
3298 }
3299
3300 /// Get the CondCode that's to be used to test the result of the comparison
3301 /// libcall against zero.
3303 return CmpLibcallCCs[Call];
3304 }
3305
3306 /// Set the CallingConv that should be used for the specified libcall.
3308 LibcallCallingConvs[Call] = CC;
3309 }
3310
3311 /// Get the CallingConv that should be used for the specified libcall.
3313 return LibcallCallingConvs[Call];
3314 }
3315
3316 /// Execute target specific actions to finalize target lowering.
3317 /// This is used to set extra flags in MachineFrameInformation and freezing
3318 /// the set of reserved registers.
3319 /// The default implementation just freezes the set of reserved registers.
3320 virtual void finalizeLowering(MachineFunction &MF) const;
3321
3322 //===----------------------------------------------------------------------===//
3323 // GlobalISel Hooks
3324 //===----------------------------------------------------------------------===//
3325 /// Check whether or not \p MI needs to be moved close to its uses.
3326 virtual bool shouldLocalize(const MachineInstr &MI, const TargetTransformInfo *TTI) const;
3327
3328
3329private:
3330 const TargetMachine &TM;
3331
3332 /// Tells the code generator that the target has multiple (allocatable)
3333 /// condition registers that can be used to store the results of comparisons
3334 /// for use by selects and conditional branches. With multiple condition
3335 /// registers, the code generator will not aggressively sink comparisons into
3336 /// the blocks of their users.
3337 bool HasMultipleConditionRegisters;
3338
3339 /// Tells the code generator that the target has BitExtract instructions.
3340 /// The code generator will aggressively sink "shift"s into the blocks of
3341 /// their users if the users will generate "and" instructions which can be
3342 /// combined with "shift" to BitExtract instructions.
3343 bool HasExtractBitsInsn;
3344
3345 /// Tells the code generator to bypass slow divide or remainder
3346 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
3347 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
3348 /// div/rem when the operands are positive and less than 256.
3349 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
3350
3351 /// Tells the code generator that it shouldn't generate extra flow control
3352 /// instructions and should attempt to combine flow control instructions via
3353 /// predication.
3354 bool JumpIsExpensive;
3355
3356 /// Information about the contents of the high-bits in boolean values held in
3357 /// a type wider than i1. See getBooleanContents.
3358 BooleanContent BooleanContents;
3359
3360 /// Information about the contents of the high-bits in boolean values held in
3361 /// a type wider than i1. See getBooleanContents.
3362 BooleanContent BooleanFloatContents;
3363
3364 /// Information about the contents of the high-bits in boolean vector values
3365 /// when the element type is wider than i1. See getBooleanContents.
3366 BooleanContent BooleanVectorContents;
3367
3368 /// The target scheduling preference: shortest possible total cycles or lowest
3369 /// register usage.
3370 Sched::Preference SchedPreferenceInfo;
3371
3372 /// The minimum alignment that any argument on the stack needs to have.
3373 Align MinStackArgumentAlignment;
3374
3375 /// The minimum function alignment (used when optimizing for size, and to
3376 /// prevent explicitly provided alignment from leading to incorrect code).
3377 Align MinFunctionAlignment;
3378
3379 /// The preferred function alignment (used when alignment unspecified and
3380 /// optimizing for speed).
3381 Align PrefFunctionAlignment;
3382
3383 /// The preferred loop alignment (in log2 bot in bytes).
3384 Align PrefLoopAlignment;
3385 /// The maximum amount of bytes permitted to be emitted for alignment.
3386 unsigned MaxBytesForAlignment;
3387
3388 /// Size in bits of the maximum atomics size the backend supports.
3389 /// Accesses larger than this will be expanded by AtomicExpandPass.
3390 unsigned MaxAtomicSizeInBitsSupported;
3391
3392 /// Size in bits of the maximum div/rem size the backend supports.
3393 /// Larger operations will be expanded by ExpandLargeDivRem.
3394 unsigned MaxDivRemBitWidthSupported;
3395
3396 /// Size in bits of the maximum larget fp convert size the backend
3397 /// supports. Larger operations will be expanded by ExpandLargeFPConvert.
3398 unsigned MaxLargeFPConvertBitWidthSupported;
3399
3400 /// Size in bits of the minimum cmpxchg or ll/sc operation the
3401 /// backend supports.
3402 unsigned MinCmpXchgSizeInBits;
3403
3404 /// This indicates if the target supports unaligned atomic operations.
3405 bool SupportsUnalignedAtomics;
3406
3407 /// If set to a physical register, this specifies the register that
3408 /// llvm.savestack/llvm.restorestack should save and restore.
3409 Register StackPointerRegisterToSaveRestore;
3410
3411 /// This indicates the default register class to use for each ValueType the
3412 /// target supports natively.
3413 const TargetRegisterClass *RegClassForVT[MVT::VALUETYPE_SIZE];
3414 uint16_t NumRegistersForVT[MVT::VALUETYPE_SIZE];
3415 MVT RegisterTypeForVT[MVT::VALUETYPE_SIZE];
3416
3417 /// This indicates the "representative" register class to use for each
3418 /// ValueType the target supports natively. This information is used by the
3419 /// scheduler to track register pressure. By default, the representative
3420 /// register class is the largest legal super-reg register class of the
3421 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
3422 /// representative class would be GR32.
3423 const TargetRegisterClass *RepRegClassForVT[MVT::VALUETYPE_SIZE] = {0};
3424
3425 /// This indicates the "cost" of the "representative" register class for each
3426 /// ValueType. The cost is used by the scheduler to approximate register
3427 /// pressure.
3428 uint8_t RepRegClassCostForVT[MVT::VALUETYPE_SIZE];
3429
3430 /// For any value types we are promoting or expanding, this contains the value
3431 /// type that we are changing to. For Expanded types, this contains one step
3432 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
3433 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
3434 /// the same type (e.g. i32 -> i32).
3435 MVT TransformToType[MVT::VALUETYPE_SIZE];
3436
3437 /// For each operation and each value type, keep a LegalizeAction that
3438 /// indicates how instruction selection should deal with the operation. Most
3439 /// operations are Legal (aka, supported natively by the target), but
3440 /// operations that are not should be described. Note that operations on
3441 /// non-legal value types are not described here.
3443
3444 /// For each load extension type and each value type, keep a LegalizeAction
3445 /// that indicates how instruction selection should deal with a load of a
3446 /// specific value type and extension type. Uses 4-bits to store the action
3447 /// for each of the 4 load ext types.
3449
3450 /// For each value type pair keep a LegalizeAction that indicates whether a
3451 /// truncating store of a specific value type and truncating type is legal.
3453
3454 /// For each indexed mode and each value type, keep a quad of LegalizeAction
3455 /// that indicates how instruction selection should deal with the load /
3456 /// store / maskedload / maskedstore.
3457 ///
3458 /// The first dimension is the value_type for the reference. The second
3459 /// dimension represents the various modes for load store.
3461
3462 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
3463 /// indicates how instruction selection should deal with the condition code.
3464 ///
3465 /// Because each CC action takes up 4 bits, we need to have the array size be
3466 /// large enough to fit all of the value types. This can be done by rounding
3467 /// up the MVT::VALUETYPE_SIZE value to the next multiple of 8.
3468 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::VALUETYPE_SIZE + 7) / 8];
3469
3470 ValueTypeActionImpl ValueTypeActions;
3471
3472private:
3473 /// Targets can specify ISD nodes that they would like PerformDAGCombine
3474 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
3475 /// array.
3476 unsigned char
3477 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
3478
3479 /// For operations that must be promoted to a specific type, this holds the
3480 /// destination type. This map should be sparse, so don't hold it as an
3481 /// array.
3482 ///
3483 /// Targets add entries to this map with AddPromotedToType(..), clients access
3484 /// this with getTypeToPromoteTo(..).
3485 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
3486 PromoteToType;
3487
3488 /// Stores the name each libcall.
3489 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
3490
3491 /// The ISD::CondCode that should be used to test the result of each of the
3492 /// comparison libcall against zero.
3493 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
3494
3495 /// Stores the CallingConv that should be used for each libcall.
3496 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
3497
3498 /// Set default libcall names and calling conventions.
3499 void InitLibcalls(const Triple &TT);
3500
3501 /// The bits of IndexedModeActions used to store the legalisation actions
3502 /// We store the data as | ML | MS | L | S | each taking 4 bits.
3503 enum IndexedModeActionsBits {
3504 IMAB_Store = 0,
3505 IMAB_Load = 4,
3506 IMAB_MaskedStore = 8,
3507 IMAB_MaskedLoad = 12
3508 };
3509
3510 void setIndexedModeAction(unsigned IdxMode, MVT VT, unsigned Shift,
3511 LegalizeAction Action) {
3512 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
3513 (unsigned)Action < 0xf && "Table isn't big enough!");
3514 unsigned Ty = (unsigned)VT.SimpleTy;
3515 IndexedModeActions[Ty][IdxMode] &= ~(0xf << Shift);
3516 IndexedModeActions[Ty][IdxMode] |= ((uint16_t)Action) << Shift;
3517 }
3518
3519 LegalizeAction getIndexedModeAction(unsigned IdxMode, MVT VT,
3520 unsigned Shift) const {
3521 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
3522 "Table isn't big enough!");
3523 unsigned Ty = (unsigned)VT.SimpleTy;
3524 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] >> Shift) & 0xf);
3525 }
3526
3527protected:
3528 /// Return true if the extension represented by \p I is free.
3529 /// \pre \p I is a sign, zero, or fp extension and
3530 /// is[Z|FP]ExtFree of the related types is not true.
3531 virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
3532
3533 /// Depth that GatherAllAliases should continue looking for chain
3534 /// dependencies when trying to find a more preferable chain. As an
3535 /// approximation, this should be more than the number of consecutive stores
3536 /// expected to be merged.
3538
3539 /// \brief Specify maximum number of store instructions per memset call.
3540 ///
3541 /// When lowering \@llvm.memset this field specifies the maximum number of
3542 /// store operations that may be substituted for the call to memset. Targets
3543 /// must set this value based on the cost threshold for that target. Targets
3544 /// should assume that the memset will be done using as many of the largest
3545 /// store operations first, followed by smaller ones, if necessary, per
3546 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
3547 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
3548 /// store. This only applies to setting a constant array of a constant size.
3550 /// Likewise for functions with the OptSize attribute.
3552
3553 /// \brief Specify maximum number of store instructions per memcpy call.
3554 ///
3555 /// When lowering \@llvm.memcpy this field specifies the maximum number of
3556 /// store operations that may be substituted for a call to memcpy. Targets
3557 /// must set this value based on the cost threshold for that target. Targets
3558 /// should assume that the memcpy will be done using as many of the largest
3559 /// store operations first, followed by smaller ones, if necessary, per
3560 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
3561 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
3562 /// and one 1-byte store. This only applies to copying a constant array of
3563 /// constant size.
3565 /// Likewise for functions with the OptSize attribute.
3567 /// \brief Specify max number of store instructions to glue in inlined memcpy.
3568 ///
3569 /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
3570 /// of store instructions to keep together. This helps in pairing and
3571 // vectorization later on.
3573
3574 /// \brief Specify maximum number of load instructions per memcmp call.
3575 ///
3576 /// When lowering \@llvm.memcmp this field specifies the maximum number of
3577 /// pairs of load operations that may be substituted for a call to memcmp.
3578 /// Targets must set this value based on the cost threshold for that target.
3579 /// Targets should assume that the memcmp will be done using as many of the
3580 /// largest load operations first, followed by smaller ones, if necessary, per
3581 /// alignment restrictions. For example, loading 7 bytes on a 32-bit machine
3582 /// with 32-bit alignment would result in one 4-byte load, a one 2-byte load
3583 /// and one 1-byte load. This only applies to copying a constant array of
3584 /// constant size.
3586 /// Likewise for functions with the OptSize attribute.
3588
3589 /// \brief Specify maximum number of store instructions per memmove call.
3590 ///
3591 /// When lowering \@llvm.memmove this field specifies the maximum number of
3592 /// store instructions that may be substituted for a call to memmove. Targets
3593 /// must set this value based on the cost threshold for that target. Targets
3594 /// should assume that the memmove will be done using as many of the largest
3595 /// store operations first, followed by smaller ones, if necessary, per
3596 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
3597 /// with 8-bit alignment would result in nine 1-byte stores. This only
3598 /// applies to copying a constant array of constant size.
3600 /// Likewise for functions with the OptSize attribute.
3602
3603 /// Tells the code generator that select is more expensive than a branch if
3604 /// the branch is usually predicted right.
3606
3607 /// \see enableExtLdPromotion.
3609
3610 /// Return true if the value types that can be represented by the specified
3611 /// register class are all legal.
3612 bool isLegalRC(const TargetRegisterInfo &TRI,
3613 const TargetRegisterClass &RC) const;
3614
3615 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
3616 /// sequence of memory operands that is recognized by PrologEpilogInserter.
3618 MachineBasicBlock *MBB) const;
3619
3621};
3622
3623/// This class defines information used to lower LLVM code to legal SelectionDAG
3624/// operators that the target instruction selector can accept natively.
3625///
3626/// This class also defines callbacks that targets must implement to lower
3627/// target-specific constructs to SelectionDAG operators.
3629public:
3630 struct DAGCombinerInfo;
3631 struct MakeLibCallOptions;
3632
3635
3636 explicit TargetLowering(const TargetMachine &TM);
3637
3638 bool isPositionIndependent() const;
3639
3642 UniformityInfo *UA) const {
3643 return false;
3644 }
3645
3646 // Lets target to control the following reassociation of operands: (op (op x,
3647 // c1), y) -> (op (op x, y), c1) where N0 is (op x, c1) and N1 is y. By
3648 // default consider profitable any case where N0 has single use. This
3649 // behavior reflects the condition replaced by this target hook call in the
3650 // DAGCombiner. Any particular target can implement its own heuristic to
3651 // restrict common combiner.
3653 SDValue N1) const {
3654 return N0.hasOneUse();
3655 }
3656
3657 // Lets target to control the following reassociation of operands: (op (op x,
3658 // c1), y) -> (op (op x, y), c1) where N0 is (op x, c1) and N1 is y. By
3659 // default consider profitable any case where N0 has single use. This
3660 // behavior reflects the condition replaced by this target hook call in the
3661 // combiner. Any particular target can implement its own heuristic to
3662 // restrict common combiner.
3664 Register N1) const {
3665 return MRI.hasOneNonDBGUse(N0);
3666 }
3667
3668 virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
3669 return false;
3670 }
3671
3672 /// Returns true by value, base pointer and offset pointer and addressing mode
3673 /// by reference if the node's address can be legally represented as
3674 /// pre-indexed load / store address.
3675 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
3676 SDValue &/*Offset*/,
3677 ISD::MemIndexedMode &/*AM*/,
3678 SelectionDAG &/*DAG*/) const {
3679 return false;
3680 }
3681
3682 /// Returns true by value, base pointer and offset pointer and addressing mode
3683 /// by reference if this node can be combined with a load / store to form a
3684 /// post-indexed load / store.
3685 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
3686 SDValue &/*Base*/,
3687 SDValue &/*Offset*/,
3688 ISD::MemIndexedMode &/*AM*/,
3689 SelectionDAG &/*DAG*/) const {
3690 return false;
3691 }
3692
3693 /// Returns true if the specified base+offset is a legal indexed addressing
3694 /// mode for this target. \p MI is the load or store instruction that is being
3695 /// considered for transformation.
3697 bool IsPre, MachineRegisterInfo &MRI) const {
3698 return false;
3699 }
3700
3701 /// Return the entry encoding for a jump table in the current function. The
3702 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
3703 virtual unsigned getJumpTableEncoding() const;
3704
3705 virtual const MCExpr *
3707 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
3708 MCContext &/*Ctx*/) const {
3709 llvm_unreachable("Need to implement this hook if target has custom JTIs");
3710 }
3711
3712 /// Returns relocation base for the given PIC jumptable.
3714 SelectionDAG &DAG) const;
3715
3716 /// This returns the relocation base for the given PIC jumptable, the same as
3717 /// getPICJumpTableRelocBase, but as an MCExpr.
3718 virtual const MCExpr *
3720 unsigned JTI, MCContext &Ctx) const;
3721
3722 /// Return true if folding a constant offset with the given GlobalAddress is
3723 /// legal. It is frequently not legal in PIC relocation models.
3724 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
3725
3726 /// On x86, return true if the operand with index OpNo is a CALL or JUMP
3727 /// instruction, which can use either a memory constraint or an address
3728 /// constraint. -fasm-blocks "__asm call foo" lowers to
3729 /// call void asm sideeffect inteldialect "call ${0:P}", "*m..."
3730 ///
3731 /// This function is used by a hack to choose the address constraint,
3732 /// lowering to a direct call.
3733 virtual bool
3735 unsigned OpNo) const {
3736 return false;
3737 }
3738
3740 SDValue &Chain) const;
3741
3742 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
3743 SDValue &NewRHS, ISD::CondCode &CCCode,
3744 const SDLoc &DL, const SDValue OldLHS,
3745 const SDValue OldRHS) const;
3746
3747 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
3748 SDValue &NewRHS, ISD::CondCode &CCCode,
3749 const SDLoc &DL, const SDValue OldLHS,
3750 const SDValue OldRHS, SDValue &Chain,
3751 bool IsSignaling = false) const;
3752
3753 /// Returns a pair of (return value, chain).
3754 /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
3755 std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
3756 EVT RetVT, ArrayRef<SDValue> Ops,
3757 MakeLibCallOptions CallOptions,
3758 const SDLoc &dl,
3759 SDValue Chain = SDValue()) const;
3760
3761 /// Check whether parameters to a call that are passed in callee saved
3762 /// registers are the same as from the calling function. This needs to be
3763 /// checked for tail call eligibility.
3765 const uint32_t *CallerPreservedMask,
3766 const SmallVectorImpl<CCValAssign> &ArgLocs,
3767 const SmallVectorImpl<SDValue> &OutVals) const;
3768
3769 //===--------------------------------------------------------------------===//
3770 // TargetLowering Optimization Methods
3771 //
3772
3773 /// A convenience struct that encapsulates a DAG, and two SDValues for
3774 /// returning information from TargetLowering to its clients that want to
3775 /// combine.
3782
3784 bool LT, bool LO) :
3785 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
3786
3787 bool LegalTypes() const { return LegalTys; }
3788 bool LegalOperations() const { return LegalOps; }
3789
3791 Old = O;
3792 New = N;
3793 return true;
3794 }
3795 };
3796
3797 /// Determines the optimal series of memory ops to replace the memset / memcpy.
3798 /// Return true if the number of memory ops is below the threshold (Limit).
3799 /// Note that this is always the case when Limit is ~0.
3800 /// It returns the types of the sequence of memory ops to perform
3801 /// memset / memcpy by reference.
3802 virtual bool
3803 findOptimalMemOpLowering(std::vector<EVT> &MemOps, unsigned Limit,
3804 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
3805 const AttributeList &FuncAttributes) const;
3806
3807 /// Check to see if the specified operand of the specified instruction is a
3808 /// constant integer. If so, check to see if there are any bits set in the
3809 /// constant that are not demanded. If so, shrink the constant and return
3810 /// true.
3812 const APInt &DemandedElts,
3813 TargetLoweringOpt &TLO) const;
3814
3815 /// Helper wrapper around ShrinkDemandedConstant, demanding all elements.
3817 TargetLoweringOpt &TLO) const;
3818
3819 // Target hook to do target-specific const optimization, which is called by
3820 // ShrinkDemandedConstant. This function should return true if the target
3821 // doesn't want ShrinkDemandedConstant to further optimize the constant.
3823 const APInt &DemandedBits,
3824 const APInt &DemandedElts,
3825 TargetLoweringOpt &TLO) const {
3826 return false;
3827 }
3828
3829 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
3830 /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
3831 /// generalized for targets with other types of implicit widening casts.
3832 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
3833 const APInt &DemandedBits,
3834 TargetLoweringOpt &TLO) const;
3835
3836 /// Look at Op. At this point, we know that only the DemandedBits bits of the
3837 /// result of Op are ever used downstream. If we can use this information to
3838 /// simplify Op, create a new simplified DAG node and return true, returning
3839 /// the original and new nodes in Old and New. Otherwise, analyze the
3840 /// expression and return a mask of KnownOne and KnownZero bits for the
3841 /// expression (used to simplify the caller). The KnownZero/One bits may only
3842 /// be accurate for those bits in the Demanded masks.
3843 /// \p AssumeSingleUse When this parameter is true, this function will
3844 /// attempt to simplify \p Op even if there are multiple uses.
3845 /// Callers are responsible for correctly updating the DAG based on the
3846 /// results of this function, because simply replacing TLO.Old
3847 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
3848 /// has multiple uses.
3850 const APInt &DemandedElts, KnownBits &Known,
3851 TargetLoweringOpt &TLO, unsigned Depth = 0,
3852 bool AssumeSingleUse = false) const;
3853
3854 /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
3855 /// Adds Op back to the worklist upon success.
3857 KnownBits &Known, TargetLoweringOpt &TLO,
3858 unsigned Depth = 0,
3859 bool AssumeSingleUse = false) const;
3860
3861 /// Helper wrapper around SimplifyDemandedBits.
3862 /// Adds Op back to the worklist upon success.
3864 DAGCombinerInfo &DCI) const;
3865
3866 /// Helper wrapper around SimplifyDemandedBits.
3867 /// Adds Op back to the worklist upon success.
3869 const APInt &DemandedElts,
3870 DAGCombinerInfo &DCI) const;
3871
3872 /// More limited version of SimplifyDemandedBits that can be used to "look
3873 /// through" ops that don't contribute to the DemandedBits/DemandedElts -
3874 /// bitwise ops etc.
3876 const APInt &DemandedElts,
3877 SelectionDAG &DAG,
3878 unsigned Depth = 0) const;
3879
3880 /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
3881 /// elements.
3883 SelectionDAG &DAG,
3884 unsigned Depth = 0) const;
3885
3886 /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
3887 /// bits from only some vector elements.
3889 const APInt &DemandedElts,
3890 SelectionDAG &DAG,
3891 unsigned Depth = 0) const;
3892
3893 /// Look at Vector Op. At this point, we know that only the DemandedElts
3894 /// elements of the result of Op are ever used downstream. If we can use
3895 /// this information to simplify Op, create a new simplified DAG node and
3896 /// return true, storing the original and new nodes in TLO.
3897 /// Otherwise, analyze the expression and return a mask of KnownUndef and
3898 /// KnownZero elements for the expression (used to simplify the caller).
3899 /// The KnownUndef/Zero elements may only be accurate for those bits
3900 /// in the DemandedMask.
3901 /// \p AssumeSingleUse When this parameter is true, this function will
3902 /// attempt to simplify \p Op even if there are multiple uses.
3903 /// Callers are responsible for correctly updating the DAG based on the
3904 /// results of this function, because simply replacing TLO.Old
3905 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
3906 /// has multiple uses.
3907 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
3908 APInt &KnownUndef, APInt &KnownZero,
3909 TargetLoweringOpt &TLO, unsigned Depth = 0,
3910 bool AssumeSingleUse = false) const;
3911
3912 /// Helper wrapper around SimplifyDemandedVectorElts.
3913 /// Adds Op back to the worklist upon success.
3914 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
3915 DAGCombinerInfo &DCI) const;
3916
3917 /// Return true if the target supports simplifying demanded vector elements by
3918 /// converting them to undefs.
3919 virtual bool
3921 const TargetLoweringOpt &TLO) const {
3922 return true;
3923 }
3924
3925 /// Determine which of the bits specified in Mask are known to be either zero
3926 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3927 /// argument allows us to only collect the known bits that are shared by the
3928 /// requested vector elements.
3929 virtual void computeKnownBitsForTargetNode(const SDValue Op,
3930 KnownBits &Known,
3931 const APInt &DemandedElts,
3932 const SelectionDAG &DAG,
3933 unsigned Depth = 0) const;
3934
3935 /// Determine which of the bits specified in Mask are known to be either zero
3936 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3937 /// argument allows us to only collect the known bits that are shared by the
3938 /// requested vector elements. This is for GISel.
3940 Register R, KnownBits &Known,
3941 const APInt &DemandedElts,
3942 const MachineRegisterInfo &MRI,
3943 unsigned Depth = 0) const;
3944
3945 /// Determine the known alignment for the pointer value \p R. This is can
3946 /// typically be inferred from the number of low known 0 bits. However, for a
3947 /// pointer with a non-integral address space, the alignment value may be
3948 /// independent from the known low bits.
3950 Register R,
3951 const MachineRegisterInfo &MRI,
3952 unsigned Depth = 0) const;
3953
3954 /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
3955 /// Default implementation computes low bits based on alignment
3956 /// information. This should preserve known bits passed into it.
3957 virtual void computeKnownBitsForFrameIndex(int FIOp,
3958 KnownBits &Known,
3959 const MachineFunction &MF) const;
3960
3961 /// This method can be implemented by targets that want to expose additional
3962 /// information about sign bits to the DAG Combiner. The DemandedElts
3963 /// argument allows us to only collect the minimum sign bits that are shared
3964 /// by the requested vector elements.
3966 const APInt &DemandedElts,
3967 const SelectionDAG &DAG,
3968 unsigned Depth = 0) const;
3969
3970 /// This method can be implemented by targets that want to expose additional
3971 /// information about sign bits to GlobalISel combiners. The DemandedElts
3972 /// argument allows us to only collect the minimum sign bits that are shared
3973 /// by the requested vector elements.
3975 Register R,
3976 const APInt &DemandedElts,
3977 const MachineRegisterInfo &MRI,
3978 unsigned Depth = 0) const;
3979
3980 /// Attempt to simplify any target nodes based on the demanded vector
3981 /// elements, returning true on success. Otherwise, analyze the expression and
3982 /// return a mask of KnownUndef and KnownZero elements for the expression
3983 /// (used to simplify the caller). The KnownUndef/Zero elements may only be
3984 /// accurate for those bits in the DemandedMask.
3986 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
3987 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
3988
3989 /// Attempt to simplify any target nodes based on the demanded bits/elts,
3990 /// returning true on success. Otherwise, analyze the
3991 /// expression and return a mask of KnownOne and KnownZero bits for the
3992 /// expression (used to simplify the caller). The KnownZero/One bits may only
3993 /// be accurate for those bits in the Demanded masks.
3995 const APInt &DemandedBits,
3996 const APInt &DemandedElts,
3997 KnownBits &Known,
3998 TargetLoweringOpt &TLO,
3999 unsigned Depth = 0) const;
4000
4001 /// More limited version of SimplifyDemandedBits that can be used to "look
4002 /// through" ops that don't contribute to the DemandedBits/DemandedElts -
4003 /// bitwise ops etc.
4005 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4006 SelectionDAG &DAG, unsigned Depth) const;
4007
4008 /// Return true if this function can prove that \p Op is never poison
4009 /// and, if \p PoisonOnly is false, does not have undef bits. The DemandedElts
4010 /// argument limits the check to the requested vector elements.
4012 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4013 bool PoisonOnly, unsigned Depth) const;
4014
4015 /// Return true if Op can create undef or poison from non-undef & non-poison
4016 /// operands. The DemandedElts argument limits the check to the requested
4017 /// vector elements.
4018 virtual bool
4020 const SelectionDAG &DAG, bool PoisonOnly,
4021 bool ConsiderFlags, unsigned Depth) const;
4022
4023 /// Tries to build a legal vector shuffle using the provided parameters
4024 /// or equivalent variations. The Mask argument maybe be modified as the
4025 /// function tries different variations.
4026 /// Returns an empty SDValue if the operation fails.
4029 SelectionDAG &DAG) const;
4030
4031 /// This method returns the constant pool value that will be loaded by LD.
4032 /// NOTE: You must check for implicit extensions of the constant by LD.
4033 virtual const Constant *getTargetConstantFromLoad(LoadSDNode *LD) const;
4034
4035 /// If \p SNaN is false, \returns true if \p Op is known to never be any
4036 /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
4037 /// NaN.
4039 const SelectionDAG &DAG,
4040 bool SNaN = false,
4041 unsigned Depth = 0) const;
4042
4043 /// Return true if vector \p Op has the same value across all \p DemandedElts,
4044 /// indicating any elements which may be undef in the output \p UndefElts.
4045 virtual bool isSplatValueForTargetNode(SDValue Op, const APInt &DemandedElts,
4046 APInt &UndefElts,
4047 const SelectionDAG &DAG,
4048 unsigned Depth = 0) const;
4049
4050 /// Returns true if the given Opc is considered a canonical constant for the
4051 /// target, which should not be transformed back into a BUILD_VECTOR.
4053 return Op.getOpcode() == ISD::SPLAT_VECTOR ||
4054 Op.getOpcode() == ISD::SPLAT_VECTOR_PARTS;
4055 }
4056
4058 void *DC; // The DAG Combiner object.
4061
4062 public:
4064
4065 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
4066 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
4067
4068 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
4069 bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
4070 bool isAfterLegalizeDAG() const { return Level >= AfterLegalizeDAG; }
4073
4074 void AddToWorklist(SDNode *N);
4075 SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
4076 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
4077 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
4078
4080
4082 };
4083
4084 /// Return if the N is a constant or constant vector equal to the true value
4085 /// from getBooleanContents().
4086 bool isConstTrueVal(SDValue N) const;
4087
4088 /// Return if the N is a constant or constant vector equal to the false value
4089 /// from getBooleanContents().
4090 bool isConstFalseVal(SDValue N) const;
4091
4092 /// Return if \p N is a True value when extended to \p VT.
4093 bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
4094
4095 /// Try to simplify a setcc built with the specified operands and cc. If it is
4096 /// unable to simplify it, return a null SDValue.
4098 bool foldBooleans, DAGCombinerInfo &DCI,
4099 const SDLoc &dl) const;
4100
4101 // For targets which wrap address, unwrap for analysis.
4102 virtual SDValue unwrapAddress(SDValue N) const { return N; }
4103
4104 /// Returns true (and the GlobalValue and the offset) if the node is a
4105 /// GlobalAddress + offset.
4106 virtual bool
4107 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
4108
4109 /// This method will be invoked for all target nodes and for any
4110 /// target-independent nodes that the target has registered with invoke it
4111 /// for.
4112 ///
4113 /// The semantics are as follows:
4114 /// Return Value:
4115 /// SDValue.Val == 0 - No change was made
4116 /// SDValue.Val == N - N was replaced, is dead, and is already handled.
4117 /// otherwise - N should be replaced by the returned Operand.
4118 ///
4119 /// In addition, methods provided by DAGCombinerInfo may be used to perform
4120 /// more complex transformations.
4121 ///
4122 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
4123
4124 /// Return true if it is profitable to move this shift by a constant amount
4125 /// through its operand, adjusting any immediate operands as necessary to
4126 /// preserve semantics. This transformation may not be desirable if it
4127 /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
4128 /// extraction in AArch64). By default, it returns true.
4129 ///
4130 /// @param N the shift node
4131 /// @param Level the current DAGCombine legalization level.
4133 CombineLevel Level) const {
4134 return true;
4135 }
4136
4137 /// GlobalISel - return true if it is profitable to move this shift by a
4138 /// constant amount through its operand, adjusting any immediate operands as
4139 /// necessary to preserve semantics. This transformation may not be desirable
4140 /// if it disrupts a particularly auspicious target-specific tree (e.g.
4141 /// bitfield extraction in AArch64). By default, it returns true.
4142 ///
4143 /// @param MI the shift instruction
4144 /// @param IsAfterLegal true if running after legalization.
4146 bool IsAfterLegal) const {
4147 return true;
4148 }
4149
4150 /// GlobalISel - return true if it's profitable to perform the combine:
4151 /// shl ([sza]ext x), y => zext (shl x, y)
4152 virtual bool isDesirableToPullExtFromShl(const MachineInstr &MI) const {
4153 return true;
4154 }
4155
4156 // Return AndOrSETCCFoldKind::{AddAnd, ABS} if its desirable to try and
4157 // optimize LogicOp(SETCC0, SETCC1). An example (what is implemented as of
4158 // writing this) is:
4159 // With C as a power of 2 and C != 0 and C != INT_MIN:
4160 // AddAnd:
4161 // (icmp eq A, C) | (icmp eq A, -C)
4162 // -> (icmp eq and(add(A, C), ~(C + C)), 0)
4163 // (icmp ne A, C) & (icmp ne A, -C)w
4164 // -> (icmp ne and(add(A, C), ~(C + C)), 0)
4165 // ABS:
4166 // (icmp eq A, C) | (icmp eq A, -C)
4167 // -> (icmp eq Abs(A), C)
4168 // (icmp ne A, C) & (icmp ne A, -C)w
4169 // -> (icmp ne Abs(A), C)
4170 //
4171 // @param LogicOp the logic op
4172 // @param SETCC0 the first of the SETCC nodes
4173 // @param SETCC0 the second of the SETCC nodes
4175 const SDNode *LogicOp, const SDNode *SETCC0, const SDNode *SETCC1) const {
4177 }
4178
4179 /// Return true if it is profitable to combine an XOR of a logical shift
4180 /// to create a logical shift of NOT. This transformation may not be desirable
4181 /// if it disrupts a particularly auspicious target-specific tree (e.g.
4182 /// BIC on ARM/AArch64). By default, it returns true.
4183 virtual bool isDesirableToCommuteXorWithShift(const SDNode *N) const {
4184 return true;
4185 }
4186
4187 /// Return true if the target has native support for the specified value type
4188 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
4189 /// i16 is legal, but undesirable since i16 instruction encodings are longer
4190 /// and some i16 instructions are slow.
4191 virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
4192 // By default, assume all legal types are desirable.
4193 return isTypeLegal(VT);
4194 }
4195
4196 /// Return true if it is profitable for dag combiner to transform a floating
4197 /// point op of specified opcode to a equivalent op of an integer
4198 /// type. e.g. f32 load -> i32 load can be profitable on ARM.
4199 virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
4200 EVT /*VT*/) const {
4201 return false;
4202 }
4203
4204 /// This method query the target whether it is beneficial for dag combiner to
4205 /// promote the specified node. If true, it should return the desired
4206 /// promotion type by reference.
4207 virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
4208 return false;
4209 }
4210
4211 /// Return true if the target supports swifterror attribute. It optimizes
4212 /// loads and stores to reading and writing a specific register.
4213 virtual bool supportSwiftError() const {
4214 return false;
4215 }
4216
4217 /// Return true if the target supports that a subset of CSRs for the given
4218 /// machine function is handled explicitly via copies.
4219 virtual bool supportSplitCSR(MachineFunction *MF) const {
4220 return false;
4221 }
4222
4223 /// Return true if the target supports kcfi operand bundles.
4224 virtual bool supportKCFIBundles() const { return false; }
4225
4226 /// Perform necessary initialization to handle a subset of CSRs explicitly
4227 /// via copies. This function is called at the beginning of instruction
4228 /// selection.
4229 virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
4230 llvm_unreachable("Not Implemented");
4231 }
4232
4233 /// Insert explicit copies in entry and exit blocks. We copy a subset of
4234 /// CSRs to virtual registers in the entry block, and copy them back to
4235 /// physical registers in the exit blocks. This function is called at the end
4236 /// of instruction selection.
4238 MachineBasicBlock *Entry,
4239 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
4240 llvm_unreachable("Not Implemented");
4241 }
4242
4243 /// Return the newly negated expression if the cost is not expensive and
4244 /// set the cost in \p Cost to indicate that if it is cheaper or neutral to
4245 /// do the negation.
4247 bool LegalOps, bool OptForSize,
4249 unsigned Depth = 0) const;
4250
4252 SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize,
4254 unsigned Depth = 0) const {
4256 SDValue Neg =
4257 getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
4258 if (!Neg)
4259 return SDValue();
4260
4261 if (Cost <= CostThreshold)
4262 return Neg;
4263
4264 // Remove the new created node to avoid the side effect to the DAG.
4265 if (Neg->use_empty())
4266 DAG.RemoveDeadNode(Neg.getNode());
4267 return SDValue();
4268 }
4269
4270 /// This is the helper function to return the newly negated expression only
4271 /// when the cost is cheaper.
4273 bool LegalOps, bool OptForSize,
4274 unsigned Depth = 0) const {
4275 return getCheaperOrNeutralNegatedExpression(Op, DAG, LegalOps, OptForSize,
4277 }
4278
4279 /// This is the helper function to return the newly negated expression if
4280 /// the cost is not expensive.
4282 bool OptForSize, unsigned Depth = 0) const {
4284 return getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
4285 }
4286
4287 //===--------------------------------------------------------------------===//
4288 // Lowering methods - These methods must be implemented by targets so that
4289 // the SelectionDAGBuilder code knows how to lower these.
4290 //
4291
4292 /// Target-specific splitting of values into parts that fit a register
4293 /// storing a legal type
4295 SelectionDAG & DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4296 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
4297 return false;
4298 }
4299
4300 /// Allows the target to handle physreg-carried dependency
4301 /// in target-specific way. Used from the ScheduleDAGSDNodes to decide whether
4302 /// to add the edge to the dependency graph.
4303 /// Def - input: Selection DAG node defininfg physical register
4304 /// User - input: Selection DAG node using physical register
4305 /// Op - input: Number of User operand
4306 /// PhysReg - inout: set to the physical register if the edge is
4307 /// necessary, unchanged otherwise
4308 /// Cost - inout: physical register copy cost.
4309 /// Returns 'true' is the edge is necessary, 'false' otherwise
4310 virtual bool checkForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
4311 const TargetRegisterInfo *TRI,
4312 const TargetInstrInfo *TII,
4313 unsigned &PhysReg, int &Cost) const {
4314 return false;
4315 }
4316
4317 /// Target-specific combining of register parts into its original value
4318 virtual SDValue
4320 const SDValue *Parts, unsigned NumParts,
4321 MVT PartVT, EVT ValueVT,
4322 std::optional<CallingConv::ID> CC) const {
4323 return SDValue();
4324 }
4325
4326 /// This hook must be implemented to lower the incoming (formal) arguments,
4327 /// described by the Ins array, into the specified DAG. The implementation
4328 /// should fill in the InVals array with legal-type argument values, and
4329 /// return the resulting token chain value.
4331 SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
4332 const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
4333 SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
4334 llvm_unreachable("Not Implemented");
4335 }
4336
4337 /// This structure contains all information that is necessary for lowering
4338 /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
4339 /// needs to lower a call, and targets will see this struct in their LowerCall
4340 /// implementation.
4343 Type *RetTy = nullptr;
4344 bool RetSExt : 1;
4345 bool RetZExt : 1;
4346 bool IsVarArg : 1;
4347 bool IsInReg : 1;
4353 bool NoMerge : 1;
4354
4355 // IsTailCall should be modified by implementations of
4356 // TargetLowering::LowerCall that perform tail call conversions.
4357 bool IsTailCall = false;
4358
4359 // Is Call lowering done post SelectionDAG type legalization.
4361
4362 unsigned NumFixedArgs = -1;
4368 const CallBase *CB = nullptr;
4373 const ConstantInt *CFIType = nullptr;
4374
4379 DAG(DAG) {}
4380
4382 DL = dl;
4383 return *this;
4384 }
4385