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