1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
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
7 //===----------------------------------------------------------------------===//
9 // This implements the TargetLowering class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/TargetLowering.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/CodeGen/CallingConvLower.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineJumpTableInfo.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/CodeGen/TargetRegisterInfo.h"
22 #include "llvm/CodeGen/TargetSubtargetInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/KnownBits.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
37 /// NOTE: The TargetMachine owns TLOF.
38 TargetLowering::TargetLowering(const TargetMachine
&tm
)
39 : TargetLoweringBase(tm
) {}
41 const char *TargetLowering::getTargetNodeName(unsigned Opcode
) const {
45 bool TargetLowering::isPositionIndependent() const {
46 return getTargetMachine().isPositionIndependent();
49 /// Check whether a given call node is in tail position within its function. If
50 /// so, it sets Chain to the input chain of the tail call.
51 bool TargetLowering::isInTailCallPosition(SelectionDAG
&DAG
, SDNode
*Node
,
52 SDValue
&Chain
) const {
53 const Function
&F
= DAG
.getMachineFunction().getFunction();
55 // Conservatively require the attributes of the call to match those of
56 // the return. Ignore NoAlias and NonNull because they don't affect the
58 AttributeList CallerAttrs
= F
.getAttributes();
59 if (AttrBuilder(CallerAttrs
, AttributeList::ReturnIndex
)
60 .removeAttribute(Attribute::NoAlias
)
61 .removeAttribute(Attribute::NonNull
)
65 // It's not safe to eliminate the sign / zero extension of the return value.
66 if (CallerAttrs
.hasAttribute(AttributeList::ReturnIndex
, Attribute::ZExt
) ||
67 CallerAttrs
.hasAttribute(AttributeList::ReturnIndex
, Attribute::SExt
))
70 // Check if the only use is a function return node.
71 return isUsedByReturnOnly(Node
, Chain
);
74 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo
&MRI
,
75 const uint32_t *CallerPreservedMask
,
76 const SmallVectorImpl
<CCValAssign
> &ArgLocs
,
77 const SmallVectorImpl
<SDValue
> &OutVals
) const {
78 for (unsigned I
= 0, E
= ArgLocs
.size(); I
!= E
; ++I
) {
79 const CCValAssign
&ArgLoc
= ArgLocs
[I
];
80 if (!ArgLoc
.isRegLoc())
82 Register Reg
= ArgLoc
.getLocReg();
83 // Only look at callee saved registers.
84 if (MachineOperand::clobbersPhysReg(CallerPreservedMask
, Reg
))
86 // Check that we pass the value used for the caller.
87 // (We look for a CopyFromReg reading a virtual register that is used
88 // for the function live-in value of register Reg)
89 SDValue Value
= OutVals
[I
];
90 if (Value
->getOpcode() != ISD::CopyFromReg
)
92 unsigned ArgReg
= cast
<RegisterSDNode
>(Value
->getOperand(1))->getReg();
93 if (MRI
.getLiveInPhysReg(ArgReg
) != Reg
)
99 /// Set CallLoweringInfo attribute flags based on a call instruction
100 /// and called function attributes.
101 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase
*Call
,
103 IsSExt
= Call
->paramHasAttr(ArgIdx
, Attribute::SExt
);
104 IsZExt
= Call
->paramHasAttr(ArgIdx
, Attribute::ZExt
);
105 IsInReg
= Call
->paramHasAttr(ArgIdx
, Attribute::InReg
);
106 IsSRet
= Call
->paramHasAttr(ArgIdx
, Attribute::StructRet
);
107 IsNest
= Call
->paramHasAttr(ArgIdx
, Attribute::Nest
);
108 IsByVal
= Call
->paramHasAttr(ArgIdx
, Attribute::ByVal
);
109 IsInAlloca
= Call
->paramHasAttr(ArgIdx
, Attribute::InAlloca
);
110 IsReturned
= Call
->paramHasAttr(ArgIdx
, Attribute::Returned
);
111 IsSwiftSelf
= Call
->paramHasAttr(ArgIdx
, Attribute::SwiftSelf
);
112 IsSwiftError
= Call
->paramHasAttr(ArgIdx
, Attribute::SwiftError
);
113 Alignment
= Call
->getParamAlignment(ArgIdx
);
115 if (Call
->paramHasAttr(ArgIdx
, Attribute::ByVal
))
116 ByValType
= Call
->getParamByValType(ArgIdx
);
119 /// Generate a libcall taking the given operands as arguments and returning a
120 /// result of type RetVT.
121 std::pair
<SDValue
, SDValue
>
122 TargetLowering::makeLibCall(SelectionDAG
&DAG
, RTLIB::Libcall LC
, EVT RetVT
,
123 ArrayRef
<SDValue
> Ops
,
124 MakeLibCallOptions CallOptions
,
125 const SDLoc
&dl
) const {
126 TargetLowering::ArgListTy Args
;
127 Args
.reserve(Ops
.size());
129 TargetLowering::ArgListEntry Entry
;
130 for (unsigned i
= 0; i
< Ops
.size(); ++i
) {
131 SDValue NewOp
= Ops
[i
];
133 Entry
.Ty
= Entry
.Node
.getValueType().getTypeForEVT(*DAG
.getContext());
134 Entry
.IsSExt
= shouldSignExtendTypeInLibCall(NewOp
.getValueType(),
136 Entry
.IsZExt
= !Entry
.IsSExt
;
138 if (CallOptions
.IsSoften
&&
139 !shouldExtendTypeInLibCall(CallOptions
.OpsVTBeforeSoften
[i
])) {
140 Entry
.IsSExt
= Entry
.IsZExt
= false;
142 Args
.push_back(Entry
);
145 if (LC
== RTLIB::UNKNOWN_LIBCALL
)
146 report_fatal_error("Unsupported library call operation!");
147 SDValue Callee
= DAG
.getExternalSymbol(getLibcallName(LC
),
148 getPointerTy(DAG
.getDataLayout()));
150 Type
*RetTy
= RetVT
.getTypeForEVT(*DAG
.getContext());
151 TargetLowering::CallLoweringInfo
CLI(DAG
);
152 bool signExtend
= shouldSignExtendTypeInLibCall(RetVT
, CallOptions
.IsSExt
);
153 bool zeroExtend
= !signExtend
;
155 if (CallOptions
.IsSoften
&&
156 !shouldExtendTypeInLibCall(CallOptions
.RetVTBeforeSoften
)) {
157 signExtend
= zeroExtend
= false;
161 .setChain(DAG
.getEntryNode())
162 .setLibCallee(getLibcallCallingConv(LC
), RetTy
, Callee
, std::move(Args
))
163 .setNoReturn(CallOptions
.DoesNotReturn
)
164 .setDiscardResult(!CallOptions
.IsReturnValueUsed
)
165 .setIsPostTypeLegalization(CallOptions
.IsPostTypeLegalization
)
166 .setSExtResult(signExtend
)
167 .setZExtResult(zeroExtend
);
168 return LowerCallTo(CLI
);
172 TargetLowering::findOptimalMemOpLowering(std::vector
<EVT
> &MemOps
,
173 unsigned Limit
, uint64_t Size
,
174 unsigned DstAlign
, unsigned SrcAlign
,
179 unsigned DstAS
, unsigned SrcAS
,
180 const AttributeList
&FuncAttributes
) const {
181 // If 'SrcAlign' is zero, that means the memory operation does not need to
182 // load the value, i.e. memset or memcpy from constant string. Otherwise,
183 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
184 // is the specified alignment of the memory operation. If it is zero, that
185 // means it's possible to change the alignment of the destination.
186 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
187 // not need to be loaded.
188 if (!(SrcAlign
== 0 || SrcAlign
>= DstAlign
))
191 EVT VT
= getOptimalMemOpType(Size
, DstAlign
, SrcAlign
,
192 IsMemset
, ZeroMemset
, MemcpyStrSrc
,
195 if (VT
== MVT::Other
) {
196 // Use the largest integer type whose alignment constraints are satisfied.
197 // We only need to check DstAlign here as SrcAlign is always greater or
198 // equal to DstAlign (or zero).
200 while (DstAlign
&& DstAlign
< VT
.getSizeInBits() / 8 &&
201 !allowsMisalignedMemoryAccesses(VT
, DstAS
, DstAlign
))
202 VT
= (MVT::SimpleValueType
)(VT
.getSimpleVT().SimpleTy
- 1);
203 assert(VT
.isInteger());
205 // Find the largest legal integer type.
207 while (!isTypeLegal(LVT
))
208 LVT
= (MVT::SimpleValueType
)(LVT
.SimpleTy
- 1);
209 assert(LVT
.isInteger());
211 // If the type we've chosen is larger than the largest legal integer type
212 // then use that instead.
217 unsigned NumMemOps
= 0;
219 unsigned VTSize
= VT
.getSizeInBits() / 8;
220 while (VTSize
> Size
) {
221 // For now, only use non-vector load / store's for the left-over pieces.
226 if (VT
.isVector() || VT
.isFloatingPoint()) {
227 NewVT
= (VT
.getSizeInBits() > 64) ? MVT::i64
: MVT::i32
;
228 if (isOperationLegalOrCustom(ISD::STORE
, NewVT
) &&
229 isSafeMemOpType(NewVT
.getSimpleVT()))
231 else if (NewVT
== MVT::i64
&&
232 isOperationLegalOrCustom(ISD::STORE
, MVT::f64
) &&
233 isSafeMemOpType(MVT::f64
)) {
234 // i64 is usually not legal on 32-bit targets, but f64 may be.
242 NewVT
= (MVT::SimpleValueType
)(NewVT
.getSimpleVT().SimpleTy
- 1);
243 if (NewVT
== MVT::i8
)
245 } while (!isSafeMemOpType(NewVT
.getSimpleVT()));
247 NewVTSize
= NewVT
.getSizeInBits() / 8;
249 // If the new VT cannot cover all of the remaining bits, then consider
250 // issuing a (or a pair of) unaligned and overlapping load / store.
252 if (NumMemOps
&& AllowOverlap
&& NewVTSize
< Size
&&
253 allowsMisalignedMemoryAccesses(VT
, DstAS
, DstAlign
,
254 MachineMemOperand::MONone
, &Fast
) &&
263 if (++NumMemOps
> Limit
)
266 MemOps
.push_back(VT
);
273 /// Soften the operands of a comparison. This code is shared among BR_CC,
274 /// SELECT_CC, and SETCC handlers.
275 void TargetLowering::softenSetCCOperands(SelectionDAG
&DAG
, EVT VT
,
276 SDValue
&NewLHS
, SDValue
&NewRHS
,
277 ISD::CondCode
&CCCode
,
278 const SDLoc
&dl
, const SDValue OldLHS
,
279 const SDValue OldRHS
) const {
280 assert((VT
== MVT::f32
|| VT
== MVT::f64
|| VT
== MVT::f128
|| VT
== MVT::ppcf128
)
281 && "Unsupported setcc type!");
283 // Expand into one or more soft-fp libcall(s).
284 RTLIB::Libcall LC1
= RTLIB::UNKNOWN_LIBCALL
, LC2
= RTLIB::UNKNOWN_LIBCALL
;
285 bool ShouldInvertCC
= false;
289 LC1
= (VT
== MVT::f32
) ? RTLIB::OEQ_F32
:
290 (VT
== MVT::f64
) ? RTLIB::OEQ_F64
:
291 (VT
== MVT::f128
) ? RTLIB::OEQ_F128
: RTLIB::OEQ_PPCF128
;
295 LC1
= (VT
== MVT::f32
) ? RTLIB::UNE_F32
:
296 (VT
== MVT::f64
) ? RTLIB::UNE_F64
:
297 (VT
== MVT::f128
) ? RTLIB::UNE_F128
: RTLIB::UNE_PPCF128
;
301 LC1
= (VT
== MVT::f32
) ? RTLIB::OGE_F32
:
302 (VT
== MVT::f64
) ? RTLIB::OGE_F64
:
303 (VT
== MVT::f128
) ? RTLIB::OGE_F128
: RTLIB::OGE_PPCF128
;
307 LC1
= (VT
== MVT::f32
) ? RTLIB::OLT_F32
:
308 (VT
== MVT::f64
) ? RTLIB::OLT_F64
:
309 (VT
== MVT::f128
) ? RTLIB::OLT_F128
: RTLIB::OLT_PPCF128
;
313 LC1
= (VT
== MVT::f32
) ? RTLIB::OLE_F32
:
314 (VT
== MVT::f64
) ? RTLIB::OLE_F64
:
315 (VT
== MVT::f128
) ? RTLIB::OLE_F128
: RTLIB::OLE_PPCF128
;
319 LC1
= (VT
== MVT::f32
) ? RTLIB::OGT_F32
:
320 (VT
== MVT::f64
) ? RTLIB::OGT_F64
:
321 (VT
== MVT::f128
) ? RTLIB::OGT_F128
: RTLIB::OGT_PPCF128
;
324 LC1
= (VT
== MVT::f32
) ? RTLIB::UO_F32
:
325 (VT
== MVT::f64
) ? RTLIB::UO_F64
:
326 (VT
== MVT::f128
) ? RTLIB::UO_F128
: RTLIB::UO_PPCF128
;
329 LC1
= (VT
== MVT::f32
) ? RTLIB::O_F32
:
330 (VT
== MVT::f64
) ? RTLIB::O_F64
:
331 (VT
== MVT::f128
) ? RTLIB::O_F128
: RTLIB::O_PPCF128
;
334 // SETONE = SETOLT | SETOGT
335 LC1
= (VT
== MVT::f32
) ? RTLIB::OLT_F32
:
336 (VT
== MVT::f64
) ? RTLIB::OLT_F64
:
337 (VT
== MVT::f128
) ? RTLIB::OLT_F128
: RTLIB::OLT_PPCF128
;
338 LC2
= (VT
== MVT::f32
) ? RTLIB::OGT_F32
:
339 (VT
== MVT::f64
) ? RTLIB::OGT_F64
:
340 (VT
== MVT::f128
) ? RTLIB::OGT_F128
: RTLIB::OGT_PPCF128
;
343 LC1
= (VT
== MVT::f32
) ? RTLIB::UO_F32
:
344 (VT
== MVT::f64
) ? RTLIB::UO_F64
:
345 (VT
== MVT::f128
) ? RTLIB::UO_F128
: RTLIB::UO_PPCF128
;
346 LC2
= (VT
== MVT::f32
) ? RTLIB::OEQ_F32
:
347 (VT
== MVT::f64
) ? RTLIB::OEQ_F64
:
348 (VT
== MVT::f128
) ? RTLIB::OEQ_F128
: RTLIB::OEQ_PPCF128
;
351 // Invert CC for unordered comparisons
352 ShouldInvertCC
= true;
355 LC1
= (VT
== MVT::f32
) ? RTLIB::OGE_F32
:
356 (VT
== MVT::f64
) ? RTLIB::OGE_F64
:
357 (VT
== MVT::f128
) ? RTLIB::OGE_F128
: RTLIB::OGE_PPCF128
;
360 LC1
= (VT
== MVT::f32
) ? RTLIB::OGT_F32
:
361 (VT
== MVT::f64
) ? RTLIB::OGT_F64
:
362 (VT
== MVT::f128
) ? RTLIB::OGT_F128
: RTLIB::OGT_PPCF128
;
365 LC1
= (VT
== MVT::f32
) ? RTLIB::OLE_F32
:
366 (VT
== MVT::f64
) ? RTLIB::OLE_F64
:
367 (VT
== MVT::f128
) ? RTLIB::OLE_F128
: RTLIB::OLE_PPCF128
;
370 LC1
= (VT
== MVT::f32
) ? RTLIB::OLT_F32
:
371 (VT
== MVT::f64
) ? RTLIB::OLT_F64
:
372 (VT
== MVT::f128
) ? RTLIB::OLT_F128
: RTLIB::OLT_PPCF128
;
374 default: llvm_unreachable("Do not know how to soften this setcc!");
378 // Use the target specific return value for comparions lib calls.
379 EVT RetVT
= getCmpLibcallReturnType();
380 SDValue Ops
[2] = {NewLHS
, NewRHS
};
381 TargetLowering::MakeLibCallOptions CallOptions
;
382 EVT OpsVT
[2] = { OldLHS
.getValueType(),
383 OldRHS
.getValueType() };
384 CallOptions
.setTypeListBeforeSoften(OpsVT
, RetVT
, true);
385 NewLHS
= makeLibCall(DAG
, LC1
, RetVT
, Ops
, CallOptions
, dl
).first
;
386 NewRHS
= DAG
.getConstant(0, dl
, RetVT
);
388 CCCode
= getCmpLibcallCC(LC1
);
390 CCCode
= getSetCCInverse(CCCode
, /*isInteger=*/true);
392 if (LC2
!= RTLIB::UNKNOWN_LIBCALL
) {
393 SDValue Tmp
= DAG
.getNode(
395 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), RetVT
),
396 NewLHS
, NewRHS
, DAG
.getCondCode(CCCode
));
397 NewLHS
= makeLibCall(DAG
, LC2
, RetVT
, Ops
, CallOptions
, dl
).first
;
398 NewLHS
= DAG
.getNode(
400 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), RetVT
),
401 NewLHS
, NewRHS
, DAG
.getCondCode(getCmpLibcallCC(LC2
)));
402 NewLHS
= DAG
.getNode(ISD::OR
, dl
, Tmp
.getValueType(), Tmp
, NewLHS
);
407 /// Return the entry encoding for a jump table in the current function. The
408 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
409 unsigned TargetLowering::getJumpTableEncoding() const {
410 // In non-pic modes, just use the address of a block.
411 if (!isPositionIndependent())
412 return MachineJumpTableInfo::EK_BlockAddress
;
414 // In PIC mode, if the target supports a GPRel32 directive, use it.
415 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
416 return MachineJumpTableInfo::EK_GPRel32BlockAddress
;
418 // Otherwise, use a label difference.
419 return MachineJumpTableInfo::EK_LabelDifference32
;
422 SDValue
TargetLowering::getPICJumpTableRelocBase(SDValue Table
,
423 SelectionDAG
&DAG
) const {
424 // If our PIC model is GP relative, use the global offset table as the base.
425 unsigned JTEncoding
= getJumpTableEncoding();
427 if ((JTEncoding
== MachineJumpTableInfo::EK_GPRel64BlockAddress
) ||
428 (JTEncoding
== MachineJumpTableInfo::EK_GPRel32BlockAddress
))
429 return DAG
.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG
.getDataLayout()));
434 /// This returns the relocation base for the given PIC jumptable, the same as
435 /// getPICJumpTableRelocBase, but as an MCExpr.
437 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction
*MF
,
438 unsigned JTI
,MCContext
&Ctx
) const{
439 // The normal PIC reloc base is the label at the start of the jump table.
440 return MCSymbolRefExpr::create(MF
->getJTISymbol(JTI
, Ctx
), Ctx
);
444 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode
*GA
) const {
445 const TargetMachine
&TM
= getTargetMachine();
446 const GlobalValue
*GV
= GA
->getGlobal();
448 // If the address is not even local to this DSO we will have to load it from
449 // a got and then add the offset.
450 if (!TM
.shouldAssumeDSOLocal(*GV
->getParent(), GV
))
453 // If the code is position independent we will have to add a base register.
454 if (isPositionIndependent())
457 // Otherwise we can do it.
461 //===----------------------------------------------------------------------===//
462 // Optimization Methods
463 //===----------------------------------------------------------------------===//
465 /// If the specified instruction has a constant integer operand and there are
466 /// bits set in that constant that are not demanded, then clear those bits and
468 bool TargetLowering::ShrinkDemandedConstant(SDValue Op
, const APInt
&Demanded
,
469 TargetLoweringOpt
&TLO
) const {
471 unsigned Opcode
= Op
.getOpcode();
473 // Do target-specific constant optimization.
474 if (targetShrinkDemandedConstant(Op
, Demanded
, TLO
))
475 return TLO
.New
.getNode();
477 // FIXME: ISD::SELECT, ISD::SELECT_CC
484 auto *Op1C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
488 // If this is a 'not' op, don't touch it because that's a canonical form.
489 const APInt
&C
= Op1C
->getAPIntValue();
490 if (Opcode
== ISD::XOR
&& Demanded
.isSubsetOf(C
))
493 if (!C
.isSubsetOf(Demanded
)) {
494 EVT VT
= Op
.getValueType();
495 SDValue NewC
= TLO
.DAG
.getConstant(Demanded
& C
, DL
, VT
);
496 SDValue NewOp
= TLO
.DAG
.getNode(Opcode
, DL
, VT
, Op
.getOperand(0), NewC
);
497 return TLO
.CombineTo(Op
, NewOp
);
507 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
508 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
509 /// generalized for targets with other types of implicit widening casts.
510 bool TargetLowering::ShrinkDemandedOp(SDValue Op
, unsigned BitWidth
,
511 const APInt
&Demanded
,
512 TargetLoweringOpt
&TLO
) const {
513 assert(Op
.getNumOperands() == 2 &&
514 "ShrinkDemandedOp only supports binary operators!");
515 assert(Op
.getNode()->getNumValues() == 1 &&
516 "ShrinkDemandedOp only supports nodes with one result!");
518 SelectionDAG
&DAG
= TLO
.DAG
;
521 // Early return, as this function cannot handle vector types.
522 if (Op
.getValueType().isVector())
525 // Don't do this if the node has another user, which may require the
527 if (!Op
.getNode()->hasOneUse())
530 // Search for the smallest integer type with free casts to and from
531 // Op's type. For expedience, just check power-of-2 integer types.
532 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
533 unsigned DemandedSize
= Demanded
.getActiveBits();
534 unsigned SmallVTBits
= DemandedSize
;
535 if (!isPowerOf2_32(SmallVTBits
))
536 SmallVTBits
= NextPowerOf2(SmallVTBits
);
537 for (; SmallVTBits
< BitWidth
; SmallVTBits
= NextPowerOf2(SmallVTBits
)) {
538 EVT SmallVT
= EVT::getIntegerVT(*DAG
.getContext(), SmallVTBits
);
539 if (TLI
.isTruncateFree(Op
.getValueType(), SmallVT
) &&
540 TLI
.isZExtFree(SmallVT
, Op
.getValueType())) {
541 // We found a type with free casts.
542 SDValue X
= DAG
.getNode(
543 Op
.getOpcode(), dl
, SmallVT
,
544 DAG
.getNode(ISD::TRUNCATE
, dl
, SmallVT
, Op
.getOperand(0)),
545 DAG
.getNode(ISD::TRUNCATE
, dl
, SmallVT
, Op
.getOperand(1)));
546 assert(DemandedSize
<= SmallVTBits
&& "Narrowed below demanded bits?");
547 SDValue Z
= DAG
.getNode(ISD::ANY_EXTEND
, dl
, Op
.getValueType(), X
);
548 return TLO
.CombineTo(Op
, Z
);
554 bool TargetLowering::SimplifyDemandedBits(SDValue Op
, const APInt
&DemandedBits
,
555 DAGCombinerInfo
&DCI
) const {
556 SelectionDAG
&DAG
= DCI
.DAG
;
557 TargetLoweringOpt
TLO(DAG
, !DCI
.isBeforeLegalize(),
558 !DCI
.isBeforeLegalizeOps());
561 bool Simplified
= SimplifyDemandedBits(Op
, DemandedBits
, Known
, TLO
);
563 DCI
.AddToWorklist(Op
.getNode());
564 DCI
.CommitTargetLoweringOpt(TLO
);
569 bool TargetLowering::SimplifyDemandedBits(SDValue Op
, const APInt
&DemandedBits
,
571 TargetLoweringOpt
&TLO
,
573 bool AssumeSingleUse
) const {
574 EVT VT
= Op
.getValueType();
575 APInt DemandedElts
= VT
.isVector()
576 ? APInt::getAllOnesValue(VT
.getVectorNumElements())
578 return SimplifyDemandedBits(Op
, DemandedBits
, DemandedElts
, Known
, TLO
, Depth
,
582 // TODO: Can we merge SelectionDAG::GetDemandedBits into this?
583 // TODO: Under what circumstances can we create nodes? Constant folding?
584 SDValue
TargetLowering::SimplifyMultipleUseDemandedBits(
585 SDValue Op
, const APInt
&DemandedBits
, const APInt
&DemandedElts
,
586 SelectionDAG
&DAG
, unsigned Depth
) const {
587 // Limit search depth.
595 // Not demanding any bits/elts from Op.
596 if (DemandedBits
== 0 || DemandedElts
== 0)
597 return DAG
.getUNDEF(Op
.getValueType());
599 unsigned NumElts
= DemandedElts
.getBitWidth();
600 KnownBits LHSKnown
, RHSKnown
;
601 switch (Op
.getOpcode()) {
603 SDValue Src
= peekThroughBitcasts(Op
.getOperand(0));
604 EVT SrcVT
= Src
.getValueType();
605 EVT DstVT
= Op
.getValueType();
606 unsigned NumSrcEltBits
= SrcVT
.getScalarSizeInBits();
607 unsigned NumDstEltBits
= DstVT
.getScalarSizeInBits();
609 if (NumSrcEltBits
== NumDstEltBits
)
610 if (SDValue V
= SimplifyMultipleUseDemandedBits(
611 Src
, DemandedBits
, DemandedElts
, DAG
, Depth
+ 1))
612 return DAG
.getBitcast(DstVT
, V
);
614 // TODO - bigendian once we have test coverage.
615 if (SrcVT
.isVector() && (NumDstEltBits
% NumSrcEltBits
) == 0 &&
616 DAG
.getDataLayout().isLittleEndian()) {
617 unsigned Scale
= NumDstEltBits
/ NumSrcEltBits
;
618 unsigned NumSrcElts
= SrcVT
.getVectorNumElements();
619 APInt DemandedSrcBits
= APInt::getNullValue(NumSrcEltBits
);
620 APInt DemandedSrcElts
= APInt::getNullValue(NumSrcElts
);
621 for (unsigned i
= 0; i
!= Scale
; ++i
) {
622 unsigned Offset
= i
* NumSrcEltBits
;
623 APInt Sub
= DemandedBits
.extractBits(NumSrcEltBits
, Offset
);
624 if (!Sub
.isNullValue()) {
625 DemandedSrcBits
|= Sub
;
626 for (unsigned j
= 0; j
!= NumElts
; ++j
)
628 DemandedSrcElts
.setBit((j
* Scale
) + i
);
632 if (SDValue V
= SimplifyMultipleUseDemandedBits(
633 Src
, DemandedSrcBits
, DemandedSrcElts
, DAG
, Depth
+ 1))
634 return DAG
.getBitcast(DstVT
, V
);
637 // TODO - bigendian once we have test coverage.
638 if ((NumSrcEltBits
% NumDstEltBits
) == 0 &&
639 DAG
.getDataLayout().isLittleEndian()) {
640 unsigned Scale
= NumSrcEltBits
/ NumDstEltBits
;
641 unsigned NumSrcElts
= SrcVT
.isVector() ? SrcVT
.getVectorNumElements() : 1;
642 APInt DemandedSrcBits
= APInt::getNullValue(NumSrcEltBits
);
643 APInt DemandedSrcElts
= APInt::getNullValue(NumSrcElts
);
644 for (unsigned i
= 0; i
!= NumElts
; ++i
)
645 if (DemandedElts
[i
]) {
646 unsigned Offset
= (i
% Scale
) * NumDstEltBits
;
647 DemandedSrcBits
.insertBits(DemandedBits
, Offset
);
648 DemandedSrcElts
.setBit(i
/ Scale
);
651 if (SDValue V
= SimplifyMultipleUseDemandedBits(
652 Src
, DemandedSrcBits
, DemandedSrcElts
, DAG
, Depth
+ 1))
653 return DAG
.getBitcast(DstVT
, V
);
659 LHSKnown
= DAG
.computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
660 RHSKnown
= DAG
.computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
662 // If all of the demanded bits are known 1 on one side, return the other.
663 // These bits cannot contribute to the result of the 'and' in this
665 if (DemandedBits
.isSubsetOf(LHSKnown
.Zero
| RHSKnown
.One
))
666 return Op
.getOperand(0);
667 if (DemandedBits
.isSubsetOf(RHSKnown
.Zero
| LHSKnown
.One
))
668 return Op
.getOperand(1);
672 LHSKnown
= DAG
.computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
673 RHSKnown
= DAG
.computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
675 // If all of the demanded bits are known zero on one side, return the
676 // other. These bits cannot contribute to the result of the 'or' in this
678 if (DemandedBits
.isSubsetOf(LHSKnown
.One
| RHSKnown
.Zero
))
679 return Op
.getOperand(0);
680 if (DemandedBits
.isSubsetOf(RHSKnown
.One
| LHSKnown
.Zero
))
681 return Op
.getOperand(1);
685 LHSKnown
= DAG
.computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
686 RHSKnown
= DAG
.computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
688 // If all of the demanded bits are known zero on one side, return the
690 if (DemandedBits
.isSubsetOf(RHSKnown
.Zero
))
691 return Op
.getOperand(0);
692 if (DemandedBits
.isSubsetOf(LHSKnown
.Zero
))
693 return Op
.getOperand(1);
696 case ISD::SIGN_EXTEND_INREG
: {
697 // If none of the extended bits are demanded, eliminate the sextinreg.
698 EVT ExVT
= cast
<VTSDNode
>(Op
.getOperand(1))->getVT();
699 if (DemandedBits
.getActiveBits() <= ExVT
.getScalarSizeInBits())
700 return Op
.getOperand(0);
703 case ISD::INSERT_VECTOR_ELT
: {
704 // If we don't demand the inserted element, return the base vector.
705 SDValue Vec
= Op
.getOperand(0);
706 auto *CIdx
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(2));
707 EVT VecVT
= Vec
.getValueType();
708 if (CIdx
&& CIdx
->getAPIntValue().ult(VecVT
.getVectorNumElements()) &&
709 !DemandedElts
[CIdx
->getZExtValue()])
713 case ISD::VECTOR_SHUFFLE
: {
714 ArrayRef
<int> ShuffleMask
= cast
<ShuffleVectorSDNode
>(Op
)->getMask();
716 // If all the demanded elts are from one operand and are inline,
717 // then we can use the operand directly.
718 bool AllUndef
= true, IdentityLHS
= true, IdentityRHS
= true;
719 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
720 int M
= ShuffleMask
[i
];
721 if (M
< 0 || !DemandedElts
[i
])
724 IdentityLHS
&= (M
== (int)i
);
725 IdentityRHS
&= ((M
- NumElts
) == i
);
729 return DAG
.getUNDEF(Op
.getValueType());
731 return Op
.getOperand(0);
733 return Op
.getOperand(1);
737 if (Op
.getOpcode() >= ISD::BUILTIN_OP_END
)
738 if (SDValue V
= SimplifyMultipleUseDemandedBitsForTargetNode(
739 Op
, DemandedBits
, DemandedElts
, DAG
, Depth
))
746 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
747 /// result of Op are ever used downstream. If we can use this information to
748 /// simplify Op, create a new simplified DAG node and return true, returning the
749 /// original and new nodes in Old and New. Otherwise, analyze the expression and
750 /// return a mask of Known bits for the expression (used to simplify the
751 /// caller). The Known bits may only be accurate for those bits in the
752 /// OriginalDemandedBits and OriginalDemandedElts.
753 bool TargetLowering::SimplifyDemandedBits(
754 SDValue Op
, const APInt
&OriginalDemandedBits
,
755 const APInt
&OriginalDemandedElts
, KnownBits
&Known
, TargetLoweringOpt
&TLO
,
756 unsigned Depth
, bool AssumeSingleUse
) const {
757 unsigned BitWidth
= OriginalDemandedBits
.getBitWidth();
758 assert(Op
.getScalarValueSizeInBits() == BitWidth
&&
759 "Mask size mismatches value type size!");
761 unsigned NumElts
= OriginalDemandedElts
.getBitWidth();
762 assert((!Op
.getValueType().isVector() ||
763 NumElts
== Op
.getValueType().getVectorNumElements()) &&
764 "Unexpected vector size");
766 APInt DemandedBits
= OriginalDemandedBits
;
767 APInt DemandedElts
= OriginalDemandedElts
;
769 auto &DL
= TLO
.DAG
.getDataLayout();
771 // Don't know anything.
772 Known
= KnownBits(BitWidth
);
778 if (Op
.getOpcode() == ISD::Constant
) {
779 // We know all of the bits for a constant!
780 Known
.One
= cast
<ConstantSDNode
>(Op
)->getAPIntValue();
781 Known
.Zero
= ~Known
.One
;
785 // Other users may use these bits.
786 EVT VT
= Op
.getValueType();
787 if (!Op
.getNode()->hasOneUse() && !AssumeSingleUse
) {
789 // If not at the root, Just compute the Known bits to
790 // simplify things downstream.
791 Known
= TLO
.DAG
.computeKnownBits(Op
, DemandedElts
, Depth
);
794 // If this is the root being simplified, allow it to have multiple uses,
795 // just set the DemandedBits/Elts to all bits.
796 DemandedBits
= APInt::getAllOnesValue(BitWidth
);
797 DemandedElts
= APInt::getAllOnesValue(NumElts
);
798 } else if (OriginalDemandedBits
== 0 || OriginalDemandedElts
== 0) {
799 // Not demanding any bits/elts from Op.
800 return TLO
.CombineTo(Op
, TLO
.DAG
.getUNDEF(VT
));
801 } else if (Depth
>= 6) { // Limit search depth.
805 KnownBits Known2
, KnownOut
;
806 switch (Op
.getOpcode()) {
807 case ISD::SCALAR_TO_VECTOR
: {
808 if (!DemandedElts
[0])
809 return TLO
.CombineTo(Op
, TLO
.DAG
.getUNDEF(VT
));
812 SDValue Src
= Op
.getOperand(0);
813 unsigned SrcBitWidth
= Src
.getScalarValueSizeInBits();
814 APInt SrcDemandedBits
= DemandedBits
.zextOrSelf(SrcBitWidth
);
815 if (SimplifyDemandedBits(Src
, SrcDemandedBits
, SrcKnown
, TLO
, Depth
+ 1))
817 Known
= SrcKnown
.zextOrTrunc(BitWidth
, false);
820 case ISD::BUILD_VECTOR
:
821 // Collect the known bits that are shared by every demanded element.
822 // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
823 Known
= TLO
.DAG
.computeKnownBits(Op
, DemandedElts
, Depth
);
824 return false; // Don't fall through, will infinitely loop.
826 LoadSDNode
*LD
= cast
<LoadSDNode
>(Op
);
827 if (getTargetConstantFromLoad(LD
)) {
828 Known
= TLO
.DAG
.computeKnownBits(Op
, DemandedElts
, Depth
);
829 return false; // Don't fall through, will infinitely loop.
833 case ISD::INSERT_VECTOR_ELT
: {
834 SDValue Vec
= Op
.getOperand(0);
835 SDValue Scl
= Op
.getOperand(1);
836 auto *CIdx
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(2));
837 EVT VecVT
= Vec
.getValueType();
839 // If index isn't constant, assume we need all vector elements AND the
841 APInt
DemandedVecElts(DemandedElts
);
842 if (CIdx
&& CIdx
->getAPIntValue().ult(VecVT
.getVectorNumElements())) {
843 unsigned Idx
= CIdx
->getZExtValue();
844 DemandedVecElts
.clearBit(Idx
);
846 // Inserted element is not required.
847 if (!DemandedElts
[Idx
])
848 return TLO
.CombineTo(Op
, Vec
);
852 unsigned NumSclBits
= Scl
.getScalarValueSizeInBits();
853 APInt DemandedSclBits
= DemandedBits
.zextOrTrunc(NumSclBits
);
854 if (SimplifyDemandedBits(Scl
, DemandedSclBits
, KnownScl
, TLO
, Depth
+ 1))
857 Known
= KnownScl
.zextOrTrunc(BitWidth
, false);
860 if (SimplifyDemandedBits(Vec
, DemandedBits
, DemandedVecElts
, KnownVec
, TLO
,
864 if (!!DemandedVecElts
) {
865 Known
.One
&= KnownVec
.One
;
866 Known
.Zero
&= KnownVec
.Zero
;
871 case ISD::INSERT_SUBVECTOR
: {
872 SDValue Base
= Op
.getOperand(0);
873 SDValue Sub
= Op
.getOperand(1);
874 EVT SubVT
= Sub
.getValueType();
875 unsigned NumSubElts
= SubVT
.getVectorNumElements();
877 // If index isn't constant, assume we need the original demanded base
878 // elements and ALL the inserted subvector elements.
879 APInt BaseElts
= DemandedElts
;
880 APInt SubElts
= APInt::getAllOnesValue(NumSubElts
);
881 if (isa
<ConstantSDNode
>(Op
.getOperand(2))) {
882 const APInt
&Idx
= Op
.getConstantOperandAPInt(2);
883 if (Idx
.ule(NumElts
- NumSubElts
)) {
884 unsigned SubIdx
= Idx
.getZExtValue();
885 SubElts
= DemandedElts
.extractBits(NumSubElts
, SubIdx
);
886 BaseElts
.insertBits(APInt::getNullValue(NumSubElts
), SubIdx
);
890 KnownBits KnownSub
, KnownBase
;
891 if (SimplifyDemandedBits(Sub
, DemandedBits
, SubElts
, KnownSub
, TLO
,
894 if (SimplifyDemandedBits(Base
, DemandedBits
, BaseElts
, KnownBase
, TLO
,
898 Known
.Zero
.setAllBits();
899 Known
.One
.setAllBits();
901 Known
.One
&= KnownSub
.One
;
902 Known
.Zero
&= KnownSub
.Zero
;
905 Known
.One
&= KnownBase
.One
;
906 Known
.Zero
&= KnownBase
.Zero
;
910 case ISD::CONCAT_VECTORS
: {
911 Known
.Zero
.setAllBits();
912 Known
.One
.setAllBits();
913 EVT SubVT
= Op
.getOperand(0).getValueType();
914 unsigned NumSubVecs
= Op
.getNumOperands();
915 unsigned NumSubElts
= SubVT
.getVectorNumElements();
916 for (unsigned i
= 0; i
!= NumSubVecs
; ++i
) {
917 APInt DemandedSubElts
=
918 DemandedElts
.extractBits(NumSubElts
, i
* NumSubElts
);
919 if (SimplifyDemandedBits(Op
.getOperand(i
), DemandedBits
, DemandedSubElts
,
920 Known2
, TLO
, Depth
+ 1))
922 // Known bits are shared by every demanded subvector element.
923 if (!!DemandedSubElts
) {
924 Known
.One
&= Known2
.One
;
925 Known
.Zero
&= Known2
.Zero
;
930 case ISD::VECTOR_SHUFFLE
: {
931 ArrayRef
<int> ShuffleMask
= cast
<ShuffleVectorSDNode
>(Op
)->getMask();
933 // Collect demanded elements from shuffle operands..
934 APInt
DemandedLHS(NumElts
, 0);
935 APInt
DemandedRHS(NumElts
, 0);
936 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
937 if (!DemandedElts
[i
])
939 int M
= ShuffleMask
[i
];
941 // For UNDEF elements, we don't know anything about the common state of
942 // the shuffle result.
943 DemandedLHS
.clearAllBits();
944 DemandedRHS
.clearAllBits();
947 assert(0 <= M
&& M
< (int)(2 * NumElts
) && "Shuffle index out of range");
948 if (M
< (int)NumElts
)
949 DemandedLHS
.setBit(M
);
951 DemandedRHS
.setBit(M
- NumElts
);
954 if (!!DemandedLHS
|| !!DemandedRHS
) {
955 SDValue Op0
= Op
.getOperand(0);
956 SDValue Op1
= Op
.getOperand(1);
958 Known
.Zero
.setAllBits();
959 Known
.One
.setAllBits();
961 if (SimplifyDemandedBits(Op0
, DemandedBits
, DemandedLHS
, Known2
, TLO
,
964 Known
.One
&= Known2
.One
;
965 Known
.Zero
&= Known2
.Zero
;
968 if (SimplifyDemandedBits(Op1
, DemandedBits
, DemandedRHS
, Known2
, TLO
,
971 Known
.One
&= Known2
.One
;
972 Known
.Zero
&= Known2
.Zero
;
975 // Attempt to avoid multi-use ops if we don't need anything from them.
976 SDValue DemandedOp0
= SimplifyMultipleUseDemandedBits(
977 Op0
, DemandedBits
, DemandedLHS
, TLO
.DAG
, Depth
+ 1);
978 SDValue DemandedOp1
= SimplifyMultipleUseDemandedBits(
979 Op1
, DemandedBits
, DemandedRHS
, TLO
.DAG
, Depth
+ 1);
980 if (DemandedOp0
|| DemandedOp1
) {
981 Op0
= DemandedOp0
? DemandedOp0
: Op0
;
982 Op1
= DemandedOp1
? DemandedOp1
: Op1
;
983 SDValue NewOp
= TLO
.DAG
.getVectorShuffle(VT
, dl
, Op0
, Op1
, ShuffleMask
);
984 return TLO
.CombineTo(Op
, NewOp
);
990 SDValue Op0
= Op
.getOperand(0);
991 SDValue Op1
= Op
.getOperand(1);
993 // If the RHS is a constant, check to see if the LHS would be zero without
994 // using the bits from the RHS. Below, we use knowledge about the RHS to
995 // simplify the LHS, here we're using information from the LHS to simplify
997 if (ConstantSDNode
*RHSC
= isConstOrConstSplat(Op1
)) {
998 // Do not increment Depth here; that can cause an infinite loop.
999 KnownBits LHSKnown
= TLO
.DAG
.computeKnownBits(Op0
, DemandedElts
, Depth
);
1000 // If the LHS already has zeros where RHSC does, this 'and' is dead.
1001 if ((LHSKnown
.Zero
& DemandedBits
) ==
1002 (~RHSC
->getAPIntValue() & DemandedBits
))
1003 return TLO
.CombineTo(Op
, Op0
);
1005 // If any of the set bits in the RHS are known zero on the LHS, shrink
1007 if (ShrinkDemandedConstant(Op
, ~LHSKnown
.Zero
& DemandedBits
, TLO
))
1010 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1011 // constant, but if this 'and' is only clearing bits that were just set by
1012 // the xor, then this 'and' can be eliminated by shrinking the mask of
1013 // the xor. For example, for a 32-bit X:
1014 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1015 if (isBitwiseNot(Op0
) && Op0
.hasOneUse() &&
1016 LHSKnown
.One
== ~RHSC
->getAPIntValue()) {
1017 SDValue Xor
= TLO
.DAG
.getNode(ISD::XOR
, dl
, VT
, Op0
.getOperand(0), Op1
);
1018 return TLO
.CombineTo(Op
, Xor
);
1022 if (SimplifyDemandedBits(Op1
, DemandedBits
, DemandedElts
, Known
, TLO
,
1025 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1026 if (SimplifyDemandedBits(Op0
, ~Known
.Zero
& DemandedBits
, DemandedElts
,
1027 Known2
, TLO
, Depth
+ 1))
1029 assert(!Known2
.hasConflict() && "Bits known to be one AND zero?");
1031 // Attempt to avoid multi-use ops if we don't need anything from them.
1032 if (!DemandedBits
.isAllOnesValue() || !DemandedElts
.isAllOnesValue()) {
1033 SDValue DemandedOp0
= SimplifyMultipleUseDemandedBits(
1034 Op0
, DemandedBits
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1035 SDValue DemandedOp1
= SimplifyMultipleUseDemandedBits(
1036 Op1
, DemandedBits
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1037 if (DemandedOp0
|| DemandedOp1
) {
1038 Op0
= DemandedOp0
? DemandedOp0
: Op0
;
1039 Op1
= DemandedOp1
? DemandedOp1
: Op1
;
1040 SDValue NewOp
= TLO
.DAG
.getNode(Op
.getOpcode(), dl
, VT
, Op0
, Op1
);
1041 return TLO
.CombineTo(Op
, NewOp
);
1045 // If all of the demanded bits are known one on one side, return the other.
1046 // These bits cannot contribute to the result of the 'and'.
1047 if (DemandedBits
.isSubsetOf(Known2
.Zero
| Known
.One
))
1048 return TLO
.CombineTo(Op
, Op0
);
1049 if (DemandedBits
.isSubsetOf(Known
.Zero
| Known2
.One
))
1050 return TLO
.CombineTo(Op
, Op1
);
1051 // If all of the demanded bits in the inputs are known zeros, return zero.
1052 if (DemandedBits
.isSubsetOf(Known
.Zero
| Known2
.Zero
))
1053 return TLO
.CombineTo(Op
, TLO
.DAG
.getConstant(0, dl
, VT
));
1054 // If the RHS is a constant, see if we can simplify it.
1055 if (ShrinkDemandedConstant(Op
, ~Known2
.Zero
& DemandedBits
, TLO
))
1057 // If the operation can be done in a smaller type, do so.
1058 if (ShrinkDemandedOp(Op
, BitWidth
, DemandedBits
, TLO
))
1061 // Output known-1 bits are only known if set in both the LHS & RHS.
1062 Known
.One
&= Known2
.One
;
1063 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1064 Known
.Zero
|= Known2
.Zero
;
1068 SDValue Op0
= Op
.getOperand(0);
1069 SDValue Op1
= Op
.getOperand(1);
1071 if (SimplifyDemandedBits(Op1
, DemandedBits
, DemandedElts
, Known
, TLO
,
1074 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1075 if (SimplifyDemandedBits(Op0
, ~Known
.One
& DemandedBits
, DemandedElts
,
1076 Known2
, TLO
, Depth
+ 1))
1078 assert(!Known2
.hasConflict() && "Bits known to be one AND zero?");
1080 // Attempt to avoid multi-use ops if we don't need anything from them.
1081 if (!DemandedBits
.isAllOnesValue() || !DemandedElts
.isAllOnesValue()) {
1082 SDValue DemandedOp0
= SimplifyMultipleUseDemandedBits(
1083 Op0
, DemandedBits
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1084 SDValue DemandedOp1
= SimplifyMultipleUseDemandedBits(
1085 Op1
, DemandedBits
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1086 if (DemandedOp0
|| DemandedOp1
) {
1087 Op0
= DemandedOp0
? DemandedOp0
: Op0
;
1088 Op1
= DemandedOp1
? DemandedOp1
: Op1
;
1089 SDValue NewOp
= TLO
.DAG
.getNode(Op
.getOpcode(), dl
, VT
, Op0
, Op1
);
1090 return TLO
.CombineTo(Op
, NewOp
);
1094 // If all of the demanded bits are known zero on one side, return the other.
1095 // These bits cannot contribute to the result of the 'or'.
1096 if (DemandedBits
.isSubsetOf(Known2
.One
| Known
.Zero
))
1097 return TLO
.CombineTo(Op
, Op0
);
1098 if (DemandedBits
.isSubsetOf(Known
.One
| Known2
.Zero
))
1099 return TLO
.CombineTo(Op
, Op1
);
1100 // If the RHS is a constant, see if we can simplify it.
1101 if (ShrinkDemandedConstant(Op
, DemandedBits
, TLO
))
1103 // If the operation can be done in a smaller type, do so.
1104 if (ShrinkDemandedOp(Op
, BitWidth
, DemandedBits
, TLO
))
1107 // Output known-0 bits are only known if clear in both the LHS & RHS.
1108 Known
.Zero
&= Known2
.Zero
;
1109 // Output known-1 are known to be set if set in either the LHS | RHS.
1110 Known
.One
|= Known2
.One
;
1114 SDValue Op0
= Op
.getOperand(0);
1115 SDValue Op1
= Op
.getOperand(1);
1117 if (SimplifyDemandedBits(Op1
, DemandedBits
, DemandedElts
, Known
, TLO
,
1120 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1121 if (SimplifyDemandedBits(Op0
, DemandedBits
, DemandedElts
, Known2
, TLO
,
1124 assert(!Known2
.hasConflict() && "Bits known to be one AND zero?");
1126 // Attempt to avoid multi-use ops if we don't need anything from them.
1127 if (!DemandedBits
.isAllOnesValue() || !DemandedElts
.isAllOnesValue()) {
1128 SDValue DemandedOp0
= SimplifyMultipleUseDemandedBits(
1129 Op0
, DemandedBits
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1130 SDValue DemandedOp1
= SimplifyMultipleUseDemandedBits(
1131 Op1
, DemandedBits
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1132 if (DemandedOp0
|| DemandedOp1
) {
1133 Op0
= DemandedOp0
? DemandedOp0
: Op0
;
1134 Op1
= DemandedOp1
? DemandedOp1
: Op1
;
1135 SDValue NewOp
= TLO
.DAG
.getNode(Op
.getOpcode(), dl
, VT
, Op0
, Op1
);
1136 return TLO
.CombineTo(Op
, NewOp
);
1140 // If all of the demanded bits are known zero on one side, return the other.
1141 // These bits cannot contribute to the result of the 'xor'.
1142 if (DemandedBits
.isSubsetOf(Known
.Zero
))
1143 return TLO
.CombineTo(Op
, Op0
);
1144 if (DemandedBits
.isSubsetOf(Known2
.Zero
))
1145 return TLO
.CombineTo(Op
, Op1
);
1146 // If the operation can be done in a smaller type, do so.
1147 if (ShrinkDemandedOp(Op
, BitWidth
, DemandedBits
, TLO
))
1150 // If all of the unknown bits are known to be zero on one side or the other
1151 // (but not both) turn this into an *inclusive* or.
1152 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1153 if (DemandedBits
.isSubsetOf(Known
.Zero
| Known2
.Zero
))
1154 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(ISD::OR
, dl
, VT
, Op0
, Op1
));
1156 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1157 KnownOut
.Zero
= (Known
.Zero
& Known2
.Zero
) | (Known
.One
& Known2
.One
);
1158 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1159 KnownOut
.One
= (Known
.Zero
& Known2
.One
) | (Known
.One
& Known2
.Zero
);
1161 if (ConstantSDNode
*C
= isConstOrConstSplat(Op1
)) {
1162 // If one side is a constant, and all of the known set bits on the other
1163 // side are also set in the constant, turn this into an AND, as we know
1164 // the bits will be cleared.
1165 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1166 // NB: it is okay if more bits are known than are requested
1167 if (C
->getAPIntValue() == Known2
.One
) {
1169 TLO
.DAG
.getConstant(~C
->getAPIntValue() & DemandedBits
, dl
, VT
);
1170 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(ISD::AND
, dl
, VT
, Op0
, ANDC
));
1173 // If the RHS is a constant, see if we can change it. Don't alter a -1
1174 // constant because that's a 'not' op, and that is better for combining
1176 if (!C
->isAllOnesValue()) {
1177 if (DemandedBits
.isSubsetOf(C
->getAPIntValue())) {
1178 // We're flipping all demanded bits. Flip the undemanded bits too.
1179 SDValue New
= TLO
.DAG
.getNOT(dl
, Op0
, VT
);
1180 return TLO
.CombineTo(Op
, New
);
1182 // If we can't turn this into a 'not', try to shrink the constant.
1183 if (ShrinkDemandedConstant(Op
, DemandedBits
, TLO
))
1188 Known
= std::move(KnownOut
);
1192 if (SimplifyDemandedBits(Op
.getOperand(2), DemandedBits
, Known
, TLO
,
1195 if (SimplifyDemandedBits(Op
.getOperand(1), DemandedBits
, Known2
, TLO
,
1198 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1199 assert(!Known2
.hasConflict() && "Bits known to be one AND zero?");
1201 // If the operands are constants, see if we can simplify them.
1202 if (ShrinkDemandedConstant(Op
, DemandedBits
, TLO
))
1205 // Only known if known in both the LHS and RHS.
1206 Known
.One
&= Known2
.One
;
1207 Known
.Zero
&= Known2
.Zero
;
1209 case ISD::SELECT_CC
:
1210 if (SimplifyDemandedBits(Op
.getOperand(3), DemandedBits
, Known
, TLO
,
1213 if (SimplifyDemandedBits(Op
.getOperand(2), DemandedBits
, Known2
, TLO
,
1216 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1217 assert(!Known2
.hasConflict() && "Bits known to be one AND zero?");
1219 // If the operands are constants, see if we can simplify them.
1220 if (ShrinkDemandedConstant(Op
, DemandedBits
, TLO
))
1223 // Only known if known in both the LHS and RHS.
1224 Known
.One
&= Known2
.One
;
1225 Known
.Zero
&= Known2
.Zero
;
1228 SDValue Op0
= Op
.getOperand(0);
1229 SDValue Op1
= Op
.getOperand(1);
1230 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
1231 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1232 // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1233 // -1, we may be able to bypass the setcc.
1234 if (DemandedBits
.isSignMask() &&
1235 Op0
.getScalarValueSizeInBits() == BitWidth
&&
1236 getBooleanContents(VT
) ==
1237 BooleanContent::ZeroOrNegativeOneBooleanContent
) {
1238 // If we're testing X < 0, then this compare isn't needed - just use X!
1239 // FIXME: We're limiting to integer types here, but this should also work
1240 // if we don't care about FP signed-zero. The use of SETLT with FP means
1241 // that we don't care about NaNs.
1242 if (CC
== ISD::SETLT
&& Op1
.getValueType().isInteger() &&
1243 (isNullConstant(Op1
) || ISD::isBuildVectorAllZeros(Op1
.getNode())))
1244 return TLO
.CombineTo(Op
, Op0
);
1246 // TODO: Should we check for other forms of sign-bit comparisons?
1247 // Examples: X <= -1, X >= 0
1249 if (getBooleanContents(Op0
.getValueType()) ==
1250 TargetLowering::ZeroOrOneBooleanContent
&&
1252 Known
.Zero
.setBitsFrom(1);
1256 SDValue Op0
= Op
.getOperand(0);
1257 SDValue Op1
= Op
.getOperand(1);
1259 if (ConstantSDNode
*SA
= isConstOrConstSplat(Op1
, DemandedElts
)) {
1260 // If the shift count is an invalid immediate, don't do anything.
1261 if (SA
->getAPIntValue().uge(BitWidth
))
1264 unsigned ShAmt
= SA
->getZExtValue();
1266 return TLO
.CombineTo(Op
, Op0
);
1268 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1269 // single shift. We can do this if the bottom bits (which are shifted
1270 // out) are never demanded.
1271 // TODO - support non-uniform vector amounts.
1272 if (Op0
.getOpcode() == ISD::SRL
) {
1273 if ((DemandedBits
& APInt::getLowBitsSet(BitWidth
, ShAmt
)) == 0) {
1274 if (ConstantSDNode
*SA2
=
1275 isConstOrConstSplat(Op0
.getOperand(1), DemandedElts
)) {
1276 if (SA2
->getAPIntValue().ult(BitWidth
)) {
1277 unsigned C1
= SA2
->getZExtValue();
1278 unsigned Opc
= ISD::SHL
;
1279 int Diff
= ShAmt
- C1
;
1285 SDValue NewSA
= TLO
.DAG
.getConstant(Diff
, dl
, Op1
.getValueType());
1286 return TLO
.CombineTo(
1287 Op
, TLO
.DAG
.getNode(Opc
, dl
, VT
, Op0
.getOperand(0), NewSA
));
1293 if (SimplifyDemandedBits(Op0
, DemandedBits
.lshr(ShAmt
), DemandedElts
,
1294 Known
, TLO
, Depth
+ 1))
1297 // Try shrinking the operation as long as the shift amount will still be
1299 if ((ShAmt
< DemandedBits
.getActiveBits()) &&
1300 ShrinkDemandedOp(Op
, BitWidth
, DemandedBits
, TLO
))
1303 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1304 // are not demanded. This will likely allow the anyext to be folded away.
1305 if (Op0
.getOpcode() == ISD::ANY_EXTEND
) {
1306 SDValue InnerOp
= Op0
.getOperand(0);
1307 EVT InnerVT
= InnerOp
.getValueType();
1308 unsigned InnerBits
= InnerVT
.getScalarSizeInBits();
1309 if (ShAmt
< InnerBits
&& DemandedBits
.getActiveBits() <= InnerBits
&&
1310 isTypeDesirableForOp(ISD::SHL
, InnerVT
)) {
1311 EVT ShTy
= getShiftAmountTy(InnerVT
, DL
);
1312 if (!APInt(BitWidth
, ShAmt
).isIntN(ShTy
.getSizeInBits()))
1315 TLO
.DAG
.getNode(ISD::SHL
, dl
, InnerVT
, InnerOp
,
1316 TLO
.DAG
.getConstant(ShAmt
, dl
, ShTy
));
1317 return TLO
.CombineTo(
1318 Op
, TLO
.DAG
.getNode(ISD::ANY_EXTEND
, dl
, VT
, NarrowShl
));
1320 // Repeat the SHL optimization above in cases where an extension
1321 // intervenes: (shl (anyext (shr x, c1)), c2) to
1322 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
1323 // aren't demanded (as above) and that the shifted upper c1 bits of
1324 // x aren't demanded.
1325 if (Op0
.hasOneUse() && InnerOp
.getOpcode() == ISD::SRL
&&
1326 InnerOp
.hasOneUse()) {
1327 if (ConstantSDNode
*SA2
=
1328 isConstOrConstSplat(InnerOp
.getOperand(1))) {
1329 unsigned InnerShAmt
= SA2
->getLimitedValue(InnerBits
);
1330 if (InnerShAmt
< ShAmt
&& InnerShAmt
< InnerBits
&&
1331 DemandedBits
.getActiveBits() <=
1332 (InnerBits
- InnerShAmt
+ ShAmt
) &&
1333 DemandedBits
.countTrailingZeros() >= ShAmt
) {
1334 SDValue NewSA
= TLO
.DAG
.getConstant(ShAmt
- InnerShAmt
, dl
,
1335 Op1
.getValueType());
1336 SDValue NewExt
= TLO
.DAG
.getNode(ISD::ANY_EXTEND
, dl
, VT
,
1337 InnerOp
.getOperand(0));
1338 return TLO
.CombineTo(
1339 Op
, TLO
.DAG
.getNode(ISD::SHL
, dl
, VT
, NewExt
, NewSA
));
1345 Known
.Zero
<<= ShAmt
;
1346 Known
.One
<<= ShAmt
;
1347 // low bits known zero.
1348 Known
.Zero
.setLowBits(ShAmt
);
1353 SDValue Op0
= Op
.getOperand(0);
1354 SDValue Op1
= Op
.getOperand(1);
1356 if (ConstantSDNode
*SA
= isConstOrConstSplat(Op1
, DemandedElts
)) {
1357 // If the shift count is an invalid immediate, don't do anything.
1358 if (SA
->getAPIntValue().uge(BitWidth
))
1361 unsigned ShAmt
= SA
->getZExtValue();
1363 return TLO
.CombineTo(Op
, Op0
);
1365 EVT ShiftVT
= Op1
.getValueType();
1366 APInt InDemandedMask
= (DemandedBits
<< ShAmt
);
1368 // If the shift is exact, then it does demand the low bits (and knows that
1370 if (Op
->getFlags().hasExact())
1371 InDemandedMask
.setLowBits(ShAmt
);
1373 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1374 // single shift. We can do this if the top bits (which are shifted out)
1375 // are never demanded.
1376 // TODO - support non-uniform vector amounts.
1377 if (Op0
.getOpcode() == ISD::SHL
) {
1378 if (ConstantSDNode
*SA2
=
1379 isConstOrConstSplat(Op0
.getOperand(1), DemandedElts
)) {
1380 if ((DemandedBits
& APInt::getHighBitsSet(BitWidth
, ShAmt
)) == 0) {
1381 if (SA2
->getAPIntValue().ult(BitWidth
)) {
1382 unsigned C1
= SA2
->getZExtValue();
1383 unsigned Opc
= ISD::SRL
;
1384 int Diff
= ShAmt
- C1
;
1390 SDValue NewSA
= TLO
.DAG
.getConstant(Diff
, dl
, ShiftVT
);
1391 return TLO
.CombineTo(
1392 Op
, TLO
.DAG
.getNode(Opc
, dl
, VT
, Op0
.getOperand(0), NewSA
));
1398 // Compute the new bits that are at the top now.
1399 if (SimplifyDemandedBits(Op0
, InDemandedMask
, DemandedElts
, Known
, TLO
,
1402 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1403 Known
.Zero
.lshrInPlace(ShAmt
);
1404 Known
.One
.lshrInPlace(ShAmt
);
1406 Known
.Zero
.setHighBits(ShAmt
); // High bits known zero.
1411 SDValue Op0
= Op
.getOperand(0);
1412 SDValue Op1
= Op
.getOperand(1);
1414 // If this is an arithmetic shift right and only the low-bit is set, we can
1415 // always convert this into a logical shr, even if the shift amount is
1416 // variable. The low bit of the shift cannot be an input sign bit unless
1417 // the shift amount is >= the size of the datatype, which is undefined.
1418 if (DemandedBits
.isOneValue())
1419 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(ISD::SRL
, dl
, VT
, Op0
, Op1
));
1421 if (ConstantSDNode
*SA
= isConstOrConstSplat(Op1
, DemandedElts
)) {
1422 // If the shift count is an invalid immediate, don't do anything.
1423 if (SA
->getAPIntValue().uge(BitWidth
))
1426 unsigned ShAmt
= SA
->getZExtValue();
1428 return TLO
.CombineTo(Op
, Op0
);
1430 APInt InDemandedMask
= (DemandedBits
<< ShAmt
);
1432 // If the shift is exact, then it does demand the low bits (and knows that
1434 if (Op
->getFlags().hasExact())
1435 InDemandedMask
.setLowBits(ShAmt
);
1437 // If any of the demanded bits are produced by the sign extension, we also
1438 // demand the input sign bit.
1439 if (DemandedBits
.countLeadingZeros() < ShAmt
)
1440 InDemandedMask
.setSignBit();
1442 if (SimplifyDemandedBits(Op0
, InDemandedMask
, DemandedElts
, Known
, TLO
,
1445 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1446 Known
.Zero
.lshrInPlace(ShAmt
);
1447 Known
.One
.lshrInPlace(ShAmt
);
1449 // If the input sign bit is known to be zero, or if none of the top bits
1450 // are demanded, turn this into an unsigned shift right.
1451 if (Known
.Zero
[BitWidth
- ShAmt
- 1] ||
1452 DemandedBits
.countLeadingZeros() >= ShAmt
) {
1454 Flags
.setExact(Op
->getFlags().hasExact());
1455 return TLO
.CombineTo(
1456 Op
, TLO
.DAG
.getNode(ISD::SRL
, dl
, VT
, Op0
, Op1
, Flags
));
1459 int Log2
= DemandedBits
.exactLogBase2();
1461 // The bit must come from the sign.
1463 TLO
.DAG
.getConstant(BitWidth
- 1 - Log2
, dl
, Op1
.getValueType());
1464 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(ISD::SRL
, dl
, VT
, Op0
, NewSA
));
1467 if (Known
.One
[BitWidth
- ShAmt
- 1])
1468 // New bits are known one.
1469 Known
.One
.setHighBits(ShAmt
);
1475 SDValue Op0
= Op
.getOperand(0);
1476 SDValue Op1
= Op
.getOperand(1);
1477 SDValue Op2
= Op
.getOperand(2);
1478 bool IsFSHL
= (Op
.getOpcode() == ISD::FSHL
);
1480 if (ConstantSDNode
*SA
= isConstOrConstSplat(Op2
, DemandedElts
)) {
1481 unsigned Amt
= SA
->getAPIntValue().urem(BitWidth
);
1483 // For fshl, 0-shift returns the 1st arg.
1484 // For fshr, 0-shift returns the 2nd arg.
1486 if (SimplifyDemandedBits(IsFSHL
? Op0
: Op1
, DemandedBits
, DemandedElts
,
1487 Known
, TLO
, Depth
+ 1))
1492 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
1493 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
1494 APInt Demanded0
= DemandedBits
.lshr(IsFSHL
? Amt
: (BitWidth
- Amt
));
1495 APInt Demanded1
= DemandedBits
<< (IsFSHL
? (BitWidth
- Amt
) : Amt
);
1496 if (SimplifyDemandedBits(Op0
, Demanded0
, DemandedElts
, Known2
, TLO
,
1499 if (SimplifyDemandedBits(Op1
, Demanded1
, DemandedElts
, Known
, TLO
,
1503 Known2
.One
<<= (IsFSHL
? Amt
: (BitWidth
- Amt
));
1504 Known2
.Zero
<<= (IsFSHL
? Amt
: (BitWidth
- Amt
));
1505 Known
.One
.lshrInPlace(IsFSHL
? (BitWidth
- Amt
) : Amt
);
1506 Known
.Zero
.lshrInPlace(IsFSHL
? (BitWidth
- Amt
) : Amt
);
1507 Known
.One
|= Known2
.One
;
1508 Known
.Zero
|= Known2
.Zero
;
1512 case ISD::BITREVERSE
: {
1513 SDValue Src
= Op
.getOperand(0);
1514 APInt DemandedSrcBits
= DemandedBits
.reverseBits();
1515 if (SimplifyDemandedBits(Src
, DemandedSrcBits
, DemandedElts
, Known2
, TLO
,
1518 Known
.One
= Known2
.One
.reverseBits();
1519 Known
.Zero
= Known2
.Zero
.reverseBits();
1522 case ISD::SIGN_EXTEND_INREG
: {
1523 SDValue Op0
= Op
.getOperand(0);
1524 EVT ExVT
= cast
<VTSDNode
>(Op
.getOperand(1))->getVT();
1525 unsigned ExVTBits
= ExVT
.getScalarSizeInBits();
1527 // If we only care about the highest bit, don't bother shifting right.
1528 if (DemandedBits
.isSignMask()) {
1529 unsigned NumSignBits
= TLO
.DAG
.ComputeNumSignBits(Op0
);
1530 bool AlreadySignExtended
= NumSignBits
>= BitWidth
- ExVTBits
+ 1;
1531 // However if the input is already sign extended we expect the sign
1532 // extension to be dropped altogether later and do not simplify.
1533 if (!AlreadySignExtended
) {
1534 // Compute the correct shift amount type, which must be getShiftAmountTy
1535 // for scalar types after legalization.
1536 EVT ShiftAmtTy
= VT
;
1537 if (TLO
.LegalTypes() && !ShiftAmtTy
.isVector())
1538 ShiftAmtTy
= getShiftAmountTy(ShiftAmtTy
, DL
);
1541 TLO
.DAG
.getConstant(BitWidth
- ExVTBits
, dl
, ShiftAmtTy
);
1542 return TLO
.CombineTo(Op
,
1543 TLO
.DAG
.getNode(ISD::SHL
, dl
, VT
, Op0
, ShiftAmt
));
1547 // If none of the extended bits are demanded, eliminate the sextinreg.
1548 if (DemandedBits
.getActiveBits() <= ExVTBits
)
1549 return TLO
.CombineTo(Op
, Op0
);
1551 APInt InputDemandedBits
= DemandedBits
.getLoBits(ExVTBits
);
1553 // Since the sign extended bits are demanded, we know that the sign
1555 InputDemandedBits
.setBit(ExVTBits
- 1);
1557 if (SimplifyDemandedBits(Op0
, InputDemandedBits
, Known
, TLO
, Depth
+ 1))
1559 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1561 // If the sign bit of the input is known set or clear, then we know the
1562 // top bits of the result.
1564 // If the input sign bit is known zero, convert this into a zero extension.
1565 if (Known
.Zero
[ExVTBits
- 1])
1566 return TLO
.CombineTo(
1567 Op
, TLO
.DAG
.getZeroExtendInReg(Op0
, dl
, ExVT
.getScalarType()));
1569 APInt Mask
= APInt::getLowBitsSet(BitWidth
, ExVTBits
);
1570 if (Known
.One
[ExVTBits
- 1]) { // Input sign bit known set
1571 Known
.One
.setBitsFrom(ExVTBits
);
1573 } else { // Input sign bit unknown
1579 case ISD::BUILD_PAIR
: {
1580 EVT HalfVT
= Op
.getOperand(0).getValueType();
1581 unsigned HalfBitWidth
= HalfVT
.getScalarSizeInBits();
1583 APInt MaskLo
= DemandedBits
.getLoBits(HalfBitWidth
).trunc(HalfBitWidth
);
1584 APInt MaskHi
= DemandedBits
.getHiBits(HalfBitWidth
).trunc(HalfBitWidth
);
1586 KnownBits KnownLo
, KnownHi
;
1588 if (SimplifyDemandedBits(Op
.getOperand(0), MaskLo
, KnownLo
, TLO
, Depth
+ 1))
1591 if (SimplifyDemandedBits(Op
.getOperand(1), MaskHi
, KnownHi
, TLO
, Depth
+ 1))
1594 Known
.Zero
= KnownLo
.Zero
.zext(BitWidth
) |
1595 KnownHi
.Zero
.zext(BitWidth
).shl(HalfBitWidth
);
1597 Known
.One
= KnownLo
.One
.zext(BitWidth
) |
1598 KnownHi
.One
.zext(BitWidth
).shl(HalfBitWidth
);
1601 case ISD::ZERO_EXTEND
:
1602 case ISD::ZERO_EXTEND_VECTOR_INREG
: {
1603 SDValue Src
= Op
.getOperand(0);
1604 EVT SrcVT
= Src
.getValueType();
1605 unsigned InBits
= SrcVT
.getScalarSizeInBits();
1606 unsigned InElts
= SrcVT
.isVector() ? SrcVT
.getVectorNumElements() : 1;
1607 bool IsVecInReg
= Op
.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG
;
1609 // If none of the top bits are demanded, convert this into an any_extend.
1610 if (DemandedBits
.getActiveBits() <= InBits
) {
1611 // If we only need the non-extended bits of the bottom element
1612 // then we can just bitcast to the result.
1613 if (IsVecInReg
&& DemandedElts
== 1 &&
1614 VT
.getSizeInBits() == SrcVT
.getSizeInBits() &&
1615 TLO
.DAG
.getDataLayout().isLittleEndian())
1616 return TLO
.CombineTo(Op
, TLO
.DAG
.getBitcast(VT
, Src
));
1619 IsVecInReg
? ISD::ANY_EXTEND_VECTOR_INREG
: ISD::ANY_EXTEND
;
1620 if (!TLO
.LegalOperations() || isOperationLegal(Opc
, VT
))
1621 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(Opc
, dl
, VT
, Src
));
1624 APInt InDemandedBits
= DemandedBits
.trunc(InBits
);
1625 APInt InDemandedElts
= DemandedElts
.zextOrSelf(InElts
);
1626 if (SimplifyDemandedBits(Src
, InDemandedBits
, InDemandedElts
, Known
, TLO
,
1629 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1630 assert(Known
.getBitWidth() == InBits
&& "Src width has changed?");
1631 Known
= Known
.zext(BitWidth
, true /* ExtendedBitsAreKnownZero */);
1634 case ISD::SIGN_EXTEND
:
1635 case ISD::SIGN_EXTEND_VECTOR_INREG
: {
1636 SDValue Src
= Op
.getOperand(0);
1637 EVT SrcVT
= Src
.getValueType();
1638 unsigned InBits
= SrcVT
.getScalarSizeInBits();
1639 unsigned InElts
= SrcVT
.isVector() ? SrcVT
.getVectorNumElements() : 1;
1640 bool IsVecInReg
= Op
.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG
;
1642 // If none of the top bits are demanded, convert this into an any_extend.
1643 if (DemandedBits
.getActiveBits() <= InBits
) {
1644 // If we only need the non-extended bits of the bottom element
1645 // then we can just bitcast to the result.
1646 if (IsVecInReg
&& DemandedElts
== 1 &&
1647 VT
.getSizeInBits() == SrcVT
.getSizeInBits() &&
1648 TLO
.DAG
.getDataLayout().isLittleEndian())
1649 return TLO
.CombineTo(Op
, TLO
.DAG
.getBitcast(VT
, Src
));
1652 IsVecInReg
? ISD::ANY_EXTEND_VECTOR_INREG
: ISD::ANY_EXTEND
;
1653 if (!TLO
.LegalOperations() || isOperationLegal(Opc
, VT
))
1654 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(Opc
, dl
, VT
, Src
));
1657 APInt InDemandedBits
= DemandedBits
.trunc(InBits
);
1658 APInt InDemandedElts
= DemandedElts
.zextOrSelf(InElts
);
1660 // Since some of the sign extended bits are demanded, we know that the sign
1662 InDemandedBits
.setBit(InBits
- 1);
1664 if (SimplifyDemandedBits(Src
, InDemandedBits
, InDemandedElts
, Known
, TLO
,
1667 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1668 assert(Known
.getBitWidth() == InBits
&& "Src width has changed?");
1670 // If the sign bit is known one, the top bits match.
1671 Known
= Known
.sext(BitWidth
);
1673 // If the sign bit is known zero, convert this to a zero extend.
1674 if (Known
.isNonNegative()) {
1676 IsVecInReg
? ISD::ZERO_EXTEND_VECTOR_INREG
: ISD::ZERO_EXTEND
;
1677 if (!TLO
.LegalOperations() || isOperationLegal(Opc
, VT
))
1678 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(Opc
, dl
, VT
, Src
));
1682 case ISD::ANY_EXTEND
:
1683 case ISD::ANY_EXTEND_VECTOR_INREG
: {
1684 SDValue Src
= Op
.getOperand(0);
1685 EVT SrcVT
= Src
.getValueType();
1686 unsigned InBits
= SrcVT
.getScalarSizeInBits();
1687 unsigned InElts
= SrcVT
.isVector() ? SrcVT
.getVectorNumElements() : 1;
1688 bool IsVecInReg
= Op
.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG
;
1690 // If we only need the bottom element then we can just bitcast.
1691 // TODO: Handle ANY_EXTEND?
1692 if (IsVecInReg
&& DemandedElts
== 1 &&
1693 VT
.getSizeInBits() == SrcVT
.getSizeInBits() &&
1694 TLO
.DAG
.getDataLayout().isLittleEndian())
1695 return TLO
.CombineTo(Op
, TLO
.DAG
.getBitcast(VT
, Src
));
1697 APInt InDemandedBits
= DemandedBits
.trunc(InBits
);
1698 APInt InDemandedElts
= DemandedElts
.zextOrSelf(InElts
);
1699 if (SimplifyDemandedBits(Src
, InDemandedBits
, InDemandedElts
, Known
, TLO
,
1702 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1703 assert(Known
.getBitWidth() == InBits
&& "Src width has changed?");
1704 Known
= Known
.zext(BitWidth
, false /* => any extend */);
1707 case ISD::TRUNCATE
: {
1708 SDValue Src
= Op
.getOperand(0);
1710 // Simplify the input, using demanded bit information, and compute the known
1711 // zero/one bits live out.
1712 unsigned OperandBitWidth
= Src
.getScalarValueSizeInBits();
1713 APInt TruncMask
= DemandedBits
.zext(OperandBitWidth
);
1714 if (SimplifyDemandedBits(Src
, TruncMask
, Known
, TLO
, Depth
+ 1))
1716 Known
= Known
.trunc(BitWidth
);
1718 // Attempt to avoid multi-use ops if we don't need anything from them.
1719 if (SDValue NewSrc
= SimplifyMultipleUseDemandedBits(
1720 Src
, TruncMask
, DemandedElts
, TLO
.DAG
, Depth
+ 1))
1721 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, NewSrc
));
1723 // If the input is only used by this truncate, see if we can shrink it based
1724 // on the known demanded bits.
1725 if (Src
.getNode()->hasOneUse()) {
1726 switch (Src
.getOpcode()) {
1730 // Shrink SRL by a constant if none of the high bits shifted in are
1732 if (TLO
.LegalTypes() && !isTypeDesirableForOp(ISD::SRL
, VT
))
1733 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1737 auto *ShAmt
= dyn_cast
<ConstantSDNode
>(Src
.getOperand(1));
1738 if (!ShAmt
|| ShAmt
->getAPIntValue().uge(BitWidth
))
1741 SDValue Shift
= Src
.getOperand(1);
1742 uint64_t ShVal
= ShAmt
->getZExtValue();
1744 if (TLO
.LegalTypes())
1745 Shift
= TLO
.DAG
.getConstant(ShVal
, dl
, getShiftAmountTy(VT
, DL
));
1748 APInt::getHighBitsSet(OperandBitWidth
, OperandBitWidth
- BitWidth
);
1749 HighBits
.lshrInPlace(ShVal
);
1750 HighBits
= HighBits
.trunc(BitWidth
);
1752 if (!(HighBits
& DemandedBits
)) {
1753 // None of the shifted in bits are needed. Add a truncate of the
1754 // shift input, then shift it.
1756 TLO
.DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, Src
.getOperand(0));
1757 return TLO
.CombineTo(
1758 Op
, TLO
.DAG
.getNode(ISD::SRL
, dl
, VT
, NewTrunc
, Shift
));
1764 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1767 case ISD::AssertZext
: {
1768 // AssertZext demands all of the high bits, plus any of the low bits
1769 // demanded by its users.
1770 EVT ZVT
= cast
<VTSDNode
>(Op
.getOperand(1))->getVT();
1771 APInt InMask
= APInt::getLowBitsSet(BitWidth
, ZVT
.getSizeInBits());
1772 if (SimplifyDemandedBits(Op
.getOperand(0), ~InMask
| DemandedBits
, Known
,
1775 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1777 Known
.Zero
|= ~InMask
;
1780 case ISD::EXTRACT_VECTOR_ELT
: {
1781 SDValue Src
= Op
.getOperand(0);
1782 SDValue Idx
= Op
.getOperand(1);
1783 unsigned NumSrcElts
= Src
.getValueType().getVectorNumElements();
1784 unsigned EltBitWidth
= Src
.getScalarValueSizeInBits();
1786 // Demand the bits from every vector element without a constant index.
1787 APInt DemandedSrcElts
= APInt::getAllOnesValue(NumSrcElts
);
1788 if (auto *CIdx
= dyn_cast
<ConstantSDNode
>(Idx
))
1789 if (CIdx
->getAPIntValue().ult(NumSrcElts
))
1790 DemandedSrcElts
= APInt::getOneBitSet(NumSrcElts
, CIdx
->getZExtValue());
1792 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
1793 // anything about the extended bits.
1794 APInt DemandedSrcBits
= DemandedBits
;
1795 if (BitWidth
> EltBitWidth
)
1796 DemandedSrcBits
= DemandedSrcBits
.trunc(EltBitWidth
);
1798 if (SimplifyDemandedBits(Src
, DemandedSrcBits
, DemandedSrcElts
, Known2
, TLO
,
1803 if (BitWidth
> EltBitWidth
)
1804 Known
= Known
.zext(BitWidth
, false /* => any extend */);
1807 case ISD::BITCAST
: {
1808 SDValue Src
= Op
.getOperand(0);
1809 EVT SrcVT
= Src
.getValueType();
1810 unsigned NumSrcEltBits
= SrcVT
.getScalarSizeInBits();
1812 // If this is an FP->Int bitcast and if the sign bit is the only
1813 // thing demanded, turn this into a FGETSIGN.
1814 if (!TLO
.LegalOperations() && !VT
.isVector() && !SrcVT
.isVector() &&
1815 DemandedBits
== APInt::getSignMask(Op
.getValueSizeInBits()) &&
1816 SrcVT
.isFloatingPoint()) {
1817 bool OpVTLegal
= isOperationLegalOrCustom(ISD::FGETSIGN
, VT
);
1818 bool i32Legal
= isOperationLegalOrCustom(ISD::FGETSIGN
, MVT::i32
);
1819 if ((OpVTLegal
|| i32Legal
) && VT
.isSimple() && SrcVT
!= MVT::f16
&&
1820 SrcVT
!= MVT::f128
) {
1821 // Cannot eliminate/lower SHL for f128 yet.
1822 EVT Ty
= OpVTLegal
? VT
: MVT::i32
;
1823 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1824 // place. We expect the SHL to be eliminated by other optimizations.
1825 SDValue Sign
= TLO
.DAG
.getNode(ISD::FGETSIGN
, dl
, Ty
, Src
);
1826 unsigned OpVTSizeInBits
= Op
.getValueSizeInBits();
1827 if (!OpVTLegal
&& OpVTSizeInBits
> 32)
1828 Sign
= TLO
.DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, Sign
);
1829 unsigned ShVal
= Op
.getValueSizeInBits() - 1;
1830 SDValue ShAmt
= TLO
.DAG
.getConstant(ShVal
, dl
, VT
);
1831 return TLO
.CombineTo(Op
,
1832 TLO
.DAG
.getNode(ISD::SHL
, dl
, VT
, Sign
, ShAmt
));
1836 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
1837 // Demand the elt/bit if any of the original elts/bits are demanded.
1838 // TODO - bigendian once we have test coverage.
1839 if (SrcVT
.isVector() && (BitWidth
% NumSrcEltBits
) == 0 &&
1840 TLO
.DAG
.getDataLayout().isLittleEndian()) {
1841 unsigned Scale
= BitWidth
/ NumSrcEltBits
;
1842 unsigned NumSrcElts
= SrcVT
.getVectorNumElements();
1843 APInt DemandedSrcBits
= APInt::getNullValue(NumSrcEltBits
);
1844 APInt DemandedSrcElts
= APInt::getNullValue(NumSrcElts
);
1845 for (unsigned i
= 0; i
!= Scale
; ++i
) {
1846 unsigned Offset
= i
* NumSrcEltBits
;
1847 APInt Sub
= DemandedBits
.extractBits(NumSrcEltBits
, Offset
);
1848 if (!Sub
.isNullValue()) {
1849 DemandedSrcBits
|= Sub
;
1850 for (unsigned j
= 0; j
!= NumElts
; ++j
)
1851 if (DemandedElts
[j
])
1852 DemandedSrcElts
.setBit((j
* Scale
) + i
);
1856 APInt KnownSrcUndef
, KnownSrcZero
;
1857 if (SimplifyDemandedVectorElts(Src
, DemandedSrcElts
, KnownSrcUndef
,
1858 KnownSrcZero
, TLO
, Depth
+ 1))
1861 KnownBits KnownSrcBits
;
1862 if (SimplifyDemandedBits(Src
, DemandedSrcBits
, DemandedSrcElts
,
1863 KnownSrcBits
, TLO
, Depth
+ 1))
1865 } else if ((NumSrcEltBits
% BitWidth
) == 0 &&
1866 TLO
.DAG
.getDataLayout().isLittleEndian()) {
1867 unsigned Scale
= NumSrcEltBits
/ BitWidth
;
1868 unsigned NumSrcElts
= SrcVT
.isVector() ? SrcVT
.getVectorNumElements() : 1;
1869 APInt DemandedSrcBits
= APInt::getNullValue(NumSrcEltBits
);
1870 APInt DemandedSrcElts
= APInt::getNullValue(NumSrcElts
);
1871 for (unsigned i
= 0; i
!= NumElts
; ++i
)
1872 if (DemandedElts
[i
]) {
1873 unsigned Offset
= (i
% Scale
) * BitWidth
;
1874 DemandedSrcBits
.insertBits(DemandedBits
, Offset
);
1875 DemandedSrcElts
.setBit(i
/ Scale
);
1878 if (SrcVT
.isVector()) {
1879 APInt KnownSrcUndef
, KnownSrcZero
;
1880 if (SimplifyDemandedVectorElts(Src
, DemandedSrcElts
, KnownSrcUndef
,
1881 KnownSrcZero
, TLO
, Depth
+ 1))
1885 KnownBits KnownSrcBits
;
1886 if (SimplifyDemandedBits(Src
, DemandedSrcBits
, DemandedSrcElts
,
1887 KnownSrcBits
, TLO
, Depth
+ 1))
1891 // If this is a bitcast, let computeKnownBits handle it. Only do this on a
1892 // recursive call where Known may be useful to the caller.
1894 Known
= TLO
.DAG
.computeKnownBits(Op
, DemandedElts
, Depth
);
1902 // Add, Sub, and Mul don't demand any bits in positions beyond that
1903 // of the highest bit demanded of them.
1904 SDValue Op0
= Op
.getOperand(0), Op1
= Op
.getOperand(1);
1905 SDNodeFlags Flags
= Op
.getNode()->getFlags();
1906 unsigned DemandedBitsLZ
= DemandedBits
.countLeadingZeros();
1907 APInt LoMask
= APInt::getLowBitsSet(BitWidth
, BitWidth
- DemandedBitsLZ
);
1908 if (SimplifyDemandedBits(Op0
, LoMask
, DemandedElts
, Known2
, TLO
,
1910 SimplifyDemandedBits(Op1
, LoMask
, DemandedElts
, Known2
, TLO
,
1912 // See if the operation should be performed at a smaller bit width.
1913 ShrinkDemandedOp(Op
, BitWidth
, DemandedBits
, TLO
)) {
1914 if (Flags
.hasNoSignedWrap() || Flags
.hasNoUnsignedWrap()) {
1915 // Disable the nsw and nuw flags. We can no longer guarantee that we
1916 // won't wrap after simplification.
1917 Flags
.setNoSignedWrap(false);
1918 Flags
.setNoUnsignedWrap(false);
1920 TLO
.DAG
.getNode(Op
.getOpcode(), dl
, VT
, Op0
, Op1
, Flags
);
1921 return TLO
.CombineTo(Op
, NewOp
);
1926 // Attempt to avoid multi-use ops if we don't need anything from them.
1927 if (!LoMask
.isAllOnesValue() || !DemandedElts
.isAllOnesValue()) {
1928 SDValue DemandedOp0
= SimplifyMultipleUseDemandedBits(
1929 Op0
, LoMask
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1930 SDValue DemandedOp1
= SimplifyMultipleUseDemandedBits(
1931 Op1
, LoMask
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1932 if (DemandedOp0
|| DemandedOp1
) {
1933 Flags
.setNoSignedWrap(false);
1934 Flags
.setNoUnsignedWrap(false);
1935 Op0
= DemandedOp0
? DemandedOp0
: Op0
;
1936 Op1
= DemandedOp1
? DemandedOp1
: Op1
;
1938 TLO
.DAG
.getNode(Op
.getOpcode(), dl
, VT
, Op0
, Op1
, Flags
);
1939 return TLO
.CombineTo(Op
, NewOp
);
1943 // If we have a constant operand, we may be able to turn it into -1 if we
1944 // do not demand the high bits. This can make the constant smaller to
1945 // encode, allow more general folding, or match specialized instruction
1946 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
1947 // is probably not useful (and could be detrimental).
1948 ConstantSDNode
*C
= isConstOrConstSplat(Op1
);
1949 APInt HighMask
= APInt::getHighBitsSet(BitWidth
, DemandedBitsLZ
);
1950 if (C
&& !C
->isAllOnesValue() && !C
->isOne() &&
1951 (C
->getAPIntValue() | HighMask
).isAllOnesValue()) {
1952 SDValue Neg1
= TLO
.DAG
.getAllOnesConstant(dl
, VT
);
1953 // Disable the nsw and nuw flags. We can no longer guarantee that we
1954 // won't wrap after simplification.
1955 Flags
.setNoSignedWrap(false);
1956 Flags
.setNoUnsignedWrap(false);
1957 SDValue NewOp
= TLO
.DAG
.getNode(Op
.getOpcode(), dl
, VT
, Op0
, Neg1
, Flags
);
1958 return TLO
.CombineTo(Op
, NewOp
);
1964 if (Op
.getOpcode() >= ISD::BUILTIN_OP_END
) {
1965 if (SimplifyDemandedBitsForTargetNode(Op
, DemandedBits
, DemandedElts
,
1971 // Just use computeKnownBits to compute output bits.
1972 Known
= TLO
.DAG
.computeKnownBits(Op
, DemandedElts
, Depth
);
1976 // If we know the value of all of the demanded bits, return this as a
1978 if (DemandedBits
.isSubsetOf(Known
.Zero
| Known
.One
)) {
1979 // Avoid folding to a constant if any OpaqueConstant is involved.
1980 const SDNode
*N
= Op
.getNode();
1981 for (SDNodeIterator I
= SDNodeIterator::begin(N
),
1982 E
= SDNodeIterator::end(N
);
1985 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Op
))
1989 // TODO: Handle float bits as well.
1991 return TLO
.CombineTo(Op
, TLO
.DAG
.getConstant(Known
.One
, dl
, VT
));
1997 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op
,
1998 const APInt
&DemandedElts
,
2001 DAGCombinerInfo
&DCI
) const {
2002 SelectionDAG
&DAG
= DCI
.DAG
;
2003 TargetLoweringOpt
TLO(DAG
, !DCI
.isBeforeLegalize(),
2004 !DCI
.isBeforeLegalizeOps());
2007 SimplifyDemandedVectorElts(Op
, DemandedElts
, KnownUndef
, KnownZero
, TLO
);
2009 DCI
.AddToWorklist(Op
.getNode());
2010 DCI
.CommitTargetLoweringOpt(TLO
);
2016 /// Given a vector binary operation and known undefined elements for each input
2017 /// operand, compute whether each element of the output is undefined.
2018 static APInt
getKnownUndefForVectorBinop(SDValue BO
, SelectionDAG
&DAG
,
2019 const APInt
&UndefOp0
,
2020 const APInt
&UndefOp1
) {
2021 EVT VT
= BO
.getValueType();
2022 assert(DAG
.getTargetLoweringInfo().isBinOp(BO
.getOpcode()) && VT
.isVector() &&
2023 "Vector binop only");
2025 EVT EltVT
= VT
.getVectorElementType();
2026 unsigned NumElts
= VT
.getVectorNumElements();
2027 assert(UndefOp0
.getBitWidth() == NumElts
&&
2028 UndefOp1
.getBitWidth() == NumElts
&& "Bad type for undef analysis");
2030 auto getUndefOrConstantElt
= [&](SDValue V
, unsigned Index
,
2031 const APInt
&UndefVals
) {
2032 if (UndefVals
[Index
])
2033 return DAG
.getUNDEF(EltVT
);
2035 if (auto *BV
= dyn_cast
<BuildVectorSDNode
>(V
)) {
2036 // Try hard to make sure that the getNode() call is not creating temporary
2037 // nodes. Ignore opaque integers because they do not constant fold.
2038 SDValue Elt
= BV
->getOperand(Index
);
2039 auto *C
= dyn_cast
<ConstantSDNode
>(Elt
);
2040 if (isa
<ConstantFPSDNode
>(Elt
) || Elt
.isUndef() || (C
&& !C
->isOpaque()))
2047 APInt KnownUndef
= APInt::getNullValue(NumElts
);
2048 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2049 // If both inputs for this element are either constant or undef and match
2050 // the element type, compute the constant/undef result for this element of
2052 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
2053 // not handle FP constants. The code within getNode() should be refactored
2054 // to avoid the danger of creating a bogus temporary node here.
2055 SDValue C0
= getUndefOrConstantElt(BO
.getOperand(0), i
, UndefOp0
);
2056 SDValue C1
= getUndefOrConstantElt(BO
.getOperand(1), i
, UndefOp1
);
2057 if (C0
&& C1
&& C0
.getValueType() == EltVT
&& C1
.getValueType() == EltVT
)
2058 if (DAG
.getNode(BO
.getOpcode(), SDLoc(BO
), EltVT
, C0
, C1
).isUndef())
2059 KnownUndef
.setBit(i
);
2064 bool TargetLowering::SimplifyDemandedVectorElts(
2065 SDValue Op
, const APInt
&OriginalDemandedElts
, APInt
&KnownUndef
,
2066 APInt
&KnownZero
, TargetLoweringOpt
&TLO
, unsigned Depth
,
2067 bool AssumeSingleUse
) const {
2068 EVT VT
= Op
.getValueType();
2069 APInt DemandedElts
= OriginalDemandedElts
;
2070 unsigned NumElts
= DemandedElts
.getBitWidth();
2071 assert(VT
.isVector() && "Expected vector op");
2072 assert(VT
.getVectorNumElements() == NumElts
&&
2073 "Mask size mismatches value type element count!");
2075 KnownUndef
= KnownZero
= APInt::getNullValue(NumElts
);
2079 KnownUndef
.setAllBits();
2083 // If Op has other users, assume that all elements are needed.
2084 if (!Op
.getNode()->hasOneUse() && !AssumeSingleUse
)
2085 DemandedElts
.setAllBits();
2087 // Not demanding any elements from Op.
2088 if (DemandedElts
== 0) {
2089 KnownUndef
.setAllBits();
2090 return TLO
.CombineTo(Op
, TLO
.DAG
.getUNDEF(VT
));
2093 // Limit search depth.
2098 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
2100 switch (Op
.getOpcode()) {
2101 case ISD::SCALAR_TO_VECTOR
: {
2102 if (!DemandedElts
[0]) {
2103 KnownUndef
.setAllBits();
2104 return TLO
.CombineTo(Op
, TLO
.DAG
.getUNDEF(VT
));
2106 KnownUndef
.setHighBits(NumElts
- 1);
2109 case ISD::BITCAST
: {
2110 SDValue Src
= Op
.getOperand(0);
2111 EVT SrcVT
= Src
.getValueType();
2113 // We only handle vectors here.
2114 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
2115 if (!SrcVT
.isVector())
2118 // Fast handling of 'identity' bitcasts.
2119 unsigned NumSrcElts
= SrcVT
.getVectorNumElements();
2120 if (NumSrcElts
== NumElts
)
2121 return SimplifyDemandedVectorElts(Src
, DemandedElts
, KnownUndef
,
2122 KnownZero
, TLO
, Depth
+ 1);
2124 APInt SrcZero
, SrcUndef
;
2125 APInt SrcDemandedElts
= APInt::getNullValue(NumSrcElts
);
2127 // Bitcast from 'large element' src vector to 'small element' vector, we
2128 // must demand a source element if any DemandedElt maps to it.
2129 if ((NumElts
% NumSrcElts
) == 0) {
2130 unsigned Scale
= NumElts
/ NumSrcElts
;
2131 for (unsigned i
= 0; i
!= NumElts
; ++i
)
2132 if (DemandedElts
[i
])
2133 SrcDemandedElts
.setBit(i
/ Scale
);
2135 if (SimplifyDemandedVectorElts(Src
, SrcDemandedElts
, SrcUndef
, SrcZero
,
2139 // Try calling SimplifyDemandedBits, converting demanded elts to the bits
2140 // of the large element.
2141 // TODO - bigendian once we have test coverage.
2142 if (TLO
.DAG
.getDataLayout().isLittleEndian()) {
2143 unsigned SrcEltSizeInBits
= SrcVT
.getScalarSizeInBits();
2144 APInt SrcDemandedBits
= APInt::getNullValue(SrcEltSizeInBits
);
2145 for (unsigned i
= 0; i
!= NumElts
; ++i
)
2146 if (DemandedElts
[i
]) {
2147 unsigned Ofs
= (i
% Scale
) * EltSizeInBits
;
2148 SrcDemandedBits
.setBits(Ofs
, Ofs
+ EltSizeInBits
);
2152 if (SimplifyDemandedBits(Src
, SrcDemandedBits
, Known
, TLO
, Depth
+ 1))
2156 // If the src element is zero/undef then all the output elements will be -
2157 // only demanded elements are guaranteed to be correct.
2158 for (unsigned i
= 0; i
!= NumSrcElts
; ++i
) {
2159 if (SrcDemandedElts
[i
]) {
2161 KnownZero
.setBits(i
* Scale
, (i
+ 1) * Scale
);
2163 KnownUndef
.setBits(i
* Scale
, (i
+ 1) * Scale
);
2168 // Bitcast from 'small element' src vector to 'large element' vector, we
2169 // demand all smaller source elements covered by the larger demanded element
2171 if ((NumSrcElts
% NumElts
) == 0) {
2172 unsigned Scale
= NumSrcElts
/ NumElts
;
2173 for (unsigned i
= 0; i
!= NumElts
; ++i
)
2174 if (DemandedElts
[i
])
2175 SrcDemandedElts
.setBits(i
* Scale
, (i
+ 1) * Scale
);
2177 if (SimplifyDemandedVectorElts(Src
, SrcDemandedElts
, SrcUndef
, SrcZero
,
2181 // If all the src elements covering an output element are zero/undef, then
2182 // the output element will be as well, assuming it was demanded.
2183 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2184 if (DemandedElts
[i
]) {
2185 if (SrcZero
.extractBits(Scale
, i
* Scale
).isAllOnesValue())
2186 KnownZero
.setBit(i
);
2187 if (SrcUndef
.extractBits(Scale
, i
* Scale
).isAllOnesValue())
2188 KnownUndef
.setBit(i
);
2194 case ISD::BUILD_VECTOR
: {
2195 // Check all elements and simplify any unused elements with UNDEF.
2196 if (!DemandedElts
.isAllOnesValue()) {
2197 // Don't simplify BROADCASTS.
2198 if (llvm::any_of(Op
->op_values(),
2199 [&](SDValue Elt
) { return Op
.getOperand(0) != Elt
; })) {
2200 SmallVector
<SDValue
, 32> Ops(Op
->op_begin(), Op
->op_end());
2201 bool Updated
= false;
2202 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2203 if (!DemandedElts
[i
] && !Ops
[i
].isUndef()) {
2204 Ops
[i
] = TLO
.DAG
.getUNDEF(Ops
[0].getValueType());
2205 KnownUndef
.setBit(i
);
2210 return TLO
.CombineTo(Op
, TLO
.DAG
.getBuildVector(VT
, DL
, Ops
));
2213 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2214 SDValue SrcOp
= Op
.getOperand(i
);
2215 if (SrcOp
.isUndef()) {
2216 KnownUndef
.setBit(i
);
2217 } else if (EltSizeInBits
== SrcOp
.getScalarValueSizeInBits() &&
2218 (isNullConstant(SrcOp
) || isNullFPConstant(SrcOp
))) {
2219 KnownZero
.setBit(i
);
2224 case ISD::CONCAT_VECTORS
: {
2225 EVT SubVT
= Op
.getOperand(0).getValueType();
2226 unsigned NumSubVecs
= Op
.getNumOperands();
2227 unsigned NumSubElts
= SubVT
.getVectorNumElements();
2228 for (unsigned i
= 0; i
!= NumSubVecs
; ++i
) {
2229 SDValue SubOp
= Op
.getOperand(i
);
2230 APInt SubElts
= DemandedElts
.extractBits(NumSubElts
, i
* NumSubElts
);
2231 APInt SubUndef
, SubZero
;
2232 if (SimplifyDemandedVectorElts(SubOp
, SubElts
, SubUndef
, SubZero
, TLO
,
2235 KnownUndef
.insertBits(SubUndef
, i
* NumSubElts
);
2236 KnownZero
.insertBits(SubZero
, i
* NumSubElts
);
2240 case ISD::INSERT_SUBVECTOR
: {
2241 if (!isa
<ConstantSDNode
>(Op
.getOperand(2)))
2243 SDValue Base
= Op
.getOperand(0);
2244 SDValue Sub
= Op
.getOperand(1);
2245 EVT SubVT
= Sub
.getValueType();
2246 unsigned NumSubElts
= SubVT
.getVectorNumElements();
2247 const APInt
&Idx
= Op
.getConstantOperandAPInt(2);
2248 if (Idx
.ugt(NumElts
- NumSubElts
))
2250 unsigned SubIdx
= Idx
.getZExtValue();
2251 APInt SubElts
= DemandedElts
.extractBits(NumSubElts
, SubIdx
);
2252 APInt SubUndef
, SubZero
;
2253 if (SimplifyDemandedVectorElts(Sub
, SubElts
, SubUndef
, SubZero
, TLO
,
2256 APInt BaseElts
= DemandedElts
;
2257 BaseElts
.insertBits(APInt::getNullValue(NumSubElts
), SubIdx
);
2259 // If none of the base operand elements are demanded, replace it with undef.
2260 if (!BaseElts
&& !Base
.isUndef())
2261 return TLO
.CombineTo(Op
,
2262 TLO
.DAG
.getNode(ISD::INSERT_SUBVECTOR
, DL
, VT
,
2263 TLO
.DAG
.getUNDEF(VT
),
2267 if (SimplifyDemandedVectorElts(Base
, BaseElts
, KnownUndef
, KnownZero
, TLO
,
2270 KnownUndef
.insertBits(SubUndef
, SubIdx
);
2271 KnownZero
.insertBits(SubZero
, SubIdx
);
2274 case ISD::EXTRACT_SUBVECTOR
: {
2275 SDValue Src
= Op
.getOperand(0);
2276 ConstantSDNode
*SubIdx
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
2277 unsigned NumSrcElts
= Src
.getValueType().getVectorNumElements();
2278 if (SubIdx
&& SubIdx
->getAPIntValue().ule(NumSrcElts
- NumElts
)) {
2279 // Offset the demanded elts by the subvector index.
2280 uint64_t Idx
= SubIdx
->getZExtValue();
2281 APInt SrcElts
= DemandedElts
.zextOrSelf(NumSrcElts
).shl(Idx
);
2282 APInt SrcUndef
, SrcZero
;
2283 if (SimplifyDemandedVectorElts(Src
, SrcElts
, SrcUndef
, SrcZero
, TLO
,
2286 KnownUndef
= SrcUndef
.extractBits(NumElts
, Idx
);
2287 KnownZero
= SrcZero
.extractBits(NumElts
, Idx
);
2291 case ISD::INSERT_VECTOR_ELT
: {
2292 SDValue Vec
= Op
.getOperand(0);
2293 SDValue Scl
= Op
.getOperand(1);
2294 auto *CIdx
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(2));
2296 // For a legal, constant insertion index, if we don't need this insertion
2297 // then strip it, else remove it from the demanded elts.
2298 if (CIdx
&& CIdx
->getAPIntValue().ult(NumElts
)) {
2299 unsigned Idx
= CIdx
->getZExtValue();
2300 if (!DemandedElts
[Idx
])
2301 return TLO
.CombineTo(Op
, Vec
);
2303 APInt
DemandedVecElts(DemandedElts
);
2304 DemandedVecElts
.clearBit(Idx
);
2305 if (SimplifyDemandedVectorElts(Vec
, DemandedVecElts
, KnownUndef
,
2306 KnownZero
, TLO
, Depth
+ 1))
2309 KnownUndef
.clearBit(Idx
);
2311 KnownUndef
.setBit(Idx
);
2313 KnownZero
.clearBit(Idx
);
2314 if (isNullConstant(Scl
) || isNullFPConstant(Scl
))
2315 KnownZero
.setBit(Idx
);
2319 APInt VecUndef
, VecZero
;
2320 if (SimplifyDemandedVectorElts(Vec
, DemandedElts
, VecUndef
, VecZero
, TLO
,
2323 // Without knowing the insertion index we can't set KnownUndef/KnownZero.
2326 case ISD::VSELECT
: {
2327 // Try to transform the select condition based on the current demanded
2329 // TODO: If a condition element is undef, we can choose from one arm of the
2330 // select (and if one arm is undef, then we can propagate that to the
2332 // TODO - add support for constant vselect masks (see IR version of this).
2333 APInt UnusedUndef
, UnusedZero
;
2334 if (SimplifyDemandedVectorElts(Op
.getOperand(0), DemandedElts
, UnusedUndef
,
2335 UnusedZero
, TLO
, Depth
+ 1))
2338 // See if we can simplify either vselect operand.
2339 APInt
DemandedLHS(DemandedElts
);
2340 APInt
DemandedRHS(DemandedElts
);
2341 APInt UndefLHS
, ZeroLHS
;
2342 APInt UndefRHS
, ZeroRHS
;
2343 if (SimplifyDemandedVectorElts(Op
.getOperand(1), DemandedLHS
, UndefLHS
,
2344 ZeroLHS
, TLO
, Depth
+ 1))
2346 if (SimplifyDemandedVectorElts(Op
.getOperand(2), DemandedRHS
, UndefRHS
,
2347 ZeroRHS
, TLO
, Depth
+ 1))
2350 KnownUndef
= UndefLHS
& UndefRHS
;
2351 KnownZero
= ZeroLHS
& ZeroRHS
;
2354 case ISD::VECTOR_SHUFFLE
: {
2355 ArrayRef
<int> ShuffleMask
= cast
<ShuffleVectorSDNode
>(Op
)->getMask();
2357 // Collect demanded elements from shuffle operands..
2358 APInt
DemandedLHS(NumElts
, 0);
2359 APInt
DemandedRHS(NumElts
, 0);
2360 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2361 int M
= ShuffleMask
[i
];
2362 if (M
< 0 || !DemandedElts
[i
])
2364 assert(0 <= M
&& M
< (int)(2 * NumElts
) && "Shuffle index out of range");
2365 if (M
< (int)NumElts
)
2366 DemandedLHS
.setBit(M
);
2368 DemandedRHS
.setBit(M
- NumElts
);
2371 // See if we can simplify either shuffle operand.
2372 APInt UndefLHS
, ZeroLHS
;
2373 APInt UndefRHS
, ZeroRHS
;
2374 if (SimplifyDemandedVectorElts(Op
.getOperand(0), DemandedLHS
, UndefLHS
,
2375 ZeroLHS
, TLO
, Depth
+ 1))
2377 if (SimplifyDemandedVectorElts(Op
.getOperand(1), DemandedRHS
, UndefRHS
,
2378 ZeroRHS
, TLO
, Depth
+ 1))
2381 // Simplify mask using undef elements from LHS/RHS.
2382 bool Updated
= false;
2383 bool IdentityLHS
= true, IdentityRHS
= true;
2384 SmallVector
<int, 32> NewMask(ShuffleMask
.begin(), ShuffleMask
.end());
2385 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2386 int &M
= NewMask
[i
];
2389 if (!DemandedElts
[i
] || (M
< (int)NumElts
&& UndefLHS
[M
]) ||
2390 (M
>= (int)NumElts
&& UndefRHS
[M
- NumElts
])) {
2394 IdentityLHS
&= (M
< 0) || (M
== (int)i
);
2395 IdentityRHS
&= (M
< 0) || ((M
- NumElts
) == i
);
2398 // Update legal shuffle masks based on demanded elements if it won't reduce
2399 // to Identity which can cause premature removal of the shuffle mask.
2400 if (Updated
&& !IdentityLHS
&& !IdentityRHS
&& !TLO
.LegalOps
) {
2401 SDValue LegalShuffle
=
2402 buildLegalVectorShuffle(VT
, DL
, Op
.getOperand(0), Op
.getOperand(1),
2405 return TLO
.CombineTo(Op
, LegalShuffle
);
2408 // Propagate undef/zero elements from LHS/RHS.
2409 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2410 int M
= ShuffleMask
[i
];
2412 KnownUndef
.setBit(i
);
2413 } else if (M
< (int)NumElts
) {
2415 KnownUndef
.setBit(i
);
2417 KnownZero
.setBit(i
);
2419 if (UndefRHS
[M
- NumElts
])
2420 KnownUndef
.setBit(i
);
2421 if (ZeroRHS
[M
- NumElts
])
2422 KnownZero
.setBit(i
);
2427 case ISD::ANY_EXTEND_VECTOR_INREG
:
2428 case ISD::SIGN_EXTEND_VECTOR_INREG
:
2429 case ISD::ZERO_EXTEND_VECTOR_INREG
: {
2430 APInt SrcUndef
, SrcZero
;
2431 SDValue Src
= Op
.getOperand(0);
2432 unsigned NumSrcElts
= Src
.getValueType().getVectorNumElements();
2433 APInt DemandedSrcElts
= DemandedElts
.zextOrSelf(NumSrcElts
);
2434 if (SimplifyDemandedVectorElts(Src
, DemandedSrcElts
, SrcUndef
, SrcZero
, TLO
,
2437 KnownZero
= SrcZero
.zextOrTrunc(NumElts
);
2438 KnownUndef
= SrcUndef
.zextOrTrunc(NumElts
);
2440 if (Op
.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG
&&
2441 Op
.getValueSizeInBits() == Src
.getValueSizeInBits() &&
2442 DemandedSrcElts
== 1 && TLO
.DAG
.getDataLayout().isLittleEndian()) {
2443 // aext - if we just need the bottom element then we can bitcast.
2444 return TLO
.CombineTo(Op
, TLO
.DAG
.getBitcast(VT
, Src
));
2447 if (Op
.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG
) {
2448 // zext(undef) upper bits are guaranteed to be zero.
2449 if (DemandedElts
.isSubsetOf(KnownUndef
))
2450 return TLO
.CombineTo(Op
, TLO
.DAG
.getConstant(0, SDLoc(Op
), VT
));
2451 KnownUndef
.clearAllBits();
2456 // TODO: There are more binop opcodes that could be handled here - MUL, MIN,
2457 // MAX, saturated math, etc.
2467 APInt UndefRHS
, ZeroRHS
;
2468 if (SimplifyDemandedVectorElts(Op
.getOperand(1), DemandedElts
, UndefRHS
,
2469 ZeroRHS
, TLO
, Depth
+ 1))
2471 APInt UndefLHS
, ZeroLHS
;
2472 if (SimplifyDemandedVectorElts(Op
.getOperand(0), DemandedElts
, UndefLHS
,
2473 ZeroLHS
, TLO
, Depth
+ 1))
2476 KnownZero
= ZeroLHS
& ZeroRHS
;
2477 KnownUndef
= getKnownUndefForVectorBinop(Op
, TLO
.DAG
, UndefLHS
, UndefRHS
);
2485 APInt UndefRHS
, ZeroRHS
;
2486 if (SimplifyDemandedVectorElts(Op
.getOperand(1), DemandedElts
, UndefRHS
,
2487 ZeroRHS
, TLO
, Depth
+ 1))
2489 APInt UndefLHS
, ZeroLHS
;
2490 if (SimplifyDemandedVectorElts(Op
.getOperand(0), DemandedElts
, UndefLHS
,
2491 ZeroLHS
, TLO
, Depth
+ 1))
2494 KnownZero
= ZeroLHS
;
2495 KnownUndef
= UndefLHS
& UndefRHS
; // TODO: use getKnownUndefForVectorBinop?
2500 APInt SrcUndef
, SrcZero
;
2501 if (SimplifyDemandedVectorElts(Op
.getOperand(1), DemandedElts
, SrcUndef
,
2502 SrcZero
, TLO
, Depth
+ 1))
2504 if (SimplifyDemandedVectorElts(Op
.getOperand(0), DemandedElts
, KnownUndef
,
2505 KnownZero
, TLO
, Depth
+ 1))
2508 // If either side has a zero element, then the result element is zero, even
2509 // if the other is an UNDEF.
2510 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
2511 // and then handle 'and' nodes with the rest of the binop opcodes.
2512 KnownZero
|= SrcZero
;
2513 KnownUndef
&= SrcUndef
;
2514 KnownUndef
&= ~KnownZero
;
2518 case ISD::SIGN_EXTEND
:
2519 case ISD::ZERO_EXTEND
:
2520 if (SimplifyDemandedVectorElts(Op
.getOperand(0), DemandedElts
, KnownUndef
,
2521 KnownZero
, TLO
, Depth
+ 1))
2524 if (Op
.getOpcode() == ISD::ZERO_EXTEND
) {
2525 // zext(undef) upper bits are guaranteed to be zero.
2526 if (DemandedElts
.isSubsetOf(KnownUndef
))
2527 return TLO
.CombineTo(Op
, TLO
.DAG
.getConstant(0, SDLoc(Op
), VT
));
2528 KnownUndef
.clearAllBits();
2532 if (Op
.getOpcode() >= ISD::BUILTIN_OP_END
) {
2533 if (SimplifyDemandedVectorEltsForTargetNode(Op
, DemandedElts
, KnownUndef
,
2534 KnownZero
, TLO
, Depth
))
2538 APInt DemandedBits
= APInt::getAllOnesValue(EltSizeInBits
);
2539 if (SimplifyDemandedBits(Op
, DemandedBits
, OriginalDemandedElts
, Known
,
2540 TLO
, Depth
, AssumeSingleUse
))
2546 assert((KnownUndef
& KnownZero
) == 0 && "Elements flagged as undef AND zero");
2548 // Constant fold all undef cases.
2549 // TODO: Handle zero cases as well.
2550 if (DemandedElts
.isSubsetOf(KnownUndef
))
2551 return TLO
.CombineTo(Op
, TLO
.DAG
.getUNDEF(VT
));
2556 /// Determine which of the bits specified in Mask are known to be either zero or
2557 /// one and return them in the Known.
2558 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op
,
2560 const APInt
&DemandedElts
,
2561 const SelectionDAG
&DAG
,
2562 unsigned Depth
) const {
2563 assert((Op
.getOpcode() >= ISD::BUILTIN_OP_END
||
2564 Op
.getOpcode() == ISD::INTRINSIC_WO_CHAIN
||
2565 Op
.getOpcode() == ISD::INTRINSIC_W_CHAIN
||
2566 Op
.getOpcode() == ISD::INTRINSIC_VOID
) &&
2567 "Should use MaskedValueIsZero if you don't know whether Op"
2568 " is a target node!");
2572 void TargetLowering::computeKnownBitsForTargetInstr(
2573 Register R
, KnownBits
&Known
, const APInt
&DemandedElts
,
2574 const MachineRegisterInfo
&MRI
, unsigned Depth
) const {
2578 void TargetLowering::computeKnownBitsForFrameIndex(const SDValue Op
,
2580 const APInt
&DemandedElts
,
2581 const SelectionDAG
&DAG
,
2582 unsigned Depth
) const {
2583 assert(isa
<FrameIndexSDNode
>(Op
) && "expected FrameIndex");
2585 if (unsigned Align
= DAG
.InferPtrAlignment(Op
)) {
2586 // The low bits are known zero if the pointer is aligned.
2587 Known
.Zero
.setLowBits(Log2_32(Align
));
2591 /// This method can be implemented by targets that want to expose additional
2592 /// information about sign bits to the DAG Combiner.
2593 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op
,
2595 const SelectionDAG
&,
2596 unsigned Depth
) const {
2597 assert((Op
.getOpcode() >= ISD::BUILTIN_OP_END
||
2598 Op
.getOpcode() == ISD::INTRINSIC_WO_CHAIN
||
2599 Op
.getOpcode() == ISD::INTRINSIC_W_CHAIN
||
2600 Op
.getOpcode() == ISD::INTRINSIC_VOID
) &&
2601 "Should use ComputeNumSignBits if you don't know whether Op"
2602 " is a target node!");
2606 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
2607 SDValue Op
, const APInt
&DemandedElts
, APInt
&KnownUndef
, APInt
&KnownZero
,
2608 TargetLoweringOpt
&TLO
, unsigned Depth
) const {
2609 assert((Op
.getOpcode() >= ISD::BUILTIN_OP_END
||
2610 Op
.getOpcode() == ISD::INTRINSIC_WO_CHAIN
||
2611 Op
.getOpcode() == ISD::INTRINSIC_W_CHAIN
||
2612 Op
.getOpcode() == ISD::INTRINSIC_VOID
) &&
2613 "Should use SimplifyDemandedVectorElts if you don't know whether Op"
2614 " is a target node!");
2618 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
2619 SDValue Op
, const APInt
&DemandedBits
, const APInt
&DemandedElts
,
2620 KnownBits
&Known
, TargetLoweringOpt
&TLO
, unsigned Depth
) const {
2621 assert((Op
.getOpcode() >= ISD::BUILTIN_OP_END
||
2622 Op
.getOpcode() == ISD::INTRINSIC_WO_CHAIN
||
2623 Op
.getOpcode() == ISD::INTRINSIC_W_CHAIN
||
2624 Op
.getOpcode() == ISD::INTRINSIC_VOID
) &&
2625 "Should use SimplifyDemandedBits if you don't know whether Op"
2626 " is a target node!");
2627 computeKnownBitsForTargetNode(Op
, Known
, DemandedElts
, TLO
.DAG
, Depth
);
2631 SDValue
TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
2632 SDValue Op
, const APInt
&DemandedBits
, const APInt
&DemandedElts
,
2633 SelectionDAG
&DAG
, unsigned Depth
) const {
2635 (Op
.getOpcode() >= ISD::BUILTIN_OP_END
||
2636 Op
.getOpcode() == ISD::INTRINSIC_WO_CHAIN
||
2637 Op
.getOpcode() == ISD::INTRINSIC_W_CHAIN
||
2638 Op
.getOpcode() == ISD::INTRINSIC_VOID
) &&
2639 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
2640 " is a target node!");
2645 TargetLowering::buildLegalVectorShuffle(EVT VT
, const SDLoc
&DL
, SDValue N0
,
2646 SDValue N1
, MutableArrayRef
<int> Mask
,
2647 SelectionDAG
&DAG
) const {
2648 bool LegalMask
= isShuffleMaskLegal(Mask
, VT
);
2651 ShuffleVectorSDNode::commuteMask(Mask
);
2652 LegalMask
= isShuffleMaskLegal(Mask
, VT
);
2658 return DAG
.getVectorShuffle(VT
, DL
, N0
, N1
, Mask
);
2661 const Constant
*TargetLowering::getTargetConstantFromLoad(LoadSDNode
*) const {
2665 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op
,
2666 const SelectionDAG
&DAG
,
2668 unsigned Depth
) const {
2669 assert((Op
.getOpcode() >= ISD::BUILTIN_OP_END
||
2670 Op
.getOpcode() == ISD::INTRINSIC_WO_CHAIN
||
2671 Op
.getOpcode() == ISD::INTRINSIC_W_CHAIN
||
2672 Op
.getOpcode() == ISD::INTRINSIC_VOID
) &&
2673 "Should use isKnownNeverNaN if you don't know whether Op"
2674 " is a target node!");
2678 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
2679 // work with truncating build vectors and vectors with elements of less than
2681 bool TargetLowering::isConstTrueVal(const SDNode
*N
) const {
2686 if (auto *CN
= dyn_cast
<ConstantSDNode
>(N
)) {
2687 CVal
= CN
->getAPIntValue();
2688 } else if (auto *BV
= dyn_cast
<BuildVectorSDNode
>(N
)) {
2689 auto *CN
= BV
->getConstantSplatNode();
2693 // If this is a truncating build vector, truncate the splat value.
2694 // Otherwise, we may fail to match the expected values below.
2695 unsigned BVEltWidth
= BV
->getValueType(0).getScalarSizeInBits();
2696 CVal
= CN
->getAPIntValue();
2697 if (BVEltWidth
< CVal
.getBitWidth())
2698 CVal
= CVal
.trunc(BVEltWidth
);
2703 switch (getBooleanContents(N
->getValueType(0))) {
2704 case UndefinedBooleanContent
:
2706 case ZeroOrOneBooleanContent
:
2707 return CVal
.isOneValue();
2708 case ZeroOrNegativeOneBooleanContent
:
2709 return CVal
.isAllOnesValue();
2712 llvm_unreachable("Invalid boolean contents");
2715 bool TargetLowering::isConstFalseVal(const SDNode
*N
) const {
2719 const ConstantSDNode
*CN
= dyn_cast
<ConstantSDNode
>(N
);
2721 const BuildVectorSDNode
*BV
= dyn_cast
<BuildVectorSDNode
>(N
);
2725 // Only interested in constant splats, we don't care about undef
2726 // elements in identifying boolean constants and getConstantSplatNode
2727 // returns NULL if all ops are undef;
2728 CN
= BV
->getConstantSplatNode();
2733 if (getBooleanContents(N
->getValueType(0)) == UndefinedBooleanContent
)
2734 return !CN
->getAPIntValue()[0];
2736 return CN
->isNullValue();
2739 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode
*N
, EVT VT
,
2744 TargetLowering::BooleanContent Cnt
= getBooleanContents(VT
);
2746 case TargetLowering::ZeroOrOneBooleanContent
:
2747 // An extended value of 1 is always true, unless its original type is i1,
2748 // in which case it will be sign extended to -1.
2749 return (N
->isOne() && !SExt
) || (SExt
&& (N
->getValueType(0) != MVT::i1
));
2750 case TargetLowering::UndefinedBooleanContent
:
2751 case TargetLowering::ZeroOrNegativeOneBooleanContent
:
2752 return N
->isAllOnesValue() && SExt
;
2754 llvm_unreachable("Unexpected enumeration.");
2757 /// This helper function of SimplifySetCC tries to optimize the comparison when
2758 /// either operand of the SetCC node is a bitwise-and instruction.
2759 SDValue
TargetLowering::foldSetCCWithAnd(EVT VT
, SDValue N0
, SDValue N1
,
2760 ISD::CondCode Cond
, const SDLoc
&DL
,
2761 DAGCombinerInfo
&DCI
) const {
2762 // Match these patterns in any of their permutations:
2765 if (N1
.getOpcode() == ISD::AND
&& N0
.getOpcode() != ISD::AND
)
2768 EVT OpVT
= N0
.getValueType();
2769 if (N0
.getOpcode() != ISD::AND
|| !OpVT
.isInteger() ||
2770 (Cond
!= ISD::SETEQ
&& Cond
!= ISD::SETNE
))
2774 if (N0
.getOperand(0) == N1
) {
2775 X
= N0
.getOperand(1);
2776 Y
= N0
.getOperand(0);
2777 } else if (N0
.getOperand(1) == N1
) {
2778 X
= N0
.getOperand(0);
2779 Y
= N0
.getOperand(1);
2784 SelectionDAG
&DAG
= DCI
.DAG
;
2785 SDValue Zero
= DAG
.getConstant(0, DL
, OpVT
);
2786 if (DAG
.isKnownToBeAPowerOfTwo(Y
)) {
2787 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
2788 // Note that where Y is variable and is known to have at most one bit set
2789 // (for example, if it is Z & 1) we cannot do this; the expressions are not
2790 // equivalent when Y == 0.
2791 Cond
= ISD::getSetCCInverse(Cond
, /*isInteger=*/true);
2792 if (DCI
.isBeforeLegalizeOps() ||
2793 isCondCodeLegal(Cond
, N0
.getSimpleValueType()))
2794 return DAG
.getSetCC(DL
, VT
, N0
, Zero
, Cond
);
2795 } else if (N0
.hasOneUse() && hasAndNotCompare(Y
)) {
2796 // If the target supports an 'and-not' or 'and-complement' logic operation,
2797 // try to use that to make a comparison operation more efficient.
2798 // But don't do this transform if the mask is a single bit because there are
2799 // more efficient ways to deal with that case (for example, 'bt' on x86 or
2800 // 'rlwinm' on PPC).
2802 // Bail out if the compare operand that we want to turn into a zero is
2803 // already a zero (otherwise, infinite loop).
2804 auto *YConst
= dyn_cast
<ConstantSDNode
>(Y
);
2805 if (YConst
&& YConst
->isNullValue())
2808 // Transform this into: ~X & Y == 0.
2809 SDValue NotX
= DAG
.getNOT(SDLoc(X
), X
, OpVT
);
2810 SDValue NewAnd
= DAG
.getNode(ISD::AND
, SDLoc(N0
), OpVT
, NotX
, Y
);
2811 return DAG
.getSetCC(DL
, VT
, NewAnd
, Zero
, Cond
);
2817 /// There are multiple IR patterns that could be checking whether certain
2818 /// truncation of a signed number would be lossy or not. The pattern which is
2819 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
2820 /// We are looking for the following pattern: (KeptBits is a constant)
2821 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
2822 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
2823 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0
2824 /// We will unfold it into the natural trunc+sext pattern:
2825 /// ((%x << C) a>> C) dstcond %x
2826 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
2827 SDValue
TargetLowering::optimizeSetCCOfSignedTruncationCheck(
2828 EVT SCCVT
, SDValue N0
, SDValue N1
, ISD::CondCode Cond
, DAGCombinerInfo
&DCI
,
2829 const SDLoc
&DL
) const {
2830 // We must be comparing with a constant.
2832 if (!(C1
= dyn_cast
<ConstantSDNode
>(N1
)))
2835 // N0 should be: add %x, (1 << (KeptBits-1))
2836 if (N0
->getOpcode() != ISD::ADD
)
2839 // And we must be 'add'ing a constant.
2840 ConstantSDNode
*C01
;
2841 if (!(C01
= dyn_cast
<ConstantSDNode
>(N0
->getOperand(1))))
2844 SDValue X
= N0
->getOperand(0);
2845 EVT XVT
= X
.getValueType();
2847 // Validate constants ...
2849 APInt I1
= C1
->getAPIntValue();
2851 ISD::CondCode NewCond
;
2852 if (Cond
== ISD::CondCode::SETULT
) {
2853 NewCond
= ISD::CondCode::SETEQ
;
2854 } else if (Cond
== ISD::CondCode::SETULE
) {
2855 NewCond
= ISD::CondCode::SETEQ
;
2856 // But need to 'canonicalize' the constant.
2858 } else if (Cond
== ISD::CondCode::SETUGT
) {
2859 NewCond
= ISD::CondCode::SETNE
;
2860 // But need to 'canonicalize' the constant.
2862 } else if (Cond
== ISD::CondCode::SETUGE
) {
2863 NewCond
= ISD::CondCode::SETNE
;
2867 APInt I01
= C01
->getAPIntValue();
2869 auto checkConstants
= [&I1
, &I01
]() -> bool {
2870 // Both of them must be power-of-two, and the constant from setcc is bigger.
2871 return I1
.ugt(I01
) && I1
.isPowerOf2() && I01
.isPowerOf2();
2874 if (checkConstants()) {
2875 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
2877 // What if we invert constants? (and the target predicate)
2880 NewCond
= getSetCCInverse(NewCond
, /*isInteger=*/true);
2881 if (!checkConstants())
2883 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
2886 // They are power-of-two, so which bit is set?
2887 const unsigned KeptBits
= I1
.logBase2();
2888 const unsigned KeptBitsMinusOne
= I01
.logBase2();
2891 if (KeptBits
!= (KeptBitsMinusOne
+ 1))
2893 assert(KeptBits
> 0 && KeptBits
< XVT
.getSizeInBits() && "unreachable");
2895 // We don't want to do this in every single case.
2896 SelectionDAG
&DAG
= DCI
.DAG
;
2897 if (!DAG
.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
2901 const unsigned MaskedBits
= XVT
.getSizeInBits() - KeptBits
;
2902 assert(MaskedBits
> 0 && MaskedBits
< XVT
.getSizeInBits() && "unreachable");
2904 // Unfold into: ((%x << C) a>> C) cond %x
2905 // Where 'cond' will be either 'eq' or 'ne'.
2906 SDValue ShiftAmt
= DAG
.getConstant(MaskedBits
, DL
, XVT
);
2907 SDValue T0
= DAG
.getNode(ISD::SHL
, DL
, XVT
, X
, ShiftAmt
);
2908 SDValue T1
= DAG
.getNode(ISD::SRA
, DL
, XVT
, T0
, ShiftAmt
);
2909 SDValue T2
= DAG
.getSetCC(DL
, SCCVT
, T1
, X
, NewCond
);
2914 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
2915 SDValue
TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
2916 EVT SCCVT
, SDValue N0
, SDValue N1C
, ISD::CondCode Cond
,
2917 DAGCombinerInfo
&DCI
, const SDLoc
&DL
) const {
2918 assert(isConstOrConstSplat(N1C
) &&
2919 isConstOrConstSplat(N1C
)->getAPIntValue().isNullValue() &&
2920 "Should be a comparison with 0.");
2921 assert((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
2922 "Valid only for [in]equality comparisons.");
2924 unsigned NewShiftOpcode
;
2927 SelectionDAG
&DAG
= DCI
.DAG
;
2928 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
2930 // Look for '(C l>>/<< Y)'.
2931 auto Match
= [&NewShiftOpcode
, &X
, &C
, &Y
, &TLI
, &DAG
](SDValue V
) {
2932 // The shift should be one-use.
2935 unsigned OldShiftOpcode
= V
.getOpcode();
2936 switch (OldShiftOpcode
) {
2938 NewShiftOpcode
= ISD::SRL
;
2941 NewShiftOpcode
= ISD::SHL
;
2944 return false; // must be a logical shift.
2946 // We should be shifting a constant.
2947 // FIXME: best to use isConstantOrConstantVector().
2948 C
= V
.getOperand(0);
2949 ConstantSDNode
*CC
=
2950 isConstOrConstSplat(C
, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
2953 Y
= V
.getOperand(1);
2955 ConstantSDNode
*XC
=
2956 isConstOrConstSplat(X
, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
2957 return TLI
.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
2958 X
, XC
, CC
, Y
, OldShiftOpcode
, NewShiftOpcode
, DAG
);
2961 // LHS of comparison should be an one-use 'and'.
2962 if (N0
.getOpcode() != ISD::AND
|| !N0
.hasOneUse())
2965 X
= N0
.getOperand(0);
2966 SDValue Mask
= N0
.getOperand(1);
2968 // 'and' is commutative!
2975 EVT VT
= X
.getValueType();
2978 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
2979 SDValue T0
= DAG
.getNode(NewShiftOpcode
, DL
, VT
, X
, Y
);
2980 SDValue T1
= DAG
.getNode(ISD::AND
, DL
, VT
, T0
, C
);
2981 SDValue T2
= DAG
.getSetCC(DL
, SCCVT
, T1
, N1C
, Cond
);
2985 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
2986 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
2987 /// handle the commuted versions of these patterns.
2988 SDValue
TargetLowering::foldSetCCWithBinOp(EVT VT
, SDValue N0
, SDValue N1
,
2989 ISD::CondCode Cond
, const SDLoc
&DL
,
2990 DAGCombinerInfo
&DCI
) const {
2991 unsigned BOpcode
= N0
.getOpcode();
2992 assert((BOpcode
== ISD::ADD
|| BOpcode
== ISD::SUB
|| BOpcode
== ISD::XOR
) &&
2993 "Unexpected binop");
2994 assert((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) && "Unexpected condcode");
2996 // (X + Y) == X --> Y == 0
2997 // (X - Y) == X --> Y == 0
2998 // (X ^ Y) == X --> Y == 0
2999 SelectionDAG
&DAG
= DCI
.DAG
;
3000 EVT OpVT
= N0
.getValueType();
3001 SDValue X
= N0
.getOperand(0);
3002 SDValue Y
= N0
.getOperand(1);
3004 return DAG
.getSetCC(DL
, VT
, Y
, DAG
.getConstant(0, DL
, OpVT
), Cond
);
3009 // (X + Y) == Y --> X == 0
3010 // (X ^ Y) == Y --> X == 0
3011 if (BOpcode
== ISD::ADD
|| BOpcode
== ISD::XOR
)
3012 return DAG
.getSetCC(DL
, VT
, X
, DAG
.getConstant(0, DL
, OpVT
), Cond
);
3014 // The shift would not be valid if the operands are boolean (i1).
3015 if (!N0
.hasOneUse() || OpVT
.getScalarSizeInBits() == 1)
3018 // (X - Y) == Y --> X == Y << 1
3019 EVT ShiftVT
= getShiftAmountTy(OpVT
, DAG
.getDataLayout(),
3020 !DCI
.isBeforeLegalize());
3021 SDValue One
= DAG
.getConstant(1, DL
, ShiftVT
);
3022 SDValue YShl1
= DAG
.getNode(ISD::SHL
, DL
, N1
.getValueType(), Y
, One
);
3023 if (!DCI
.isCalledByLegalizer())
3024 DCI
.AddToWorklist(YShl1
.getNode());
3025 return DAG
.getSetCC(DL
, VT
, X
, YShl1
, Cond
);
3028 /// Try to simplify a setcc built with the specified operands and cc. If it is
3029 /// unable to simplify it, return a null SDValue.
3030 SDValue
TargetLowering::SimplifySetCC(EVT VT
, SDValue N0
, SDValue N1
,
3031 ISD::CondCode Cond
, bool foldBooleans
,
3032 DAGCombinerInfo
&DCI
,
3033 const SDLoc
&dl
) const {
3034 SelectionDAG
&DAG
= DCI
.DAG
;
3035 EVT OpVT
= N0
.getValueType();
3037 // Constant fold or commute setcc.
3038 if (SDValue Fold
= DAG
.FoldSetCC(VT
, N0
, N1
, Cond
, dl
))
3041 // Ensure that the constant occurs on the RHS and fold constant comparisons.
3042 // TODO: Handle non-splat vector constants. All undef causes trouble.
3043 ISD::CondCode SwappedCC
= ISD::getSetCCSwappedOperands(Cond
);
3044 if (isConstOrConstSplat(N0
) &&
3045 (DCI
.isBeforeLegalizeOps() ||
3046 isCondCodeLegal(SwappedCC
, N0
.getSimpleValueType())))
3047 return DAG
.getSetCC(dl
, VT
, N1
, N0
, SwappedCC
);
3049 // If we have a subtract with the same 2 non-constant operands as this setcc
3050 // -- but in reverse order -- then try to commute the operands of this setcc
3051 // to match. A matching pair of setcc (cmp) and sub may be combined into 1
3052 // instruction on some targets.
3053 if (!isConstOrConstSplat(N0
) && !isConstOrConstSplat(N1
) &&
3054 (DCI
.isBeforeLegalizeOps() ||
3055 isCondCodeLegal(SwappedCC
, N0
.getSimpleValueType())) &&
3056 DAG
.getNodeIfExists(ISD::SUB
, DAG
.getVTList(OpVT
), { N1
, N0
} ) &&
3057 !DAG
.getNodeIfExists(ISD::SUB
, DAG
.getVTList(OpVT
), { N0
, N1
} ))
3058 return DAG
.getSetCC(dl
, VT
, N1
, N0
, SwappedCC
);
3060 if (auto *N1C
= dyn_cast
<ConstantSDNode
>(N1
.getNode())) {
3061 const APInt
&C1
= N1C
->getAPIntValue();
3063 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3064 // equality comparison, then we're just comparing whether X itself is
3066 if (N0
.getOpcode() == ISD::SRL
&& (C1
.isNullValue() || C1
.isOneValue()) &&
3067 N0
.getOperand(0).getOpcode() == ISD::CTLZ
&&
3068 N0
.getOperand(1).getOpcode() == ISD::Constant
) {
3069 const APInt
&ShAmt
= N0
.getConstantOperandAPInt(1);
3070 if ((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
3071 ShAmt
== Log2_32(N0
.getValueSizeInBits())) {
3072 if ((C1
== 0) == (Cond
== ISD::SETEQ
)) {
3073 // (srl (ctlz x), 5) == 0 -> X != 0
3074 // (srl (ctlz x), 5) != 1 -> X != 0
3077 // (srl (ctlz x), 5) != 0 -> X == 0
3078 // (srl (ctlz x), 5) == 1 -> X == 0
3081 SDValue Zero
= DAG
.getConstant(0, dl
, N0
.getValueType());
3082 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0).getOperand(0),
3088 // Look through truncs that don't change the value of a ctpop.
3089 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::TRUNCATE
)
3090 CTPOP
= N0
.getOperand(0);
3092 if (CTPOP
.hasOneUse() && CTPOP
.getOpcode() == ISD::CTPOP
&&
3094 N0
.getValueSizeInBits() > Log2_32_Ceil(CTPOP
.getValueSizeInBits()))) {
3095 EVT CTVT
= CTPOP
.getValueType();
3096 SDValue CTOp
= CTPOP
.getOperand(0);
3098 // (ctpop x) u< 2 -> (x & x-1) == 0
3099 // (ctpop x) u> 1 -> (x & x-1) != 0
3100 if ((Cond
== ISD::SETULT
&& C1
== 2) || (Cond
== ISD::SETUGT
&& C1
== 1)){
3101 SDValue NegOne
= DAG
.getAllOnesConstant(dl
, CTVT
);
3102 SDValue Add
= DAG
.getNode(ISD::ADD
, dl
, CTVT
, CTOp
, NegOne
);
3103 SDValue And
= DAG
.getNode(ISD::AND
, dl
, CTVT
, CTOp
, Add
);
3104 ISD::CondCode CC
= Cond
== ISD::SETULT
? ISD::SETEQ
: ISD::SETNE
;
3105 return DAG
.getSetCC(dl
, VT
, And
, DAG
.getConstant(0, dl
, CTVT
), CC
);
3108 // If ctpop is not supported, expand a power-of-2 comparison based on it.
3109 if (C1
== 1 && !isOperationLegalOrCustom(ISD::CTPOP
, CTVT
) &&
3110 (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
)) {
3111 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0)
3112 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0)
3113 SDValue Zero
= DAG
.getConstant(0, dl
, CTVT
);
3114 SDValue NegOne
= DAG
.getAllOnesConstant(dl
, CTVT
);
3115 ISD::CondCode InvCond
= ISD::getSetCCInverse(Cond
, true);
3116 SDValue Add
= DAG
.getNode(ISD::ADD
, dl
, CTVT
, CTOp
, NegOne
);
3117 SDValue And
= DAG
.getNode(ISD::AND
, dl
, CTVT
, CTOp
, Add
);
3118 SDValue LHS
= DAG
.getSetCC(dl
, VT
, CTOp
, Zero
, InvCond
);
3119 SDValue RHS
= DAG
.getSetCC(dl
, VT
, And
, Zero
, Cond
);
3120 unsigned LogicOpcode
= Cond
== ISD::SETEQ
? ISD::AND
: ISD::OR
;
3121 return DAG
.getNode(LogicOpcode
, dl
, VT
, LHS
, RHS
);
3125 // (zext x) == C --> x == (trunc C)
3126 // (sext x) == C --> x == (trunc C)
3127 if ((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
3128 DCI
.isBeforeLegalize() && N0
->hasOneUse()) {
3129 unsigned MinBits
= N0
.getValueSizeInBits();
3131 bool Signed
= false;
3132 if (N0
->getOpcode() == ISD::ZERO_EXTEND
) {
3134 MinBits
= N0
->getOperand(0).getValueSizeInBits();
3135 PreExt
= N0
->getOperand(0);
3136 } else if (N0
->getOpcode() == ISD::AND
) {
3137 // DAGCombine turns costly ZExts into ANDs
3138 if (auto *C
= dyn_cast
<ConstantSDNode
>(N0
->getOperand(1)))
3139 if ((C
->getAPIntValue()+1).isPowerOf2()) {
3140 MinBits
= C
->getAPIntValue().countTrailingOnes();
3141 PreExt
= N0
->getOperand(0);
3143 } else if (N0
->getOpcode() == ISD::SIGN_EXTEND
) {
3145 MinBits
= N0
->getOperand(0).getValueSizeInBits();
3146 PreExt
= N0
->getOperand(0);
3148 } else if (auto *LN0
= dyn_cast
<LoadSDNode
>(N0
)) {
3149 // ZEXTLOAD / SEXTLOAD
3150 if (LN0
->getExtensionType() == ISD::ZEXTLOAD
) {
3151 MinBits
= LN0
->getMemoryVT().getSizeInBits();
3153 } else if (LN0
->getExtensionType() == ISD::SEXTLOAD
) {
3155 MinBits
= LN0
->getMemoryVT().getSizeInBits();
3160 // Figure out how many bits we need to preserve this constant.
3161 unsigned ReqdBits
= Signed
?
3162 C1
.getBitWidth() - C1
.getNumSignBits() + 1 :
3165 // Make sure we're not losing bits from the constant.
3167 MinBits
< C1
.getBitWidth() &&
3168 MinBits
>= ReqdBits
) {
3169 EVT MinVT
= EVT::getIntegerVT(*DAG
.getContext(), MinBits
);
3170 if (isTypeDesirableForOp(ISD::SETCC
, MinVT
)) {
3171 // Will get folded away.
3172 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, dl
, MinVT
, PreExt
);
3173 if (MinBits
== 1 && C1
== 1)
3174 // Invert the condition.
3175 return DAG
.getSetCC(dl
, VT
, Trunc
, DAG
.getConstant(0, dl
, MVT::i1
),
3176 Cond
== ISD::SETEQ
? ISD::SETNE
: ISD::SETEQ
);
3177 SDValue C
= DAG
.getConstant(C1
.trunc(MinBits
), dl
, MinVT
);
3178 return DAG
.getSetCC(dl
, VT
, Trunc
, C
, Cond
);
3181 // If truncating the setcc operands is not desirable, we can still
3182 // simplify the expression in some cases:
3183 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
3184 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
3185 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
3186 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
3187 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
3188 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
3189 SDValue TopSetCC
= N0
->getOperand(0);
3190 unsigned N0Opc
= N0
->getOpcode();
3191 bool SExt
= (N0Opc
== ISD::SIGN_EXTEND
);
3192 if (TopSetCC
.getValueType() == MVT::i1
&& VT
== MVT::i1
&&
3193 TopSetCC
.getOpcode() == ISD::SETCC
&&
3194 (N0Opc
== ISD::ZERO_EXTEND
|| N0Opc
== ISD::SIGN_EXTEND
) &&
3195 (isConstFalseVal(N1C
) ||
3196 isExtendedTrueVal(N1C
, N0
->getValueType(0), SExt
))) {
3198 bool Inverse
= (N1C
->isNullValue() && Cond
== ISD::SETEQ
) ||
3199 (!N1C
->isNullValue() && Cond
== ISD::SETNE
);
3204 ISD::CondCode InvCond
= ISD::getSetCCInverse(
3205 cast
<CondCodeSDNode
>(TopSetCC
.getOperand(2))->get(),
3206 TopSetCC
.getOperand(0).getValueType().isInteger());
3207 return DAG
.getSetCC(dl
, VT
, TopSetCC
.getOperand(0),
3208 TopSetCC
.getOperand(1),
3214 // If the LHS is '(and load, const)', the RHS is 0, the test is for
3215 // equality or unsigned, and all 1 bits of the const are in the same
3216 // partial word, see if we can shorten the load.
3217 if (DCI
.isBeforeLegalize() &&
3218 !ISD::isSignedIntSetCC(Cond
) &&
3219 N0
.getOpcode() == ISD::AND
&& C1
== 0 &&
3220 N0
.getNode()->hasOneUse() &&
3221 isa
<LoadSDNode
>(N0
.getOperand(0)) &&
3222 N0
.getOperand(0).getNode()->hasOneUse() &&
3223 isa
<ConstantSDNode
>(N0
.getOperand(1))) {
3224 LoadSDNode
*Lod
= cast
<LoadSDNode
>(N0
.getOperand(0));
3226 unsigned bestWidth
= 0, bestOffset
= 0;
3227 if (!Lod
->isVolatile() && Lod
->isUnindexed()) {
3228 unsigned origWidth
= N0
.getValueSizeInBits();
3229 unsigned maskWidth
= origWidth
;
3230 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
3231 // 8 bits, but have to be careful...
3232 if (Lod
->getExtensionType() != ISD::NON_EXTLOAD
)
3233 origWidth
= Lod
->getMemoryVT().getSizeInBits();
3234 const APInt
&Mask
= N0
.getConstantOperandAPInt(1);
3235 for (unsigned width
= origWidth
/ 2; width
>=8; width
/= 2) {
3236 APInt newMask
= APInt::getLowBitsSet(maskWidth
, width
);
3237 for (unsigned offset
=0; offset
<origWidth
/width
; offset
++) {
3238 if (Mask
.isSubsetOf(newMask
)) {
3239 if (DAG
.getDataLayout().isLittleEndian())
3240 bestOffset
= (uint64_t)offset
* (width
/8);
3242 bestOffset
= (origWidth
/width
- offset
- 1) * (width
/8);
3243 bestMask
= Mask
.lshr(offset
* (width
/8) * 8);
3252 EVT newVT
= EVT::getIntegerVT(*DAG
.getContext(), bestWidth
);
3253 if (newVT
.isRound() &&
3254 shouldReduceLoadWidth(Lod
, ISD::NON_EXTLOAD
, newVT
)) {
3255 EVT PtrType
= Lod
->getOperand(1).getValueType();
3256 SDValue Ptr
= Lod
->getBasePtr();
3257 if (bestOffset
!= 0)
3258 Ptr
= DAG
.getNode(ISD::ADD
, dl
, PtrType
, Lod
->getBasePtr(),
3259 DAG
.getConstant(bestOffset
, dl
, PtrType
));
3260 unsigned NewAlign
= MinAlign(Lod
->getAlignment(), bestOffset
);
3261 SDValue NewLoad
= DAG
.getLoad(
3262 newVT
, dl
, Lod
->getChain(), Ptr
,
3263 Lod
->getPointerInfo().getWithOffset(bestOffset
), NewAlign
);
3264 return DAG
.getSetCC(dl
, VT
,
3265 DAG
.getNode(ISD::AND
, dl
, newVT
, NewLoad
,
3266 DAG
.getConstant(bestMask
.trunc(bestWidth
),
3268 DAG
.getConstant(0LL, dl
, newVT
), Cond
);
3273 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3274 if (N0
.getOpcode() == ISD::ZERO_EXTEND
) {
3275 unsigned InSize
= N0
.getOperand(0).getValueSizeInBits();
3277 // If the comparison constant has bits in the upper part, the
3278 // zero-extended value could never match.
3279 if (C1
.intersects(APInt::getHighBitsSet(C1
.getBitWidth(),
3280 C1
.getBitWidth() - InSize
))) {
3285 return DAG
.getConstant(0, dl
, VT
);
3289 return DAG
.getConstant(1, dl
, VT
);
3292 // True if the sign bit of C1 is set.
3293 return DAG
.getConstant(C1
.isNegative(), dl
, VT
);
3296 // True if the sign bit of C1 isn't set.
3297 return DAG
.getConstant(C1
.isNonNegative(), dl
, VT
);
3303 // Otherwise, we can perform the comparison with the low bits.
3311 EVT newVT
= N0
.getOperand(0).getValueType();
3312 if (DCI
.isBeforeLegalizeOps() ||
3313 (isOperationLegal(ISD::SETCC
, newVT
) &&
3314 isCondCodeLegal(Cond
, newVT
.getSimpleVT()))) {
3316 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), newVT
);
3317 SDValue NewConst
= DAG
.getConstant(C1
.trunc(InSize
), dl
, newVT
);
3319 SDValue NewSetCC
= DAG
.getSetCC(dl
, NewSetCCVT
, N0
.getOperand(0),
3321 return DAG
.getBoolExtOrTrunc(NewSetCC
, dl
, VT
, N0
.getValueType());
3326 break; // todo, be more careful with signed comparisons
3328 } else if (N0
.getOpcode() == ISD::SIGN_EXTEND_INREG
&&
3329 (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
)) {
3330 EVT ExtSrcTy
= cast
<VTSDNode
>(N0
.getOperand(1))->getVT();
3331 unsigned ExtSrcTyBits
= ExtSrcTy
.getSizeInBits();
3332 EVT ExtDstTy
= N0
.getValueType();
3333 unsigned ExtDstTyBits
= ExtDstTy
.getSizeInBits();
3335 // If the constant doesn't fit into the number of bits for the source of
3336 // the sign extension, it is impossible for both sides to be equal.
3337 if (C1
.getMinSignedBits() > ExtSrcTyBits
)
3338 return DAG
.getConstant(Cond
== ISD::SETNE
, dl
, VT
);
3341 EVT Op0Ty
= N0
.getOperand(0).getValueType();
3342 if (Op0Ty
== ExtSrcTy
) {
3343 ZextOp
= N0
.getOperand(0);
3345 APInt Imm
= APInt::getLowBitsSet(ExtDstTyBits
, ExtSrcTyBits
);
3346 ZextOp
= DAG
.getNode(ISD::AND
, dl
, Op0Ty
, N0
.getOperand(0),
3347 DAG
.getConstant(Imm
, dl
, Op0Ty
));
3349 if (!DCI
.isCalledByLegalizer())
3350 DCI
.AddToWorklist(ZextOp
.getNode());
3351 // Otherwise, make this a use of a zext.
3352 return DAG
.getSetCC(dl
, VT
, ZextOp
,
3353 DAG
.getConstant(C1
& APInt::getLowBitsSet(
3358 } else if ((N1C
->isNullValue() || N1C
->isOne()) &&
3359 (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
)) {
3360 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
3361 if (N0
.getOpcode() == ISD::SETCC
&&
3362 isTypeLegal(VT
) && VT
.bitsLE(N0
.getValueType())) {
3363 bool TrueWhenTrue
= (Cond
== ISD::SETEQ
) ^ (!N1C
->isOne());
3365 return DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, N0
);
3366 // Invert the condition.
3367 ISD::CondCode CC
= cast
<CondCodeSDNode
>(N0
.getOperand(2))->get();
3368 CC
= ISD::getSetCCInverse(CC
,
3369 N0
.getOperand(0).getValueType().isInteger());
3370 if (DCI
.isBeforeLegalizeOps() ||
3371 isCondCodeLegal(CC
, N0
.getOperand(0).getSimpleValueType()))
3372 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0), N0
.getOperand(1), CC
);
3375 if ((N0
.getOpcode() == ISD::XOR
||
3376 (N0
.getOpcode() == ISD::AND
&&
3377 N0
.getOperand(0).getOpcode() == ISD::XOR
&&
3378 N0
.getOperand(1) == N0
.getOperand(0).getOperand(1))) &&
3379 isa
<ConstantSDNode
>(N0
.getOperand(1)) &&
3380 cast
<ConstantSDNode
>(N0
.getOperand(1))->isOne()) {
3381 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
3382 // can only do this if the top bits are known zero.
3383 unsigned BitWidth
= N0
.getValueSizeInBits();
3384 if (DAG
.MaskedValueIsZero(N0
,
3385 APInt::getHighBitsSet(BitWidth
,
3387 // Okay, get the un-inverted input value.
3389 if (N0
.getOpcode() == ISD::XOR
) {
3390 Val
= N0
.getOperand(0);
3392 assert(N0
.getOpcode() == ISD::AND
&&
3393 N0
.getOperand(0).getOpcode() == ISD::XOR
);
3394 // ((X^1)&1)^1 -> X & 1
3395 Val
= DAG
.getNode(ISD::AND
, dl
, N0
.getValueType(),
3396 N0
.getOperand(0).getOperand(0),
3400 return DAG
.getSetCC(dl
, VT
, Val
, N1
,
3401 Cond
== ISD::SETEQ
? ISD::SETNE
: ISD::SETEQ
);
3403 } else if (N1C
->isOne() &&
3405 getBooleanContents(N0
->getValueType(0)) ==
3406 ZeroOrOneBooleanContent
)) {
3408 if (Op0
.getOpcode() == ISD::TRUNCATE
)
3409 Op0
= Op0
.getOperand(0);
3411 if ((Op0
.getOpcode() == ISD::XOR
) &&
3412 Op0
.getOperand(0).getOpcode() == ISD::SETCC
&&
3413 Op0
.getOperand(1).getOpcode() == ISD::SETCC
) {
3414 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
3415 Cond
= (Cond
== ISD::SETEQ
) ? ISD::SETNE
: ISD::SETEQ
;
3416 return DAG
.getSetCC(dl
, VT
, Op0
.getOperand(0), Op0
.getOperand(1),
3419 if (Op0
.getOpcode() == ISD::AND
&&
3420 isa
<ConstantSDNode
>(Op0
.getOperand(1)) &&
3421 cast
<ConstantSDNode
>(Op0
.getOperand(1))->isOne()) {
3422 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
3423 if (Op0
.getValueType().bitsGT(VT
))
3424 Op0
= DAG
.getNode(ISD::AND
, dl
, VT
,
3425 DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, Op0
.getOperand(0)),
3426 DAG
.getConstant(1, dl
, VT
));
3427 else if (Op0
.getValueType().bitsLT(VT
))
3428 Op0
= DAG
.getNode(ISD::AND
, dl
, VT
,
3429 DAG
.getNode(ISD::ANY_EXTEND
, dl
, VT
, Op0
.getOperand(0)),
3430 DAG
.getConstant(1, dl
, VT
));
3432 return DAG
.getSetCC(dl
, VT
, Op0
,
3433 DAG
.getConstant(0, dl
, Op0
.getValueType()),
3434 Cond
== ISD::SETEQ
? ISD::SETNE
: ISD::SETEQ
);
3436 if (Op0
.getOpcode() == ISD::AssertZext
&&
3437 cast
<VTSDNode
>(Op0
.getOperand(1))->getVT() == MVT::i1
)
3438 return DAG
.getSetCC(dl
, VT
, Op0
,
3439 DAG
.getConstant(0, dl
, Op0
.getValueType()),
3440 Cond
== ISD::SETEQ
? ISD::SETNE
: ISD::SETEQ
);
3445 // icmp eq/ne (urem %x, %y), 0
3446 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
3448 if (N0
.getOpcode() == ISD::UREM
&& N1C
->isNullValue() &&
3449 (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
)) {
3450 KnownBits XKnown
= DAG
.computeKnownBits(N0
.getOperand(0));
3451 KnownBits YKnown
= DAG
.computeKnownBits(N0
.getOperand(1));
3452 if (XKnown
.countMaxPopulation() == 1 && YKnown
.countMinPopulation() >= 2)
3453 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0), N1
, Cond
);
3457 optimizeSetCCOfSignedTruncationCheck(VT
, N0
, N1
, Cond
, DCI
, dl
))
3461 // These simplifications apply to splat vectors as well.
3462 // TODO: Handle more splat vector cases.
3463 if (auto *N1C
= isConstOrConstSplat(N1
)) {
3464 const APInt
&C1
= N1C
->getAPIntValue();
3466 APInt MinVal
, MaxVal
;
3467 unsigned OperandBitSize
= N1C
->getValueType(0).getScalarSizeInBits();
3468 if (ISD::isSignedIntSetCC(Cond
)) {
3469 MinVal
= APInt::getSignedMinValue(OperandBitSize
);
3470 MaxVal
= APInt::getSignedMaxValue(OperandBitSize
);
3472 MinVal
= APInt::getMinValue(OperandBitSize
);
3473 MaxVal
= APInt::getMaxValue(OperandBitSize
);
3476 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
3477 if (Cond
== ISD::SETGE
|| Cond
== ISD::SETUGE
) {
3478 // X >= MIN --> true
3480 return DAG
.getBoolConstant(true, dl
, VT
, OpVT
);
3482 if (!VT
.isVector()) { // TODO: Support this for vectors.
3483 // X >= C0 --> X > (C0 - 1)
3485 ISD::CondCode NewCC
= (Cond
== ISD::SETGE
) ? ISD::SETGT
: ISD::SETUGT
;
3486 if ((DCI
.isBeforeLegalizeOps() ||
3487 isCondCodeLegal(NewCC
, VT
.getSimpleVT())) &&
3488 (!N1C
->isOpaque() || (C
.getBitWidth() <= 64 &&
3489 isLegalICmpImmediate(C
.getSExtValue())))) {
3490 return DAG
.getSetCC(dl
, VT
, N0
,
3491 DAG
.getConstant(C
, dl
, N1
.getValueType()),
3497 if (Cond
== ISD::SETLE
|| Cond
== ISD::SETULE
) {
3498 // X <= MAX --> true
3500 return DAG
.getBoolConstant(true, dl
, VT
, OpVT
);
3502 // X <= C0 --> X < (C0 + 1)
3503 if (!VT
.isVector()) { // TODO: Support this for vectors.
3505 ISD::CondCode NewCC
= (Cond
== ISD::SETLE
) ? ISD::SETLT
: ISD::SETULT
;
3506 if ((DCI
.isBeforeLegalizeOps() ||
3507 isCondCodeLegal(NewCC
, VT
.getSimpleVT())) &&
3508 (!N1C
->isOpaque() || (C
.getBitWidth() <= 64 &&
3509 isLegalICmpImmediate(C
.getSExtValue())))) {
3510 return DAG
.getSetCC(dl
, VT
, N0
,
3511 DAG
.getConstant(C
, dl
, N1
.getValueType()),
3517 if (Cond
== ISD::SETLT
|| Cond
== ISD::SETULT
) {
3519 return DAG
.getBoolConstant(false, dl
, VT
, OpVT
); // X < MIN --> false
3521 // TODO: Support this for vectors after legalize ops.
3522 if (!VT
.isVector() || DCI
.isBeforeLegalizeOps()) {
3523 // Canonicalize setlt X, Max --> setne X, Max
3525 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETNE
);
3527 // If we have setult X, 1, turn it into seteq X, 0
3529 return DAG
.getSetCC(dl
, VT
, N0
,
3530 DAG
.getConstant(MinVal
, dl
, N0
.getValueType()),
3535 if (Cond
== ISD::SETGT
|| Cond
== ISD::SETUGT
) {
3537 return DAG
.getBoolConstant(false, dl
, VT
, OpVT
); // X > MAX --> false
3539 // TODO: Support this for vectors after legalize ops.
3540 if (!VT
.isVector() || DCI
.isBeforeLegalizeOps()) {
3541 // Canonicalize setgt X, Min --> setne X, Min
3543 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETNE
);
3545 // If we have setugt X, Max-1, turn it into seteq X, Max
3547 return DAG
.getSetCC(dl
, VT
, N0
,
3548 DAG
.getConstant(MaxVal
, dl
, N0
.getValueType()),
3553 if (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) {
3554 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
3555 if (C1
.isNullValue())
3556 if (SDValue CC
= optimizeSetCCByHoistingAndByConstFromLogicalShift(
3557 VT
, N0
, N1
, Cond
, DCI
, dl
))
3561 // If we have "setcc X, C0", check to see if we can shrink the immediate
3563 // TODO: Support this for vectors after legalize ops.
3564 if (!VT
.isVector() || DCI
.isBeforeLegalizeOps()) {
3565 // SETUGT X, SINTMAX -> SETLT X, 0
3566 if (Cond
== ISD::SETUGT
&&
3567 C1
== APInt::getSignedMaxValue(OperandBitSize
))
3568 return DAG
.getSetCC(dl
, VT
, N0
,
3569 DAG
.getConstant(0, dl
, N1
.getValueType()),
3572 // SETULT X, SINTMIN -> SETGT X, -1
3573 if (Cond
== ISD::SETULT
&&
3574 C1
== APInt::getSignedMinValue(OperandBitSize
)) {
3575 SDValue ConstMinusOne
=
3576 DAG
.getConstant(APInt::getAllOnesValue(OperandBitSize
), dl
,
3578 return DAG
.getSetCC(dl
, VT
, N0
, ConstMinusOne
, ISD::SETGT
);
3583 // Back to non-vector simplifications.
3584 // TODO: Can we do these for vector splats?
3585 if (auto *N1C
= dyn_cast
<ConstantSDNode
>(N1
.getNode())) {
3586 const APInt
&C1
= N1C
->getAPIntValue();
3588 // Fold bit comparisons when we can.
3589 if ((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
3590 (VT
== N0
.getValueType() ||
3591 (isTypeLegal(VT
) && VT
.bitsLE(N0
.getValueType()))) &&
3592 N0
.getOpcode() == ISD::AND
) {
3593 auto &DL
= DAG
.getDataLayout();
3594 if (auto *AndRHS
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1))) {
3595 EVT ShiftTy
= getShiftAmountTy(N0
.getValueType(), DL
,
3596 !DCI
.isBeforeLegalize());
3597 if (Cond
== ISD::SETNE
&& C1
== 0) {// (X & 8) != 0 --> (X & 8) >> 3
3598 // Perform the xform if the AND RHS is a single bit.
3599 if (AndRHS
->getAPIntValue().isPowerOf2()) {
3600 return DAG
.getNode(ISD::TRUNCATE
, dl
, VT
,
3601 DAG
.getNode(ISD::SRL
, dl
, N0
.getValueType(), N0
,
3602 DAG
.getConstant(AndRHS
->getAPIntValue().logBase2(), dl
,
3605 } else if (Cond
== ISD::SETEQ
&& C1
== AndRHS
->getAPIntValue()) {
3606 // (X & 8) == 8 --> (X & 8) >> 3
3607 // Perform the xform if C1 is a single bit.
3608 if (C1
.isPowerOf2()) {
3609 return DAG
.getNode(ISD::TRUNCATE
, dl
, VT
,
3610 DAG
.getNode(ISD::SRL
, dl
, N0
.getValueType(), N0
,
3611 DAG
.getConstant(C1
.logBase2(), dl
,
3618 if (C1
.getMinSignedBits() <= 64 &&
3619 !isLegalICmpImmediate(C1
.getSExtValue())) {
3620 // (X & -256) == 256 -> (X >> 8) == 1
3621 if ((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
3622 N0
.getOpcode() == ISD::AND
&& N0
.hasOneUse()) {
3623 if (auto *AndRHS
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1))) {
3624 const APInt
&AndRHSC
= AndRHS
->getAPIntValue();
3625 if ((-AndRHSC
).isPowerOf2() && (AndRHSC
& C1
) == C1
) {
3626 unsigned ShiftBits
= AndRHSC
.countTrailingZeros();
3627 auto &DL
= DAG
.getDataLayout();
3628 EVT ShiftTy
= getShiftAmountTy(N0
.getValueType(), DL
,
3629 !DCI
.isBeforeLegalize());
3630 EVT CmpTy
= N0
.getValueType();
3631 SDValue Shift
= DAG
.getNode(ISD::SRL
, dl
, CmpTy
, N0
.getOperand(0),
3632 DAG
.getConstant(ShiftBits
, dl
,
3634 SDValue CmpRHS
= DAG
.getConstant(C1
.lshr(ShiftBits
), dl
, CmpTy
);
3635 return DAG
.getSetCC(dl
, VT
, Shift
, CmpRHS
, Cond
);
3638 } else if (Cond
== ISD::SETULT
|| Cond
== ISD::SETUGE
||
3639 Cond
== ISD::SETULE
|| Cond
== ISD::SETUGT
) {
3640 bool AdjOne
= (Cond
== ISD::SETULE
|| Cond
== ISD::SETUGT
);
3641 // X < 0x100000000 -> (X >> 32) < 1
3642 // X >= 0x100000000 -> (X >> 32) >= 1
3643 // X <= 0x0ffffffff -> (X >> 32) < 1
3644 // X > 0x0ffffffff -> (X >> 32) >= 1
3647 ISD::CondCode NewCond
= Cond
;
3649 ShiftBits
= C1
.countTrailingOnes();
3651 NewCond
= (Cond
== ISD::SETULE
) ? ISD::SETULT
: ISD::SETUGE
;
3653 ShiftBits
= C1
.countTrailingZeros();
3655 NewC
.lshrInPlace(ShiftBits
);
3656 if (ShiftBits
&& NewC
.getMinSignedBits() <= 64 &&
3657 isLegalICmpImmediate(NewC
.getSExtValue())) {
3658 auto &DL
= DAG
.getDataLayout();
3659 EVT ShiftTy
= getShiftAmountTy(N0
.getValueType(), DL
,
3660 !DCI
.isBeforeLegalize());
3661 EVT CmpTy
= N0
.getValueType();
3662 SDValue Shift
= DAG
.getNode(ISD::SRL
, dl
, CmpTy
, N0
,
3663 DAG
.getConstant(ShiftBits
, dl
, ShiftTy
));
3664 SDValue CmpRHS
= DAG
.getConstant(NewC
, dl
, CmpTy
);
3665 return DAG
.getSetCC(dl
, VT
, Shift
, CmpRHS
, NewCond
);
3671 if (!isa
<ConstantFPSDNode
>(N0
) && isa
<ConstantFPSDNode
>(N1
)) {
3672 auto *CFP
= cast
<ConstantFPSDNode
>(N1
);
3673 assert(!CFP
->getValueAPF().isNaN() && "Unexpected NaN value");
3675 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
3676 // constant if knowing that the operand is non-nan is enough. We prefer to
3677 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
3679 if (Cond
== ISD::SETO
|| Cond
== ISD::SETUO
)
3680 return DAG
.getSetCC(dl
, VT
, N0
, N0
, Cond
);
3682 // setcc (fneg x), C -> setcc swap(pred) x, -C
3683 if (N0
.getOpcode() == ISD::FNEG
) {
3684 ISD::CondCode SwapCond
= ISD::getSetCCSwappedOperands(Cond
);
3685 if (DCI
.isBeforeLegalizeOps() ||
3686 isCondCodeLegal(SwapCond
, N0
.getSimpleValueType())) {
3687 SDValue NegN1
= DAG
.getNode(ISD::FNEG
, dl
, N0
.getValueType(), N1
);
3688 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0), NegN1
, SwapCond
);
3692 // If the condition is not legal, see if we can find an equivalent one
3694 if (!isCondCodeLegal(Cond
, N0
.getSimpleValueType())) {
3695 // If the comparison was an awkward floating-point == or != and one of
3696 // the comparison operands is infinity or negative infinity, convert the
3697 // condition to a less-awkward <= or >=.
3698 if (CFP
->getValueAPF().isInfinity()) {
3699 if (CFP
->getValueAPF().isNegative()) {
3700 if (Cond
== ISD::SETOEQ
&&
3701 isCondCodeLegal(ISD::SETOLE
, N0
.getSimpleValueType()))
3702 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETOLE
);
3703 if (Cond
== ISD::SETUEQ
&&
3704 isCondCodeLegal(ISD::SETOLE
, N0
.getSimpleValueType()))
3705 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETULE
);
3706 if (Cond
== ISD::SETUNE
&&
3707 isCondCodeLegal(ISD::SETUGT
, N0
.getSimpleValueType()))
3708 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETUGT
);
3709 if (Cond
== ISD::SETONE
&&
3710 isCondCodeLegal(ISD::SETUGT
, N0
.getSimpleValueType()))
3711 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETOGT
);
3713 if (Cond
== ISD::SETOEQ
&&
3714 isCondCodeLegal(ISD::SETOGE
, N0
.getSimpleValueType()))
3715 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETOGE
);
3716 if (Cond
== ISD::SETUEQ
&&
3717 isCondCodeLegal(ISD::SETOGE
, N0
.getSimpleValueType()))
3718 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETUGE
);
3719 if (Cond
== ISD::SETUNE
&&
3720 isCondCodeLegal(ISD::SETULT
, N0
.getSimpleValueType()))
3721 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETULT
);
3722 if (Cond
== ISD::SETONE
&&
3723 isCondCodeLegal(ISD::SETULT
, N0
.getSimpleValueType()))
3724 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETOLT
);
3731 // The sext(setcc()) => setcc() optimization relies on the appropriate
3732 // constant being emitted.
3733 assert(!N0
.getValueType().isInteger() &&
3734 "Integer types should be handled by FoldSetCC");
3736 bool EqTrue
= ISD::isTrueWhenEqual(Cond
);
3737 unsigned UOF
= ISD::getUnorderedFlavor(Cond
);
3738 if (UOF
== 2) // FP operators that are undefined on NaNs.
3739 return DAG
.getBoolConstant(EqTrue
, dl
, VT
, OpVT
);
3740 if (UOF
== unsigned(EqTrue
))
3741 return DAG
.getBoolConstant(EqTrue
, dl
, VT
, OpVT
);
3742 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
3743 // if it is not already.
3744 ISD::CondCode NewCond
= UOF
== 0 ? ISD::SETO
: ISD::SETUO
;
3745 if (NewCond
!= Cond
&&
3746 (DCI
.isBeforeLegalizeOps() ||
3747 isCondCodeLegal(NewCond
, N0
.getSimpleValueType())))
3748 return DAG
.getSetCC(dl
, VT
, N0
, N1
, NewCond
);
3751 if ((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
3752 N0
.getValueType().isInteger()) {
3753 if (N0
.getOpcode() == ISD::ADD
|| N0
.getOpcode() == ISD::SUB
||
3754 N0
.getOpcode() == ISD::XOR
) {
3755 // Simplify (X+Y) == (X+Z) --> Y == Z
3756 if (N0
.getOpcode() == N1
.getOpcode()) {
3757 if (N0
.getOperand(0) == N1
.getOperand(0))
3758 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(1), N1
.getOperand(1), Cond
);
3759 if (N0
.getOperand(1) == N1
.getOperand(1))
3760 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0), N1
.getOperand(0), Cond
);
3761 if (isCommutativeBinOp(N0
.getOpcode())) {
3762 // If X op Y == Y op X, try other combinations.
3763 if (N0
.getOperand(0) == N1
.getOperand(1))
3764 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(1), N1
.getOperand(0),
3766 if (N0
.getOperand(1) == N1
.getOperand(0))
3767 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0), N1
.getOperand(1),
3772 // If RHS is a legal immediate value for a compare instruction, we need
3773 // to be careful about increasing register pressure needlessly.
3774 bool LegalRHSImm
= false;
3776 if (auto *RHSC
= dyn_cast
<ConstantSDNode
>(N1
)) {
3777 if (auto *LHSR
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1))) {
3778 // Turn (X+C1) == C2 --> X == C2-C1
3779 if (N0
.getOpcode() == ISD::ADD
&& N0
.getNode()->hasOneUse()) {
3780 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0),
3781 DAG
.getConstant(RHSC
->getAPIntValue()-
3782 LHSR
->getAPIntValue(),
3783 dl
, N0
.getValueType()), Cond
);
3786 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
3787 if (N0
.getOpcode() == ISD::XOR
)
3788 // If we know that all of the inverted bits are zero, don't bother
3789 // performing the inversion.
3790 if (DAG
.MaskedValueIsZero(N0
.getOperand(0), ~LHSR
->getAPIntValue()))
3792 DAG
.getSetCC(dl
, VT
, N0
.getOperand(0),
3793 DAG
.getConstant(LHSR
->getAPIntValue() ^
3794 RHSC
->getAPIntValue(),
3795 dl
, N0
.getValueType()),
3799 // Turn (C1-X) == C2 --> X == C1-C2
3800 if (auto *SUBC
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(0))) {
3801 if (N0
.getOpcode() == ISD::SUB
&& N0
.getNode()->hasOneUse()) {
3803 DAG
.getSetCC(dl
, VT
, N0
.getOperand(1),
3804 DAG
.getConstant(SUBC
->getAPIntValue() -
3805 RHSC
->getAPIntValue(),
3806 dl
, N0
.getValueType()),
3811 // Could RHSC fold directly into a compare?
3812 if (RHSC
->getValueType(0).getSizeInBits() <= 64)
3813 LegalRHSImm
= isLegalICmpImmediate(RHSC
->getSExtValue());
3816 // (X+Y) == X --> Y == 0 and similar folds.
3817 // Don't do this if X is an immediate that can fold into a cmp
3818 // instruction and X+Y has other uses. It could be an induction variable
3819 // chain, and the transform would increase register pressure.
3820 if (!LegalRHSImm
|| N0
.hasOneUse())
3821 if (SDValue V
= foldSetCCWithBinOp(VT
, N0
, N1
, Cond
, dl
, DCI
))
3825 if (N1
.getOpcode() == ISD::ADD
|| N1
.getOpcode() == ISD::SUB
||
3826 N1
.getOpcode() == ISD::XOR
)
3827 if (SDValue V
= foldSetCCWithBinOp(VT
, N1
, N0
, Cond
, dl
, DCI
))
3830 if (SDValue V
= foldSetCCWithAnd(VT
, N0
, N1
, Cond
, dl
, DCI
))
3834 // Fold remainder of division by a constant.
3835 if ((N0
.getOpcode() == ISD::UREM
|| N0
.getOpcode() == ISD::SREM
) &&
3836 N0
.hasOneUse() && (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
)) {
3837 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
3839 // When division is cheap or optimizing for minimum size,
3840 // fall through to DIVREM creation by skipping this fold.
3841 if (!isIntDivCheap(VT
, Attr
) && !Attr
.hasFnAttribute(Attribute::MinSize
)) {
3842 if (N0
.getOpcode() == ISD::UREM
) {
3843 if (SDValue Folded
= buildUREMEqFold(VT
, N0
, N1
, Cond
, DCI
, dl
))
3845 } else if (N0
.getOpcode() == ISD::SREM
) {
3846 if (SDValue Folded
= buildSREMEqFold(VT
, N0
, N1
, Cond
, DCI
, dl
))
3852 // Fold away ALL boolean setcc's.
3853 if (N0
.getValueType().getScalarType() == MVT::i1
&& foldBooleans
) {
3856 default: llvm_unreachable("Unknown integer setcc!");
3857 case ISD::SETEQ
: // X == Y -> ~(X^Y)
3858 Temp
= DAG
.getNode(ISD::XOR
, dl
, OpVT
, N0
, N1
);
3859 N0
= DAG
.getNOT(dl
, Temp
, OpVT
);
3860 if (!DCI
.isCalledByLegalizer())
3861 DCI
.AddToWorklist(Temp
.getNode());
3863 case ISD::SETNE
: // X != Y --> (X^Y)
3864 N0
= DAG
.getNode(ISD::XOR
, dl
, OpVT
, N0
, N1
);
3866 case ISD::SETGT
: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
3867 case ISD::SETULT
: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
3868 Temp
= DAG
.getNOT(dl
, N0
, OpVT
);
3869 N0
= DAG
.getNode(ISD::AND
, dl
, OpVT
, N1
, Temp
);
3870 if (!DCI
.isCalledByLegalizer())
3871 DCI
.AddToWorklist(Temp
.getNode());
3873 case ISD::SETLT
: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
3874 case ISD::SETUGT
: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
3875 Temp
= DAG
.getNOT(dl
, N1
, OpVT
);
3876 N0
= DAG
.getNode(ISD::AND
, dl
, OpVT
, N0
, Temp
);
3877 if (!DCI
.isCalledByLegalizer())
3878 DCI
.AddToWorklist(Temp
.getNode());
3880 case ISD::SETULE
: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
3881 case ISD::SETGE
: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
3882 Temp
= DAG
.getNOT(dl
, N0
, OpVT
);
3883 N0
= DAG
.getNode(ISD::OR
, dl
, OpVT
, N1
, Temp
);
3884 if (!DCI
.isCalledByLegalizer())
3885 DCI
.AddToWorklist(Temp
.getNode());
3887 case ISD::SETUGE
: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
3888 case ISD::SETLE
: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
3889 Temp
= DAG
.getNOT(dl
, N1
, OpVT
);
3890 N0
= DAG
.getNode(ISD::OR
, dl
, OpVT
, N0
, Temp
);
3893 if (VT
.getScalarType() != MVT::i1
) {
3894 if (!DCI
.isCalledByLegalizer())
3895 DCI
.AddToWorklist(N0
.getNode());
3896 // FIXME: If running after legalize, we probably can't do this.
3897 ISD::NodeType ExtendCode
= getExtendForContent(getBooleanContents(OpVT
));
3898 N0
= DAG
.getNode(ExtendCode
, dl
, VT
, N0
);
3903 // Could not fold it.
3907 /// Returns true (and the GlobalValue and the offset) if the node is a
3908 /// GlobalAddress + offset.
3909 bool TargetLowering::isGAPlusOffset(SDNode
*WN
, const GlobalValue
*&GA
,
3910 int64_t &Offset
) const {
3912 SDNode
*N
= unwrapAddress(SDValue(WN
, 0)).getNode();
3914 if (auto *GASD
= dyn_cast
<GlobalAddressSDNode
>(N
)) {
3915 GA
= GASD
->getGlobal();
3916 Offset
+= GASD
->getOffset();
3920 if (N
->getOpcode() == ISD::ADD
) {
3921 SDValue N1
= N
->getOperand(0);
3922 SDValue N2
= N
->getOperand(1);
3923 if (isGAPlusOffset(N1
.getNode(), GA
, Offset
)) {
3924 if (auto *V
= dyn_cast
<ConstantSDNode
>(N2
)) {
3925 Offset
+= V
->getSExtValue();
3928 } else if (isGAPlusOffset(N2
.getNode(), GA
, Offset
)) {
3929 if (auto *V
= dyn_cast
<ConstantSDNode
>(N1
)) {
3930 Offset
+= V
->getSExtValue();
3939 SDValue
TargetLowering::PerformDAGCombine(SDNode
*N
,
3940 DAGCombinerInfo
&DCI
) const {
3941 // Default implementation: no optimization.
3945 //===----------------------------------------------------------------------===//
3946 // Inline Assembler Implementation Methods
3947 //===----------------------------------------------------------------------===//
3949 TargetLowering::ConstraintType
3950 TargetLowering::getConstraintType(StringRef Constraint
) const {
3951 unsigned S
= Constraint
.size();
3954 switch (Constraint
[0]) {
3957 return C_RegisterClass
;
3959 case 'o': // offsetable
3960 case 'V': // not offsetable
3962 case 'n': // Simple Integer
3963 case 'E': // Floating Point Constant
3964 case 'F': // Floating Point Constant
3966 case 'i': // Simple Integer or Relocatable Constant
3967 case 's': // Relocatable Constant
3968 case 'p': // Address.
3969 case 'X': // Allow ANY value.
3970 case 'I': // Target registers.
3984 if (S
> 1 && Constraint
[0] == '{' && Constraint
[S
- 1] == '}') {
3985 if (S
== 8 && Constraint
.substr(1, 6) == "memory") // "{memory}"
3992 /// Try to replace an X constraint, which matches anything, with another that
3993 /// has more specific requirements based on the type of the corresponding
3995 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT
) const {
3996 if (ConstraintVT
.isInteger())
3998 if (ConstraintVT
.isFloatingPoint())
3999 return "f"; // works for many targets
4003 SDValue
TargetLowering::LowerAsmOutputForConstraint(
4004 SDValue
&Chain
, SDValue
&Flag
, SDLoc DL
, const AsmOperandInfo
&OpInfo
,
4005 SelectionDAG
&DAG
) const {
4009 /// Lower the specified operand into the Ops vector.
4010 /// If it is invalid, don't add anything to Ops.
4011 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op
,
4012 std::string
&Constraint
,
4013 std::vector
<SDValue
> &Ops
,
4014 SelectionDAG
&DAG
) const {
4016 if (Constraint
.length() > 1) return;
4018 char ConstraintLetter
= Constraint
[0];
4019 switch (ConstraintLetter
) {
4021 case 'X': // Allows any operand; labels (basic block) use this.
4022 if (Op
.getOpcode() == ISD::BasicBlock
||
4023 Op
.getOpcode() == ISD::TargetBlockAddress
) {
4028 case 'i': // Simple Integer or Relocatable Constant
4029 case 'n': // Simple Integer
4030 case 's': { // Relocatable Constant
4032 GlobalAddressSDNode
*GA
;
4034 BlockAddressSDNode
*BA
;
4035 uint64_t Offset
= 0;
4037 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
4038 // etc., since getelementpointer is variadic. We can't use
4039 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
4040 // while in this case the GA may be furthest from the root node which is
4041 // likely an ISD::ADD.
4043 if ((GA
= dyn_cast
<GlobalAddressSDNode
>(Op
)) && ConstraintLetter
!= 'n') {
4044 Ops
.push_back(DAG
.getTargetGlobalAddress(GA
->getGlobal(), SDLoc(Op
),
4045 GA
->getValueType(0),
4046 Offset
+ GA
->getOffset()));
4048 } else if ((C
= dyn_cast
<ConstantSDNode
>(Op
)) &&
4049 ConstraintLetter
!= 's') {
4050 // gcc prints these as sign extended. Sign extend value to 64 bits
4051 // now; without this it would get ZExt'd later in
4052 // ScheduleDAGSDNodes::EmitNode, which is very generic.
4053 bool IsBool
= C
->getConstantIntValue()->getBitWidth() == 1;
4054 BooleanContent BCont
= getBooleanContents(MVT::i64
);
4055 ISD::NodeType ExtOpc
= IsBool
? getExtendForContent(BCont
)
4057 int64_t ExtVal
= ExtOpc
== ISD::ZERO_EXTEND
? C
->getZExtValue()
4058 : C
->getSExtValue();
4059 Ops
.push_back(DAG
.getTargetConstant(Offset
+ ExtVal
,
4060 SDLoc(C
), MVT::i64
));
4062 } else if ((BA
= dyn_cast
<BlockAddressSDNode
>(Op
)) &&
4063 ConstraintLetter
!= 'n') {
4064 Ops
.push_back(DAG
.getTargetBlockAddress(
4065 BA
->getBlockAddress(), BA
->getValueType(0),
4066 Offset
+ BA
->getOffset(), BA
->getTargetFlags()));
4069 const unsigned OpCode
= Op
.getOpcode();
4070 if (OpCode
== ISD::ADD
|| OpCode
== ISD::SUB
) {
4071 if ((C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(0))))
4072 Op
= Op
.getOperand(1);
4073 // Subtraction is not commutative.
4074 else if (OpCode
== ISD::ADD
&&
4075 (C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1))))
4076 Op
= Op
.getOperand(0);
4079 Offset
+= (OpCode
== ISD::ADD
? 1 : -1) * C
->getSExtValue();
4090 std::pair
<unsigned, const TargetRegisterClass
*>
4091 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo
*RI
,
4092 StringRef Constraint
,
4094 if (Constraint
.empty() || Constraint
[0] != '{')
4095 return std::make_pair(0u, static_cast<TargetRegisterClass
*>(nullptr));
4096 assert(*(Constraint
.end() - 1) == '}' && "Not a brace enclosed constraint?");
4098 // Remove the braces from around the name.
4099 StringRef
RegName(Constraint
.data() + 1, Constraint
.size() - 2);
4101 std::pair
<unsigned, const TargetRegisterClass
*> R
=
4102 std::make_pair(0u, static_cast<const TargetRegisterClass
*>(nullptr));
4104 // Figure out which register class contains this reg.
4105 for (const TargetRegisterClass
*RC
: RI
->regclasses()) {
4106 // If none of the value types for this register class are valid, we
4107 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4108 if (!isLegalRC(*RI
, *RC
))
4111 for (TargetRegisterClass::iterator I
= RC
->begin(), E
= RC
->end();
4113 if (RegName
.equals_lower(RI
->getRegAsmName(*I
))) {
4114 std::pair
<unsigned, const TargetRegisterClass
*> S
=
4115 std::make_pair(*I
, RC
);
4117 // If this register class has the requested value type, return it,
4118 // otherwise keep searching and return the first class found
4119 // if no other is found which explicitly has the requested type.
4120 if (RI
->isTypeLegalForClass(*RC
, VT
))
4131 //===----------------------------------------------------------------------===//
4132 // Constraint Selection.
4134 /// Return true of this is an input operand that is a matching constraint like
4136 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
4137 assert(!ConstraintCode
.empty() && "No known constraint!");
4138 return isdigit(static_cast<unsigned char>(ConstraintCode
[0]));
4141 /// If this is an input matching constraint, this method returns the output
4142 /// operand it matches.
4143 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
4144 assert(!ConstraintCode
.empty() && "No known constraint!");
4145 return atoi(ConstraintCode
.c_str());
4148 /// Split up the constraint string from the inline assembly value into the
4149 /// specific constraints and their prefixes, and also tie in the associated
4151 /// If this returns an empty vector, and if the constraint string itself
4152 /// isn't empty, there was an error parsing.
4153 TargetLowering::AsmOperandInfoVector
4154 TargetLowering::ParseConstraints(const DataLayout
&DL
,
4155 const TargetRegisterInfo
*TRI
,
4156 ImmutableCallSite CS
) const {
4157 /// Information about all of the constraints.
4158 AsmOperandInfoVector ConstraintOperands
;
4159 const InlineAsm
*IA
= cast
<InlineAsm
>(CS
.getCalledValue());
4160 unsigned maCount
= 0; // Largest number of multiple alternative constraints.
4162 // Do a prepass over the constraints, canonicalizing them, and building up the
4163 // ConstraintOperands list.
4164 unsigned ArgNo
= 0; // ArgNo - The argument of the CallInst.
4165 unsigned ResNo
= 0; // ResNo - The result number of the next output.
4167 for (InlineAsm::ConstraintInfo
&CI
: IA
->ParseConstraints()) {
4168 ConstraintOperands
.emplace_back(std::move(CI
));
4169 AsmOperandInfo
&OpInfo
= ConstraintOperands
.back();
4171 // Update multiple alternative constraint count.
4172 if (OpInfo
.multipleAlternatives
.size() > maCount
)
4173 maCount
= OpInfo
.multipleAlternatives
.size();
4175 OpInfo
.ConstraintVT
= MVT::Other
;
4177 // Compute the value type for each operand.
4178 switch (OpInfo
.Type
) {
4179 case InlineAsm::isOutput
:
4180 // Indirect outputs just consume an argument.
4181 if (OpInfo
.isIndirect
) {
4182 OpInfo
.CallOperandVal
= const_cast<Value
*>(CS
.getArgument(ArgNo
++));
4186 // The return value of the call is this value. As such, there is no
4187 // corresponding argument.
4188 assert(!CS
.getType()->isVoidTy() &&
4190 if (StructType
*STy
= dyn_cast
<StructType
>(CS
.getType())) {
4191 OpInfo
.ConstraintVT
=
4192 getSimpleValueType(DL
, STy
->getElementType(ResNo
));
4194 assert(ResNo
== 0 && "Asm only has one result!");
4195 OpInfo
.ConstraintVT
= getSimpleValueType(DL
, CS
.getType());
4199 case InlineAsm::isInput
:
4200 OpInfo
.CallOperandVal
= const_cast<Value
*>(CS
.getArgument(ArgNo
++));
4202 case InlineAsm::isClobber
:
4207 if (OpInfo
.CallOperandVal
) {
4208 llvm::Type
*OpTy
= OpInfo
.CallOperandVal
->getType();
4209 if (OpInfo
.isIndirect
) {
4210 llvm::PointerType
*PtrTy
= dyn_cast
<PointerType
>(OpTy
);
4212 report_fatal_error("Indirect operand for inline asm not a pointer!");
4213 OpTy
= PtrTy
->getElementType();
4216 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
4217 if (StructType
*STy
= dyn_cast
<StructType
>(OpTy
))
4218 if (STy
->getNumElements() == 1)
4219 OpTy
= STy
->getElementType(0);
4221 // If OpTy is not a single value, it may be a struct/union that we
4222 // can tile with integers.
4223 if (!OpTy
->isSingleValueType() && OpTy
->isSized()) {
4224 unsigned BitSize
= DL
.getTypeSizeInBits(OpTy
);
4233 OpInfo
.ConstraintVT
=
4234 MVT::getVT(IntegerType::get(OpTy
->getContext(), BitSize
), true);
4237 } else if (PointerType
*PT
= dyn_cast
<PointerType
>(OpTy
)) {
4238 unsigned PtrSize
= DL
.getPointerSizeInBits(PT
->getAddressSpace());
4239 OpInfo
.ConstraintVT
= MVT::getIntegerVT(PtrSize
);
4241 OpInfo
.ConstraintVT
= MVT::getVT(OpTy
, true);
4246 // If we have multiple alternative constraints, select the best alternative.
4247 if (!ConstraintOperands
.empty()) {
4249 unsigned bestMAIndex
= 0;
4250 int bestWeight
= -1;
4251 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
4254 // Compute the sums of the weights for each alternative, keeping track
4255 // of the best (highest weight) one so far.
4256 for (maIndex
= 0; maIndex
< maCount
; ++maIndex
) {
4258 for (unsigned cIndex
= 0, eIndex
= ConstraintOperands
.size();
4259 cIndex
!= eIndex
; ++cIndex
) {
4260 AsmOperandInfo
&OpInfo
= ConstraintOperands
[cIndex
];
4261 if (OpInfo
.Type
== InlineAsm::isClobber
)
4264 // If this is an output operand with a matching input operand,
4265 // look up the matching input. If their types mismatch, e.g. one
4266 // is an integer, the other is floating point, or their sizes are
4267 // different, flag it as an maCantMatch.
4268 if (OpInfo
.hasMatchingInput()) {
4269 AsmOperandInfo
&Input
= ConstraintOperands
[OpInfo
.MatchingInput
];
4270 if (OpInfo
.ConstraintVT
!= Input
.ConstraintVT
) {
4271 if ((OpInfo
.ConstraintVT
.isInteger() !=
4272 Input
.ConstraintVT
.isInteger()) ||
4273 (OpInfo
.ConstraintVT
.getSizeInBits() !=
4274 Input
.ConstraintVT
.getSizeInBits())) {
4275 weightSum
= -1; // Can't match.
4280 weight
= getMultipleConstraintMatchWeight(OpInfo
, maIndex
);
4285 weightSum
+= weight
;
4288 if (weightSum
> bestWeight
) {
4289 bestWeight
= weightSum
;
4290 bestMAIndex
= maIndex
;
4294 // Now select chosen alternative in each constraint.
4295 for (unsigned cIndex
= 0, eIndex
= ConstraintOperands
.size();
4296 cIndex
!= eIndex
; ++cIndex
) {
4297 AsmOperandInfo
&cInfo
= ConstraintOperands
[cIndex
];
4298 if (cInfo
.Type
== InlineAsm::isClobber
)
4300 cInfo
.selectAlternative(bestMAIndex
);
4305 // Check and hook up tied operands, choose constraint code to use.
4306 for (unsigned cIndex
= 0, eIndex
= ConstraintOperands
.size();
4307 cIndex
!= eIndex
; ++cIndex
) {
4308 AsmOperandInfo
&OpInfo
= ConstraintOperands
[cIndex
];
4310 // If this is an output operand with a matching input operand, look up the
4311 // matching input. If their types mismatch, e.g. one is an integer, the
4312 // other is floating point, or their sizes are different, flag it as an
4314 if (OpInfo
.hasMatchingInput()) {
4315 AsmOperandInfo
&Input
= ConstraintOperands
[OpInfo
.MatchingInput
];
4317 if (OpInfo
.ConstraintVT
!= Input
.ConstraintVT
) {
4318 std::pair
<unsigned, const TargetRegisterClass
*> MatchRC
=
4319 getRegForInlineAsmConstraint(TRI
, OpInfo
.ConstraintCode
,
4320 OpInfo
.ConstraintVT
);
4321 std::pair
<unsigned, const TargetRegisterClass
*> InputRC
=
4322 getRegForInlineAsmConstraint(TRI
, Input
.ConstraintCode
,
4323 Input
.ConstraintVT
);
4324 if ((OpInfo
.ConstraintVT
.isInteger() !=
4325 Input
.ConstraintVT
.isInteger()) ||
4326 (MatchRC
.second
!= InputRC
.second
)) {
4327 report_fatal_error("Unsupported asm: input constraint"
4328 " with a matching output constraint of"
4329 " incompatible type!");
4335 return ConstraintOperands
;
4338 /// Return an integer indicating how general CT is.
4339 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT
) {
4341 case TargetLowering::C_Immediate
:
4342 case TargetLowering::C_Other
:
4343 case TargetLowering::C_Unknown
:
4345 case TargetLowering::C_Register
:
4347 case TargetLowering::C_RegisterClass
:
4349 case TargetLowering::C_Memory
:
4352 llvm_unreachable("Invalid constraint type");
4355 /// Examine constraint type and operand type and determine a weight value.
4356 /// This object must already have been set up with the operand type
4357 /// and the current alternative constraint selected.
4358 TargetLowering::ConstraintWeight
4359 TargetLowering::getMultipleConstraintMatchWeight(
4360 AsmOperandInfo
&info
, int maIndex
) const {
4361 InlineAsm::ConstraintCodeVector
*rCodes
;
4362 if (maIndex
>= (int)info
.multipleAlternatives
.size())
4363 rCodes
= &info
.Codes
;
4365 rCodes
= &info
.multipleAlternatives
[maIndex
].Codes
;
4366 ConstraintWeight BestWeight
= CW_Invalid
;
4368 // Loop over the options, keeping track of the most general one.
4369 for (unsigned i
= 0, e
= rCodes
->size(); i
!= e
; ++i
) {
4370 ConstraintWeight weight
=
4371 getSingleConstraintMatchWeight(info
, (*rCodes
)[i
].c_str());
4372 if (weight
> BestWeight
)
4373 BestWeight
= weight
;
4379 /// Examine constraint type and operand type and determine a weight value.
4380 /// This object must already have been set up with the operand type
4381 /// and the current alternative constraint selected.
4382 TargetLowering::ConstraintWeight
4383 TargetLowering::getSingleConstraintMatchWeight(
4384 AsmOperandInfo
&info
, const char *constraint
) const {
4385 ConstraintWeight weight
= CW_Invalid
;
4386 Value
*CallOperandVal
= info
.CallOperandVal
;
4387 // If we don't have a value, we can't do a match,
4388 // but allow it at the lowest weight.
4389 if (!CallOperandVal
)
4391 // Look at the constraint type.
4392 switch (*constraint
) {
4393 case 'i': // immediate integer.
4394 case 'n': // immediate integer with a known value.
4395 if (isa
<ConstantInt
>(CallOperandVal
))
4396 weight
= CW_Constant
;
4398 case 's': // non-explicit intregal immediate.
4399 if (isa
<GlobalValue
>(CallOperandVal
))
4400 weight
= CW_Constant
;
4402 case 'E': // immediate float if host format.
4403 case 'F': // immediate float.
4404 if (isa
<ConstantFP
>(CallOperandVal
))
4405 weight
= CW_Constant
;
4407 case '<': // memory operand with autodecrement.
4408 case '>': // memory operand with autoincrement.
4409 case 'm': // memory operand.
4410 case 'o': // offsettable memory operand
4411 case 'V': // non-offsettable memory operand
4414 case 'r': // general register.
4415 case 'g': // general register, memory operand or immediate integer.
4416 // note: Clang converts "g" to "imr".
4417 if (CallOperandVal
->getType()->isIntegerTy())
4418 weight
= CW_Register
;
4420 case 'X': // any operand.
4422 weight
= CW_Default
;
4428 /// If there are multiple different constraints that we could pick for this
4429 /// operand (e.g. "imr") try to pick the 'best' one.
4430 /// This is somewhat tricky: constraints fall into four classes:
4431 /// Other -> immediates and magic values
4432 /// Register -> one specific register
4433 /// RegisterClass -> a group of regs
4434 /// Memory -> memory
4435 /// Ideally, we would pick the most specific constraint possible: if we have
4436 /// something that fits into a register, we would pick it. The problem here
4437 /// is that if we have something that could either be in a register or in
4438 /// memory that use of the register could cause selection of *other*
4439 /// operands to fail: they might only succeed if we pick memory. Because of
4440 /// this the heuristic we use is:
4442 /// 1) If there is an 'other' constraint, and if the operand is valid for
4443 /// that constraint, use it. This makes us take advantage of 'i'
4444 /// constraints when available.
4445 /// 2) Otherwise, pick the most general constraint present. This prefers
4446 /// 'm' over 'r', for example.
4448 static void ChooseConstraint(TargetLowering::AsmOperandInfo
&OpInfo
,
4449 const TargetLowering
&TLI
,
4450 SDValue Op
, SelectionDAG
*DAG
) {
4451 assert(OpInfo
.Codes
.size() > 1 && "Doesn't have multiple constraint options");
4452 unsigned BestIdx
= 0;
4453 TargetLowering::ConstraintType BestType
= TargetLowering::C_Unknown
;
4454 int BestGenerality
= -1;
4456 // Loop over the options, keeping track of the most general one.
4457 for (unsigned i
= 0, e
= OpInfo
.Codes
.size(); i
!= e
; ++i
) {
4458 TargetLowering::ConstraintType CType
=
4459 TLI
.getConstraintType(OpInfo
.Codes
[i
]);
4461 // If this is an 'other' or 'immediate' constraint, see if the operand is
4462 // valid for it. For example, on X86 we might have an 'rI' constraint. If
4463 // the operand is an integer in the range [0..31] we want to use I (saving a
4464 // load of a register), otherwise we must use 'r'.
4465 if ((CType
== TargetLowering::C_Other
||
4466 CType
== TargetLowering::C_Immediate
) && Op
.getNode()) {
4467 assert(OpInfo
.Codes
[i
].size() == 1 &&
4468 "Unhandled multi-letter 'other' constraint");
4469 std::vector
<SDValue
> ResultOps
;
4470 TLI
.LowerAsmOperandForConstraint(Op
, OpInfo
.Codes
[i
],
4472 if (!ResultOps
.empty()) {
4479 // Things with matching constraints can only be registers, per gcc
4480 // documentation. This mainly affects "g" constraints.
4481 if (CType
== TargetLowering::C_Memory
&& OpInfo
.hasMatchingInput())
4484 // This constraint letter is more general than the previous one, use it.
4485 int Generality
= getConstraintGenerality(CType
);
4486 if (Generality
> BestGenerality
) {
4489 BestGenerality
= Generality
;
4493 OpInfo
.ConstraintCode
= OpInfo
.Codes
[BestIdx
];
4494 OpInfo
.ConstraintType
= BestType
;
4497 /// Determines the constraint code and constraint type to use for the specific
4498 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
4499 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo
&OpInfo
,
4501 SelectionDAG
*DAG
) const {
4502 assert(!OpInfo
.Codes
.empty() && "Must have at least one constraint");
4504 // Single-letter constraints ('r') are very common.
4505 if (OpInfo
.Codes
.size() == 1) {
4506 OpInfo
.ConstraintCode
= OpInfo
.Codes
[0];
4507 OpInfo
.ConstraintType
= getConstraintType(OpInfo
.ConstraintCode
);
4509 ChooseConstraint(OpInfo
, *this, Op
, DAG
);
4512 // 'X' matches anything.
4513 if (OpInfo
.ConstraintCode
== "X" && OpInfo
.CallOperandVal
) {
4514 // Labels and constants are handled elsewhere ('X' is the only thing
4515 // that matches labels). For Functions, the type here is the type of
4516 // the result, which is not what we want to look at; leave them alone.
4517 Value
*v
= OpInfo
.CallOperandVal
;
4518 if (isa
<BasicBlock
>(v
) || isa
<ConstantInt
>(v
) || isa
<Function
>(v
)) {
4519 OpInfo
.CallOperandVal
= v
;
4523 if (Op
.getNode() && Op
.getOpcode() == ISD::TargetBlockAddress
)
4526 // Otherwise, try to resolve it to something we know about by looking at
4527 // the actual operand type.
4528 if (const char *Repl
= LowerXConstraint(OpInfo
.ConstraintVT
)) {
4529 OpInfo
.ConstraintCode
= Repl
;
4530 OpInfo
.ConstraintType
= getConstraintType(OpInfo
.ConstraintCode
);
4535 /// Given an exact SDIV by a constant, create a multiplication
4536 /// with the multiplicative inverse of the constant.
4537 static SDValue
BuildExactSDIV(const TargetLowering
&TLI
, SDNode
*N
,
4538 const SDLoc
&dl
, SelectionDAG
&DAG
,
4539 SmallVectorImpl
<SDNode
*> &Created
) {
4540 SDValue Op0
= N
->getOperand(0);
4541 SDValue Op1
= N
->getOperand(1);
4542 EVT VT
= N
->getValueType(0);
4543 EVT SVT
= VT
.getScalarType();
4544 EVT ShVT
= TLI
.getShiftAmountTy(VT
, DAG
.getDataLayout());
4545 EVT ShSVT
= ShVT
.getScalarType();
4547 bool UseSRA
= false;
4548 SmallVector
<SDValue
, 16> Shifts
, Factors
;
4550 auto BuildSDIVPattern
= [&](ConstantSDNode
*C
) {
4551 if (C
->isNullValue())
4553 APInt Divisor
= C
->getAPIntValue();
4554 unsigned Shift
= Divisor
.countTrailingZeros();
4556 Divisor
.ashrInPlace(Shift
);
4559 // Calculate the multiplicative inverse, using Newton's method.
4561 APInt Factor
= Divisor
;
4562 while ((t
= Divisor
* Factor
) != 1)
4563 Factor
*= APInt(Divisor
.getBitWidth(), 2) - t
;
4564 Shifts
.push_back(DAG
.getConstant(Shift
, dl
, ShSVT
));
4565 Factors
.push_back(DAG
.getConstant(Factor
, dl
, SVT
));
4569 // Collect all magic values from the build vector.
4570 if (!ISD::matchUnaryPredicate(Op1
, BuildSDIVPattern
))
4573 SDValue Shift
, Factor
;
4574 if (VT
.isVector()) {
4575 Shift
= DAG
.getBuildVector(ShVT
, dl
, Shifts
);
4576 Factor
= DAG
.getBuildVector(VT
, dl
, Factors
);
4579 Factor
= Factors
[0];
4584 // Shift the value upfront if it is even, so the LSB is one.
4586 // TODO: For UDIV use SRL instead of SRA.
4588 Flags
.setExact(true);
4589 Res
= DAG
.getNode(ISD::SRA
, dl
, VT
, Res
, Shift
, Flags
);
4590 Created
.push_back(Res
.getNode());
4593 return DAG
.getNode(ISD::MUL
, dl
, VT
, Res
, Factor
);
4596 SDValue
TargetLowering::BuildSDIVPow2(SDNode
*N
, const APInt
&Divisor
,
4598 SmallVectorImpl
<SDNode
*> &Created
) const {
4599 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
4600 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
4601 if (TLI
.isIntDivCheap(N
->getValueType(0), Attr
))
4602 return SDValue(N
, 0); // Lower SDIV as SDIV
4606 /// Given an ISD::SDIV node expressing a divide by constant,
4607 /// return a DAG expression to select that will generate the same value by
4608 /// multiplying by a magic number.
4609 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
4610 SDValue
TargetLowering::BuildSDIV(SDNode
*N
, SelectionDAG
&DAG
,
4611 bool IsAfterLegalization
,
4612 SmallVectorImpl
<SDNode
*> &Created
) const {
4614 EVT VT
= N
->getValueType(0);
4615 EVT SVT
= VT
.getScalarType();
4616 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
4617 EVT ShSVT
= ShVT
.getScalarType();
4618 unsigned EltBits
= VT
.getScalarSizeInBits();
4620 // Check to see if we can do this.
4621 // FIXME: We should be more aggressive here.
4622 if (!isTypeLegal(VT
))
4625 // If the sdiv has an 'exact' bit we can use a simpler lowering.
4626 if (N
->getFlags().hasExact())
4627 return BuildExactSDIV(*this, N
, dl
, DAG
, Created
);
4629 SmallVector
<SDValue
, 16> MagicFactors
, Factors
, Shifts
, ShiftMasks
;
4631 auto BuildSDIVPattern
= [&](ConstantSDNode
*C
) {
4632 if (C
->isNullValue())
4635 const APInt
&Divisor
= C
->getAPIntValue();
4636 APInt::ms magics
= Divisor
.magic();
4637 int NumeratorFactor
= 0;
4640 if (Divisor
.isOneValue() || Divisor
.isAllOnesValue()) {
4641 // If d is +1/-1, we just multiply the numerator by +1/-1.
4642 NumeratorFactor
= Divisor
.getSExtValue();
4646 } else if (Divisor
.isStrictlyPositive() && magics
.m
.isNegative()) {
4647 // If d > 0 and m < 0, add the numerator.
4648 NumeratorFactor
= 1;
4649 } else if (Divisor
.isNegative() && magics
.m
.isStrictlyPositive()) {
4650 // If d < 0 and m > 0, subtract the numerator.
4651 NumeratorFactor
= -1;
4654 MagicFactors
.push_back(DAG
.getConstant(magics
.m
, dl
, SVT
));
4655 Factors
.push_back(DAG
.getConstant(NumeratorFactor
, dl
, SVT
));
4656 Shifts
.push_back(DAG
.getConstant(magics
.s
, dl
, ShSVT
));
4657 ShiftMasks
.push_back(DAG
.getConstant(ShiftMask
, dl
, SVT
));
4661 SDValue N0
= N
->getOperand(0);
4662 SDValue N1
= N
->getOperand(1);
4664 // Collect the shifts / magic values from each element.
4665 if (!ISD::matchUnaryPredicate(N1
, BuildSDIVPattern
))
4668 SDValue MagicFactor
, Factor
, Shift
, ShiftMask
;
4669 if (VT
.isVector()) {
4670 MagicFactor
= DAG
.getBuildVector(VT
, dl
, MagicFactors
);
4671 Factor
= DAG
.getBuildVector(VT
, dl
, Factors
);
4672 Shift
= DAG
.getBuildVector(ShVT
, dl
, Shifts
);
4673 ShiftMask
= DAG
.getBuildVector(VT
, dl
, ShiftMasks
);
4675 MagicFactor
= MagicFactors
[0];
4676 Factor
= Factors
[0];
4678 ShiftMask
= ShiftMasks
[0];
4681 // Multiply the numerator (operand 0) by the magic value.
4682 // FIXME: We should support doing a MUL in a wider type.
4684 if (IsAfterLegalization
? isOperationLegal(ISD::MULHS
, VT
)
4685 : isOperationLegalOrCustom(ISD::MULHS
, VT
))
4686 Q
= DAG
.getNode(ISD::MULHS
, dl
, VT
, N0
, MagicFactor
);
4687 else if (IsAfterLegalization
? isOperationLegal(ISD::SMUL_LOHI
, VT
)
4688 : isOperationLegalOrCustom(ISD::SMUL_LOHI
, VT
)) {
4690 DAG
.getNode(ISD::SMUL_LOHI
, dl
, DAG
.getVTList(VT
, VT
), N0
, MagicFactor
);
4691 Q
= SDValue(LoHi
.getNode(), 1);
4693 return SDValue(); // No mulhs or equivalent.
4694 Created
.push_back(Q
.getNode());
4696 // (Optionally) Add/subtract the numerator using Factor.
4697 Factor
= DAG
.getNode(ISD::MUL
, dl
, VT
, N0
, Factor
);
4698 Created
.push_back(Factor
.getNode());
4699 Q
= DAG
.getNode(ISD::ADD
, dl
, VT
, Q
, Factor
);
4700 Created
.push_back(Q
.getNode());
4702 // Shift right algebraic by shift value.
4703 Q
= DAG
.getNode(ISD::SRA
, dl
, VT
, Q
, Shift
);
4704 Created
.push_back(Q
.getNode());
4706 // Extract the sign bit, mask it and add it to the quotient.
4707 SDValue SignShift
= DAG
.getConstant(EltBits
- 1, dl
, ShVT
);
4708 SDValue T
= DAG
.getNode(ISD::SRL
, dl
, VT
, Q
, SignShift
);
4709 Created
.push_back(T
.getNode());
4710 T
= DAG
.getNode(ISD::AND
, dl
, VT
, T
, ShiftMask
);
4711 Created
.push_back(T
.getNode());
4712 return DAG
.getNode(ISD::ADD
, dl
, VT
, Q
, T
);
4715 /// Given an ISD::UDIV node expressing a divide by constant,
4716 /// return a DAG expression to select that will generate the same value by
4717 /// multiplying by a magic number.
4718 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
4719 SDValue
TargetLowering::BuildUDIV(SDNode
*N
, SelectionDAG
&DAG
,
4720 bool IsAfterLegalization
,
4721 SmallVectorImpl
<SDNode
*> &Created
) const {
4723 EVT VT
= N
->getValueType(0);
4724 EVT SVT
= VT
.getScalarType();
4725 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
4726 EVT ShSVT
= ShVT
.getScalarType();
4727 unsigned EltBits
= VT
.getScalarSizeInBits();
4729 // Check to see if we can do this.
4730 // FIXME: We should be more aggressive here.
4731 if (!isTypeLegal(VT
))
4734 bool UseNPQ
= false;
4735 SmallVector
<SDValue
, 16> PreShifts
, PostShifts
, MagicFactors
, NPQFactors
;
4737 auto BuildUDIVPattern
= [&](ConstantSDNode
*C
) {
4738 if (C
->isNullValue())
4740 // FIXME: We should use a narrower constant when the upper
4741 // bits are known to be zero.
4742 APInt Divisor
= C
->getAPIntValue();
4743 APInt::mu magics
= Divisor
.magicu();
4744 unsigned PreShift
= 0, PostShift
= 0;
4746 // If the divisor is even, we can avoid using the expensive fixup by
4747 // shifting the divided value upfront.
4748 if (magics
.a
!= 0 && !Divisor
[0]) {
4749 PreShift
= Divisor
.countTrailingZeros();
4750 // Get magic number for the shifted divisor.
4751 magics
= Divisor
.lshr(PreShift
).magicu(PreShift
);
4752 assert(magics
.a
== 0 && "Should use cheap fixup now");
4755 APInt Magic
= magics
.m
;
4758 if (magics
.a
== 0 || Divisor
.isOneValue()) {
4759 assert(magics
.s
< Divisor
.getBitWidth() &&
4760 "We shouldn't generate an undefined shift!");
4761 PostShift
= magics
.s
;
4764 PostShift
= magics
.s
- 1;
4768 PreShifts
.push_back(DAG
.getConstant(PreShift
, dl
, ShSVT
));
4769 MagicFactors
.push_back(DAG
.getConstant(Magic
, dl
, SVT
));
4770 NPQFactors
.push_back(
4771 DAG
.getConstant(SelNPQ
? APInt::getOneBitSet(EltBits
, EltBits
- 1)
4772 : APInt::getNullValue(EltBits
),
4774 PostShifts
.push_back(DAG
.getConstant(PostShift
, dl
, ShSVT
));
4779 SDValue N0
= N
->getOperand(0);
4780 SDValue N1
= N
->getOperand(1);
4782 // Collect the shifts/magic values from each element.
4783 if (!ISD::matchUnaryPredicate(N1
, BuildUDIVPattern
))
4786 SDValue PreShift
, PostShift
, MagicFactor
, NPQFactor
;
4787 if (VT
.isVector()) {
4788 PreShift
= DAG
.getBuildVector(ShVT
, dl
, PreShifts
);
4789 MagicFactor
= DAG
.getBuildVector(VT
, dl
, MagicFactors
);
4790 NPQFactor
= DAG
.getBuildVector(VT
, dl
, NPQFactors
);
4791 PostShift
= DAG
.getBuildVector(ShVT
, dl
, PostShifts
);
4793 PreShift
= PreShifts
[0];
4794 MagicFactor
= MagicFactors
[0];
4795 PostShift
= PostShifts
[0];
4799 Q
= DAG
.getNode(ISD::SRL
, dl
, VT
, Q
, PreShift
);
4800 Created
.push_back(Q
.getNode());
4802 // FIXME: We should support doing a MUL in a wider type.
4803 auto GetMULHU
= [&](SDValue X
, SDValue Y
) {
4804 if (IsAfterLegalization
? isOperationLegal(ISD::MULHU
, VT
)
4805 : isOperationLegalOrCustom(ISD::MULHU
, VT
))
4806 return DAG
.getNode(ISD::MULHU
, dl
, VT
, X
, Y
);
4807 if (IsAfterLegalization
? isOperationLegal(ISD::UMUL_LOHI
, VT
)
4808 : isOperationLegalOrCustom(ISD::UMUL_LOHI
, VT
)) {
4810 DAG
.getNode(ISD::UMUL_LOHI
, dl
, DAG
.getVTList(VT
, VT
), X
, Y
);
4811 return SDValue(LoHi
.getNode(), 1);
4813 return SDValue(); // No mulhu or equivalent
4816 // Multiply the numerator (operand 0) by the magic value.
4817 Q
= GetMULHU(Q
, MagicFactor
);
4821 Created
.push_back(Q
.getNode());
4824 SDValue NPQ
= DAG
.getNode(ISD::SUB
, dl
, VT
, N0
, Q
);
4825 Created
.push_back(NPQ
.getNode());
4827 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
4828 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
4830 NPQ
= GetMULHU(NPQ
, NPQFactor
);
4832 NPQ
= DAG
.getNode(ISD::SRL
, dl
, VT
, NPQ
, DAG
.getConstant(1, dl
, ShVT
));
4834 Created
.push_back(NPQ
.getNode());
4836 Q
= DAG
.getNode(ISD::ADD
, dl
, VT
, NPQ
, Q
);
4837 Created
.push_back(Q
.getNode());
4840 Q
= DAG
.getNode(ISD::SRL
, dl
, VT
, Q
, PostShift
);
4841 Created
.push_back(Q
.getNode());
4843 SDValue One
= DAG
.getConstant(1, dl
, VT
);
4844 SDValue IsOne
= DAG
.getSetCC(dl
, VT
, N1
, One
, ISD::SETEQ
);
4845 return DAG
.getSelect(dl
, VT
, IsOne
, N0
, Q
);
4848 /// If all values in Values that *don't* match the predicate are same 'splat'
4849 /// value, then replace all values with that splat value.
4850 /// Else, if AlternativeReplacement was provided, then replace all values that
4851 /// do match predicate with AlternativeReplacement value.
4853 turnVectorIntoSplatVector(MutableArrayRef
<SDValue
> Values
,
4854 std::function
<bool(SDValue
)> Predicate
,
4855 SDValue AlternativeReplacement
= SDValue()) {
4856 SDValue Replacement
;
4857 // Is there a value for which the Predicate does *NOT* match? What is it?
4858 auto SplatValue
= llvm::find_if_not(Values
, Predicate
);
4859 if (SplatValue
!= Values
.end()) {
4860 // Does Values consist only of SplatValue's and values matching Predicate?
4861 if (llvm::all_of(Values
, [Predicate
, SplatValue
](SDValue Value
) {
4862 return Value
== *SplatValue
|| Predicate(Value
);
4863 })) // Then we shall replace values matching predicate with SplatValue.
4864 Replacement
= *SplatValue
;
4867 // Oops, we did not find the "baseline" splat value.
4868 if (!AlternativeReplacement
)
4869 return; // Nothing to do.
4870 // Let's replace with provided value then.
4871 Replacement
= AlternativeReplacement
;
4873 std::replace_if(Values
.begin(), Values
.end(), Predicate
, Replacement
);
4876 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
4877 /// where the divisor is constant and the comparison target is zero,
4878 /// return a DAG expression that will generate the same comparison result
4879 /// using only multiplications, additions and shifts/rotations.
4880 /// Ref: "Hacker's Delight" 10-17.
4881 SDValue
TargetLowering::buildUREMEqFold(EVT SETCCVT
, SDValue REMNode
,
4882 SDValue CompTargetNode
,
4884 DAGCombinerInfo
&DCI
,
4885 const SDLoc
&DL
) const {
4886 SmallVector
<SDNode
*, 2> Built
;
4887 if (SDValue Folded
= prepareUREMEqFold(SETCCVT
, REMNode
, CompTargetNode
, Cond
,
4889 for (SDNode
*N
: Built
)
4890 DCI
.AddToWorklist(N
);
4898 TargetLowering::prepareUREMEqFold(EVT SETCCVT
, SDValue REMNode
,
4899 SDValue CompTargetNode
, ISD::CondCode Cond
,
4900 DAGCombinerInfo
&DCI
, const SDLoc
&DL
,
4901 SmallVectorImpl
<SDNode
*> &Created
) const {
4902 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
4903 // - D must be constant, with D = D0 * 2^K where D0 is odd
4904 // - P is the multiplicative inverse of D0 modulo 2^W
4905 // - Q = floor(((2^W) - 1) / D)
4906 // where W is the width of the common type of N and D.
4907 assert((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
4908 "Only applicable for (in)equality comparisons.");
4910 SelectionDAG
&DAG
= DCI
.DAG
;
4912 EVT VT
= REMNode
.getValueType();
4913 EVT SVT
= VT
.getScalarType();
4914 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
4915 EVT ShSVT
= ShVT
.getScalarType();
4917 // If MUL is unavailable, we cannot proceed in any case.
4918 if (!isOperationLegalOrCustom(ISD::MUL
, VT
))
4921 // TODO: Could support comparing with non-zero too.
4922 ConstantSDNode
*CompTarget
= isConstOrConstSplat(CompTargetNode
);
4923 if (!CompTarget
|| !CompTarget
->isNullValue())
4926 bool HadOneDivisor
= false;
4927 bool AllDivisorsAreOnes
= true;
4928 bool HadEvenDivisor
= false;
4929 bool AllDivisorsArePowerOfTwo
= true;
4930 SmallVector
<SDValue
, 16> PAmts
, KAmts
, QAmts
;
4932 auto BuildUREMPattern
= [&](ConstantSDNode
*C
) {
4933 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
4934 if (C
->isNullValue())
4937 const APInt
&D
= C
->getAPIntValue();
4938 // If all divisors are ones, we will prefer to avoid the fold.
4939 HadOneDivisor
|= D
.isOneValue();
4940 AllDivisorsAreOnes
&= D
.isOneValue();
4942 // Decompose D into D0 * 2^K
4943 unsigned K
= D
.countTrailingZeros();
4944 assert((!D
.isOneValue() || (K
== 0)) && "For divisor '1' we won't rotate.");
4945 APInt D0
= D
.lshr(K
);
4947 // D is even if it has trailing zeros.
4948 HadEvenDivisor
|= (K
!= 0);
4949 // D is a power-of-two if D0 is one.
4950 // If all divisors are power-of-two, we will prefer to avoid the fold.
4951 AllDivisorsArePowerOfTwo
&= D0
.isOneValue();
4954 // 2^W requires W + 1 bits, so we have to extend and then truncate.
4955 unsigned W
= D
.getBitWidth();
4956 APInt P
= D0
.zext(W
+ 1)
4957 .multiplicativeInverse(APInt::getSignedMinValue(W
+ 1))
4959 assert(!P
.isNullValue() && "No multiplicative inverse!"); // unreachable
4960 assert((D0
* P
).isOneValue() && "Multiplicative inverse sanity check.");
4962 // Q = floor((2^W - 1) / D)
4963 APInt Q
= APInt::getAllOnesValue(W
).udiv(D
);
4965 assert(APInt::getAllOnesValue(ShSVT
.getSizeInBits()).ugt(K
) &&
4966 "We are expecting that K is always less than all-ones for ShSVT");
4968 // If the divisor is 1 the result can be constant-folded.
4969 if (D
.isOneValue()) {
4970 // Set P and K amount to a bogus values so we can try to splat them.
4973 assert(Q
.isAllOnesValue() &&
4974 "Expecting all-ones comparison for one divisor");
4977 PAmts
.push_back(DAG
.getConstant(P
, DL
, SVT
));
4979 DAG
.getConstant(APInt(ShSVT
.getSizeInBits(), K
), DL
, ShSVT
));
4980 QAmts
.push_back(DAG
.getConstant(Q
, DL
, SVT
));
4984 SDValue N
= REMNode
.getOperand(0);
4985 SDValue D
= REMNode
.getOperand(1);
4987 // Collect the values from each element.
4988 if (!ISD::matchUnaryPredicate(D
, BuildUREMPattern
))
4991 // If this is a urem by a one, avoid the fold since it can be constant-folded.
4992 if (AllDivisorsAreOnes
)
4995 // If this is a urem by a powers-of-two, avoid the fold since it can be
4996 // best implemented as a bit test.
4997 if (AllDivisorsArePowerOfTwo
)
5000 SDValue PVal
, KVal
, QVal
;
5001 if (VT
.isVector()) {
5002 if (HadOneDivisor
) {
5003 // Try to turn PAmts into a splat, since we don't care about the values
5004 // that are currently '0'. If we can't, just keep '0'`s.
5005 turnVectorIntoSplatVector(PAmts
, isNullConstant
);
5006 // Try to turn KAmts into a splat, since we don't care about the values
5007 // that are currently '-1'. If we can't, change them to '0'`s.
5008 turnVectorIntoSplatVector(KAmts
, isAllOnesConstant
,
5009 DAG
.getConstant(0, DL
, ShSVT
));
5012 PVal
= DAG
.getBuildVector(VT
, DL
, PAmts
);
5013 KVal
= DAG
.getBuildVector(ShVT
, DL
, KAmts
);
5014 QVal
= DAG
.getBuildVector(VT
, DL
, QAmts
);
5022 SDValue Op0
= DAG
.getNode(ISD::MUL
, DL
, VT
, N
, PVal
);
5023 Created
.push_back(Op0
.getNode());
5025 // Rotate right only if any divisor was even. We avoid rotates for all-odd
5026 // divisors as a performance improvement, since rotating by 0 is a no-op.
5027 if (HadEvenDivisor
) {
5028 // We need ROTR to do this.
5029 if (!isOperationLegalOrCustom(ISD::ROTR
, VT
))
5032 Flags
.setExact(true);
5033 // UREM: (rotr (mul N, P), K)
5034 Op0
= DAG
.getNode(ISD::ROTR
, DL
, VT
, Op0
, KVal
, Flags
);
5035 Created
.push_back(Op0
.getNode());
5038 // UREM: (setule/setugt (rotr (mul N, P), K), Q)
5039 return DAG
.getSetCC(DL
, SETCCVT
, Op0
, QVal
,
5040 ((Cond
== ISD::SETEQ
) ? ISD::SETULE
: ISD::SETUGT
));
5043 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
5044 /// where the divisor is constant and the comparison target is zero,
5045 /// return a DAG expression that will generate the same comparison result
5046 /// using only multiplications, additions and shifts/rotations.
5047 /// Ref: "Hacker's Delight" 10-17.
5048 SDValue
TargetLowering::buildSREMEqFold(EVT SETCCVT
, SDValue REMNode
,
5049 SDValue CompTargetNode
,
5051 DAGCombinerInfo
&DCI
,
5052 const SDLoc
&DL
) const {
5053 SmallVector
<SDNode
*, 7> Built
;
5054 if (SDValue Folded
= prepareSREMEqFold(SETCCVT
, REMNode
, CompTargetNode
, Cond
,
5056 assert(Built
.size() <= 7 && "Max size prediction failed.");
5057 for (SDNode
*N
: Built
)
5058 DCI
.AddToWorklist(N
);
5066 TargetLowering::prepareSREMEqFold(EVT SETCCVT
, SDValue REMNode
,
5067 SDValue CompTargetNode
, ISD::CondCode Cond
,
5068 DAGCombinerInfo
&DCI
, const SDLoc
&DL
,
5069 SmallVectorImpl
<SDNode
*> &Created
) const {
5071 // (seteq/ne (srem N, D), 0)
5073 // (setule/ugt (rotr (add (mul N, P), A), K), Q)
5075 // - D must be constant, with D = D0 * 2^K where D0 is odd
5076 // - P is the multiplicative inverse of D0 modulo 2^W
5077 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
5078 // - Q = floor((2 * A) / (2^K))
5079 // where W is the width of the common type of N and D.
5080 assert((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
5081 "Only applicable for (in)equality comparisons.");
5083 SelectionDAG
&DAG
= DCI
.DAG
;
5085 EVT VT
= REMNode
.getValueType();
5086 EVT SVT
= VT
.getScalarType();
5087 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
5088 EVT ShSVT
= ShVT
.getScalarType();
5090 // If MUL is unavailable, we cannot proceed in any case.
5091 if (!isOperationLegalOrCustom(ISD::MUL
, VT
))
5094 // TODO: Could support comparing with non-zero too.
5095 ConstantSDNode
*CompTarget
= isConstOrConstSplat(CompTargetNode
);
5096 if (!CompTarget
|| !CompTarget
->isNullValue())
5099 bool HadIntMinDivisor
= false;
5100 bool HadOneDivisor
= false;
5101 bool AllDivisorsAreOnes
= true;
5102 bool HadEvenDivisor
= false;
5103 bool NeedToApplyOffset
= false;
5104 bool AllDivisorsArePowerOfTwo
= true;
5105 SmallVector
<SDValue
, 16> PAmts
, AAmts
, KAmts
, QAmts
;
5107 auto BuildSREMPattern
= [&](ConstantSDNode
*C
) {
5108 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
5109 if (C
->isNullValue())
5112 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
5114 // WARNING: this fold is only valid for positive divisors!
5115 APInt D
= C
->getAPIntValue();
5117 D
.negate(); // `rem %X, -C` is equivalent to `rem %X, C`
5119 HadIntMinDivisor
|= D
.isMinSignedValue();
5121 // If all divisors are ones, we will prefer to avoid the fold.
5122 HadOneDivisor
|= D
.isOneValue();
5123 AllDivisorsAreOnes
&= D
.isOneValue();
5125 // Decompose D into D0 * 2^K
5126 unsigned K
= D
.countTrailingZeros();
5127 assert((!D
.isOneValue() || (K
== 0)) && "For divisor '1' we won't rotate.");
5128 APInt D0
= D
.lshr(K
);
5130 if (!D
.isMinSignedValue()) {
5131 // D is even if it has trailing zeros; unless it's INT_MIN, in which case
5132 // we don't care about this lane in this fold, we'll special-handle it.
5133 HadEvenDivisor
|= (K
!= 0);
5136 // D is a power-of-two if D0 is one. This includes INT_MIN.
5137 // If all divisors are power-of-two, we will prefer to avoid the fold.
5138 AllDivisorsArePowerOfTwo
&= D0
.isOneValue();
5141 // 2^W requires W + 1 bits, so we have to extend and then truncate.
5142 unsigned W
= D
.getBitWidth();
5143 APInt P
= D0
.zext(W
+ 1)
5144 .multiplicativeInverse(APInt::getSignedMinValue(W
+ 1))
5146 assert(!P
.isNullValue() && "No multiplicative inverse!"); // unreachable
5147 assert((D0
* P
).isOneValue() && "Multiplicative inverse sanity check.");
5149 // A = floor((2^(W - 1) - 1) / D0) & -2^K
5150 APInt A
= APInt::getSignedMaxValue(W
).udiv(D0
);
5153 if (!D
.isMinSignedValue()) {
5154 // If divisor INT_MIN, then we don't care about this lane in this fold,
5155 // we'll special-handle it.
5156 NeedToApplyOffset
|= A
!= 0;
5159 // Q = floor((2 * A) / (2^K))
5160 APInt Q
= (2 * A
).udiv(APInt::getOneBitSet(W
, K
));
5162 assert(APInt::getAllOnesValue(SVT
.getSizeInBits()).ugt(A
) &&
5163 "We are expecting that A is always less than all-ones for SVT");
5164 assert(APInt::getAllOnesValue(ShSVT
.getSizeInBits()).ugt(K
) &&
5165 "We are expecting that K is always less than all-ones for ShSVT");
5167 // If the divisor is 1 the result can be constant-folded. Likewise, we
5168 // don't care about INT_MIN lanes, those can be set to undef if appropriate.
5169 if (D
.isOneValue()) {
5170 // Set P, A and K to a bogus values so we can try to splat them.
5175 // x ?% 1 == 0 <--> true <--> x u<= -1
5179 PAmts
.push_back(DAG
.getConstant(P
, DL
, SVT
));
5180 AAmts
.push_back(DAG
.getConstant(A
, DL
, SVT
));
5182 DAG
.getConstant(APInt(ShSVT
.getSizeInBits(), K
), DL
, ShSVT
));
5183 QAmts
.push_back(DAG
.getConstant(Q
, DL
, SVT
));
5187 SDValue N
= REMNode
.getOperand(0);
5188 SDValue D
= REMNode
.getOperand(1);
5190 // Collect the values from each element.
5191 if (!ISD::matchUnaryPredicate(D
, BuildSREMPattern
))
5194 // If this is a srem by a one, avoid the fold since it can be constant-folded.
5195 if (AllDivisorsAreOnes
)
5198 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
5199 // since it can be best implemented as a bit test.
5200 if (AllDivisorsArePowerOfTwo
)
5203 SDValue PVal
, AVal
, KVal
, QVal
;
5204 if (VT
.isVector()) {
5205 if (HadOneDivisor
) {
5206 // Try to turn PAmts into a splat, since we don't care about the values
5207 // that are currently '0'. If we can't, just keep '0'`s.
5208 turnVectorIntoSplatVector(PAmts
, isNullConstant
);
5209 // Try to turn AAmts into a splat, since we don't care about the
5210 // values that are currently '-1'. If we can't, change them to '0'`s.
5211 turnVectorIntoSplatVector(AAmts
, isAllOnesConstant
,
5212 DAG
.getConstant(0, DL
, SVT
));
5213 // Try to turn KAmts into a splat, since we don't care about the values
5214 // that are currently '-1'. If we can't, change them to '0'`s.
5215 turnVectorIntoSplatVector(KAmts
, isAllOnesConstant
,
5216 DAG
.getConstant(0, DL
, ShSVT
));
5219 PVal
= DAG
.getBuildVector(VT
, DL
, PAmts
);
5220 AVal
= DAG
.getBuildVector(VT
, DL
, AAmts
);
5221 KVal
= DAG
.getBuildVector(ShVT
, DL
, KAmts
);
5222 QVal
= DAG
.getBuildVector(VT
, DL
, QAmts
);
5231 SDValue Op0
= DAG
.getNode(ISD::MUL
, DL
, VT
, N
, PVal
);
5232 Created
.push_back(Op0
.getNode());
5234 if (NeedToApplyOffset
) {
5235 // We need ADD to do this.
5236 if (!isOperationLegalOrCustom(ISD::ADD
, VT
))
5239 // (add (mul N, P), A)
5240 Op0
= DAG
.getNode(ISD::ADD
, DL
, VT
, Op0
, AVal
);
5241 Created
.push_back(Op0
.getNode());
5244 // Rotate right only if any divisor was even. We avoid rotates for all-odd
5245 // divisors as a performance improvement, since rotating by 0 is a no-op.
5246 if (HadEvenDivisor
) {
5247 // We need ROTR to do this.
5248 if (!isOperationLegalOrCustom(ISD::ROTR
, VT
))
5251 Flags
.setExact(true);
5252 // SREM: (rotr (add (mul N, P), A), K)
5253 Op0
= DAG
.getNode(ISD::ROTR
, DL
, VT
, Op0
, KVal
, Flags
);
5254 Created
.push_back(Op0
.getNode());
5257 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
5259 DAG
.getSetCC(DL
, SETCCVT
, Op0
, QVal
,
5260 ((Cond
== ISD::SETEQ
) ? ISD::SETULE
: ISD::SETUGT
));
5262 // If we didn't have lanes with INT_MIN divisor, then we're done.
5263 if (!HadIntMinDivisor
)
5266 // That fold is only valid for positive divisors. Which effectively means,
5267 // it is invalid for INT_MIN divisors. So if we have such a lane,
5268 // we must fix-up results for said lanes.
5269 assert(VT
.isVector() && "Can/should only get here for vectors.");
5271 if (!isOperationLegalOrCustom(ISD::SETEQ
, VT
) ||
5272 !isOperationLegalOrCustom(ISD::AND
, VT
) ||
5273 !isOperationLegalOrCustom(Cond
, VT
) ||
5274 !isOperationLegalOrCustom(ISD::VSELECT
, VT
))
5277 Created
.push_back(Fold
.getNode());
5279 SDValue IntMin
= DAG
.getConstant(
5280 APInt::getSignedMinValue(SVT
.getScalarSizeInBits()), DL
, VT
);
5281 SDValue IntMax
= DAG
.getConstant(
5282 APInt::getSignedMaxValue(SVT
.getScalarSizeInBits()), DL
, VT
);
5284 DAG
.getConstant(APInt::getNullValue(SVT
.getScalarSizeInBits()), DL
, VT
);
5286 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded.
5287 SDValue DivisorIsIntMin
= DAG
.getSetCC(DL
, SETCCVT
, D
, IntMin
, ISD::SETEQ
);
5288 Created
.push_back(DivisorIsIntMin
.getNode());
5290 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0
5291 SDValue Masked
= DAG
.getNode(ISD::AND
, DL
, VT
, N
, IntMax
);
5292 Created
.push_back(Masked
.getNode());
5293 SDValue MaskedIsZero
= DAG
.getSetCC(DL
, SETCCVT
, Masked
, Zero
, Cond
);
5294 Created
.push_back(MaskedIsZero
.getNode());
5296 // To produce final result we need to blend 2 vectors: 'SetCC' and
5297 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick
5298 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is
5299 // constant-folded, select can get lowered to a shuffle with constant mask.
5301 DAG
.getNode(ISD::VSELECT
, DL
, VT
, DivisorIsIntMin
, MaskedIsZero
, Fold
);
5306 bool TargetLowering::
5307 verifyReturnAddressArgumentIsConstant(SDValue Op
, SelectionDAG
&DAG
) const {
5308 if (!isa
<ConstantSDNode
>(Op
.getOperand(0))) {
5309 DAG
.getContext()->emitError("argument to '__builtin_return_address' must "
5310 "be a constant integer");
5317 //===----------------------------------------------------------------------===//
5318 // Legalization Utilities
5319 //===----------------------------------------------------------------------===//
5321 bool TargetLowering::expandMUL_LOHI(unsigned Opcode
, EVT VT
, SDLoc dl
,
5322 SDValue LHS
, SDValue RHS
,
5323 SmallVectorImpl
<SDValue
> &Result
,
5324 EVT HiLoVT
, SelectionDAG
&DAG
,
5325 MulExpansionKind Kind
, SDValue LL
,
5326 SDValue LH
, SDValue RL
, SDValue RH
) const {
5327 assert(Opcode
== ISD::MUL
|| Opcode
== ISD::UMUL_LOHI
||
5328 Opcode
== ISD::SMUL_LOHI
);
5330 bool HasMULHS
= (Kind
== MulExpansionKind::Always
) ||
5331 isOperationLegalOrCustom(ISD::MULHS
, HiLoVT
);
5332 bool HasMULHU
= (Kind
== MulExpansionKind::Always
) ||
5333 isOperationLegalOrCustom(ISD::MULHU
, HiLoVT
);
5334 bool HasSMUL_LOHI
= (Kind
== MulExpansionKind::Always
) ||
5335 isOperationLegalOrCustom(ISD::SMUL_LOHI
, HiLoVT
);
5336 bool HasUMUL_LOHI
= (Kind
== MulExpansionKind::Always
) ||
5337 isOperationLegalOrCustom(ISD::UMUL_LOHI
, HiLoVT
);
5339 if (!HasMULHU
&& !HasMULHS
&& !HasUMUL_LOHI
&& !HasSMUL_LOHI
)
5342 unsigned OuterBitSize
= VT
.getScalarSizeInBits();
5343 unsigned InnerBitSize
= HiLoVT
.getScalarSizeInBits();
5344 unsigned LHSSB
= DAG
.ComputeNumSignBits(LHS
);
5345 unsigned RHSSB
= DAG
.ComputeNumSignBits(RHS
);
5347 // LL, LH, RL, and RH must be either all NULL or all set to a value.
5348 assert((LL
.getNode() && LH
.getNode() && RL
.getNode() && RH
.getNode()) ||
5349 (!LL
.getNode() && !LH
.getNode() && !RL
.getNode() && !RH
.getNode()));
5351 SDVTList VTs
= DAG
.getVTList(HiLoVT
, HiLoVT
);
5352 auto MakeMUL_LOHI
= [&](SDValue L
, SDValue R
, SDValue
&Lo
, SDValue
&Hi
,
5353 bool Signed
) -> bool {
5354 if ((Signed
&& HasSMUL_LOHI
) || (!Signed
&& HasUMUL_LOHI
)) {
5355 Lo
= DAG
.getNode(Signed
? ISD::SMUL_LOHI
: ISD::UMUL_LOHI
, dl
, VTs
, L
, R
);
5356 Hi
= SDValue(Lo
.getNode(), 1);
5359 if ((Signed
&& HasMULHS
) || (!Signed
&& HasMULHU
)) {
5360 Lo
= DAG
.getNode(ISD::MUL
, dl
, HiLoVT
, L
, R
);
5361 Hi
= DAG
.getNode(Signed
? ISD::MULHS
: ISD::MULHU
, dl
, HiLoVT
, L
, R
);
5369 if (!LL
.getNode() && !RL
.getNode() &&
5370 isOperationLegalOrCustom(ISD::TRUNCATE
, HiLoVT
)) {
5371 LL
= DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, LHS
);
5372 RL
= DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, RHS
);
5378 APInt HighMask
= APInt::getHighBitsSet(OuterBitSize
, InnerBitSize
);
5379 if (DAG
.MaskedValueIsZero(LHS
, HighMask
) &&
5380 DAG
.MaskedValueIsZero(RHS
, HighMask
)) {
5381 // The inputs are both zero-extended.
5382 if (MakeMUL_LOHI(LL
, RL
, Lo
, Hi
, false)) {
5383 Result
.push_back(Lo
);
5384 Result
.push_back(Hi
);
5385 if (Opcode
!= ISD::MUL
) {
5386 SDValue Zero
= DAG
.getConstant(0, dl
, HiLoVT
);
5387 Result
.push_back(Zero
);
5388 Result
.push_back(Zero
);
5394 if (!VT
.isVector() && Opcode
== ISD::MUL
&& LHSSB
> InnerBitSize
&&
5395 RHSSB
> InnerBitSize
) {
5396 // The input values are both sign-extended.
5397 // TODO non-MUL case?
5398 if (MakeMUL_LOHI(LL
, RL
, Lo
, Hi
, true)) {
5399 Result
.push_back(Lo
);
5400 Result
.push_back(Hi
);
5405 unsigned ShiftAmount
= OuterBitSize
- InnerBitSize
;
5406 EVT ShiftAmountTy
= getShiftAmountTy(VT
, DAG
.getDataLayout());
5407 if (APInt::getMaxValue(ShiftAmountTy
.getSizeInBits()).ult(ShiftAmount
)) {
5408 // FIXME getShiftAmountTy does not always return a sensible result when VT
5409 // is an illegal type, and so the type may be too small to fit the shift
5410 // amount. Override it with i32. The shift will have to be legalized.
5411 ShiftAmountTy
= MVT::i32
;
5413 SDValue Shift
= DAG
.getConstant(ShiftAmount
, dl
, ShiftAmountTy
);
5415 if (!LH
.getNode() && !RH
.getNode() &&
5416 isOperationLegalOrCustom(ISD::SRL
, VT
) &&
5417 isOperationLegalOrCustom(ISD::TRUNCATE
, HiLoVT
)) {
5418 LH
= DAG
.getNode(ISD::SRL
, dl
, VT
, LHS
, Shift
);
5419 LH
= DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, LH
);
5420 RH
= DAG
.getNode(ISD::SRL
, dl
, VT
, RHS
, Shift
);
5421 RH
= DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, RH
);
5427 if (!MakeMUL_LOHI(LL
, RL
, Lo
, Hi
, false))
5430 Result
.push_back(Lo
);
5432 if (Opcode
== ISD::MUL
) {
5433 RH
= DAG
.getNode(ISD::MUL
, dl
, HiLoVT
, LL
, RH
);
5434 LH
= DAG
.getNode(ISD::MUL
, dl
, HiLoVT
, LH
, RL
);
5435 Hi
= DAG
.getNode(ISD::ADD
, dl
, HiLoVT
, Hi
, RH
);
5436 Hi
= DAG
.getNode(ISD::ADD
, dl
, HiLoVT
, Hi
, LH
);
5437 Result
.push_back(Hi
);
5441 // Compute the full width result.
5442 auto Merge
= [&](SDValue Lo
, SDValue Hi
) -> SDValue
{
5443 Lo
= DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, Lo
);
5444 Hi
= DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, Hi
);
5445 Hi
= DAG
.getNode(ISD::SHL
, dl
, VT
, Hi
, Shift
);
5446 return DAG
.getNode(ISD::OR
, dl
, VT
, Lo
, Hi
);
5449 SDValue Next
= DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, Hi
);
5450 if (!MakeMUL_LOHI(LL
, RH
, Lo
, Hi
, false))
5453 // This is effectively the add part of a multiply-add of half-sized operands,
5454 // so it cannot overflow.
5455 Next
= DAG
.getNode(ISD::ADD
, dl
, VT
, Next
, Merge(Lo
, Hi
));
5457 if (!MakeMUL_LOHI(LH
, RL
, Lo
, Hi
, false))
5460 SDValue Zero
= DAG
.getConstant(0, dl
, HiLoVT
);
5461 EVT BoolType
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
5463 bool UseGlue
= (isOperationLegalOrCustom(ISD::ADDC
, VT
) &&
5464 isOperationLegalOrCustom(ISD::ADDE
, VT
));
5466 Next
= DAG
.getNode(ISD::ADDC
, dl
, DAG
.getVTList(VT
, MVT::Glue
), Next
,
5469 Next
= DAG
.getNode(ISD::ADDCARRY
, dl
, DAG
.getVTList(VT
, BoolType
), Next
,
5470 Merge(Lo
, Hi
), DAG
.getConstant(0, dl
, BoolType
));
5472 SDValue Carry
= Next
.getValue(1);
5473 Result
.push_back(DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, Next
));
5474 Next
= DAG
.getNode(ISD::SRL
, dl
, VT
, Next
, Shift
);
5476 if (!MakeMUL_LOHI(LH
, RH
, Lo
, Hi
, Opcode
== ISD::SMUL_LOHI
))
5480 Hi
= DAG
.getNode(ISD::ADDE
, dl
, DAG
.getVTList(HiLoVT
, MVT::Glue
), Hi
, Zero
,
5483 Hi
= DAG
.getNode(ISD::ADDCARRY
, dl
, DAG
.getVTList(HiLoVT
, BoolType
), Hi
,
5486 Next
= DAG
.getNode(ISD::ADD
, dl
, VT
, Next
, Merge(Lo
, Hi
));
5488 if (Opcode
== ISD::SMUL_LOHI
) {
5489 SDValue NextSub
= DAG
.getNode(ISD::SUB
, dl
, VT
, Next
,
5490 DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, RL
));
5491 Next
= DAG
.getSelectCC(dl
, LH
, Zero
, NextSub
, Next
, ISD::SETLT
);
5493 NextSub
= DAG
.getNode(ISD::SUB
, dl
, VT
, Next
,
5494 DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, LL
));
5495 Next
= DAG
.getSelectCC(dl
, RH
, Zero
, NextSub
, Next
, ISD::SETLT
);
5498 Result
.push_back(DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, Next
));
5499 Next
= DAG
.getNode(ISD::SRL
, dl
, VT
, Next
, Shift
);
5500 Result
.push_back(DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, Next
));
5504 bool TargetLowering::expandMUL(SDNode
*N
, SDValue
&Lo
, SDValue
&Hi
, EVT HiLoVT
,
5505 SelectionDAG
&DAG
, MulExpansionKind Kind
,
5506 SDValue LL
, SDValue LH
, SDValue RL
,
5508 SmallVector
<SDValue
, 2> Result
;
5509 bool Ok
= expandMUL_LOHI(N
->getOpcode(), N
->getValueType(0), N
,
5510 N
->getOperand(0), N
->getOperand(1), Result
, HiLoVT
,
5511 DAG
, Kind
, LL
, LH
, RL
, RH
);
5513 assert(Result
.size() == 2);
5520 bool TargetLowering::expandFunnelShift(SDNode
*Node
, SDValue
&Result
,
5521 SelectionDAG
&DAG
) const {
5522 EVT VT
= Node
->getValueType(0);
5524 if (VT
.isVector() && (!isOperationLegalOrCustom(ISD::SHL
, VT
) ||
5525 !isOperationLegalOrCustom(ISD::SRL
, VT
) ||
5526 !isOperationLegalOrCustom(ISD::SUB
, VT
) ||
5527 !isOperationLegalOrCustomOrPromote(ISD::OR
, VT
)))
5530 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5531 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5532 SDValue X
= Node
->getOperand(0);
5533 SDValue Y
= Node
->getOperand(1);
5534 SDValue Z
= Node
->getOperand(2);
5536 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
5537 bool IsFSHL
= Node
->getOpcode() == ISD::FSHL
;
5538 SDLoc
DL(SDValue(Node
, 0));
5540 EVT ShVT
= Z
.getValueType();
5541 SDValue BitWidthC
= DAG
.getConstant(EltSizeInBits
, DL
, ShVT
);
5542 SDValue Zero
= DAG
.getConstant(0, DL
, ShVT
);
5545 if (isPowerOf2_32(EltSizeInBits
)) {
5546 SDValue Mask
= DAG
.getConstant(EltSizeInBits
- 1, DL
, ShVT
);
5547 ShAmt
= DAG
.getNode(ISD::AND
, DL
, ShVT
, Z
, Mask
);
5549 ShAmt
= DAG
.getNode(ISD::UREM
, DL
, ShVT
, Z
, BitWidthC
);
5552 SDValue InvShAmt
= DAG
.getNode(ISD::SUB
, DL
, ShVT
, BitWidthC
, ShAmt
);
5553 SDValue ShX
= DAG
.getNode(ISD::SHL
, DL
, VT
, X
, IsFSHL
? ShAmt
: InvShAmt
);
5554 SDValue ShY
= DAG
.getNode(ISD::SRL
, DL
, VT
, Y
, IsFSHL
? InvShAmt
: ShAmt
);
5555 SDValue Or
= DAG
.getNode(ISD::OR
, DL
, VT
, ShX
, ShY
);
5557 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
5558 // and that is undefined. We must compare and select to avoid UB.
5559 EVT CCVT
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), ShVT
);
5561 // For fshl, 0-shift returns the 1st arg (X).
5562 // For fshr, 0-shift returns the 2nd arg (Y).
5563 SDValue IsZeroShift
= DAG
.getSetCC(DL
, CCVT
, ShAmt
, Zero
, ISD::SETEQ
);
5564 Result
= DAG
.getSelect(DL
, VT
, IsZeroShift
, IsFSHL
? X
: Y
, Or
);
5568 // TODO: Merge with expandFunnelShift.
5569 bool TargetLowering::expandROT(SDNode
*Node
, SDValue
&Result
,
5570 SelectionDAG
&DAG
) const {
5571 EVT VT
= Node
->getValueType(0);
5572 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
5573 bool IsLeft
= Node
->getOpcode() == ISD::ROTL
;
5574 SDValue Op0
= Node
->getOperand(0);
5575 SDValue Op1
= Node
->getOperand(1);
5576 SDLoc
DL(SDValue(Node
, 0));
5578 EVT ShVT
= Op1
.getValueType();
5579 SDValue BitWidthC
= DAG
.getConstant(EltSizeInBits
, DL
, ShVT
);
5581 // If a rotate in the other direction is legal, use it.
5582 unsigned RevRot
= IsLeft
? ISD::ROTR
: ISD::ROTL
;
5583 if (isOperationLegal(RevRot
, VT
)) {
5584 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, ShVT
, BitWidthC
, Op1
);
5585 Result
= DAG
.getNode(RevRot
, DL
, VT
, Op0
, Sub
);
5589 if (VT
.isVector() && (!isOperationLegalOrCustom(ISD::SHL
, VT
) ||
5590 !isOperationLegalOrCustom(ISD::SRL
, VT
) ||
5591 !isOperationLegalOrCustom(ISD::SUB
, VT
) ||
5592 !isOperationLegalOrCustomOrPromote(ISD::OR
, VT
) ||
5593 !isOperationLegalOrCustomOrPromote(ISD::AND
, VT
)))
5597 // (rotl x, c) -> (or (shl x, (and c, w-1)), (srl x, (and w-c, w-1)))
5598 // (rotr x, c) -> (or (srl x, (and c, w-1)), (shl x, (and w-c, w-1)))
5600 assert(isPowerOf2_32(EltSizeInBits
) && EltSizeInBits
> 1 &&
5601 "Expecting the type bitwidth to be a power of 2");
5602 unsigned ShOpc
= IsLeft
? ISD::SHL
: ISD::SRL
;
5603 unsigned HsOpc
= IsLeft
? ISD::SRL
: ISD::SHL
;
5604 SDValue BitWidthMinusOneC
= DAG
.getConstant(EltSizeInBits
- 1, DL
, ShVT
);
5605 SDValue NegOp1
= DAG
.getNode(ISD::SUB
, DL
, ShVT
, BitWidthC
, Op1
);
5606 SDValue And0
= DAG
.getNode(ISD::AND
, DL
, ShVT
, Op1
, BitWidthMinusOneC
);
5607 SDValue And1
= DAG
.getNode(ISD::AND
, DL
, ShVT
, NegOp1
, BitWidthMinusOneC
);
5608 Result
= DAG
.getNode(ISD::OR
, DL
, VT
, DAG
.getNode(ShOpc
, DL
, VT
, Op0
, And0
),
5609 DAG
.getNode(HsOpc
, DL
, VT
, Op0
, And1
));
5613 bool TargetLowering::expandFP_TO_SINT(SDNode
*Node
, SDValue
&Result
,
5614 SelectionDAG
&DAG
) const {
5615 unsigned OpNo
= Node
->isStrictFPOpcode() ? 1 : 0;
5616 SDValue Src
= Node
->getOperand(OpNo
);
5617 EVT SrcVT
= Src
.getValueType();
5618 EVT DstVT
= Node
->getValueType(0);
5619 SDLoc
dl(SDValue(Node
, 0));
5621 // FIXME: Only f32 to i64 conversions are supported.
5622 if (SrcVT
!= MVT::f32
|| DstVT
!= MVT::i64
)
5625 if (Node
->isStrictFPOpcode())
5626 // When a NaN is converted to an integer a trap is allowed. We can't
5627 // use this expansion here because it would eliminate that trap. Other
5628 // traps are also allowed and cannot be eliminated. See
5629 // IEEE 754-2008 sec 5.8.
5632 // Expand f32 -> i64 conversion
5633 // This algorithm comes from compiler-rt's implementation of fixsfdi:
5634 // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/builtins/fixsfdi.c
5635 unsigned SrcEltBits
= SrcVT
.getScalarSizeInBits();
5636 EVT IntVT
= SrcVT
.changeTypeToInteger();
5637 EVT IntShVT
= getShiftAmountTy(IntVT
, DAG
.getDataLayout());
5639 SDValue ExponentMask
= DAG
.getConstant(0x7F800000, dl
, IntVT
);
5640 SDValue ExponentLoBit
= DAG
.getConstant(23, dl
, IntVT
);
5641 SDValue Bias
= DAG
.getConstant(127, dl
, IntVT
);
5642 SDValue SignMask
= DAG
.getConstant(APInt::getSignMask(SrcEltBits
), dl
, IntVT
);
5643 SDValue SignLowBit
= DAG
.getConstant(SrcEltBits
- 1, dl
, IntVT
);
5644 SDValue MantissaMask
= DAG
.getConstant(0x007FFFFF, dl
, IntVT
);
5646 SDValue Bits
= DAG
.getNode(ISD::BITCAST
, dl
, IntVT
, Src
);
5648 SDValue ExponentBits
= DAG
.getNode(
5649 ISD::SRL
, dl
, IntVT
, DAG
.getNode(ISD::AND
, dl
, IntVT
, Bits
, ExponentMask
),
5650 DAG
.getZExtOrTrunc(ExponentLoBit
, dl
, IntShVT
));
5651 SDValue Exponent
= DAG
.getNode(ISD::SUB
, dl
, IntVT
, ExponentBits
, Bias
);
5653 SDValue Sign
= DAG
.getNode(ISD::SRA
, dl
, IntVT
,
5654 DAG
.getNode(ISD::AND
, dl
, IntVT
, Bits
, SignMask
),
5655 DAG
.getZExtOrTrunc(SignLowBit
, dl
, IntShVT
));
5656 Sign
= DAG
.getSExtOrTrunc(Sign
, dl
, DstVT
);
5658 SDValue R
= DAG
.getNode(ISD::OR
, dl
, IntVT
,
5659 DAG
.getNode(ISD::AND
, dl
, IntVT
, Bits
, MantissaMask
),
5660 DAG
.getConstant(0x00800000, dl
, IntVT
));
5662 R
= DAG
.getZExtOrTrunc(R
, dl
, DstVT
);
5664 R
= DAG
.getSelectCC(
5665 dl
, Exponent
, ExponentLoBit
,
5666 DAG
.getNode(ISD::SHL
, dl
, DstVT
, R
,
5668 DAG
.getNode(ISD::SUB
, dl
, IntVT
, Exponent
, ExponentLoBit
),
5670 DAG
.getNode(ISD::SRL
, dl
, DstVT
, R
,
5672 DAG
.getNode(ISD::SUB
, dl
, IntVT
, ExponentLoBit
, Exponent
),
5676 SDValue Ret
= DAG
.getNode(ISD::SUB
, dl
, DstVT
,
5677 DAG
.getNode(ISD::XOR
, dl
, DstVT
, R
, Sign
), Sign
);
5679 Result
= DAG
.getSelectCC(dl
, Exponent
, DAG
.getConstant(0, dl
, IntVT
),
5680 DAG
.getConstant(0, dl
, DstVT
), Ret
, ISD::SETLT
);
5684 bool TargetLowering::expandFP_TO_UINT(SDNode
*Node
, SDValue
&Result
,
5686 SelectionDAG
&DAG
) const {
5687 SDLoc
dl(SDValue(Node
, 0));
5688 unsigned OpNo
= Node
->isStrictFPOpcode() ? 1 : 0;
5689 SDValue Src
= Node
->getOperand(OpNo
);
5691 EVT SrcVT
= Src
.getValueType();
5692 EVT DstVT
= Node
->getValueType(0);
5694 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), SrcVT
);
5696 // Only expand vector types if we have the appropriate vector bit operations.
5697 unsigned SIntOpcode
= Node
->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT
:
5699 if (DstVT
.isVector() && (!isOperationLegalOrCustom(SIntOpcode
, DstVT
) ||
5700 !isOperationLegalOrCustomOrPromote(ISD::XOR
, SrcVT
)))
5703 // If the maximum float value is smaller then the signed integer range,
5704 // the destination signmask can't be represented by the float, so we can
5705 // just use FP_TO_SINT directly.
5706 const fltSemantics
&APFSem
= DAG
.EVTToAPFloatSemantics(SrcVT
);
5707 APFloat
APF(APFSem
, APInt::getNullValue(SrcVT
.getScalarSizeInBits()));
5708 APInt SignMask
= APInt::getSignMask(DstVT
.getScalarSizeInBits());
5709 if (APFloat::opOverflow
&
5710 APF
.convertFromAPInt(SignMask
, false, APFloat::rmNearestTiesToEven
)) {
5711 if (Node
->isStrictFPOpcode()) {
5712 Result
= DAG
.getNode(ISD::STRICT_FP_TO_SINT
, dl
, { DstVT
, MVT::Other
},
5713 { Node
->getOperand(0), Src
});
5714 Chain
= Result
.getValue(1);
5716 Result
= DAG
.getNode(ISD::FP_TO_SINT
, dl
, DstVT
, Src
);
5720 SDValue Cst
= DAG
.getConstantFP(APF
, dl
, SrcVT
);
5721 SDValue Sel
= DAG
.getSetCC(dl
, SetCCVT
, Src
, Cst
, ISD::SETLT
);
5723 bool Strict
= Node
->isStrictFPOpcode() ||
5724 shouldUseStrictFP_TO_INT(SrcVT
, DstVT
, /*IsSigned*/ false);
5727 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
5728 // signmask then offset (the result of which should be fully representable).
5729 // Sel = Src < 0x8000000000000000
5730 // Val = select Sel, Src, Src - 0x8000000000000000
5731 // Ofs = select Sel, 0, 0x8000000000000000
5732 // Result = fp_to_sint(Val) ^ Ofs
5734 // TODO: Should any fast-math-flags be set for the FSUB?
5736 if (Node
->isStrictFPOpcode())
5737 SrcBiased
= DAG
.getNode(ISD::STRICT_FSUB
, dl
, { SrcVT
, MVT::Other
},
5738 { Node
->getOperand(0), Src
, Cst
});
5740 SrcBiased
= DAG
.getNode(ISD::FSUB
, dl
, SrcVT
, Src
, Cst
);
5741 SDValue Val
= DAG
.getSelect(dl
, SrcVT
, Sel
, Src
, SrcBiased
);
5742 SDValue Ofs
= DAG
.getSelect(dl
, DstVT
, Sel
, DAG
.getConstant(0, dl
, DstVT
),
5743 DAG
.getConstant(SignMask
, dl
, DstVT
));
5745 if (Node
->isStrictFPOpcode()) {
5746 SInt
= DAG
.getNode(ISD::STRICT_FP_TO_SINT
, dl
, { DstVT
, MVT::Other
},
5747 { SrcBiased
.getValue(1), Val
});
5748 Chain
= SInt
.getValue(1);
5750 SInt
= DAG
.getNode(ISD::FP_TO_SINT
, dl
, DstVT
, Val
);
5751 Result
= DAG
.getNode(ISD::XOR
, dl
, DstVT
, SInt
, Ofs
);
5753 // Expand based on maximum range of FP_TO_SINT:
5754 // True = fp_to_sint(Src)
5755 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
5756 // Result = select (Src < 0x8000000000000000), True, False
5758 SDValue True
= DAG
.getNode(ISD::FP_TO_SINT
, dl
, DstVT
, Src
);
5759 // TODO: Should any fast-math-flags be set for the FSUB?
5760 SDValue False
= DAG
.getNode(ISD::FP_TO_SINT
, dl
, DstVT
,
5761 DAG
.getNode(ISD::FSUB
, dl
, SrcVT
, Src
, Cst
));
5762 False
= DAG
.getNode(ISD::XOR
, dl
, DstVT
, False
,
5763 DAG
.getConstant(SignMask
, dl
, DstVT
));
5764 Result
= DAG
.getSelect(dl
, DstVT
, Sel
, True
, False
);
5769 bool TargetLowering::expandUINT_TO_FP(SDNode
*Node
, SDValue
&Result
,
5770 SelectionDAG
&DAG
) const {
5771 SDValue Src
= Node
->getOperand(0);
5772 EVT SrcVT
= Src
.getValueType();
5773 EVT DstVT
= Node
->getValueType(0);
5775 if (SrcVT
.getScalarType() != MVT::i64
)
5778 SDLoc
dl(SDValue(Node
, 0));
5779 EVT ShiftVT
= getShiftAmountTy(SrcVT
, DAG
.getDataLayout());
5781 if (DstVT
.getScalarType() == MVT::f32
) {
5782 // Only expand vector types if we have the appropriate vector bit
5784 if (SrcVT
.isVector() &&
5785 (!isOperationLegalOrCustom(ISD::SRL
, SrcVT
) ||
5786 !isOperationLegalOrCustom(ISD::FADD
, DstVT
) ||
5787 !isOperationLegalOrCustom(ISD::SINT_TO_FP
, SrcVT
) ||
5788 !isOperationLegalOrCustomOrPromote(ISD::OR
, SrcVT
) ||
5789 !isOperationLegalOrCustomOrPromote(ISD::AND
, SrcVT
)))
5792 // For unsigned conversions, convert them to signed conversions using the
5793 // algorithm from the x86_64 __floatundidf in compiler_rt.
5794 SDValue Fast
= DAG
.getNode(ISD::SINT_TO_FP
, dl
, DstVT
, Src
);
5796 SDValue ShiftConst
= DAG
.getConstant(1, dl
, ShiftVT
);
5797 SDValue Shr
= DAG
.getNode(ISD::SRL
, dl
, SrcVT
, Src
, ShiftConst
);
5798 SDValue AndConst
= DAG
.getConstant(1, dl
, SrcVT
);
5799 SDValue And
= DAG
.getNode(ISD::AND
, dl
, SrcVT
, Src
, AndConst
);
5800 SDValue Or
= DAG
.getNode(ISD::OR
, dl
, SrcVT
, And
, Shr
);
5802 SDValue SignCvt
= DAG
.getNode(ISD::SINT_TO_FP
, dl
, DstVT
, Or
);
5803 SDValue Slow
= DAG
.getNode(ISD::FADD
, dl
, DstVT
, SignCvt
, SignCvt
);
5805 // TODO: This really should be implemented using a branch rather than a
5806 // select. We happen to get lucky and machinesink does the right
5807 // thing most of the time. This would be a good candidate for a
5808 // pseudo-op, or, even better, for whole-function isel.
5810 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), SrcVT
);
5812 SDValue SignBitTest
= DAG
.getSetCC(
5813 dl
, SetCCVT
, Src
, DAG
.getConstant(0, dl
, SrcVT
), ISD::SETLT
);
5814 Result
= DAG
.getSelect(dl
, DstVT
, SignBitTest
, Slow
, Fast
);
5818 if (DstVT
.getScalarType() == MVT::f64
) {
5819 // Only expand vector types if we have the appropriate vector bit
5821 if (SrcVT
.isVector() &&
5822 (!isOperationLegalOrCustom(ISD::SRL
, SrcVT
) ||
5823 !isOperationLegalOrCustom(ISD::FADD
, DstVT
) ||
5824 !isOperationLegalOrCustom(ISD::FSUB
, DstVT
) ||
5825 !isOperationLegalOrCustomOrPromote(ISD::OR
, SrcVT
) ||
5826 !isOperationLegalOrCustomOrPromote(ISD::AND
, SrcVT
)))
5829 // Implementation of unsigned i64 to f64 following the algorithm in
5830 // __floatundidf in compiler_rt. This implementation has the advantage
5831 // of performing rounding correctly, both in the default rounding mode
5832 // and in all alternate rounding modes.
5833 SDValue TwoP52
= DAG
.getConstant(UINT64_C(0x4330000000000000), dl
, SrcVT
);
5834 SDValue TwoP84PlusTwoP52
= DAG
.getConstantFP(
5835 BitsToDouble(UINT64_C(0x4530000000100000)), dl
, DstVT
);
5836 SDValue TwoP84
= DAG
.getConstant(UINT64_C(0x4530000000000000), dl
, SrcVT
);
5837 SDValue LoMask
= DAG
.getConstant(UINT64_C(0x00000000FFFFFFFF), dl
, SrcVT
);
5838 SDValue HiShift
= DAG
.getConstant(32, dl
, ShiftVT
);
5840 SDValue Lo
= DAG
.getNode(ISD::AND
, dl
, SrcVT
, Src
, LoMask
);
5841 SDValue Hi
= DAG
.getNode(ISD::SRL
, dl
, SrcVT
, Src
, HiShift
);
5842 SDValue LoOr
= DAG
.getNode(ISD::OR
, dl
, SrcVT
, Lo
, TwoP52
);
5843 SDValue HiOr
= DAG
.getNode(ISD::OR
, dl
, SrcVT
, Hi
, TwoP84
);
5844 SDValue LoFlt
= DAG
.getBitcast(DstVT
, LoOr
);
5845 SDValue HiFlt
= DAG
.getBitcast(DstVT
, HiOr
);
5846 SDValue HiSub
= DAG
.getNode(ISD::FSUB
, dl
, DstVT
, HiFlt
, TwoP84PlusTwoP52
);
5847 Result
= DAG
.getNode(ISD::FADD
, dl
, DstVT
, LoFlt
, HiSub
);
5854 SDValue
TargetLowering::expandFMINNUM_FMAXNUM(SDNode
*Node
,
5855 SelectionDAG
&DAG
) const {
5857 unsigned NewOp
= Node
->getOpcode() == ISD::FMINNUM
?
5858 ISD::FMINNUM_IEEE
: ISD::FMAXNUM_IEEE
;
5859 EVT VT
= Node
->getValueType(0);
5860 if (isOperationLegalOrCustom(NewOp
, VT
)) {
5861 SDValue Quiet0
= Node
->getOperand(0);
5862 SDValue Quiet1
= Node
->getOperand(1);
5864 if (!Node
->getFlags().hasNoNaNs()) {
5865 // Insert canonicalizes if it's possible we need to quiet to get correct
5867 if (!DAG
.isKnownNeverSNaN(Quiet0
)) {
5868 Quiet0
= DAG
.getNode(ISD::FCANONICALIZE
, dl
, VT
, Quiet0
,
5871 if (!DAG
.isKnownNeverSNaN(Quiet1
)) {
5872 Quiet1
= DAG
.getNode(ISD::FCANONICALIZE
, dl
, VT
, Quiet1
,
5877 return DAG
.getNode(NewOp
, dl
, VT
, Quiet0
, Quiet1
, Node
->getFlags());
5880 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
5881 // instead if there are no NaNs.
5882 if (Node
->getFlags().hasNoNaNs()) {
5883 unsigned IEEE2018Op
=
5884 Node
->getOpcode() == ISD::FMINNUM
? ISD::FMINIMUM
: ISD::FMAXIMUM
;
5885 if (isOperationLegalOrCustom(IEEE2018Op
, VT
)) {
5886 return DAG
.getNode(IEEE2018Op
, dl
, VT
, Node
->getOperand(0),
5887 Node
->getOperand(1), Node
->getFlags());
5894 bool TargetLowering::expandCTPOP(SDNode
*Node
, SDValue
&Result
,
5895 SelectionDAG
&DAG
) const {
5897 EVT VT
= Node
->getValueType(0);
5898 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
5899 SDValue Op
= Node
->getOperand(0);
5900 unsigned Len
= VT
.getScalarSizeInBits();
5901 assert(VT
.isInteger() && "CTPOP not implemented for this type.");
5903 // TODO: Add support for irregular type lengths.
5904 if (!(Len
<= 128 && Len
% 8 == 0))
5907 // Only expand vector types if we have the appropriate vector bit operations.
5908 if (VT
.isVector() && (!isOperationLegalOrCustom(ISD::ADD
, VT
) ||
5909 !isOperationLegalOrCustom(ISD::SUB
, VT
) ||
5910 !isOperationLegalOrCustom(ISD::SRL
, VT
) ||
5911 (Len
!= 8 && !isOperationLegalOrCustom(ISD::MUL
, VT
)) ||
5912 !isOperationLegalOrCustomOrPromote(ISD::AND
, VT
)))
5915 // This is the "best" algorithm from
5916 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
5918 DAG
.getConstant(APInt::getSplat(Len
, APInt(8, 0x55)), dl
, VT
);
5920 DAG
.getConstant(APInt::getSplat(Len
, APInt(8, 0x33)), dl
, VT
);
5922 DAG
.getConstant(APInt::getSplat(Len
, APInt(8, 0x0F)), dl
, VT
);
5924 DAG
.getConstant(APInt::getSplat(Len
, APInt(8, 0x01)), dl
, VT
);
5926 // v = v - ((v >> 1) & 0x55555555...)
5927 Op
= DAG
.getNode(ISD::SUB
, dl
, VT
, Op
,
5928 DAG
.getNode(ISD::AND
, dl
, VT
,
5929 DAG
.getNode(ISD::SRL
, dl
, VT
, Op
,
5930 DAG
.getConstant(1, dl
, ShVT
)),
5932 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
5933 Op
= DAG
.getNode(ISD::ADD
, dl
, VT
, DAG
.getNode(ISD::AND
, dl
, VT
, Op
, Mask33
),
5934 DAG
.getNode(ISD::AND
, dl
, VT
,
5935 DAG
.getNode(ISD::SRL
, dl
, VT
, Op
,
5936 DAG
.getConstant(2, dl
, ShVT
)),
5938 // v = (v + (v >> 4)) & 0x0F0F0F0F...
5939 Op
= DAG
.getNode(ISD::AND
, dl
, VT
,
5940 DAG
.getNode(ISD::ADD
, dl
, VT
, Op
,
5941 DAG
.getNode(ISD::SRL
, dl
, VT
, Op
,
5942 DAG
.getConstant(4, dl
, ShVT
))),
5944 // v = (v * 0x01010101...) >> (Len - 8)
5947 DAG
.getNode(ISD::SRL
, dl
, VT
, DAG
.getNode(ISD::MUL
, dl
, VT
, Op
, Mask01
),
5948 DAG
.getConstant(Len
- 8, dl
, ShVT
));
5954 bool TargetLowering::expandCTLZ(SDNode
*Node
, SDValue
&Result
,
5955 SelectionDAG
&DAG
) const {
5957 EVT VT
= Node
->getValueType(0);
5958 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
5959 SDValue Op
= Node
->getOperand(0);
5960 unsigned NumBitsPerElt
= VT
.getScalarSizeInBits();
5962 // If the non-ZERO_UNDEF version is supported we can use that instead.
5963 if (Node
->getOpcode() == ISD::CTLZ_ZERO_UNDEF
&&
5964 isOperationLegalOrCustom(ISD::CTLZ
, VT
)) {
5965 Result
= DAG
.getNode(ISD::CTLZ
, dl
, VT
, Op
);
5969 // If the ZERO_UNDEF version is supported use that and handle the zero case.
5970 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF
, VT
)) {
5972 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
5973 SDValue CTLZ
= DAG
.getNode(ISD::CTLZ_ZERO_UNDEF
, dl
, VT
, Op
);
5974 SDValue Zero
= DAG
.getConstant(0, dl
, VT
);
5975 SDValue SrcIsZero
= DAG
.getSetCC(dl
, SetCCVT
, Op
, Zero
, ISD::SETEQ
);
5976 Result
= DAG
.getNode(ISD::SELECT
, dl
, VT
, SrcIsZero
,
5977 DAG
.getConstant(NumBitsPerElt
, dl
, VT
), CTLZ
);
5981 // Only expand vector types if we have the appropriate vector bit operations.
5982 if (VT
.isVector() && (!isPowerOf2_32(NumBitsPerElt
) ||
5983 !isOperationLegalOrCustom(ISD::CTPOP
, VT
) ||
5984 !isOperationLegalOrCustom(ISD::SRL
, VT
) ||
5985 !isOperationLegalOrCustomOrPromote(ISD::OR
, VT
)))
5988 // for now, we do this:
5989 // x = x | (x >> 1);
5990 // x = x | (x >> 2);
5992 // x = x | (x >>16);
5993 // x = x | (x >>32); // for 64-bit input
5994 // return popcount(~x);
5996 // Ref: "Hacker's Delight" by Henry Warren
5997 for (unsigned i
= 0; (1U << i
) <= (NumBitsPerElt
/ 2); ++i
) {
5998 SDValue Tmp
= DAG
.getConstant(1ULL << i
, dl
, ShVT
);
5999 Op
= DAG
.getNode(ISD::OR
, dl
, VT
, Op
,
6000 DAG
.getNode(ISD::SRL
, dl
, VT
, Op
, Tmp
));
6002 Op
= DAG
.getNOT(dl
, Op
, VT
);
6003 Result
= DAG
.getNode(ISD::CTPOP
, dl
, VT
, Op
);
6007 bool TargetLowering::expandCTTZ(SDNode
*Node
, SDValue
&Result
,
6008 SelectionDAG
&DAG
) const {
6010 EVT VT
= Node
->getValueType(0);
6011 SDValue Op
= Node
->getOperand(0);
6012 unsigned NumBitsPerElt
= VT
.getScalarSizeInBits();
6014 // If the non-ZERO_UNDEF version is supported we can use that instead.
6015 if (Node
->getOpcode() == ISD::CTTZ_ZERO_UNDEF
&&
6016 isOperationLegalOrCustom(ISD::CTTZ
, VT
)) {
6017 Result
= DAG
.getNode(ISD::CTTZ
, dl
, VT
, Op
);
6021 // If the ZERO_UNDEF version is supported use that and handle the zero case.
6022 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF
, VT
)) {
6024 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
6025 SDValue CTTZ
= DAG
.getNode(ISD::CTTZ_ZERO_UNDEF
, dl
, VT
, Op
);
6026 SDValue Zero
= DAG
.getConstant(0, dl
, VT
);
6027 SDValue SrcIsZero
= DAG
.getSetCC(dl
, SetCCVT
, Op
, Zero
, ISD::SETEQ
);
6028 Result
= DAG
.getNode(ISD::SELECT
, dl
, VT
, SrcIsZero
,
6029 DAG
.getConstant(NumBitsPerElt
, dl
, VT
), CTTZ
);
6033 // Only expand vector types if we have the appropriate vector bit operations.
6034 if (VT
.isVector() && (!isPowerOf2_32(NumBitsPerElt
) ||
6035 (!isOperationLegalOrCustom(ISD::CTPOP
, VT
) &&
6036 !isOperationLegalOrCustom(ISD::CTLZ
, VT
)) ||
6037 !isOperationLegalOrCustom(ISD::SUB
, VT
) ||
6038 !isOperationLegalOrCustomOrPromote(ISD::AND
, VT
) ||
6039 !isOperationLegalOrCustomOrPromote(ISD::XOR
, VT
)))
6042 // for now, we use: { return popcount(~x & (x - 1)); }
6043 // unless the target has ctlz but not ctpop, in which case we use:
6044 // { return 32 - nlz(~x & (x-1)); }
6045 // Ref: "Hacker's Delight" by Henry Warren
6046 SDValue Tmp
= DAG
.getNode(
6047 ISD::AND
, dl
, VT
, DAG
.getNOT(dl
, Op
, VT
),
6048 DAG
.getNode(ISD::SUB
, dl
, VT
, Op
, DAG
.getConstant(1, dl
, VT
)));
6050 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
6051 if (isOperationLegal(ISD::CTLZ
, VT
) && !isOperationLegal(ISD::CTPOP
, VT
)) {
6053 DAG
.getNode(ISD::SUB
, dl
, VT
, DAG
.getConstant(NumBitsPerElt
, dl
, VT
),
6054 DAG
.getNode(ISD::CTLZ
, dl
, VT
, Tmp
));
6058 Result
= DAG
.getNode(ISD::CTPOP
, dl
, VT
, Tmp
);
6062 bool TargetLowering::expandABS(SDNode
*N
, SDValue
&Result
,
6063 SelectionDAG
&DAG
) const {
6065 EVT VT
= N
->getValueType(0);
6066 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
6067 SDValue Op
= N
->getOperand(0);
6069 // Only expand vector types if we have the appropriate vector operations.
6070 if (VT
.isVector() && (!isOperationLegalOrCustom(ISD::SRA
, VT
) ||
6071 !isOperationLegalOrCustom(ISD::ADD
, VT
) ||
6072 !isOperationLegalOrCustomOrPromote(ISD::XOR
, VT
)))
6076 DAG
.getNode(ISD::SRA
, dl
, VT
, Op
,
6077 DAG
.getConstant(VT
.getScalarSizeInBits() - 1, dl
, ShVT
));
6078 SDValue Add
= DAG
.getNode(ISD::ADD
, dl
, VT
, Op
, Shift
);
6079 Result
= DAG
.getNode(ISD::XOR
, dl
, VT
, Add
, Shift
);
6083 SDValue
TargetLowering::scalarizeVectorLoad(LoadSDNode
*LD
,
6084 SelectionDAG
&DAG
) const {
6086 SDValue Chain
= LD
->getChain();
6087 SDValue BasePTR
= LD
->getBasePtr();
6088 EVT SrcVT
= LD
->getMemoryVT();
6089 ISD::LoadExtType ExtType
= LD
->getExtensionType();
6091 unsigned NumElem
= SrcVT
.getVectorNumElements();
6093 EVT SrcEltVT
= SrcVT
.getScalarType();
6094 EVT DstEltVT
= LD
->getValueType(0).getScalarType();
6096 unsigned Stride
= SrcEltVT
.getSizeInBits() / 8;
6097 assert(SrcEltVT
.isByteSized());
6099 SmallVector
<SDValue
, 8> Vals
;
6100 SmallVector
<SDValue
, 8> LoadChains
;
6102 for (unsigned Idx
= 0; Idx
< NumElem
; ++Idx
) {
6103 SDValue ScalarLoad
=
6104 DAG
.getExtLoad(ExtType
, SL
, DstEltVT
, Chain
, BasePTR
,
6105 LD
->getPointerInfo().getWithOffset(Idx
* Stride
),
6106 SrcEltVT
, MinAlign(LD
->getAlignment(), Idx
* Stride
),
6107 LD
->getMemOperand()->getFlags(), LD
->getAAInfo());
6109 BasePTR
= DAG
.getObjectPtrOffset(SL
, BasePTR
, Stride
);
6111 Vals
.push_back(ScalarLoad
.getValue(0));
6112 LoadChains
.push_back(ScalarLoad
.getValue(1));
6115 SDValue NewChain
= DAG
.getNode(ISD::TokenFactor
, SL
, MVT::Other
, LoadChains
);
6116 SDValue Value
= DAG
.getBuildVector(LD
->getValueType(0), SL
, Vals
);
6118 return DAG
.getMergeValues({Value
, NewChain
}, SL
);
6121 SDValue
TargetLowering::scalarizeVectorStore(StoreSDNode
*ST
,
6122 SelectionDAG
&DAG
) const {
6125 SDValue Chain
= ST
->getChain();
6126 SDValue BasePtr
= ST
->getBasePtr();
6127 SDValue Value
= ST
->getValue();
6128 EVT StVT
= ST
->getMemoryVT();
6130 // The type of the data we want to save
6131 EVT RegVT
= Value
.getValueType();
6132 EVT RegSclVT
= RegVT
.getScalarType();
6134 // The type of data as saved in memory.
6135 EVT MemSclVT
= StVT
.getScalarType();
6137 EVT IdxVT
= getVectorIdxTy(DAG
.getDataLayout());
6138 unsigned NumElem
= StVT
.getVectorNumElements();
6140 // A vector must always be stored in memory as-is, i.e. without any padding
6141 // between the elements, since various code depend on it, e.g. in the
6142 // handling of a bitcast of a vector type to int, which may be done with a
6143 // vector store followed by an integer load. A vector that does not have
6144 // elements that are byte-sized must therefore be stored as an integer
6145 // built out of the extracted vector elements.
6146 if (!MemSclVT
.isByteSized()) {
6147 unsigned NumBits
= StVT
.getSizeInBits();
6148 EVT IntVT
= EVT::getIntegerVT(*DAG
.getContext(), NumBits
);
6150 SDValue CurrVal
= DAG
.getConstant(0, SL
, IntVT
);
6152 for (unsigned Idx
= 0; Idx
< NumElem
; ++Idx
) {
6153 SDValue Elt
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, SL
, RegSclVT
, Value
,
6154 DAG
.getConstant(Idx
, SL
, IdxVT
));
6155 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SL
, MemSclVT
, Elt
);
6156 SDValue ExtElt
= DAG
.getNode(ISD::ZERO_EXTEND
, SL
, IntVT
, Trunc
);
6157 unsigned ShiftIntoIdx
=
6158 (DAG
.getDataLayout().isBigEndian() ? (NumElem
- 1) - Idx
: Idx
);
6159 SDValue ShiftAmount
=
6160 DAG
.getConstant(ShiftIntoIdx
* MemSclVT
.getSizeInBits(), SL
, IntVT
);
6161 SDValue ShiftedElt
=
6162 DAG
.getNode(ISD::SHL
, SL
, IntVT
, ExtElt
, ShiftAmount
);
6163 CurrVal
= DAG
.getNode(ISD::OR
, SL
, IntVT
, CurrVal
, ShiftedElt
);
6166 return DAG
.getStore(Chain
, SL
, CurrVal
, BasePtr
, ST
->getPointerInfo(),
6167 ST
->getAlignment(), ST
->getMemOperand()->getFlags(),
6171 // Store Stride in bytes
6172 unsigned Stride
= MemSclVT
.getSizeInBits() / 8;
6173 assert(Stride
&& "Zero stride!");
6174 // Extract each of the elements from the original vector and save them into
6175 // memory individually.
6176 SmallVector
<SDValue
, 8> Stores
;
6177 for (unsigned Idx
= 0; Idx
< NumElem
; ++Idx
) {
6178 SDValue Elt
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, SL
, RegSclVT
, Value
,
6179 DAG
.getConstant(Idx
, SL
, IdxVT
));
6181 SDValue Ptr
= DAG
.getObjectPtrOffset(SL
, BasePtr
, Idx
* Stride
);
6183 // This scalar TruncStore may be illegal, but we legalize it later.
6184 SDValue Store
= DAG
.getTruncStore(
6185 Chain
, SL
, Elt
, Ptr
, ST
->getPointerInfo().getWithOffset(Idx
* Stride
),
6186 MemSclVT
, MinAlign(ST
->getAlignment(), Idx
* Stride
),
6187 ST
->getMemOperand()->getFlags(), ST
->getAAInfo());
6189 Stores
.push_back(Store
);
6192 return DAG
.getNode(ISD::TokenFactor
, SL
, MVT::Other
, Stores
);
6195 std::pair
<SDValue
, SDValue
>
6196 TargetLowering::expandUnalignedLoad(LoadSDNode
*LD
, SelectionDAG
&DAG
) const {
6197 assert(LD
->getAddressingMode() == ISD::UNINDEXED
&&
6198 "unaligned indexed loads not implemented!");
6199 SDValue Chain
= LD
->getChain();
6200 SDValue Ptr
= LD
->getBasePtr();
6201 EVT VT
= LD
->getValueType(0);
6202 EVT LoadedVT
= LD
->getMemoryVT();
6204 auto &MF
= DAG
.getMachineFunction();
6206 if (VT
.isFloatingPoint() || VT
.isVector()) {
6207 EVT intVT
= EVT::getIntegerVT(*DAG
.getContext(), LoadedVT
.getSizeInBits());
6208 if (isTypeLegal(intVT
) && isTypeLegal(LoadedVT
)) {
6209 if (!isOperationLegalOrCustom(ISD::LOAD
, intVT
) &&
6210 LoadedVT
.isVector()) {
6211 // Scalarize the load and let the individual components be handled.
6212 SDValue Scalarized
= scalarizeVectorLoad(LD
, DAG
);
6213 if (Scalarized
->getOpcode() == ISD::MERGE_VALUES
)
6214 return std::make_pair(Scalarized
.getOperand(0), Scalarized
.getOperand(1));
6215 return std::make_pair(Scalarized
.getValue(0), Scalarized
.getValue(1));
6218 // Expand to a (misaligned) integer load of the same size,
6219 // then bitconvert to floating point or vector.
6220 SDValue newLoad
= DAG
.getLoad(intVT
, dl
, Chain
, Ptr
,
6221 LD
->getMemOperand());
6222 SDValue Result
= DAG
.getNode(ISD::BITCAST
, dl
, LoadedVT
, newLoad
);
6224 Result
= DAG
.getNode(VT
.isFloatingPoint() ? ISD::FP_EXTEND
:
6225 ISD::ANY_EXTEND
, dl
, VT
, Result
);
6227 return std::make_pair(Result
, newLoad
.getValue(1));
6230 // Copy the value to a (aligned) stack slot using (unaligned) integer
6231 // loads and stores, then do a (aligned) load from the stack slot.
6232 MVT RegVT
= getRegisterType(*DAG
.getContext(), intVT
);
6233 unsigned LoadedBytes
= LoadedVT
.getStoreSize();
6234 unsigned RegBytes
= RegVT
.getSizeInBits() / 8;
6235 unsigned NumRegs
= (LoadedBytes
+ RegBytes
- 1) / RegBytes
;
6237 // Make sure the stack slot is also aligned for the register type.
6238 SDValue StackBase
= DAG
.CreateStackTemporary(LoadedVT
, RegVT
);
6239 auto FrameIndex
= cast
<FrameIndexSDNode
>(StackBase
.getNode())->getIndex();
6240 SmallVector
<SDValue
, 8> Stores
;
6241 SDValue StackPtr
= StackBase
;
6242 unsigned Offset
= 0;
6244 EVT PtrVT
= Ptr
.getValueType();
6245 EVT StackPtrVT
= StackPtr
.getValueType();
6247 SDValue PtrIncrement
= DAG
.getConstant(RegBytes
, dl
, PtrVT
);
6248 SDValue StackPtrIncrement
= DAG
.getConstant(RegBytes
, dl
, StackPtrVT
);
6250 // Do all but one copies using the full register width.
6251 for (unsigned i
= 1; i
< NumRegs
; i
++) {
6252 // Load one integer register's worth from the original location.
6253 SDValue Load
= DAG
.getLoad(
6254 RegVT
, dl
, Chain
, Ptr
, LD
->getPointerInfo().getWithOffset(Offset
),
6255 MinAlign(LD
->getAlignment(), Offset
), LD
->getMemOperand()->getFlags(),
6257 // Follow the load with a store to the stack slot. Remember the store.
6258 Stores
.push_back(DAG
.getStore(
6259 Load
.getValue(1), dl
, Load
, StackPtr
,
6260 MachinePointerInfo::getFixedStack(MF
, FrameIndex
, Offset
)));
6261 // Increment the pointers.
6264 Ptr
= DAG
.getObjectPtrOffset(dl
, Ptr
, PtrIncrement
);
6265 StackPtr
= DAG
.getObjectPtrOffset(dl
, StackPtr
, StackPtrIncrement
);
6268 // The last copy may be partial. Do an extending load.
6269 EVT MemVT
= EVT::getIntegerVT(*DAG
.getContext(),
6270 8 * (LoadedBytes
- Offset
));
6272 DAG
.getExtLoad(ISD::EXTLOAD
, dl
, RegVT
, Chain
, Ptr
,
6273 LD
->getPointerInfo().getWithOffset(Offset
), MemVT
,
6274 MinAlign(LD
->getAlignment(), Offset
),
6275 LD
->getMemOperand()->getFlags(), LD
->getAAInfo());
6276 // Follow the load with a store to the stack slot. Remember the store.
6277 // On big-endian machines this requires a truncating store to ensure
6278 // that the bits end up in the right place.
6279 Stores
.push_back(DAG
.getTruncStore(
6280 Load
.getValue(1), dl
, Load
, StackPtr
,
6281 MachinePointerInfo::getFixedStack(MF
, FrameIndex
, Offset
), MemVT
));
6283 // The order of the stores doesn't matter - say it with a TokenFactor.
6284 SDValue TF
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, Stores
);
6286 // Finally, perform the original load only redirected to the stack slot.
6287 Load
= DAG
.getExtLoad(LD
->getExtensionType(), dl
, VT
, TF
, StackBase
,
6288 MachinePointerInfo::getFixedStack(MF
, FrameIndex
, 0),
6291 // Callers expect a MERGE_VALUES node.
6292 return std::make_pair(Load
, TF
);
6295 assert(LoadedVT
.isInteger() && !LoadedVT
.isVector() &&
6296 "Unaligned load of unsupported type.");
6298 // Compute the new VT that is half the size of the old one. This is an
6300 unsigned NumBits
= LoadedVT
.getSizeInBits();
6302 NewLoadedVT
= EVT::getIntegerVT(*DAG
.getContext(), NumBits
/2);
6305 unsigned Alignment
= LD
->getAlignment();
6306 unsigned IncrementSize
= NumBits
/ 8;
6307 ISD::LoadExtType HiExtType
= LD
->getExtensionType();
6309 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
6310 if (HiExtType
== ISD::NON_EXTLOAD
)
6311 HiExtType
= ISD::ZEXTLOAD
;
6313 // Load the value in two parts
6315 if (DAG
.getDataLayout().isLittleEndian()) {
6316 Lo
= DAG
.getExtLoad(ISD::ZEXTLOAD
, dl
, VT
, Chain
, Ptr
, LD
->getPointerInfo(),
6317 NewLoadedVT
, Alignment
, LD
->getMemOperand()->getFlags(),
6320 Ptr
= DAG
.getObjectPtrOffset(dl
, Ptr
, IncrementSize
);
6321 Hi
= DAG
.getExtLoad(HiExtType
, dl
, VT
, Chain
, Ptr
,
6322 LD
->getPointerInfo().getWithOffset(IncrementSize
),
6323 NewLoadedVT
, MinAlign(Alignment
, IncrementSize
),
6324 LD
->getMemOperand()->getFlags(), LD
->getAAInfo());
6326 Hi
= DAG
.getExtLoad(HiExtType
, dl
, VT
, Chain
, Ptr
, LD
->getPointerInfo(),
6327 NewLoadedVT
, Alignment
, LD
->getMemOperand()->getFlags(),
6330 Ptr
= DAG
.getObjectPtrOffset(dl
, Ptr
, IncrementSize
);
6331 Lo
= DAG
.getExtLoad(ISD::ZEXTLOAD
, dl
, VT
, Chain
, Ptr
,
6332 LD
->getPointerInfo().getWithOffset(IncrementSize
),
6333 NewLoadedVT
, MinAlign(Alignment
, IncrementSize
),
6334 LD
->getMemOperand()->getFlags(), LD
->getAAInfo());
6337 // aggregate the two parts
6338 SDValue ShiftAmount
=
6339 DAG
.getConstant(NumBits
, dl
, getShiftAmountTy(Hi
.getValueType(),
6340 DAG
.getDataLayout()));
6341 SDValue Result
= DAG
.getNode(ISD::SHL
, dl
, VT
, Hi
, ShiftAmount
);
6342 Result
= DAG
.getNode(ISD::OR
, dl
, VT
, Result
, Lo
);
6344 SDValue TF
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, Lo
.getValue(1),
6347 return std::make_pair(Result
, TF
);
6350 SDValue
TargetLowering::expandUnalignedStore(StoreSDNode
*ST
,
6351 SelectionDAG
&DAG
) const {
6352 assert(ST
->getAddressingMode() == ISD::UNINDEXED
&&
6353 "unaligned indexed stores not implemented!");
6354 SDValue Chain
= ST
->getChain();
6355 SDValue Ptr
= ST
->getBasePtr();
6356 SDValue Val
= ST
->getValue();
6357 EVT VT
= Val
.getValueType();
6358 int Alignment
= ST
->getAlignment();
6359 auto &MF
= DAG
.getMachineFunction();
6360 EVT StoreMemVT
= ST
->getMemoryVT();
6363 if (StoreMemVT
.isFloatingPoint() || StoreMemVT
.isVector()) {
6364 EVT intVT
= EVT::getIntegerVT(*DAG
.getContext(), VT
.getSizeInBits());
6365 if (isTypeLegal(intVT
)) {
6366 if (!isOperationLegalOrCustom(ISD::STORE
, intVT
) &&
6367 StoreMemVT
.isVector()) {
6368 // Scalarize the store and let the individual components be handled.
6369 SDValue Result
= scalarizeVectorStore(ST
, DAG
);
6372 // Expand to a bitconvert of the value to the integer type of the
6373 // same size, then a (misaligned) int store.
6374 // FIXME: Does not handle truncating floating point stores!
6375 SDValue Result
= DAG
.getNode(ISD::BITCAST
, dl
, intVT
, Val
);
6376 Result
= DAG
.getStore(Chain
, dl
, Result
, Ptr
, ST
->getPointerInfo(),
6377 Alignment
, ST
->getMemOperand()->getFlags());
6380 // Do a (aligned) store to a stack slot, then copy from the stack slot
6381 // to the final destination using (unaligned) integer loads and stores.
6382 MVT RegVT
= getRegisterType(
6384 EVT::getIntegerVT(*DAG
.getContext(), StoreMemVT
.getSizeInBits()));
6385 EVT PtrVT
= Ptr
.getValueType();
6386 unsigned StoredBytes
= StoreMemVT
.getStoreSize();
6387 unsigned RegBytes
= RegVT
.getSizeInBits() / 8;
6388 unsigned NumRegs
= (StoredBytes
+ RegBytes
- 1) / RegBytes
;
6390 // Make sure the stack slot is also aligned for the register type.
6391 SDValue StackPtr
= DAG
.CreateStackTemporary(StoreMemVT
, RegVT
);
6392 auto FrameIndex
= cast
<FrameIndexSDNode
>(StackPtr
.getNode())->getIndex();
6394 // Perform the original store, only redirected to the stack slot.
6395 SDValue Store
= DAG
.getTruncStore(
6396 Chain
, dl
, Val
, StackPtr
,
6397 MachinePointerInfo::getFixedStack(MF
, FrameIndex
, 0), StoreMemVT
);
6399 EVT StackPtrVT
= StackPtr
.getValueType();
6401 SDValue PtrIncrement
= DAG
.getConstant(RegBytes
, dl
, PtrVT
);
6402 SDValue StackPtrIncrement
= DAG
.getConstant(RegBytes
, dl
, StackPtrVT
);
6403 SmallVector
<SDValue
, 8> Stores
;
6404 unsigned Offset
= 0;
6406 // Do all but one copies using the full register width.
6407 for (unsigned i
= 1; i
< NumRegs
; i
++) {
6408 // Load one integer register's worth from the stack slot.
6409 SDValue Load
= DAG
.getLoad(
6410 RegVT
, dl
, Store
, StackPtr
,
6411 MachinePointerInfo::getFixedStack(MF
, FrameIndex
, Offset
));
6412 // Store it to the final location. Remember the store.
6413 Stores
.push_back(DAG
.getStore(Load
.getValue(1), dl
, Load
, Ptr
,
6414 ST
->getPointerInfo().getWithOffset(Offset
),
6415 MinAlign(ST
->getAlignment(), Offset
),
6416 ST
->getMemOperand()->getFlags()));
6417 // Increment the pointers.
6419 StackPtr
= DAG
.getObjectPtrOffset(dl
, StackPtr
, StackPtrIncrement
);
6420 Ptr
= DAG
.getObjectPtrOffset(dl
, Ptr
, PtrIncrement
);
6423 // The last store may be partial. Do a truncating store. On big-endian
6424 // machines this requires an extending load from the stack slot to ensure
6425 // that the bits are in the right place.
6427 EVT::getIntegerVT(*DAG
.getContext(), 8 * (StoredBytes
- Offset
));
6429 // Load from the stack slot.
6430 SDValue Load
= DAG
.getExtLoad(
6431 ISD::EXTLOAD
, dl
, RegVT
, Store
, StackPtr
,
6432 MachinePointerInfo::getFixedStack(MF
, FrameIndex
, Offset
), LoadMemVT
);
6435 DAG
.getTruncStore(Load
.getValue(1), dl
, Load
, Ptr
,
6436 ST
->getPointerInfo().getWithOffset(Offset
), LoadMemVT
,
6437 MinAlign(ST
->getAlignment(), Offset
),
6438 ST
->getMemOperand()->getFlags(), ST
->getAAInfo()));
6439 // The order of the stores doesn't matter - say it with a TokenFactor.
6440 SDValue Result
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, Stores
);
6444 assert(StoreMemVT
.isInteger() && !StoreMemVT
.isVector() &&
6445 "Unaligned store of unknown type.");
6446 // Get the half-size VT
6447 EVT NewStoredVT
= StoreMemVT
.getHalfSizedIntegerVT(*DAG
.getContext());
6448 int NumBits
= NewStoredVT
.getSizeInBits();
6449 int IncrementSize
= NumBits
/ 8;
6451 // Divide the stored value in two parts.
6452 SDValue ShiftAmount
= DAG
.getConstant(
6453 NumBits
, dl
, getShiftAmountTy(Val
.getValueType(), DAG
.getDataLayout()));
6455 SDValue Hi
= DAG
.getNode(ISD::SRL
, dl
, VT
, Val
, ShiftAmount
);
6457 // Store the two parts
6458 SDValue Store1
, Store2
;
6459 Store1
= DAG
.getTruncStore(Chain
, dl
,
6460 DAG
.getDataLayout().isLittleEndian() ? Lo
: Hi
,
6461 Ptr
, ST
->getPointerInfo(), NewStoredVT
, Alignment
,
6462 ST
->getMemOperand()->getFlags());
6464 Ptr
= DAG
.getObjectPtrOffset(dl
, Ptr
, IncrementSize
);
6465 Alignment
= MinAlign(Alignment
, IncrementSize
);
6466 Store2
= DAG
.getTruncStore(
6467 Chain
, dl
, DAG
.getDataLayout().isLittleEndian() ? Hi
: Lo
, Ptr
,
6468 ST
->getPointerInfo().getWithOffset(IncrementSize
), NewStoredVT
, Alignment
,
6469 ST
->getMemOperand()->getFlags(), ST
->getAAInfo());
6472 DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, Store1
, Store2
);
6477 TargetLowering::IncrementMemoryAddress(SDValue Addr
, SDValue Mask
,
6478 const SDLoc
&DL
, EVT DataVT
,
6480 bool IsCompressedMemory
) const {
6482 EVT AddrVT
= Addr
.getValueType();
6483 EVT MaskVT
= Mask
.getValueType();
6484 assert(DataVT
.getVectorNumElements() == MaskVT
.getVectorNumElements() &&
6485 "Incompatible types of Data and Mask");
6486 if (IsCompressedMemory
) {
6487 // Incrementing the pointer according to number of '1's in the mask.
6488 EVT MaskIntVT
= EVT::getIntegerVT(*DAG
.getContext(), MaskVT
.getSizeInBits());
6489 SDValue MaskInIntReg
= DAG
.getBitcast(MaskIntVT
, Mask
);
6490 if (MaskIntVT
.getSizeInBits() < 32) {
6491 MaskInIntReg
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i32
, MaskInIntReg
);
6492 MaskIntVT
= MVT::i32
;
6495 // Count '1's with POPCNT.
6496 Increment
= DAG
.getNode(ISD::CTPOP
, DL
, MaskIntVT
, MaskInIntReg
);
6497 Increment
= DAG
.getZExtOrTrunc(Increment
, DL
, AddrVT
);
6498 // Scale is an element size in bytes.
6499 SDValue Scale
= DAG
.getConstant(DataVT
.getScalarSizeInBits() / 8, DL
,
6501 Increment
= DAG
.getNode(ISD::MUL
, DL
, AddrVT
, Increment
, Scale
);
6503 Increment
= DAG
.getConstant(DataVT
.getStoreSize(), DL
, AddrVT
);
6505 return DAG
.getNode(ISD::ADD
, DL
, AddrVT
, Addr
, Increment
);
6508 static SDValue
clampDynamicVectorIndex(SelectionDAG
&DAG
,
6512 if (isa
<ConstantSDNode
>(Idx
))
6515 EVT IdxVT
= Idx
.getValueType();
6516 unsigned NElts
= VecVT
.getVectorNumElements();
6517 if (isPowerOf2_32(NElts
)) {
6518 APInt Imm
= APInt::getLowBitsSet(IdxVT
.getSizeInBits(),
6520 return DAG
.getNode(ISD::AND
, dl
, IdxVT
, Idx
,
6521 DAG
.getConstant(Imm
, dl
, IdxVT
));
6524 return DAG
.getNode(ISD::UMIN
, dl
, IdxVT
, Idx
,
6525 DAG
.getConstant(NElts
- 1, dl
, IdxVT
));
6528 SDValue
TargetLowering::getVectorElementPointer(SelectionDAG
&DAG
,
6529 SDValue VecPtr
, EVT VecVT
,
6530 SDValue Index
) const {
6532 // Make sure the index type is big enough to compute in.
6533 Index
= DAG
.getZExtOrTrunc(Index
, dl
, VecPtr
.getValueType());
6535 EVT EltVT
= VecVT
.getVectorElementType();
6537 // Calculate the element offset and add it to the pointer.
6538 unsigned EltSize
= EltVT
.getSizeInBits() / 8; // FIXME: should be ABI size.
6539 assert(EltSize
* 8 == EltVT
.getSizeInBits() &&
6540 "Converting bits to bytes lost precision");
6542 Index
= clampDynamicVectorIndex(DAG
, Index
, VecVT
, dl
);
6544 EVT IdxVT
= Index
.getValueType();
6546 Index
= DAG
.getNode(ISD::MUL
, dl
, IdxVT
, Index
,
6547 DAG
.getConstant(EltSize
, dl
, IdxVT
));
6548 return DAG
.getNode(ISD::ADD
, dl
, IdxVT
, VecPtr
, Index
);
6551 //===----------------------------------------------------------------------===//
6552 // Implementation of Emulated TLS Model
6553 //===----------------------------------------------------------------------===//
6555 SDValue
TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode
*GA
,
6556 SelectionDAG
&DAG
) const {
6557 // Access to address of TLS varialbe xyz is lowered to a function call:
6558 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
6559 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
6560 PointerType
*VoidPtrType
= Type::getInt8PtrTy(*DAG
.getContext());
6565 std::string NameString
= ("__emutls_v." + GA
->getGlobal()->getName()).str();
6566 Module
*VariableModule
= const_cast<Module
*>(GA
->getGlobal()->getParent());
6567 StringRef
EmuTlsVarName(NameString
);
6568 GlobalVariable
*EmuTlsVar
= VariableModule
->getNamedGlobal(EmuTlsVarName
);
6569 assert(EmuTlsVar
&& "Cannot find EmuTlsVar ");
6570 Entry
.Node
= DAG
.getGlobalAddress(EmuTlsVar
, dl
, PtrVT
);
6571 Entry
.Ty
= VoidPtrType
;
6572 Args
.push_back(Entry
);
6574 SDValue EmuTlsGetAddr
= DAG
.getExternalSymbol("__emutls_get_address", PtrVT
);
6576 TargetLowering::CallLoweringInfo
CLI(DAG
);
6577 CLI
.setDebugLoc(dl
).setChain(DAG
.getEntryNode());
6578 CLI
.setLibCallee(CallingConv::C
, VoidPtrType
, EmuTlsGetAddr
, std::move(Args
));
6579 std::pair
<SDValue
, SDValue
> CallResult
= LowerCallTo(CLI
);
6581 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6582 // At last for X86 targets, maybe good for other targets too?
6583 MachineFrameInfo
&MFI
= DAG
.getMachineFunction().getFrameInfo();
6584 MFI
.setAdjustsStack(true); // Is this only for X86 target?
6585 MFI
.setHasCalls(true);
6587 assert((GA
->getOffset() == 0) &&
6588 "Emulated TLS must have zero offset in GlobalAddressSDNode");
6589 return CallResult
.first
;
6592 SDValue
TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op
,
6593 SelectionDAG
&DAG
) const {
6594 assert((Op
->getOpcode() == ISD::SETCC
) && "Input has to be a SETCC node.");
6597 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
6599 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1))) {
6600 if (C
->isNullValue() && CC
== ISD::SETEQ
) {
6601 EVT VT
= Op
.getOperand(0).getValueType();
6602 SDValue Zext
= Op
.getOperand(0);
6603 if (VT
.bitsLT(MVT::i32
)) {
6605 Zext
= DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, Op
.getOperand(0));
6607 unsigned Log2b
= Log2_32(VT
.getSizeInBits());
6608 SDValue Clz
= DAG
.getNode(ISD::CTLZ
, dl
, VT
, Zext
);
6609 SDValue Scc
= DAG
.getNode(ISD::SRL
, dl
, VT
, Clz
,
6610 DAG
.getConstant(Log2b
, dl
, MVT::i32
));
6611 return DAG
.getNode(ISD::TRUNCATE
, dl
, MVT::i32
, Scc
);
6617 SDValue
TargetLowering::expandAddSubSat(SDNode
*Node
, SelectionDAG
&DAG
) const {
6618 unsigned Opcode
= Node
->getOpcode();
6619 SDValue LHS
= Node
->getOperand(0);
6620 SDValue RHS
= Node
->getOperand(1);
6621 EVT VT
= LHS
.getValueType();
6624 assert(VT
== RHS
.getValueType() && "Expected operands to be the same type");
6625 assert(VT
.isInteger() && "Expected operands to be integers");
6627 // usub.sat(a, b) -> umax(a, b) - b
6628 if (Opcode
== ISD::USUBSAT
&& isOperationLegalOrCustom(ISD::UMAX
, VT
)) {
6629 SDValue Max
= DAG
.getNode(ISD::UMAX
, dl
, VT
, LHS
, RHS
);
6630 return DAG
.getNode(ISD::SUB
, dl
, VT
, Max
, RHS
);
6633 if (Opcode
== ISD::UADDSAT
&& isOperationLegalOrCustom(ISD::UMIN
, VT
)) {
6634 SDValue InvRHS
= DAG
.getNOT(dl
, RHS
, VT
);
6635 SDValue Min
= DAG
.getNode(ISD::UMIN
, dl
, VT
, LHS
, InvRHS
);
6636 return DAG
.getNode(ISD::ADD
, dl
, VT
, Min
, RHS
);
6639 unsigned OverflowOp
;
6642 OverflowOp
= ISD::SADDO
;
6645 OverflowOp
= ISD::UADDO
;
6648 OverflowOp
= ISD::SSUBO
;
6651 OverflowOp
= ISD::USUBO
;
6654 llvm_unreachable("Expected method to receive signed or unsigned saturation "
6655 "addition or subtraction node.");
6658 unsigned BitWidth
= LHS
.getScalarValueSizeInBits();
6659 EVT BoolVT
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
6660 SDValue Result
= DAG
.getNode(OverflowOp
, dl
, DAG
.getVTList(VT
, BoolVT
),
6662 SDValue SumDiff
= Result
.getValue(0);
6663 SDValue Overflow
= Result
.getValue(1);
6664 SDValue Zero
= DAG
.getConstant(0, dl
, VT
);
6665 SDValue AllOnes
= DAG
.getAllOnesConstant(dl
, VT
);
6667 if (Opcode
== ISD::UADDSAT
) {
6668 if (getBooleanContents(VT
) == ZeroOrNegativeOneBooleanContent
) {
6669 // (LHS + RHS) | OverflowMask
6670 SDValue OverflowMask
= DAG
.getSExtOrTrunc(Overflow
, dl
, VT
);
6671 return DAG
.getNode(ISD::OR
, dl
, VT
, SumDiff
, OverflowMask
);
6673 // Overflow ? 0xffff.... : (LHS + RHS)
6674 return DAG
.getSelect(dl
, VT
, Overflow
, AllOnes
, SumDiff
);
6675 } else if (Opcode
== ISD::USUBSAT
) {
6676 if (getBooleanContents(VT
) == ZeroOrNegativeOneBooleanContent
) {
6677 // (LHS - RHS) & ~OverflowMask
6678 SDValue OverflowMask
= DAG
.getSExtOrTrunc(Overflow
, dl
, VT
);
6679 SDValue Not
= DAG
.getNOT(dl
, OverflowMask
, VT
);
6680 return DAG
.getNode(ISD::AND
, dl
, VT
, SumDiff
, Not
);
6682 // Overflow ? 0 : (LHS - RHS)
6683 return DAG
.getSelect(dl
, VT
, Overflow
, Zero
, SumDiff
);
6685 // SatMax -> Overflow && SumDiff < 0
6686 // SatMin -> Overflow && SumDiff >= 0
6687 APInt MinVal
= APInt::getSignedMinValue(BitWidth
);
6688 APInt MaxVal
= APInt::getSignedMaxValue(BitWidth
);
6689 SDValue SatMin
= DAG
.getConstant(MinVal
, dl
, VT
);
6690 SDValue SatMax
= DAG
.getConstant(MaxVal
, dl
, VT
);
6691 SDValue SumNeg
= DAG
.getSetCC(dl
, BoolVT
, SumDiff
, Zero
, ISD::SETLT
);
6692 Result
= DAG
.getSelect(dl
, VT
, SumNeg
, SatMax
, SatMin
);
6693 return DAG
.getSelect(dl
, VT
, Overflow
, Result
, SumDiff
);
6698 TargetLowering::expandFixedPointMul(SDNode
*Node
, SelectionDAG
&DAG
) const {
6699 assert((Node
->getOpcode() == ISD::SMULFIX
||
6700 Node
->getOpcode() == ISD::UMULFIX
||
6701 Node
->getOpcode() == ISD::SMULFIXSAT
) &&
6702 "Expected a fixed point multiplication opcode");
6705 SDValue LHS
= Node
->getOperand(0);
6706 SDValue RHS
= Node
->getOperand(1);
6707 EVT VT
= LHS
.getValueType();
6708 unsigned Scale
= Node
->getConstantOperandVal(2);
6709 bool Saturating
= Node
->getOpcode() == ISD::SMULFIXSAT
;
6710 EVT BoolVT
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
6711 unsigned VTSize
= VT
.getScalarSizeInBits();
6714 // [us]mul.fix(a, b, 0) -> mul(a, b)
6715 if (!Saturating
&& isOperationLegalOrCustom(ISD::MUL
, VT
)) {
6716 return DAG
.getNode(ISD::MUL
, dl
, VT
, LHS
, RHS
);
6717 } else if (Saturating
&& isOperationLegalOrCustom(ISD::SMULO
, VT
)) {
6719 DAG
.getNode(ISD::SMULO
, dl
, DAG
.getVTList(VT
, BoolVT
), LHS
, RHS
);
6720 SDValue Product
= Result
.getValue(0);
6721 SDValue Overflow
= Result
.getValue(1);
6722 SDValue Zero
= DAG
.getConstant(0, dl
, VT
);
6724 APInt MinVal
= APInt::getSignedMinValue(VTSize
);
6725 APInt MaxVal
= APInt::getSignedMaxValue(VTSize
);
6726 SDValue SatMin
= DAG
.getConstant(MinVal
, dl
, VT
);
6727 SDValue SatMax
= DAG
.getConstant(MaxVal
, dl
, VT
);
6728 SDValue ProdNeg
= DAG
.getSetCC(dl
, BoolVT
, Product
, Zero
, ISD::SETLT
);
6729 Result
= DAG
.getSelect(dl
, VT
, ProdNeg
, SatMax
, SatMin
);
6730 return DAG
.getSelect(dl
, VT
, Overflow
, Result
, Product
);
6735 Node
->getOpcode() == ISD::SMULFIX
|| Node
->getOpcode() == ISD::SMULFIXSAT
;
6736 assert(((Signed
&& Scale
< VTSize
) || (!Signed
&& Scale
<= VTSize
)) &&
6737 "Expected scale to be less than the number of bits if signed or at "
6738 "most the number of bits if unsigned.");
6739 assert(LHS
.getValueType() == RHS
.getValueType() &&
6740 "Expected both operands to be the same type");
6742 // Get the upper and lower bits of the result.
6744 unsigned LoHiOp
= Signed
? ISD::SMUL_LOHI
: ISD::UMUL_LOHI
;
6745 unsigned HiOp
= Signed
? ISD::MULHS
: ISD::MULHU
;
6746 if (isOperationLegalOrCustom(LoHiOp
, VT
)) {
6747 SDValue Result
= DAG
.getNode(LoHiOp
, dl
, DAG
.getVTList(VT
, VT
), LHS
, RHS
);
6748 Lo
= Result
.getValue(0);
6749 Hi
= Result
.getValue(1);
6750 } else if (isOperationLegalOrCustom(HiOp
, VT
)) {
6751 Lo
= DAG
.getNode(ISD::MUL
, dl
, VT
, LHS
, RHS
);
6752 Hi
= DAG
.getNode(HiOp
, dl
, VT
, LHS
, RHS
);
6753 } else if (VT
.isVector()) {
6756 report_fatal_error("Unable to expand fixed point multiplication.");
6759 if (Scale
== VTSize
)
6760 // Result is just the top half since we'd be shifting by the width of the
6764 // The result will need to be shifted right by the scale since both operands
6765 // are scaled. The result is given to us in 2 halves, so we only want part of
6766 // both in the result.
6767 EVT ShiftTy
= getShiftAmountTy(VT
, DAG
.getDataLayout());
6768 SDValue Result
= DAG
.getNode(ISD::FSHR
, dl
, VT
, Hi
, Lo
,
6769 DAG
.getConstant(Scale
, dl
, ShiftTy
));
6773 unsigned OverflowBits
= VTSize
- Scale
+ 1; // +1 for the sign
6775 DAG
.getConstant(APInt::getHighBitsSet(VTSize
, OverflowBits
), dl
, VT
);
6776 SDValue LoMask
= DAG
.getConstant(
6777 APInt::getLowBitsSet(VTSize
, VTSize
- OverflowBits
), dl
, VT
);
6778 APInt MaxVal
= APInt::getSignedMaxValue(VTSize
);
6779 APInt MinVal
= APInt::getSignedMinValue(VTSize
);
6781 Result
= DAG
.getSelectCC(dl
, Hi
, LoMask
,
6782 DAG
.getConstant(MaxVal
, dl
, VT
), Result
,
6784 return DAG
.getSelectCC(dl
, Hi
, HiMask
,
6785 DAG
.getConstant(MinVal
, dl
, VT
), Result
,
6789 void TargetLowering::expandUADDSUBO(
6790 SDNode
*Node
, SDValue
&Result
, SDValue
&Overflow
, SelectionDAG
&DAG
) const {
6792 SDValue LHS
= Node
->getOperand(0);
6793 SDValue RHS
= Node
->getOperand(1);
6794 bool IsAdd
= Node
->getOpcode() == ISD::UADDO
;
6796 // If ADD/SUBCARRY is legal, use that instead.
6797 unsigned OpcCarry
= IsAdd
? ISD::ADDCARRY
: ISD::SUBCARRY
;
6798 if (isOperationLegalOrCustom(OpcCarry
, Node
->getValueType(0))) {
6799 SDValue CarryIn
= DAG
.getConstant(0, dl
, Node
->getValueType(1));
6800 SDValue NodeCarry
= DAG
.getNode(OpcCarry
, dl
, Node
->getVTList(),
6801 { LHS
, RHS
, CarryIn
});
6802 Result
= SDValue(NodeCarry
.getNode(), 0);
6803 Overflow
= SDValue(NodeCarry
.getNode(), 1);
6807 Result
= DAG
.getNode(IsAdd
? ISD::ADD
: ISD::SUB
, dl
,
6808 LHS
.getValueType(), LHS
, RHS
);
6810 EVT ResultType
= Node
->getValueType(1);
6811 EVT SetCCType
= getSetCCResultType(
6812 DAG
.getDataLayout(), *DAG
.getContext(), Node
->getValueType(0));
6813 ISD::CondCode CC
= IsAdd
? ISD::SETULT
: ISD::SETUGT
;
6814 SDValue SetCC
= DAG
.getSetCC(dl
, SetCCType
, Result
, LHS
, CC
);
6815 Overflow
= DAG
.getBoolExtOrTrunc(SetCC
, dl
, ResultType
, ResultType
);
6818 void TargetLowering::expandSADDSUBO(
6819 SDNode
*Node
, SDValue
&Result
, SDValue
&Overflow
, SelectionDAG
&DAG
) const {
6821 SDValue LHS
= Node
->getOperand(0);
6822 SDValue RHS
= Node
->getOperand(1);
6823 bool IsAdd
= Node
->getOpcode() == ISD::SADDO
;
6825 Result
= DAG
.getNode(IsAdd
? ISD::ADD
: ISD::SUB
, dl
,
6826 LHS
.getValueType(), LHS
, RHS
);
6828 EVT ResultType
= Node
->getValueType(1);
6829 EVT OType
= getSetCCResultType(
6830 DAG
.getDataLayout(), *DAG
.getContext(), Node
->getValueType(0));
6832 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
6833 unsigned OpcSat
= IsAdd
? ISD::SADDSAT
: ISD::SSUBSAT
;
6834 if (isOperationLegalOrCustom(OpcSat
, LHS
.getValueType())) {
6835 SDValue Sat
= DAG
.getNode(OpcSat
, dl
, LHS
.getValueType(), LHS
, RHS
);
6836 SDValue SetCC
= DAG
.getSetCC(dl
, OType
, Result
, Sat
, ISD::SETNE
);
6837 Overflow
= DAG
.getBoolExtOrTrunc(SetCC
, dl
, ResultType
, ResultType
);
6841 SDValue Zero
= DAG
.getConstant(0, dl
, LHS
.getValueType());
6843 // LHSSign -> LHS >= 0
6844 // RHSSign -> RHS >= 0
6845 // SumSign -> Result >= 0
6848 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
6850 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
6851 SDValue LHSSign
= DAG
.getSetCC(dl
, OType
, LHS
, Zero
, ISD::SETGE
);
6852 SDValue RHSSign
= DAG
.getSetCC(dl
, OType
, RHS
, Zero
, ISD::SETGE
);
6853 SDValue SignsMatch
= DAG
.getSetCC(dl
, OType
, LHSSign
, RHSSign
,
6854 IsAdd
? ISD::SETEQ
: ISD::SETNE
);
6856 SDValue SumSign
= DAG
.getSetCC(dl
, OType
, Result
, Zero
, ISD::SETGE
);
6857 SDValue SumSignNE
= DAG
.getSetCC(dl
, OType
, LHSSign
, SumSign
, ISD::SETNE
);
6859 SDValue Cmp
= DAG
.getNode(ISD::AND
, dl
, OType
, SignsMatch
, SumSignNE
);
6860 Overflow
= DAG
.getBoolExtOrTrunc(Cmp
, dl
, ResultType
, ResultType
);
6863 bool TargetLowering::expandMULO(SDNode
*Node
, SDValue
&Result
,
6864 SDValue
&Overflow
, SelectionDAG
&DAG
) const {
6866 EVT VT
= Node
->getValueType(0);
6867 EVT SetCCVT
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
6868 SDValue LHS
= Node
->getOperand(0);
6869 SDValue RHS
= Node
->getOperand(1);
6870 bool isSigned
= Node
->getOpcode() == ISD::SMULO
;
6872 // For power-of-two multiplications we can use a simpler shift expansion.
6873 if (ConstantSDNode
*RHSC
= isConstOrConstSplat(RHS
)) {
6874 const APInt
&C
= RHSC
->getAPIntValue();
6875 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
6876 if (C
.isPowerOf2()) {
6877 // smulo(x, signed_min) is same as umulo(x, signed_min).
6878 bool UseArithShift
= isSigned
&& !C
.isMinSignedValue();
6879 EVT ShiftAmtTy
= getShiftAmountTy(VT
, DAG
.getDataLayout());
6880 SDValue ShiftAmt
= DAG
.getConstant(C
.logBase2(), dl
, ShiftAmtTy
);
6881 Result
= DAG
.getNode(ISD::SHL
, dl
, VT
, LHS
, ShiftAmt
);
6882 Overflow
= DAG
.getSetCC(dl
, SetCCVT
,
6883 DAG
.getNode(UseArithShift
? ISD::SRA
: ISD::SRL
,
6884 dl
, VT
, Result
, ShiftAmt
),
6890 EVT WideVT
= EVT::getIntegerVT(*DAG
.getContext(), VT
.getScalarSizeInBits() * 2);
6892 WideVT
= EVT::getVectorVT(*DAG
.getContext(), WideVT
,
6893 VT
.getVectorNumElements());
6897 static const unsigned Ops
[2][3] =
6898 { { ISD::MULHU
, ISD::UMUL_LOHI
, ISD::ZERO_EXTEND
},
6899 { ISD::MULHS
, ISD::SMUL_LOHI
, ISD::SIGN_EXTEND
}};
6900 if (isOperationLegalOrCustom(Ops
[isSigned
][0], VT
)) {
6901 BottomHalf
= DAG
.getNode(ISD::MUL
, dl
, VT
, LHS
, RHS
);
6902 TopHalf
= DAG
.getNode(Ops
[isSigned
][0], dl
, VT
, LHS
, RHS
);
6903 } else if (isOperationLegalOrCustom(Ops
[isSigned
][1], VT
)) {
6904 BottomHalf
= DAG
.getNode(Ops
[isSigned
][1], dl
, DAG
.getVTList(VT
, VT
), LHS
,
6906 TopHalf
= BottomHalf
.getValue(1);
6907 } else if (isTypeLegal(WideVT
)) {
6908 LHS
= DAG
.getNode(Ops
[isSigned
][2], dl
, WideVT
, LHS
);
6909 RHS
= DAG
.getNode(Ops
[isSigned
][2], dl
, WideVT
, RHS
);
6910 SDValue Mul
= DAG
.getNode(ISD::MUL
, dl
, WideVT
, LHS
, RHS
);
6911 BottomHalf
= DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, Mul
);
6912 SDValue ShiftAmt
= DAG
.getConstant(VT
.getScalarSizeInBits(), dl
,
6913 getShiftAmountTy(WideVT
, DAG
.getDataLayout()));
6914 TopHalf
= DAG
.getNode(ISD::TRUNCATE
, dl
, VT
,
6915 DAG
.getNode(ISD::SRL
, dl
, WideVT
, Mul
, ShiftAmt
));
6920 // We can fall back to a libcall with an illegal type for the MUL if we
6921 // have a libcall big enough.
6922 // Also, we can fall back to a division in some cases, but that's a big
6923 // performance hit in the general case.
6924 RTLIB::Libcall LC
= RTLIB::UNKNOWN_LIBCALL
;
6925 if (WideVT
== MVT::i16
)
6926 LC
= RTLIB::MUL_I16
;
6927 else if (WideVT
== MVT::i32
)
6928 LC
= RTLIB::MUL_I32
;
6929 else if (WideVT
== MVT::i64
)
6930 LC
= RTLIB::MUL_I64
;
6931 else if (WideVT
== MVT::i128
)
6932 LC
= RTLIB::MUL_I128
;
6933 assert(LC
!= RTLIB::UNKNOWN_LIBCALL
&& "Cannot expand this operation!");
6938 // The high part is obtained by SRA'ing all but one of the bits of low
6940 unsigned LoSize
= VT
.getSizeInBits();
6942 DAG
.getNode(ISD::SRA
, dl
, VT
, LHS
,
6943 DAG
.getConstant(LoSize
- 1, dl
,
6944 getPointerTy(DAG
.getDataLayout())));
6946 DAG
.getNode(ISD::SRA
, dl
, VT
, RHS
,
6947 DAG
.getConstant(LoSize
- 1, dl
,
6948 getPointerTy(DAG
.getDataLayout())));
6950 HiLHS
= DAG
.getConstant(0, dl
, VT
);
6951 HiRHS
= DAG
.getConstant(0, dl
, VT
);
6954 // Here we're passing the 2 arguments explicitly as 4 arguments that are
6955 // pre-lowered to the correct types. This all depends upon WideVT not
6956 // being a legal type for the architecture and thus has to be split to
6959 TargetLowering::MakeLibCallOptions CallOptions
;
6960 CallOptions
.setSExt(isSigned
);
6961 CallOptions
.setIsPostTypeLegalization(true);
6962 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG
.getDataLayout())) {
6963 // Halves of WideVT are packed into registers in different order
6964 // depending on platform endianness. This is usually handled by
6965 // the C calling convention, but we can't defer to it in
6967 SDValue Args
[] = { LHS
, HiLHS
, RHS
, HiRHS
};
6968 Ret
= makeLibCall(DAG
, LC
, WideVT
, Args
, CallOptions
, dl
).first
;
6970 SDValue Args
[] = { HiLHS
, LHS
, HiRHS
, RHS
};
6971 Ret
= makeLibCall(DAG
, LC
, WideVT
, Args
, CallOptions
, dl
).first
;
6973 assert(Ret
.getOpcode() == ISD::MERGE_VALUES
&&
6974 "Ret value is a collection of constituent nodes holding result.");
6975 if (DAG
.getDataLayout().isLittleEndian()) {
6977 BottomHalf
= Ret
.getOperand(0);
6978 TopHalf
= Ret
.getOperand(1);
6980 BottomHalf
= Ret
.getOperand(1);
6981 TopHalf
= Ret
.getOperand(0);
6985 Result
= BottomHalf
;
6987 SDValue ShiftAmt
= DAG
.getConstant(
6988 VT
.getScalarSizeInBits() - 1, dl
,
6989 getShiftAmountTy(BottomHalf
.getValueType(), DAG
.getDataLayout()));
6990 SDValue Sign
= DAG
.getNode(ISD::SRA
, dl
, VT
, BottomHalf
, ShiftAmt
);
6991 Overflow
= DAG
.getSetCC(dl
, SetCCVT
, TopHalf
, Sign
, ISD::SETNE
);
6993 Overflow
= DAG
.getSetCC(dl
, SetCCVT
, TopHalf
,
6994 DAG
.getConstant(0, dl
, VT
), ISD::SETNE
);
6997 // Truncate the result if SetCC returns a larger type than needed.
6998 EVT RType
= Node
->getValueType(1);
6999 if (RType
.getSizeInBits() < Overflow
.getValueSizeInBits())
7000 Overflow
= DAG
.getNode(ISD::TRUNCATE
, dl
, RType
, Overflow
);
7002 assert(RType
.getSizeInBits() == Overflow
.getValueSizeInBits() &&
7003 "Unexpected result type for S/UMULO legalization");
7007 SDValue
TargetLowering::expandVecReduce(SDNode
*Node
, SelectionDAG
&DAG
) const {
7009 bool NoNaN
= Node
->getFlags().hasNoNaNs();
7010 unsigned BaseOpcode
= 0;
7011 switch (Node
->getOpcode()) {
7012 default: llvm_unreachable("Expected VECREDUCE opcode");
7013 case ISD::VECREDUCE_FADD
: BaseOpcode
= ISD::FADD
; break;
7014 case ISD::VECREDUCE_FMUL
: BaseOpcode
= ISD::FMUL
; break;
7015 case ISD::VECREDUCE_ADD
: BaseOpcode
= ISD::ADD
; break;
7016 case ISD::VECREDUCE_MUL
: BaseOpcode
= ISD::MUL
; break;
7017 case ISD::VECREDUCE_AND
: BaseOpcode
= ISD::AND
; break;
7018 case ISD::VECREDUCE_OR
: BaseOpcode
= ISD::OR
; break;
7019 case ISD::VECREDUCE_XOR
: BaseOpcode
= ISD::XOR
; break;
7020 case ISD::VECREDUCE_SMAX
: BaseOpcode
= ISD::SMAX
; break;
7021 case ISD::VECREDUCE_SMIN
: BaseOpcode
= ISD::SMIN
; break;
7022 case ISD::VECREDUCE_UMAX
: BaseOpcode
= ISD::UMAX
; break;
7023 case ISD::VECREDUCE_UMIN
: BaseOpcode
= ISD::UMIN
; break;
7024 case ISD::VECREDUCE_FMAX
:
7025 BaseOpcode
= NoNaN
? ISD::FMAXNUM
: ISD::FMAXIMUM
;
7027 case ISD::VECREDUCE_FMIN
:
7028 BaseOpcode
= NoNaN
? ISD::FMINNUM
: ISD::FMINIMUM
;
7032 SDValue Op
= Node
->getOperand(0);
7033 EVT VT
= Op
.getValueType();
7035 // Try to use a shuffle reduction for power of two vectors.
7036 if (VT
.isPow2VectorType()) {
7037 while (VT
.getVectorNumElements() > 1) {
7038 EVT HalfVT
= VT
.getHalfNumVectorElementsVT(*DAG
.getContext());
7039 if (!isOperationLegalOrCustom(BaseOpcode
, HalfVT
))
7043 std::tie(Lo
, Hi
) = DAG
.SplitVector(Op
, dl
);
7044 Op
= DAG
.getNode(BaseOpcode
, dl
, HalfVT
, Lo
, Hi
);
7049 EVT EltVT
= VT
.getVectorElementType();
7050 unsigned NumElts
= VT
.getVectorNumElements();
7052 SmallVector
<SDValue
, 8> Ops
;
7053 DAG
.ExtractVectorElements(Op
, Ops
, 0, NumElts
);
7055 SDValue Res
= Ops
[0];
7056 for (unsigned i
= 1; i
< NumElts
; i
++)
7057 Res
= DAG
.getNode(BaseOpcode
, dl
, EltVT
, Res
, Ops
[i
], Node
->getFlags());
7059 // Result type may be wider than element type.
7060 if (EltVT
!= Node
->getValueType(0))
7061 Res
= DAG
.getNode(ISD::ANY_EXTEND
, dl
, Node
->getValueType(0), Res
);