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"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/CodeGen/DAGCombine.h"
32#include "llvm/CodeGen/ISDOpcodes.h"
33#include "llvm/CodeGen/RuntimeLibcalls.h"
34#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SelectionDAGNodes.h"
36#include "llvm/CodeGen/TargetCallingConv.h"
37#include "llvm/CodeGen/ValueTypes.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/CallingConv.h"
40#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/DerivedTypes.h"
42#include "llvm/IR/Function.h"
43#include "llvm/IR/IRBuilder.h"
44#include "llvm/IR/InlineAsm.h"
45#include "llvm/IR/Instruction.h"
46#include "llvm/IR/Instructions.h"
47#include "llvm/IR/Type.h"
48#include "llvm/Support/Alignment.h"
49#include "llvm/Support/AtomicOrdering.h"
50#include "llvm/Support/Casting.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/InstructionCost.h"
53#include "llvm/Support/MachineValueType.h"
54#include <algorithm>
55#include <cassert>
56#include <climits>
57#include <cstdint>
58#include <iterator>
59#include <map>
60#include <string>
61#include <utility>
62#include <vector>
63
64namespace llvm {
65
66class BranchProbability;
67class CCState;
68class CCValAssign;
69class Constant;
70class FastISel;
71class FunctionLoweringInfo;
72class GlobalValue;
73class GISelKnownBits;
74class IntrinsicInst;
75struct KnownBits;
76class LegacyDivergenceAnalysis;
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
97 enum Preference {
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 };
105
106} // end namespace Sched
107
108// MemOp models a memory operation, either memset or memcpy/memmove.
109struct MemOp {
110private:
111 // Shared
112 uint64_t Size;
113 bool DstAlignCanChange; // true if destination alignment can satisfy any
114 // constraint.
115 Align DstAlign; // Specified alignment of the memory operation.
116
117 bool AllowOverlap;
118 // memset only
119 bool IsMemset; // If setthis memory operation is a memset.
120 bool ZeroMemset; // If set clears out memory with zeros.
121 // memcpy only
122 bool MemcpyStrSrc; // Indicates whether the memcpy source is an in-register
123 // constant so it does not need to be loaded.
124 Align SrcAlign; // Inferred alignment of the source or default value if the
125 // memory operation does not need to load the value.
126public:
127 static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
128 Align SrcAlign, bool IsVolatile,
129 bool MemcpyStrSrc = false) {
130 MemOp Op;
131 Op.Size = Size;
132 Op.DstAlignCanChange = DstAlignCanChange;
133 Op.DstAlign = DstAlign;
134 Op.AllowOverlap = !IsVolatile;
135 Op.IsMemset = false;
136 Op.ZeroMemset = false;
137 Op.MemcpyStrSrc = MemcpyStrSrc;
138 Op.SrcAlign = SrcAlign;
139 return Op;
140 }
141
142 static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
143 bool IsZeroMemset, bool IsVolatile) {
144 MemOp Op;
145 Op.Size = Size;
146 Op.DstAlignCanChange = DstAlignCanChange;
147 Op.DstAlign = DstAlign;
148 Op.AllowOverlap = !IsVolatile;
149 Op.IsMemset = true;
150 Op.ZeroMemset = IsZeroMemset;
151 Op.MemcpyStrSrc = false;
152 return Op;
153 }
154
155 uint64_t size() const { return Size; }
156 Align getDstAlign() const {
157 assert(!DstAlignCanChange);
158 return DstAlign;
159 }
160 bool isFixedDstAlign() const { return !DstAlignCanChange; }
161 bool allowOverlap() const { return AllowOverlap; }
162 bool isMemset() const { return IsMemset; }
163 bool isMemcpy() const { return !IsMemset; }
164 bool isMemcpyWithFixedDstAlign() const {
165 return isMemcpy() && !DstAlignCanChange;
166 }
167 bool isZeroMemset() const { return isMemset() && ZeroMemset; }
168 bool isMemcpyStrSrc() const {
169 assert(isMemcpy() && "Must be a memcpy");
170 return MemcpyStrSrc;
171 }
172 Align getSrcAlign() const {
173 assert(isMemcpy() && "Must be a memcpy");
174 return SrcAlign;
175 }
176 bool isSrcAligned(Align AlignCheck) const {
177 return isMemset() || llvm::isAligned(AlignCheck, SrcAlign.value());
178 }
179 bool isDstAligned(Align AlignCheck) const {
180 return DstAlignCanChange || llvm::isAligned(AlignCheck, DstAlign.value());
181 }
182 bool isAligned(Align AlignCheck) const {
183 return isSrcAligned(AlignCheck) && isDstAligned(AlignCheck);
184 }
185};
186
187/// This base class for TargetLowering contains the SelectionDAG-independent
188/// parts that can be used from the rest of CodeGen.
189class TargetLoweringBase {
190public:
191 /// This enum indicates whether operations are valid for a target, and if not,
192 /// what action should be used to make them valid.
193 enum LegalizeAction : uint8_t {
194 Legal, // The target natively supports this operation.
195 Promote, // This operation should be executed in a larger type.
196 Expand, // Try to expand this to other ops, otherwise use a libcall.
197 LibCall, // Don't try to expand this to other ops, always use a libcall.
198 Custom // Use the LowerOperation hook to implement custom lowering.
199 };
200
201 /// This enum indicates whether a types are legal for a target, and if not,
202 /// what action should be used to make them valid.
203 enum LegalizeTypeAction : uint8_t {
204 TypeLegal, // The target natively supports this type.
205 TypePromoteInteger, // Replace this integer with a larger one.
206 TypeExpandInteger, // Split this integer into two of half the size.
207 TypeSoftenFloat, // Convert this float to a same size integer type.
208 TypeExpandFloat, // Split this float into two of half the size.
209 TypeScalarizeVector, // Replace this one-element vector with its element.
210 TypeSplitVector, // Split this vector into two of half the size.
211 TypeWidenVector, // This vector should be widened into a larger vector.
212 TypePromoteFloat, // Replace this float with a larger one.
213 TypeSoftPromoteHalf, // Soften half to i16 and use float to do arithmetic.
214 TypeScalarizeScalableVector, // This action is explicitly left unimplemented.
215 // While it is theoretically possible to
216 // legalize operations on scalable types with a
217 // loop that handles the vscale * #lanes of the
218 // vector, this is non-trivial at SelectionDAG
219 // level and these types are better to be
220 // widened or promoted.
221 };
222
223 /// LegalizeKind holds the legalization kind that needs to happen to EVT
224 /// in order to type-legalize it.
225 using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
226
227 /// Enum that describes how the target represents true/false values.
228 enum BooleanContent {
229 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
230 ZeroOrOneBooleanContent, // All bits zero except for bit 0.
231 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
232 };
233
234 /// Enum that describes what type of support for selects the target has.
235 enum SelectSupportKind {
236 ScalarValSelect, // The target supports scalar selects (ex: cmov).
237 ScalarCondVectorVal, // The target supports selects with a scalar condition
238 // and vector values (ex: cmov).
239 VectorMaskSelect // The target supports vector selects with a vector
240 // mask (ex: x86 blends).
241 };
242
243 /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
244 /// to, if at all. Exists because different targets have different levels of
245 /// support for these atomic instructions, and also have different options
246 /// w.r.t. what they should expand to.
247 enum class AtomicExpansionKind {
248 None, // Don't expand the instruction.
249 LLSC, // Expand the instruction into loadlinked/storeconditional; used
250 // by ARM/AArch64.
251 LLOnly, // Expand the (load) instruction into just a load-linked, which has
252 // greater atomic guarantees than a normal load.
253 CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
254 MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
255 };
256
257 /// Enum that specifies when a multiplication should be expanded.
258 enum class MulExpansionKind {
259 Always, // Always expand the instruction.
260 OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
261 // or custom.
262 };
263
264 /// Enum that specifies when a float negation is beneficial.
265 enum class NegatibleCost {
266 Cheaper = 0, // Negated expression is cheaper.
267 Neutral = 1, // Negated expression has the same cost.
268 Expensive = 2 // Negated expression is more expensive.
269 };
270
271 class ArgListEntry {
272 public:
273 Value *Val = nullptr;
274 SDValue Node = SDValue();
275 Type *Ty = nullptr;
276 bool IsSExt : 1;
277 bool IsZExt : 1;
278 bool IsInReg : 1;
279 bool IsSRet : 1;
280 bool IsNest : 1;
281 bool IsByVal : 1;
282 bool IsByRef : 1;
283 bool IsInAlloca : 1;
284 bool IsPreallocated : 1;
285 bool IsReturned : 1;
286 bool IsSwiftSelf : 1;
287 bool IsSwiftError : 1;
288 bool IsCFGuardTarget : 1;
289 MaybeAlign Alignment = None;
290 Type *ByValType = nullptr;
291 Type *PreallocatedType = nullptr;
292
293 ArgListEntry()
294 : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
295 IsNest(false), IsByVal(false), IsByRef(false), IsInAlloca(false),
296 IsPreallocated(false), IsReturned(false), IsSwiftSelf(false),
297 IsSwiftError(false), IsCFGuardTarget(false) {}
298
299 void setAttributes(const CallBase *Call, unsigned ArgIdx);
300 };
301 using ArgListTy = std::vector<ArgListEntry>;
302
303 virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
304 ArgListTy &Args) const {};
305
306 static ISD::NodeType getExtendForContent(BooleanContent Content) {
307 switch (Content) {
308 case UndefinedBooleanContent:
309 // Extend by adding rubbish bits.
310 return ISD::ANY_EXTEND;
311 case ZeroOrOneBooleanContent:
312 // Extend by adding zero bits.
313 return ISD::ZERO_EXTEND;
314 case ZeroOrNegativeOneBooleanContent:
315 // Extend by copying the sign bit.
316 return ISD::SIGN_EXTEND;
317 }
318 llvm_unreachable("Invalid content kind");
319 }
320
321 explicit TargetLoweringBase(const TargetMachine &TM);
322 TargetLoweringBase(const TargetLoweringBase &) = delete;
323 TargetLoweringBase &operator=(const TargetLoweringBase &) = delete;
324 virtual ~TargetLoweringBase() = default;
325
326 /// Return true if the target support strict float operation
327 bool isStrictFPEnabled() const {
328 return IsStrictFPEnabled;
329 }
330
331protected:
332 /// Initialize all of the actions to default values.
333 void initActions();
334
335public:
336 const TargetMachine &getTargetMachine() const { return TM; }
337
338 virtual bool useSoftFloat() const { return false; }
339
340 /// Return the pointer type for the given address space, defaults to
341 /// the pointer type from the data layout.
342 /// FIXME: The default needs to be removed once all the code is updated.
343 virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
344 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
345 }
346
347 /// Return the in-memory pointer type for the given address space, defaults to
348 /// the pointer type from the data layout. FIXME: The default needs to be
349 /// removed once all the code is updated.
350 MVT getPointerMemTy(const DataLayout &DL, uint32_t AS = 0) const {
351 return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
352 }
353
354 /// Return the type for frame index, which is determined by
355 /// the alloca address space specified through the data layout.
356 MVT getFrameIndexTy(const DataLayout &DL) const {
357 return getPointerTy(DL, DL.getAllocaAddrSpace());
358 }
359
360 /// Return the type for code pointers, which is determined by the program
361 /// address space specified through the data layout.
362 MVT getProgramPointerTy(const DataLayout &DL) const {
363 return getPointerTy(DL, DL.getProgramAddressSpace());
364 }
365
366 /// Return the type for operands of fence.
367 /// TODO: Let fence operands be of i32 type and remove this.
368 virtual MVT getFenceOperandTy(const DataLayout &DL) const {
369 return getPointerTy(DL);
370 }
371
372 /// EVT is not used in-tree, but is used by out-of-tree target.
373 /// A documentation for this function would be nice...
374 virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
375
376 EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
377 bool LegalTypes = true) const;
378
379 /// Return the preferred type to use for a shift opcode, given the shifted
380 /// amount type is \p ShiftValueTy.
381 LLVM_READONLY
382 virtual LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const {
383 return ShiftValueTy;
384 }
385
386 /// Returns the type to be used for the index operand of:
387 /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
388 /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
389 virtual MVT getVectorIdxTy(const DataLayout &DL) const {
390 return getPointerTy(DL);
391 }
392
393 /// This callback is used to inspect load/store instructions and add
394 /// target-specific MachineMemOperand flags to them. The default
395 /// implementation does nothing.
396 virtual MachineMemOperand::Flags getTargetMMOFlags(const Instruction &I) const {
397 return MachineMemOperand::MONone;
398 }
399
400 MachineMemOperand::Flags getLoadMemOperandFlags(const LoadInst &LI,
401 const DataLayout &DL) const;
402 MachineMemOperand::Flags getStoreMemOperandFlags(const StoreInst &SI,
403 const DataLayout &DL) const;
404 MachineMemOperand::Flags getAtomicMemOperandFlags(const Instruction &AI,
405 const DataLayout &DL) const;
406
407 virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
408 return true;
409 }
410
411 /// Return true if it is profitable to convert a select of FP constants into
412 /// a constant pool load whose address depends on the select condition. The
413 /// parameter may be used to differentiate a select with FP compare from
414 /// integer compare.
415 virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
416 return true;
417 }
418
419 /// Return true if multiple condition registers are available.
420 bool hasMultipleConditionRegisters() const {
421 return HasMultipleConditionRegisters;
422 }
423
424 /// Return true if the target has BitExtract instructions.
425 bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
426
427 /// Return the preferred vector type legalization action.
428 virtual TargetLoweringBase::LegalizeTypeAction
429 getPreferredVectorAction(MVT VT) const {
430 // The default action for one element vectors is to scalarize
431 if (VT.getVectorElementCount().isScalar())
432 return TypeScalarizeVector;
433 // The default action for an odd-width vector is to widen.
434 if (!VT.isPow2VectorType())
435 return TypeWidenVector;
436 // The default action for other vectors is to promote
437 return TypePromoteInteger;
438 }
439
440 // Return true if the half type should be passed around as i16, but promoted
441 // to float around arithmetic. The default behavior is to pass around as
442 // float and convert around loads/stores/bitcasts and other places where
443 // the size matters.
444 virtual bool softPromoteHalfType() const { return false; }
445
446 // There are two general methods for expanding a BUILD_VECTOR node:
447 // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
448 // them together.
449 // 2. Build the vector on the stack and then load it.
450 // If this function returns true, then method (1) will be used, subject to
451 // the constraint that all of the necessary shuffles are legal (as determined
452 // by isShuffleMaskLegal). If this function returns false, then method (2) is
453 // always used. The vector type, and the number of defined values, are
454 // provided.
455 virtual bool
456 shouldExpandBuildVectorWithShuffles(EVT /* VT */,
457 unsigned DefinedValues) const {
458 return DefinedValues < 3;
459 }
460
461 /// Return true if integer divide is usually cheaper than a sequence of
462 /// several shifts, adds, and multiplies for this target.
463 /// The definition of "cheaper" may depend on whether we're optimizing
464 /// for speed or for size.
465 virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
466
467 /// Return true if the target can handle a standalone remainder operation.
468 virtual bool hasStandaloneRem(EVT VT) const {
469 return true;
470 }
471
472 /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
473 virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
474 // Default behavior is to replace SQRT(X) with X*RSQRT(X).
475 return false;
476 }
477
478 /// Reciprocal estimate status values used by the functions below.
479 enum ReciprocalEstimate : int {
480 Unspecified = -1,
481 Disabled = 0,
482 Enabled = 1
483 };
484
485 /// Return a ReciprocalEstimate enum value for a square root of the given type
486 /// based on the function's attributes. If the operation is not overridden by
487 /// the function's attributes, "Unspecified" is returned and target defaults
488 /// are expected to be used for instruction selection.
489 int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
490
491 /// Return a ReciprocalEstimate enum value for a division of the given type
492 /// based on the function's attributes. If the operation is not overridden by
493 /// the function's attributes, "Unspecified" is returned and target defaults
494 /// are expected to be used for instruction selection.
495 int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
496
497 /// Return the refinement step count for a square root of the given type based
498 /// on the function's attributes. If the operation is not overridden by
499 /// the function's attributes, "Unspecified" is returned and target defaults
500 /// are expected to be used for instruction selection.
501 int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
502
503 /// Return the refinement step count for a division of the given type based
504 /// on the function's attributes. If the operation is not overridden by
505 /// the function's attributes, "Unspecified" is returned and target defaults
506 /// are expected to be used for instruction selection.
507 int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
508
509 /// Returns true if target has indicated at least one type should be bypassed.
510 bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
511
512 /// Returns map of slow types for division or remainder with corresponding
513 /// fast types
514 const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
515 return BypassSlowDivWidths;
516 }
517
518 /// Return true if Flow Control is an expensive operation that should be
519 /// avoided.
520 bool isJumpExpensive() const { return JumpIsExpensive; }
521
522 /// Return true if selects are only cheaper than branches if the branch is
523 /// unlikely to be predicted right.
524 bool isPredictableSelectExpensive() const {
525 return PredictableSelectIsExpensive;
526 }
527
528 virtual bool fallBackToDAGISel(const Instruction &Inst) const {
529 return false;
530 }
531
532 /// Return true if the following transform is beneficial:
533 /// fold (conv (load x)) -> (load (conv*)x)
534 /// On architectures that don't natively support some vector loads
535 /// efficiently, casting the load to a smaller vector of larger types and
536 /// loading is more efficient, however, this can be undone by optimizations in
537 /// dag combiner.
538 virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
539 const SelectionDAG &DAG,
540 const MachineMemOperand &MMO) const {
541 // Don't do if we could do an indexed load on the original type, but not on
542 // the new one.
543 if (!LoadVT.isSimple() || !BitcastVT.isSimple())
544 return true;
545
546 MVT LoadMVT = LoadVT.getSimpleVT();
547
548 // Don't bother doing this if it's just going to be promoted again later, as
549 // doing so might interfere with other combines.
550 if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
551 getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
552 return false;
553
554 bool Fast = false;
555 return allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), BitcastVT,
556 MMO, &Fast) && Fast;
557 }
558
559 /// Return true if the following transform is beneficial:
560 /// (store (y (conv x)), y*)) -> (store x, (x*))
561 virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT,
562 const SelectionDAG &DAG,
563 const MachineMemOperand &MMO) const {
564 // Default to the same logic as loads.
565 return isLoadBitCastBeneficial(StoreVT, BitcastVT, DAG, MMO);
566 }
567
568 /// Return true if it is expected to be cheaper to do a store of a non-zero
569 /// vector constant with the given size and type for the address space than to
570 /// store the individual scalar element constants.
571 virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
572 unsigned NumElem,
573 unsigned AddrSpace) const {
574 return false;
575 }
576
577 /// Allow store merging for the specified type after legalization in addition
578 /// to before legalization. This may transform stores that do not exist
579 /// earlier (for example, stores created from intrinsics).
580 virtual bool mergeStoresAfterLegalization(EVT MemVT) const {
581 return true;
582 }
583
584 /// Returns if it's reasonable to merge stores to MemVT size.
585 virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
586 const SelectionDAG &DAG) const {
587 return true;
588 }
589
590 /// Return true if it is cheap to speculate a call to intrinsic cttz.
591 virtual bool isCheapToSpeculateCttz() const {
592 return false;
593 }
594
595 /// Return true if it is cheap to speculate a call to intrinsic ctlz.
596 virtual bool isCheapToSpeculateCtlz() const {
597 return false;
598 }
599
600 /// Return true if ctlz instruction is fast.
601 virtual bool isCtlzFast() const {
602 return false;
603 }
604
605 /// Return the maximum number of "x & (x - 1)" operations that can be done
606 /// instead of deferring to a custom CTPOP.
607 virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const {
608 return 1;
609 }
610
611 /// Return true if instruction generated for equality comparison is folded
612 /// with instruction generated for signed comparison.
613 virtual bool isEqualityCmpFoldedWithSignedCmp() const { return true; }
614
615 /// Return true if it is safe to transform an integer-domain bitwise operation
616 /// into the equivalent floating-point operation. This should be set to true
617 /// if the target has IEEE-754-compliant fabs/fneg operations for the input
618 /// type.
619 virtual bool hasBitPreservingFPLogic(EVT VT) const {
620 return false;
621 }
622
623 /// Return true if it is cheaper to split the store of a merged int val
624 /// from a pair of smaller values into multiple stores.
625 virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
626 return false;
627 }
628
629 /// Return if the target supports combining a
630 /// chain like:
631 /// \code
632 /// %andResult = and %val1, #mask
633 /// %icmpResult = icmp %andResult, 0
634 /// \endcode
635 /// into a single machine instruction of a form like:
636 /// \code
637 /// cc = test %register, #mask
638 /// \endcode
639 virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
640 return false;
641 }
642
643 /// Use bitwise logic to make pairs of compares more efficient. For example:
644 /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
645 /// This should be true when it takes more than one instruction to lower
646 /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
647 /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
648 virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
649 return false;
650 }
651
652 /// Return the preferred operand type if the target has a quick way to compare
653 /// integer values of the given size. Assume that any legal integer type can
654 /// be compared efficiently. Targets may override this to allow illegal wide
655 /// types to return a vector type if there is support to compare that type.
656 virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
657 MVT VT = MVT::getIntegerVT(NumBits);
658 return isTypeLegal(VT) ? VT : MVT::INVALID_SIMPLE_VALUE_TYPE;
659 }
660
661 /// Return true if the target should transform:
662 /// (X & Y) == Y ---> (~X & Y) == 0
663 /// (X & Y) != Y ---> (~X & Y) != 0
664 ///
665 /// This may be profitable if the target has a bitwise and-not operation that
666 /// sets comparison flags. A target may want to limit the transformation based
667 /// on the type of Y or if Y is a constant.
668 ///
669 /// Note that the transform will not occur if Y is known to be a power-of-2
670 /// because a mask and compare of a single bit can be handled by inverting the
671 /// predicate, for example:
672 /// (X & 8) == 8 ---> (X & 8) != 0
673 virtual bool hasAndNotCompare(SDValue Y) const {
674 return false;
675 }
676
677 /// Return true if the target has a bitwise and-not operation:
678 /// X = ~A & B
679 /// This can be used to simplify select or other instructions.
680 virtual bool hasAndNot(SDValue X) const {
681 // If the target has the more complex version of this operation, assume that
682 // it has this operation too.
683 return hasAndNotCompare(X);
684 }
685
686 /// Return true if the target has a bit-test instruction:
687 /// (X & (1 << Y)) ==/!= 0
688 /// This knowledge can be used to prevent breaking the pattern,
689 /// or creating it if it could be recognized.
690 virtual bool hasBitTest(SDValue X, SDValue Y) const { return false; }
691
692 /// There are two ways to clear extreme bits (either low or high):
693 /// Mask: x & (-1 << y) (the instcombine canonical form)
694 /// Shifts: x >> y << y
695 /// Return true if the variant with 2 variable shifts is preferred.
696 /// Return false if there is no preference.
697 virtual bool shouldFoldMaskToVariableShiftPair(SDValue X) const {
698 // By default, let's assume that no one prefers shifts.
699 return false;
700 }
701
702 /// Return true if it is profitable to fold a pair of shifts into a mask.
703 /// This is usually true on most targets. But some targets, like Thumb1,
704 /// have immediate shift instructions, but no immediate "and" instruction;
705 /// this makes the fold unprofitable.
706 virtual bool shouldFoldConstantShiftPairToMask(const SDNode *N,
707 CombineLevel Level) const {
708 return true;
709 }
710
711 /// Should we tranform the IR-optimal check for whether given truncation
712 /// down into KeptBits would be truncating or not:
713 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
714 /// Into it's more traditional form:
715 /// ((%x << C) a>> C) dstcond %x
716 /// Return true if we should transform.
717 /// Return false if there is no preference.
718 virtual bool shouldTransformSignedTruncationCheck(EVT XVT,
719 unsigned KeptBits) const {
720 // By default, let's assume that no one prefers shifts.
721 return false;
722 }
723
724 /// Given the pattern
725 /// (X & (C l>>/<< Y)) ==/!= 0
726 /// return true if it should be transformed into:
727 /// ((X <</l>> Y) & C) ==/!= 0
728 /// WARNING: if 'X' is a constant, the fold may deadlock!
729 /// FIXME: we could avoid passing XC, but we can't use isConstOrConstSplat()
730 /// here because it can end up being not linked in.
731 virtual bool shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
732 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
733 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
734 SelectionDAG &DAG) const {
735 if (hasBitTest(X, Y)) {
736 // One interesting pattern that we'd want to form is 'bit test':
737 // ((1 << Y) & C) ==/!= 0
738 // But we also need to be careful not to try to reverse that fold.
739
740 // Is this '1 << Y' ?
741 if (OldShiftOpcode == ISD::SHL && CC->isOne())
742 return false; // Keep the 'bit test' pattern.
743
744 // Will it be '1 << Y' after the transform ?
745 if (XC && NewShiftOpcode == ISD::SHL && XC->isOne())
746 return true; // Do form the 'bit test' pattern.
747 }
748
749 // If 'X' is a constant, and we transform, then we will immediately
750 // try to undo the fold, thus causing endless combine loop.
751 // So by default, let's assume everyone prefers the fold
752 // iff 'X' is not a constant.
753 return !XC;
754 }
755
756 /// These two forms are equivalent:
757 /// sub %y, (xor %x, -1)
758 /// add (add %x, 1), %y
759 /// The variant with two add's is IR-canonical.
760 /// Some targets may prefer one to the other.
761 virtual bool preferIncOfAddToSubOfNot(EVT VT) const {
762 // By default, let's assume that everyone prefers the form with two add's.
763 return true;
764 }
765
766 /// Return true if the target wants to use the optimization that
767 /// turns ext(promotableInst1(...(promotableInstN(load)))) into
768 /// promotedInst1(...(promotedInstN(ext(load)))).
769 bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
770
771 /// Return true if the target can combine store(extractelement VectorTy,
772 /// Idx).
773 /// \p Cost[out] gives the cost of that transformation when this is true.
774 virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
775 unsigned &Cost) const {
776 return false;
777 }
778
779 /// Return true if inserting a scalar into a variable element of an undef
780 /// vector is more efficiently handled by splatting the scalar instead.
781 virtual bool shouldSplatInsEltVarIndex(EVT) const {
782 return false;
783 }
784
785 /// Return true if target always benefits from combining into FMA for a
786 /// given value type. This must typically return false on targets where FMA
787 /// takes more cycles to execute than FADD.
788 virtual bool enableAggressiveFMAFusion(EVT VT) const {
789 return false;
790 }
791
792 /// Return the ValueType of the result of SETCC operations.
793 virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
794 EVT VT) const;
795
796 /// Return the ValueType for comparison libcalls. Comparions libcalls include
797 /// floating point comparion calls, and Ordered/Unordered check calls on
798 /// floating point numbers.
799 virtual
800 MVT::SimpleValueType getCmpLibcallReturnType() const;
801
802 /// For targets without i1 registers, this gives the nature of the high-bits
803 /// of boolean values held in types wider than i1.
804 ///
805 /// "Boolean values" are special true/false values produced by nodes like
806 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
807 /// Not to be confused with general values promoted from i1. Some cpus
808 /// distinguish between vectors of boolean and scalars; the isVec parameter
809 /// selects between the two kinds. For example on X86 a scalar boolean should
810 /// be zero extended from i1, while the elements of a vector of booleans
811 /// should be sign extended from i1.
812 ///
813 /// Some cpus also treat floating point types the same way as they treat
814 /// vectors instead of the way they treat scalars.
815 BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
816 if (isVec)
817 return BooleanVectorContents;
818 return isFloat ? BooleanFloatContents : BooleanContents;
819 }
820
821 BooleanContent getBooleanContents(EVT Type) const {
822 return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
823 }
824
825 /// Return target scheduling preference.
826 Sched::Preference getSchedulingPreference() const {
827 return SchedPreferenceInfo;
828 }
829
830 /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
831 /// for different nodes. This function returns the preference (or none) for
832 /// the given node.
833 virtual Sched::Preference getSchedulingPreference(SDNode *) const {
834 return Sched::None;
835 }
836
837 /// Return the register class that should be used for the specified value
838 /// type.
839 virtual const TargetRegisterClass *getRegClassFor(MVT VT, bool isDivergent = false) const {
840 (void)isDivergent;
841 const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
842 assert(RC && "This value type is not natively supported!");
843 return RC;
844 }
845
846 /// Allows target to decide about the register class of the
847 /// specific value that is live outside the defining block.
848 /// Returns true if the value needs uniform register class.
849 virtual bool requiresUniformRegister(MachineFunction &MF,
850 const Value *) const {
851 return false;
852 }
853
854 /// Return the 'representative' register class for the specified value
855 /// type.
856 ///
857 /// The 'representative' register class is the largest legal super-reg
858 /// register class for the register class of the value type. For example, on
859 /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
860 /// register class is GR64 on x86_64.
861 virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
862 const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
863 return RC;
864 }
865
866 /// Return the cost of the 'representative' register class for the specified
867 /// value type.
868 virtual uint8_t getRepRegClassCostFor(MVT VT) const {
869 return RepRegClassCostForVT[VT.SimpleTy];
870 }
871
872 /// Return true if SHIFT instructions should be expanded to SHIFT_PARTS
873 /// instructions, and false if a library call is preferred (e.g for code-size
874 /// reasons).
875 virtual bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
876 return true;
877 }
878
879 /// Return true if the target has native support for the specified value type.
880 /// This means that it has a register that directly holds it without
881 /// promotions or expansions.
882 bool isTypeLegal(EVT VT) const {
883 assert(!VT.isSimple() ||
884 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
885 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
886 }
887
888 class ValueTypeActionImpl {
889 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
890 /// that indicates how instruction selection should deal with the type.
891 LegalizeTypeAction ValueTypeActions[MVT::LAST_VALUETYPE];
892
893 public:
894 ValueTypeActionImpl() {
895 std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
896 TypeLegal);
897 }
898
899 LegalizeTypeAction getTypeAction(MVT VT) const {
900 return ValueTypeActions[VT.SimpleTy];
901 }
902
903 void setTypeAction(MVT VT, LegalizeTypeAction Action) {
904 ValueTypeActions[VT.SimpleTy] = Action;
905 }
906 };
907
908 const ValueTypeActionImpl &getValueTypeActions() const {
909 return ValueTypeActions;
910 }
911
912 /// Return how we should legalize values of this type, either it is already
913 /// legal (return 'Legal') or we need to promote it to a larger type (return
914 /// 'Promote'), or we need to expand it into multiple registers of smaller
915 /// integer type (return 'Expand'). 'Custom' is not an option.
916 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
917 return getTypeConversion(Context, VT).first;
918 }
919 LegalizeTypeAction getTypeAction(MVT VT) const {
920 return ValueTypeActions.getTypeAction(VT);
921 }
922
923 /// For types supported by the target, this is an identity function. For
924 /// types that must be promoted to larger types, this returns the larger type
925 /// to promote to. For integer types that are larger than the largest integer
926 /// register, this contains one step in the expansion to get to the smaller
927 /// register. For illegal floating point types, this returns the integer type
928 /// to transform to.
929 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
930 return getTypeConversion(Context, VT).second;
931 }
932
933 /// For types supported by the target, this is an identity function. For
934 /// types that must be expanded (i.e. integer types that are larger than the
935 /// largest integer register or illegal floating point types), this returns
936 /// the largest legal type it will be expanded to.
937 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
938 assert(!VT.isVector());
939 while (true) {
940 switch (getTypeAction(Context, VT)) {
941 case TypeLegal:
942 return VT;
943 case TypeExpandInteger:
944 VT = getTypeToTransformTo(Context, VT);
945 break;
946 default:
947 llvm_unreachable("Type is not legal nor is it to be expanded!");
948 }
949 }
950 }
951
952 /// Vector types are broken down into some number of legal first class types.
953 /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
954 /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
955 /// turns into 4 EVT::i32 values with both PPC and X86.
956 ///
957 /// This method returns the number of registers needed, and the VT for each
958 /// register. It also returns the VT and quantity of the intermediate values
959 /// before they are promoted/expanded.
960 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
961 EVT &IntermediateVT,
962 unsigned &NumIntermediates,
963 MVT &RegisterVT) const;
964
965 /// Certain targets such as MIPS require that some types such as vectors are
966 /// always broken down into scalars in some contexts. This occurs even if the
967 /// vector type is legal.
968 virtual unsigned getVectorTypeBreakdownForCallingConv(
969 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
970 unsigned &NumIntermediates, MVT &RegisterVT) const {
971 return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
972 RegisterVT);
973 }
974
975 struct IntrinsicInfo {
976 unsigned opc = 0; // target opcode
977 EVT memVT; // memory VT
978
979 // value representing memory location
980 PointerUnion<const Value *, const PseudoSourceValue *> ptrVal;
981
982 int offset = 0; // offset off of ptrVal
983 uint64_t size = 0; // the size of the memory location
984 // (taken from memVT if zero)
985 MaybeAlign align = Align(1); // alignment
986
987 MachineMemOperand::Flags flags = MachineMemOperand::MONone;
988 IntrinsicInfo() = default;
989 };
990
991 /// Given an intrinsic, checks if on the target the intrinsic will need to map
992 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
993 /// true and store the intrinsic information into the IntrinsicInfo that was
994 /// passed to the function.
995 virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
996 MachineFunction &,
997 unsigned /*Intrinsic*/) const {
998 return false;
999 }
1000
1001 /// Returns true if the target can instruction select the specified FP
1002 /// immediate natively. If false, the legalizer will materialize the FP
1003 /// immediate as a load from a constant pool.
1004 virtual bool isFPImmLegal(const APFloat & /*Imm*/, EVT /*VT*/,
1005 bool ForCodeSize = false) const {
1006 return false;
1007 }
1008
1009 /// Targets can use this to indicate that they only support *some*
1010 /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
1011 /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
1012 /// legal.
1013 virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
1014 return true;
1015 }
1016
1017 /// Returns true if the operation can trap for the value type.
1018 ///
1019 /// VT must be a legal type. By default, we optimistically assume most
1020 /// operations don't trap except for integer divide and remainder.
1021 virtual bool canOpTrap(unsigned Op, EVT VT) const;
1022
1023 /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
1024 /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
1025 /// constant pool entry.
1026 virtual bool isVectorClearMaskLegal(ArrayRef<int> /*Mask*/,
1027 EVT /*VT*/) const {
1028 return false;
1029 }
1030
1031 /// Return how this operation should be treated: either it is legal, needs to
1032 /// be promoted to a larger size, needs to be expanded to some other code
1033 /// sequence, or the target has a custom expander for it.
1034 LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
1035 if (VT.isExtended()) return Expand;
1036 // If a target-specific SDNode requires legalization, require the target
1037 // to provide custom legalization for it.
1038 if (Op >= array_lengthof(OpActions[0])) return Custom;
1039 return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
1040 }
1041
1042 /// Custom method defined by each target to indicate if an operation which
1043 /// may require a scale is supported natively by the target.
1044 /// If not, the operation is illegal.
1045 virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
1046 unsigned Scale) const {
1047 return false;
1048 }
1049
1050 /// Some fixed point operations may be natively supported by the target but
1051 /// only for specific scales. This method allows for checking
1052 /// if the width is supported by the target for a given operation that may
1053 /// depend on scale.
1054 LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT,
1055 unsigned Scale) const {
1056 auto Action = getOperationAction(Op, VT);
1057 if (Action != Legal)
1058 return Action;
1059
1060 // This operation is supported in this type but may only work on specific
1061 // scales.
1062 bool Supported;
1063 switch (Op) {
1064 default:
1065 llvm_unreachable("Unexpected fixed point operation.");
1066 case ISD::SMULFIX:
1067 case ISD::SMULFIXSAT:
1068 case ISD::UMULFIX:
1069 case ISD::UMULFIXSAT:
1070 case ISD::SDIVFIX:
1071 case ISD::SDIVFIXSAT:
1072 case ISD::UDIVFIX:
1073 case ISD::UDIVFIXSAT:
1074 Supported = isSupportedFixedPointOperation(Op, VT, Scale);
1075 break;
1076 }
1077
1078 return Supported ? Action : Expand;
1079 }
1080
1081 // If Op is a strict floating-point operation, return the result
1082 // of getOperationAction for the equivalent non-strict operation.
1083 LegalizeAction getStrictFPOperationAction(unsigned Op, EVT VT) const {
1084 unsigned EqOpc;
1085 switch (Op) {
1086 default: llvm_unreachable("Unexpected FP pseudo-opcode");
1087#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1088 case ISD::STRICT_##DAGN: EqOpc = ISD::DAGN; break;
1089#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
1090 case ISD::STRICT_##DAGN: EqOpc = ISD::SETCC; break;
1091#include "llvm/IR/ConstrainedOps.def"
1092 }
1093
1094 return getOperationAction(EqOpc, VT);
1095 }
1096
1097 /// Return true if the specified operation is legal on this target or can be
1098 /// made legal with custom lowering. This is used to help guide high-level
1099 /// lowering decisions. LegalOnly is an optional convenience for code paths
1100 /// traversed pre and post legalisation.
1101 bool isOperationLegalOrCustom(unsigned Op, EVT VT,
1102 bool LegalOnly = false) const {
1103 if (LegalOnly)
1104 return isOperationLegal(Op, VT);
1105
1106 return (VT == MVT::Other || isTypeLegal(VT)) &&
1107 (getOperationAction(Op, VT) == Legal ||
1108 getOperationAction(Op, VT) == Custom);
1109 }
1110
1111 /// Return true if the specified operation is legal on this target or can be
1112 /// made legal using promotion. This is used to help guide high-level lowering
1113 /// decisions. LegalOnly is an optional convenience for code paths traversed
1114 /// pre and post legalisation.
1115 bool isOperationLegalOrPromote(unsigned Op, EVT VT,
1116 bool LegalOnly = false) const {
1117 if (LegalOnly)
1118 return isOperationLegal(Op, VT);
1119
1120 return (VT == MVT::Other || isTypeLegal(VT)) &&
1121 (getOperationAction(Op, VT) == Legal ||
1122 getOperationAction(Op, VT) == Promote);
1123 }
1124
1125 /// Return true if the specified operation is legal on this target or can be
1126 /// made legal with custom lowering or using promotion. This is used to help
1127 /// guide high-level lowering decisions. LegalOnly is an optional convenience
1128 /// for code paths traversed pre and post legalisation.
1129 bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT,
1130 bool LegalOnly = false) const {
1131 if (LegalOnly)
1132 return isOperationLegal(Op, VT);
1133
1134 return (VT == MVT::Other || isTypeLegal(VT)) &&
1135 (getOperationAction(Op, VT) == Legal ||
1136 getOperationAction(Op, VT) == Custom ||
1137 getOperationAction(Op, VT) == Promote);
1138 }
1139
1140 /// Return true if the operation uses custom lowering, regardless of whether
1141 /// the type is legal or not.
1142 bool isOperationCustom(unsigned Op, EVT VT) const {
1143 return getOperationAction(Op, VT) == Custom;
1144 }
1145
1146 /// Return true if lowering to a jump table is allowed.
1147 virtual bool areJTsAllowed(const Function *Fn) const {
1148 if (Fn->getFnAttribute("no-jump-tables").getValueAsBool())
1149 return false;
1150
1151 return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1152 isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
1153 }
1154
1155 /// Check whether the range [Low,High] fits in a machine word.
1156 bool rangeFitsInWord(const APInt &Low, const APInt &High,
1157 const DataLayout &DL) const {
1158 // FIXME: Using the pointer type doesn't seem ideal.
1159 uint64_t BW = DL.getIndexSizeInBits(0u);
1160 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
1161 return Range <= BW;
1162 }
1163
1164 /// Return true if lowering to a jump table is suitable for a set of case
1165 /// clusters which may contain \p NumCases cases, \p Range range of values.
1166 virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
1167 uint64_t Range, ProfileSummaryInfo *PSI,
1168 BlockFrequencyInfo *BFI) const;
1169
1170 /// Return true if lowering to a bit test is suitable for a set of case
1171 /// clusters which contains \p NumDests unique destinations, \p Low and
1172 /// \p High as its lowest and highest case values, and expects \p NumCmps
1173 /// case value comparisons. Check if the number of destinations, comparison
1174 /// metric, and range are all suitable.
1175 bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
1176 const APInt &Low, const APInt &High,
1177 const DataLayout &DL) const {
1178 // FIXME: I don't think NumCmps is the correct metric: a single case and a
1179 // range of cases both require only one branch to lower. Just looking at the
1180 // number of clusters and destinations should be enough to decide whether to
1181 // build bit tests.
1182
1183 // To lower a range with bit tests, the range must fit the bitwidth of a
1184 // machine word.
1185 if (!rangeFitsInWord(Low, High, DL))
1186 return false;
1187
1188 // Decide whether it's profitable to lower this range with bit tests. Each
1189 // destination requires a bit test and branch, and there is an overall range
1190 // check branch. For a small number of clusters, separate comparisons might
1191 // be cheaper, and for many destinations, splitting the range might be
1192 // better.
1193 return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
1194 (NumDests == 3 && NumCmps >= 6);
1195 }
1196
1197 /// Return true if the specified operation is illegal on this target or
1198 /// unlikely to be made legal with custom lowering. This is used to help guide
1199 /// high-level lowering decisions.
1200 bool isOperationExpand(unsigned Op, EVT VT) const {
1201 return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
1202 }
1203
1204 /// Return true if the specified operation is legal on this target.
1205 bool isOperationLegal(unsigned Op, EVT VT) const {
1206 return (VT == MVT::Other || isTypeLegal(VT)) &&
1207 getOperationAction(Op, VT) == Legal;
1208 }
1209
1210 /// Return how this load with extension should be treated: either it is legal,
1211 /// needs to be promoted to a larger size, needs to be expanded to some other
1212 /// code sequence, or the target has a custom expander for it.
1213 LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
1214 EVT MemVT) const {
1215 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1216 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1217 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1218 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::LAST_VALUETYPE &&
1219 MemI < MVT::LAST_VALUETYPE && "Table isn't big enough!");
1220 unsigned Shift = 4 * ExtType;
1221 return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
1222 }
1223
1224 /// Return true if the specified load with extension is legal on this target.
1225 bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1226 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
1227 }
1228
1229 /// Return true if the specified load with extension is legal or custom
1230 /// on this target.
1231 bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
1232 return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
1233 getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
1234 }
1235
1236 /// Return how this store with truncation should be treated: either it is
1237 /// legal, needs to be promoted to a larger size, needs to be expanded to some
1238 /// other code sequence, or the target has a custom expander for it.
1239 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
1240 if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
1241 unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
1242 unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
1243 assert(ValI < MVT::LAST_VALUETYPE && MemI < MVT::LAST_VALUETYPE &&
1244 "Table isn't big enough!");
1245 return TruncStoreActions[ValI][MemI];
1246 }
1247
1248 /// Return true if the specified store with truncation is legal on this
1249 /// target.
1250 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
1251 return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
1252 }
1253
1254 /// Return true if the specified store with truncation has solution on this
1255 /// target.
1256 bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
1257 return isTypeLegal(ValVT) &&
1258 (getTruncStoreAction(ValVT, MemVT) == Legal ||
1259 getTruncStoreAction(ValVT, MemVT) == Custom);
1260 }
1261
1262 /// Return how the indexed load should be treated: either it is legal, needs
1263 /// to be promoted to a larger size, needs to be expanded to some other code
1264 /// sequence, or the target has a custom expander for it.
1265 LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
1266 return getIndexedModeAction(IdxMode, VT, IMAB_Load);
1267 }
1268
1269 /// Return true if the specified indexed load is legal on this target.
1270 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
1271 return VT.isSimple() &&
1272 (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1273 getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1274 }
1275
1276 /// Return how the indexed store should be treated: either it is legal, needs
1277 /// to be promoted to a larger size, needs to be expanded to some other code
1278 /// sequence, or the target has a custom expander for it.
1279 LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
1280 return getIndexedModeAction(IdxMode, VT, IMAB_Store);
1281 }
1282
1283 /// Return true if the specified indexed load is legal on this target.
1284 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
1285 return VT.isSimple() &&
1286 (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1287 getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1288 }
1289
1290 /// Return how the indexed load should be treated: either it is legal, needs
1291 /// to be promoted to a larger size, needs to be expanded to some other code
1292 /// sequence, or the target has a custom expander for it.
1293 LegalizeAction getIndexedMaskedLoadAction(unsigned IdxMode, MVT VT) const {
1294 return getIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad);
1295 }
1296
1297 /// Return true if the specified indexed load is legal on this target.
1298 bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const {
1299 return VT.isSimple() &&
1300 (getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
1301 getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
1302 }
1303
1304 /// Return how the indexed store should be treated: either it is legal, needs
1305 /// to be promoted to a larger size, needs to be expanded to some other code
1306 /// sequence, or the target has a custom expander for it.
1307 LegalizeAction getIndexedMaskedStoreAction(unsigned IdxMode, MVT VT) const {
1308 return getIndexedModeAction(IdxMode, VT, IMAB_MaskedStore);
1309 }
1310
1311 /// Return true if the specified indexed load is legal on this target.
1312 bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const {
1313 return VT.isSimple() &&
1314 (getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
1315 getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
1316 }
1317
1318 /// Returns true if the index type for a masked gather/scatter requires
1319 /// extending
1320 virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const { return false; }
1321
1322 // Returns true if VT is a legal index type for masked gathers/scatters
1323 // on this target
1324 virtual bool shouldRemoveExtendFromGSIndex(EVT VT) const { return false; }
1325
1326 /// Return how the condition code should be treated: either it is legal, needs
1327 /// to be expanded to some other code sequence, or the target has a custom
1328 /// expander for it.
1329 LegalizeAction
1330 getCondCodeAction(ISD::CondCode CC, MVT VT) const {
1331 assert((unsigned)CC < array_lengthof(CondCodeActions) &&
1332 ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&
1333 "Table isn't big enough!");
1334 // See setCondCodeAction for how this is encoded.
1335 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
1336 uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
1337 LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
1338 assert(Action != Promote && "Can't promote condition code!");
1339 return Action;
1340 }
1341
1342 /// Return true if the specified condition code is legal on this target.
1343 bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
1344 return getCondCodeAction(CC, VT) == Legal;
1345 }
1346
1347 /// Return true if the specified condition code is legal or custom on this
1348 /// target.
1349 bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const {
1350 return getCondCodeAction(CC, VT) == Legal ||
1351 getCondCodeAction(CC, VT) == Custom;
1352 }
1353
1354 /// If the action for this operation is to promote, this method returns the
1355 /// ValueType to promote to.
1356 MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
1357 assert(getOperationAction(Op, VT) == Promote &&
1358 "This operation isn't promoted!");
1359
1360 // See if this has an explicit type specified.
1361 std::map<std::pair<unsigned, MVT::SimpleValueType>,
1362 MVT::SimpleValueType>::const_iterator PTTI =
1363 PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
1364 if (PTTI != PromoteToType.end()) return PTTI->second;
1365
1366 assert((VT.isInteger() || VT.isFloatingPoint()) &&
1367 "Cannot autopromote this type, add it with AddPromotedToType.");
1368
1369 MVT NVT = VT;
1370 do {
1371 NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
1372 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
1373 "Didn't find type to promote to!");
1374 } while (!isTypeLegal(NVT) ||
1375 getOperationAction(Op, NVT) == Promote);
1376 return NVT;
1377 }
1378
1379 /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
1380 /// operations except for the pointer size. If AllowUnknown is true, this
1381 /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
1382 /// otherwise it will assert.
1383 EVT getValueType(const DataLayout &DL, Type *Ty,
1384 bool AllowUnknown = false) const {
1385 // Lower scalar pointers to native pointer types.
1386 if (auto *PTy = dyn_cast<PointerType>(Ty))
1387 return getPointerTy(DL, PTy->getAddressSpace());
1388
1389 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1390 Type *EltTy = VTy->getElementType();
1391 // Lower vectors of pointers to native pointer types.
1392 if (auto *PTy = dyn_cast<PointerType>(EltTy)) {
1393 EVT PointerTy(getPointerTy(DL, PTy->getAddressSpace()));
1394 EltTy = PointerTy.getTypeForEVT(Ty->getContext());
1395 }
1396 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(EltTy, false),
1397 VTy->getElementCount());
1398 }
1399
1400 return EVT::getEVT(Ty, AllowUnknown);
1401 }
1402
1403 EVT getMemValueType(const DataLayout &DL, Type *Ty,
1404 bool AllowUnknown = false) const {
1405 // Lower scalar pointers to native pointer types.
1406 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1407 return getPointerMemTy(DL, PTy->getAddressSpace());
1408 else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1409 Type *Elm = VTy->getElementType();
1410 if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
1411 EVT PointerTy(getPointerMemTy(DL, PT->getAddressSpace()));
1412 Elm = PointerTy.getTypeForEVT(Ty->getContext());
1413 }
1414 return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
1415 VTy->getElementCount());
1416 }
1417
1418 return getValueType(DL, Ty, AllowUnknown);
1419 }
1420
1421
1422 /// Return the MVT corresponding to this LLVM type. See getValueType.
1423 MVT getSimpleValueType(const DataLayout &DL, Type *Ty,
1424 bool AllowUnknown = false) const {
1425 return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
1426 }
1427
1428 /// Return the desired alignment for ByVal or InAlloca aggregate function
1429 /// arguments in the caller parameter area. This is the actual alignment, not
1430 /// its logarithm.
1431 virtual unsigned getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
1432
1433 /// Return the type of registers that this ValueType will eventually require.
1434 MVT getRegisterType(MVT VT) const {
1435 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
1436 return RegisterTypeForVT[VT.SimpleTy];
1437 }
1438
1439 /// Return the type of registers that this ValueType will eventually require.
1440 MVT getRegisterType(LLVMContext &Context, EVT VT) const {
1441 if (VT.isSimple()) {
1442 assert((unsigned)VT.getSimpleVT().SimpleTy <
1443 array_lengthof(RegisterTypeForVT));
1444 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
1445 }
1446 if (VT.isVector()) {
1447 EVT VT1;
1448 MVT RegisterVT;
1449 unsigned NumIntermediates;
1450 (void)getVectorTypeBreakdown(Context, VT, VT1,
1451 NumIntermediates, RegisterVT);
1452 return RegisterVT;
1453 }
1454 if (VT.isInteger()) {
1455 return getRegisterType(Context, getTypeToTransformTo(Context, VT));
1456 }
1457 llvm_unreachable("Unsupported extended type!");
1458 }
1459
1460 /// Return the number of registers that this ValueType will eventually
1461 /// require.
1462 ///
1463 /// This is one for any types promoted to live in larger registers, but may be
1464 /// more than one for types (like i64) that are split into pieces. For types
1465 /// like i140, which are first promoted then expanded, it is the number of
1466 /// registers needed to hold all the bits of the original type. For an i140
1467 /// on a 32 bit machine this means 5 registers.
1468 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const {
1469 if (VT.isSimple()) {
1470 assert((unsigned)VT.getSimpleVT().SimpleTy <
1471 array_lengthof(NumRegistersForVT));
1472 return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
1473 }
1474 if (VT.isVector()) {
1475 EVT VT1;
1476 MVT VT2;
1477 unsigned NumIntermediates;
1478 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
1479 }
1480 if (VT.isInteger()) {
1481 unsigned BitWidth = VT.getSizeInBits();
1482 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
1483 return (BitWidth + RegWidth - 1) / RegWidth;
1484 }
1485 llvm_unreachable("Unsupported extended type!");
1486 }
1487
1488 /// Certain combinations of ABIs, Targets and features require that types
1489 /// are legal for some operations and not for other operations.
1490 /// For MIPS all vector types must be passed through the integer register set.
1491 virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context,
1492 CallingConv::ID CC, EVT VT) const {
1493 return getRegisterType(Context, VT);
1494 }
1495
1496 /// Certain targets require unusual breakdowns of certain types. For MIPS,
1497 /// this occurs when a vector type is used, as vector are passed through the
1498 /// integer register set.
1499 virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context,
1500 CallingConv::ID CC,
1501 EVT VT) const {
1502 return getNumRegisters(Context, VT);
1503 }
1504
1505 /// Certain targets have context senstive alignment requirements, where one
1506 /// type has the alignment requirement of another type.
1507 virtual Align getABIAlignmentForCallingConv(Type *ArgTy,
1508 DataLayout DL) const {
1509 return DL.getABITypeAlign(ArgTy);
1510 }
1511
1512 /// If true, then instruction selection should seek to shrink the FP constant
1513 /// of the specified type to a smaller type in order to save space and / or
1514 /// reduce runtime.
1515 virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
1516
1517 /// Return true if it is profitable to reduce a load to a smaller type.
1518 /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
1519 virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy,
1520 EVT NewVT) const {
1521 // By default, assume that it is cheaper to extract a subvector from a wide
1522 // vector load rather than creating multiple narrow vector loads.
1523 if (NewVT.isVector() && !Load->hasOneUse())
1524 return false;
1525
1526 return true;
1527 }
1528
1529 /// When splitting a value of the specified type into parts, does the Lo
1530 /// or Hi part come first? This usually follows the endianness, except
1531 /// for ppcf128, where the Hi part always comes first.
1532 bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
1533 return DL.isBigEndian() || VT == MVT::ppcf128;
1534 }
1535
1536 /// If true, the target has custom DAG combine transformations that it can
1537 /// perform for the specified node.
1538 bool hasTargetDAGCombine(ISD::NodeType NT) const {
1539 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
1540 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
1541 }
1542
1543 unsigned getGatherAllAliasesMaxDepth() const {
1544 return GatherAllAliasesMaxDepth;
1545 }
1546
1547 /// Returns the size of the platform's va_list object.
1548 virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
1549 return getPointerTy(DL).getSizeInBits();
1550 }
1551
1552 /// Get maximum # of store operations permitted for llvm.memset
1553 ///
1554 /// This function returns the maximum number of store operations permitted
1555 /// to replace a call to llvm.memset. The value is set by the target at the
1556 /// performance threshold for such a replacement. If OptSize is true,
1557 /// return the limit for functions that have OptSize attribute.
1558 unsigned getMaxStoresPerMemset(bool OptSize) const {
1559 return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
1560 }
1561
1562 /// Get maximum # of store operations permitted for llvm.memcpy
1563 ///
1564 /// This function returns the maximum number of store operations permitted
1565 /// to replace a call to llvm.memcpy. The value is set by the target at the
1566 /// performance threshold for such a replacement. If OptSize is true,
1567 /// return the limit for functions that have OptSize attribute.
1568 unsigned getMaxStoresPerMemcpy(bool OptSize) const {
1569 return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
1570 }
1571
1572 /// \brief Get maximum # of store operations to be glued together
1573 ///
1574 /// This function returns the maximum number of store operations permitted
1575 /// to glue together during lowering of llvm.memcpy. The value is set by
1576 // the target at the performance threshold for such a replacement.
1577 virtual unsigned getMaxGluedStoresPerMemcpy() const {
1578 return MaxGluedStoresPerMemcpy;
1579 }
1580
1581 /// Get maximum # of load operations permitted for memcmp
1582 ///
1583 /// This function returns the maximum number of load operations permitted
1584 /// to replace a call to memcmp. The value is set by the target at the
1585 /// performance threshold for such a replacement. If OptSize is true,
1586 /// return the limit for functions that have OptSize attribute.
1587 unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
1588 return OptSize ? MaxLoadsPerMemcmpOptSize : MaxLoadsPerMemcmp;
1589 }
1590
1591 /// Get maximum # of store operations permitted for llvm.memmove
1592 ///
1593 /// This function returns the maximum number of store operations permitted
1594 /// to replace a call to llvm.memmove. The value is set by the target at the
1595 /// performance threshold for such a replacement. If OptSize is true,
1596 /// return the limit for functions that have OptSize attribute.
1597 unsigned getMaxStoresPerMemmove(bool OptSize) const {
1598 return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
1599 }
1600
1601 /// Determine if the target supports unaligned memory accesses.
1602 ///
1603 /// This function returns true if the target allows unaligned memory accesses
1604 /// of the specified type in the given address space. If true, it also returns
1605 /// whether the unaligned memory access is "fast" in the last argument by
1606 /// reference. This is used, for example, in situations where an array
1607 /// copy/move/set is converted to a sequence of store operations. Its use
1608 /// helps to ensure that such replacements don't generate code that causes an
1609 /// alignment error (trap) on the target machine.
1610 virtual bool allowsMisalignedMemoryAccesses(
1611 EVT, unsigned AddrSpace = 0, Align Alignment = Align(1),
1612 MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
1613 bool * /*Fast*/ = nullptr) const {
1614 return false;
1615 }
1616
1617 /// LLT handling variant.
1618 virtual bool allowsMisalignedMemoryAccesses(
1619 LLT, unsigned AddrSpace = 0, Align Alignment = Align(1),
1620 MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
1621 bool * /*Fast*/ = nullptr) const {
1622 return false;
1623 }
1624
1625 /// This function returns true if the memory access is aligned or if the
1626 /// target allows this specific unaligned memory access. If the access is
1627 /// allowed, the optional final parameter returns if the access is also fast
1628 /// (as defined by the target).
1629 bool allowsMemoryAccessForAlignment(
1630 LLVMContext &Context, const DataLayout &DL, EVT VT,
1631 unsigned AddrSpace = 0, Align Alignment = Align(1),
1632 MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
1633 bool *Fast = nullptr) const;
1634
1635 /// Return true if the memory access of this type is aligned or if the target
1636 /// allows this specific unaligned access for the given MachineMemOperand.
1637 /// If the access is allowed, the optional final parameter returns if the
1638 /// access is also fast (as defined by the target).
1639 bool allowsMemoryAccessForAlignment(LLVMContext &Context,
1640 const DataLayout &DL, EVT VT,
1641 const MachineMemOperand &MMO,
1642 bool *Fast = nullptr) const;
1643
1644 /// Return true if the target supports a memory access of this type for the
1645 /// given address space and alignment. If the access is allowed, the optional
1646 /// final parameter returns if the access is also fast (as defined by the
1647 /// target).
1648 virtual bool
1649 allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1650 unsigned AddrSpace = 0, Align Alignment = Align(1),
1651 MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
1652 bool *Fast = nullptr) const;
1653
1654 /// Return true if the target supports a memory access of this type for the
1655 /// given MachineMemOperand. If the access is allowed, the optional
1656 /// final parameter returns if the access is also fast (as defined by the
1657 /// target).
1658 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
1659 const MachineMemOperand &MMO,
1660 bool *Fast = nullptr) const;
1661
1662 /// LLT handling variant.
1663 bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, LLT Ty,
1664 const MachineMemOperand &MMO,
1665 bool *Fast = nullptr) const;
1666
1667 /// Returns the target specific optimal type for load and store operations as
1668 /// a result of memset, memcpy, and memmove lowering.
1669 /// It returns EVT::Other if the type should be determined using generic
1670 /// target-independent logic.
1671 virtual EVT
1672 getOptimalMemOpType(const MemOp &Op,
1673 const AttributeList & /*FuncAttributes*/) const {
1674 return MVT::Other;
1675 }
1676
1677 /// LLT returning variant.
1678 virtual LLT
1679 getOptimalMemOpLLT(const MemOp &Op,
1680 const AttributeList & /*FuncAttributes*/) const {
1681 return LLT();
1682 }
1683
1684 /// Returns true if it's safe to use load / store of the specified type to
1685 /// expand memcpy / memset inline.
1686 ///
1687 /// This is mostly true for all types except for some special cases. For
1688 /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
1689 /// fstpl which also does type conversion. Note the specified type doesn't
1690 /// have to be legal as the hook is used before type legalization.
1691 virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
1692
1693 /// Return lower limit for number of blocks in a jump table.
1694 virtual unsigned getMinimumJumpTableEntries() const;
1695
1696 /// Return lower limit of the density in a jump table.
1697 unsigned getMinimumJumpTableDensity(bool OptForSize) const;
1698
1699 /// Return upper limit for number of entries in a jump table.
1700 /// Zero if no limit.
1701 unsigned getMaximumJumpTableSize() const;
1702
1703 virtual bool isJumpTableRelative() const;
1704
1705 /// If a physical register, this specifies the register that
1706 /// llvm.savestack/llvm.restorestack should save and restore.
1707 Register getStackPointerRegisterToSaveRestore() const {
1708 return StackPointerRegisterToSaveRestore;
1709 }
1710
1711 /// If a physical register, this returns the register that receives the
1712 /// exception address on entry to an EH pad.
1713 virtual Register
1714 getExceptionPointerRegister(const Constant *PersonalityFn) const {
1715 return Register();
1716 }
1717
1718 /// If a physical register, this returns the register that receives the
1719 /// exception typeid on entry to a landing pad.
1720 virtual Register
1721 getExceptionSelectorRegister(const Constant *PersonalityFn) const {
1722 return Register();
1723 }
1724
1725 virtual bool needsFixedCatchObjects() const {
1726 report_fatal_error("Funclet EH is not implemented for this target");
1727 }
1728
1729 /// Return the minimum stack alignment of an argument.
1730 Align getMinStackArgumentAlignment() const {
1731 return MinStackArgumentAlignment;
1732 }
1733
1734 /// Return the minimum function alignment.
1735 Align getMinFunctionAlignment() const { return MinFunctionAlignment; }
1736
1737 /// Return the preferred function alignment.
1738 Align getPrefFunctionAlignment() const { return PrefFunctionAlignment; }
1739
1740 /// Return the preferred loop alignment.
1741 virtual Align getPrefLoopAlignment(MachineLoop *ML = nullptr) const {
1742 return PrefLoopAlignment;
1743 }
1744
1745 /// Should loops be aligned even when the function is marked OptSize (but not
1746 /// MinSize).
1747 virtual bool alignLoopsWithOptSize() const {
1748 return false;
1749 }
1750
1751 /// If the target has a standard location for the stack protector guard,
1752 /// returns the address of that location. Otherwise, returns nullptr.
1753 /// DEPRECATED: please override useLoadStackGuardNode and customize
1754 /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
1755 virtual Value *getIRStackGuard(IRBuilder<> &IRB) const;
1756
1757 /// Inserts necessary declarations for SSP (stack protection) purpose.
1758 /// Should be used only when getIRStackGuard returns nullptr.
1759 virtual void insertSSPDeclarations(Module &M) const;
1760
1761 /// Return the variable that's previously inserted by insertSSPDeclarations,
1762 /// if any, otherwise return nullptr. Should be used only when
1763 /// getIRStackGuard returns nullptr.
1764 virtual Value *getSDagStackGuard(const Module &M) const;
1765
1766 /// If this function returns true, stack protection checks should XOR the
1767 /// frame pointer (or whichever pointer is used to address locals) into the
1768 /// stack guard value before checking it. getIRStackGuard must return nullptr
1769 /// if this returns true.
1770 virtual bool useStackGuardXorFP() const { return false; }
1771
1772 /// If the target has a standard stack protection check function that
1773 /// performs validation and error handling, returns the function. Otherwise,
1774 /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
1775 /// Should be used only when getIRStackGuard returns nullptr.
1776 virtual Function *getSSPStackGuardCheck(const Module &M) const;
1777
1778protected:
1779 Value *getDefaultSafeStackPointerLocation(IRBuilder<> &IRB,
1780 bool UseTLS) const;
1781
1782public:
1783 /// Returns the target-specific address of the unsafe stack pointer.
1784 virtual Value *getSafeStackPointerLocation(IRBuilder<> &IRB) const;
1785
1786 /// Returns the name of the symbol used to emit stack probes or the empty
1787 /// string if not applicable.
1788 virtual bool hasStackProbeSymbol(MachineFunction &MF) const { return false; }
1789
1790 virtual bool hasInlineStackProbe(MachineFunction &MF) const { return false; }
1791
1792 virtual StringRef getStackProbeSymbolName(MachineFunction &MF) const {
1793 return "";
1794 }
1795
1796 /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
1797 /// are happy to sink it into basic blocks. A cast may be free, but not
1798 /// necessarily a no-op. e.g. a free truncate from a 64-bit to 32-bit pointer.
1799 virtual bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const;
1800
1801 /// Return true if the pointer arguments to CI should be aligned by aligning
1802 /// the object whose address is being passed. If so then MinSize is set to the
1803 /// minimum size the object must be to be aligned and PrefAlign is set to the
1804 /// preferred alignment.
1805 virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
1806 unsigned & /*PrefAlign*/) const {
1807 return false;
1808 }
1809
1810 //===--------------------------------------------------------------------===//
1811 /// \name Helpers for TargetTransformInfo implementations
1812 /// @{
1813
1814 /// Get the ISD node that corresponds to the Instruction class opcode.
1815 int InstructionOpcodeToISD(unsigned Opcode) const;
1816
1817 /// Estimate the cost of type-legalization and the legalized type.
1818 std::pair<InstructionCost, MVT> getTypeLegalizationCost(const DataLayout &DL,
1819 Type *Ty) const;
1820
1821 /// @}
1822
1823 //===--------------------------------------------------------------------===//
1824 /// \name Helpers for atomic expansion.
1825 /// @{
1826
1827 /// Returns the maximum atomic operation size (in bits) supported by
1828 /// the backend. Atomic operations greater than this size (as well
1829 /// as ones that are not naturally aligned), will be expanded by
1830 /// AtomicExpandPass into an __atomic_* library call.
1831 unsigned getMaxAtomicSizeInBitsSupported() const {
1832 return MaxAtomicSizeInBitsSupported;
1833 }
1834
1835 /// Returns the size of the smallest cmpxchg or ll/sc instruction
1836 /// the backend supports. Any smaller operations are widened in
1837 /// AtomicExpandPass.
1838 ///
1839 /// Note that *unlike* operations above the maximum size, atomic ops
1840 /// are still natively supported below the minimum; they just
1841 /// require a more complex expansion.
1842 unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
1843
1844 /// Whether the target supports unaligned atomic operations.
1845 bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
1846
1847 /// Whether AtomicExpandPass should automatically insert fences and reduce
1848 /// ordering for this atomic. This should be true for most architectures with
1849 /// weak memory ordering. Defaults to false.
1850 virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
1851 return false;
1852 }
1853
1854 /// Perform a load-linked operation on Addr, returning a "Value *" with the
1855 /// corresponding pointee type. This may entail some non-trivial operations to
1856 /// truncate or reconstruct types that will be illegal in the backend. See
1857 /// ARMISelLowering for an example implementation.
1858 virtual Value *emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
1859 AtomicOrdering Ord) const {
1860 llvm_unreachable("Load linked unimplemented on this target");
1861 }
1862
1863 /// Perform a store-conditional operation to Addr. Return the status of the
1864 /// store. This should be 0 if the store succeeded, non-zero otherwise.
1865 virtual Value *emitStoreConditional(IRBuilder<> &Builder, Value *Val,
1866 Value *Addr, AtomicOrdering Ord) const {
1867 llvm_unreachable("Store conditional unimplemented on this target");
1868 }
1869
1870 /// Perform a masked atomicrmw using a target-specific intrinsic. This
1871 /// represents the core LL/SC loop which will be lowered at a late stage by
1872 /// the backend.
1873 virtual Value *emitMaskedAtomicRMWIntrinsic(IRBuilder<> &Builder,
1874 AtomicRMWInst *AI,
1875 Value *AlignedAddr, Value *Incr,
1876 Value *Mask, Value *ShiftAmt,
1877 AtomicOrdering Ord) const {
1878 llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
1879 }
1880
1881 /// Perform a masked cmpxchg using a target-specific intrinsic. This
1882 /// represents the core LL/SC loop which will be lowered at a late stage by
1883 /// the backend.
1884 virtual Value *emitMaskedAtomicCmpXchgIntrinsic(
1885 IRBuilder<> &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
1886 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
1887 llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
1888 }
1889
1890 /// Inserts in the IR a target-specific intrinsic specifying a fence.
1891 /// It is called by AtomicExpandPass before expanding an
1892 /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
1893 /// if shouldInsertFencesForAtomic returns true.
1894 ///
1895 /// Inst is the original atomic instruction, prior to other expansions that
1896 /// may be performed.
1897 ///
1898 /// This function should either return a nullptr, or a pointer to an IR-level
1899 /// Instruction*. Even complex fence sequences can be represented by a
1900 /// single Instruction* through an intrinsic to be lowered later.
1901 /// Backends should override this method to produce target-specific intrinsic
1902 /// for their fences.
1903 /// FIXME: Please note that the default implementation here in terms of
1904 /// IR-level fences exists for historical/compatibility reasons and is
1905 /// *unsound* ! Fences cannot, in general, be used to restore sequential
1906 /// consistency. For example, consider the following example:
1907 /// atomic<int> x = y = 0;
1908 /// int r1, r2, r3, r4;
1909 /// Thread 0:
1910 /// x.store(1);
1911 /// Thread 1:
1912 /// y.store(1);
1913 /// Thread 2:
1914 /// r1 = x.load();
1915 /// r2 = y.load();
1916 /// Thread 3:
1917 /// r3 = y.load();
1918 /// r4 = x.load();
1919 /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
1920 /// seq_cst. But if they are lowered to monotonic accesses, no amount of
1921 /// IR-level fences can prevent it.
1922 /// @{
1923 virtual Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst,
1924 AtomicOrdering Ord) const {
1925 if (isReleaseOrStronger(Ord) && Inst->hasAtomicStore())
1926 return Builder.CreateFence(Ord);
1927 else
1928 return nullptr;
1929 }
1930
1931 virtual Instruction *emitTrailingFence(IRBuilder<> &Builder,
1932 Instruction *Inst,
1933 AtomicOrdering Ord) const {
1934 if (isAcquireOrStronger(Ord))
1935 return Builder.CreateFence(Ord);
1936 else
1937 return nullptr;
1938 }
1939 /// @}
1940
1941 // Emits code that executes when the comparison result in the ll/sc
1942 // expansion of a cmpxchg instruction is such that the store-conditional will
1943 // not execute. This makes it possible to balance out the load-linked with
1944 // a dedicated instruction, if desired.
1945 // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
1946 // be unnecessarily held, except if clrex, inserted by this hook, is executed.
1947 virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> &Builder) const {}
1948
1949 /// Returns true if the given (atomic) store should be expanded by the
1950 /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
1951 virtual bool shouldExpandAtomicStoreInIR(StoreInst *SI) const {
1952 return false;
1953 }
1954
1955 /// Returns true if arguments should be sign-extended in lib calls.
1956 virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
1957 return IsSigned;
1958 }
1959
1960 /// Returns true if arguments should be extended in lib calls.
1961 virtual bool shouldExtendTypeInLibCall(EVT Type) const {
1962 return true;
1963 }
1964
1965 /// Returns how the given (atomic) load should be expanded by the
1966 /// IR-level AtomicExpand pass.
1967 virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const {
1968 return AtomicExpansionKind::None;
1969 }
1970
1971 /// Returns how the given atomic cmpxchg should be expanded by the IR-level
1972 /// AtomicExpand pass.
1973 virtual AtomicExpansionKind
1974 shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
1975 return AtomicExpansionKind::None;
1976 }
1977
1978 /// Returns how the IR-level AtomicExpand pass should expand the given
1979 /// AtomicRMW, if at all. Default is to never expand.
1980 virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
1981 return RMW->isFloatingPointOperation() ?
1982 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None;
1983 }
1984
1985 /// On some platforms, an AtomicRMW that never actually modifies the value
1986 /// (such as fetch_add of 0) can be turned into a fence followed by an
1987 /// atomic load. This may sound useless, but it makes it possible for the
1988 /// processor to keep the cacheline shared, dramatically improving
1989 /// performance. And such idempotent RMWs are useful for implementing some
1990 /// kinds of locks, see for example (justification + benchmarks):
1991 /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
1992 /// This method tries doing that transformation, returning the atomic load if
1993 /// it succeeds, and nullptr otherwise.
1994 /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
1995 /// another round of expansion.
1996 virtual LoadInst *
1997 lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const {
1998 return nullptr;
1999 }
2000
2001 /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
2002 /// SIGN_EXTEND, or ANY_EXTEND).
2003 virtual ISD::NodeType getExtendForAtomicOps() const {
2004 return ISD::ZERO_EXTEND;
2005 }
2006
2007 /// Returns how the platform's atomic compare and swap expects its comparison
2008 /// value to be extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND). This is
2009 /// separate from getExtendForAtomicOps, which is concerned with the
2010 /// sign-extension of the instruction's output, whereas here we are concerned
2011 /// with the sign-extension of the input. For targets with compare-and-swap
2012 /// instructions (or sub-word comparisons in their LL/SC loop expansions),
2013 /// the input can be ANY_EXTEND, but the output will still have a specific
2014 /// extension.
2015 virtual ISD::NodeType getExtendForAtomicCmpSwapArg() const {
2016 return ISD::ANY_EXTEND;
2017 }
2018
2019 /// @}
2020
2021 /// Returns true if we should normalize
2022 /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
2023 /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
2024 /// that it saves us from materializing N0 and N1 in an integer register.
2025 /// Targets that are able to perform and/or on flags should return false here.
2026 virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context,
2027 EVT VT) const {
2028 // If a target has multiple condition registers, then it likely has logical
2029 // operations on those registers.
2030 if (hasMultipleConditionRegisters())
2031 return false;
2032 // Only do the transform if the value won't be split into multiple
2033 // registers.
2034 LegalizeTypeAction Action = getTypeAction(Context, VT);
2035 return Action != TypeExpandInteger && Action != TypeExpandFloat &&
2036 Action != TypeSplitVector;
2037 }
2038
2039 virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
2040
2041 /// Return true if a select of constants (select Cond, C1, C2) should be
2042 /// transformed into simple math ops with the condition value. For example:
2043 /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
2044 virtual bool convertSelectOfConstantsToMath(EVT VT) const {
2045 return false;
2046 }
2047
2048 /// Return true if it is profitable to transform an integer
2049 /// multiplication-by-constant into simpler operations like shifts and adds.
2050 /// This may be true if the target does not directly support the
2051 /// multiplication operation for the specified type or the sequence of simpler
2052 /// ops is faster than the multiply.
2053 virtual bool decomposeMulByConstant(LLVMContext &Context,
2054 EVT VT, SDValue C) const {
2055 return false;
2056 }
2057
2058 /// Return true if it is more correct/profitable to use strict FP_TO_INT
2059 /// conversion operations - canonicalizing the FP source value instead of
2060 /// converting all cases and then selecting based on value.
2061 /// This may be true if the target throws exceptions for out of bounds
2062 /// conversions or has fast FP CMOV.
2063 virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
2064 bool IsSigned) const {
2065 return false;
2066 }
2067
2068 //===--------------------------------------------------------------------===//
2069 // TargetLowering Configuration Methods - These methods should be invoked by
2070 // the derived class constructor to configure this object for the target.
2071 //
2072protected:
2073 /// Specify how the target extends the result of integer and floating point
2074 /// boolean values from i1 to a wider type. See getBooleanContents.
2075 void setBooleanContents(BooleanContent Ty) {
2076 BooleanContents = Ty;
2077 BooleanFloatContents = Ty;
2078 }
2079
2080 /// Specify how the target extends the result of integer and floating point
2081 /// boolean values from i1 to a wider type. See getBooleanContents.
2082 void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy) {
2083 BooleanContents = IntTy;
2084 BooleanFloatContents = FloatTy;
2085 }
2086
2087 /// Specify how the target extends the result of a vector boolean value from a
2088 /// vector of i1 to a wider type. See getBooleanContents.
2089 void setBooleanVectorContents(BooleanContent Ty) {
2090 BooleanVectorContents = Ty;
2091 }
2092
2093 /// Specify the target scheduling preference.
2094 void setSchedulingPreference(Sched::Preference Pref) {
2095 SchedPreferenceInfo = Pref;
2096 }
2097
2098 /// Indicate the minimum number of blocks to generate jump tables.
2099 void setMinimumJumpTableEntries(unsigned Val);
2100
2101 /// Indicate the maximum number of entries in jump tables.
2102 /// Set to zero to generate unlimited jump tables.
2103 void setMaximumJumpTableSize(unsigned);
2104
2105 /// If set to a physical register, this specifies the register that
2106 /// llvm.savestack/llvm.restorestack should save and restore.
2107 void setStackPointerRegisterToSaveRestore(Register R) {
2108 StackPointerRegisterToSaveRestore = R;
2109 }
2110
2111 /// Tells the code generator that the target has multiple (allocatable)
2112 /// condition registers that can be used to store the results of comparisons
2113 /// for use by selects and conditional branches. With multiple condition
2114 /// registers, the code generator will not aggressively sink comparisons into
2115 /// the blocks of their users.
2116 void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
2117 HasMultipleConditionRegisters = hasManyRegs;
2118 }
2119
2120 /// Tells the code generator that the target has BitExtract instructions.
2121 /// The code generator will aggressively sink "shift"s into the blocks of
2122 /// their users if the users will generate "and" instructions which can be
2123 /// combined with "shift" to BitExtract instructions.
2124 void setHasExtractBitsInsn(bool hasExtractInsn = true) {
2125 HasExtractBitsInsn = hasExtractInsn;
2126 }
2127
2128 /// Tells the code generator not to expand logic operations on comparison
2129 /// predicates into separate sequences that increase the amount of flow
2130 /// control.
2131 void setJumpIsExpensive(bool isExpensive = true);
2132
2133 /// Tells the code generator which bitwidths to bypass.
2134 void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
2135 BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
2136 }
2137
2138 /// Add the specified register class as an available regclass for the
2139 /// specified value type. This indicates the selector can handle values of
2140 /// that class natively.
2141 void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
2142 assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
2143 RegClassForVT[VT.SimpleTy] = RC;
2144 }
2145
2146 /// Return the largest legal super-reg register class of the register class
2147 /// for the specified type and its associated "cost".
2148 virtual std::pair<const TargetRegisterClass *, uint8_t>
2149 findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
2150
2151 /// Once all of the register classes are added, this allows us to compute
2152 /// derived properties we expose.
2153 void computeRegisterProperties(const TargetRegisterInfo *TRI);
2154
2155 /// Indicate that the specified operation does not work with the specified
2156 /// type and indicate what to do about it. Note that VT may refer to either
2157 /// the type of a result or that of an operand of Op.
2158 void setOperationAction(unsigned Op, MVT VT,
2159 LegalizeAction Action) {
2160 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
2161 OpActions[(unsigned)VT.SimpleTy][Op] = Action;
2162 }
2163
2164 /// Indicate that the specified load with extension does not work with the
2165 /// specified type and indicate what to do about it.
2166 void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
2167 LegalizeAction Action) {
2168 assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
2169 MemVT.isValid() && "Table isn't big enough!");
2170 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2171 unsigned Shift = 4 * ExtType;
2172 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
2173 LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
2174 }
2175
2176 /// Indicate that the specified truncating store does not work with the
2177 /// specified type and indicate what to do about it.
2178 void setTruncStoreAction(MVT ValVT, MVT MemVT,
2179 LegalizeAction Action) {
2180 assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
2181 TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
2182 }
2183
2184 /// Indicate that the specified indexed load does or does not work with the
2185 /// specified type and indicate what to do abort it.
2186 ///
2187 /// NOTE: All indexed mode loads are initialized to Expand in
2188 /// TargetLowering.cpp
2189 void setIndexedLoadAction(unsigned IdxMode, MVT VT, LegalizeAction Action) {
2190 setIndexedModeAction(IdxMode, VT, IMAB_Load, Action);
2191 }
2192
2193 /// Indicate that the specified indexed store does or does not work with the
2194 /// specified type and indicate what to do about it.
2195 ///
2196 /// NOTE: All indexed mode stores are initialized to Expand in
2197 /// TargetLowering.cpp
2198 void setIndexedStoreAction(unsigned IdxMode, MVT VT, LegalizeAction Action) {
2199 setIndexedModeAction(IdxMode, VT, IMAB_Store, Action);
2200 }
2201
2202 /// Indicate that the specified indexed masked load does or does not work with
2203 /// the specified type and indicate what to do about it.
2204 ///
2205 /// NOTE: All indexed mode masked loads are initialized to Expand in
2206 /// TargetLowering.cpp
2207 void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT,
2208 LegalizeAction Action) {
2209 setIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad, Action);
2210 }
2211
2212 /// Indicate that the specified indexed masked store does or does not work
2213 /// with the specified type and indicate what to do about it.
2214 ///
2215 /// NOTE: All indexed mode masked stores are initialized to Expand in
2216 /// TargetLowering.cpp
2217 void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT,
2218 LegalizeAction Action) {
2219 setIndexedModeAction(IdxMode, VT, IMAB_MaskedStore, Action);
2220 }
2221
2222 /// Indicate that the specified condition code is or isn't supported on the
2223 /// target and indicate what to do about it.
2224 void setCondCodeAction(ISD::CondCode CC, MVT VT,
2225 LegalizeAction Action) {
2226 assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&
2227 "Table isn't big enough!");
2228 assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
2229 /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
2230 /// value and the upper 29 bits index into the second dimension of the array
2231 /// to select what 32-bit value to use.
2232 uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
2233 CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
2234 CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
2235 }
2236
2237 /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
2238 /// to trying a larger integer/fp until it can find one that works. If that
2239 /// default is insufficient, this method can be used by the target to override
2240 /// the default.
2241 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2242 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
2243 }
2244
2245 /// Convenience method to set an operation to Promote and specify the type
2246 /// in a single call.
2247 void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
2248 setOperationAction(Opc, OrigVT, Promote);
2249 AddPromotedToType(Opc, OrigVT, DestVT);
2250 }
2251
2252 /// Targets should invoke this method for each target independent node that
2253 /// they want to provide a custom DAG combiner for by implementing the
2254 /// PerformDAGCombine virtual method.
2255 void setTargetDAGCombine(ISD::NodeType NT) {
2256 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
2257 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
2258 }
2259
2260 /// Set the target's minimum function alignment.
2261 void setMinFunctionAlignment(Align Alignment) {
2262 MinFunctionAlignment = Alignment;
2263 }
2264
2265 /// Set the target's preferred function alignment. This should be set if
2266 /// there is a performance benefit to higher-than-minimum alignment
2267 void setPrefFunctionAlignment(Align Alignment) {
2268 PrefFunctionAlignment = Alignment;
2269 }
2270
2271 /// Set the target's preferred loop alignment. Default alignment is one, it
2272 /// means the target does not care about loop alignment. The target may also
2273 /// override getPrefLoopAlignment to provide per-loop values.
2274 void setPrefLoopAlignment(Align Alignment) { PrefLoopAlignment = Alignment; }
2275
2276 /// Set the minimum stack alignment of an argument.
2277 void setMinStackArgumentAlignment(Align Alignment) {
2278 MinStackArgumentAlignment = Alignment;
2279 }
2280
2281 /// Set the maximum atomic operation size supported by the
2282 /// backend. Atomic operations greater than this size (as well as
2283 /// ones that are not naturally aligned), will be expanded by
2284 /// AtomicExpandPass into an __atomic_* library call.
2285 void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
2286 MaxAtomicSizeInBitsSupported = SizeInBits;
2287 }
2288
2289 /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
2290 void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
2291 MinCmpXchgSizeInBits = SizeInBits;
2292 }
2293
2294 /// Sets whether unaligned atomic operations are supported.
2295 void setSupportsUnalignedAtomics(bool UnalignedSupported) {
2296 SupportsUnalignedAtomics = UnalignedSupported;
2297 }
2298
2299public:
2300 //===--------------------------------------------------------------------===//
2301 // Addressing mode description hooks (used by LSR etc).
2302 //
2303
2304 /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
2305 /// instructions reading the address. This allows as much computation as
2306 /// possible to be done in the address mode for that operand. This hook lets
2307 /// targets also pass back when this should be done on intrinsics which
2308 /// load/store.
2309 virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
2310 SmallVectorImpl<Value*> &/*Ops*/,
2311 Type *&/*AccessTy*/) const {
2312 return false;
2313 }
2314
2315 /// This represents an addressing mode of:
2316 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
2317 /// If BaseGV is null, there is no BaseGV.
2318 /// If BaseOffs is zero, there is no base offset.
2319 /// If HasBaseReg is false, there is no base register.
2320 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
2321 /// no scale.
2322 struct AddrMode {
2323 GlobalValue *BaseGV = nullptr;
2324 int64_t BaseOffs = 0;
2325 bool HasBaseReg = false;
2326 int64_t Scale = 0;
2327 AddrMode() = default;
2328 };
2329
2330 /// Return true if the addressing mode represented by AM is legal for this
2331 /// target, for a load/store of the specified type.
2332 ///
2333 /// The type may be VoidTy, in which case only return true if the addressing
2334 /// mode is legal for a load/store of any legal type. TODO: Handle
2335 /// pre/postinc as well.
2336 ///
2337 /// If the address space cannot be determined, it will be -1.
2338 ///
2339 /// TODO: Remove default argument
2340 virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
2341 Type *Ty, unsigned AddrSpace,
2342 Instruction *I = nullptr) const;
2343
2344 /// Return the cost of the scaling factor used in the addressing mode
2345 /// represented by AM for this target, for a load/store of the specified type.
2346 ///
2347 /// If the AM is supported, the return value must be >= 0.
2348 /// If the AM is not supported, it returns a negative value.
2349 /// TODO: Handle pre/postinc as well.
2350 /// TODO: Remove default argument
2351 virtual InstructionCost getScalingFactorCost(const DataLayout &DL,
2352 const AddrMode &AM, Type *Ty,
2353 unsigned AS = 0) const {
2354 // Default: assume that any scaling factor used in a legal AM is free.
2355 if (isLegalAddressingMode(DL, AM, Ty, AS))
2356 return 0;
2357 return -1;
2358 }
2359
2360 /// Return true if the specified immediate is legal icmp immediate, that is
2361 /// the target has icmp instructions which can compare a register against the
2362 /// immediate without having to materialize the immediate into a register.
2363 virtual bool isLegalICmpImmediate(int64_t) const {
2364 return true;
2365 }
2366
2367 /// Return true if the specified immediate is legal add immediate, that is the
2368 /// target has add instructions which can add a register with the immediate
2369 /// without having to materialize the immediate into a register.
2370 virtual bool isLegalAddImmediate(int64_t) const {
2371 return true;
2372 }
2373
2374 /// Return true if the specified immediate is legal for the value input of a
2375 /// store instruction.
2376 virtual bool isLegalStoreImmediate(int64_t Value) const {
2377 // Default implementation assumes that at least 0 works since it is likely
2378 // that a zero register exists or a zero immediate is allowed.
2379 return Value == 0;
2380 }
2381
2382 /// Return true if it's significantly cheaper to shift a vector by a uniform
2383 /// scalar than by an amount which will vary across each lane. On x86 before
2384 /// AVX2 for example, there is a "psllw" instruction for the former case, but
2385 /// no simple instruction for a general "a << b" operation on vectors.
2386 /// This should also apply to lowering for vector funnel shifts (rotates).
2387 virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
2388 return false;
2389 }
2390
2391 /// Given a shuffle vector SVI representing a vector splat, return a new
2392 /// scalar type of size equal to SVI's scalar type if the new type is more
2393 /// profitable. Returns nullptr otherwise. For example under MVE float splats
2394 /// are converted to integer to prevent the need to move from SPR to GPR
2395 /// registers.
2396 virtual Type* shouldConvertSplatType(ShuffleVectorInst* SVI) const {
2397 return nullptr;
2398 }
2399
2400 /// Given a set in interconnected phis of type 'From' that are loaded/stored
2401 /// or bitcast to type 'To', return true if the set should be converted to
2402 /// 'To'.
2403 virtual bool shouldConvertPhiType(Type *From, Type *To) const {
2404 return (From->isIntegerTy() || From->isFloatingPointTy()) &&
2405 (To->isIntegerTy() || To->isFloatingPointTy());
2406 }
2407
2408 /// Returns true if the opcode is a commutative binary operation.
2409 virtual bool isCommutativeBinOp(unsigned Opcode) const {
2410 // FIXME: This should get its info from the td file.
2411 switch (Opcode) {
2412 case ISD::ADD:
2413 case ISD::SMIN:
2414 case ISD::SMAX:
2415 case ISD::UMIN:
2416 case ISD::UMAX:
2417 case ISD::MUL:
2418 case ISD::MULHU:
2419 case ISD::MULHS:
2420 case ISD::SMUL_LOHI:
2421 case ISD::UMUL_LOHI:
2422 case ISD::FADD:
2423 case ISD::FMUL:
2424 case ISD::AND:
2425 case ISD::OR:
2426 case ISD::XOR:
2427 case ISD::SADDO:
2428 case ISD::UADDO:
2429 case ISD::ADDC:
2430 case ISD::ADDE:
2431 case ISD::SADDSAT:
2432 case ISD::UADDSAT:
2433 case ISD::FMINNUM:
2434 case ISD::FMAXNUM:
2435 case ISD::FMINNUM_IEEE:
2436 case ISD::FMAXNUM_IEEE:
2437 case ISD::FMINIMUM:
2438 case ISD::FMAXIMUM:
2439 return true;
2440 default: return false;
2441 }
2442 }
2443
2444 /// Return true if the node is a math/logic binary operator.
2445 virtual bool isBinOp(unsigned Opcode) const {
2446 // A commutative binop must be a binop.
2447 if (isCommutativeBinOp(Opcode))
2448 return true;
2449 // These are non-commutative binops.
2450 switch (Opcode) {
2451 case ISD::SUB:
2452 case ISD::SHL:
2453 case ISD::SRL:
2454 case ISD::SRA:
2455 case ISD::SDIV:
2456 case ISD::UDIV:
2457 case ISD::SREM:
2458 case ISD::UREM:
2459 case ISD::SSUBSAT:
2460 case ISD::USUBSAT:
2461 case ISD::FSUB:
2462 case ISD::FDIV:
2463 case ISD::FREM:
2464 return true;
2465 default:
2466 return false;
2467 }
2468 }
2469
2470 /// Return true if it's free to truncate a value of type FromTy to type
2471 /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
2472 /// by referencing its sub-register AX.
2473 /// Targets must return false when FromTy <= ToTy.
2474 virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
2475 return false;
2476 }
2477
2478 /// Return true if a truncation from FromTy to ToTy is permitted when deciding
2479 /// whether a call is in tail position. Typically this means that both results
2480 /// would be assigned to the same register or stack slot, but it could mean
2481 /// the target performs adequate checks of its own before proceeding with the
2482 /// tail call. Targets must return false when FromTy <= ToTy.
2483 virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
2484 return false;
2485 }
2486
2487 virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const {
2488 return false;
2489 }
2490
2491 virtual bool isProfitableToHoist(Instruction *I) const { return true; }
2492
2493 /// Return true if the extension represented by \p I is free.
2494 /// Unlikely the is[Z|FP]ExtFree family which is based on types,
2495 /// this method can use the context provided by \p I to decide
2496 /// whether or not \p I is free.
2497 /// This method extends the behavior of the is[Z|FP]ExtFree family.
2498 /// In other words, if is[Z|FP]Free returns true, then this method
2499 /// returns true as well. The converse is not true.
2500 /// The target can perform the adequate checks by overriding isExtFreeImpl.
2501 /// \pre \p I must be a sign, zero, or fp extension.
2502 bool isExtFree(const Instruction *I) const {
2503 switch (I->getOpcode()) {
2504 case Instruction::FPExt:
2505 if (isFPExtFree(EVT::getEVT(I->getType()),
2506 EVT::getEVT(I->getOperand(0)->getType())))
2507 return true;
2508 break;
2509 case Instruction::ZExt:
2510 if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
2511 return true;
2512 break;
2513 case Instruction::SExt:
2514 break;
2515 default:
2516 llvm_unreachable("Instruction is not an extension");
2517 }
2518 return isExtFreeImpl(I);
2519 }
2520
2521 /// Return true if \p Load and \p Ext can form an ExtLoad.
2522 /// For example, in AArch64
2523 /// %L = load i8, i8* %ptr
2524 /// %E = zext i8 %L to i32
2525 /// can be lowered into one load instruction
2526 /// ldrb w0, [x0]
2527 bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
2528 const DataLayout &DL) const {
2529 EVT VT = getValueType(DL, Ext->getType());
2530 EVT LoadVT = getValueType(DL, Load->getType());
2531
2532 // If the load has other users and the truncate is not free, the ext
2533 // probably isn't free.
2534 if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
2535 !isTruncateFree(Ext->getType(), Load->getType()))
2536 return false;
2537
2538 // Check whether the target supports casts folded into loads.
2539 unsigned LType;
2540 if (isa<ZExtInst>(Ext))
2541 LType = ISD::ZEXTLOAD;
2542 else {
2543 assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
2544 LType = ISD::SEXTLOAD;
2545 }
2546
2547 return isLoadExtLegal(LType, VT, LoadVT);
2548 }
2549
2550 /// Return true if any actual instruction that defines a value of type FromTy
2551 /// implicitly zero-extends the value to ToTy in the result register.
2552 ///
2553 /// The function should return true when it is likely that the truncate can
2554 /// be freely folded with an instruction defining a value of FromTy. If
2555 /// the defining instruction is unknown (because you're looking at a
2556 /// function argument, PHI, etc.) then the target may require an
2557 /// explicit truncate, which is not necessarily free, but this function
2558 /// does not deal with those cases.
2559 /// Targets must return false when FromTy >= ToTy.
2560 virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
2561 return false;
2562 }
2563
2564 virtual bool isZExtFree(EVT FromTy, EVT ToTy) const {
2565 return false;
2566 }
2567
2568 /// Return true if sign-extension from FromTy to ToTy is cheaper than
2569 /// zero-extension.
2570 virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
2571 return false;
2572 }
2573
2574 /// Return true if sinking I's operands to the same basic block as I is
2575 /// profitable, e.g. because the operands can be folded into a target
2576 /// instruction during instruction selection. After calling the function
2577 /// \p Ops contains the Uses to sink ordered by dominance (dominating users
2578 /// come first).
2579 virtual bool shouldSinkOperands(Instruction *I,
2580 SmallVectorImpl<Use *> &Ops) const {
2581 return false;
2582 }
2583
2584 /// Return true if the target supplies and combines to a paired load
2585 /// two loaded values of type LoadedType next to each other in memory.
2586 /// RequiredAlignment gives the minimal alignment constraints that must be met
2587 /// to be able to select this paired load.
2588 ///
2589 /// This information is *not* used to generate actual paired loads, but it is
2590 /// used to generate a sequence of loads that is easier to combine into a
2591 /// paired load.
2592 /// For instance, something like this:
2593 /// a = load i64* addr
2594 /// b = trunc i64 a to i32
2595 /// c = lshr i64 a, 32
2596 /// d = trunc i64 c to i32
2597 /// will be optimized into:
2598 /// b = load i32* addr1
2599 /// d = load i32* addr2
2600 /// Where addr1 = addr2 +/- sizeof(i32).
2601 ///
2602 /// In other words, unless the target performs a post-isel load combining,
2603 /// this information should not be provided because it will generate more
2604 /// loads.
2605 virtual bool hasPairedLoad(EVT /*LoadedType*/,
2606 Align & /*RequiredAlignment*/) const {
2607 return false;
2608 }
2609
2610 /// Return true if the target has a vector blend instruction.
2611 virtual bool hasVectorBlend() const { return false; }
2612
2613 /// Get the maximum supported factor for interleaved memory accesses.
2614 /// Default to be the minimum interleave factor: 2.
2615 virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
2616
2617 /// Lower an interleaved load to target specific intrinsics. Return
2618 /// true on success.
2619 ///
2620 /// \p LI is the vector load instruction.
2621 /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
2622 /// \p Indices is the corresponding indices for each shufflevector.
2623 /// \p Factor is the interleave factor.
2624 virtual bool lowerInterleavedLoad(LoadInst *LI,
2625 ArrayRef<ShuffleVectorInst *> Shuffles,
2626 ArrayRef<unsigned> Indices,
2627 unsigned Factor) const {
2628 return false;
2629 }
2630
2631 /// Lower an interleaved store to target specific intrinsics. Return
2632 /// true on success.
2633 ///
2634 /// \p SI is the vector store instruction.
2635 /// \p SVI is the shufflevector to RE-interleave the stored vector.
2636 /// \p Factor is the interleave factor.
2637 virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI,
2638 unsigned Factor) const {
2639 return false;
2640 }
2641
2642 /// Return true if zero-extending the specific node Val to type VT2 is free
2643 /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
2644 /// because it's folded such as X86 zero-extending loads).
2645 virtual bool isZExtFree(SDValue Val, EVT VT2) const {
2646 return isZExtFree(Val.getValueType(), VT2);
2647 }
2648
2649 /// Return true if an fpext operation is free (for instance, because
2650 /// single-precision floating-point numbers are implicitly extended to
2651 /// double-precision).
2652 virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
2653 assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
2654 "invalid fpext types");
2655 return false;
2656 }
2657
2658 /// Return true if an fpext operation input to an \p Opcode operation is free
2659 /// (for instance, because half-precision floating-point numbers are
2660 /// implicitly extended to float-precision) for an FMA instruction.
2661 virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
2662 EVT DestVT, EVT SrcVT) const {
2663 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
2664 "invalid fpext types");
2665 return isFPExtFree(DestVT, SrcVT);
2666 }
2667
2668 /// Return true if folding a vector load into ExtVal (a sign, zero, or any
2669 /// extend node) is profitable.
2670 virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
2671
2672 /// Return true if an fneg operation is free to the point where it is never
2673 /// worthwhile to replace it with a bitwise operation.
2674 virtual bool isFNegFree(EVT VT) const {
2675 assert(VT.isFloatingPoint());
2676 return false;
2677 }
2678
2679 /// Return true if an fabs operation is free to the point where it is never
2680 /// worthwhile to replace it with a bitwise operation.
2681 virtual bool isFAbsFree(EVT VT) const {
2682 assert(VT.isFloatingPoint());
2683 return false;
2684 }
2685
2686 /// Return true if an FMA operation is faster than a pair of fmul and fadd
2687 /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
2688 /// returns true, otherwise fmuladd is expanded to fmul + fadd.
2689 ///
2690 /// NOTE: This may be called before legalization on types for which FMAs are
2691 /// not legal, but should return true if those types will eventually legalize
2692 /// to types that support FMAs. After legalization, it will only be called on
2693 /// types that support FMAs (via Legal or Custom actions)
2694 virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
2695 EVT) const {
2696 return false;
2697 }
2698
2699 /// IR version
2700 virtual bool isFMAFasterThanFMulAndFAdd(const Function &F, Type *) const {
2701 return false;
2702 }
2703
2704 /// Returns true if be combined with to form an ISD::FMAD. \p N may be an
2705 /// ISD::FADD, ISD::FSUB, or an ISD::FMUL which will be distributed into an
2706 /// fadd/fsub.
2707 virtual bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const {
2708 assert((N->getOpcode() == ISD::FADD || N->getOpcode() == ISD::FSUB ||
2709 N->getOpcode() == ISD::FMUL) &&
2710 "unexpected node in FMAD forming combine");
2711 return isOperationLegal(ISD::FMAD, N->getValueType(0));
2712 }
2713
2714 // Return true when the decision to generate FMA's (or FMS, FMLA etc) rather
2715 // than FMUL and ADD is delegated to the machine combiner.
2716 virtual bool generateFMAsInMachineCombiner(EVT VT,
2717 CodeGenOpt::Level OptLevel) const {
2718 return false;
2719 }
2720
2721 /// Return true if it's profitable to narrow operations of type VT1 to
2722 /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
2723 /// i32 to i16.
2724 virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
2725 return false;
2726 }
2727
2728 /// Return true if it is beneficial to convert a load of a constant to
2729 /// just the constant itself.
2730 /// On some targets it might be more efficient to use a combination of
2731 /// arithmetic instructions to materialize the constant instead of loading it
2732 /// from a constant pool.
2733 virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
2734 Type *Ty) const {
2735 return false;
2736 }
2737
2738 /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
2739 /// from this source type with this index. This is needed because
2740 /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
2741 /// the first element, and only the target knows which lowering is cheap.
2742 virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
2743 unsigned Index) const {
2744 return false;
2745 }
2746
2747 /// Try to convert an extract element of a vector binary operation into an
2748 /// extract element followed by a scalar operation.
2749 virtual bool shouldScalarizeBinop(SDValue VecOp) const {
2750 return false;
2751 }
2752
2753 /// Return true if extraction of a scalar element from the given vector type
2754 /// at the given index is cheap. For example, if scalar operations occur on
2755 /// the same register file as vector operations, then an extract element may
2756 /// be a sub-register rename rather than an actual instruction.
2757 virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
2758 return false;
2759 }
2760
2761 /// Try to convert math with an overflow comparison into the corresponding DAG
2762 /// node operation. Targets may want to override this independently of whether
2763 /// the operation is legal/custom for the given type because it may obscure
2764 /// matching of other patterns.
2765 virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT,
2766 bool MathUsed) const {
2767 // TODO: The default logic is inherited from code in CodeGenPrepare.
2768 // The opcode should not make a difference by default?
2769 if (Opcode != ISD::UADDO)
2770 return false;
2771
2772 // Allow the transform as long as we have an integer type that is not
2773 // obviously illegal and unsupported and if the math result is used
2774 // besides the overflow check. On some targets (e.g. SPARC), it is
2775 // not profitable to form on overflow op if the math result has no
2776 // concrete users.
2777 if (VT.isVector())
2778 return false;
2779 return MathUsed && (VT.isSimple() || !isOperationExpand(Opcode, VT));
2780 }
2781
2782 // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
2783 // even if the vector itself has multiple uses.
2784 virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
2785 return false;
2786 }
2787
2788 // Return true if CodeGenPrepare should consider splitting large offset of a
2789 // GEP to make the GEP fit into the addressing mode and can be sunk into the
2790 // same blocks of its users.
2791 virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
2792
2793 /// Return true if creating a shift of the type by the given
2794 /// amount is not profitable.
2795 virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const {
2796 return false;
2797 }
2798
2799 /// Does this target require the clearing of high-order bits in a register
2800 /// passed to the fp16 to fp conversion library function.
2801 virtual bool shouldKeepZExtForFP16Conv() const { return false; }
2802
2803 //===--------------------------------------------------------------------===//
2804 // Runtime Library hooks
2805 //
2806
2807 /// Rename the default libcall routine name for the specified libcall.
2808 void setLibcallName(RTLIB::Libcall Call, const char *Name) {
2809 LibcallRoutineNames[Call] = Name;
2810 }
2811
2812 /// Get the libcall routine name for the specified libcall.
2813 const char *getLibcallName(RTLIB::Libcall Call) const {
2814 return LibcallRoutineNames[Call];
2815 }
2816
2817 /// Override the default CondCode to be used to test the result of the
2818 /// comparison libcall against zero.
2819 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
2820 CmpLibcallCCs[Call] = CC;
2821 }
2822
2823 /// Get the CondCode that's to be used to test the result of the comparison
2824 /// libcall against zero.
2825 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
2826 return CmpLibcallCCs[Call];
2827 }
2828
2829 /// Set the CallingConv that should be used for the specified libcall.
2830 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
2831 LibcallCallingConvs[Call] = CC;
2832 }
2833
2834 /// Get the CallingConv that should be used for the specified libcall.
2835 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
2836 return LibcallCallingConvs[Call];
2837 }
2838
2839 /// Execute target specific actions to finalize target lowering.
2840 /// This is used to set extra flags in MachineFrameInformation and freezing
2841 /// the set of reserved registers.
2842 /// The default implementation just freezes the set of reserved registers.
2843 virtual void finalizeLowering(MachineFunction &MF) const;
2844
2845 //===----------------------------------------------------------------------===//
2846 // GlobalISel Hooks
2847 //===----------------------------------------------------------------------===//
2848 /// Check whether or not \p MI needs to be moved close to its uses.
2849 virtual bool shouldLocalize(const MachineInstr &MI, const TargetTransformInfo *TTI) const;
2850
2851
2852private:
2853 const TargetMachine &TM;
2854
2855 /// Tells the code generator that the target has multiple (allocatable)
2856 /// condition registers that can be used to store the results of comparisons
2857 /// for use by selects and conditional branches. With multiple condition
2858 /// registers, the code generator will not aggressively sink comparisons into
2859 /// the blocks of their users.
2860 bool HasMultipleConditionRegisters;
2861
2862 /// Tells the code generator that the target has BitExtract instructions.
2863 /// The code generator will aggressively sink "shift"s into the blocks of
2864 /// their users if the users will generate "and" instructions which can be
2865 /// combined with "shift" to BitExtract instructions.
2866 bool HasExtractBitsInsn;
2867
2868 /// Tells the code generator to bypass slow divide or remainder
2869 /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
2870 /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
2871 /// div/rem when the operands are positive and less than 256.
2872 DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
2873
2874 /// Tells the code generator that it shouldn't generate extra flow control
2875 /// instructions and should attempt to combine flow control instructions via
2876 /// predication.
2877 bool JumpIsExpensive;
2878
2879 /// Information about the contents of the high-bits in boolean values held in
2880 /// a type wider than i1. See getBooleanContents.
2881 BooleanContent BooleanContents;
2882
2883 /// Information about the contents of the high-bits in boolean values held in
2884 /// a type wider than i1. See getBooleanContents.
2885 BooleanContent BooleanFloatContents;
2886
2887 /// Information about the contents of the high-bits in boolean vector values
2888 /// when the element type is wider than i1. See getBooleanContents.
2889 BooleanContent BooleanVectorContents;
2890
2891 /// The target scheduling preference: shortest possible total cycles or lowest
2892 /// register usage.
2893 Sched::Preference SchedPreferenceInfo;
2894
2895 /// The minimum alignment that any argument on the stack needs to have.
2896 Align MinStackArgumentAlignment;
2897
2898 /// The minimum function alignment (used when optimizing for size, and to
2899 /// prevent explicitly provided alignment from leading to incorrect code).
2900 Align MinFunctionAlignment;
2901
2902 /// The preferred function alignment (used when alignment unspecified and
2903 /// optimizing for speed).
2904 Align PrefFunctionAlignment;
2905
2906 /// The preferred loop alignment (in log2 bot in bytes).
2907 Align PrefLoopAlignment;
2908
2909 /// Size in bits of the maximum atomics size the backend supports.
2910 /// Accesses larger than this will be expanded by AtomicExpandPass.
2911 unsigned MaxAtomicSizeInBitsSupported;
2912
2913 /// Size in bits of the minimum cmpxchg or ll/sc operation the
2914 /// backend supports.
2915 unsigned MinCmpXchgSizeInBits;
2916
2917 /// This indicates if the target supports unaligned atomic operations.
2918 bool SupportsUnalignedAtomics;
2919
2920 /// If set to a physical register, this specifies the register that
2921 /// llvm.savestack/llvm.restorestack should save and restore.
2922 Register StackPointerRegisterToSaveRestore;
2923
2924 /// This indicates the default register class to use for each ValueType the
2925 /// target supports natively.
2926 const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
2927 uint16_t NumRegistersForVT[MVT::LAST_VALUETYPE];
2928 MVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
2929
2930 /// This indicates the "representative" register class to use for each
2931 /// ValueType the target supports natively. This information is used by the
2932 /// scheduler to track register pressure. By default, the representative
2933 /// register class is the largest legal super-reg register class of the
2934 /// register class of the specified type. e.g. On x86, i8, i16, and i32's
2935 /// representative class would be GR32.
2936 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE];
2937
2938 /// This indicates the "cost" of the "representative" register class for each
2939 /// ValueType. The cost is used by the scheduler to approximate register
2940 /// pressure.
2941 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE];
2942
2943 /// For any value types we are promoting or expanding, this contains the value
2944 /// type that we are changing to. For Expanded types, this contains one step
2945 /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
2946 /// (e.g. i64 -> i16). For types natively supported by the system, this holds
2947 /// the same type (e.g. i32 -> i32).
2948 MVT TransformToType[MVT::LAST_VALUETYPE];
2949
2950 /// For each operation and each value type, keep a LegalizeAction that
2951 /// indicates how instruction selection should deal with the operation. Most
2952 /// operations are Legal (aka, supported natively by the target), but
2953 /// operations that are not should be described. Note that operations on
2954 /// non-legal value types are not described here.
2955 LegalizeAction OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END];
2956
2957 /// For each load extension type and each value type, keep a LegalizeAction
2958 /// that indicates how instruction selection should deal with a load of a
2959 /// specific value type and extension type. Uses 4-bits to store the action
2960 /// for each of the 4 load ext types.
2961 uint16_t LoadExtActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2962
2963 /// For each value type pair keep a LegalizeAction that indicates whether a
2964 /// truncating store of a specific value type and truncating type is legal.
2965 LegalizeAction TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE];
2966
2967 /// For each indexed mode and each value type, keep a quad of LegalizeAction
2968 /// that indicates how instruction selection should deal with the load /
2969 /// store / maskedload / maskedstore.
2970 ///
2971 /// The first dimension is the value_type for the reference. The second
2972 /// dimension represents the various modes for load store.
2973 uint16_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE];
2974
2975 /// For each condition code (ISD::CondCode) keep a LegalizeAction that
2976 /// indicates how instruction selection should deal with the condition code.
2977 ///
2978 /// Because each CC action takes up 4 bits, we need to have the array size be
2979 /// large enough to fit all of the value types. This can be done by rounding
2980 /// up the MVT::LAST_VALUETYPE value to the next multiple of 8.
2981 uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::LAST_VALUETYPE + 7) / 8];
2982
2983 ValueTypeActionImpl ValueTypeActions;
2984
2985private:
2986 LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
2987
2988 /// Targets can specify ISD nodes that they would like PerformDAGCombine
2989 /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
2990 /// array.
2991 unsigned char
2992 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
2993
2994 /// For operations that must be promoted to a specific type, this holds the
2995 /// destination type. This map should be sparse, so don't hold it as an
2996 /// array.
2997 ///
2998 /// Targets add entries to this map with AddPromotedToType(..), clients access
2999 /// this with getTypeToPromoteTo(..).
3000 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
3001 PromoteToType;
3002
3003 /// Stores the name each libcall.
3004 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
3005
3006 /// The ISD::CondCode that should be used to test the result of each of the
3007 /// comparison libcall against zero.
3008 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
3009
3010 /// Stores the CallingConv that should be used for each libcall.
3011 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
3012
3013 /// Set default libcall names and calling conventions.
3014 void InitLibcalls(const Triple &TT);
3015
3016 /// The bits of IndexedModeActions used to store the legalisation actions
3017 /// We store the data as | ML | MS | L | S | each taking 4 bits.
3018 enum IndexedModeActionsBits {
3019 IMAB_Store = 0,
3020 IMAB_Load = 4,
3021 IMAB_MaskedStore = 8,
3022 IMAB_MaskedLoad = 12
3023 };
3024
3025 void setIndexedModeAction(unsigned IdxMode, MVT VT, unsigned Shift,
3026 LegalizeAction Action) {
3027 assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
3028 (unsigned)Action < 0xf && "Table isn't big enough!");
3029 unsigned Ty = (unsigned)VT.SimpleTy;
3030 IndexedModeActions[Ty][IdxMode] &= ~(0xf << Shift);
3031 IndexedModeActions[Ty][IdxMode] |= ((uint16_t)Action) << Shift;
3032 }
3033
3034 LegalizeAction getIndexedModeAction(unsigned IdxMode, MVT VT,
3035 unsigned Shift) const {
3036 assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
3037 "Table isn't big enough!");
3038 unsigned Ty = (unsigned)VT.SimpleTy;
3039 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] >> Shift) & 0xf);
3040 }
3041
3042protected:
3043 /// Return true if the extension represented by \p I is free.
3044 /// \pre \p I is a sign, zero, or fp extension and
3045 /// is[Z|FP]ExtFree of the related types is not true.
3046 virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
3047
3048 /// Depth that GatherAllAliases should should continue looking for chain
3049 /// dependencies when trying to find a more preferable chain. As an
3050 /// approximation, this should be more than the number of consecutive stores
3051 /// expected to be merged.
3052 unsigned GatherAllAliasesMaxDepth;
3053
3054 /// \brief Specify maximum number of store instructions per memset call.
3055 ///
3056 /// When lowering \@llvm.memset this field specifies the maximum number of
3057 /// store operations that may be substituted for the call to memset. Targets
3058 /// must set this value based on the cost threshold for that target. Targets
3059 /// should assume that the memset will be done using as many of the largest
3060 /// store operations first, followed by smaller ones, if necessary, per
3061 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
3062 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
3063 /// store. This only applies to setting a constant array of a constant size.
3064 unsigned MaxStoresPerMemset;
3065 /// Likewise for functions with the OptSize attribute.
3066 unsigned MaxStoresPerMemsetOptSize;
3067
3068 /// \brief Specify maximum number of store instructions per memcpy call.
3069 ///
3070 /// When lowering \@llvm.memcpy this field specifies the maximum number of
3071 /// store operations that may be substituted for a call to memcpy. Targets
3072 /// must set this value based on the cost threshold for that target. Targets
3073 /// should assume that the memcpy will be done using as many of the largest
3074 /// store operations first, followed by smaller ones, if necessary, per
3075 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
3076 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
3077 /// and one 1-byte store. This only applies to copying a constant array of
3078 /// constant size.
3079 unsigned MaxStoresPerMemcpy;
3080 /// Likewise for functions with the OptSize attribute.
3081 unsigned MaxStoresPerMemcpyOptSize;
3082 /// \brief Specify max number of store instructions to glue in inlined memcpy.
3083 ///
3084 /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
3085 /// of store instructions to keep together. This helps in pairing and
3086 // vectorization later on.
3087 unsigned MaxGluedStoresPerMemcpy = 0;
3088
3089 /// \brief Specify maximum number of load instructions per memcmp call.
3090 ///
3091 /// When lowering \@llvm.memcmp this field specifies the maximum number of
3092 /// pairs of load operations that may be substituted for a call to memcmp.
3093 /// Targets must set this value based on the cost threshold for that target.
3094 /// Targets should assume that the memcmp will be done using as many of the
3095 /// largest load operations first, followed by smaller ones, if necessary, per
3096 /// alignment restrictions. For example, loading 7 bytes on a 32-bit machine
3097 /// with 32-bit alignment would result in one 4-byte load, a one 2-byte load
3098 /// and one 1-byte load. This only applies to copying a constant array of
3099 /// constant size.
3100 unsigned MaxLoadsPerMemcmp;
3101 /// Likewise for functions with the OptSize attribute.
3102 unsigned MaxLoadsPerMemcmpOptSize;
3103
3104 /// \brief Specify maximum number of store instructions per memmove call.
3105 ///
3106 /// When lowering \@llvm.memmove this field specifies the maximum number of
3107 /// store instructions that may be substituted for a call to memmove. Targets
3108 /// must set this value based on the cost threshold for that target. Targets
3109 /// should assume that the memmove will be done using as many of the largest
3110 /// store operations first, followed by smaller ones, if necessary, per
3111 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
3112 /// with 8-bit alignment would result in nine 1-byte stores. This only
3113 /// applies to copying a constant array of constant size.
3114 unsigned MaxStoresPerMemmove;
3115 /// Likewise for functions with the OptSize attribute.
3116 unsigned MaxStoresPerMemmoveOptSize;
3117
3118 /// Tells the code generator that select is more expensive than a branch if
3119 /// the branch is usually predicted right.
3120 bool PredictableSelectIsExpensive;
3121
3122 /// \see enableExtLdPromotion.
3123 bool EnableExtLdPromotion;
3124
3125 /// Return true if the value types that can be represented by the specified
3126 /// register class are all legal.
3127 bool isLegalRC(const TargetRegisterInfo &TRI,
3128 const TargetRegisterClass &RC) const;
3129
3130 /// Replace/modify any TargetFrameIndex operands with a targte-dependent
3131 /// sequence of memory operands that is recognized by PrologEpilogInserter.
3132 MachineBasicBlock *emitPatchPoint(MachineInstr &MI,
3133 MachineBasicBlock *MBB) const;
3134
3135 bool IsStrictFPEnabled;
3136};
3137
3138/// This class defines information used to lower LLVM code to legal SelectionDAG
3139/// operators that the target instruction selector can accept natively.
3140///
3141/// This class also defines callbacks that targets must implement to lower
3142/// target-specific constructs to SelectionDAG operators.
3143class TargetLowering : public TargetLoweringBase {
3144public:
3145 struct DAGCombinerInfo;
3146 struct MakeLibCallOptions;
3147
3148 TargetLowering(const TargetLowering &) = delete;
3149 TargetLowering &operator=(const TargetLowering &) = delete;
3150
3151 explicit TargetLowering(const TargetMachine &TM);
3152
3153 bool isPositionIndependent() const;
3154
3155 virtual bool isSDNodeSourceOfDivergence(const SDNode *N,
3156 FunctionLoweringInfo *FLI,
3157 LegacyDivergenceAnalysis *DA) const {
3158 return false;
3159 }
3160
3161 virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
3162 return false;
3163 }
3164
3165 /// Returns true by value, base pointer and offset pointer and addressing mode
3166 /// by reference if the node's address can be legally represented as
3167 /// pre-indexed load / store address.
3168 virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
3169 SDValue &/*Offset*/,
3170 ISD::MemIndexedMode &/*AM*/,
3171 SelectionDAG &/*DAG*/) const {
3172 return false;
3173 }
3174
3175 /// Returns true by value, base pointer and offset pointer and addressing mode
3176 /// by reference if this node can be combined with a load / store to form a
3177 /// post-indexed load / store.
3178 virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
3179 SDValue &/*Base*/,
3180 SDValue &/*Offset*/,
3181 ISD::MemIndexedMode &/*AM*/,
3182 SelectionDAG &/*DAG*/) const {
3183 return false;
3184 }
3185
3186 /// Returns true if the specified base+offset is a legal indexed addressing
3187 /// mode for this target. \p MI is the load or store instruction that is being
3188 /// considered for transformation.
3189 virtual bool isIndexingLegal(MachineInstr &MI, Register Base, Register Offset,
3190 bool IsPre, MachineRegisterInfo &MRI) const {
3191 return false;
3192 }
3193
3194 /// Return the entry encoding for a jump table in the current function. The
3195 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
3196 virtual unsigned getJumpTableEncoding() const;
3197
3198 virtual const MCExpr *
3199 LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
3200 const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
3201 MCContext &/*Ctx*/) const {
3202 llvm_unreachable("Need to implement this hook if target has custom JTIs");
3203 }
3204
3205 /// Returns relocation base for the given PIC jumptable.
3206 virtual SDValue getPICJumpTableRelocBase(SDValue Table,
3207 SelectionDAG &DAG) const;
3208
3209 /// This returns the relocation base for the given PIC jumptable, the same as
3210 /// getPICJumpTableRelocBase, but as an MCExpr.
3211 virtual const MCExpr *
3212 getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3213 unsigned JTI, MCContext &Ctx) const;
3214
3215 /// Return true if folding a constant offset with the given GlobalAddress is
3216 /// legal. It is frequently not legal in PIC relocation models.
3217 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
3218
3219 bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
3220 SDValue &Chain) const;
3221
3222 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
3223 SDValue &NewRHS, ISD::CondCode &CCCode,
3224 const SDLoc &DL, const SDValue OldLHS,
3225 const SDValue OldRHS) const;
3226
3227 void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
3228 SDValue &NewRHS, ISD::CondCode &CCCode,
3229 const SDLoc &DL, const SDValue OldLHS,
3230 const SDValue OldRHS, SDValue &Chain,
3231 bool IsSignaling = false) const;
3232
3233 /// Returns a pair of (return value, chain).
3234 /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
3235 std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
3236 EVT RetVT, ArrayRef<SDValue> Ops,
3237 MakeLibCallOptions CallOptions,
3238 const SDLoc &dl,
3239 SDValue Chain = SDValue()) const;
3240
3241 /// Check whether parameters to a call that are passed in callee saved
3242 /// registers are the same as from the calling function. This needs to be
3243 /// checked for tail call eligibility.
3244 bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
3245 const uint32_t *CallerPreservedMask,
3246 const SmallVectorImpl<CCValAssign> &ArgLocs,
3247 const SmallVectorImpl<SDValue> &OutVals) const;
3248
3249 //===--------------------------------------------------------------------===//
3250 // TargetLowering Optimization Methods
3251 //
3252
3253 /// A convenience struct that encapsulates a DAG, and two SDValues for
3254 /// returning information from TargetLowering to its clients that want to
3255 /// combine.
3256 struct TargetLoweringOpt {
3257 SelectionDAG &DAG;
3258 bool LegalTys;
3259 bool LegalOps;
3260 SDValue Old;
3261 SDValue New;
3262
3263 explicit TargetLoweringOpt(SelectionDAG &InDAG,
3264 bool LT, bool LO) :
3265 DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
3266
3267 bool LegalTypes() const { return LegalTys; }
3268 bool LegalOperations() const { return LegalOps; }
3269
3270 bool CombineTo(SDValue O, SDValue N) {
3271 Old = O;
3272 New = N;
3273 return true;
3274 }
3275 };
3276
3277 /// Determines the optimal series of memory ops to replace the memset / memcpy.
3278 /// Return true if the number of memory ops is below the threshold (Limit).
3279 /// It returns the types of the sequence of memory ops to perform
3280 /// memset / memcpy by reference.
3281 bool findOptimalMemOpLowering(std::vector<EVT> &MemOps, unsigned Limit,
3282 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
3283 const AttributeList &FuncAttributes) const;
3284
3285 /// Check to see if the specified operand of the specified instruction is a
3286 /// constant integer. If so, check to see if there are any bits set in the
3287 /// constant that are not demanded. If so, shrink the constant and return
3288 /// true.
3289 bool ShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits,
3290 const APInt &DemandedElts,
3291 TargetLoweringOpt &TLO) const;
3292
3293 /// Helper wrapper around ShrinkDemandedConstant, demanding all elements.
3294 bool ShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits,
3295 TargetLoweringOpt &TLO) const;
3296
3297 // Target hook to do target-specific const optimization, which is called by
3298 // ShrinkDemandedConstant. This function should return true if the target
3299 // doesn't want ShrinkDemandedConstant to further optimize the constant.
3300 virtual bool targetShrinkDemandedConstant(SDValue Op,
3301 const APInt &DemandedBits,
3302 const APInt &DemandedElts,
3303 TargetLoweringOpt &TLO) const {
3304 return false;
3305 }
3306
3307 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
3308 /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
3309 /// generalized for targets with other types of implicit widening casts.
3310 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
3311 TargetLoweringOpt &TLO) const;
3312
3313 /// Look at Op. At this point, we know that only the DemandedBits bits of the
3314 /// result of Op are ever used downstream. If we can use this information to
3315 /// simplify Op, create a new simplified DAG node and return true, returning
3316 /// the original and new nodes in Old and New. Otherwise, analyze the
3317 /// expression and return a mask of KnownOne and KnownZero bits for the
3318 /// expression (used to simplify the caller). The KnownZero/One bits may only
3319 /// be accurate for those bits in the Demanded masks.
3320 /// \p AssumeSingleUse When this parameter is true, this function will
3321 /// attempt to simplify \p Op even if there are multiple uses.
3322 /// Callers are responsible for correctly updating the DAG based on the
3323 /// results of this function, because simply replacing replacing TLO.Old
3324 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
3325 /// has multiple uses.
3326 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
3327 const APInt &DemandedElts, KnownBits &Known,
3328 TargetLoweringOpt &TLO, unsigned Depth = 0,
3329 bool AssumeSingleUse = false) const;
3330
3331 /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
3332 /// Adds Op back to the worklist upon success.
3333 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
3334 KnownBits &Known, TargetLoweringOpt &TLO,
3335 unsigned Depth = 0,
3336 bool AssumeSingleUse = false) const;
3337
3338 /// Helper wrapper around SimplifyDemandedBits.
3339 /// Adds Op back to the worklist upon success.
3340 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
3341 DAGCombinerInfo &DCI) const;
3342
3343 /// More limited version of SimplifyDemandedBits that can be used to "look
3344 /// through" ops that don't contribute to the DemandedBits/DemandedElts -
3345 /// bitwise ops etc.
3346 SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
3347 const APInt &DemandedElts,
3348 SelectionDAG &DAG,
3349 unsigned Depth) const;
3350
3351 /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
3352 /// elements.
3353 SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
3354 SelectionDAG &DAG,
3355 unsigned Depth = 0) const;
3356
3357 /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
3358 /// bits from only some vector elements.
3359 SDValue SimplifyMultipleUseDemandedVectorElts(SDValue Op,
3360 const APInt &DemandedElts,
3361 SelectionDAG &DAG,
3362 unsigned Depth = 0) const;
3363
3364 /// Look at Vector Op. At this point, we know that only the DemandedElts
3365 /// elements of the result of Op are ever used downstream. If we can use
3366 /// this information to simplify Op, create a new simplified DAG node and
3367 /// return true, storing the original and new nodes in TLO.
3368 /// Otherwise, analyze the expression and return a mask of KnownUndef and
3369 /// KnownZero elements for the expression (used to simplify the caller).
3370 /// The KnownUndef/Zero elements may only be accurate for those bits
3371 /// in the DemandedMask.
3372 /// \p AssumeSingleUse When this parameter is true, this function will
3373 /// attempt to simplify \p Op even if there are multiple uses.
3374 /// Callers are responsible for correctly updating the DAG based on the
3375 /// results of this function, because simply replacing replacing TLO.Old
3376 /// with TLO.New will be incorrect when this parameter is true and TLO.Old
3377 /// has multiple uses.
3378 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
3379 APInt &KnownUndef, APInt &KnownZero,
3380 TargetLoweringOpt &TLO, unsigned Depth = 0,
3381 bool AssumeSingleUse = false) const;
3382
3383 /// Helper wrapper around SimplifyDemandedVectorElts.
3384 /// Adds Op back to the worklist upon success.
3385 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
3386 APInt &KnownUndef, APInt &KnownZero,
3387 DAGCombinerInfo &DCI) const;
3388
3389 /// Determine which of the bits specified in Mask are known to be either zero
3390 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3391 /// argument allows us to only collect the known bits that are shared by the
3392 /// requested vector elements.
3393 virtual void computeKnownBitsForTargetNode(const SDValue Op,
3394 KnownBits &Known,
3395 const APInt &DemandedElts,
3396 const SelectionDAG &DAG,
3397 unsigned Depth = 0) const;
3398
3399 /// Determine which of the bits specified in Mask are known to be either zero
3400 /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
3401 /// argument allows us to only collect the known bits that are shared by the
3402 /// requested vector elements. This is for GISel.
3403 virtual void computeKnownBitsForTargetInstr(GISelKnownBits &Analysis,
3404 Register R, KnownBits &Known,
3405 const APInt &DemandedElts,
3406 const MachineRegisterInfo &MRI,
3407 unsigned Depth = 0) const;
3408
3409 /// Determine the known alignment for the pointer value \p R. This is can
3410 /// typically be inferred from the number of low known 0 bits. However, for a
3411 /// pointer with a non-integral address space, the alignment value may be
3412 /// independent from the known low bits.
3413 virtual Align computeKnownAlignForTargetInstr(GISelKnownBits &Analysis,
3414 Register R,
3415 const MachineRegisterInfo &MRI,
3416 unsigned Depth = 0) const;
3417
3418 /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
3419 /// Default implementation computes low bits based on alignment
3420 /// information. This should preserve known bits passed into it.
3421 virtual void computeKnownBitsForFrameIndex(int FIOp,
3422 KnownBits &Known,
3423 const MachineFunction &MF) const;
3424
3425 /// This method can be implemented by targets that want to expose additional
3426 /// information about sign bits to the DAG Combiner. The DemandedElts
3427 /// argument allows us to only collect the minimum sign bits that are shared
3428 /// by the requested vector elements.
3429 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
3430 const APInt &DemandedElts,
3431 const SelectionDAG &DAG,
3432 unsigned Depth = 0) const;
3433
3434 /// This method can be implemented by targets that want to expose additional
3435 /// information about sign bits to GlobalISel combiners. The DemandedElts
3436 /// argument allows us to only collect the minimum sign bits that are shared
3437 /// by the requested vector elements.
3438 virtual unsigned computeNumSignBitsForTargetInstr(GISelKnownBits &Analysis,
3439 Register R,
3440 const APInt &DemandedElts,
3441 const MachineRegisterInfo &MRI,
3442 unsigned Depth = 0) const;
3443
3444 /// Attempt to simplify any target nodes based on the demanded vector
3445 /// elements, returning true on success. Otherwise, analyze the expression and
3446 /// return a mask of KnownUndef and KnownZero elements for the expression
3447 /// (used to simplify the caller). The KnownUndef/Zero elements may only be
3448 /// accurate for those bits in the DemandedMask.
3449 virtual bool SimplifyDemandedVectorEltsForTargetNode(
3450 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
3451 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
3452
3453 /// Attempt to simplify any target nodes based on the demanded bits/elts,
3454 /// returning true on success. Otherwise, analyze the
3455 /// expression and return a mask of KnownOne and KnownZero bits for the
3456 /// expression (used to simplify the caller). The KnownZero/One bits may only
3457 /// be accurate for those bits in the Demanded masks.
3458 virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op,
3459 const APInt &DemandedBits,
3460 const APInt &DemandedElts,
3461 KnownBits &Known,
3462 TargetLoweringOpt &TLO,
3463 unsigned Depth = 0) const;
3464
3465 /// More limited version of SimplifyDemandedBits that can be used to "look
3466 /// through" ops that don't contribute to the DemandedBits/DemandedElts -
3467 /// bitwise ops etc.
3468 virtual SDValue SimplifyMultipleUseDemandedBitsForTargetNode(
3469 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3470 SelectionDAG &DAG, unsigned Depth) const;
3471
3472 /// Tries to build a legal vector shuffle using the provided parameters
3473 /// or equivalent variations. The Mask argument maybe be modified as the
3474 /// function tries different variations.
3475 /// Returns an empty SDValue if the operation fails.
3476 SDValue buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
3477 SDValue N1, MutableArrayRef<int> Mask,
3478 SelectionDAG &DAG) const;
3479
3480 /// This method returns the constant pool value that will be loaded by LD.
3481 /// NOTE: You must check for implicit extensions of the constant by LD.
3482 virtual const Constant *getTargetConstantFromLoad(LoadSDNode *LD) const;
3483
3484 /// If \p SNaN is false, \returns true if \p Op is known to never be any
3485 /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
3486 /// NaN.
3487 virtual bool isKnownNeverNaNForTargetNode(SDValue Op,
3488 const SelectionDAG &DAG,
3489 bool SNaN = false,
3490 unsigned Depth = 0) const;
3491 struct DAGCombinerInfo {
3492 void *DC; // The DAG Combiner object.
3493 CombineLevel Level;
3494 bool CalledByLegalizer;
3495
3496 public:
3497 SelectionDAG &DAG;
3498
3499 DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
3500 : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
3501
3502 bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
3503 bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
3504 bool isAfterLegalizeDAG() const { return Level >= AfterLegalizeDAG; }
3505 CombineLevel getDAGCombineLevel() { return Level; }
3506 bool isCalledByLegalizer() const { return CalledByLegalizer; }
3507
3508 void AddToWorklist(SDNode *N);
3509 SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
3510 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
3511 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
3512
3513 bool recursivelyDeleteUnusedNodes(SDNode *N);
3514
3515 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
3516 };
3517
3518 /// Return if the N is a constant or constant vector equal to the true value
3519 /// from getBooleanContents().
3520 bool isConstTrueVal(const SDNode *N) const;
3521
3522 /// Return if the N is a constant or constant vector equal to the false value
3523 /// from getBooleanContents().
3524 bool isConstFalseVal(const SDNode *N) const;
3525
3526 /// Return if \p N is a True value when extended to \p VT.
3527 bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
3528
3529 /// Try to simplify a setcc built with the specified operands and cc. If it is
3530 /// unable to simplify it, return a null SDValue.
3531 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
3532 bool foldBooleans, DAGCombinerInfo &DCI,
3533 const SDLoc &dl) const;