LLVM 23.0.0git
TargetLowering.cpp
Go to the documentation of this file.
1//===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements the TargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/STLExtras.h"
27#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/MC/MCAsmInfo.h"
32#include "llvm/MC/MCExpr.h"
38#include <cctype>
39#include <deque>
40using namespace llvm;
41using namespace llvm::SDPatternMatch;
42
43/// NOTE: The TargetMachine owns TLOF.
47
48// Define the virtual destructor out-of-line for build efficiency.
50
51const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
52 return nullptr;
53}
54
58
59/// Check whether a given call node is in tail position within its function. If
60/// so, it sets Chain to the input chain of the tail call.
62 SDValue &Chain) const {
64
65 // First, check if tail calls have been disabled in this function.
66 if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
67 return false;
68
69 // Conservatively require the attributes of the call to match those of
70 // the return. Ignore following attributes because they don't affect the
71 // call sequence.
72 AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs());
73 for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
74 Attribute::DereferenceableOrNull, Attribute::NoAlias,
75 Attribute::NonNull, Attribute::NoUndef,
76 Attribute::Range, Attribute::NoFPClass})
77 CallerAttrs.removeAttribute(Attr);
78
79 if (CallerAttrs.hasAttributes())
80 return false;
81
82 // It's not safe to eliminate the sign / zero extension of the return value.
83 if (CallerAttrs.contains(Attribute::ZExt) ||
84 CallerAttrs.contains(Attribute::SExt))
85 return false;
86
87 // Check if the only use is a function return node.
88 return isUsedByReturnOnly(Node, Chain);
89}
90
92 const uint32_t *CallerPreservedMask,
93 const SmallVectorImpl<CCValAssign> &ArgLocs,
94 const SmallVectorImpl<SDValue> &OutVals) const {
95 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
96 const CCValAssign &ArgLoc = ArgLocs[I];
97 if (!ArgLoc.isRegLoc())
98 continue;
99 MCRegister Reg = ArgLoc.getLocReg();
100 // Only look at callee saved registers.
101 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
102 continue;
103 // Check that we pass the value used for the caller.
104 // (We look for a CopyFromReg reading a virtual register that is used
105 // for the function live-in value of register Reg)
106 SDValue Value = OutVals[I];
107 if (Value->getOpcode() == ISD::AssertZext)
108 Value = Value.getOperand(0);
109 if (Value->getOpcode() != ISD::CopyFromReg)
110 return false;
111 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
112 if (MRI.getLiveInPhysReg(ArgReg) != Reg)
113 return false;
114 }
115 return true;
116}
117
118/// Set CallLoweringInfo attribute flags based on a call instruction
119/// and called function attributes.
121 unsigned ArgIdx) {
122 IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt);
123 IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt);
124 IsNoExt = Call->paramHasAttr(ArgIdx, Attribute::NoExt);
125 IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg);
126 IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet);
127 IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest);
128 IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal);
129 IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated);
130 IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca);
131 IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned);
132 IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
133 IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync);
134 IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError);
135 Alignment = Call->getParamStackAlign(ArgIdx);
136 IndirectType = nullptr;
138 "multiple ABI attributes?");
139 if (IsByVal) {
140 IndirectType = Call->getParamByValType(ArgIdx);
141 if (!Alignment)
142 Alignment = Call->getParamAlign(ArgIdx);
143 }
144 if (IsPreallocated)
145 IndirectType = Call->getParamPreallocatedType(ArgIdx);
146 if (IsInAlloca)
147 IndirectType = Call->getParamInAllocaType(ArgIdx);
148 if (IsSRet)
149 IndirectType = Call->getParamStructRetType(ArgIdx);
150}
151
152/// Generate a libcall taking the given operands as arguments and returning a
153/// result of type RetVT.
154std::pair<SDValue, SDValue>
155TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl,
157 MakeLibCallOptions CallOptions, const SDLoc &dl,
158 SDValue InChain) const {
159 if (LibcallImpl == RTLIB::Unsupported)
160 reportFatalInternalError("unsupported library call operation");
161
162 if (!InChain)
163 InChain = DAG.getEntryNode();
164
166 Args.reserve(Ops.size());
167
168 ArrayRef<Type *> OpsTypeOverrides = CallOptions.OpsTypeOverrides;
169 for (unsigned i = 0; i < Ops.size(); ++i) {
170 SDValue NewOp = Ops[i];
171 Type *Ty = i < OpsTypeOverrides.size() && OpsTypeOverrides[i]
172 ? OpsTypeOverrides[i]
173 : NewOp.getValueType().getTypeForEVT(*DAG.getContext());
174 TargetLowering::ArgListEntry Entry(NewOp, Ty);
175 if (CallOptions.IsSoften)
176 Entry.OrigTy =
177 CallOptions.OpsVTBeforeSoften[i].getTypeForEVT(*DAG.getContext());
178
179 Entry.IsSExt =
180 shouldSignExtendTypeInLibCall(Entry.Ty, CallOptions.IsSigned);
181 Entry.IsZExt = !Entry.IsSExt;
182
183 if (CallOptions.IsSoften &&
185 Entry.IsSExt = Entry.IsZExt = false;
186 }
187 Args.push_back(Entry);
188 }
189
190 SDValue Callee =
191 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
192
193 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
194 Type *OrigRetTy = RetTy;
196 bool signExtend = shouldSignExtendTypeInLibCall(RetTy, CallOptions.IsSigned);
197 bool zeroExtend = !signExtend;
198
199 if (CallOptions.IsSoften) {
200 OrigRetTy = CallOptions.RetVTBeforeSoften.getTypeForEVT(*DAG.getContext());
202 signExtend = zeroExtend = false;
203 }
204
205 CLI.setDebugLoc(dl)
206 .setChain(InChain)
207 .setLibCallee(getLibcallImplCallingConv(LibcallImpl), RetTy, OrigRetTy,
208 Callee, std::move(Args))
209 .setNoReturn(CallOptions.DoesNotReturn)
212 .setSExtResult(signExtend)
213 .setZExtResult(zeroExtend);
214 return LowerCallTo(CLI);
215}
216
218 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
219 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
220 const AttributeList &FuncAttributes, EVT *LargestVT) const {
221 EVT VT = getOptimalMemOpType(Context, Op, FuncAttributes);
222
223 if (VT == MVT::Other) {
224 // Use the largest integer type whose alignment constraints are satisfied.
225 VT = MVT::LAST_INTEGER_VALUETYPE;
226 if (Op.isFixedDstAlign()) {
227 bool LoadsFromSrc = Op.isMemcpy() && !Op.isMemcpyStrSrc();
228 while (VT != MVT::i8) {
229 unsigned VTSize = VT.getSizeInBits() / 8;
230 bool DstOk =
231 Op.getDstAlign() >= VTSize ||
232 allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign());
233 bool SrcOk =
234 !LoadsFromSrc || Op.getSrcAlign() >= VTSize ||
235 allowsMisalignedMemoryAccesses(VT, SrcAS, Op.getSrcAlign());
236 if (DstOk && SrcOk)
237 break;
239 }
240 }
241 assert(VT.isInteger());
242
243 // Find the largest legal integer type.
244 MVT LVT = MVT::LAST_INTEGER_VALUETYPE;
245 while (!isTypeLegal(LVT))
246 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
247 assert(LVT.isInteger());
248
249 // If the type we've chosen is larger than the largest legal integer type
250 // then use the largest legal type.
251 if (VT.bitsGT(LVT))
252 VT = LVT;
253 }
254
255 unsigned NumMemOps = 0;
256 uint64_t Size = Op.size();
257 while (Size) {
258 unsigned VTSize = VT.getSizeInBits() / 8;
259 while (VTSize > Size) {
260 // For now, only use non-vector load / store's for the left-over pieces.
261 EVT NewVT = VT;
262 unsigned NewVTSize;
263
264 bool Found = false;
265 if (VT.isVector() || VT.isFloatingPoint()) {
266 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
269 Found = true;
270 else if (NewVT == MVT::i64 &&
272 isSafeMemOpType(MVT::f64)) {
273 // i64 is usually not legal on 32-bit targets, but f64 may be.
274 NewVT = MVT::f64;
275 Found = true;
276 }
277 }
278
279 if (!Found) {
280 do {
281 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
282 if (NewVT == MVT::i8)
283 break;
284 } while (!isSafeMemOpType(NewVT.getSimpleVT()));
285 }
286 NewVTSize = NewVT.getSizeInBits() / 8;
287
288 // If the new VT cannot cover all of the remaining bits, then consider
289 // issuing a (or a pair of) unaligned and overlapping load / store.
290 unsigned Fast;
291 if (NumMemOps && Op.allowOverlap() && NewVTSize < Size &&
293 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
295 Fast)
296 VTSize = Size;
297 else {
298 VT = NewVT;
299 VTSize = NewVTSize;
300 }
301 }
302
303 if (++NumMemOps > Limit)
304 return false;
305
306 MemOps.push_back(VT);
307 Size -= VTSize;
308 }
309
310 return true;
311}
312
313/// Soften the operands of a comparison. This code is shared among BR_CC,
314/// SELECT_CC, and SETCC handlers.
316 SDValue &NewLHS, SDValue &NewRHS,
317 ISD::CondCode &CCCode,
318 const SDLoc &dl, const SDValue OldLHS,
319 const SDValue OldRHS) const {
320 SDValue Chain;
321 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
322 OldRHS, Chain);
323}
324
326 SDValue &NewLHS, SDValue &NewRHS,
327 ISD::CondCode &CCCode,
328 const SDLoc &dl, const SDValue OldLHS,
329 const SDValue OldRHS,
330 SDValue &Chain,
331 bool IsSignaling) const {
332 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
333 // not supporting it. We can update this code when libgcc provides such
334 // functions.
335
336 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
337 && "Unsupported setcc type!");
338
339 // Expand into one or more soft-fp libcall(s).
340 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
341 bool ShouldInvertCC = false;
342 switch (CCCode) {
343 case ISD::SETEQ:
344 case ISD::SETOEQ:
345 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
346 (VT == MVT::f64) ? RTLIB::OEQ_F64 :
347 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
348 break;
349 case ISD::SETNE:
350 case ISD::SETUNE:
351 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
352 (VT == MVT::f64) ? RTLIB::UNE_F64 :
353 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
354 break;
355 case ISD::SETGE:
356 case ISD::SETOGE:
357 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
358 (VT == MVT::f64) ? RTLIB::OGE_F64 :
359 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
360 break;
361 case ISD::SETLT:
362 case ISD::SETOLT:
363 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
364 (VT == MVT::f64) ? RTLIB::OLT_F64 :
365 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
366 break;
367 case ISD::SETLE:
368 case ISD::SETOLE:
369 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
370 (VT == MVT::f64) ? RTLIB::OLE_F64 :
371 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
372 break;
373 case ISD::SETGT:
374 case ISD::SETOGT:
375 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
376 (VT == MVT::f64) ? RTLIB::OGT_F64 :
377 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
378 break;
379 case ISD::SETO:
380 ShouldInvertCC = true;
381 [[fallthrough]];
382 case ISD::SETUO:
383 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
384 (VT == MVT::f64) ? RTLIB::UO_F64 :
385 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
386 break;
387 case ISD::SETONE:
388 // SETONE = O && UNE
389 ShouldInvertCC = true;
390 [[fallthrough]];
391 case ISD::SETUEQ:
392 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
393 (VT == MVT::f64) ? RTLIB::UO_F64 :
394 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
395 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
396 (VT == MVT::f64) ? RTLIB::OEQ_F64 :
397 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
398 break;
399 default:
400 // Invert CC for unordered comparisons
401 ShouldInvertCC = true;
402 switch (CCCode) {
403 case ISD::SETULT:
404 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
405 (VT == MVT::f64) ? RTLIB::OGE_F64 :
406 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
407 break;
408 case ISD::SETULE:
409 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
410 (VT == MVT::f64) ? RTLIB::OGT_F64 :
411 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
412 break;
413 case ISD::SETUGT:
414 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
415 (VT == MVT::f64) ? RTLIB::OLE_F64 :
416 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
417 break;
418 case ISD::SETUGE:
419 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
420 (VT == MVT::f64) ? RTLIB::OLT_F64 :
421 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
422 break;
423 default: llvm_unreachable("Do not know how to soften this setcc!");
424 }
425 }
426
427 // Use the target specific return value for comparison lib calls.
429 SDValue Ops[2] = {NewLHS, NewRHS};
431 EVT OpsVT[2] = { OldLHS.getValueType(),
432 OldRHS.getValueType() };
433 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT);
434 auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain);
435 NewLHS = Call.first;
436 NewRHS = DAG.getConstant(0, dl, RetVT);
437
438 RTLIB::LibcallImpl LC1Impl = getLibcallImpl(LC1);
439 if (LC1Impl == RTLIB::Unsupported) {
441 "no libcall available to soften floating-point compare");
442 }
443
444 CCCode = getSoftFloatCmpLibcallPredicate(LC1Impl);
445 if (ShouldInvertCC) {
446 assert(RetVT.isInteger());
447 CCCode = getSetCCInverse(CCCode, RetVT);
448 }
449
450 if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
451 // Update Chain.
452 Chain = Call.second;
453 } else {
454 RTLIB::LibcallImpl LC2Impl = getLibcallImpl(LC2);
455 if (LC2Impl == RTLIB::Unsupported) {
457 "no libcall available to soften floating-point compare");
458 }
459
460 assert(CCCode == (ShouldInvertCC ? ISD::SETEQ : ISD::SETNE) &&
461 "unordered call should be simple boolean");
462
463 EVT SetCCVT =
464 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
466 NewLHS = DAG.getNode(ISD::AssertZext, dl, RetVT, Call.first,
467 DAG.getValueType(MVT::i1));
468 }
469
470 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
471 auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain);
472 CCCode = getSoftFloatCmpLibcallPredicate(LC2Impl);
473 if (ShouldInvertCC)
474 CCCode = getSetCCInverse(CCCode, RetVT);
475 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
476 if (Chain)
477 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
478 Call2.second);
479 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
480 Tmp.getValueType(), Tmp, NewLHS);
481 NewRHS = SDValue();
482 }
483}
484
485/// Return the entry encoding for a jump table in the current function. The
486/// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
488 // In non-pic modes, just use the address of a block.
491
492 // Otherwise, use a label difference.
494}
495
497 SelectionDAG &DAG) const {
498 return Table;
499}
500
501/// This returns the relocation base for the given PIC jumptable, the same as
502/// getPICJumpTableRelocBase, but as an MCExpr.
503const MCExpr *
505 unsigned JTI,MCContext &Ctx) const{
506 // The normal PIC reloc base is the label at the start of the jump table.
507 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
508}
509
511 SDValue Addr, int JTI,
512 SelectionDAG &DAG) const {
513 SDValue Chain = Value;
514 // Jump table debug info is only needed if CodeView is enabled.
516 Chain = DAG.getJumpTableDebugInfo(JTI, Chain, dl);
517 }
518 return DAG.getNode(ISD::BRIND, dl, MVT::Other, Chain, Addr);
519}
520
521bool
523 const TargetMachine &TM = getTargetMachine();
524 const GlobalValue *GV = GA->getGlobal();
525
526 // If the address is not even local to this DSO we will have to load it from
527 // a got and then add the offset.
528 if (!TM.shouldAssumeDSOLocal(GV))
529 return false;
530
531 // If the code is position independent we will have to add a base register.
533 return false;
534
535 // Otherwise we can do it.
536 return true;
537}
538
539//===----------------------------------------------------------------------===//
540// Optimization Methods
541//===----------------------------------------------------------------------===//
542
543/// If the specified instruction has a constant integer operand and there are
544/// bits set in that constant that are not demanded, then clear those bits and
545/// return true.
547 const APInt &DemandedBits,
548 const APInt &DemandedElts,
549 TargetLoweringOpt &TLO) const {
550 SDLoc DL(Op);
551 unsigned Opcode = Op.getOpcode();
552
553 // Early-out if we've ended up calling an undemanded node, leave this to
554 // constant folding.
555 if (DemandedBits.isZero() || DemandedElts.isZero())
556 return false;
557
558 // Do target-specific constant optimization.
559 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
560 return TLO.New.getNode();
561
562 // FIXME: ISD::SELECT, ISD::SELECT_CC
563 switch (Opcode) {
564 default:
565 break;
566 case ISD::XOR:
567 case ISD::AND:
568 case ISD::OR: {
569 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
570 if (!Op1C || Op1C->isOpaque())
571 return false;
572
573 // If this is a 'not' op, don't touch it because that's a canonical form.
574 const APInt &C = Op1C->getAPIntValue();
575 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
576 return false;
577
578 if (!C.isSubsetOf(DemandedBits)) {
579 EVT VT = Op.getValueType();
580 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
581 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC,
582 Op->getFlags());
583 return TLO.CombineTo(Op, NewOp);
584 }
585
586 break;
587 }
588 }
589
590 return false;
591}
592
594 const APInt &DemandedBits,
595 TargetLoweringOpt &TLO) const {
596 EVT VT = Op.getValueType();
597 APInt DemandedElts = VT.isVector()
599 : APInt(1, 1);
600 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
601}
602
603/// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
604/// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast,
605/// but it could be generalized for targets with other types of implicit
606/// widening casts.
608 const APInt &DemandedBits,
609 TargetLoweringOpt &TLO) const {
610 assert(Op.getNumOperands() == 2 &&
611 "ShrinkDemandedOp only supports binary operators!");
612 assert(Op.getNode()->getNumValues() == 1 &&
613 "ShrinkDemandedOp only supports nodes with one result!");
614
615 EVT VT = Op.getValueType();
616 SelectionDAG &DAG = TLO.DAG;
617 SDLoc dl(Op);
618
619 // Early return, as this function cannot handle vector types.
620 if (VT.isVector())
621 return false;
622
623 assert(Op.getOperand(0).getValueType().getScalarSizeInBits() == BitWidth &&
624 Op.getOperand(1).getValueType().getScalarSizeInBits() == BitWidth &&
625 "ShrinkDemandedOp only supports operands that have the same size!");
626
627 // Don't do this if the node has another user, which may require the
628 // full value.
629 if (!Op.getNode()->hasOneUse())
630 return false;
631
632 // Search for the smallest integer type with free casts to and from
633 // Op's type. For expedience, just check power-of-2 integer types.
634 unsigned DemandedSize = DemandedBits.getActiveBits();
635 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
636 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
637 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
638 if (isTruncateFree(Op, SmallVT) && isZExtFree(SmallVT, VT)) {
639 // We found a type with free casts.
640
641 // If the operation has the 'disjoint' flag, then the
642 // operands on the new node are also disjoint.
643 SDNodeFlags Flags(Op->getFlags().hasDisjoint() ? SDNodeFlags::Disjoint
645 unsigned Opcode = Op.getOpcode();
646 if (Opcode == ISD::PTRADD) {
647 // It isn't a ptradd anymore if it doesn't operate on the entire
648 // pointer.
649 Opcode = ISD::ADD;
650 }
651 SDValue X = DAG.getNode(
652 Opcode, dl, SmallVT,
653 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
654 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)), Flags);
655 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
656 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, VT, X);
657 return TLO.CombineTo(Op, Z);
658 }
659 }
660 return false;
661}
662
664 DAGCombinerInfo &DCI) const {
665 SelectionDAG &DAG = DCI.DAG;
666 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
667 !DCI.isBeforeLegalizeOps());
669
670 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
671 if (Simplified) {
672 DCI.AddToWorklist(Op.getNode());
674 }
675 return Simplified;
676}
677
679 const APInt &DemandedElts,
680 DAGCombinerInfo &DCI) const {
681 SelectionDAG &DAG = DCI.DAG;
682 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
683 !DCI.isBeforeLegalizeOps());
685
686 bool Simplified =
687 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
688 if (Simplified) {
689 DCI.AddToWorklist(Op.getNode());
691 }
692 return Simplified;
693}
694
698 unsigned Depth,
699 bool AssumeSingleUse) const {
700 EVT VT = Op.getValueType();
701
702 // Since the number of lanes in a scalable vector is unknown at compile time,
703 // we track one bit which is implicitly broadcast to all lanes. This means
704 // that all lanes in a scalable vector are considered demanded.
705 APInt DemandedElts = VT.isFixedLengthVector()
707 : APInt(1, 1);
708 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
709 AssumeSingleUse);
710}
711
712// TODO: Under what circumstances can we create nodes? Constant folding?
714 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
715 SelectionDAG &DAG, unsigned Depth) const {
716 EVT VT = Op.getValueType();
717
718 // Limit search depth.
720 return SDValue();
721
722 // Ignore UNDEFs.
723 if (Op.isUndef())
724 return SDValue();
725
726 // Not demanding any bits/elts from Op.
727 if (DemandedBits == 0 || DemandedElts == 0)
728 return DAG.getUNDEF(VT);
729
730 bool IsLE = DAG.getDataLayout().isLittleEndian();
731 unsigned NumElts = DemandedElts.getBitWidth();
732 unsigned BitWidth = DemandedBits.getBitWidth();
733 KnownBits LHSKnown, RHSKnown;
734 switch (Op.getOpcode()) {
735 case ISD::BITCAST: {
736 if (VT.isScalableVector())
737 return SDValue();
738
739 SDValue Src = peekThroughBitcasts(Op.getOperand(0));
740 EVT SrcVT = Src.getValueType();
741 EVT DstVT = Op.getValueType();
742 if (SrcVT == DstVT)
743 return Src;
744
745 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
746 unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
747 if (NumSrcEltBits == NumDstEltBits)
749 Src, DemandedBits, DemandedElts, DAG, Depth + 1))
750 return DAG.getBitcast(DstVT, V);
751
752 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
753 unsigned Scale = NumDstEltBits / NumSrcEltBits;
754 unsigned NumSrcElts = SrcVT.getVectorNumElements();
755 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
756 for (unsigned i = 0; i != Scale; ++i) {
757 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
758 unsigned BitOffset = EltOffset * NumSrcEltBits;
759 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
760 }
761 // Recursive calls below may turn not demanded elements into poison, so we
762 // need to demand all smaller source elements that maps to a demanded
763 // destination element.
764 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
765
767 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
768 return DAG.getBitcast(DstVT, V);
769 }
770
771 // TODO - bigendian once we have test coverage.
772 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
773 unsigned Scale = NumSrcEltBits / NumDstEltBits;
774 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
775 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
776 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
777 for (unsigned i = 0; i != NumElts; ++i)
778 if (DemandedElts[i]) {
779 unsigned Offset = (i % Scale) * NumDstEltBits;
780 DemandedSrcBits.insertBits(DemandedBits, Offset);
781 DemandedSrcElts.setBit(i / Scale);
782 }
783
785 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
786 return DAG.getBitcast(DstVT, V);
787 }
788
789 break;
790 }
791 case ISD::AND: {
792 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
793 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
794
795 // If all of the demanded bits are known 1 on one side, return the other.
796 // These bits cannot contribute to the result of the 'and' in this
797 // context.
798 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
799 return Op.getOperand(0);
800 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
801 return Op.getOperand(1);
802 break;
803 }
804 case ISD::OR: {
805 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
806 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
807
808 // If all of the demanded bits are known zero on one side, return the
809 // other. These bits cannot contribute to the result of the 'or' in this
810 // context.
811 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
812 return Op.getOperand(0);
813 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
814 return Op.getOperand(1);
815 break;
816 }
817 case ISD::XOR: {
818 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
819 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
820
821 // If all of the demanded bits are known zero on one side, return the
822 // other.
823 if (DemandedBits.isSubsetOf(RHSKnown.Zero))
824 return Op.getOperand(0);
825 if (DemandedBits.isSubsetOf(LHSKnown.Zero))
826 return Op.getOperand(1);
827 break;
828 }
829 case ISD::ADD:
830 case ISD::MUL:
831 case ISD::SMIN:
832 case ISD::SMAX:
833 case ISD::UMIN:
834 case ISD::UMAX: {
835 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(1),
836 DemandedElts, 1, Depth + 1))
837 return Op.getOperand(0);
838
839 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(0),
840 DemandedElts, 0, Depth + 1))
841 return Op.getOperand(1);
842 break;
843 }
844 case ISD::SHL: {
845 // If we are only demanding sign bits then we can use the shift source
846 // directly.
847 if (std::optional<unsigned> MaxSA =
848 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
849 SDValue Op0 = Op.getOperand(0);
850 unsigned ShAmt = *MaxSA;
851 unsigned NumSignBits =
852 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
853 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
854 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
855 return Op0;
856 }
857 break;
858 }
859 case ISD::SRL: {
860 // If we are only demanding sign bits then we can use the shift source
861 // directly.
862 if (std::optional<unsigned> MaxSA =
863 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
864 SDValue Op0 = Op.getOperand(0);
865 unsigned ShAmt = *MaxSA;
866 // Must already be signbits in DemandedBits bounds, and can't demand any
867 // shifted in zeroes.
868 if (DemandedBits.countl_zero() >= ShAmt) {
869 unsigned NumSignBits =
870 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
871 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
872 return Op0;
873 }
874 }
875 break;
876 }
877 case ISD::SETCC: {
878 SDValue Op0 = Op.getOperand(0);
879 SDValue Op1 = Op.getOperand(1);
880 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
881 // If (1) we only need the sign-bit, (2) the setcc operands are the same
882 // width as the setcc result, and (3) the result of a setcc conforms to 0 or
883 // -1, we may be able to bypass the setcc.
884 if (DemandedBits.isSignMask() &&
888 // If we're testing X < 0, then this compare isn't needed - just use X!
889 // FIXME: We're limiting to integer types here, but this should also work
890 // if we don't care about FP signed-zero. The use of SETLT with FP means
891 // that we don't care about NaNs.
892 if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
894 return Op0;
895 }
896 break;
897 }
899 // If none of the extended bits are demanded, eliminate the sextinreg.
900 SDValue Op0 = Op.getOperand(0);
901 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
902 unsigned ExBits = ExVT.getScalarSizeInBits();
903 if (DemandedBits.getActiveBits() <= ExBits &&
905 return Op0;
906 // If the input is already sign extended, just drop the extension.
907 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
908 if (NumSignBits >= (BitWidth - ExBits + 1))
909 return Op0;
910 break;
911 }
915 if (VT.isScalableVector())
916 return SDValue();
917
918 // If we only want the lowest element and none of extended bits, then we can
919 // return the bitcasted source vector.
920 SDValue Src = Op.getOperand(0);
921 EVT SrcVT = Src.getValueType();
922 EVT DstVT = Op.getValueType();
923 if (IsLE && DemandedElts == 1 &&
924 DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
925 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
926 return DAG.getBitcast(DstVT, Src);
927 }
928 break;
929 }
931 if (VT.isScalableVector())
932 return SDValue();
933
934 // If we don't demand the inserted element, return the base vector.
935 SDValue Vec = Op.getOperand(0);
936 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
937 EVT VecVT = Vec.getValueType();
938 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
939 !DemandedElts[CIdx->getZExtValue()])
940 return Vec;
941 break;
942 }
944 if (VT.isScalableVector())
945 return SDValue();
946
947 SDValue Vec = Op.getOperand(0);
948 SDValue Sub = Op.getOperand(1);
949 uint64_t Idx = Op.getConstantOperandVal(2);
950 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
951 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
952 // If we don't demand the inserted subvector, return the base vector.
953 if (DemandedSubElts == 0)
954 return Vec;
955 break;
956 }
957 case ISD::VECTOR_SHUFFLE: {
959 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
960
961 // If all the demanded elts are from one operand and are inline,
962 // then we can use the operand directly.
963 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
964 for (unsigned i = 0; i != NumElts; ++i) {
965 int M = ShuffleMask[i];
966 if (M < 0 || !DemandedElts[i])
967 continue;
968 AllUndef = false;
969 IdentityLHS &= (M == (int)i);
970 IdentityRHS &= ((M - NumElts) == i);
971 }
972
973 if (AllUndef)
974 return DAG.getUNDEF(Op.getValueType());
975 if (IdentityLHS)
976 return Op.getOperand(0);
977 if (IdentityRHS)
978 return Op.getOperand(1);
979 break;
980 }
981 default:
982 // TODO: Probably okay to remove after audit; here to reduce change size
983 // in initial enablement patch for scalable vectors
984 if (VT.isScalableVector())
985 return SDValue();
986
987 if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
989 Op, DemandedBits, DemandedElts, DAG, Depth))
990 return V;
991 break;
992 }
993 return SDValue();
994}
995
998 unsigned Depth) const {
999 EVT VT = Op.getValueType();
1000 // Since the number of lanes in a scalable vector is unknown at compile time,
1001 // we track one bit which is implicitly broadcast to all lanes. This means
1002 // that all lanes in a scalable vector are considered demanded.
1003 APInt DemandedElts = VT.isFixedLengthVector()
1005 : APInt(1, 1);
1006 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1007 Depth);
1008}
1009
1011 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
1012 unsigned Depth) const {
1013 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
1014 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1015 Depth);
1016}
1017
1018// Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
1019// or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
1022 const TargetLowering &TLI,
1023 const APInt &DemandedBits,
1024 const APInt &DemandedElts, unsigned Depth) {
1025 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
1026 "SRL or SRA node is required here!");
1027 // Is the right shift using an immediate value of 1?
1028 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
1029 if (!N1C || !N1C->isOne())
1030 return SDValue();
1031
1032 // We are looking for an avgfloor
1033 // add(ext, ext)
1034 // or one of these as a avgceil
1035 // add(add(ext, ext), 1)
1036 // add(add(ext, 1), ext)
1037 // add(ext, add(ext, 1))
1038 SDValue Add = Op.getOperand(0);
1039 if (Add.getOpcode() != ISD::ADD)
1040 return SDValue();
1041
1042 SDValue ExtOpA = Add.getOperand(0);
1043 SDValue ExtOpB = Add.getOperand(1);
1044 SDValue Add2;
1045 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3, SDValue A) {
1046 ConstantSDNode *ConstOp;
1047 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
1048 ConstOp->isOne()) {
1049 ExtOpA = Op1;
1050 ExtOpB = Op3;
1051 Add2 = A;
1052 return true;
1053 }
1054 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
1055 ConstOp->isOne()) {
1056 ExtOpA = Op1;
1057 ExtOpB = Op2;
1058 Add2 = A;
1059 return true;
1060 }
1061 return false;
1062 };
1063 bool IsCeil =
1064 (ExtOpA.getOpcode() == ISD::ADD &&
1065 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB, ExtOpA)) ||
1066 (ExtOpB.getOpcode() == ISD::ADD &&
1067 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA, ExtOpB));
1068
1069 // If the shift is signed (sra):
1070 // - Needs >= 2 sign bit for both operands.
1071 // - Needs >= 2 zero bits.
1072 // If the shift is unsigned (srl):
1073 // - Needs >= 1 zero bit for both operands.
1074 // - Needs 1 demanded bit zero and >= 2 sign bits.
1075 SelectionDAG &DAG = TLO.DAG;
1076 unsigned ShiftOpc = Op.getOpcode();
1077 bool IsSigned = false;
1078 unsigned KnownBits;
1079 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
1080 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
1081 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
1082 unsigned NumZeroA =
1083 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
1084 unsigned NumZeroB =
1085 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
1086 unsigned NumZero = std::min(NumZeroA, NumZeroB);
1087
1088 switch (ShiftOpc) {
1089 default:
1090 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
1091 case ISD::SRA: {
1092 if (NumZero >= 2 && NumSigned < NumZero) {
1093 IsSigned = false;
1094 KnownBits = NumZero;
1095 break;
1096 }
1097 if (NumSigned >= 1) {
1098 IsSigned = true;
1099 KnownBits = NumSigned;
1100 break;
1101 }
1102 return SDValue();
1103 }
1104 case ISD::SRL: {
1105 if (NumZero >= 1 && NumSigned < NumZero) {
1106 IsSigned = false;
1107 KnownBits = NumZero;
1108 break;
1109 }
1110 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1111 IsSigned = true;
1112 KnownBits = NumSigned;
1113 break;
1114 }
1115 return SDValue();
1116 }
1117 }
1118
1119 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1120 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1121
1122 // Find the smallest power-2 type that is legal for this vector size and
1123 // operation, given the original type size and the number of known sign/zero
1124 // bits.
1125 EVT VT = Op.getValueType();
1126 unsigned MinWidth =
1127 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1128 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_ceil(MinWidth));
1130 return SDValue();
1131 if (VT.isVector())
1132 NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
1133 if (TLO.LegalTypes() && !TLI.isOperationLegal(AVGOpc, NVT)) {
1134 // If we could not transform, and (both) adds are nuw/nsw, we can use the
1135 // larger type size to do the transform.
1136 if (TLO.LegalOperations() && !TLI.isOperationLegal(AVGOpc, VT))
1137 return SDValue();
1138 if (DAG.willNotOverflowAdd(IsSigned, Add.getOperand(0),
1139 Add.getOperand(1)) &&
1140 (!Add2 || DAG.willNotOverflowAdd(IsSigned, Add2.getOperand(0),
1141 Add2.getOperand(1))))
1142 NVT = VT;
1143 else
1144 return SDValue();
1145 }
1146
1147 // Don't create a AVGFLOOR node with a scalar constant unless its legal as
1148 // this is likely to stop other folds (reassociation, value tracking etc.)
1149 if (!IsCeil && !TLI.isOperationLegal(AVGOpc, NVT) &&
1150 (isa<ConstantSDNode>(ExtOpA) || isa<ConstantSDNode>(ExtOpB)))
1151 return SDValue();
1152
1153 SDLoc DL(Op);
1154 SDValue ResultAVG =
1155 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, ExtOpA, DL, NVT),
1156 DAG.getExtOrTrunc(IsSigned, ExtOpB, DL, NVT));
1157 return DAG.getExtOrTrunc(IsSigned, ResultAVG, DL, VT);
1158}
1159
1160/// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1161/// result of Op are ever used downstream. If we can use this information to
1162/// simplify Op, create a new simplified DAG node and return true, returning the
1163/// original and new nodes in Old and New. Otherwise, analyze the expression and
1164/// return a mask of Known bits for the expression (used to simplify the
1165/// caller). The Known bits may only be accurate for those bits in the
1166/// OriginalDemandedBits and OriginalDemandedElts.
1168 SDValue Op, const APInt &OriginalDemandedBits,
1169 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1170 unsigned Depth, bool AssumeSingleUse) const {
1171 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1172 assert(Op.getScalarValueSizeInBits() == BitWidth &&
1173 "Mask size mismatches value type size!");
1174
1175 // Don't know anything.
1177
1178 EVT VT = Op.getValueType();
1179 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1180 unsigned NumElts = OriginalDemandedElts.getBitWidth();
1181 assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) &&
1182 "Unexpected vector size");
1183
1184 APInt DemandedBits = OriginalDemandedBits;
1185 APInt DemandedElts = OriginalDemandedElts;
1186 SDLoc dl(Op);
1187
1188 // Undef operand.
1189 if (Op.isUndef())
1190 return false;
1191
1192 // We can't simplify target constants.
1193 if (Op.getOpcode() == ISD::TargetConstant)
1194 return false;
1195
1196 if (Op.getOpcode() == ISD::Constant) {
1197 // We know all of the bits for a constant!
1198 Known = KnownBits::makeConstant(Op->getAsAPIntVal());
1199 return false;
1200 }
1201
1202 if (Op.getOpcode() == ISD::ConstantFP) {
1203 // We know all of the bits for a floating point constant!
1205 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1206 return false;
1207 }
1208
1209 // Other users may use these bits.
1210 bool HasMultiUse = false;
1211 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) {
1213 // Limit search depth.
1214 return false;
1215 }
1216 // Allow multiple uses, just set the DemandedBits/Elts to all bits.
1218 DemandedElts = APInt::getAllOnes(NumElts);
1219 HasMultiUse = true;
1220 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1221 // Not demanding any bits/elts from Op.
1222 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1223 } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1224 // Limit search depth.
1225 return false;
1226 }
1227
1228 KnownBits Known2;
1229 switch (Op.getOpcode()) {
1230 case ISD::SCALAR_TO_VECTOR: {
1231 if (VT.isScalableVector())
1232 return false;
1233 if (!DemandedElts[0])
1234 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1235
1236 KnownBits SrcKnown;
1237 SDValue Src = Op.getOperand(0);
1238 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1239 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1240 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1241 return true;
1242
1243 // Upper elements are undef, so only get the knownbits if we just demand
1244 // the bottom element.
1245 if (DemandedElts == 1)
1246 Known = SrcKnown.anyextOrTrunc(BitWidth);
1247 break;
1248 }
1249 case ISD::BUILD_VECTOR:
1250 // Collect the known bits that are shared by every demanded element.
1251 // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1252 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1253 return false; // Don't fall through, will infinitely loop.
1254 case ISD::SPLAT_VECTOR: {
1255 SDValue Scl = Op.getOperand(0);
1256 APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits());
1257 KnownBits KnownScl;
1258 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1259 return true;
1260
1261 // Implicitly truncate the bits to match the official semantics of
1262 // SPLAT_VECTOR.
1263 Known = KnownScl.trunc(BitWidth);
1264 break;
1265 }
1266 case ISD::FREEZE: {
1267 SDValue N0 = Op.getOperand(0);
1269 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
1270 return TLO.CombineTo(Op, N0);
1271 break;
1272 }
1273 case ISD::LOAD: {
1274 auto *LD = cast<LoadSDNode>(Op);
1275 if (getTargetConstantFromLoad(LD)) {
1276 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1277 return false; // Don't fall through, will infinitely loop.
1278 }
1279 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1280 // If this is a ZEXTLoad and we are looking at the loaded value.
1281 EVT MemVT = LD->getMemoryVT();
1282 unsigned MemBits = MemVT.getScalarSizeInBits();
1283 Known.Zero.setBitsFrom(MemBits);
1284 return false; // Don't fall through, will infinitely loop.
1285 }
1286 break;
1287 }
1289 if (VT.isScalableVector())
1290 return false;
1291 SDValue Vec = Op.getOperand(0);
1292 SDValue Scl = Op.getOperand(1);
1293 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1294 EVT VecVT = Vec.getValueType();
1295
1296 // If index isn't constant, assume we need all vector elements AND the
1297 // inserted element.
1298 APInt DemandedVecElts(DemandedElts);
1299 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1300 unsigned Idx = CIdx->getZExtValue();
1301 DemandedVecElts.clearBit(Idx);
1302
1303 // Inserted element is not required.
1304 if (!DemandedElts[Idx])
1305 return TLO.CombineTo(Op, Vec);
1306 }
1307
1308 KnownBits KnownScl;
1309 unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1310 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1311 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1312 return true;
1313
1314 Known = KnownScl.anyextOrTrunc(BitWidth);
1315
1316 KnownBits KnownVec;
1317 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1318 Depth + 1))
1319 return true;
1320
1321 if (!!DemandedVecElts)
1322 Known = Known.intersectWith(KnownVec);
1323
1324 return false;
1325 }
1326 case ISD::INSERT_SUBVECTOR: {
1327 if (VT.isScalableVector())
1328 return false;
1329 // Demand any elements from the subvector and the remainder from the src its
1330 // inserted into.
1331 SDValue Src = Op.getOperand(0);
1332 SDValue Sub = Op.getOperand(1);
1333 uint64_t Idx = Op.getConstantOperandVal(2);
1334 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1335 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1336 APInt DemandedSrcElts = DemandedElts;
1337 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
1338
1339 KnownBits KnownSub, KnownSrc;
1340 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1341 Depth + 1))
1342 return true;
1343 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1344 Depth + 1))
1345 return true;
1346
1347 Known.setAllConflict();
1348 if (!!DemandedSubElts)
1349 Known = Known.intersectWith(KnownSub);
1350 if (!!DemandedSrcElts)
1351 Known = Known.intersectWith(KnownSrc);
1352
1353 // Attempt to avoid multi-use src if we don't need anything from it.
1354 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1355 !DemandedSrcElts.isAllOnes()) {
1357 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1359 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1360 if (NewSub || NewSrc) {
1361 NewSub = NewSub ? NewSub : Sub;
1362 NewSrc = NewSrc ? NewSrc : Src;
1363 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1364 Op.getOperand(2));
1365 return TLO.CombineTo(Op, NewOp);
1366 }
1367 }
1368 break;
1369 }
1371 if (VT.isScalableVector())
1372 return false;
1373 // Offset the demanded elts by the subvector index.
1374 SDValue Src = Op.getOperand(0);
1375 if (Src.getValueType().isScalableVector())
1376 break;
1377 uint64_t Idx = Op.getConstantOperandVal(1);
1378 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1379 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1380
1381 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1382 Depth + 1))
1383 return true;
1384
1385 // Attempt to avoid multi-use src if we don't need anything from it.
1386 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1388 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1389 if (DemandedSrc) {
1390 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1391 Op.getOperand(1));
1392 return TLO.CombineTo(Op, NewOp);
1393 }
1394 }
1395 break;
1396 }
1397 case ISD::CONCAT_VECTORS: {
1398 if (VT.isScalableVector())
1399 return false;
1400 Known.setAllConflict();
1401 EVT SubVT = Op.getOperand(0).getValueType();
1402 unsigned NumSubVecs = Op.getNumOperands();
1403 unsigned NumSubElts = SubVT.getVectorNumElements();
1404 for (unsigned i = 0; i != NumSubVecs; ++i) {
1405 APInt DemandedSubElts =
1406 DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1407 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1408 Known2, TLO, Depth + 1))
1409 return true;
1410 // Known bits are shared by every demanded subvector element.
1411 if (!!DemandedSubElts)
1412 Known = Known.intersectWith(Known2);
1413 }
1414 break;
1415 }
1416 case ISD::VECTOR_SHUFFLE: {
1417 assert(!VT.isScalableVector());
1418 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1419
1420 // Collect demanded elements from shuffle operands..
1421 APInt DemandedLHS, DemandedRHS;
1422 if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS,
1423 DemandedRHS))
1424 break;
1425
1426 if (!!DemandedLHS || !!DemandedRHS) {
1427 SDValue Op0 = Op.getOperand(0);
1428 SDValue Op1 = Op.getOperand(1);
1429
1430 Known.setAllConflict();
1431 if (!!DemandedLHS) {
1432 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1433 Depth + 1))
1434 return true;
1435 Known = Known.intersectWith(Known2);
1436 }
1437 if (!!DemandedRHS) {
1438 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1439 Depth + 1))
1440 return true;
1441 Known = Known.intersectWith(Known2);
1442 }
1443
1444 // Attempt to avoid multi-use ops if we don't need anything from them.
1446 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1448 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1449 if (DemandedOp0 || DemandedOp1) {
1450 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1451 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1452 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1453 return TLO.CombineTo(Op, NewOp);
1454 }
1455 }
1456 break;
1457 }
1458 case ISD::AND: {
1459 SDValue Op0 = Op.getOperand(0);
1460 SDValue Op1 = Op.getOperand(1);
1461
1462 // If the RHS is a constant, check to see if the LHS would be zero without
1463 // using the bits from the RHS. Below, we use knowledge about the RHS to
1464 // simplify the LHS, here we're using information from the LHS to simplify
1465 // the RHS.
1466 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1, DemandedElts)) {
1467 // Do not increment Depth here; that can cause an infinite loop.
1468 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1469 // If the LHS already has zeros where RHSC does, this 'and' is dead.
1470 if ((LHSKnown.Zero & DemandedBits) ==
1471 (~RHSC->getAPIntValue() & DemandedBits))
1472 return TLO.CombineTo(Op, Op0);
1473
1474 // If any of the set bits in the RHS are known zero on the LHS, shrink
1475 // the constant.
1476 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1477 DemandedElts, TLO))
1478 return true;
1479
1480 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1481 // constant, but if this 'and' is only clearing bits that were just set by
1482 // the xor, then this 'and' can be eliminated by shrinking the mask of
1483 // the xor. For example, for a 32-bit X:
1484 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1485 if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1486 LHSKnown.One == ~RHSC->getAPIntValue()) {
1487 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1488 return TLO.CombineTo(Op, Xor);
1489 }
1490 }
1491
1492 // (X +/- Y) & Y --> ~X & Y when Y is a power of 2 (or zero).
1493 SDValue X, Y;
1494 if (sd_match(Op,
1495 m_And(m_Value(Y),
1497 m_Sub(m_Value(X), m_Deferred(Y)))))) &&
1498 TLO.DAG.isKnownToBeAPowerOfTwo(Y, DemandedElts, /*OrZero=*/true)) {
1499 return TLO.CombineTo(
1500 Op, TLO.DAG.getNode(ISD::AND, dl, VT, TLO.DAG.getNOT(dl, X, VT), Y));
1501 }
1502
1503 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I)
1504 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits).
1505 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() &&
1506 (Op0.getOperand(0).isUndef() ||
1508 Op0->hasOneUse()) {
1509 unsigned NumSubElts =
1511 unsigned SubIdx = Op0.getConstantOperandVal(2);
1512 APInt DemandedSub =
1513 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts);
1514 KnownBits KnownSubMask =
1515 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1);
1516 if (DemandedBits.isSubsetOf(KnownSubMask.One)) {
1517 SDValue NewAnd =
1518 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1);
1519 SDValue NewInsert =
1520 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd,
1521 Op0.getOperand(1), Op0.getOperand(2));
1522 return TLO.CombineTo(Op, NewInsert);
1523 }
1524 }
1525
1526 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1527 Depth + 1))
1528 return true;
1529 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1530 Known2, TLO, Depth + 1))
1531 return true;
1532
1533 // If all of the demanded bits are known one on one side, return the other.
1534 // These bits cannot contribute to the result of the 'and'.
1535 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1536 return TLO.CombineTo(Op, Op0);
1537 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1538 return TLO.CombineTo(Op, Op1);
1539 // If all of the demanded bits in the inputs are known zeros, return zero.
1540 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1541 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1542 // If the RHS is a constant, see if we can simplify it.
1543 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1544 TLO))
1545 return true;
1546 // If the operation can be done in a smaller type, do so.
1548 return true;
1549
1550 // Attempt to avoid multi-use ops if we don't need anything from them.
1551 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1553 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1555 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1556 if (DemandedOp0 || DemandedOp1) {
1557 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1558 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1559 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1560 return TLO.CombineTo(Op, NewOp);
1561 }
1562 }
1563
1564 Known &= Known2;
1565 break;
1566 }
1567 case ISD::OR: {
1568 SDValue Op0 = Op.getOperand(0);
1569 SDValue Op1 = Op.getOperand(1);
1570 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1571 Depth + 1)) {
1572 Op->dropFlags(SDNodeFlags::Disjoint);
1573 return true;
1574 }
1575
1576 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1577 Known2, TLO, Depth + 1)) {
1578 Op->dropFlags(SDNodeFlags::Disjoint);
1579 return true;
1580 }
1581
1582 // If all of the demanded bits are known zero on one side, return the other.
1583 // These bits cannot contribute to the result of the 'or'.
1584 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1585 return TLO.CombineTo(Op, Op0);
1586 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1587 return TLO.CombineTo(Op, Op1);
1588 // If the RHS is a constant, see if we can simplify it.
1589 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1590 return true;
1591 // If the operation can be done in a smaller type, do so.
1593 return true;
1594
1595 // Attempt to avoid multi-use ops if we don't need anything from them.
1596 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1598 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1600 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1601 if (DemandedOp0 || DemandedOp1) {
1602 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1603 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1604 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1605 return TLO.CombineTo(Op, NewOp);
1606 }
1607 }
1608
1609 // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2))
1610 // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks.
1611 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::AND &&
1612 Op0->hasOneUse() && Op1->hasOneUse()) {
1613 // Attempt to match all commutations - m_c_Or would've been useful!
1614 for (int I = 0; I != 2; ++I) {
1615 SDValue X = Op.getOperand(I).getOperand(0);
1616 SDValue C1 = Op.getOperand(I).getOperand(1);
1617 SDValue Alt = Op.getOperand(1 - I).getOperand(0);
1618 SDValue C2 = Op.getOperand(1 - I).getOperand(1);
1619 if (Alt.getOpcode() == ISD::OR) {
1620 for (int J = 0; J != 2; ++J) {
1621 if (X == Alt.getOperand(J)) {
1622 SDValue Y = Alt.getOperand(1 - J);
1623 if (SDValue C12 = TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT,
1624 {C1, C2})) {
1625 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12);
1626 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2);
1627 return TLO.CombineTo(
1628 Op, TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY));
1629 }
1630 }
1631 }
1632 }
1633 }
1634 }
1635
1636 Known |= Known2;
1637 break;
1638 }
1639 case ISD::XOR: {
1640 SDValue Op0 = Op.getOperand(0);
1641 SDValue Op1 = Op.getOperand(1);
1642
1643 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1644 Depth + 1))
1645 return true;
1646 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1647 Depth + 1))
1648 return true;
1649
1650 // If all of the demanded bits are known zero on one side, return the other.
1651 // These bits cannot contribute to the result of the 'xor'.
1652 if (DemandedBits.isSubsetOf(Known.Zero))
1653 return TLO.CombineTo(Op, Op0);
1654 if (DemandedBits.isSubsetOf(Known2.Zero))
1655 return TLO.CombineTo(Op, Op1);
1656 // If the operation can be done in a smaller type, do so.
1658 return true;
1659
1660 // If all of the unknown bits are known to be zero on one side or the other
1661 // turn this into an *inclusive* or.
1662 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1663 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1664 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1665
1666 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts);
1667 if (C) {
1668 // If one side is a constant, and all of the set bits in the constant are
1669 // also known set on the other side, turn this into an AND, as we know
1670 // the bits will be cleared.
1671 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1672 // NB: it is okay if more bits are known than are requested
1673 if (C->getAPIntValue() == Known2.One) {
1674 SDValue ANDC =
1675 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1676 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1677 }
1678
1679 // If the RHS is a constant, see if we can change it. Don't alter a -1
1680 // constant because that's a 'not' op, and that is better for combining
1681 // and codegen.
1682 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1683 // We're flipping all demanded bits. Flip the undemanded bits too.
1684 SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1685 return TLO.CombineTo(Op, New);
1686 }
1687
1688 unsigned Op0Opcode = Op0.getOpcode();
1689 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) {
1690 if (ConstantSDNode *ShiftC =
1691 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1692 // Don't crash on an oversized shift. We can not guarantee that a
1693 // bogus shift has been simplified to undef.
1694 if (ShiftC->getAPIntValue().ult(BitWidth)) {
1695 uint64_t ShiftAmt = ShiftC->getZExtValue();
1697 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt)
1698 : Ones.lshr(ShiftAmt);
1699 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) &&
1701 // If the xor constant is a demanded mask, do a 'not' before the
1702 // shift:
1703 // xor (X << ShiftC), XorC --> (not X) << ShiftC
1704 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
1705 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT);
1706 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not,
1707 Op0.getOperand(1)));
1708 }
1709 }
1710 }
1711 }
1712 }
1713
1714 // If we can't turn this into a 'not', try to shrink the constant.
1715 if (!C || !C->isAllOnes())
1716 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1717 return true;
1718
1719 // Attempt to avoid multi-use ops if we don't need anything from them.
1720 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1722 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1724 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1725 if (DemandedOp0 || DemandedOp1) {
1726 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1727 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1728 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1729 return TLO.CombineTo(Op, NewOp);
1730 }
1731 }
1732
1733 Known ^= Known2;
1734 break;
1735 }
1736 case ISD::SELECT:
1737 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1738 Known, TLO, Depth + 1))
1739 return true;
1740 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1741 Known2, TLO, Depth + 1))
1742 return true;
1743
1744 // If the operands are constants, see if we can simplify them.
1745 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1746 return true;
1747
1748 // Only known if known in both the LHS and RHS.
1749 Known = Known.intersectWith(Known2);
1750 break;
1751 case ISD::VSELECT:
1752 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1753 Known, TLO, Depth + 1))
1754 return true;
1755 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1756 Known2, TLO, Depth + 1))
1757 return true;
1758
1759 // Only known if known in both the LHS and RHS.
1760 Known = Known.intersectWith(Known2);
1761 break;
1762 case ISD::SELECT_CC:
1763 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, DemandedElts,
1764 Known, TLO, Depth + 1))
1765 return true;
1766 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1767 Known2, TLO, Depth + 1))
1768 return true;
1769
1770 // If the operands are constants, see if we can simplify them.
1771 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1772 return true;
1773
1774 // Only known if known in both the LHS and RHS.
1775 Known = Known.intersectWith(Known2);
1776 break;
1777 case ISD::SETCC: {
1778 SDValue Op0 = Op.getOperand(0);
1779 SDValue Op1 = Op.getOperand(1);
1780 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1781 // If we're testing X < 0, X >= 0, X <= -1 or X > -1
1782 // (X is of integer type) then we only need the sign mask of the previous
1783 // result
1784 if (Op1.getValueType().isInteger() &&
1785 (((CC == ISD::SETLT || CC == ISD::SETGE) && isNullOrNullSplat(Op1)) ||
1786 ((CC == ISD::SETLE || CC == ISD::SETGT) &&
1787 isAllOnesOrAllOnesSplat(Op1)))) {
1788 KnownBits KnownOp0;
1791 DemandedElts, KnownOp0, TLO, Depth + 1))
1792 return true;
1793 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1794 // width as the setcc result, and (3) the result of a setcc conforms to 0
1795 // or -1, we may be able to bypass the setcc.
1796 if (DemandedBits.isSignMask() &&
1800 // If we remove a >= 0 or > -1 (for integers), we need to introduce a
1801 // NOT Operation
1802 if (CC == ISD::SETGE || CC == ISD::SETGT) {
1803 SDLoc DL(Op);
1804 EVT VT = Op0.getValueType();
1805 SDValue NotOp0 = TLO.DAG.getNOT(DL, Op0, VT);
1806 return TLO.CombineTo(Op, NotOp0);
1807 }
1808 return TLO.CombineTo(Op, Op0);
1809 }
1810 }
1811 if (getBooleanContents(Op0.getValueType()) ==
1813 BitWidth > 1)
1814 Known.Zero.setBitsFrom(1);
1815 break;
1816 }
1817 case ISD::SHL: {
1818 SDValue Op0 = Op.getOperand(0);
1819 SDValue Op1 = Op.getOperand(1);
1820 EVT ShiftVT = Op1.getValueType();
1821
1822 if (std::optional<unsigned> KnownSA =
1823 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
1824 unsigned ShAmt = *KnownSA;
1825 if (ShAmt == 0)
1826 return TLO.CombineTo(Op, Op0);
1827
1828 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1829 // single shift. We can do this if the bottom bits (which are shifted
1830 // out) are never demanded.
1831 // TODO - support non-uniform vector amounts.
1832 if (Op0.getOpcode() == ISD::SRL) {
1833 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
1834 if (std::optional<unsigned> InnerSA =
1835 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
1836 unsigned C1 = *InnerSA;
1837 unsigned Opc = ISD::SHL;
1838 int Diff = ShAmt - C1;
1839 if (Diff < 0) {
1840 Diff = -Diff;
1841 Opc = ISD::SRL;
1842 }
1843 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1844 return TLO.CombineTo(
1845 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1846 }
1847 }
1848 }
1849
1850 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1851 // are not demanded. This will likely allow the anyext to be folded away.
1852 // TODO - support non-uniform vector amounts.
1853 if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1854 SDValue InnerOp = Op0.getOperand(0);
1855 EVT InnerVT = InnerOp.getValueType();
1856 unsigned InnerBits = InnerVT.getScalarSizeInBits();
1857 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1858 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1859 SDValue NarrowShl = TLO.DAG.getNode(
1860 ISD::SHL, dl, InnerVT, InnerOp,
1861 TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl));
1862 return TLO.CombineTo(
1863 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1864 }
1865
1866 // Repeat the SHL optimization above in cases where an extension
1867 // intervenes: (shl (anyext (shr x, c1)), c2) to
1868 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
1869 // aren't demanded (as above) and that the shifted upper c1 bits of
1870 // x aren't demanded.
1871 // TODO - support non-uniform vector amounts.
1872 if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() &&
1873 InnerOp.hasOneUse()) {
1874 if (std::optional<unsigned> SA2 = TLO.DAG.getValidShiftAmount(
1875 InnerOp, DemandedElts, Depth + 2)) {
1876 unsigned InnerShAmt = *SA2;
1877 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1878 DemandedBits.getActiveBits() <=
1879 (InnerBits - InnerShAmt + ShAmt) &&
1880 DemandedBits.countr_zero() >= ShAmt) {
1881 SDValue NewSA =
1882 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
1883 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1884 InnerOp.getOperand(0));
1885 return TLO.CombineTo(
1886 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1887 }
1888 }
1889 }
1890 }
1891
1892 APInt InDemandedMask = DemandedBits.lshr(ShAmt);
1893 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1894 Depth + 1)) {
1895 // Disable the nsw and nuw flags. We can no longer guarantee that we
1896 // won't wrap after simplification.
1897 Op->dropFlags(SDNodeFlags::NoWrap);
1898 return true;
1899 }
1900 Known <<= ShAmt;
1901 // low bits known zero.
1902 Known.Zero.setLowBits(ShAmt);
1903
1904 // Attempt to avoid multi-use ops if we don't need anything from them.
1905 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
1907 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1908 if (DemandedOp0) {
1909 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
1910 return TLO.CombineTo(Op, NewOp);
1911 }
1912 }
1913
1914 // TODO: Can we merge this fold with the one below?
1915 // Try shrinking the operation as long as the shift amount will still be
1916 // in range.
1917 if (ShAmt < DemandedBits.getActiveBits() && !VT.isVector() &&
1918 Op.getNode()->hasOneUse()) {
1919 // Search for the smallest integer type with free casts to and from
1920 // Op's type. For expedience, just check power-of-2 integer types.
1921 unsigned DemandedSize = DemandedBits.getActiveBits();
1922 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
1923 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
1924 EVT SmallVT = EVT::getIntegerVT(*TLO.DAG.getContext(), SmallVTBits);
1925 if (isNarrowingProfitable(Op.getNode(), VT, SmallVT) &&
1926 isTypeDesirableForOp(ISD::SHL, SmallVT) &&
1927 isTruncateFree(VT, SmallVT) && isZExtFree(SmallVT, VT) &&
1928 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, SmallVT))) {
1929 assert(DemandedSize <= SmallVTBits &&
1930 "Narrowed below demanded bits?");
1931 // We found a type with free casts.
1932 SDValue NarrowShl = TLO.DAG.getNode(
1933 ISD::SHL, dl, SmallVT,
1934 TLO.DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
1935 TLO.DAG.getShiftAmountConstant(ShAmt, SmallVT, dl));
1936 return TLO.CombineTo(
1937 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1938 }
1939 }
1940 }
1941
1942 // Narrow shift to lower half - similar to ShrinkDemandedOp.
1943 // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K))
1944 // Only do this if we demand the upper half so the knownbits are correct.
1945 unsigned HalfWidth = BitWidth / 2;
1946 if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth &&
1947 DemandedBits.countLeadingOnes() >= HalfWidth) {
1948 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth);
1949 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
1950 isTypeDesirableForOp(ISD::SHL, HalfVT) &&
1951 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
1952 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) {
1953 // If we're demanding the upper bits at all, we must ensure
1954 // that the upper bits of the shift result are known to be zero,
1955 // which is equivalent to the narrow shift being NUW.
1956 if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) {
1957 bool IsNSW = Known.countMinSignBits() > HalfWidth;
1958 SDNodeFlags Flags;
1959 Flags.setNoSignedWrap(IsNSW);
1960 Flags.setNoUnsignedWrap(IsNUW);
1961 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
1962 SDValue NewShiftAmt =
1963 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
1964 SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp,
1965 NewShiftAmt, Flags);
1966 SDValue NewExt =
1967 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift);
1968 return TLO.CombineTo(Op, NewExt);
1969 }
1970 }
1971 }
1972 } else {
1973 // This is a variable shift, so we can't shift the demand mask by a known
1974 // amount. But if we are not demanding high bits, then we are not
1975 // demanding those bits from the pre-shifted operand either.
1976 if (unsigned CTLZ = DemandedBits.countl_zero()) {
1977 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
1978 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO,
1979 Depth + 1)) {
1980 // Disable the nsw and nuw flags. We can no longer guarantee that we
1981 // won't wrap after simplification.
1982 Op->dropFlags(SDNodeFlags::NoWrap);
1983 return true;
1984 }
1985 Known.resetAll();
1986 }
1987 }
1988
1989 // If we are only demanding sign bits then we can use the shift source
1990 // directly.
1991 if (std::optional<unsigned> MaxSA =
1992 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
1993 unsigned ShAmt = *MaxSA;
1994 unsigned NumSignBits =
1995 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1996 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
1997 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
1998 return TLO.CombineTo(Op, Op0);
1999 }
2000 break;
2001 }
2002 case ISD::SRL: {
2003 SDValue Op0 = Op.getOperand(0);
2004 SDValue Op1 = Op.getOperand(1);
2005 EVT ShiftVT = Op1.getValueType();
2006
2007 if (std::optional<unsigned> KnownSA =
2008 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2009 unsigned ShAmt = *KnownSA;
2010 if (ShAmt == 0)
2011 return TLO.CombineTo(Op, Op0);
2012
2013 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
2014 // single shift. We can do this if the top bits (which are shifted out)
2015 // are never demanded.
2016 // TODO - support non-uniform vector amounts.
2017 if (Op0.getOpcode() == ISD::SHL) {
2018 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2019 if (std::optional<unsigned> InnerSA =
2020 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2021 unsigned C1 = *InnerSA;
2022 unsigned Opc = ISD::SRL;
2023 int Diff = ShAmt - C1;
2024 if (Diff < 0) {
2025 Diff = -Diff;
2026 Opc = ISD::SHL;
2027 }
2028 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
2029 return TLO.CombineTo(
2030 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
2031 }
2032 }
2033 }
2034
2035 // If this is (srl (sra X, C1), ShAmt), see if we can combine this into a
2036 // single sra. We can do this if the top bits are never demanded.
2037 if (Op0.getOpcode() == ISD::SRA && Op0.hasOneUse()) {
2038 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2039 if (std::optional<unsigned> InnerSA =
2040 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2041 unsigned C1 = *InnerSA;
2042 // Clamp the combined shift amount if it exceeds the bit width.
2043 unsigned Combined = std::min(C1 + ShAmt, BitWidth - 1);
2044 SDValue NewSA = TLO.DAG.getConstant(Combined, dl, ShiftVT);
2045 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRA, dl, VT,
2046 Op0.getOperand(0), NewSA));
2047 }
2048 }
2049 }
2050
2051 APInt InDemandedMask = (DemandedBits << ShAmt);
2052
2053 // If the shift is exact, then it does demand the low bits (and knows that
2054 // they are zero).
2055 if (Op->getFlags().hasExact())
2056 InDemandedMask.setLowBits(ShAmt);
2057
2058 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2059 // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K))
2060 if ((BitWidth % 2) == 0 && !VT.isVector()) {
2062 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2);
2063 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2064 isTypeDesirableForOp(ISD::SRL, HalfVT) &&
2065 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2066 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) &&
2067 ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) ||
2068 TLO.DAG.MaskedValueIsZero(Op0, HiBits))) {
2069 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2070 SDValue NewShiftAmt =
2071 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2072 SDValue NewShift =
2073 TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt);
2074 return TLO.CombineTo(
2075 Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift));
2076 }
2077 }
2078
2079 // Compute the new bits that are at the top now.
2080 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2081 Depth + 1))
2082 return true;
2083 Known >>= ShAmt;
2084 // High bits known zero.
2085 Known.Zero.setHighBits(ShAmt);
2086
2087 // Attempt to avoid multi-use ops if we don't need anything from them.
2088 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2090 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2091 if (DemandedOp0) {
2092 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1);
2093 return TLO.CombineTo(Op, NewOp);
2094 }
2095 }
2096 } else {
2097 // Use generic knownbits computation as it has support for non-uniform
2098 // shift amounts.
2099 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2100 }
2101
2102 // If we are only demanding sign bits then we can use the shift source
2103 // directly.
2104 if (std::optional<unsigned> MaxSA =
2105 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2106 unsigned ShAmt = *MaxSA;
2107 // Must already be signbits in DemandedBits bounds, and can't demand any
2108 // shifted in zeroes.
2109 if (DemandedBits.countl_zero() >= ShAmt) {
2110 unsigned NumSignBits =
2111 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2112 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
2113 return TLO.CombineTo(Op, Op0);
2114 }
2115 }
2116
2117 // Try to match AVG patterns (after shift simplification).
2118 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2119 DemandedElts, Depth + 1))
2120 return TLO.CombineTo(Op, AVG);
2121
2122 break;
2123 }
2124 case ISD::SRA: {
2125 SDValue Op0 = Op.getOperand(0);
2126 SDValue Op1 = Op.getOperand(1);
2127 EVT ShiftVT = Op1.getValueType();
2128
2129 // If we only want bits that already match the signbit then we don't need
2130 // to shift.
2131 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero();
2132 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
2133 NumHiDemandedBits)
2134 return TLO.CombineTo(Op, Op0);
2135
2136 // If this is an arithmetic shift right and only the low-bit is set, we can
2137 // always convert this into a logical shr, even if the shift amount is
2138 // variable. The low bit of the shift cannot be an input sign bit unless
2139 // the shift amount is >= the size of the datatype, which is undefined.
2140 if (DemandedBits.isOne())
2141 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2142
2143 if (std::optional<unsigned> KnownSA =
2144 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2145 unsigned ShAmt = *KnownSA;
2146 if (ShAmt == 0)
2147 return TLO.CombineTo(Op, Op0);
2148
2149 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target
2150 // supports sext_inreg.
2151 if (Op0.getOpcode() == ISD::SHL) {
2152 if (std::optional<unsigned> InnerSA =
2153 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2154 unsigned LowBits = BitWidth - ShAmt;
2155 EVT ExtVT = VT.changeElementType(
2156 *TLO.DAG.getContext(),
2157 EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits));
2158
2159 if (*InnerSA == ShAmt) {
2160 if (!TLO.LegalOperations() ||
2162 return TLO.CombineTo(
2163 Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
2164 Op0.getOperand(0),
2165 TLO.DAG.getValueType(ExtVT)));
2166
2167 // Even if we can't convert to sext_inreg, we might be able to
2168 // remove this shift pair if the input is already sign extended.
2169 unsigned NumSignBits =
2170 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts);
2171 if (NumSignBits > ShAmt)
2172 return TLO.CombineTo(Op, Op0.getOperand(0));
2173 }
2174 }
2175 }
2176
2177 APInt InDemandedMask = (DemandedBits << ShAmt);
2178
2179 // If the shift is exact, then it does demand the low bits (and knows that
2180 // they are zero).
2181 if (Op->getFlags().hasExact())
2182 InDemandedMask.setLowBits(ShAmt);
2183
2184 // If any of the demanded bits are produced by the sign extension, we also
2185 // demand the input sign bit.
2186 if (DemandedBits.countl_zero() < ShAmt)
2187 InDemandedMask.setSignBit();
2188
2189 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2190 Depth + 1))
2191 return true;
2192 Known >>= ShAmt;
2193
2194 // If the input sign bit is known to be zero, or if none of the top bits
2195 // are demanded, turn this into an unsigned shift right.
2196 if (Known.Zero[BitWidth - ShAmt - 1] ||
2197 DemandedBits.countl_zero() >= ShAmt) {
2198 SDNodeFlags Flags;
2199 Flags.setExact(Op->getFlags().hasExact());
2200 return TLO.CombineTo(
2201 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
2202 }
2203
2204 int Log2 = DemandedBits.exactLogBase2();
2205 if (Log2 >= 0) {
2206 // The bit must come from the sign.
2207 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
2208 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
2209 }
2210
2211 if (Known.One[BitWidth - ShAmt - 1])
2212 // New bits are known one.
2213 Known.One.setHighBits(ShAmt);
2214
2215 // Attempt to avoid multi-use ops if we don't need anything from them.
2216 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2218 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2219 if (DemandedOp0) {
2220 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
2221 return TLO.CombineTo(Op, NewOp);
2222 }
2223 }
2224 }
2225
2226 // Try to match AVG patterns (after shift simplification).
2227 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2228 DemandedElts, Depth + 1))
2229 return TLO.CombineTo(Op, AVG);
2230
2231 break;
2232 }
2233 case ISD::FSHL:
2234 case ISD::FSHR: {
2235 SDValue Op0 = Op.getOperand(0);
2236 SDValue Op1 = Op.getOperand(1);
2237 SDValue Op2 = Op.getOperand(2);
2238 bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
2239
2240 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
2241 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2242
2243 // For fshl, 0-shift returns the 1st arg.
2244 // For fshr, 0-shift returns the 2nd arg.
2245 if (Amt == 0) {
2246 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
2247 Known, TLO, Depth + 1))
2248 return true;
2249 break;
2250 }
2251
2252 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
2253 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
2254 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
2255 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
2256 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2257 Depth + 1))
2258 return true;
2259 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
2260 Depth + 1))
2261 return true;
2262
2263 Known2 <<= (IsFSHL ? Amt : (BitWidth - Amt));
2264 Known >>= (IsFSHL ? (BitWidth - Amt) : Amt);
2265 Known = Known.unionWith(Known2);
2266
2267 // Attempt to avoid multi-use ops if we don't need anything from them.
2268 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
2269 !DemandedElts.isAllOnes()) {
2271 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
2273 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
2274 if (DemandedOp0 || DemandedOp1) {
2275 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
2276 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
2277 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
2278 DemandedOp1, Op2);
2279 return TLO.CombineTo(Op, NewOp);
2280 }
2281 }
2282 }
2283
2284 if (isPowerOf2_32(BitWidth)) {
2285 // Fold FSHR(Op0,Op1,Op2) -> SRL(Op1,Op2)
2286 // iff we're guaranteed not to use Op0.
2287 // TODO: Add FSHL equivalent?
2288 if (!IsFSHL && !DemandedBits.isAllOnes() &&
2289 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT))) {
2290 KnownBits KnownAmt =
2291 TLO.DAG.computeKnownBits(Op2, DemandedElts, Depth + 1);
2292 unsigned MaxShiftAmt =
2293 KnownAmt.getMaxValue().getLimitedValue(BitWidth - 1);
2294 // Check we don't demand any shifted bits outside Op1.
2295 if (DemandedBits.countl_zero() >= MaxShiftAmt) {
2296 EVT AmtVT = Op2.getValueType();
2297 SDValue NewAmt =
2298 TLO.DAG.getNode(ISD::AND, dl, AmtVT, Op2,
2299 TLO.DAG.getConstant(BitWidth - 1, dl, AmtVT));
2300 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, Op1, NewAmt);
2301 return TLO.CombineTo(Op, NewOp);
2302 }
2303 }
2304
2305 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2306 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
2307 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, Known2, TLO,
2308 Depth + 1))
2309 return true;
2310 }
2311 break;
2312 }
2313 case ISD::ROTL:
2314 case ISD::ROTR: {
2315 SDValue Op0 = Op.getOperand(0);
2316 SDValue Op1 = Op.getOperand(1);
2317 bool IsROTL = (Op.getOpcode() == ISD::ROTL);
2318
2319 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
2320 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
2321 return TLO.CombineTo(Op, Op0);
2322
2323 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
2324 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2325 unsigned RevAmt = BitWidth - Amt;
2326
2327 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
2328 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
2329 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
2330 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2331 Depth + 1))
2332 return true;
2333
2334 // rot*(x, 0) --> x
2335 if (Amt == 0)
2336 return TLO.CombineTo(Op, Op0);
2337
2338 // See if we don't demand either half of the rotated bits.
2339 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
2340 DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) {
2341 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
2342 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
2343 }
2344 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
2345 DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) {
2346 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
2347 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2348 }
2349 }
2350
2351 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2352 if (isPowerOf2_32(BitWidth)) {
2353 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
2354 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
2355 Depth + 1))
2356 return true;
2357 }
2358 break;
2359 }
2360 case ISD::SMIN:
2361 case ISD::SMAX:
2362 case ISD::UMIN:
2363 case ISD::UMAX: {
2364 unsigned Opc = Op.getOpcode();
2365 SDValue Op0 = Op.getOperand(0);
2366 SDValue Op1 = Op.getOperand(1);
2367
2368 // If we're only demanding signbits, then we can simplify to OR/AND node.
2369 unsigned BitOp =
2370 (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND;
2371 unsigned NumSignBits =
2372 std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1),
2373 TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1));
2374 unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero();
2375 if (NumSignBits >= NumDemandedUpperBits)
2376 return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1));
2377
2378 // Check if one arg is always less/greater than (or equal) to the other arg.
2379 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2380 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2381 switch (Opc) {
2382 case ISD::SMIN:
2383 if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1))
2384 return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1);
2385 if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1))
2386 return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1);
2387 Known = KnownBits::smin(Known0, Known1);
2388 break;
2389 case ISD::SMAX:
2390 if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1))
2391 return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1);
2392 if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1))
2393 return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1);
2394 Known = KnownBits::smax(Known0, Known1);
2395 break;
2396 case ISD::UMIN:
2397 if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1))
2398 return TLO.CombineTo(Op, *IsULE ? Op0 : Op1);
2399 if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1))
2400 return TLO.CombineTo(Op, *IsULT ? Op0 : Op1);
2401 Known = KnownBits::umin(Known0, Known1);
2402 break;
2403 case ISD::UMAX:
2404 if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
2405 return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1);
2406 if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
2407 return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1);
2408 Known = KnownBits::umax(Known0, Known1);
2409 break;
2410 }
2411 break;
2412 }
2413 case ISD::BITREVERSE: {
2414 SDValue Src = Op.getOperand(0);
2415 APInt DemandedSrcBits = DemandedBits.reverseBits();
2416 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2417 Depth + 1))
2418 return true;
2419 Known = Known2.reverseBits();
2420 break;
2421 }
2422 case ISD::BSWAP: {
2423 SDValue Src = Op.getOperand(0);
2424
2425 // If the only bits demanded come from one byte of the bswap result,
2426 // just shift the input byte into position to eliminate the bswap.
2427 unsigned NLZ = DemandedBits.countl_zero();
2428 unsigned NTZ = DemandedBits.countr_zero();
2429
2430 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
2431 // we need all the bits down to bit 8. Likewise, round NLZ. If we
2432 // have 14 leading zeros, round to 8.
2433 NLZ = alignDown(NLZ, 8);
2434 NTZ = alignDown(NTZ, 8);
2435 // If we need exactly one byte, we can do this transformation.
2436 if (BitWidth - NLZ - NTZ == 8) {
2437 // Replace this with either a left or right shift to get the byte into
2438 // the right place.
2439 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2440 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2441 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2442 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
2443 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2444 return TLO.CombineTo(Op, NewOp);
2445 }
2446 }
2447
2448 APInt DemandedSrcBits = DemandedBits.byteSwap();
2449 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2450 Depth + 1))
2451 return true;
2452 Known = Known2.byteSwap();
2453 break;
2454 }
2455 case ISD::CTPOP: {
2456 // If only 1 bit is demanded, replace with PARITY as long as we're before
2457 // op legalization.
2458 // FIXME: Limit to scalars for now.
2459 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2460 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2461 Op.getOperand(0)));
2462
2463 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2464 break;
2465 }
2466 case ISD::PDEP: {
2467 SDValue Op0 = Op.getOperand(0);
2468 SDValue Op1 = Op.getOperand(1);
2469
2470 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
2471 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2472
2473 // If the demanded bits has leading zeroes, we don't demand those from the
2474 // mask.
2475 if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
2476 return true;
2477
2478 // The number of possible 1s in the mask determines the number of LSBs of
2479 // operand 0 used. Undemanded bits from the mask don't matter so filter
2480 // them before counting.
2481 KnownBits Known2;
2482 uint64_t Count = (~Known.Zero & LoMask).popcount();
2483 APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
2484 if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
2485 return true;
2486
2487 // Zeroes are retained from the mask, but not ones.
2488 Known.One.clearAllBits();
2489 // The result will have at least as many trailing zeros as the non-mask
2490 // operand since bits can only map to the same or higher bit position.
2491 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
2492 break;
2493 }
2495 SDValue Op0 = Op.getOperand(0);
2496 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2497 unsigned ExVTBits = ExVT.getScalarSizeInBits();
2498
2499 // If we only care about the highest bit, don't bother shifting right.
2500 if (DemandedBits.isSignMask()) {
2501 unsigned MinSignedBits =
2502 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2503 bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2504 // However if the input is already sign extended we expect the sign
2505 // extension to be dropped altogether later and do not simplify.
2506 if (!AlreadySignExtended) {
2507 // Compute the correct shift amount type, which must be getShiftAmountTy
2508 // for scalar types after legalization.
2509 SDValue ShiftAmt =
2510 TLO.DAG.getShiftAmountConstant(BitWidth - ExVTBits, VT, dl);
2511 return TLO.CombineTo(Op,
2512 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2513 }
2514 }
2515
2516 // If none of the extended bits are demanded, eliminate the sextinreg.
2517 if (DemandedBits.getActiveBits() <= ExVTBits)
2518 return TLO.CombineTo(Op, Op0);
2519
2520 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2521
2522 // Since the sign extended bits are demanded, we know that the sign
2523 // bit is demanded.
2524 InputDemandedBits.setBit(ExVTBits - 1);
2525
2526 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2527 Depth + 1))
2528 return true;
2529
2530 // If the sign bit of the input is known set or clear, then we know the
2531 // top bits of the result.
2532
2533 // If the input sign bit is known zero, convert this into a zero extension.
2534 if (Known.Zero[ExVTBits - 1])
2535 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2536
2537 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2538 if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2539 Known.One.setBitsFrom(ExVTBits);
2540 Known.Zero &= Mask;
2541 } else { // Input sign bit unknown
2542 Known.Zero &= Mask;
2543 Known.One &= Mask;
2544 }
2545 break;
2546 }
2547 case ISD::BUILD_PAIR: {
2548 EVT HalfVT = Op.getOperand(0).getValueType();
2549 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2550
2551 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2552 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2553
2554 KnownBits KnownLo, KnownHi;
2555
2556 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2557 return true;
2558
2559 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2560 return true;
2561
2562 Known = KnownHi.concat(KnownLo);
2563 break;
2564 }
2566 if (VT.isScalableVector())
2567 return false;
2568 [[fallthrough]];
2569 case ISD::ZERO_EXTEND: {
2570 SDValue Src = Op.getOperand(0);
2571 EVT SrcVT = Src.getValueType();
2572 unsigned InBits = SrcVT.getScalarSizeInBits();
2573 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2574 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2575
2576 // If none of the top bits are demanded, convert this into an any_extend.
2577 if (DemandedBits.getActiveBits() <= InBits) {
2578 // If we only need the non-extended bits of the bottom element
2579 // then we can just bitcast to the result.
2580 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2581 VT.getSizeInBits() == SrcVT.getSizeInBits())
2582 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2583
2584 unsigned Opc =
2586 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2587 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2588 }
2589
2590 APInt InDemandedBits = DemandedBits.trunc(InBits);
2591 APInt InDemandedElts = DemandedElts.zext(InElts);
2592 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2593 Depth + 1)) {
2594 Op->dropFlags(SDNodeFlags::NonNeg);
2595 return true;
2596 }
2597 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2598 Known = Known.zext(BitWidth);
2599
2600 // Attempt to avoid multi-use ops if we don't need anything from them.
2602 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2603 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2604 break;
2605 }
2607 if (VT.isScalableVector())
2608 return false;
2609 [[fallthrough]];
2610 case ISD::SIGN_EXTEND: {
2611 SDValue Src = Op.getOperand(0);
2612 EVT SrcVT = Src.getValueType();
2613 unsigned InBits = SrcVT.getScalarSizeInBits();
2614 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2615 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2616
2617 APInt InDemandedElts = DemandedElts.zext(InElts);
2618 APInt InDemandedBits = DemandedBits.trunc(InBits);
2619
2620 // Since some of the sign extended bits are demanded, we know that the sign
2621 // bit is demanded.
2622 InDemandedBits.setBit(InBits - 1);
2623
2624 // If none of the top bits are demanded, convert this into an any_extend.
2625 if (DemandedBits.getActiveBits() <= InBits) {
2626 // If we only need the non-extended bits of the bottom element
2627 // then we can just bitcast to the result.
2628 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2629 VT.getSizeInBits() == SrcVT.getSizeInBits())
2630 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2631
2632 // Don't lose an all signbits 0/-1 splat on targets with 0/-1 booleans.
2634 TLO.DAG.ComputeNumSignBits(Src, InDemandedElts, Depth + 1) !=
2635 InBits) {
2636 unsigned Opc =
2638 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2639 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2640 }
2641 }
2642
2643 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2644 Depth + 1))
2645 return true;
2646 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2647
2648 // If the sign bit is known one, the top bits match.
2649 Known = Known.sext(BitWidth);
2650
2651 // If the sign bit is known zero, convert this to a zero extend.
2652 if (Known.isNonNegative()) {
2653 unsigned Opc =
2655 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) {
2656 SDNodeFlags Flags;
2657 if (!IsVecInReg)
2658 Flags |= SDNodeFlags::NonNeg;
2659 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src, Flags));
2660 }
2661 }
2662
2663 // Attempt to avoid multi-use ops if we don't need anything from them.
2665 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2666 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2667 break;
2668 }
2670 if (VT.isScalableVector())
2671 return false;
2672 [[fallthrough]];
2673 case ISD::ANY_EXTEND: {
2674 SDValue Src = Op.getOperand(0);
2675 EVT SrcVT = Src.getValueType();
2676 unsigned InBits = SrcVT.getScalarSizeInBits();
2677 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2678 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2679
2680 // If we only need the bottom element then we can just bitcast.
2681 // TODO: Handle ANY_EXTEND?
2682 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2683 VT.getSizeInBits() == SrcVT.getSizeInBits())
2684 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2685
2686 APInt InDemandedBits = DemandedBits.trunc(InBits);
2687 APInt InDemandedElts = DemandedElts.zext(InElts);
2688 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2689 Depth + 1))
2690 return true;
2691 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2692 Known = Known.anyext(BitWidth);
2693
2694 // Attempt to avoid multi-use ops if we don't need anything from them.
2696 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2697 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2698 break;
2699 }
2700 case ISD::TRUNCATE: {
2701 SDValue Src = Op.getOperand(0);
2702
2703 // Simplify the input, using demanded bit information, and compute the known
2704 // zero/one bits live out.
2705 unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2706 APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2707 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2708 Depth + 1)) {
2709 // Disable the nsw and nuw flags. We can no longer guarantee that we
2710 // won't wrap after simplification.
2711 Op->dropFlags(SDNodeFlags::NoWrap);
2712 return true;
2713 }
2714 Known = Known.trunc(BitWidth);
2715
2716 // Attempt to avoid multi-use ops if we don't need anything from them.
2718 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2719 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2720
2721 // If the input is only used by this truncate, see if we can shrink it based
2722 // on the known demanded bits.
2723 switch (Src.getOpcode()) {
2724 default:
2725 break;
2726 case ISD::SRL:
2727 // Shrink SRL by a constant if none of the high bits shifted in are
2728 // demanded.
2729 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2730 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2731 // undesirable.
2732 break;
2733
2734 if (Src.getNode()->hasOneUse()) {
2735 if (isTruncateFree(Src, VT) &&
2736 !isTruncateFree(Src.getValueType(), VT)) {
2737 // If truncate is only free at trunc(srl), do not turn it into
2738 // srl(trunc). The check is done by first check the truncate is free
2739 // at Src's opcode(srl), then check the truncate is not done by
2740 // referencing sub-register. In test, if both trunc(srl) and
2741 // srl(trunc)'s trunc are free, srl(trunc) performs better. If only
2742 // trunc(srl)'s trunc is free, trunc(srl) is better.
2743 break;
2744 }
2745
2746 std::optional<unsigned> ShAmtC =
2747 TLO.DAG.getValidShiftAmount(Src, DemandedElts, Depth + 2);
2748 if (!ShAmtC || *ShAmtC >= BitWidth)
2749 break;
2750 unsigned ShVal = *ShAmtC;
2751
2752 APInt HighBits =
2753 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2754 HighBits.lshrInPlace(ShVal);
2755 HighBits = HighBits.trunc(BitWidth);
2756 if (!(HighBits & DemandedBits)) {
2757 // None of the shifted in bits are needed. Add a truncate of the
2758 // shift input, then shift it.
2759 SDValue NewShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
2760 SDValue NewTrunc =
2761 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2762 return TLO.CombineTo(
2763 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2764 }
2765 }
2766 break;
2767 }
2768
2769 break;
2770 }
2771 case ISD::AssertZext: {
2772 // AssertZext demands all of the high bits, plus any of the low bits
2773 // demanded by its users.
2774 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2776 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2777 TLO, Depth + 1))
2778 return true;
2779
2780 Known.Zero |= ~InMask;
2781 Known.One &= (~Known.Zero);
2782 break;
2783 }
2785 SDValue Src = Op.getOperand(0);
2786 SDValue Idx = Op.getOperand(1);
2787 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2788 unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2789
2790 if (SrcEltCnt.isScalable())
2791 return false;
2792
2793 // Demand the bits from every vector element without a constant index.
2794 unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2795 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
2796 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2797 if (CIdx->getAPIntValue().ult(NumSrcElts))
2798 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2799
2800 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2801 // anything about the extended bits.
2802 APInt DemandedSrcBits = DemandedBits;
2803 if (BitWidth > EltBitWidth)
2804 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2805
2806 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2807 Depth + 1))
2808 return true;
2809
2810 // Attempt to avoid multi-use ops if we don't need anything from them.
2811 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2812 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2813 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2814 SDValue NewOp =
2815 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2816 return TLO.CombineTo(Op, NewOp);
2817 }
2818 }
2819
2820 Known = Known2;
2821 if (BitWidth > EltBitWidth)
2822 Known = Known.anyext(BitWidth);
2823 break;
2824 }
2825 case ISD::BITCAST: {
2826 if (VT.isScalableVector())
2827 return false;
2828 SDValue Src = Op.getOperand(0);
2829 EVT SrcVT = Src.getValueType();
2830 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
2831
2832 // If this is an FP->Int bitcast and if the sign bit is the only
2833 // thing demanded, turn this into a FGETSIGN.
2834 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
2835 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
2836 SrcVT.isFloatingPoint()) {
2838 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2839 // place. We expect the SHL to be eliminated by other optimizations.
2840 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, VT, Src);
2841 unsigned ShVal = Op.getValueSizeInBits() - 1;
2842 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
2843 return TLO.CombineTo(Op,
2844 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
2845 }
2846 }
2847
2848 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
2849 // Demand the elt/bit if any of the original elts/bits are demanded.
2850 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
2851 unsigned Scale = BitWidth / NumSrcEltBits;
2852 unsigned NumSrcElts = SrcVT.getVectorNumElements();
2853 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2854 for (unsigned i = 0; i != Scale; ++i) {
2855 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
2856 unsigned BitOffset = EltOffset * NumSrcEltBits;
2857 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
2858 }
2859 // Recursive calls below may turn not demanded elements into poison, so we
2860 // need to demand all smaller source elements that maps to a demanded
2861 // destination element.
2862 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2863
2864 APInt KnownSrcUndef, KnownSrcZero;
2865 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2866 KnownSrcZero, TLO, Depth + 1))
2867 return true;
2868
2869 KnownBits KnownSrcBits;
2870 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2871 KnownSrcBits, TLO, Depth + 1))
2872 return true;
2873 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
2874 // TODO - bigendian once we have test coverage.
2875 unsigned Scale = NumSrcEltBits / BitWidth;
2876 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2877 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2878 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2879 for (unsigned i = 0; i != NumElts; ++i)
2880 if (DemandedElts[i]) {
2881 unsigned Offset = (i % Scale) * BitWidth;
2882 DemandedSrcBits.insertBits(DemandedBits, Offset);
2883 DemandedSrcElts.setBit(i / Scale);
2884 }
2885
2886 if (SrcVT.isVector()) {
2887 APInt KnownSrcUndef, KnownSrcZero;
2888 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2889 KnownSrcZero, TLO, Depth + 1))
2890 return true;
2891 }
2892
2893 KnownBits KnownSrcBits;
2894 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2895 KnownSrcBits, TLO, Depth + 1))
2896 return true;
2897
2898 // Attempt to avoid multi-use ops if we don't need anything from them.
2899 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2900 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2901 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2902 SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc);
2903 return TLO.CombineTo(Op, NewOp);
2904 }
2905 }
2906 }
2907
2908 // If this is a bitcast, let computeKnownBits handle it. Only do this on a
2909 // recursive call where Known may be useful to the caller.
2910 if (Depth > 0) {
2911 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2912 return false;
2913 }
2914 break;
2915 }
2916 case ISD::MUL:
2917 if (DemandedBits.isPowerOf2()) {
2918 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
2919 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
2920 // odd (has LSB set), then the left-shifted low bit of X is the answer.
2921 unsigned CTZ = DemandedBits.countr_zero();
2922 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
2923 if (C && C->getAPIntValue().countr_zero() == CTZ) {
2924 SDValue AmtC = TLO.DAG.getShiftAmountConstant(CTZ, VT, dl);
2925 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
2926 return TLO.CombineTo(Op, Shl);
2927 }
2928 }
2929 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
2930 // X * X is odd iff X is odd.
2931 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
2932 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
2933 SDValue One = TLO.DAG.getConstant(1, dl, VT);
2934 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
2935 return TLO.CombineTo(Op, And1);
2936 }
2937 [[fallthrough]];
2938 case ISD::PTRADD:
2939 if (Op.getOperand(0).getValueType() != Op.getOperand(1).getValueType())
2940 break;
2941 // PTRADD behaves like ADD if pointers are represented as integers.
2942 [[fallthrough]];
2943 case ISD::ADD:
2944 case ISD::SUB: {
2945 // Add, Sub, and Mul don't demand any bits in positions beyond that
2946 // of the highest bit demanded of them.
2947 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
2948 SDNodeFlags Flags = Op.getNode()->getFlags();
2949 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
2950 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2951 KnownBits KnownOp0, KnownOp1;
2952 auto GetDemandedBitsLHSMask = [&](APInt Demanded,
2953 const KnownBits &KnownRHS) {
2954 if (Op.getOpcode() == ISD::MUL)
2955 Demanded.clearHighBits(KnownRHS.countMinTrailingZeros());
2956 return Demanded;
2957 };
2958 if (SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO,
2959 Depth + 1) ||
2960 SimplifyDemandedBits(Op0, GetDemandedBitsLHSMask(LoMask, KnownOp1),
2961 DemandedElts, KnownOp0, TLO, Depth + 1) ||
2962 // See if the operation should be performed at a smaller bit width.
2964 // Disable the nsw and nuw flags. We can no longer guarantee that we
2965 // won't wrap after simplification.
2966 Op->dropFlags(SDNodeFlags::NoWrap);
2967 return true;
2968 }
2969
2970 // neg x with only low bit demanded is simply x.
2971 if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() &&
2972 isNullConstant(Op0))
2973 return TLO.CombineTo(Op, Op1);
2974
2975 // Attempt to avoid multi-use ops if we don't need anything from them.
2976 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2978 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2980 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2981 if (DemandedOp0 || DemandedOp1) {
2982 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
2983 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
2984 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1,
2985 Flags & ~SDNodeFlags::NoWrap);
2986 return TLO.CombineTo(Op, NewOp);
2987 }
2988 }
2989
2990 // If we have a constant operand, we may be able to turn it into -1 if we
2991 // do not demand the high bits. This can make the constant smaller to
2992 // encode, allow more general folding, or match specialized instruction
2993 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
2994 // is probably not useful (and could be detrimental).
2996 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
2997 if (C && !C->isAllOnes() && !C->isOne() &&
2998 (C->getAPIntValue() | HighMask).isAllOnes()) {
2999 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
3000 // Disable the nsw and nuw flags. We can no longer guarantee that we
3001 // won't wrap after simplification.
3002 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1,
3003 Flags & ~SDNodeFlags::NoWrap);
3004 return TLO.CombineTo(Op, NewOp);
3005 }
3006
3007 // Match a multiply with a disguised negated-power-of-2 and convert to a
3008 // an equivalent shift-left amount.
3009 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3010 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
3011 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
3012 return 0;
3013
3014 // Don't touch opaque constants. Also, ignore zero and power-of-2
3015 // multiplies. Those will get folded later.
3016 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
3017 if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
3018 !MulC->getAPIntValue().isPowerOf2()) {
3019 APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
3020 if (UnmaskedC.isNegatedPowerOf2())
3021 return (-UnmaskedC).logBase2();
3022 }
3023 return 0;
3024 };
3025
3026 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y,
3027 unsigned ShlAmt) {
3028 SDValue ShlAmtC = TLO.DAG.getShiftAmountConstant(ShlAmt, VT, dl);
3029 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
3030 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
3031 return TLO.CombineTo(Op, Res);
3032 };
3033
3035 if (Op.getOpcode() == ISD::ADD) {
3036 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3037 if (unsigned ShAmt = getShiftLeftAmt(Op0))
3038 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
3039 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
3040 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3041 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
3042 }
3043 if (Op.getOpcode() == ISD::SUB) {
3044 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
3045 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3046 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
3047 }
3048 }
3049
3050 if (Op.getOpcode() == ISD::MUL) {
3051 Known = KnownBits::mul(KnownOp0, KnownOp1);
3052 } else { // Op.getOpcode() is either ISD::ADD, ISD::PTRADD, or ISD::SUB.
3054 Op.getOpcode() != ISD::SUB, Flags.hasNoSignedWrap(),
3055 Flags.hasNoUnsignedWrap(), KnownOp0, KnownOp1);
3056 }
3057 break;
3058 }
3059 case ISD::FABS: {
3060 SDValue Op0 = Op.getOperand(0);
3061 APInt SignMask = APInt::getSignMask(BitWidth);
3062
3063 if (!DemandedBits.intersects(SignMask))
3064 return TLO.CombineTo(Op, Op0);
3065
3066 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3067 Depth + 1))
3068 return true;
3069
3070 if (Known.isNonNegative())
3071 return TLO.CombineTo(Op, Op0);
3072 if (Known.isNegative())
3073 return TLO.CombineTo(
3074 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT, Op0, Op->getFlags()));
3075
3076 Known.Zero |= SignMask;
3077 Known.One &= ~SignMask;
3078
3079 break;
3080 }
3081 case ISD::FCOPYSIGN: {
3082 SDValue Op0 = Op.getOperand(0);
3083 SDValue Op1 = Op.getOperand(1);
3084
3085 unsigned BitWidth0 = Op0.getScalarValueSizeInBits();
3086 unsigned BitWidth1 = Op1.getScalarValueSizeInBits();
3087 APInt SignMask0 = APInt::getSignMask(BitWidth0);
3088 APInt SignMask1 = APInt::getSignMask(BitWidth1);
3089
3090 if (!DemandedBits.intersects(SignMask0))
3091 return TLO.CombineTo(Op, Op0);
3092
3093 if (SimplifyDemandedBits(Op0, ~SignMask0 & DemandedBits, DemandedElts,
3094 Known, TLO, Depth + 1) ||
3095 SimplifyDemandedBits(Op1, SignMask1, DemandedElts, Known2, TLO,
3096 Depth + 1))
3097 return true;
3098
3099 if (Known2.isNonNegative())
3100 return TLO.CombineTo(
3101 Op, TLO.DAG.getNode(ISD::FABS, dl, VT, Op0, Op->getFlags()));
3102
3103 if (Known2.isNegative())
3104 return TLO.CombineTo(
3105 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT,
3106 TLO.DAG.getNode(ISD::FABS, SDLoc(Op0), VT, Op0)));
3107
3108 Known.Zero &= ~SignMask0;
3109 Known.One &= ~SignMask0;
3110 break;
3111 }
3112 case ISD::FNEG: {
3113 SDValue Op0 = Op.getOperand(0);
3114 APInt SignMask = APInt::getSignMask(BitWidth);
3115
3116 if (!DemandedBits.intersects(SignMask))
3117 return TLO.CombineTo(Op, Op0);
3118
3119 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3120 Depth + 1))
3121 return true;
3122
3123 if (!Known.isSignUnknown()) {
3124 Known.Zero ^= SignMask;
3125 Known.One ^= SignMask;
3126 }
3127
3128 break;
3129 }
3130 default:
3131 // We also ask the target about intrinsics (which could be specific to it).
3132 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3133 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
3134 // TODO: Probably okay to remove after audit; here to reduce change size
3135 // in initial enablement patch for scalable vectors
3136 if (Op.getValueType().isScalableVector())
3137 break;
3139 Known, TLO, Depth))
3140 return true;
3141 break;
3142 }
3143
3144 // Just use computeKnownBits to compute output bits.
3145 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3146 break;
3147 }
3148
3149 // If we know the value of all of the demanded bits, return this as a
3150 // constant.
3152 DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
3153 // Avoid folding to a constant if any OpaqueConstant is involved.
3154 if (llvm::any_of(Op->ops(), [](SDValue V) {
3155 auto *C = dyn_cast<ConstantSDNode>(V);
3156 return C && C->isOpaque();
3157 }))
3158 return false;
3159 if (VT.isInteger())
3160 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
3161 if (VT.isFloatingPoint())
3162 return TLO.CombineTo(
3164 dl, VT));
3165 }
3166
3167 // A multi use 'all demanded elts' simplify failed to find any knownbits.
3168 // Try again just for the original demanded elts.
3169 // Ensure we do this AFTER constant folding above.
3170 if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes())
3171 Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth);
3172
3173 return false;
3174}
3175
3177 const APInt &DemandedElts,
3178 DAGCombinerInfo &DCI) const {
3179 SelectionDAG &DAG = DCI.DAG;
3180 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3181 !DCI.isBeforeLegalizeOps());
3182
3183 APInt KnownUndef, KnownZero;
3184 bool Simplified =
3185 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
3186 if (Simplified) {
3187 DCI.AddToWorklist(Op.getNode());
3188 DCI.CommitTargetLoweringOpt(TLO);
3189 }
3190
3191 return Simplified;
3192}
3193
3194/// Given a vector binary operation and known undefined elements for each input
3195/// operand, compute whether each element of the output is undefined.
3197 const APInt &UndefOp0,
3198 const APInt &UndefOp1) {
3199 EVT VT = BO.getValueType();
3201 "Vector binop only");
3202
3203 EVT EltVT = VT.getVectorElementType();
3204 unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1;
3205 assert(UndefOp0.getBitWidth() == NumElts &&
3206 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
3207
3208 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
3209 const APInt &UndefVals) {
3210 if (UndefVals[Index])
3211 return DAG.getUNDEF(EltVT);
3212
3213 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
3214 // Try hard to make sure that the getNode() call is not creating temporary
3215 // nodes. Ignore opaque integers because they do not constant fold.
3216 SDValue Elt = BV->getOperand(Index);
3217 auto *C = dyn_cast<ConstantSDNode>(Elt);
3218 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
3219 return Elt;
3220 }
3221
3222 return SDValue();
3223 };
3224
3225 APInt KnownUndef = APInt::getZero(NumElts);
3226 for (unsigned i = 0; i != NumElts; ++i) {
3227 // If both inputs for this element are either constant or undef and match
3228 // the element type, compute the constant/undef result for this element of
3229 // the vector.
3230 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
3231 // not handle FP constants. The code within getNode() should be refactored
3232 // to avoid the danger of creating a bogus temporary node here.
3233 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
3234 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
3235 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
3236 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
3237 KnownUndef.setBit(i);
3238 }
3239 return KnownUndef;
3240}
3241
3243 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
3244 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
3245 bool AssumeSingleUse) const {
3246 EVT VT = Op.getValueType();
3247 unsigned Opcode = Op.getOpcode();
3248 APInt DemandedElts = OriginalDemandedElts;
3249 unsigned NumElts = DemandedElts.getBitWidth();
3250 assert(VT.isVector() && "Expected vector op");
3251
3252 KnownUndef = KnownZero = APInt::getZero(NumElts);
3253
3255 return false;
3256
3257 // TODO: For now we assume we know nothing about scalable vectors.
3258 if (VT.isScalableVector())
3259 return false;
3260
3261 assert(VT.getVectorNumElements() == NumElts &&
3262 "Mask size mismatches value type element count!");
3263
3264 // Undef operand.
3265 if (Op.isUndef()) {
3266 KnownUndef.setAllBits();
3267 return false;
3268 }
3269
3270 // If Op has other users, assume that all elements are needed.
3271 if (!AssumeSingleUse && !Op.getNode()->hasOneUse())
3272 DemandedElts.setAllBits();
3273
3274 // Not demanding any elements from Op.
3275 if (DemandedElts == 0) {
3276 KnownUndef.setAllBits();
3277 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3278 }
3279
3280 // Limit search depth.
3282 return false;
3283
3284 SDLoc DL(Op);
3285 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3286 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
3287
3288 auto TryShrinkBinOp = [&](SDValue Op0, SDValue Op1) {
3289 unsigned ShrunkSize = getPreferredShrunkVectorSizeInBits(Op, DemandedElts);
3290 if (!ShrunkSize)
3291 return false;
3292
3293 assert(ShrunkSize % EltSizeInBits == 0 &&
3294 "Shrunk size not a multiple of element size");
3295 assert(ShrunkSize < VT.getSizeInBits() &&
3296 "Shrunk size must be < original vector size");
3297 assert(ShrunkSize >= EltSizeInBits * DemandedElts.getActiveBits() &&
3298 "Shrunk size must be >= demanded size");
3299
3300 EVT ShrunkVT = VT.changeVectorElementCount(
3301 *TLO.DAG.getContext(),
3302 ElementCount::getFixed(ShrunkSize / EltSizeInBits));
3303 Op0 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op0, 0);
3304 Op1 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op1, 0);
3305 SDValue NewOp =
3306 TLO.DAG.getNode(Opcode, DL, ShrunkVT, Op0, Op1, Op->getFlags());
3307 return TLO.CombineTo(
3308 Op, TLO.DAG.getInsertSubvector(DL, TLO.DAG.getUNDEF(VT), NewOp, 0));
3309 };
3310
3311 // Helper for demanding the specified elements and all the bits of both binary
3312 // operands.
3313 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
3314 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
3315 TLO.DAG, Depth + 1);
3316 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
3317 TLO.DAG, Depth + 1);
3318 if (NewOp0 || NewOp1) {
3319 SDValue NewOp =
3320 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0,
3321 NewOp1 ? NewOp1 : Op1, Op->getFlags());
3322 return TLO.CombineTo(Op, NewOp);
3323 }
3324
3325 if (TryShrinkBinOp(Op0, Op1))
3326 return true;
3327
3328 return false;
3329 };
3330
3331 switch (Opcode) {
3332 case ISD::SCALAR_TO_VECTOR: {
3333 if (!DemandedElts[0]) {
3334 KnownUndef.setAllBits();
3335 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3336 }
3337 KnownUndef.setHighBits(NumElts - 1);
3338 break;
3339 }
3340 case ISD::BITCAST: {
3341 SDValue Src = Op.getOperand(0);
3342 EVT SrcVT = Src.getValueType();
3343
3344 if (!SrcVT.isVector()) {
3345 // TODO - bigendian once we have test coverage.
3346 if (IsLE) {
3347 APInt DemandedSrcBits = APInt::getZero(SrcVT.getSizeInBits());
3348 unsigned EltSize = VT.getScalarSizeInBits();
3349 for (unsigned I = 0; I != NumElts; ++I) {
3350 if (DemandedElts[I]) {
3351 unsigned Offset = I * EltSize;
3352 DemandedSrcBits.setBits(Offset, Offset + EltSize);
3353 }
3354 }
3356 if (SimplifyDemandedBits(Src, DemandedSrcBits, Known, TLO, Depth + 1))
3357 return true;
3358 }
3359 break;
3360 }
3361
3362 // Fast handling of 'identity' bitcasts.
3363 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3364 if (NumSrcElts == NumElts)
3365 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
3366 KnownZero, TLO, Depth + 1);
3367
3368 APInt SrcDemandedElts, SrcZero, SrcUndef;
3369
3370 // Bitcast from 'large element' src vector to 'small element' vector, we
3371 // must demand a source element if any DemandedElt maps to it.
3372 if ((NumElts % NumSrcElts) == 0) {
3373 unsigned Scale = NumElts / NumSrcElts;
3374 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3375 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3376 TLO, Depth + 1))
3377 return true;
3378
3379 // Try calling SimplifyDemandedBits, converting demanded elts to the bits
3380 // of the large element.
3381 // TODO - bigendian once we have test coverage.
3382 if (IsLE) {
3383 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
3384 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
3385 for (unsigned i = 0; i != NumElts; ++i)
3386 if (DemandedElts[i]) {
3387 unsigned Ofs = (i % Scale) * EltSizeInBits;
3388 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
3389 }
3390
3392 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
3393 TLO, Depth + 1))
3394 return true;
3395
3396 // The bitcast has split each wide element into a number of
3397 // narrow subelements. We have just computed the Known bits
3398 // for wide elements. See if element splitting results in
3399 // some subelements being zero. Only for demanded elements!
3400 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
3401 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
3402 .isAllOnes())
3403 continue;
3404 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
3405 unsigned Elt = Scale * SrcElt + SubElt;
3406 if (DemandedElts[Elt])
3407 KnownZero.setBit(Elt);
3408 }
3409 }
3410 }
3411
3412 // If the src element is zero/undef then all the output elements will be -
3413 // only demanded elements are guaranteed to be correct.
3414 for (unsigned i = 0; i != NumSrcElts; ++i) {
3415 if (SrcDemandedElts[i]) {
3416 if (SrcZero[i])
3417 KnownZero.setBits(i * Scale, (i + 1) * Scale);
3418 if (SrcUndef[i])
3419 KnownUndef.setBits(i * Scale, (i + 1) * Scale);
3420 }
3421 }
3422 }
3423
3424 // Bitcast from 'small element' src vector to 'large element' vector, we
3425 // demand all smaller source elements covered by the larger demanded element
3426 // of this vector.
3427 if ((NumSrcElts % NumElts) == 0) {
3428 unsigned Scale = NumSrcElts / NumElts;
3429 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3430 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3431 TLO, Depth + 1))
3432 return true;
3433
3434 // If all the src elements covering an output element are zero/undef, then
3435 // the output element will be as well, assuming it was demanded.
3436 for (unsigned i = 0; i != NumElts; ++i) {
3437 if (DemandedElts[i]) {
3438 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
3439 KnownZero.setBit(i);
3440 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
3441 KnownUndef.setBit(i);
3442 }
3443 }
3444 }
3445 break;
3446 }
3447 case ISD::FREEZE: {
3448 SDValue N0 = Op.getOperand(0);
3450 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
3451 return TLO.CombineTo(Op, N0);
3452
3453 // TODO: Replace this with the general fold from DAGCombiner::visitFREEZE
3454 // freeze(op(x, ...)) -> op(freeze(x), ...).
3455 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && DemandedElts == 1)
3456 return TLO.CombineTo(
3458 TLO.DAG.getFreeze(N0.getOperand(0))));
3459 break;
3460 }
3461 case ISD::BUILD_VECTOR: {
3462 // Check all elements and simplify any unused elements with UNDEF.
3463 if (!DemandedElts.isAllOnes()) {
3464 // Don't simplify BROADCASTS.
3465 if (llvm::any_of(Op->op_values(),
3466 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
3468 bool Updated = false;
3469 for (unsigned i = 0; i != NumElts; ++i) {
3470 if (!DemandedElts[i] && !Ops[i].isUndef()) {
3471 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
3472 KnownUndef.setBit(i);
3473 Updated = true;
3474 }
3475 }
3476 if (Updated)
3477 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
3478 }
3479 }
3480 for (unsigned i = 0; i != NumElts; ++i) {
3481 SDValue SrcOp = Op.getOperand(i);
3482 if (SrcOp.isUndef()) {
3483 KnownUndef.setBit(i);
3484 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
3486 KnownZero.setBit(i);
3487 }
3488 }
3489 break;
3490 }
3491 case ISD::CONCAT_VECTORS: {
3492 EVT SubVT = Op.getOperand(0).getValueType();
3493 unsigned NumSubVecs = Op.getNumOperands();
3494 unsigned NumSubElts = SubVT.getVectorNumElements();
3495 for (unsigned i = 0; i != NumSubVecs; ++i) {
3496 SDValue SubOp = Op.getOperand(i);
3497 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3498 APInt SubUndef, SubZero;
3499 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
3500 Depth + 1))
3501 return true;
3502 KnownUndef.insertBits(SubUndef, i * NumSubElts);
3503 KnownZero.insertBits(SubZero, i * NumSubElts);
3504 }
3505
3506 // Attempt to avoid multi-use ops if we don't need anything from them.
3507 if (!DemandedElts.isAllOnes()) {
3508 bool FoundNewSub = false;
3509 SmallVector<SDValue, 2> DemandedSubOps;
3510 for (unsigned i = 0; i != NumSubVecs; ++i) {
3511 SDValue SubOp = Op.getOperand(i);
3512 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3514 SubOp, SubElts, TLO.DAG, Depth + 1);
3515 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
3516 FoundNewSub = NewSubOp ? true : FoundNewSub;
3517 }
3518 if (FoundNewSub) {
3519 SDValue NewOp =
3520 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
3521 return TLO.CombineTo(Op, NewOp);
3522 }
3523 }
3524 break;
3525 }
3526 case ISD::INSERT_SUBVECTOR: {
3527 // Demand any elements from the subvector and the remainder from the src it
3528 // is inserted into.
3529 SDValue Src = Op.getOperand(0);
3530 SDValue Sub = Op.getOperand(1);
3531 uint64_t Idx = Op.getConstantOperandVal(2);
3532 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3533 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3534 APInt DemandedSrcElts = DemandedElts;
3535 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3536
3537 // If none of the sub operand elements are demanded, bypass the insert.
3538 if (!DemandedSubElts)
3539 return TLO.CombineTo(Op, Src);
3540
3541 APInt SubUndef, SubZero;
3542 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
3543 Depth + 1))
3544 return true;
3545
3546 // If none of the src operand elements are demanded, replace it with undef.
3547 if (!DemandedSrcElts && !Src.isUndef())
3548 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3549 TLO.DAG.getUNDEF(VT), Sub,
3550 Op.getOperand(2)));
3551
3552 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
3553 TLO, Depth + 1))
3554 return true;
3555 KnownUndef.insertBits(SubUndef, Idx);
3556 KnownZero.insertBits(SubZero, Idx);
3557
3558 // Attempt to avoid multi-use ops if we don't need anything from them.
3559 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
3561 Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3563 Sub, DemandedSubElts, TLO.DAG, Depth + 1);
3564 if (NewSrc || NewSub) {
3565 NewSrc = NewSrc ? NewSrc : Src;
3566 NewSub = NewSub ? NewSub : Sub;
3567 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3568 NewSub, Op.getOperand(2));
3569 return TLO.CombineTo(Op, NewOp);
3570 }
3571 }
3572 break;
3573 }
3575 // Offset the demanded elts by the subvector index.
3576 SDValue Src = Op.getOperand(0);
3577 if (Src.getValueType().isScalableVector())
3578 break;
3579 uint64_t Idx = Op.getConstantOperandVal(1);
3580 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3581 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3582
3583 APInt SrcUndef, SrcZero;
3584 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3585 Depth + 1))
3586 return true;
3587 KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3588 KnownZero = SrcZero.extractBits(NumElts, Idx);
3589
3590 // Attempt to avoid multi-use ops if we don't need anything from them.
3591 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(Src, DemandedSrcElts,
3592 TLO.DAG, Depth + 1);
3593 if (NewSrc) {
3594 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3595 Op.getOperand(1));
3596 return TLO.CombineTo(Op, NewOp);
3597 }
3598 break;
3599 }
3601 SDValue Vec = Op.getOperand(0);
3602 SDValue Scl = Op.getOperand(1);
3603 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3604
3605 // For a legal, constant insertion index, if we don't need this insertion
3606 // then strip it, else remove it from the demanded elts.
3607 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3608 unsigned Idx = CIdx->getZExtValue();
3609 if (!DemandedElts[Idx])
3610 return TLO.CombineTo(Op, Vec);
3611
3612 APInt DemandedVecElts(DemandedElts);
3613 DemandedVecElts.clearBit(Idx);
3614 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3615 KnownZero, TLO, Depth + 1))
3616 return true;
3617
3618 KnownUndef.setBitVal(Idx, Scl.isUndef());
3619
3620 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3621 break;
3622 }
3623
3624 APInt VecUndef, VecZero;
3625 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3626 Depth + 1))
3627 return true;
3628 // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3629 break;
3630 }
3631 case ISD::VSELECT: {
3632 SDValue Sel = Op.getOperand(0);
3633 SDValue LHS = Op.getOperand(1);
3634 SDValue RHS = Op.getOperand(2);
3635
3636 // Try to transform the select condition based on the current demanded
3637 // elements.
3638 APInt UndefSel, ZeroSel;
3639 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO,
3640 Depth + 1))
3641 return true;
3642
3643 // See if we can simplify either vselect operand.
3644 APInt DemandedLHS(DemandedElts);
3645 APInt DemandedRHS(DemandedElts);
3646 APInt UndefLHS, ZeroLHS;
3647 APInt UndefRHS, ZeroRHS;
3648 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3649 Depth + 1))
3650 return true;
3651 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3652 Depth + 1))
3653 return true;
3654
3655 KnownUndef = UndefLHS & UndefRHS;
3656 KnownZero = ZeroLHS & ZeroRHS;
3657
3658 // If we know that the selected element is always zero, we don't need the
3659 // select value element.
3660 APInt DemandedSel = DemandedElts & ~KnownZero;
3661 if (DemandedSel != DemandedElts)
3662 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO,
3663 Depth + 1))
3664 return true;
3665
3666 break;
3667 }
3668 case ISD::VECTOR_SHUFFLE: {
3669 SDValue LHS = Op.getOperand(0);
3670 SDValue RHS = Op.getOperand(1);
3671 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3672
3673 // Collect demanded elements from shuffle operands..
3674 APInt DemandedLHS(NumElts, 0);
3675 APInt DemandedRHS(NumElts, 0);
3676 for (unsigned i = 0; i != NumElts; ++i) {
3677 int M = ShuffleMask[i];
3678 if (M < 0 || !DemandedElts[i])
3679 continue;
3680 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3681 if (M < (int)NumElts)
3682 DemandedLHS.setBit(M);
3683 else
3684 DemandedRHS.setBit(M - NumElts);
3685 }
3686
3687 // If either side isn't demanded, replace it by UNDEF. We handle this
3688 // explicitly here to also simplify in case of multiple uses (on the
3689 // contrary to the SimplifyDemandedVectorElts calls below).
3690 bool FoldLHS = !DemandedLHS && !LHS.isUndef();
3691 bool FoldRHS = !DemandedRHS && !RHS.isUndef();
3692 if (FoldLHS || FoldRHS) {
3693 LHS = FoldLHS ? TLO.DAG.getUNDEF(LHS.getValueType()) : LHS;
3694 RHS = FoldRHS ? TLO.DAG.getUNDEF(RHS.getValueType()) : RHS;
3695 SDValue NewOp =
3696 TLO.DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, ShuffleMask);
3697 return TLO.CombineTo(Op, NewOp);
3698 }
3699
3700 // See if we can simplify either shuffle operand.
3701 APInt UndefLHS, ZeroLHS;
3702 APInt UndefRHS, ZeroRHS;
3703 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3704 Depth + 1))
3705 return true;
3706 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3707 Depth + 1))
3708 return true;
3709
3710 // Simplify mask using undef elements from LHS/RHS.
3711 bool Updated = false;
3712 bool IdentityLHS = true, IdentityRHS = true;
3713 SmallVector<int, 32> NewMask(ShuffleMask);
3714 for (unsigned i = 0; i != NumElts; ++i) {
3715 int &M = NewMask[i];
3716 if (M < 0)
3717 continue;
3718 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3719 (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3720 Updated = true;
3721 M = -1;
3722 }
3723 IdentityLHS &= (M < 0) || (M == (int)i);
3724 IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3725 }
3726
3727 // Update legal shuffle masks based on demanded elements if it won't reduce
3728 // to Identity which can cause premature removal of the shuffle mask.
3729 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3730 SDValue LegalShuffle =
3731 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG);
3732 if (LegalShuffle)
3733 return TLO.CombineTo(Op, LegalShuffle);
3734 }
3735
3736 // Propagate undef/zero elements from LHS/RHS.
3737 for (unsigned i = 0; i != NumElts; ++i) {
3738 int M = ShuffleMask[i];
3739 if (M < 0) {
3740 KnownUndef.setBit(i);
3741 } else if (M < (int)NumElts) {
3742 if (UndefLHS[M])
3743 KnownUndef.setBit(i);
3744 if (ZeroLHS[M])
3745 KnownZero.setBit(i);
3746 } else {
3747 if (UndefRHS[M - NumElts])
3748 KnownUndef.setBit(i);
3749 if (ZeroRHS[M - NumElts])
3750 KnownZero.setBit(i);
3751 }
3752 }
3753 break;
3754 }
3758 APInt SrcUndef, SrcZero;
3759 SDValue Src = Op.getOperand(0);
3760 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3761 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3762 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3763 Depth + 1))
3764 return true;
3765 KnownZero = SrcZero.zextOrTrunc(NumElts);
3766 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3767
3768 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3769 Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3770 DemandedSrcElts == 1) {
3771 // aext - if we just need the bottom element then we can bitcast.
3772 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3773 }
3774
3775 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3776 // zext(undef) upper bits are guaranteed to be zero.
3777 if (DemandedElts.isSubsetOf(KnownUndef))
3778 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3779 KnownUndef.clearAllBits();
3780
3781 // zext - if we just need the bottom element then we can mask:
3782 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3783 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3784 Op->isOnlyUserOf(Src.getNode()) &&
3785 Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3786 SDLoc DL(Op);
3787 EVT SrcVT = Src.getValueType();
3788 EVT SrcSVT = SrcVT.getScalarType();
3789
3790 // If we're after type legalization and SrcSVT is not legal, use the
3791 // promoted type for creating constants to avoid creating nodes with
3792 // illegal types.
3793 if (TLO.LegalTypes())
3794 SrcSVT = getLegalTypeToTransformTo(*TLO.DAG.getContext(), SrcSVT);
3795
3796 SmallVector<SDValue> MaskElts;
3797 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3798 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3799 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3800 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3801 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3802 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3803 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3804 }
3805 }
3806 }
3807 break;
3808 }
3809
3810 // TODO: There are more binop opcodes that could be handled here - MIN,
3811 // MAX, saturated math, etc.
3812 case ISD::ADD: {
3813 SDValue Op0 = Op.getOperand(0);
3814 SDValue Op1 = Op.getOperand(1);
3815 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
3816 APInt UndefLHS, ZeroLHS;
3817 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3818 Depth + 1, /*AssumeSingleUse*/ true))
3819 return true;
3820 }
3821 [[fallthrough]];
3822 }
3823 case ISD::AVGCEILS:
3824 case ISD::AVGCEILU:
3825 case ISD::AVGFLOORS:
3826 case ISD::AVGFLOORU:
3827 case ISD::OR:
3828 case ISD::XOR:
3829 case ISD::SUB:
3830 case ISD::FADD:
3831 case ISD::FSUB:
3832 case ISD::FMUL:
3833 case ISD::FDIV:
3834 case ISD::FREM:
3835 case ISD::PSEUDO_FMIN:
3836 case ISD::PSEUDO_FMAX: {
3837 SDValue Op0 = Op.getOperand(0);
3838 SDValue Op1 = Op.getOperand(1);
3839
3840 APInt UndefRHS, ZeroRHS;
3841 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3842 Depth + 1))
3843 return true;
3844 APInt UndefLHS, ZeroLHS;
3845 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3846 Depth + 1))
3847 return true;
3848
3849 KnownZero = ZeroLHS & ZeroRHS;
3850 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
3851
3852 // Attempt to avoid multi-use ops if we don't need anything from them.
3853 // TODO - use KnownUndef to relax the demandedelts?
3854 if (!DemandedElts.isAllOnes())
3855 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3856 return true;
3857 break;
3858 }
3859 case ISD::SHL:
3860 case ISD::SRL:
3861 case ISD::SRA:
3862 case ISD::ROTL:
3863 case ISD::ROTR: {
3864 SDValue Op0 = Op.getOperand(0);
3865 SDValue Op1 = Op.getOperand(1);
3866
3867 APInt UndefRHS, ZeroRHS;
3868 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3869 Depth + 1))
3870 return true;
3871 APInt UndefLHS, ZeroLHS;
3872 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3873 Depth + 1))
3874 return true;
3875
3876 KnownZero = ZeroLHS;
3877 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
3878
3879 // Attempt to avoid multi-use ops if we don't need anything from them.
3880 // TODO - use KnownUndef to relax the demandedelts?
3881 if (!DemandedElts.isAllOnes())
3882 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3883 return true;
3884 break;
3885 }
3886 case ISD::MUL:
3887 case ISD::MULHU:
3888 case ISD::MULHS:
3889 case ISD::AND: {
3890 SDValue Op0 = Op.getOperand(0);
3891 SDValue Op1 = Op.getOperand(1);
3892
3893 APInt SrcUndef, SrcZero;
3894 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
3895 Depth + 1))
3896 return true;
3897 // FIXME: If we know that a demanded element was zero in Op1 we don't need
3898 // to demand it in Op0 - its guaranteed to be zero. There is however a
3899 // restriction, as we must not make any of the originally demanded elements
3900 // more poisonous. We could reduce amount of elements demanded, but then we
3901 // also need a to inform SimplifyDemandedVectorElts that some elements must
3902 // not be made more poisonous.
3903 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
3904 TLO, Depth + 1))
3905 return true;
3906
3907 KnownUndef &= DemandedElts;
3908 KnownZero &= DemandedElts;
3909
3910 // If every element pair has a zero/undef/poison then just fold to zero.
3911 // fold (and x, undef/poison) -> 0 / (and x, 0) -> 0
3912 // fold (mul x, undef/poison) -> 0 / (mul x, 0) -> 0
3913 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef))
3914 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3915
3916 // If either side has a zero element, then the result element is zero, even
3917 // if the other is an UNDEF.
3918 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
3919 // and then handle 'and' nodes with the rest of the binop opcodes.
3920 KnownZero |= SrcZero;
3921 KnownUndef &= SrcUndef;
3922 KnownUndef &= ~KnownZero;
3923
3924 // Attempt to avoid multi-use ops if we don't need anything from them.
3925 if (!DemandedElts.isAllOnes())
3926 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3927 return true;
3928 break;
3929 }
3930 case ISD::TRUNCATE:
3931 case ISD::SIGN_EXTEND:
3932 case ISD::ZERO_EXTEND:
3933 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
3934 KnownZero, TLO, Depth + 1))
3935 return true;
3936
3937 if (!DemandedElts.isAllOnes())
3939 Op.getOperand(0), DemandedElts, TLO.DAG, Depth + 1))
3940 return TLO.CombineTo(Op, TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp));
3941
3942 if (Op.getOpcode() == ISD::ZERO_EXTEND) {
3943 // zext(undef) upper bits are guaranteed to be zero.
3944 if (DemandedElts.isSubsetOf(KnownUndef))
3945 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3946 KnownUndef.clearAllBits();
3947 }
3948 break;
3949 case ISD::SINT_TO_FP:
3950 case ISD::UINT_TO_FP:
3951 case ISD::FP_TO_SINT:
3952 case ISD::FP_TO_UINT:
3953 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
3954 KnownZero, TLO, Depth + 1))
3955 return true;
3956 // Don't fall through to generic undef -> undef handling.
3957 return false;
3958 default: {
3959 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
3960 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
3961 KnownZero, TLO, Depth))
3962 return true;
3963 } else {
3965 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
3966 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
3967 TLO, Depth, AssumeSingleUse))
3968 return true;
3969 }
3970 break;
3971 }
3972 }
3973 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
3974
3975 // Constant fold all undef cases.
3976 // TODO: Handle zero cases as well.
3977 if (DemandedElts.isSubsetOf(KnownUndef))
3978 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3979
3980 return false;
3981}
3982
3983/// Determine which of the bits specified in Mask are known to be either zero or
3984/// one and return them in the Known.
3987 const APInt &DemandedElts,
3988 const SelectionDAG &DAG,
3989 unsigned Depth) const {
3990 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3991 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3992 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3993 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3994 "Should use MaskedValueIsZero if you don't know whether Op"
3995 " is a target node!");
3996 Known.resetAll();
3997}
3998
4001 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4002 unsigned Depth) const {
4003 Known.resetAll();
4004}
4005
4008 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4009 unsigned Depth) const {
4010 Known.resetAll();
4011}
4012
4014 KnownBits &Known, const MachineFunction &, Align Alignment) const {
4015 // The low bits are known zero if the pointer is aligned.
4016 Known.Zero.setLowBits(Log2(Alignment));
4017}
4018
4020 SelectionDAG &DAG,
4021 const SDLoc &DL,
4022 Align Alignment) const {
4023 // Materialize leading-zero stack object pointer facts as AssertZext.
4024 // Alignment-derived low zero bits are not represented on the returned DAG
4025 // value here.
4026 EVT PtrVT = Ptr.getValueType();
4027
4028 unsigned RegSize = PtrVT.getScalarSizeInBits();
4031 Alignment);
4032
4033 unsigned NumZeroBits = Known.countMinLeadingZeros();
4034 if (!NumZeroBits)
4035 return Ptr;
4036
4037 EVT FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
4038 return DAG.getNode(ISD::AssertZext, DL, PtrVT, Ptr, DAG.getValueType(FromVT));
4039}
4040
4046
4047/// This method can be implemented by targets that want to expose additional
4048/// information about sign bits to the DAG Combiner.
4050 const APInt &,
4051 const SelectionDAG &,
4052 unsigned Depth) const {
4053 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4054 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4055 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4056 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4057 "Should use ComputeNumSignBits if you don't know whether Op"
4058 " is a target node!");
4059 return 1;
4060}
4061
4063 GISelValueTracking &Analysis, Register R, const APInt &DemandedElts,
4064 const MachineRegisterInfo &MRI, unsigned Depth) const {
4065 return 1;
4066}
4067
4069 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
4070 TargetLoweringOpt &TLO, unsigned Depth) const {
4071 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4072 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4073 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4074 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4075 "Should use SimplifyDemandedVectorElts if you don't know whether Op"
4076 " is a target node!");
4077 return false;
4078}
4079
4081 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4082 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
4083 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4084 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4085 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4086 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4087 "Should use SimplifyDemandedBits if you don't know whether Op"
4088 " is a target node!");
4089 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
4090 return false;
4091}
4092
4094 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4095 SelectionDAG &DAG, unsigned Depth) const {
4096 assert(
4097 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4098 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4099 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4100 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4101 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
4102 " is a target node!");
4103 return SDValue();
4104}
4105
4106SDValue
4109 SelectionDAG &DAG) const {
4110 bool LegalMask = isShuffleMaskLegal(Mask, VT);
4111 if (!LegalMask) {
4112 std::swap(N0, N1);
4114 LegalMask = isShuffleMaskLegal(Mask, VT);
4115 }
4116
4117 if (!LegalMask)
4118 return SDValue();
4119
4120 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
4121}
4122
4124 return nullptr;
4125}
4126
4128 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4129 UndefPoisonKind Kind, unsigned Depth) const {
4130 assert(
4131 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4132 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4133 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4134 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4135 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
4136 " is a target node!");
4137
4138 // If Op can't create undef/poison and none of its operands are undef/poison
4139 // then Op is never undef/poison.
4140 return !canCreateUndefOrPoisonForTargetNode(Op, DemandedElts, DAG, Kind,
4141 /*ConsiderFlags*/ true, Depth) &&
4142 all_of(Op->ops(), [&](SDValue V) {
4143 return DAG.isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
4144 });
4145}
4146
4148 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4149 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const {
4150 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4151 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4152 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4153 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4154 "Should use canCreateUndefOrPoison if you don't know whether Op"
4155 " is a target node!");
4156 // Be conservative and return true.
4157 return true;
4158}
4159
4162 const APInt &DemandedElts,
4163 const SelectionDAG &DAG,
4164 unsigned Depth) const {
4165 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4166 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4167 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4168 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4169 "Should use computeKnownFPClass if you don't know whether Op"
4170 " is a target node!");
4171}
4172
4174 const APInt &DemandedElts,
4175 const SelectionDAG &DAG,
4176 bool SNaN,
4177 unsigned Depth) const {
4178 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4179 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4180 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4181 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4182 "Should use isKnownNeverNaN if you don't know whether Op"
4183 " is a target node!");
4184 return false;
4185}
4186
4188 const APInt &DemandedElts,
4189 APInt &UndefElts,
4190 const SelectionDAG &DAG,
4191 unsigned Depth) const {
4192 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4193 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4194 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4195 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4196 "Should use isSplatValue if you don't know whether Op"
4197 " is a target node!");
4198 return false;
4199}
4200
4201// FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
4202// work with truncating build vectors and vectors with elements of less than
4203// 8 bits.
4205 if (!N)
4206 return false;
4207
4208 unsigned EltWidth;
4209 APInt CVal;
4210 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
4211 /*AllowTruncation=*/true)) {
4212 CVal = CN->getAPIntValue();
4213 EltWidth = N.getValueType().getScalarSizeInBits();
4214 } else
4215 return false;
4216
4217 // If this is a truncating splat, truncate the splat value.
4218 // Otherwise, we may fail to match the expected values below.
4219 if (EltWidth < CVal.getBitWidth())
4220 CVal = CVal.trunc(EltWidth);
4221
4222 switch (getBooleanContents(N.getValueType())) {
4224 return CVal[0];
4226 return CVal.isOne();
4228 return CVal.isAllOnes();
4229 }
4230
4231 llvm_unreachable("Invalid boolean contents");
4232}
4233
4235 if (!N)
4236 return false;
4237
4239 if (!CN) {
4241 if (!BV)
4242 return false;
4243
4244 // Only interested in constant splats, we don't care about undef
4245 // elements in identifying boolean constants and getConstantSplatNode
4246 // returns NULL if all ops are undef;
4247 CN = BV->getConstantSplatNode();
4248 if (!CN)
4249 return false;
4250 }
4251
4252 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
4253 return !CN->getAPIntValue()[0];
4254
4255 return CN->isZero();
4256}
4257
4259 bool SExt) const {
4260 if (VT == MVT::i1)
4261 return N->isOne();
4262
4264 switch (Cnt) {
4266 // An extended value of 1 is always true, unless its original type is i1,
4267 // in which case it will be sign extended to -1.
4268 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
4271 return N->isAllOnes() && SExt;
4272 }
4273 llvm_unreachable("Unexpected enumeration.");
4274}
4275
4276/// This helper function of SimplifySetCC tries to optimize the comparison when
4277/// either operand of the SetCC node is a bitwise-and instruction.
4278SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
4279 ISD::CondCode Cond, const SDLoc &DL,
4280 DAGCombinerInfo &DCI) const {
4281 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
4282 std::swap(N0, N1);
4283
4284 SelectionDAG &DAG = DCI.DAG;
4285 EVT OpVT = N0.getValueType();
4286 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
4287 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4288 return SDValue();
4289
4290 // (X & Y) != 0 --> zextOrTrunc(X & Y)
4291 // iff everything but LSB is known zero:
4292 if (Cond == ISD::SETNE && isNullConstant(N1) &&
4295 unsigned NumEltBits = OpVT.getScalarSizeInBits();
4296 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
4297 if (DAG.MaskedValueIsZero(N0, UpperBits))
4298 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
4299 }
4300
4301 // Try to eliminate a power-of-2 mask constant by converting to a signbit
4302 // test in a narrow type that we can truncate to with no cost. Examples:
4303 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0
4304 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0
4305 // TODO: This conservatively checks for type legality on the source and
4306 // destination types. That may inhibit optimizations, but it also
4307 // allows setcc->shift transforms that may be more beneficial.
4308 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4309 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() &&
4310 isTypeLegal(OpVT) && N0.hasOneUse()) {
4311 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(),
4312 AndC->getAPIntValue().getActiveBits());
4313 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) {
4314 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT);
4315 SDValue Zero = DAG.getConstant(0, DL, NarrowVT);
4316 return DAG.getSetCC(DL, VT, Trunc, Zero,
4318 }
4319 }
4320
4321 // Match these patterns in any of their permutations:
4322 // (X & Y) == Y
4323 // (X & Y) != Y
4324 SDValue X, Y;
4325 if (N0.getOperand(0) == N1) {
4326 X = N0.getOperand(1);
4327 Y = N0.getOperand(0);
4328 } else if (N0.getOperand(1) == N1) {
4329 X = N0.getOperand(0);
4330 Y = N0.getOperand(1);
4331 } else {
4332 return SDValue();
4333 }
4334
4335 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if
4336 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as
4337 // its liable to create and infinite loop.
4338 SDValue Zero = DAG.getConstant(0, DL, OpVT);
4339 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) &&
4341 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
4342 // Note that where Y is variable and is known to have at most one bit set
4343 // (for example, if it is Z & 1) we cannot do this; the expressions are not
4344 // equivalent when Y == 0.
4345 assert(OpVT.isInteger());
4347 if (DCI.isBeforeLegalizeOps() ||
4349 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
4350 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
4351 // If the target supports an 'and-not' or 'and-complement' logic operation,
4352 // try to use that to make a comparison operation more efficient.
4353 // But don't do this transform if the mask is a single bit because there are
4354 // more efficient ways to deal with that case (for example, 'bt' on x86 or
4355 // 'rlwinm' on PPC).
4356
4357 // Bail out if the compare operand that we want to turn into a zero is
4358 // already a zero (otherwise, infinite loop).
4359 if (isNullConstant(Y))
4360 return SDValue();
4361
4362 // Transform this into: ~X & Y == 0.
4363 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
4364 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
4365 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
4366 }
4367
4368 return SDValue();
4369}
4370
4371/// This helper function of SimplifySetCC tries to optimize the comparison when
4372/// either operand of the SetCC node is a bitwise-or instruction.
4373/// For now, this just transforms (X | Y) ==/!= Y into X & ~Y ==/!= 0.
4374SDValue TargetLowering::foldSetCCWithOr(EVT VT, SDValue N0, SDValue N1,
4375 ISD::CondCode Cond, const SDLoc &DL,
4376 DAGCombinerInfo &DCI) const {
4377 if (N1.getOpcode() == ISD::OR && N0.getOpcode() != ISD::OR)
4378 std::swap(N0, N1);
4379
4380 SelectionDAG &DAG = DCI.DAG;
4381 EVT OpVT = N0.getValueType();
4382 if (!N0.hasOneUse() || !OpVT.isInteger() ||
4383 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4384 return SDValue();
4385
4386 // (X | Y) == Y
4387 // (X | Y) != Y
4388 SDValue X;
4389 if (sd_match(N0, m_Or(m_Value(X), m_Specific(N1))) && hasAndNotCompare(X)) {
4390 // If the target supports an 'and-not' or 'and-complement' logic operation,
4391 // try to use that to make a comparison operation more efficient.
4392
4393 // Bail out if the compare operand that we want to turn into a zero is
4394 // already a zero (otherwise, infinite loop).
4395 if (isNullConstant(N1))
4396 return SDValue();
4397
4398 // Transform this into: X & ~Y ==/!= 0.
4399 SDValue NotY = DAG.getNOT(SDLoc(N1), N1, OpVT);
4400 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, X, NotY);
4401 return DAG.getSetCC(DL, VT, NewAnd, DAG.getConstant(0, DL, OpVT), Cond);
4402 }
4403
4404 return SDValue();
4405}
4406
4407/// There are multiple IR patterns that could be checking whether certain
4408/// truncation of a signed number would be lossy or not. The pattern which is
4409/// best at IR level, may not lower optimally. Thus, we want to unfold it.
4410/// We are looking for the following pattern: (KeptBits is a constant)
4411/// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
4412/// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
4413/// KeptBits also can't be 1, that would have been folded to %x dstcond 0
4414/// We will unfold it into the natural trunc+sext pattern:
4415/// ((%x << C) a>> C) dstcond %x
4416/// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
4417SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
4418 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
4419 const SDLoc &DL) const {
4420 // We must be comparing with a constant.
4421 ConstantSDNode *C1;
4422 if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
4423 return SDValue();
4424
4425 // N0 should be: add %x, (1 << (KeptBits-1))
4426 if (N0->getOpcode() != ISD::ADD)
4427 return SDValue();
4428
4429 // And we must be 'add'ing a constant.
4430 ConstantSDNode *C01;
4431 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
4432 return SDValue();
4433
4434 SDValue X = N0->getOperand(0);
4435 EVT XVT = X.getValueType();
4436
4437 // Validate constants ...
4438
4439 APInt I1 = C1->getAPIntValue();
4440
4441 ISD::CondCode NewCond;
4442 if (Cond == ISD::CondCode::SETULT) {
4443 NewCond = ISD::CondCode::SETEQ;
4444 } else if (Cond == ISD::CondCode::SETULE) {
4445 NewCond = ISD::CondCode::SETEQ;
4446 // But need to 'canonicalize' the constant.
4447 I1 += 1;
4448 } else if (Cond == ISD::CondCode::SETUGT) {
4449 NewCond = ISD::CondCode::SETNE;
4450 // But need to 'canonicalize' the constant.
4451 I1 += 1;
4452 } else if (Cond == ISD::CondCode::SETUGE) {
4453 NewCond = ISD::CondCode::SETNE;
4454 } else
4455 return SDValue();
4456
4457 APInt I01 = C01->getAPIntValue();
4458
4459 auto checkConstants = [&I1, &I01]() -> bool {
4460 // Both of them must be power-of-two, and the constant from setcc is bigger.
4461 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
4462 };
4463
4464 if (checkConstants()) {
4465 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
4466 } else {
4467 // What if we invert constants? (and the target predicate)
4468 I1.negate();
4469 I01.negate();
4470 assert(XVT.isInteger());
4471 NewCond = getSetCCInverse(NewCond, XVT);
4472 if (!checkConstants())
4473 return SDValue();
4474 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
4475 }
4476
4477 // They are power-of-two, so which bit is set?
4478 const unsigned KeptBits = I1.logBase2();
4479 const unsigned KeptBitsMinusOne = I01.logBase2();
4480
4481 // Magic!
4482 if (KeptBits != (KeptBitsMinusOne + 1))
4483 return SDValue();
4484 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
4485
4486 // We don't want to do this in every single case.
4487 SelectionDAG &DAG = DCI.DAG;
4488 if (!shouldTransformSignedTruncationCheck(XVT, KeptBits))
4489 return SDValue();
4490
4491 // Unfold into: sext_inreg(%x) cond %x
4492 // Where 'cond' will be either 'eq' or 'ne'.
4493 SDValue SExtInReg = DAG.getNode(
4495 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), KeptBits)));
4496 return DAG.getSetCC(DL, SCCVT, SExtInReg, X, NewCond);
4497}
4498
4499// (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
4500SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
4501 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4502 DAGCombinerInfo &DCI, const SDLoc &DL) const {
4504 "Should be a comparison with 0.");
4505 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4506 "Valid only for [in]equality comparisons.");
4507
4508 unsigned NewShiftOpcode;
4509 SDValue X, C, Y;
4510
4511 SelectionDAG &DAG = DCI.DAG;
4512
4513 // Look for '(C l>>/<< Y)'.
4514 auto Match = [&NewShiftOpcode, &X, &C, &Y, &DAG, this](SDValue V) {
4515 // The shift should be one-use.
4516 if (!V.hasOneUse())
4517 return false;
4518 unsigned OldShiftOpcode = V.getOpcode();
4519 switch (OldShiftOpcode) {
4520 case ISD::SHL:
4521 NewShiftOpcode = ISD::SRL;
4522 break;
4523 case ISD::SRL:
4524 NewShiftOpcode = ISD::SHL;
4525 break;
4526 default:
4527 return false; // must be a logical shift.
4528 }
4529 // We should be shifting a constant.
4530 // FIXME: best to use isConstantOrConstantVector().
4531 C = V.getOperand(0);
4532 ConstantSDNode *CC =
4533 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4534 if (!CC)
4535 return false;
4536 Y = V.getOperand(1);
4537
4538 ConstantSDNode *XC =
4539 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4541 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
4542 };
4543
4544 // LHS of comparison should be an one-use 'and'.
4545 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
4546 return SDValue();
4547
4548 X = N0.getOperand(0);
4549 SDValue Mask = N0.getOperand(1);
4550
4551 // 'and' is commutative!
4552 if (!Match(Mask)) {
4553 std::swap(X, Mask);
4554 if (!Match(Mask))
4555 return SDValue();
4556 }
4557
4558 EVT VT = X.getValueType();
4559
4560 // Produce:
4561 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
4562 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
4563 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
4564 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
4565 return T2;
4566}
4567
4568/// Try to fold an equality comparison with a {add/sub/xor} binary operation as
4569/// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
4570/// handle the commuted versions of these patterns.
4571SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
4572 ISD::CondCode Cond, const SDLoc &DL,
4573 DAGCombinerInfo &DCI) const {
4574 unsigned BOpcode = N0.getOpcode();
4575 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
4576 "Unexpected binop");
4577 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
4578
4579 // (X + Y) == X --> Y == 0
4580 // (X - Y) == X --> Y == 0
4581 // (X ^ Y) == X --> Y == 0
4582 SelectionDAG &DAG = DCI.DAG;
4583 EVT OpVT = N0.getValueType();
4584 SDValue X = N0.getOperand(0);
4585 SDValue Y = N0.getOperand(1);
4586 if (X == N1)
4587 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
4588
4589 if (Y != N1)
4590 return SDValue();
4591
4592 // (X + Y) == Y --> X == 0
4593 // (X ^ Y) == Y --> X == 0
4594 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
4595 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
4596
4597 // The shift would not be valid if the operands are boolean (i1).
4598 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
4599 return SDValue();
4600
4601 // (X - Y) == Y --> X == Y << 1
4602 SDValue One = DAG.getShiftAmountConstant(1, OpVT, DL);
4603 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
4604 if (!DCI.isCalledByLegalizer())
4605 DCI.AddToWorklist(YShl1.getNode());
4606 return DAG.getSetCC(DL, VT, X, YShl1, Cond);
4607}
4608
4610 SDValue N0, const APInt &C1,
4611 ISD::CondCode Cond, const SDLoc &dl,
4612 SelectionDAG &DAG) {
4613 // Look through truncs that don't change the value of a ctpop.
4614 // FIXME: Add vector support? Need to be careful with setcc result type below.
4615 SDValue CTPOP = N0;
4616 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
4618 CTPOP = N0.getOperand(0);
4619
4620 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
4621 return SDValue();
4622
4623 EVT CTVT = CTPOP.getValueType();
4624 SDValue CTOp = CTPOP.getOperand(0);
4625
4626 // Expand a power-of-2-or-zero comparison based on ctpop:
4627 // (ctpop x) u< 2 -> (x & x-1) == 0
4628 // (ctpop x) u> 1 -> (x & x-1) != 0
4629 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
4630 // Keep the CTPOP if it is a cheap vector op.
4631 if (CTVT.isVector() && TLI.isCtpopFast(CTVT))
4632 return SDValue();
4633
4634 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
4635 if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
4636 return SDValue();
4637 if (C1 == 0 && (Cond == ISD::SETULT))
4638 return SDValue(); // This is handled elsewhere.
4639
4640 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
4641
4642 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4643 SDValue Result = CTOp;
4644 for (unsigned i = 0; i < Passes; i++) {
4645 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
4646 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
4647 }
4649 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
4650 }
4651
4652 // Expand a power-of-2 comparison based on ctpop
4653 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
4654 // Keep the CTPOP if it is cheap.
4655 if (TLI.isCtpopFast(CTVT))
4656 return SDValue();
4657
4658 SDValue Zero = DAG.getConstant(0, dl, CTVT);
4659 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4660 assert(CTVT.isInteger());
4661 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
4662
4663 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so
4664 // check before emitting a potentially unnecessary op.
4665 if (DAG.isKnownNeverZero(CTOp)) {
4666 // (ctpop x) == 1 --> (x & x-1) == 0
4667 // (ctpop x) != 1 --> (x & x-1) != 0
4668 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
4669 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
4670 return RHS;
4671 }
4672
4673 // (ctpop x) == 1 --> (x ^ x-1) > x-1
4674 // (ctpop x) != 1 --> (x ^ x-1) <= x-1
4675 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add);
4677 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond);
4678 }
4679
4680 return SDValue();
4681}
4682
4684 ISD::CondCode Cond, const SDLoc &dl,
4685 SelectionDAG &DAG) {
4686 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4687 return SDValue();
4688
4689 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4690 if (!C1 || !(C1->isZero() || C1->isAllOnes()))
4691 return SDValue();
4692
4693 auto getRotateSource = [](SDValue X) {
4694 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
4695 return X.getOperand(0);
4696 return SDValue();
4697 };
4698
4699 // Peek through a rotated value compared against 0 or -1:
4700 // (rot X, Y) == 0/-1 --> X == 0/-1
4701 // (rot X, Y) != 0/-1 --> X != 0/-1
4702 if (SDValue R = getRotateSource(N0))
4703 return DAG.getSetCC(dl, VT, R, N1, Cond);
4704
4705 // Peek through an 'or' of a rotated value compared against 0:
4706 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
4707 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
4708 //
4709 // TODO: Add the 'and' with -1 sibling.
4710 // TODO: Recurse through a series of 'or' ops to find the rotate.
4711 EVT OpVT = N0.getValueType();
4712 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
4713 if (SDValue R = getRotateSource(N0.getOperand(0))) {
4714 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
4715 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4716 }
4717 if (SDValue R = getRotateSource(N0.getOperand(1))) {
4718 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
4719 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4720 }
4721 }
4722
4723 return SDValue();
4724}
4725
4727 ISD::CondCode Cond, const SDLoc &dl,
4728 SelectionDAG &DAG) {
4729 // If we are testing for all-bits-clear, we might be able to do that with
4730 // less shifting since bit-order does not matter.
4731 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4732 return SDValue();
4733
4734 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4735 if (!C1 || !C1->isZero())
4736 return SDValue();
4737
4738 if (!N0.hasOneUse() ||
4739 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
4740 return SDValue();
4741
4742 unsigned BitWidth = N0.getScalarValueSizeInBits();
4743 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
4744 if (!ShAmtC)
4745 return SDValue();
4746
4747 uint64_t ShAmt = ShAmtC->getAPIntValue().urem(BitWidth);
4748 if (ShAmt == 0)
4749 return SDValue();
4750
4751 // Canonicalize fshr as fshl to reduce pattern-matching.
4752 if (N0.getOpcode() == ISD::FSHR)
4753 ShAmt = BitWidth - ShAmt;
4754
4755 // Match an 'or' with a specific operand 'Other' in either commuted variant.
4756 SDValue X, Y;
4757 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
4758 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
4759 return false;
4760 if (Or.getOperand(0) == Other) {
4761 X = Or.getOperand(0);
4762 Y = Or.getOperand(1);
4763 return true;
4764 }
4765 if (Or.getOperand(1) == Other) {
4766 X = Or.getOperand(1);
4767 Y = Or.getOperand(0);
4768 return true;
4769 }
4770 return false;
4771 };
4772
4773 EVT OpVT = N0.getValueType();
4774 EVT ShAmtVT = N0.getOperand(2).getValueType();
4775 SDValue F0 = N0.getOperand(0);
4776 SDValue F1 = N0.getOperand(1);
4777 if (matchOr(F0, F1)) {
4778 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
4779 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
4780 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
4781 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4782 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4783 }
4784 if (matchOr(F1, F0)) {
4785 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
4786 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
4787 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
4788 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4789 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4790 }
4791
4792 return SDValue();
4793}
4794
4795/// Try to simplify a setcc built with the specified operands and cc. If it is
4796/// unable to simplify it, return a null SDValue.
4798 ISD::CondCode Cond, bool foldBooleans,
4799 DAGCombinerInfo &DCI,
4800 const SDLoc &dl) const {
4801 SelectionDAG &DAG = DCI.DAG;
4802 const DataLayout &Layout = DAG.getDataLayout();
4803 EVT OpVT = N0.getValueType();
4804 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4805
4806 // Constant fold or commute setcc.
4807 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
4808 return Fold;
4809
4810 bool N0ConstOrSplat =
4811 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4812 bool N1ConstOrSplat =
4813 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4814
4815 // Canonicalize toward having the constant on the RHS.
4816 // TODO: Handle non-splat vector constants. All undef causes trouble.
4817 // FIXME: We can't yet fold constant scalable vector splats, so avoid an
4818 // infinite loop here when we encounter one.
4820 if (N0ConstOrSplat && !N1ConstOrSplat &&
4821 (DCI.isBeforeLegalizeOps() ||
4822 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
4823 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4824
4825 // If we have a subtract with the same 2 non-constant operands as this setcc
4826 // -- but in reverse order -- then try to commute the operands of this setcc
4827 // to match. A matching pair of setcc (cmp) and sub may be combined into 1
4828 // instruction on some targets.
4829 if (!N0ConstOrSplat && !N1ConstOrSplat &&
4830 (DCI.isBeforeLegalizeOps() ||
4831 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
4832 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
4833 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
4834 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4835
4836 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
4837 return V;
4838
4839 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
4840 return V;
4841
4842 if (auto *N1C = isConstOrConstSplat(N1)) {
4843 const APInt &C1 = N1C->getAPIntValue();
4844
4845 // Optimize some CTPOP cases.
4846 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
4847 return V;
4848
4849 // For equality to 0 of a no-wrap multiply, decompose and test each op:
4850 // X * Y == 0 --> (X == 0) || (Y == 0)
4851 // X * Y != 0 --> (X != 0) && (Y != 0)
4852 // TODO: This bails out if minsize is set, but if the target doesn't have a
4853 // single instruction multiply for this type, it would likely be
4854 // smaller to decompose.
4855 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4856 N0.getOpcode() == ISD::MUL && N0.hasOneUse() &&
4857 (N0->getFlags().hasNoUnsignedWrap() ||
4858 N0->getFlags().hasNoSignedWrap()) &&
4859 !Attr.hasFnAttr(Attribute::MinSize)) {
4860 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4861 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond);
4862 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND;
4863 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero);
4864 }
4865
4866 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
4867 // equality comparison, then we're just comparing whether X itself is
4868 // zero.
4869 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
4870 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
4872 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
4873 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4874 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
4875 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
4876 // (srl (ctlz x), 5) == 0 -> X != 0
4877 // (srl (ctlz x), 5) != 1 -> X != 0
4878 Cond = ISD::SETNE;
4879 } else {
4880 // (srl (ctlz x), 5) != 0 -> X == 0
4881 // (srl (ctlz x), 5) == 1 -> X == 0
4882 Cond = ISD::SETEQ;
4883 }
4884 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
4885 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
4886 Cond);
4887 }
4888 }
4889 }
4890 }
4891
4892 // setcc X, 0, setlt --> X (when X is all sign bits)
4893 // setcc X, 0, setne --> X (when X is all sign bits)
4894 //
4895 // When we know that X has 0 or -1 in each element (or scalar), this
4896 // comparison will produce X. This is only true when boolean contents are
4897 // represented via 0s and -1s.
4898 if (VT == OpVT &&
4899 // Check that the result of setcc is 0 and -1.
4901 // Match only for checks X < 0 and X != 0
4902 (Cond == ISD::SETLT || Cond == ISD::SETNE) && isNullOrNullSplat(N1) &&
4903 // The identity holds iff we know all sign bits for all lanes.
4905 return N0;
4906
4907 // FIXME: Support vectors.
4908 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4909 const APInt &C1 = N1C->getAPIntValue();
4910
4911 // (zext x) == C --> x == (trunc C)
4912 // (sext x) == C --> x == (trunc C)
4913 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4914 DCI.isBeforeLegalize() && N0->hasOneUse()) {
4915 unsigned MinBits = N0.getValueSizeInBits();
4916 SDValue PreExt;
4917 bool Signed = false;
4918 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
4919 // ZExt
4920 MinBits = N0->getOperand(0).getValueSizeInBits();
4921 PreExt = N0->getOperand(0);
4922 } else if (N0->getOpcode() == ISD::AND) {
4923 // DAGCombine turns costly ZExts into ANDs
4924 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
4925 if ((C->getAPIntValue()+1).isPowerOf2()) {
4926 MinBits = C->getAPIntValue().countr_one();
4927 PreExt = N0->getOperand(0);
4928 }
4929 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
4930 // SExt
4931 MinBits = N0->getOperand(0).getValueSizeInBits();
4932 PreExt = N0->getOperand(0);
4933 Signed = true;
4934 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
4935 // ZEXTLOAD / SEXTLOAD
4936 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
4937 MinBits = LN0->getMemoryVT().getSizeInBits();
4938 PreExt = N0;
4939 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
4940 Signed = true;
4941 MinBits = LN0->getMemoryVT().getSizeInBits();
4942 PreExt = N0;
4943 }
4944 }
4945
4946 // Figure out how many bits we need to preserve this constant.
4947 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits();
4948
4949 // Make sure we're not losing bits from the constant.
4950 if (MinBits > 0 &&
4951 MinBits < C1.getBitWidth() &&
4952 MinBits >= ReqdBits) {
4953 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
4954 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
4955 // Will get folded away.
4956 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
4957 if (MinBits == 1 && C1 == 1)
4958 // Invert the condition.
4959 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
4961 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
4962 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
4963 }
4964
4965 // If truncating the setcc operands is not desirable, we can still
4966 // simplify the expression in some cases:
4967 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
4968 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
4969 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
4970 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
4971 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
4972 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
4973 SDValue TopSetCC = N0->getOperand(0);
4974 unsigned N0Opc = N0->getOpcode();
4975 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
4976 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
4977 TopSetCC.getOpcode() == ISD::SETCC &&
4978 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
4979 (isConstFalseVal(N1) ||
4980 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
4981
4982 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
4983 (!N1C->isZero() && Cond == ISD::SETNE);
4984
4985 if (!Inverse)
4986 return TopSetCC;
4987
4989 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
4990 TopSetCC.getOperand(0).getValueType());
4991 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
4992 TopSetCC.getOperand(1),
4993 InvCond);
4994 }
4995 }
4996 }
4997
4998 // If the LHS is '(and load, const)', the RHS is 0, the test is for
4999 // equality or unsigned, and all 1 bits of the const are in the same
5000 // partial word, see if we can shorten the load.
5001 if (DCI.isBeforeLegalize() &&
5003 N0.getOpcode() == ISD::AND && C1 == 0 &&
5004 N0.getNode()->hasOneUse() &&
5005 isa<LoadSDNode>(N0.getOperand(0)) &&
5006 N0.getOperand(0).getNode()->hasOneUse() &&
5008 auto *Lod = cast<LoadSDNode>(N0.getOperand(0));
5009 APInt bestMask;
5010 unsigned bestWidth = 0, bestOffset = 0;
5011 if (Lod->isSimple() && Lod->isUnindexed() &&
5012 (Lod->getMemoryVT().isByteSized() ||
5013 isPaddedAtMostSignificantBitsWhenStored(Lod->getMemoryVT()))) {
5014 unsigned memWidth = Lod->getMemoryVT().getStoreSizeInBits();
5015 unsigned origWidth = N0.getValueSizeInBits();
5016 unsigned maskWidth = origWidth;
5017 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
5018 // 8 bits, but have to be careful...
5019 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
5020 origWidth = Lod->getMemoryVT().getSizeInBits();
5021 const APInt &Mask = N0.getConstantOperandAPInt(1);
5022 // Only consider power-of-2 widths (and at least one byte) as candiates
5023 // for the narrowed load.
5024 for (unsigned width = 8; width < origWidth; width *= 2) {
5025 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), width);
5026 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
5027 // Avoid accessing any padding here for now (we could use memWidth
5028 // instead of origWidth here otherwise).
5029 unsigned maxOffset = origWidth - width;
5030 for (unsigned offset = 0; offset <= maxOffset; offset += 8) {
5031 if (Mask.isSubsetOf(newMask)) {
5032 unsigned ptrOffset =
5033 Layout.isLittleEndian() ? offset : memWidth - width - offset;
5034 unsigned IsFast = 0;
5035 assert((ptrOffset % 8) == 0 && "Non-Bytealigned pointer offset");
5036 Align NewAlign = commonAlignment(Lod->getAlign(), ptrOffset / 8);
5038 ptrOffset / 8) &&
5040 *DAG.getContext(), Layout, newVT, Lod->getAddressSpace(),
5041 NewAlign, Lod->getMemOperand()->getFlags(), &IsFast) &&
5042 IsFast) {
5043 bestOffset = ptrOffset / 8;
5044 bestMask = Mask.lshr(offset);
5045 bestWidth = width;
5046 break;
5047 }
5048 }
5049 newMask <<= 8;
5050 }
5051 if (bestWidth)
5052 break;
5053 }
5054 }
5055 if (bestWidth) {
5056 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
5057 SDValue Ptr = Lod->getBasePtr();
5058 if (bestOffset != 0)
5059 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(bestOffset));
5060 SDValue NewLoad =
5061 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
5062 Lod->getPointerInfo().getWithOffset(bestOffset),
5063 Lod->getBaseAlign());
5064 SDValue And =
5065 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
5066 DAG.getConstant(bestMask.trunc(bestWidth), dl, newVT));
5067 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0LL, dl, newVT), Cond);
5068 }
5069 }
5070
5071 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
5072 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
5073 unsigned InSize = N0.getOperand(0).getValueSizeInBits();
5074
5075 // If the comparison constant has bits in the upper part, the
5076 // zero-extended value could never match.
5078 C1.getBitWidth() - InSize))) {
5079 switch (Cond) {
5080 case ISD::SETUGT:
5081 case ISD::SETUGE:
5082 case ISD::SETEQ:
5083 return DAG.getConstant(0, dl, VT);
5084 case ISD::SETULT:
5085 case ISD::SETULE:
5086 case ISD::SETNE:
5087 return DAG.getConstant(1, dl, VT);
5088 case ISD::SETGT:
5089 case ISD::SETGE:
5090 // True if the sign bit of C1 is set.
5091 return DAG.getConstant(C1.isNegative(), dl, VT);
5092 case ISD::SETLT:
5093 case ISD::SETLE:
5094 // True if the sign bit of C1 isn't set.
5095 return DAG.getConstant(C1.isNonNegative(), dl, VT);
5096 default:
5097 break;
5098 }
5099 }
5100
5101 // Otherwise, we can perform the comparison with the low bits.
5102 switch (Cond) {
5103 case ISD::SETEQ:
5104 case ISD::SETNE:
5105 case ISD::SETUGT:
5106 case ISD::SETUGE:
5107 case ISD::SETULT:
5108 case ISD::SETULE: {
5109 EVT newVT = N0.getOperand(0).getValueType();
5110 // FIXME: Should use isNarrowingProfitable.
5111 if (DCI.isBeforeLegalizeOps() ||
5112 (isOperationLegal(ISD::SETCC, newVT) &&
5113 isCondCodeLegal(Cond, newVT.getSimpleVT()) &&
5115 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
5116 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
5117
5118 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
5119 NewConst, Cond);
5120 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
5121 }
5122 break;
5123 }
5124 default:
5125 break; // todo, be more careful with signed comparisons
5126 }
5127 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5128 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5130 OpVT)) {
5131 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
5132 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
5133 EVT ExtDstTy = N0.getValueType();
5134 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
5135
5136 // If the constant doesn't fit into the number of bits for the source of
5137 // the sign extension, it is impossible for both sides to be equal.
5138 if (C1.getSignificantBits() > ExtSrcTyBits)
5139 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
5140
5141 assert(ExtDstTy == N0.getOperand(0).getValueType() &&
5142 ExtDstTy != ExtSrcTy && "Unexpected types!");
5143 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
5144 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
5145 DAG.getConstant(Imm, dl, ExtDstTy));
5146 if (!DCI.isCalledByLegalizer())
5147 DCI.AddToWorklist(ZextOp.getNode());
5148 // Otherwise, make this a use of a zext.
5149 return DAG.getSetCC(dl, VT, ZextOp,
5150 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
5151 } else if ((N1C->isZero() || N1C->isOne()) &&
5152 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5153 // SETCC (X), [0|1], [EQ|NE] -> X if X is known 0/1. i1 types are
5154 // excluded as they are handled below whilst checking for foldBooleans.
5155 if ((N0.getOpcode() == ISD::SETCC || VT.getScalarType() != MVT::i1) &&
5156 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
5157 (N0.getValueType() == MVT::i1 ||
5161 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
5162 if (TrueWhenTrue)
5163 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
5164 // Invert the condition.
5165 if (N0.getOpcode() == ISD::SETCC) {
5168 if (DCI.isBeforeLegalizeOps() ||
5170 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
5171 }
5172 }
5173
5174 if ((N0.getOpcode() == ISD::XOR ||
5175 (N0.getOpcode() == ISD::AND &&
5176 N0.getOperand(0).getOpcode() == ISD::XOR &&
5177 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
5178 isOneConstant(N0.getOperand(1))) {
5179 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
5180 // can only do this if the top bits are known zero.
5181 unsigned BitWidth = N0.getValueSizeInBits();
5182 if (DAG.MaskedValueIsZero(N0,
5184 BitWidth-1))) {
5185 // Okay, get the un-inverted input value.
5186 SDValue Val;
5187 if (N0.getOpcode() == ISD::XOR) {
5188 Val = N0.getOperand(0);
5189 } else {
5190 assert(N0.getOpcode() == ISD::AND &&
5191 N0.getOperand(0).getOpcode() == ISD::XOR);
5192 // ((X^1)&1)^1 -> X & 1
5193 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
5194 N0.getOperand(0).getOperand(0),
5195 N0.getOperand(1));
5196 }
5197
5198 return DAG.getSetCC(dl, VT, Val, N1,
5200 }
5201 } else if (N1C->isOne()) {
5202 SDValue Op0 = N0;
5203 if (Op0.getOpcode() == ISD::TRUNCATE)
5204 Op0 = Op0.getOperand(0);
5205
5206 if ((Op0.getOpcode() == ISD::XOR) &&
5207 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
5208 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
5209 SDValue XorLHS = Op0.getOperand(0);
5210 SDValue XorRHS = Op0.getOperand(1);
5211 // Ensure that the input setccs return an i1 type or 0/1 value.
5212 if (Op0.getValueType() == MVT::i1 ||
5217 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
5219 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
5220 }
5221 }
5222 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
5223 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
5224 if (Op0.getValueType().bitsGT(VT))
5225 Op0 = DAG.getNode(ISD::AND, dl, VT,
5226 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
5227 DAG.getConstant(1, dl, VT));
5228 else if (Op0.getValueType().bitsLT(VT))
5229 Op0 = DAG.getNode(ISD::AND, dl, VT,
5230 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
5231 DAG.getConstant(1, dl, VT));
5232
5233 return DAG.getSetCC(dl, VT, Op0,
5234 DAG.getConstant(0, dl, Op0.getValueType()),
5236 }
5237 if (Op0.getOpcode() == ISD::AssertZext &&
5238 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
5239 return DAG.getSetCC(dl, VT, Op0,
5240 DAG.getConstant(0, dl, Op0.getValueType()),
5242 }
5243 }
5244
5245 // Given:
5246 // icmp eq/ne (urem %x, %y), 0
5247 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
5248 // icmp eq/ne %x, 0
5249 if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
5250 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5251 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
5252 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
5253 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
5254 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5255 }
5256
5257 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
5258 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
5259 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5261 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
5262 N1C->isAllOnes()) {
5263 return DAG.getSetCC(dl, VT, N0.getOperand(0),
5264 DAG.getConstant(0, dl, OpVT),
5266 }
5267
5268 // fold (setcc (trunc x) c) -> (setcc x c)
5269 if (N0.getOpcode() == ISD::TRUNCATE &&
5271 (N0->getFlags().hasNoSignedWrap() &&
5274 EVT NewVT = N0.getOperand(0).getValueType();
5275 SDValue NewConst = DAG.getConstant(
5277 ? C1.sext(NewVT.getSizeInBits())
5278 : C1.zext(NewVT.getSizeInBits()),
5279 dl, NewVT);
5280 return DAG.getSetCC(dl, VT, N0.getOperand(0), NewConst, Cond);
5281 }
5282
5283 if (SDValue V =
5284 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
5285 return V;
5286 }
5287
5288 // These simplifications apply to splat vectors as well.
5289 // TODO: Handle more splat vector cases.
5290 if (auto *N1C = isConstOrConstSplat(N1)) {
5291 const APInt &C1 = N1C->getAPIntValue();
5292
5293 APInt MinVal, MaxVal;
5294 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
5296 MinVal = APInt::getSignedMinValue(OperandBitSize);
5297 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
5298 } else {
5299 MinVal = APInt::getMinValue(OperandBitSize);
5300 MaxVal = APInt::getMaxValue(OperandBitSize);
5301 }
5302
5303 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
5304 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
5305 // X >= MIN --> true
5306 if (C1 == MinVal)
5307 return DAG.getBoolConstant(true, dl, VT, OpVT);
5308
5309 if (!VT.isVector()) { // TODO: Support this for vectors.
5310 // X >= C0 --> X > (C0 - 1)
5311 APInt C = C1 - 1;
5313 if ((DCI.isBeforeLegalizeOps() ||
5314 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5315 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5316 isLegalICmpImmediate(C.getSExtValue())))) {
5317 return DAG.getSetCC(dl, VT, N0,
5318 DAG.getConstant(C, dl, N1.getValueType()),
5319 NewCC);
5320 }
5321 }
5322 }
5323
5324 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
5325 // X <= MAX --> true
5326 if (C1 == MaxVal)
5327 return DAG.getBoolConstant(true, dl, VT, OpVT);
5328
5329 // X <= C0 --> X < (C0 + 1)
5330 if (!VT.isVector()) { // TODO: Support this for vectors.
5331 APInt C = C1 + 1;
5333 if ((DCI.isBeforeLegalizeOps() ||
5334 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5335 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5336 isLegalICmpImmediate(C.getSExtValue())))) {
5337 return DAG.getSetCC(dl, VT, N0,
5338 DAG.getConstant(C, dl, N1.getValueType()),
5339 NewCC);
5340 }
5341 }
5342 }
5343
5344 if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
5345 if (C1 == MinVal)
5346 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
5347
5348 // TODO: Support this for vectors after legalize ops.
5349 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5350 // Canonicalize setlt X, Max --> setne X, Max
5351 if (C1 == MaxVal)
5352 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5353
5354 // If we have setult X, 1, turn it into seteq X, 0
5355 if (C1 == MinVal+1)
5356 return DAG.getSetCC(dl, VT, N0,
5357 DAG.getConstant(MinVal, dl, N0.getValueType()),
5358 ISD::SETEQ);
5359 }
5360 }
5361
5362 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
5363 if (C1 == MaxVal)
5364 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
5365
5366 // TODO: Support this for vectors after legalize ops.
5367 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5368 // Canonicalize setgt X, Min --> setne X, Min
5369 if (C1 == MinVal)
5370 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5371
5372 // If we have setugt X, Max-1, turn it into seteq X, Max
5373 if (C1 == MaxVal-1)
5374 return DAG.getSetCC(dl, VT, N0,
5375 DAG.getConstant(MaxVal, dl, N0.getValueType()),
5376 ISD::SETEQ);
5377 }
5378 }
5379
5380 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
5381 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
5382 if (C1.isZero())
5383 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
5384 VT, N0, N1, Cond, DCI, dl))
5385 return CC;
5386
5387 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
5388 // For example, when high 32-bits of i64 X are known clear:
5389 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0
5390 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1
5391 bool CmpZero = N1C->isZero();
5392 bool CmpNegOne = N1C->isAllOnes();
5393 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
5394 // Match or(lo,shl(hi,bw/2)) pattern.
5395 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
5396 unsigned EltBits = V.getScalarValueSizeInBits();
5397 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
5398 return false;
5399 SDValue LHS = V.getOperand(0);
5400 SDValue RHS = V.getOperand(1);
5401 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
5402 // Unshifted element must have zero upperbits.
5403 if (RHS.getOpcode() == ISD::SHL &&
5404 isa<ConstantSDNode>(RHS.getOperand(1)) &&
5405 RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5406 DAG.MaskedValueIsZero(LHS, HiBits)) {
5407 Lo = LHS;
5408 Hi = RHS.getOperand(0);
5409 return true;
5410 }
5411 if (LHS.getOpcode() == ISD::SHL &&
5412 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5413 LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5414 DAG.MaskedValueIsZero(RHS, HiBits)) {
5415 Lo = RHS;
5416 Hi = LHS.getOperand(0);
5417 return true;
5418 }
5419 return false;
5420 };
5421
5422 auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
5423 unsigned EltBits = N0.getScalarValueSizeInBits();
5424 unsigned HalfBits = EltBits / 2;
5425 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
5426 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
5427 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
5428 SDValue NewN0 =
5429 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
5430 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
5431 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
5432 };
5433
5434 SDValue Lo, Hi;
5435 if (IsConcat(N0, Lo, Hi))
5436 return MergeConcat(Lo, Hi);
5437
5438 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
5439 SDValue Lo0, Lo1, Hi0, Hi1;
5440 if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
5441 IsConcat(N0.getOperand(1), Lo1, Hi1)) {
5442 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
5443 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
5444 }
5445 }
5446 }
5447 }
5448
5449 // If we have "setcc X, C0", check to see if we can shrink the immediate
5450 // by changing cc.
5451 // TODO: Support this for vectors after legalize ops.
5452 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5453 // SETUGT X, SINTMAX -> SETLT X, 0
5454 // SETUGE X, SINTMIN -> SETLT X, 0
5455 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
5456 (Cond == ISD::SETUGE && C1.isMinSignedValue()))
5457 return DAG.getSetCC(dl, VT, N0,
5458 DAG.getConstant(0, dl, N1.getValueType()),
5459 ISD::SETLT);
5460
5461 // SETULT X, SINTMIN -> SETGT X, -1
5462 // SETULE X, SINTMAX -> SETGT X, -1
5463 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
5464 (Cond == ISD::SETULE && C1.isMaxSignedValue()))
5465 return DAG.getSetCC(dl, VT, N0,
5466 DAG.getAllOnesConstant(dl, N1.getValueType()),
5467 ISD::SETGT);
5468 }
5469 }
5470
5471 // Back to non-vector simplifications.
5472 // TODO: Can we do these for vector splats?
5473 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5474 const APInt &C1 = N1C->getAPIntValue();
5475 EVT ShValTy = N0.getValueType();
5476
5477 // Fold bit comparisons when we can. This will result in an
5478 // incorrect value when boolean false is negative one, unless
5479 // the bitsize is 1 in which case the false value is the same
5480 // in practice regardless of the representation.
5481 if ((VT.getSizeInBits() == 1 ||
5483 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5484 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
5485 N0.getOpcode() == ISD::AND) {
5486 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5487 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
5488 // Perform the xform if the AND RHS is a single bit.
5489 unsigned ShCt = AndRHS->getAPIntValue().logBase2();
5490 if (AndRHS->getAPIntValue().isPowerOf2() &&
5491 !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5492 return DAG.getNode(
5493 ISD::TRUNCATE, dl, VT,
5494 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5495 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5496 }
5497 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
5498 // (X & 8) == 8 --> (X & 8) >> 3
5499 // Perform the xform if C1 is a single bit.
5500 unsigned ShCt = C1.logBase2();
5501 if (C1.isPowerOf2() && !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5502 return DAG.getNode(
5503 ISD::TRUNCATE, dl, VT,
5504 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5505 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5506 }
5507 }
5508 }
5509 }
5510
5511 if (C1.getSignificantBits() <= 64 &&
5513 // (X & -256) == 256 -> (X >> 8) == 1
5514 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5515 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5516 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5517 const APInt &AndRHSC = AndRHS->getAPIntValue();
5518 if (AndRHSC.isNegatedPowerOf2() && C1.isSubsetOf(AndRHSC)) {
5519 unsigned ShiftBits = AndRHSC.countr_zero();
5520 if (!shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5521 // If using an unsigned shift doesn't yield a legal compare
5522 // immediate, try using sra instead.
5523 APInt NewC = C1.lshr(ShiftBits);
5524 if (NewC.getSignificantBits() <= 64 &&
5526 APInt SignedC = C1.ashr(ShiftBits);
5527 if (SignedC.getSignificantBits() <= 64 &&
5529 SDValue Shift = DAG.getNode(
5530 ISD::SRA, dl, ShValTy, N0.getOperand(0),
5531 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5532 SDValue CmpRHS = DAG.getConstant(SignedC, dl, ShValTy);
5533 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5534 }
5535 }
5536 SDValue Shift = DAG.getNode(
5537 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5538 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5539 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5540 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5541 }
5542 }
5543 }
5544 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
5545 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
5546 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
5547 // X < 0x100000000 -> (X >> 32) < 1
5548 // X >= 0x100000000 -> (X >> 32) >= 1
5549 // X <= 0x0ffffffff -> (X >> 32) < 1
5550 // X > 0x0ffffffff -> (X >> 32) >= 1
5551 unsigned ShiftBits;
5552 APInt NewC = C1;
5553 ISD::CondCode NewCond = Cond;
5554 if (AdjOne) {
5555 ShiftBits = C1.countr_one();
5556 NewC = NewC + 1;
5557 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
5558 } else {
5559 ShiftBits = C1.countr_zero();
5560 }
5561 NewC.lshrInPlace(ShiftBits);
5562 if (ShiftBits && NewC.getSignificantBits() <= 64 &&
5564 !shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5565 SDValue Shift =
5566 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5567 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5568 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5569 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
5570 }
5571 }
5572 }
5573 }
5574
5576 auto *CFP = cast<ConstantFPSDNode>(N1);
5577 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
5578
5579 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
5580 // constant if knowing that the operand is non-nan is enough. We prefer to
5581 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
5582 // materialize 0.0.
5583 if (Cond == ISD::SETO || Cond == ISD::SETUO)
5584 return DAG.getSetCC(dl, VT, N0, N0, Cond);
5585
5586 // setcc (fneg x), C -> setcc swap(pred) x, -C
5587 if (N0.getOpcode() == ISD::FNEG) {
5589 if (DCI.isBeforeLegalizeOps() ||
5590 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
5591 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
5592 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
5593 }
5594 }
5595
5596 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf
5598 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) {
5599 bool IsFabs = N0.getOpcode() == ISD::FABS;
5600 SDValue Op = IsFabs ? N0.getOperand(0) : N0;
5601 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) {
5602 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf)
5603 : (IsFabs ? fcInf : fcPosInf);
5604 if (Cond == ISD::SETUEQ)
5605 Flag |= fcNan;
5606 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op,
5607 DAG.getTargetConstant(Flag, dl, MVT::i32));
5608 }
5609 }
5610
5611 // If the condition is not legal, see if we can find an equivalent one
5612 // which is legal.
5614 // If the comparison was an awkward floating-point == or != and one of
5615 // the comparison operands is infinity or negative infinity, convert the
5616 // condition to a less-awkward <= or >=.
5617 if (CFP->getValueAPF().isInfinity()) {
5618 bool IsNegInf = CFP->getValueAPF().isNegative();
5620 switch (Cond) {
5621 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
5622 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
5623 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
5624 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
5625 default: break;
5626 }
5627 if (NewCond != ISD::SETCC_INVALID &&
5628 isCondCodeLegal(NewCond, N0.getSimpleValueType()))
5629 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5630 }
5631 }
5632 }
5633
5634 if (N0 == N1) {
5635 // The sext(setcc()) => setcc() optimization relies on the appropriate
5636 // constant being emitted.
5637 assert(!N0.getValueType().isInteger() &&
5638 "Integer types should be handled by FoldSetCC");
5639
5640 bool EqTrue = ISD::isTrueWhenEqual(Cond);
5641 unsigned UOF = ISD::getUnorderedFlavor(Cond);
5642 if (UOF == 2) // FP operators that are undefined on NaNs.
5643 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5644 if (UOF == unsigned(EqTrue))
5645 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5646 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
5647 // if it is not already.
5648 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
5649 if (NewCond != Cond &&
5650 (DCI.isBeforeLegalizeOps() ||
5651 isCondCodeLegal(NewCond, N0.getSimpleValueType())))
5652 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5653 }
5654
5655 // ~X > ~Y --> Y > X
5656 // ~X < ~Y --> Y < X
5657 // ~X < C --> X > ~C
5658 // ~X > C --> X < ~C
5659 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) &&
5660 N0.getValueType().isInteger()) {
5661 if (isBitwiseNot(N0)) {
5662 if (isBitwiseNot(N1))
5663 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond);
5664
5667 SDValue Not = DAG.getNOT(dl, N1, OpVT);
5668 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond);
5669 }
5670 }
5671 }
5672
5673 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5674 N0.getValueType().isInteger()) {
5675 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
5676 N0.getOpcode() == ISD::XOR) {
5677 // Simplify (X+Y) == (X+Z) --> Y == Z
5678 if (N0.getOpcode() == N1.getOpcode()) {
5679 if (N0.getOperand(0) == N1.getOperand(0))
5680 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
5681 if (N0.getOperand(1) == N1.getOperand(1))
5682 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
5683 if (isCommutativeBinOp(N0.getOpcode())) {
5684 // If X op Y == Y op X, try other combinations.
5685 if (N0.getOperand(0) == N1.getOperand(1))
5686 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
5687 Cond);
5688 if (N0.getOperand(1) == N1.getOperand(0))
5689 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
5690 Cond);
5691 }
5692 }
5693
5694 // If RHS is a legal immediate value for a compare instruction, we need
5695 // to be careful about increasing register pressure needlessly.
5696 bool LegalRHSImm = false;
5697
5698 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
5699 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5700 // Turn (X+C1) == C2 --> X == C2-C1
5701 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
5702 return DAG.getSetCC(
5703 dl, VT, N0.getOperand(0),
5704 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
5705 dl, N0.getValueType()),
5706 Cond);
5707
5708 // Turn (X^C1) == C2 --> X == C1^C2
5709 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
5710 return DAG.getSetCC(
5711 dl, VT, N0.getOperand(0),
5712 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
5713 dl, N0.getValueType()),
5714 Cond);
5715 }
5716
5717 // Turn (C1-X) == C2 --> X == C1-C2
5718 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
5719 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
5720 return DAG.getSetCC(
5721 dl, VT, N0.getOperand(1),
5722 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
5723 dl, N0.getValueType()),
5724 Cond);
5725
5726 // Could RHSC fold directly into a compare?
5727 if (RHSC->getValueType(0).getSizeInBits() <= 64)
5728 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
5729 }
5730
5731 // (X+Y) == X --> Y == 0 and similar folds.
5732 // Don't do this if X is an immediate that can fold into a cmp
5733 // instruction and X+Y has other uses. It could be an induction variable
5734 // chain, and the transform would increase register pressure.
5735 if (!LegalRHSImm || N0.hasOneUse())
5736 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
5737 return V;
5738 }
5739
5740 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
5741 N1.getOpcode() == ISD::XOR)
5742 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
5743 return V;
5744
5745 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
5746 return V;
5747
5748 if (SDValue V = foldSetCCWithOr(VT, N0, N1, Cond, dl, DCI))
5749 return V;
5750 }
5751
5752 // Fold remainder of division by a constant.
5753 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
5754 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5755 // When division is cheap or optimizing for minimum size,
5756 // fall through to DIVREM creation by skipping this fold.
5757 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
5758 if (N0.getOpcode() == ISD::UREM) {
5759 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
5760 return Folded;
5761 } else if (N0.getOpcode() == ISD::SREM) {
5762 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
5763 return Folded;
5764 }
5765 }
5766 }
5767
5768 // Fold away ALL boolean setcc's.
5769 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
5770 SDValue Temp;
5771 switch (Cond) {
5772 default: llvm_unreachable("Unknown integer setcc!");
5773 case ISD::SETEQ: // X == Y -> ~(X^Y)
5774 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5775 N0 = DAG.getNOT(dl, Temp, OpVT);
5776 if (!DCI.isCalledByLegalizer())
5777 DCI.AddToWorklist(Temp.getNode());
5778 break;
5779 case ISD::SETNE: // X != Y --> (X^Y)
5780 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5781 break;
5782 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
5783 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
5784 Temp = DAG.getNOT(dl, N0, OpVT);
5785 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
5786 if (!DCI.isCalledByLegalizer())
5787 DCI.AddToWorklist(Temp.getNode());
5788 break;
5789 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
5790 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
5791 Temp = DAG.getNOT(dl, N1, OpVT);
5792 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
5793 if (!DCI.isCalledByLegalizer())
5794 DCI.AddToWorklist(Temp.getNode());
5795 break;
5796 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
5797 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
5798 Temp = DAG.getNOT(dl, N0, OpVT);
5799 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
5800 if (!DCI.isCalledByLegalizer())
5801 DCI.AddToWorklist(Temp.getNode());
5802 break;
5803 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
5804 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
5805 Temp = DAG.getNOT(dl, N1, OpVT);
5806 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
5807 break;
5808 }
5809 if (VT.getScalarType() != MVT::i1) {
5810 if (!DCI.isCalledByLegalizer())
5811 DCI.AddToWorklist(N0.getNode());
5812 // FIXME: If running after legalize, we probably can't do this.
5814 N0 = DAG.getNode(ExtendCode, dl, VT, N0);
5815 }
5816 return N0;
5817 }
5818
5819 // Fold (setcc (trunc x) (trunc y)) -> (setcc x y)
5820 if (N0.getOpcode() == ISD::TRUNCATE && N1.getOpcode() == ISD::TRUNCATE &&
5821 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
5823 N1->getFlags().hasNoUnsignedWrap()) ||
5825 N1->getFlags().hasNoSignedWrap())) &&
5827 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
5828 }
5829
5830 // Fold (setcc (sub nsw a, b), zero, s??) -> (setcc a, b, s??)
5831 // TODO: Remove that .isVector() check
5832 if (VT.isVector() && isZeroOrZeroSplat(N1) && N0.getOpcode() == ISD::SUB &&
5834 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), Cond);
5835 }
5836
5837 // Could not fold it.
5838 return SDValue();
5839}
5840
5841/// Returns true (and the GlobalValue and the offset) if the node is a
5842/// GlobalAddress + offset.
5844 int64_t &Offset) const {
5845
5846 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
5847
5848 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
5849 GA = GASD->getGlobal();
5850 Offset += GASD->getOffset();
5851 return true;
5852 }
5853
5854 if (N->isAnyAdd()) {
5855 SDValue N1 = N->getOperand(0);
5856 SDValue N2 = N->getOperand(1);
5857 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
5858 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
5859 Offset += V->getSExtValue();
5860 return true;
5861 }
5862 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
5863 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
5864 Offset += V->getSExtValue();
5865 return true;
5866 }
5867 }
5868 }
5869
5870 return false;
5871}
5872
5874 DAGCombinerInfo &DCI) const {
5875 // Default implementation: no optimization.
5876 return SDValue();
5877}
5878
5879//===----------------------------------------------------------------------===//
5880// Inline Assembler Implementation Methods
5881//===----------------------------------------------------------------------===//
5882
5885 unsigned S = Constraint.size();
5886
5887 if (S == 1) {
5888 switch (Constraint[0]) {
5889 default: break;
5890 case 'r':
5891 return C_RegisterClass;
5892 case 'm': // memory
5893 case 'o': // offsetable
5894 case 'V': // not offsetable
5895 return C_Memory;
5896 case 'p': // Address.
5897 return C_Address;
5898 case 'n': // Simple Integer
5899 case 'E': // Floating Point Constant
5900 case 'F': // Floating Point Constant
5901 return C_Immediate;
5902 case 'i': // Simple Integer or Relocatable Constant
5903 case 's': // Relocatable Constant
5904 case 'X': // Allow ANY value.
5905 case 'I': // Target registers.
5906 case 'J':
5907 case 'K':
5908 case 'L':
5909 case 'M':
5910 case 'N':
5911 case 'O':
5912 case 'P':
5913 case '<':
5914 case '>':
5915 return C_Other;
5916 }
5917 }
5918
5919 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
5920 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
5921 return C_Memory;
5922 return C_Register;
5923 }
5924 return C_Unknown;
5925}
5926
5927/// Try to replace an X constraint, which matches anything, with another that
5928/// has more specific requirements based on the type of the corresponding
5929/// operand.
5930const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5931 if (ConstraintVT.isInteger())
5932 return "r";
5933 if (ConstraintVT.isFloatingPoint())
5934 return "f"; // works for many targets
5935 return nullptr;
5936}
5937
5939 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
5940 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
5941 return SDValue();
5942}
5943
5944/// Lower the specified operand into the Ops vector.
5945/// If it is invalid, don't add anything to Ops.
5947 StringRef Constraint,
5948 std::vector<SDValue> &Ops,
5949 SelectionDAG &DAG) const {
5950
5951 if (Constraint.size() > 1)
5952 return;
5953
5954 char ConstraintLetter = Constraint[0];
5955 switch (ConstraintLetter) {
5956 default: break;
5957 case 'X': // Allows any operand
5958 case 'i': // Simple Integer or Relocatable Constant
5959 case 'n': // Simple Integer
5960 case 's': { // Relocatable Constant
5961
5963 uint64_t Offset = 0;
5964
5965 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
5966 // etc., since getelementpointer is variadic. We can't use
5967 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
5968 // while in this case the GA may be furthest from the root node which is
5969 // likely an ISD::ADD.
5970 while (true) {
5971 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
5972 // gcc prints these as sign extended. Sign extend value to 64 bits
5973 // now; without this it would get ZExt'd later in
5974 // ScheduleDAGSDNodes::EmitNode, which is very generic.
5975 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
5976 BooleanContent BCont = getBooleanContents(MVT::i64);
5977 ISD::NodeType ExtOpc =
5978 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
5979 int64_t ExtVal =
5980 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
5981 Ops.push_back(
5982 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
5983 return;
5984 }
5985 if (ConstraintLetter != 'n') {
5986 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5987 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5988 GA->getValueType(0),
5989 Offset + GA->getOffset()));
5990 return;
5991 }
5992 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
5993 Ops.push_back(DAG.getTargetBlockAddress(
5994 BA->getBlockAddress(), BA->getValueType(0),
5995 Offset + BA->getOffset(), BA->getTargetFlags()));
5996 return;
5997 }
5999 Ops.push_back(Op);
6000 return;
6001 }
6002 }
6003 const unsigned OpCode = Op.getOpcode();
6004 if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
6005 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
6006 Op = Op.getOperand(1);
6007 // Subtraction is not commutative.
6008 else if (OpCode == ISD::ADD &&
6009 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
6010 Op = Op.getOperand(0);
6011 else
6012 return;
6013 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
6014 continue;
6015 }
6016 return;
6017 }
6018 break;
6019 }
6020 }
6021}
6022
6026
6027std::pair<unsigned, const TargetRegisterClass *>
6029 StringRef Constraint,
6030 MVT VT) const {
6031 if (!Constraint.starts_with("{"))
6032 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
6033 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
6034
6035 // Remove the braces from around the name.
6036 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
6037
6038 std::pair<unsigned, const TargetRegisterClass *> R =
6039 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
6040
6041 // Figure out which register class contains this reg.
6042 for (const TargetRegisterClass &RC : RI->regclasses()) {
6043 // If none of the value types for this register class are valid, we
6044 // can't use it. For example, 64-bit reg classes on 32-bit targets.
6045 if (!isLegalRC(*RI, RC))
6046 continue;
6047
6048 for (const MCPhysReg &PR : RC) {
6049 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
6050 std::pair<unsigned, const TargetRegisterClass *> S =
6051 std::make_pair(PR, &RC);
6052
6053 // If this register class has the requested value type, return it,
6054 // otherwise keep searching and return the first class found
6055 // if no other is found which explicitly has the requested type.
6056 if (RI->isTypeLegalForClass(RC, VT))
6057 return S;
6058 if (!R.second)
6059 R = S;
6060 }
6061 }
6062 }
6063
6064 return R;
6065}
6066
6067//===----------------------------------------------------------------------===//
6068// Constraint Selection.
6069
6070/// Return true of this is an input operand that is a matching constraint like
6071/// "4".
6073 assert(!ConstraintCode.empty() && "No known constraint!");
6074 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
6075}
6076
6077/// If this is an input matching constraint, this method returns the output
6078/// operand it matches.
6080 assert(!ConstraintCode.empty() && "No known constraint!");
6081 return atoi(ConstraintCode.c_str());
6082}
6083
6084/// Split up the constraint string from the inline assembly value into the
6085/// specific constraints and their prefixes, and also tie in the associated
6086/// operand values.
6087/// If this returns an empty vector, and if the constraint string itself
6088/// isn't empty, there was an error parsing.
6091 const TargetRegisterInfo *TRI,
6092 const CallBase &Call) const {
6093 /// Information about all of the constraints.
6094 AsmOperandInfoVector ConstraintOperands;
6095 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
6096 unsigned maCount = 0; // Largest number of multiple alternative constraints.
6097
6098 // Do a prepass over the constraints, canonicalizing them, and building up the
6099 // ConstraintOperands list.
6100 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6101 unsigned ResNo = 0; // ResNo - The result number of the next output.
6102 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
6103
6104 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
6105 ConstraintOperands.emplace_back(std::move(CI));
6106 AsmOperandInfo &OpInfo = ConstraintOperands.back();
6107
6108 // Update multiple alternative constraint count.
6109 if (OpInfo.multipleAlternatives.size() > maCount)
6110 maCount = OpInfo.multipleAlternatives.size();
6111
6112 OpInfo.ConstraintVT = MVT::Other;
6113
6114 // Compute the value type for each operand.
6115 switch (OpInfo.Type) {
6116 case InlineAsm::isOutput: {
6117 // Indirect outputs just consume an argument.
6118 if (OpInfo.isIndirect) {
6119 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6120 break;
6121 }
6122
6123 // The return value of the call is this value. As such, there is no
6124 // corresponding argument.
6125 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
6126 EVT VT;
6127 if (auto *STy = dyn_cast<StructType>(Call.getType())) {
6128 VT = getAsmOperandValueType(DL, STy->getElementType(ResNo));
6129 } else {
6130 assert(ResNo == 0 && "Asm only has one result!");
6131 VT = getAsmOperandValueType(DL, Call.getType());
6132 }
6133 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6134 ++ResNo;
6135 break;
6136 }
6137 case InlineAsm::isInput:
6138 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6139 break;
6140 case InlineAsm::isLabel:
6141 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo);
6142 ++LabelNo;
6143 continue;
6145 // Nothing to do.
6146 break;
6147 }
6148
6149 if (OpInfo.CallOperandVal) {
6150 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
6151 if (OpInfo.isIndirect) {
6152 OpTy = Call.getParamElementType(ArgNo);
6153 assert(OpTy && "Indirect operand must have elementtype attribute");
6154 }
6155
6156 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6158 if (STy->getNumElements() == 1)
6159 OpTy = STy->getElementType(0);
6160
6161 // If OpTy is not a single value, it may be a struct/union that we
6162 // can tile with integers.
6163 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6164 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6165 switch (BitSize) {
6166 default: break;
6167 case 1:
6168 case 8:
6169 case 16:
6170 case 32:
6171 case 64:
6172 case 128:
6173 OpTy = IntegerType::get(OpTy->getContext(), BitSize);
6174 break;
6175 }
6176 }
6177
6178 EVT VT = getAsmOperandValueType(DL, OpTy, true);
6179 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6180 ArgNo++;
6181 }
6182 }
6183
6184 // If we have multiple alternative constraints, select the best alternative.
6185 if (!ConstraintOperands.empty()) {
6186 if (maCount) {
6187 unsigned bestMAIndex = 0;
6188 int bestWeight = -1;
6189 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
6190 int weight = -1;
6191 unsigned maIndex;
6192 // Compute the sums of the weights for each alternative, keeping track
6193 // of the best (highest weight) one so far.
6194 for (maIndex = 0; maIndex < maCount; ++maIndex) {
6195 int weightSum = 0;
6196 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6197 cIndex != eIndex; ++cIndex) {
6198 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6199 if (OpInfo.Type == InlineAsm::isClobber)
6200 continue;
6201
6202 // If this is an output operand with a matching input operand,
6203 // look up the matching input. If their types mismatch, e.g. one
6204 // is an integer, the other is floating point, or their sizes are
6205 // different, flag it as an maCantMatch.
6206 if (OpInfo.hasMatchingInput()) {
6207 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6208 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6209 if ((OpInfo.ConstraintVT.isInteger() !=
6210 Input.ConstraintVT.isInteger()) ||
6211 (OpInfo.ConstraintVT.getSizeInBits() !=
6212 Input.ConstraintVT.getSizeInBits())) {
6213 weightSum = -1; // Can't match.
6214 break;
6215 }
6216 }
6217 }
6218 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
6219 if (weight == -1) {
6220 weightSum = -1;
6221 break;
6222 }
6223 weightSum += weight;
6224 }
6225 // Update best.
6226 if (weightSum > bestWeight) {
6227 bestWeight = weightSum;
6228 bestMAIndex = maIndex;
6229 }
6230 }
6231
6232 // Now select chosen alternative in each constraint.
6233 for (AsmOperandInfo &cInfo : ConstraintOperands)
6234 if (cInfo.Type != InlineAsm::isClobber)
6235 cInfo.selectAlternative(bestMAIndex);
6236 }
6237 }
6238
6239 // Check and hook up tied operands, choose constraint code to use.
6240 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6241 cIndex != eIndex; ++cIndex) {
6242 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6243
6244 // If this is an output operand with a matching input operand, look up the
6245 // matching input. If their types mismatch, e.g. one is an integer, the
6246 // other is floating point, or their sizes are different, flag it as an
6247 // error.
6248 if (OpInfo.hasMatchingInput()) {
6249 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6250
6251 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6252 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6253 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6254 OpInfo.ConstraintVT);
6255 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6256 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6257 Input.ConstraintVT);
6258 const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() ||
6259 OpInfo.ConstraintVT.isFloatingPoint();
6260 const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() ||
6261 Input.ConstraintVT.isFloatingPoint();
6262 if ((OutOpIsIntOrFP != InOpIsIntOrFP) ||
6263 (MatchRC.second != InputRC.second)) {
6264 report_fatal_error("Unsupported asm: input constraint"
6265 " with a matching output constraint of"
6266 " incompatible type!");
6267 }
6268 }
6269 }
6270 }
6271
6272 return ConstraintOperands;
6273}
6274
6275/// Return a number indicating our preference for chosing a type of constraint
6276/// over another, for the purpose of sorting them. Immediates are almost always
6277/// preferrable (when they can be emitted). A higher return value means a
6278/// stronger preference for one constraint type relative to another.
6279/// FIXME: We should prefer registers over memory but doing so may lead to
6280/// unrecoverable register exhaustion later.
6281/// https://github.com/llvm/llvm-project/issues/20571
6283 switch (CT) {
6286 return 4;
6289 return 3;
6291 return 2;
6293 return 1;
6295 return 0;
6296 }
6297 llvm_unreachable("Invalid constraint type");
6298}
6299
6300/// Examine constraint type and operand type and determine a weight value.
6301/// This object must already have been set up with the operand type
6302/// and the current alternative constraint selected.
6305 AsmOperandInfo &info, int maIndex) const {
6307 if (maIndex >= (int)info.multipleAlternatives.size())
6308 rCodes = &info.Codes;
6309 else
6310 rCodes = &info.multipleAlternatives[maIndex].Codes;
6311 ConstraintWeight BestWeight = CW_Invalid;
6312
6313 // Loop over the options, keeping track of the most general one.
6314 for (const std::string &rCode : *rCodes) {
6315 ConstraintWeight weight =
6316 getSingleConstraintMatchWeight(info, rCode.c_str());
6317 if (weight > BestWeight)
6318 BestWeight = weight;
6319 }
6320
6321 return BestWeight;
6322}
6323
6324/// Examine constraint type and operand type and determine a weight value.
6325/// This object must already have been set up with the operand type
6326/// and the current alternative constraint selected.
6329 AsmOperandInfo &info, const char *constraint) const {
6331 Value *CallOperandVal = info.CallOperandVal;
6332 // If we don't have a value, we can't do a match,
6333 // but allow it at the lowest weight.
6334 if (!CallOperandVal)
6335 return CW_Default;
6336 // Look at the constraint type.
6337 switch (*constraint) {
6338 case 'i': // immediate integer.
6339 case 'n': // immediate integer with a known value.
6340 if (isa<ConstantInt>(CallOperandVal))
6341 weight = CW_Constant;
6342 break;
6343 case 's': // non-explicit intregal immediate.
6344 if (isa<GlobalValue>(CallOperandVal))
6345 weight = CW_Constant;
6346 break;
6347 case 'E': // immediate float if host format.
6348 case 'F': // immediate float.
6349 if (isa<ConstantFP>(CallOperandVal))
6350 weight = CW_Constant;
6351 break;
6352 case '<': // memory operand with autodecrement.
6353 case '>': // memory operand with autoincrement.
6354 case 'm': // memory operand.
6355 case 'o': // offsettable memory operand
6356 case 'V': // non-offsettable memory operand
6357 weight = CW_Memory;
6358 break;
6359 case 'r': // general register.
6360 case 'g': // general register, memory operand or immediate integer.
6361 // note: Clang converts "g" to "imr".
6362 if (CallOperandVal->getType()->isIntegerTy())
6363 weight = CW_Register;
6364 break;
6365 case 'X': // any operand.
6366 default:
6367 weight = CW_Default;
6368 break;
6369 }
6370 return weight;
6371}
6372
6373/// If there are multiple different constraints that we could pick for this
6374/// operand (e.g. "imr") try to pick the 'best' one.
6375/// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall
6376/// into seven classes:
6377/// Register -> one specific register
6378/// RegisterClass -> a group of regs
6379/// Memory -> memory
6380/// Address -> a symbolic memory reference
6381/// Immediate -> immediate values
6382/// Other -> magic values (such as "Flag Output Operands")
6383/// Unknown -> something we don't recognize yet and can't handle
6384/// Ideally, we would pick the most specific constraint possible: if we have
6385/// something that fits into a register, we would pick it. The problem here
6386/// is that if we have something that could either be in a register or in
6387/// memory that use of the register could cause selection of *other*
6388/// operands to fail: they might only succeed if we pick memory. Because of
6389/// this the heuristic we use is:
6390///
6391/// 1) If there is an 'other' constraint, and if the operand is valid for
6392/// that constraint, use it. This makes us take advantage of 'i'
6393/// constraints when available.
6394/// 2) Otherwise, pick the most general constraint present. This prefers
6395/// 'm' over 'r', for example.
6396///
6398 TargetLowering::AsmOperandInfo &OpInfo) const {
6399 ConstraintGroup Ret;
6400
6401 Ret.reserve(OpInfo.Codes.size());
6402 for (StringRef Code : OpInfo.Codes) {
6404
6405 // Indirect 'other' or 'immediate' constraints are not allowed.
6406 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
6407 CType == TargetLowering::C_Register ||
6409 continue;
6410
6411 // Things with matching constraints can only be registers, per gcc
6412 // documentation. This mainly affects "g" constraints.
6413 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
6414 continue;
6415
6416 Ret.emplace_back(Code, CType);
6417 }
6418
6420 return getConstraintPiority(a.second) > getConstraintPiority(b.second);
6421 });
6422
6423 return Ret;
6424}
6425
6426/// If we have an immediate, see if we can lower it. Return true if we can,
6427/// false otherwise.
6429 SDValue Op, SelectionDAG *DAG,
6430 const TargetLowering &TLI) {
6431
6432 assert((P.second == TargetLowering::C_Other ||
6433 P.second == TargetLowering::C_Immediate) &&
6434 "need immediate or other");
6435
6436 if (!Op.getNode())
6437 return false;
6438
6439 std::vector<SDValue> ResultOps;
6440 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG);
6441 return !ResultOps.empty();
6442}
6443
6444/// Determines the constraint code and constraint type to use for the specific
6445/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
6447 SDValue Op,
6448 SelectionDAG *DAG) const {
6449 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
6450
6451 // Single-letter constraints ('r') are very common.
6452 if (OpInfo.Codes.size() == 1) {
6453 OpInfo.ConstraintCode = OpInfo.Codes[0];
6454 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6455 } else {
6457 if (G.empty())
6458 return;
6459
6460 unsigned BestIdx = 0;
6461 for (const unsigned E = G.size();
6462 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other ||
6463 G[BestIdx].second == TargetLowering::C_Immediate);
6464 ++BestIdx) {
6465 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this))
6466 break;
6467 // If we're out of constraints, just pick the first one.
6468 if (BestIdx + 1 == E) {
6469 BestIdx = 0;
6470 break;
6471 }
6472 }
6473
6474 OpInfo.ConstraintCode = G[BestIdx].first;
6475 OpInfo.ConstraintType = G[BestIdx].second;
6476 }
6477
6478 // 'X' matches anything.
6479 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
6480 // Constants are handled elsewhere. For Functions, the type here is the
6481 // type of the result, which is not what we want to look at; leave them
6482 // alone.
6483 Value *v = OpInfo.CallOperandVal;
6484 if (isa<ConstantInt>(v) || isa<Function>(v)) {
6485 return;
6486 }
6487
6488 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
6489 OpInfo.ConstraintCode = "i";
6490 return;
6491 }
6492
6493 // Otherwise, try to resolve it to something we know about by looking at
6494 // the actual operand type.
6495 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
6496 OpInfo.ConstraintCode = Repl;
6497 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6498 }
6499 }
6500}
6501
6502/// Given an exact SDIV by a constant, create a multiplication
6503/// with the multiplicative inverse of the constant.
6504/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6506 const SDLoc &dl, SelectionDAG &DAG,
6507 SmallVectorImpl<SDNode *> &Created) {
6508 SDValue Op0 = N->getOperand(0);
6509 SDValue Op1 = N->getOperand(1);
6510 EVT VT = N->getValueType(0);
6511 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6512 EVT ShSVT = ShVT.getScalarType();
6513
6514 bool UseSRA = false;
6515 SmallVector<SDValue, 16> Shifts, Factors;
6516
6517 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6518 if (C->isZero())
6519 return false;
6520
6521 EVT CT = C->getValueType(0);
6522 APInt Divisor = C->getAPIntValue();
6523 unsigned Shift = Divisor.countr_zero();
6524 if (Shift) {
6525 Divisor.ashrInPlace(Shift);
6526 UseSRA = true;
6527 }
6528 APInt Factor = Divisor.multiplicativeInverse();
6529 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6530 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6531 return true;
6532 };
6533
6534 // Collect all magic values from the build vector.
6535 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
6536 return SDValue();
6537
6538 SDValue Shift, Factor;
6539 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6540 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6541 Factor = DAG.getBuildVector(VT, dl, Factors);
6542 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6543 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6544 "Expected matchUnaryPredicate to return one element for scalable "
6545 "vectors");
6546 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6547 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6548 } else {
6549 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6550 Shift = Shifts[0];
6551 Factor = Factors[0];
6552 }
6553
6554 SDValue Res = Op0;
6555 if (UseSRA) {
6556 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, SDNodeFlags::Exact);
6557 Created.push_back(Res.getNode());
6558 }
6559
6560 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6561}
6562
6563/// Given an exact UDIV by a constant, create a multiplication
6564/// with the multiplicative inverse of the constant.
6565/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6567 const SDLoc &dl, SelectionDAG &DAG,
6568 SmallVectorImpl<SDNode *> &Created) {
6569 EVT VT = N->getValueType(0);
6570 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6571 EVT ShSVT = ShVT.getScalarType();
6572
6573 bool UseSRL = false;
6574 SmallVector<SDValue, 16> Shifts, Factors;
6575
6576 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6577 if (C->isZero())
6578 return false;
6579
6580 EVT CT = C->getValueType(0);
6581 APInt Divisor = C->getAPIntValue();
6582 unsigned Shift = Divisor.countr_zero();
6583 if (Shift) {
6584 Divisor.lshrInPlace(Shift);
6585 UseSRL = true;
6586 }
6587 // Calculate the multiplicative inverse modulo BW.
6588 APInt Factor = Divisor.multiplicativeInverse();
6589 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6590 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6591 return true;
6592 };
6593
6594 SDValue Op1 = N->getOperand(1);
6595
6596 // Collect all magic values from the build vector.
6597 if (!ISD::matchUnaryPredicate(Op1, BuildUDIVPattern))
6598 return SDValue();
6599
6600 SDValue Shift, Factor;
6601 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6602 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6603 Factor = DAG.getBuildVector(VT, dl, Factors);
6604 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6605 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6606 "Expected matchUnaryPredicate to return one element for scalable "
6607 "vectors");
6608 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6609 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6610 } else {
6611 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6612 Shift = Shifts[0];
6613 Factor = Factors[0];
6614 }
6615
6616 SDValue Res = N->getOperand(0);
6617 if (UseSRL) {
6618 Res = DAG.getNode(ISD::SRL, dl, VT, Res, Shift, SDNodeFlags::Exact);
6619 Created.push_back(Res.getNode());
6620 }
6621
6622 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6623}
6624
6626 SelectionDAG &DAG,
6627 SmallVectorImpl<SDNode *> &Created) const {
6628 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
6629 if (isIntDivCheap(N->getValueType(0), Attr))
6630 return SDValue(N, 0); // Lower SDIV as SDIV
6631 return SDValue();
6632}
6633
6634SDValue
6636 SelectionDAG &DAG,
6637 SmallVectorImpl<SDNode *> &Created) const {
6638 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
6639 if (isIntDivCheap(N->getValueType(0), Attr))
6640 return SDValue(N, 0); // Lower SREM as SREM
6641 return SDValue();
6642}
6643
6644/// Build sdiv by power-of-2 with conditional move instructions
6645/// Ref: "Hacker's Delight" by Henry Warren 10-1
6646/// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into:
6647/// bgez x, label
6648/// add x, x, 2**k-1
6649/// label:
6650/// sra res, x, k
6651/// neg res, res (when the divisor is negative)
6653 SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
6654 SmallVectorImpl<SDNode *> &Created) const {
6655 unsigned Lg2 = Divisor.countr_zero();
6656 EVT VT = N->getValueType(0);
6657
6658 SDLoc DL(N);
6659 SDValue N0 = N->getOperand(0);
6660 SDValue Zero = DAG.getConstant(0, DL, VT);
6661 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
6662 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
6663
6664 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
6665 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6666 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT);
6667 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6668 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
6669
6670 Created.push_back(Cmp.getNode());
6671 Created.push_back(Add.getNode());
6672 Created.push_back(CMov.getNode());
6673
6674 // Divide by pow2.
6675 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, CMov,
6676 DAG.getShiftAmountConstant(Lg2, VT, DL));
6677
6678 // If we're dividing by a positive value, we're done. Otherwise, we must
6679 // negate the result.
6680 if (Divisor.isNonNegative())
6681 return SRA;
6682
6683 Created.push_back(SRA.getNode());
6684 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
6685}
6686
6687/// Given an ISD::SDIV node expressing a divide by constant,
6688/// return a DAG expression to select that will generate the same value by
6689/// multiplying by a magic number.
6690/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
6692 bool IsAfterLegalization,
6693 bool IsAfterLegalTypes,
6694 SmallVectorImpl<SDNode *> &Created) const {
6695 SDLoc dl(N);
6696
6697 // If the sdiv has an 'exact' bit we can use a simpler lowering.
6698 if (N->getFlags().hasExact())
6699 return BuildExactSDIV(*this, N, dl, DAG, Created);
6700
6701 EVT VT = N->getValueType(0);
6702 EVT SVT = VT.getScalarType();
6703 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6704 EVT ShSVT = ShVT.getScalarType();
6705 unsigned EltBits = VT.getScalarSizeInBits();
6706 EVT MulVT;
6707
6708 // Check to see if we can do this.
6709 // FIXME: We should be more aggressive here.
6710 EVT QueryVT = VT;
6711 if (VT.isVector()) {
6712 // If the vector type will be legalized to a vector type with the same
6713 // element type, allow the transform before type legalization if MULHS or
6714 // SMUL_LOHI are supported.
6715 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
6716 if (!QueryVT.isVector() ||
6718 return SDValue();
6719 } else if (!isTypeLegal(VT)) {
6720 // Limit this to simple scalars for now.
6721 if (!VT.isSimple())
6722 return SDValue();
6723
6724 // If this type will be promoted to a large enough type with a legal
6725 // multiply operation, we can go ahead and do this transform.
6727 return SDValue();
6728
6729 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
6730 if (MulVT.getSizeInBits() < (2 * EltBits) ||
6731 !isOperationLegal(ISD::MUL, MulVT))
6732 return SDValue();
6733 }
6734
6735 bool HasMULHS =
6736 isOperationLegalOrCustom(ISD::MULHS, QueryVT, IsAfterLegalization);
6737 bool HasSMUL_LOHI =
6738 isOperationLegalOrCustom(ISD::SMUL_LOHI, QueryVT, IsAfterLegalization);
6739
6740 if (isTypeLegal(VT) && !HasMULHS && !HasSMUL_LOHI && MulVT == EVT()) {
6741 // If type twice as wide legal, widen and use a mul plus a shift.
6742 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
6743 // Some targets like AMDGPU try to go from SDIV to SDIVREM which is then
6744 // custom lowered. This is very expensive so avoid it at all costs for
6745 // constant divisors.
6746 if ((!IsAfterLegalTypes && isOperationExpand(ISD::SDIV, VT) &&
6749 MulVT = WideVT;
6750 }
6751
6752 if (!HasMULHS && !HasSMUL_LOHI && MulVT == EVT())
6753 return SDValue();
6754
6755 // If we're after type legalization and SVT is not legal, use the
6756 // promoted type for creating constants to avoid creating nodes with
6757 // illegal types.
6758 if (IsAfterLegalTypes && VT.isVector()) {
6759 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
6760 if (SVT.bitsLT(VT.getScalarType()))
6761 return SDValue();
6762 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
6763 if (ShSVT.bitsLT(ShVT.getScalarType()))
6764 return SDValue();
6765 }
6766 const unsigned SVTBits = SVT.getSizeInBits();
6767
6768 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
6769
6770 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6771 if (C->isZero())
6772 return false;
6773 // Truncate the divisor to the target scalar type in case it was promoted
6774 // during type legalization.
6775 APInt Divisor = C->getAPIntValue().trunc(EltBits);
6777 int NumeratorFactor = 0;
6778 int ShiftMask = -1;
6779
6780 if (Divisor.isOne() || Divisor.isAllOnes()) {
6781 // If d is +1/-1, we just multiply the numerator by +1/-1.
6782 NumeratorFactor = Divisor.getSExtValue();
6783 magics.Magic = 0;
6784 magics.ShiftAmount = 0;
6785 ShiftMask = 0;
6786 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
6787 // If d > 0 and m < 0, add the numerator.
6788 NumeratorFactor = 1;
6789 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
6790 // If d < 0 and m > 0, subtract the numerator.
6791 NumeratorFactor = -1;
6792 }
6793
6794 MagicFactors.push_back(
6795 DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT));
6796 Factors.push_back(DAG.getSignedConstant(NumeratorFactor, dl, SVT));
6797 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
6798 ShiftMasks.push_back(DAG.getSignedConstant(ShiftMask, dl, SVT));
6799 return true;
6800 };
6801
6802 SDValue N0 = N->getOperand(0);
6803 SDValue N1 = N->getOperand(1);
6804
6805 // Collect the shifts / magic values from each element.
6806 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern, /*AllowUndefs=*/false,
6807 /*AllowTruncation=*/true))
6808 return SDValue();
6809
6810 SDValue MagicFactor, Factor, Shift, ShiftMask;
6811 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
6812 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
6813 Factor = DAG.getBuildVector(VT, dl, Factors);
6814 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6815 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
6816 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
6817 assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
6818 Shifts.size() == 1 && ShiftMasks.size() == 1 &&
6819 "Expected matchUnaryPredicate to return one element for scalable "
6820 "vectors");
6821 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
6822 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6823 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6824 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
6825 } else {
6826 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
6827 MagicFactor = MagicFactors[0];
6828 Factor = Factors[0];
6829 Shift = Shifts[0];
6830 ShiftMask = ShiftMasks[0];
6831 }
6832
6833 // Multiply the numerator (operand 0) by the magic value.
6834 auto GetMULHS = [&](SDValue X, SDValue Y) {
6835 if (HasMULHS)
6836 return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
6837 if (HasSMUL_LOHI) {
6838 SDValue LoHi =
6839 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
6840 return LoHi.getValue(1);
6841 }
6842
6843 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
6844 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
6845 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
6846 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
6847 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
6848 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
6849 };
6850
6851 SDValue Q = GetMULHS(N0, MagicFactor);
6852 if (!Q)
6853 return SDValue();
6854
6855 Created.push_back(Q.getNode());
6856
6857 // (Optionally) Add/subtract the numerator using Factor.
6858 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
6859 Created.push_back(Factor.getNode());
6860 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
6861 Created.push_back(Q.getNode());
6862
6863 // Shift right algebraic by shift value.
6864 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
6865 Created.push_back(Q.getNode());
6866
6867 // Extract the sign bit, mask it and add it to the quotient.
6868 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
6869 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
6870 Created.push_back(T.getNode());
6871 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
6872 Created.push_back(T.getNode());
6873 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
6874}
6875
6876/// Given an ISD::UDIV node expressing a divide by constant,
6877/// return a DAG expression to select that will generate the same value by
6878/// multiplying by a magic number.
6879/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
6881 bool IsAfterLegalization,
6882 bool IsAfterLegalTypes,
6883 SmallVectorImpl<SDNode *> &Created) const {
6884 SDLoc dl(N);
6885
6886 // If the udiv has an 'exact' bit we can use a simpler lowering.
6887 if (N->getFlags().hasExact())
6888 return BuildExactUDIV(*this, N, dl, DAG, Created);
6889
6890 EVT VT = N->getValueType(0);
6891 EVT SVT = VT.getScalarType();
6892 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6893 EVT ShSVT = ShVT.getScalarType();
6894 unsigned EltBits = VT.getScalarSizeInBits();
6895 EVT MulVT;
6896
6897 // Check to see if we can do this.
6898 // FIXME: We should be more aggressive here.
6899 EVT QueryVT = VT;
6900 if (VT.isVector()) {
6901 // If the vector type will be legalized to a vector type with the same
6902 // element type, allow the transform before type legalization if MULHU or
6903 // UMUL_LOHI are supported.
6904 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
6905 if (!QueryVT.isVector() ||
6907 return SDValue();
6908 } else if (!isTypeLegal(VT)) {
6909 // Limit this to simple scalars for now.
6910 if (!VT.isSimple())
6911 return SDValue();
6912
6913 // If this type will be promoted to a large enough type with a legal
6914 // multiply operation, we can go ahead and do this transform.
6916 return SDValue();
6917
6918 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
6919 if (MulVT.getSizeInBits() < (2 * EltBits) ||
6920 !isOperationLegal(ISD::MUL, MulVT))
6921 return SDValue();
6922 }
6923
6924 bool HasMULHU =
6925 isOperationLegalOrCustom(ISD::MULHU, QueryVT, IsAfterLegalization);
6926 bool HasUMUL_LOHI =
6927 isOperationLegalOrCustom(ISD::UMUL_LOHI, QueryVT, IsAfterLegalization);
6928
6929 if (isTypeLegal(VT) && !HasMULHU && !HasUMUL_LOHI && MulVT == EVT()) {
6930 // If type twice as wide legal, widen and use a mul plus a shift.
6931 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
6932 // Some targets like AMDGPU try to go from UDIV to UDIVREM which is then
6933 // custom lowered. This is very expensive so avoid it at all costs for
6934 // constant divisors.
6935 if ((!IsAfterLegalTypes && isOperationExpand(ISD::UDIV, VT) &&
6938 MulVT = WideVT;
6939 }
6940
6941 if (!HasMULHU && !HasUMUL_LOHI && MulVT == EVT())
6942 return SDValue();
6943
6944 SDValue N0 = N->getOperand(0);
6945 SDValue N1 = N->getOperand(1);
6946
6947 // Try to use leading zeros of the dividend to reduce the multiplier and
6948 // avoid expensive fixups.
6949 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
6950
6951 // If we're after type legalization and SVT is not legal, use the
6952 // promoted type for creating constants to avoid creating nodes with
6953 // illegal types.
6954 if (IsAfterLegalTypes && VT.isVector()) {
6955 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
6956 if (SVT.bitsLT(VT.getScalarType()))
6957 return SDValue();
6958 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
6959 if (ShSVT.bitsLT(ShVT.getScalarType()))
6960 return SDValue();
6961 }
6962 const unsigned SVTBits = SVT.getSizeInBits();
6963
6964 // Allow i32 to be widened to i64 for uncooperative divisors if i64 MULHU or
6965 // UMUL_LOHI is supported.
6966 const EVT WideSVT = MVT::i64;
6967 const bool HasWideMULHU =
6968 VT == MVT::i32 &&
6969 isOperationLegalOrCustom(ISD::MULHU, WideSVT, IsAfterLegalization);
6970 const bool HasWideUMUL_LOHI =
6971 VT == MVT::i32 &&
6972 isOperationLegalOrCustom(ISD::UMUL_LOHI, WideSVT, IsAfterLegalization);
6973 const bool AllowWiden = (HasWideMULHU || HasWideUMUL_LOHI);
6974
6975 // For even divisors with a 33-bit magic number, the widened high-multiply
6976 // path is only worthwhile over the even-divisor rewrite on targets that
6977 // zero-extend i32 to i64 for free (e.g. x86-64 and AArch64). Elsewhere (e.g.
6978 // RISC-V) keep the even-divisor rewrite, which avoids the explicit extension.
6979 const bool AllowEvenToWiden = AllowWiden && isZExtFree(VT, WideSVT);
6980
6981 bool UseNPQ = false, UsePreShift = false, UsePostShift = false;
6982 bool UseWiden = false;
6983 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
6984
6985 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6986 if (C->isZero())
6987 return false;
6988 // Truncate the divisor to the target scalar type in case it was promoted
6989 // during type legalization.
6990 APInt Divisor = C->getAPIntValue().trunc(EltBits);
6991
6992 SDValue PreShift, MagicFactor, NPQFactor, PostShift;
6993
6994 // Magic algorithm doesn't work for division by 1. We need to emit a select
6995 // at the end.
6996 if (Divisor.isOne()) {
6997 PreShift = PostShift = DAG.getUNDEF(ShSVT);
6998 MagicFactor = NPQFactor = DAG.getUNDEF(SVT);
6999 } else {
7002 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()),
7003 /*AllowEvenDivisorOptimization=*/!AllowEvenToWiden,
7004 /*AllowWidenOptimization=*/AllowWiden);
7005
7006 if (magics.Widen) {
7007 UseWiden = true;
7008 MagicFactor = DAG.getConstant(magics.Magic, dl, WideSVT);
7009 } else {
7010 MagicFactor = DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT);
7011 }
7012
7013 assert(magics.PreShift < Divisor.getBitWidth() &&
7014 "We shouldn't generate an undefined shift!");
7015 assert(magics.PostShift < Divisor.getBitWidth() &&
7016 "We shouldn't generate an undefined shift!");
7017 assert((!magics.IsAdd || magics.PreShift == 0) &&
7018 "Unexpected pre-shift");
7019 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT);
7020 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT);
7021 NPQFactor = DAG.getConstant(
7022 magics.IsAdd ? APInt::getOneBitSet(SVTBits, EltBits - 1)
7023 : APInt::getZero(SVTBits),
7024 dl, SVT);
7025 UseNPQ |= magics.IsAdd;
7026 UsePreShift |= magics.PreShift != 0;
7027 UsePostShift |= magics.PostShift != 0;
7028 }
7029
7030 PreShifts.push_back(PreShift);
7031 MagicFactors.push_back(MagicFactor);
7032 NPQFactors.push_back(NPQFactor);
7033 PostShifts.push_back(PostShift);
7034 return true;
7035 };
7036
7037 // Collect the shifts/magic values from each element.
7038 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern, /*AllowUndefs=*/false,
7039 /*AllowTruncation=*/true))
7040 return SDValue();
7041
7042 SDValue PreShift, PostShift, MagicFactor, NPQFactor;
7043 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7044 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
7045 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7046 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
7047 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
7048 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7049 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
7050 NPQFactors.size() == 1 && PostShifts.size() == 1 &&
7051 "Expected matchUnaryPredicate to return one for scalable vectors");
7052 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
7053 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7054 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
7055 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
7056 } else {
7057 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7058 PreShift = PreShifts[0];
7059 MagicFactor = MagicFactors[0];
7060 PostShift = PostShifts[0];
7061 }
7062
7063 if (UseWiden) {
7064 // Compute: (WideSVT(x) * MagicFactor) >> WideSVTBits.
7065 SDValue WideN0 = DAG.getNode(ISD::ZERO_EXTEND, dl, WideSVT, N0);
7066
7067 // Perform WideSVTxWideSVT -> 2*WideSVT multiplication and extract high
7068 // WideSVT bits
7069 SDValue High;
7070 if (HasWideMULHU) {
7071 High = DAG.getNode(ISD::MULHU, dl, WideSVT, WideN0, MagicFactor);
7072 } else {
7073 assert(HasWideUMUL_LOHI);
7074 SDValue LoHi =
7075 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(WideSVT, WideSVT),
7076 WideN0, MagicFactor);
7077 High = LoHi.getValue(1);
7078 }
7079
7080 Created.push_back(High.getNode());
7081 return DAG.getNode(ISD::TRUNCATE, dl, VT, High);
7082 }
7083
7084 SDValue Q = N0;
7085 if (UsePreShift) {
7086 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
7087 Created.push_back(Q.getNode());
7088 }
7089
7090 auto GetMULHU = [&](SDValue X, SDValue Y) {
7091 if (HasMULHU)
7092 return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
7093 if (HasUMUL_LOHI) {
7094 SDValue LoHi =
7095 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7096 return LoHi.getValue(1);
7097 }
7098
7099 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
7100 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
7101 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7102 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7103 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7104 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7105 };
7106
7107 // Multiply the numerator (operand 0) by the magic value.
7108 Q = GetMULHU(Q, MagicFactor);
7109 if (!Q)
7110 return SDValue();
7111
7112 Created.push_back(Q.getNode());
7113
7114 if (UseNPQ) {
7115 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
7116 Created.push_back(NPQ.getNode());
7117
7118 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
7119 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
7120 if (VT.isVector())
7121 NPQ = GetMULHU(NPQ, NPQFactor);
7122 else
7123 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
7124
7125 Created.push_back(NPQ.getNode());
7126
7127 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
7128 Created.push_back(Q.getNode());
7129 }
7130
7131 if (UsePostShift) {
7132 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
7133 Created.push_back(Q.getNode());
7134 }
7135
7136 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7137
7138 SDValue One = DAG.getConstant(1, dl, VT);
7139 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
7140 return DAG.getSelect(dl, VT, IsOne, N0, Q);
7141}
7142
7143/// If all values in Values that *don't* match the predicate are same 'splat'
7144/// value, then replace all values with that splat value.
7145/// Else, if AlternativeReplacement was provided, then replace all values that
7146/// do match predicate with AlternativeReplacement value.
7147static void
7149 std::function<bool(SDValue)> Predicate,
7150 SDValue AlternativeReplacement = SDValue()) {
7151 SDValue Replacement;
7152 // Is there a value for which the Predicate does *NOT* match? What is it?
7153 auto SplatValue = llvm::find_if_not(Values, Predicate);
7154 if (SplatValue != Values.end()) {
7155 // Does Values consist only of SplatValue's and values matching Predicate?
7156 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
7157 return Value == *SplatValue || Predicate(Value);
7158 })) // Then we shall replace values matching predicate with SplatValue.
7159 Replacement = *SplatValue;
7160 }
7161 if (!Replacement) {
7162 // Oops, we did not find the "baseline" splat value.
7163 if (!AlternativeReplacement)
7164 return; // Nothing to do.
7165 // Let's replace with provided value then.
7166 Replacement = AlternativeReplacement;
7167 }
7168 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
7169}
7170
7171/// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
7172/// where the divisor and comparison target are constants,
7173/// return a DAG expression that will generate the same comparison result
7174/// using only multiplications, additions and shifts/rotations.
7175/// Ref: "Hacker's Delight" 10-17.
7176SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
7177 SDValue CompTargetNode,
7179 DAGCombinerInfo &DCI,
7180 const SDLoc &DL) const {
7182 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7183 DCI, DL, Built)) {
7184 for (SDNode *N : Built)
7185 DCI.AddToWorklist(N);
7186 return Folded;
7187 }
7188
7189 return SDValue();
7190}
7191
7192SDValue
7193TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
7194 SDValue CompTargetNode, ISD::CondCode Cond,
7195 DAGCombinerInfo &DCI, const SDLoc &DL,
7196 SmallVectorImpl<SDNode *> &Created) const {
7197 // fold (seteq/ne (urem N, D), C) ->
7198 // (setule/ugt (rotr (mul (sub N, C), P), K), Q)
7199 // - D must be constant, with D = D0 * 2^K where D0 is odd
7200 // - P is the multiplicative inverse of D0 modulo 2^W
7201 // - Q = floor(((2^W) - 1) / D)
7202 // where W is the width of the common type of N and D.
7203 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7204 "Only applicable for (in)equality comparisons.");
7205
7206 SelectionDAG &DAG = DCI.DAG;
7207
7208 EVT VT = REMNode.getValueType();
7209 EVT SVT = VT.getScalarType();
7210 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7211 EVT ShSVT = ShVT.getScalarType();
7212
7213 // If MUL is unavailable, we cannot proceed in any case.
7214 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7215 return SDValue();
7216
7217 bool ComparingWithAllZeros = true;
7218 bool AllComparisonsWithNonZerosAreTautological = true;
7219 bool HadTautologicalLanes = false;
7220 bool AllLanesAreTautological = true;
7221 bool HadEvenDivisor = false;
7222 bool AllDivisorsArePowerOfTwo = true;
7223 bool HadTautologicalInvertedLanes = false;
7224 SmallVector<SDValue, 16> PAmts, KAmts, QAmts;
7225
7226 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
7227 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7228 if (CDiv->isZero())
7229 return false;
7230
7231 const APInt &D = CDiv->getAPIntValue();
7232 const APInt &Cmp = CCmp->getAPIntValue();
7233
7234 ComparingWithAllZeros &= Cmp.isZero();
7235
7236 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7237 // if C2 is not less than C1, the comparison is always false.
7238 // But we will only be able to produce the comparison that will give the
7239 // opposive tautological answer. So this lane would need to be fixed up.
7240 bool TautologicalInvertedLane = D.ule(Cmp);
7241 HadTautologicalInvertedLanes |= TautologicalInvertedLane;
7242
7243 // If all lanes are tautological (either all divisors are ones, or divisor
7244 // is not greater than the constant we are comparing with),
7245 // we will prefer to avoid the fold.
7246 bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
7247 HadTautologicalLanes |= TautologicalLane;
7248 AllLanesAreTautological &= TautologicalLane;
7249
7250 // If we are comparing with non-zero, we need'll need to subtract said
7251 // comparison value from the LHS. But there is no point in doing that if
7252 // every lane where we are comparing with non-zero is tautological..
7253 if (!Cmp.isZero())
7254 AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
7255
7256 // Decompose D into D0 * 2^K
7257 unsigned K = D.countr_zero();
7258 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7259 APInt D0 = D.lshr(K);
7260
7261 // D is even if it has trailing zeros.
7262 HadEvenDivisor |= (K != 0);
7263 // D is a power-of-two if D0 is one.
7264 // If all divisors are power-of-two, we will prefer to avoid the fold.
7265 AllDivisorsArePowerOfTwo &= D0.isOne();
7266
7267 // P = inv(D0, 2^W)
7268 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7269 unsigned W = D.getBitWidth();
7270 APInt P = D0.multiplicativeInverse();
7271 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7272
7273 // Q = floor((2^W - 1) u/ D)
7274 // R = ((2^W - 1) u% D)
7275 APInt Q, R;
7277
7278 // If we are comparing with zero, then that comparison constant is okay,
7279 // else it may need to be one less than that.
7280 if (Cmp.ugt(R))
7281 Q -= 1;
7282
7284 "We are expecting that K is always less than all-ones for ShSVT");
7285
7286 // If the lane is tautological the result can be constant-folded.
7287 if (TautologicalLane) {
7288 // Set P and K amount to a bogus values so we can try to splat them.
7289 P = 0;
7290 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7291 // And ensure that comparison constant is tautological,
7292 // it will always compare true/false.
7293 Q.setAllBits();
7294 } else {
7295 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7296 }
7297
7298 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7299 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7300 return true;
7301 };
7302
7303 SDValue N = REMNode.getOperand(0);
7304 SDValue D = REMNode.getOperand(1);
7305
7306 // Collect the values from each element.
7307 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
7308 return SDValue();
7309
7310 // If all lanes are tautological, the result can be constant-folded.
7311 if (AllLanesAreTautological)
7312 return SDValue();
7313
7314 // If this is a urem by a powers-of-two, avoid the fold since it can be
7315 // best implemented as a bit test.
7316 if (AllDivisorsArePowerOfTwo)
7317 return SDValue();
7318
7319 SDValue PVal, KVal, QVal;
7320 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7321 if (HadTautologicalLanes) {
7322 // Try to turn PAmts into a splat, since we don't care about the values
7323 // that are currently '0'. If we can't, just keep '0'`s.
7325 // Try to turn KAmts into a splat, since we don't care about the values
7326 // that are currently '-1'. If we can't, change them to '0'`s.
7328 DAG.getConstant(0, DL, ShSVT));
7329 }
7330
7331 PVal = DAG.getBuildVector(VT, DL, PAmts);
7332 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7333 QVal = DAG.getBuildVector(VT, DL, QAmts);
7334 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7335 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
7336 "Expected matchBinaryPredicate to return one element for "
7337 "SPLAT_VECTORs");
7338 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7339 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7340 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7341 } else {
7342 PVal = PAmts[0];
7343 KVal = KAmts[0];
7344 QVal = QAmts[0];
7345 }
7346
7347 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
7348 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
7349 return SDValue(); // FIXME: Could/should use `ISD::ADD`?
7350 assert(CompTargetNode.getValueType() == N.getValueType() &&
7351 "Expecting that the types on LHS and RHS of comparisons match.");
7352 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
7353 }
7354
7355 // (mul N, P)
7356 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7357 Created.push_back(Op0.getNode());
7358
7359 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7360 // divisors as a performance improvement, since rotating by 0 is a no-op.
7361 if (HadEvenDivisor) {
7362 // We need ROTR to do this.
7363 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7364 return SDValue();
7365 // UREM: (rotr (mul N, P), K)
7366 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7367 Created.push_back(Op0.getNode());
7368 }
7369
7370 // UREM: (setule/setugt (rotr (mul N, P), K), Q)
7371 SDValue NewCC =
7372 DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7374 if (!HadTautologicalInvertedLanes)
7375 return NewCC;
7376
7377 // If any lanes previously compared always-false, the NewCC will give
7378 // always-true result for them, so we need to fixup those lanes.
7379 // Or the other way around for inequality predicate.
7380 assert(VT.isVector() && "Can/should only get here for vectors.");
7381 Created.push_back(NewCC.getNode());
7382
7383 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7384 // if C2 is not less than C1, the comparison is always false.
7385 // But we have produced the comparison that will give the
7386 // opposive tautological answer. So these lanes would need to be fixed up.
7387 SDValue TautologicalInvertedChannels =
7388 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
7389 Created.push_back(TautologicalInvertedChannels.getNode());
7390
7391 // NOTE: we avoid letting illegal types through even if we're before legalize
7392 // ops – legalization has a hard time producing good code for this.
7393 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
7394 // If we have a vector select, let's replace the comparison results in the
7395 // affected lanes with the correct tautological result.
7396 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
7397 DL, SETCCVT, SETCCVT);
7398 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
7399 Replacement, NewCC);
7400 }
7401
7402 // Else, we can just invert the comparison result in the appropriate lanes.
7403 //
7404 // NOTE: see the note above VSELECT above.
7405 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
7406 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
7407 TautologicalInvertedChannels);
7408
7409 return SDValue(); // Don't know how to lower.
7410}
7411
7412/// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
7413/// where the divisor is constant and the comparison target is zero,
7414/// return a DAG expression that will generate the same comparison result
7415/// using only multiplications, additions and shifts/rotations.
7416/// Ref: "Hacker's Delight" 10-17.
7417SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
7418 SDValue CompTargetNode,
7420 DAGCombinerInfo &DCI,
7421 const SDLoc &DL) const {
7423 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7424 DCI, DL, Built)) {
7425 assert(Built.size() <= 7 && "Max size prediction failed.");
7426 for (SDNode *N : Built)
7427 DCI.AddToWorklist(N);
7428 return Folded;
7429 }
7430
7431 return SDValue();
7432}
7433
7434SDValue
7435TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
7436 SDValue CompTargetNode, ISD::CondCode Cond,
7437 DAGCombinerInfo &DCI, const SDLoc &DL,
7438 SmallVectorImpl<SDNode *> &Created) const {
7439 // Derived from Hacker's Delight, 2nd Edition, by Hank Warren. Section 10-17.
7440 // Fold:
7441 // (seteq/ne (srem N, D), 0)
7442 // To:
7443 // (setule/ugt (rotr (add (mul N, P), A), K), Q)
7444 //
7445 // - D must be constant, with D = D0 * 2^K where D0 is odd
7446 // - P is the multiplicative inverse of D0 modulo 2^W
7447 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
7448 // - Q = floor((2 * A) / (2^K))
7449 // where W is the width of the common type of N and D.
7450 //
7451 // When D is a power of two (and thus D0 is 1), the normal
7452 // formula for A and Q don't apply, because the derivation
7453 // depends on D not dividing 2^(W-1), and thus theorem ZRS
7454 // does not apply. This specifically fails when N = INT_MIN.
7455 //
7456 // Instead, for power-of-two D, we use:
7457 // - A = 0
7458 // | -> No offset needed. We're effectively treating it the same as urem.
7459 // - Q = 2^(W-K) - 1
7460 // |-> Test that the top K bits are zero after rotation
7461 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7462 "Only applicable for (in)equality comparisons.");
7463
7464 SelectionDAG &DAG = DCI.DAG;
7465
7466 EVT VT = REMNode.getValueType();
7467 EVT SVT = VT.getScalarType();
7468 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7469 EVT ShSVT = ShVT.getScalarType();
7470
7471 // If we are after ops legalization, and MUL is unavailable, we can not
7472 // proceed.
7473 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7474 return SDValue();
7475
7476 // TODO: Could support comparing with non-zero too.
7477 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
7478 if (!CompTarget || !CompTarget->isZero())
7479 return SDValue();
7480
7481 bool HadOneDivisor = false;
7482 bool AllDivisorsAreOnes = true;
7483 bool HadEvenDivisor = false;
7484 bool AllDivisorsArePowerOfTwo = true;
7485 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
7486
7487 auto BuildSREMPattern = [&](ConstantSDNode *C) {
7488 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7489 if (C->isZero())
7490 return false;
7491
7492 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
7493
7494 // WARNING: this fold is only valid for positive divisors!
7495 // `rem %X, -C` is equivalent to `rem %X, C`
7496 APInt D = C->getAPIntValue().abs();
7497
7498 // If all divisors are ones, we will prefer to avoid the fold.
7499 HadOneDivisor |= D.isOne();
7500 AllDivisorsAreOnes &= D.isOne();
7501
7502 // Decompose D into D0 * 2^K
7503 unsigned K = D.countr_zero();
7504 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7505 APInt D0 = D.lshr(K);
7506
7507 // D is even if it has trailing zeros.
7508 HadEvenDivisor |= (K != 0);
7509
7510 // D is a power-of-two if D0 is one. This includes INT_MIN.
7511 // If all divisors are power-of-two, we will prefer to avoid the fold.
7512 AllDivisorsArePowerOfTwo &= D0.isOne();
7513
7514 // P = inv(D0, 2^W)
7515 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7516 unsigned W = D.getBitWidth();
7517 APInt P = D0.multiplicativeInverse();
7518 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7519
7520 // A = floor((2^(W - 1) - 1) / D0) & -2^K
7521 APInt A = APInt::getSignedMaxValue(W).udiv(D0);
7522 A.clearLowBits(K);
7523
7524 // Q = floor((2 * A) / (2^K))
7525 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
7526
7528 "We are expecting that A is always less than all-ones for SVT");
7530 "We are expecting that K is always less than all-ones for ShSVT");
7531
7532 // If D was a power of two, apply the alternate constant derivation.
7533 if (D0.isOne()) {
7534 // A = 0
7535 A = APInt(W, 0);
7536 // - Q = 2^(W-K) - 1
7537 Q = APInt::getLowBitsSet(W, W - K);
7538 }
7539
7540 // If the divisor is 1 the result can be constant-folded.
7541 if (D.isOne()) {
7542 // Set P, A and K to a bogus values so we can try to splat them.
7543 P = 0;
7544 A.setAllBits();
7545 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7546
7547 // x ?% 1 == 0 <--> true <--> x u<= -1
7548 Q.setAllBits();
7549 } else {
7550 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7551 }
7552
7553 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7554 AAmts.push_back(DAG.getConstant(A, DL, SVT));
7555 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7556 return true;
7557 };
7558
7559 SDValue N = REMNode.getOperand(0);
7560 SDValue D = REMNode.getOperand(1);
7561
7562 // Collect the values from each element.
7563 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
7564 return SDValue();
7565
7566 // If this is a srem by a one, avoid the fold since it can be constant-folded.
7567 if (AllDivisorsAreOnes)
7568 return SDValue();
7569
7570 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
7571 // since it can be best implemented as a bit test.
7572 if (AllDivisorsArePowerOfTwo)
7573 return SDValue();
7574
7575 SDValue PVal, AVal, KVal, QVal;
7576 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7577 if (HadOneDivisor) {
7578 // Try to turn PAmts into a splat, since we don't care about the values
7579 // that are currently '0'. If we can't, just keep '0'`s.
7581 // Try to turn AAmts into a splat, since we don't care about the
7582 // values that are currently '-1'. If we can't, change them to '0'`s.
7584 DAG.getConstant(0, DL, SVT));
7585 // Try to turn KAmts into a splat, since we don't care about the values
7586 // that are currently '-1'. If we can't, change them to '0'`s.
7588 DAG.getConstant(0, DL, ShSVT));
7589 }
7590
7591 PVal = DAG.getBuildVector(VT, DL, PAmts);
7592 AVal = DAG.getBuildVector(VT, DL, AAmts);
7593 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7594 QVal = DAG.getBuildVector(VT, DL, QAmts);
7595 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7596 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
7597 QAmts.size() == 1 &&
7598 "Expected matchUnaryPredicate to return one element for scalable "
7599 "vectors");
7600 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7601 AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
7602 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7603 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7604 } else {
7605 assert(isa<ConstantSDNode>(D) && "Expected a constant");
7606 PVal = PAmts[0];
7607 AVal = AAmts[0];
7608 KVal = KAmts[0];
7609 QVal = QAmts[0];
7610 }
7611
7612 // (mul N, P)
7613 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7614 Created.push_back(Op0.getNode());
7615
7616 // We need ADD to do this.
7617 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
7618 return SDValue();
7619
7620 // (add (mul N, P), A)
7621 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
7622 Created.push_back(Op0.getNode());
7623
7624 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7625 // divisors as a performance improvement, since rotating by 0 is a no-op.
7626 if (HadEvenDivisor) {
7627 // We need ROTR to do this.
7628 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7629 return SDValue();
7630 // SREM: (rotr (add (mul N, P), A), K)
7631 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7632 Created.push_back(Op0.getNode());
7633 }
7634
7635 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
7636 return DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7638}
7639
7641 const DenormalMode &Mode,
7642 SDNodeFlags Flags) const {
7643 SDLoc DL(Op);
7644 EVT VT = Op.getValueType();
7645 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7646 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
7647
7648 // This is specifically a check for the handling of denormal inputs, not the
7649 // result.
7650 if (Mode.Input == DenormalMode::PreserveSign ||
7651 Mode.Input == DenormalMode::PositiveZero) {
7652 // Test = X == 0.0
7653 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ, /*Chain=*/{},
7654 /*Signaling=*/false, Flags);
7655 }
7656
7657 // Testing it with denormal inputs to avoid wrong estimate.
7658 //
7659 // Test = fabs(X) < SmallestNormal
7660 const fltSemantics &FltSem = VT.getFltSemantics();
7661 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
7662 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
7663 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op, Flags);
7664 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT, /*Chain=*/{},
7665 /*Signaling=*/false, Flags);
7666}
7667
7669 bool LegalOps, bool OptForSize,
7671 unsigned Depth) const {
7672 // fneg is removable even if it has multiple uses.
7673 if (Op.getOpcode() == ISD::FNEG) {
7675 return Op.getOperand(0);
7676 }
7677
7678 // Don't recurse exponentially.
7680 return SDValue();
7681
7682 // Pre-increment recursion depth for use in recursive calls.
7683 ++Depth;
7684 const SDNodeFlags Flags = Op->getFlags();
7685 EVT VT = Op.getValueType();
7686 unsigned Opcode = Op.getOpcode();
7687
7688 // Don't allow anything with multiple uses unless we know it is free.
7689 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
7690 bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
7691 isFPExtFree(VT, Op.getOperand(0).getValueType());
7692 if (!IsFreeExtend)
7693 return SDValue();
7694 }
7695
7696 auto RemoveDeadNode = [&](SDValue N) {
7697 if (N && N.getNode()->use_empty())
7698 DAG.RemoveDeadNode(N.getNode());
7699 };
7700
7701 SDLoc DL(Op);
7702
7703 // Because getNegatedExpression can delete nodes we need a handle to keep
7704 // temporary nodes alive in case the recursion manages to create an identical
7705 // node.
7706 std::list<HandleSDNode> Handles;
7707
7708 switch (Opcode) {
7709 case ISD::ConstantFP: {
7710 // Don't invert constant FP values after legalization unless the target says
7711 // the negated constant is legal.
7712 bool IsOpLegal =
7714 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
7715 OptForSize);
7716
7717 if (LegalOps && !IsOpLegal)
7718 break;
7719
7720 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
7721 V.changeSign();
7722 SDValue CFP = DAG.getConstantFP(V, DL, VT);
7723
7724 // If we already have the use of the negated floating constant, it is free
7725 // to negate it even it has multiple uses.
7726 if (!Op.hasOneUse() && CFP.use_empty())
7727 break;
7729 return CFP;
7730 }
7731 case ISD::SPLAT_VECTOR: {
7732 // fold splat_vector(fneg(X)) -> splat_vector(-X)
7733 SDValue X = Op.getOperand(0);
7735 break;
7736
7737 SDValue NegX = getCheaperNegatedExpression(X, DAG, LegalOps, OptForSize);
7738 if (!NegX)
7739 break;
7741 return DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, NegX);
7742 }
7743 case ISD::BUILD_VECTOR: {
7744 // Only permit BUILD_VECTOR of constants.
7745 if (llvm::any_of(Op->op_values(), [&](SDValue N) {
7746 return !N.isUndef() && !isa<ConstantFPSDNode>(N);
7747 }))
7748 break;
7749
7750 bool IsOpLegal =
7753 llvm::all_of(Op->op_values(), [&](SDValue N) {
7754 return N.isUndef() ||
7755 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
7756 OptForSize);
7757 });
7758
7759 if (LegalOps && !IsOpLegal)
7760 break;
7761
7763 for (SDValue C : Op->op_values()) {
7764 if (C.isUndef()) {
7765 Ops.push_back(C);
7766 continue;
7767 }
7768 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
7769 V.changeSign();
7770 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
7771 }
7773 return DAG.getBuildVector(VT, DL, Ops);
7774 }
7775 case ISD::FADD: {
7776 if (!Flags.hasNoSignedZeros())
7777 break;
7778
7779 // After operation legalization, it might not be legal to create new FSUBs.
7780 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
7781 break;
7782 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7783
7784 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
7786 SDValue NegX =
7787 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7788 // Prevent this node from being deleted by the next call.
7789 if (NegX)
7790 Handles.emplace_back(NegX);
7791
7792 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
7794 SDValue NegY =
7795 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7796
7797 // We're done with the handles.
7798 Handles.clear();
7799
7800 // Negate the X if its cost is less or equal than Y.
7801 if (NegX && (CostX <= CostY)) {
7802 Cost = CostX;
7803 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
7804 if (NegY != N)
7805 RemoveDeadNode(NegY);
7806 return N;
7807 }
7808
7809 // Negate the Y if it is not expensive.
7810 if (NegY) {
7811 Cost = CostY;
7812 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
7813 if (NegX != N)
7814 RemoveDeadNode(NegX);
7815 return N;
7816 }
7817 break;
7818 }
7819 case ISD::FSUB: {
7820 // We can't turn -(A-B) into B-A when we honor signed zeros.
7821 if (!Flags.hasNoSignedZeros())
7822 break;
7823
7824 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7825 // fold (fneg (fsub 0, Y)) -> Y
7826 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
7827 if (C->isZero()) {
7829 return Y;
7830 }
7831
7832 // fold (fneg (fsub X, Y)) -> (fsub Y, X)
7834 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
7835 }
7836 case ISD::FMUL:
7837 case ISD::FDIV: {
7838 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7839
7840 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
7842 SDValue NegX =
7843 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7844 // Prevent this node from being deleted by the next call.
7845 if (NegX)
7846 Handles.emplace_back(NegX);
7847
7848 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
7850 SDValue NegY =
7851 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7852
7853 // We're done with the handles.
7854 Handles.clear();
7855
7856 // Negate the X if its cost is less or equal than Y.
7857 if (NegX && (CostX <= CostY)) {
7858 Cost = CostX;
7859 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
7860 if (NegY != N)
7861 RemoveDeadNode(NegY);
7862 return N;
7863 }
7864
7865 // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
7866 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
7867 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
7868 break;
7869
7870 // Negate the Y if it is not expensive.
7871 if (NegY) {
7872 Cost = CostY;
7873 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
7874 if (NegX != N)
7875 RemoveDeadNode(NegX);
7876 return N;
7877 }
7878 break;
7879 }
7880 case ISD::FMA:
7881 case ISD::FMULADD:
7882 case ISD::FMAD: {
7883 if (!Flags.hasNoSignedZeros())
7884 break;
7885
7886 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
7888 SDValue NegZ =
7889 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
7890 // Give up if fail to negate the Z.
7891 if (!NegZ)
7892 break;
7893
7894 // Prevent this node from being deleted by the next two calls.
7895 Handles.emplace_back(NegZ);
7896
7897 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
7899 SDValue NegX =
7900 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7901 // Prevent this node from being deleted by the next call.
7902 if (NegX)
7903 Handles.emplace_back(NegX);
7904
7905 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
7907 SDValue NegY =
7908 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7909
7910 // We're done with the handles.
7911 Handles.clear();
7912
7913 // Negate the X if its cost is less or equal than Y.
7914 if (NegX && (CostX <= CostY)) {
7915 Cost = std::min(CostX, CostZ);
7916 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
7917 if (NegY != N)
7918 RemoveDeadNode(NegY);
7919 return N;
7920 }
7921
7922 // Negate the Y if it is not expensive.
7923 if (NegY) {
7924 Cost = std::min(CostY, CostZ);
7925 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
7926 if (NegX != N)
7927 RemoveDeadNode(NegX);
7928 return N;
7929 }
7930 break;
7931 }
7932
7933 case ISD::FP_EXTEND:
7934 case ISD::FSIN:
7935 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
7936 OptForSize, Cost, Depth))
7937 return DAG.getNode(Opcode, DL, VT, NegV);
7938 break;
7939 case ISD::FP_ROUND:
7940 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
7941 OptForSize, Cost, Depth))
7942 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
7943 break;
7944 case ISD::SELECT:
7945 case ISD::VSELECT: {
7946 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS))
7947 // iff at least one cost is cheaper and the other is neutral/cheaper
7948 SDValue LHS = Op.getOperand(1);
7950 SDValue NegLHS =
7951 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth);
7952 if (!NegLHS || CostLHS > NegatibleCost::Neutral) {
7953 RemoveDeadNode(NegLHS);
7954 break;
7955 }
7956
7957 // Prevent this node from being deleted by the next call.
7958 Handles.emplace_back(NegLHS);
7959
7960 SDValue RHS = Op.getOperand(2);
7962 SDValue NegRHS =
7963 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth);
7964
7965 // We're done with the handles.
7966 Handles.clear();
7967
7968 if (!NegRHS || CostRHS > NegatibleCost::Neutral ||
7969 (CostLHS != NegatibleCost::Cheaper &&
7970 CostRHS != NegatibleCost::Cheaper)) {
7971 RemoveDeadNode(NegLHS);
7972 RemoveDeadNode(NegRHS);
7973 break;
7974 }
7975
7976 Cost = std::min(CostLHS, CostRHS);
7977 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS);
7978 }
7979 }
7980
7981 return SDValue();
7982}
7983
7984//===----------------------------------------------------------------------===//
7985// Legalization Utilities
7986//===----------------------------------------------------------------------===//
7987
7988bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
7989 SDValue LHS, SDValue RHS,
7991 EVT HiLoVT, SelectionDAG &DAG,
7992 MulExpansionKind Kind, SDValue LL,
7993 SDValue LH, SDValue RL, SDValue RH) const {
7994 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
7995 Opcode == ISD::SMUL_LOHI);
7996
7997 bool HasMULHS = (Kind == MulExpansionKind::Always) ||
7999 bool HasMULHU = (Kind == MulExpansionKind::Always) ||
8001 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8003 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8005
8006 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
8007 return false;
8008
8009 unsigned OuterBitSize = VT.getScalarSizeInBits();
8010 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
8011
8012 // LL, LH, RL, and RH must be either all NULL or all set to a value.
8013 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
8014 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
8015
8016 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
8017 bool Signed) -> bool {
8018 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
8019 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
8020 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
8021 Hi = Lo.getValue(1);
8022 return true;
8023 }
8024 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
8025 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
8026 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
8027 return true;
8028 }
8029 return false;
8030 };
8031
8032 SDValue Lo, Hi;
8033
8034 if (!LL.getNode() && !RL.getNode() &&
8036 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
8037 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
8038 }
8039
8040 if (!LL.getNode())
8041 return false;
8042
8043 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
8044 if (DAG.MaskedValueIsZero(LHS, HighMask) &&
8045 DAG.MaskedValueIsZero(RHS, HighMask)) {
8046 // The inputs are both zero-extended.
8047 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
8048 Result.push_back(Lo);
8049 Result.push_back(Hi);
8050 if (Opcode != ISD::MUL) {
8051 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8052 Result.push_back(Zero);
8053 Result.push_back(Zero);
8054 }
8055 return true;
8056 }
8057 }
8058
8059 if (!VT.isVector() && Opcode == ISD::MUL &&
8060 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize &&
8061 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) {
8062 // The input values are both sign-extended.
8063 // TODO non-MUL case?
8064 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
8065 Result.push_back(Lo);
8066 Result.push_back(Hi);
8067 return true;
8068 }
8069 }
8070
8071 unsigned ShiftAmount = OuterBitSize - InnerBitSize;
8072 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
8073
8074 if (!LH.getNode() && !RH.getNode() &&
8077 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
8078 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
8079 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
8080 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
8081 }
8082
8083 if (!LH.getNode())
8084 return false;
8085
8086 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
8087 return false;
8088
8089 Result.push_back(Lo);
8090
8091 if (Opcode == ISD::MUL) {
8092 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
8093 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
8094 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
8095 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
8096 Result.push_back(Hi);
8097 return true;
8098 }
8099
8100 // Compute the full width result.
8101 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
8102 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
8103 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8104 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
8105 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
8106 };
8107
8108 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8109 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
8110 return false;
8111
8112 // This is effectively the add part of a multiply-add of half-sized operands,
8113 // so it cannot overflow.
8114 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8115
8116 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
8117 return false;
8118
8119 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8120 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8121
8122 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
8124 if (UseGlue)
8125 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
8126 Merge(Lo, Hi));
8127 else
8128 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next,
8129 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
8130
8131 SDValue Carry = Next.getValue(1);
8132 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8133 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8134
8135 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
8136 return false;
8137
8138 if (UseGlue)
8139 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
8140 Carry);
8141 else
8142 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
8143 Zero, Carry);
8144
8145 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8146
8147 if (Opcode == ISD::SMUL_LOHI) {
8148 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8149 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
8150 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
8151
8152 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8153 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
8154 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
8155 }
8156
8157 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8158 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8159 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8160 return true;
8161}
8162
8164 SelectionDAG &DAG, MulExpansionKind Kind,
8165 SDValue LL, SDValue LH, SDValue RL,
8166 SDValue RH) const {
8168 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
8169 N->getOperand(0), N->getOperand(1), Result, HiLoVT,
8170 DAG, Kind, LL, LH, RL, RH);
8171 if (Ok) {
8172 assert(Result.size() == 2);
8173 Lo = Result[0];
8174 Hi = Result[1];
8175 }
8176 return Ok;
8177}
8178
8179// Optimize unsigned division or remainder by constants for types twice as large
8180// as a legal VT.
8181//
8182// If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
8183// can be computed
8184// as:
8185// Sum = __builtin_uadd_overflow(Lo, High, &Sum);
8186// Remainder = Sum % Constant;
8187//
8188// If (1 << (BitWidth / 2)) % Constant != 1, we can search for a smaller value
8189// W such that W != (BitWidth / 2) and (1 << W) % Constant == 1. We can break
8190// High:Low into 3 chunks of W bits and compute remainder as
8191// Sum = Chunk0 + Chunk1 + Chunk2;
8192// Remainder = Sum % Constant;
8193//
8194// This is based on "Remainder by Summing Digits" from Hacker's Delight.
8195//
8196// For division, we can compute the remainder using the algorithm described
8197// above, subtract it from the dividend to get an exact multiple of Constant.
8198// Then multiply that exact multiply by the multiplicative inverse modulo
8199// (1 << (BitWidth / 2)) to get the quotient.
8200
8201// If Constant is even, we can shift right the dividend and the divisor by the
8202// number of trailing zeros in Constant before applying the remainder algorithm.
8203// If we're after the quotient, we can subtract this value from the shifted
8204// dividend and multiply by the multiplicative inverse of the shifted divisor.
8205// If we want the remainder, we shift the value left by the number of trailing
8206// zeros and add the bits that were shifted out of the dividend.
8207bool TargetLowering::expandUDIVREMByConstantViaUREMDecomposition(
8208 SDNode *N, APInt Divisor, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
8209 SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8210 unsigned Opcode = N->getOpcode();
8211 EVT VT = N->getValueType(0);
8212
8213 unsigned BitWidth = Divisor.getBitWidth();
8214 unsigned HBitWidth = BitWidth / 2;
8216 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs");
8217
8218 // If the divisor is even, shift it until it becomes odd.
8219 unsigned TrailingZeros = 0;
8220 if (!Divisor[0]) {
8221 TrailingZeros = Divisor.countr_zero();
8222 Divisor.lshrInPlace(TrailingZeros);
8223 }
8224
8225 // After removing trailing zeros, the divisor needs to be less than
8226 // (1 << HBitWidth).
8227 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth);
8228 if (Divisor.uge(HalfMaxPlus1))
8229 return false;
8230
8231 // Look for the largest chunk width W such that (1 << W) % Divisor == 1 or
8232 // (1 << W) % Divisor == -1.
8233 unsigned BestChunkWidth = 0, AltChunkWidth = 0;
8234 for (unsigned I = HBitWidth, E = HBitWidth / 2; I > E; --I) {
8235 // Skip HBitWidth-1, it doesn't have enough bits for carries.
8236 if (I == HBitWidth - 1)
8237 continue;
8238
8239 APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
8240
8241 if (Mod.isOne()) {
8242 BestChunkWidth = I;
8243 break;
8244 }
8245
8246 // We have an alternate strategy for Remainder == Divisor - 1.
8247 // FIXME: Support HBitWidth.
8248 if (I != HBitWidth && Mod == Divisor - 1)
8249 AltChunkWidth = I;
8250 }
8251
8252 bool Alternate = false;
8253 if (!BestChunkWidth) {
8254 if (!AltChunkWidth)
8255 return false;
8256 Alternate = true;
8257 BestChunkWidth = AltChunkWidth;
8258 }
8259
8260 SDLoc dl(N);
8261
8262 assert(!LL == !LH && "Expected both input halves or no input halves!");
8263 if (!LL)
8264 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
8265
8266 bool HasFSHR = isOperationLegal(ISD::FSHR, HiLoVT);
8267
8268 auto GetFSHR = [&](SDValue Lo, SDValue Hi, unsigned ShiftAmt) {
8269 assert(ShiftAmt > 0 && ShiftAmt < HBitWidth);
8270 if (HasFSHR)
8271 return DAG.getNode(ISD::FSHR, dl, HiLoVT, Hi, Lo,
8272 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8273 return DAG.getNode(
8274 ISD::OR, dl, HiLoVT,
8275 DAG.getNode(ISD::SRL, dl, HiLoVT, Lo,
8276 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl)),
8277 DAG.getNode(
8278 ISD::SHL, dl, HiLoVT, Hi,
8279 DAG.getShiftAmountConstant(HBitWidth - ShiftAmt, HiLoVT, dl)));
8280 };
8281
8282 // Helper to perform a right shift on a 128-bit value split into two halves.
8283 // Handles shifts >= HBitWidth by moving Hi to Lo and shifting Hi.
8284 auto ShiftRight = [&](SDValue &Lo, SDValue &Hi, unsigned ShiftAmt) {
8285 if (ShiftAmt == 0)
8286 return;
8287 if (ShiftAmt < HBitWidth) {
8288 Lo = GetFSHR(Lo, Hi, ShiftAmt);
8289 Hi = DAG.getNode(ISD::SRL, dl, HiLoVT, Hi,
8290 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8291 } else if (ShiftAmt == HBitWidth) {
8292 Lo = Hi;
8293 Hi = DAG.getConstant(0, dl, HiLoVT);
8294 } else {
8295 Lo = DAG.getNode(
8296 ISD::SRL, dl, HiLoVT, Hi,
8297 DAG.getShiftAmountConstant(ShiftAmt - HBitWidth, HiLoVT, dl));
8298 Hi = DAG.getConstant(0, dl, HiLoVT);
8299 }
8300 };
8301
8302 // Shift the input by the number of TrailingZeros in the divisor. The
8303 // shifted out bits will be added to the remainder later.
8304 SDValue PartialRemL, PartialRemH;
8305 if (TrailingZeros && Opcode != ISD::UDIV) {
8306 // Save the shifted off bits if we need the remainder.
8307 if (TrailingZeros < HBitWidth) {
8308 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
8309 PartialRemL = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
8310 DAG.getConstant(Mask, dl, HiLoVT));
8311 } else if (TrailingZeros == HBitWidth) {
8312 // All of LL is part of the remainder.
8313 PartialRemL = LL;
8314 } else {
8315 // TrailingZeros > HBitWidth: LL and part of LH are the remainder.
8316 PartialRemL = LL;
8317 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros - HBitWidth);
8318 PartialRemH = DAG.getNode(ISD::AND, dl, HiLoVT, LH,
8319 DAG.getConstant(Mask, dl, HiLoVT));
8320 }
8321 }
8322
8323 SDValue Sum;
8324 // If BestChunkWidth is HBitWidth add low and high half. If there is a carry
8325 // out, add that to the final sum.
8326 if (BestChunkWidth == HBitWidth) {
8327 assert(!Alternate);
8328 // Shift LH:LL right if there were trailing zeros in the divisor.
8329 ShiftRight(LL, LH, TrailingZeros);
8330
8331 // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
8332 EVT SetCCType =
8333 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
8335 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType);
8336 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH);
8337 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum,
8338 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1));
8339 } else {
8340 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH);
8341 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT);
8342 // If the boolean for the target is 0 or 1, we can add the setcc result
8343 // directly.
8344 if (getBooleanContents(HiLoVT) ==
8346 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT);
8347 else
8348 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT),
8349 DAG.getConstant(0, dl, HiLoVT));
8350 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
8351 }
8352 } else {
8353 // Otherwise split into multple chunks and add them together. We chose
8354 // BestChunkWidth so that the sum will not overflow.
8355 SDValue Mask = DAG.getConstant(
8356 APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
8357
8358 for (unsigned I = 0; I < BitWidth - TrailingZeros; I += BestChunkWidth) {
8359 // If there were trailing zeros in the divisor, increase the shift amount.
8360 unsigned Shift = I + TrailingZeros;
8361 SDValue Chunk;
8362 if (Shift == 0)
8363 Chunk = LL;
8364 else if (Shift >= HBitWidth)
8365 Chunk = DAG.getNode(
8366 ISD::SRL, dl, HiLoVT, LH,
8367 DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, dl));
8368 else
8369 Chunk = GetFSHR(LL, LH, Shift);
8370 // If we're on the last chunk, we don't need an AND.
8371 if (I + BestChunkWidth < BitWidth - TrailingZeros)
8372 Chunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
8373 if (!Sum) {
8374 Sum = Chunk;
8375 } else {
8376 // For Alternate, we need to subtract odd chunks.
8377 unsigned ChunkNum = I / BestChunkWidth;
8378 unsigned Opc = (Alternate && (ChunkNum % 2) != 0) ? ISD::SUB : ISD::ADD;
8379 Sum = DAG.getNode(Opc, dl, HiLoVT, Sum, Chunk);
8380 }
8381 }
8382
8383 // For Alternate, the sum may be negative, but we need a positive sum. We
8384 // can increase it by a multiple of the divisor to make it positive. For 3
8385 // chunks the largest negative value is -(2^BestChunkWidth - 1). For 4
8386 // chunks, it's 2*-(2^BestChunkWidth - 1). We know that 2^BestChunkWidth + 1
8387 // is a multiple of the divisor. Add that 1 or 2 times to make the sum
8388 // positive.
8389 if (Alternate) {
8390 unsigned NumChunks = divideCeil(BitWidth - TrailingZeros, BestChunkWidth);
8391 assert(NumChunks <= 4);
8392
8393 APInt Adjust = APInt::getOneBitSet(HBitWidth, BestChunkWidth);
8394 Adjust.setBit(0);
8395 // If there are 4 chunks, we need to adjust twice.
8396 if (NumChunks == 4)
8397 Adjust <<= 1;
8398 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum,
8399 DAG.getConstant(Adjust, dl, HiLoVT));
8400 }
8401 }
8402
8403 // Perform a HiLoVT urem on the Sum using truncated divisor.
8404 SDValue RemL =
8405 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
8406 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT));
8407 SDValue RemH = DAG.getConstant(0, dl, HiLoVT);
8408
8409 if (Opcode != ISD::UREM) {
8410 // If we didn't shift LH/LR earlier, do it now.
8411 if (BestChunkWidth != HBitWidth)
8412 ShiftRight(LL, LH, TrailingZeros);
8413
8414 // Subtract the remainder from the shifted dividend.
8415 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH);
8416 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH);
8417
8418 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem);
8419
8420 // Multiply by the multiplicative inverse of the divisor modulo
8421 // (1 << BitWidth).
8422 APInt MulFactor = Divisor.multiplicativeInverse();
8423
8424 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend,
8425 DAG.getConstant(MulFactor, dl, VT));
8426
8427 // Split the quotient into low and high parts.
8428 SDValue QuotL, QuotH;
8429 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT);
8430 Result.push_back(QuotL);
8431 Result.push_back(QuotH);
8432 }
8433
8434 if (Opcode != ISD::UDIV) {
8435 // If we shifted the input, shift the remainder left and add the bits we
8436 // shifted off the input.
8437 if (TrailingZeros) {
8438 if (TrailingZeros < HBitWidth) {
8439 // Shift RemH:RemL left by TrailingZeros.
8440 // RemH gets the high bits shifted out of RemL.
8441 RemH = DAG.getNode(
8442 ISD::SRL, dl, HiLoVT, RemL,
8443 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, HiLoVT, dl));
8444 RemL =
8445 DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
8446 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
8447 // OR in the partial remainder.
8448 RemL = DAG.getNode(ISD::OR, dl, HiLoVT, RemL, PartialRemL,
8450 } else if (TrailingZeros == HBitWidth) {
8451 // Shift left by exactly HBitWidth: RemH becomes RemL, RemL becomes
8452 // PartialRemL.
8453 RemH = RemL;
8454 RemL = PartialRemL;
8455 } else {
8456 // Shift left by more than HBitWidth.
8457 RemH = DAG.getNode(
8458 ISD::SHL, dl, HiLoVT, RemL,
8459 DAG.getShiftAmountConstant(TrailingZeros - HBitWidth, HiLoVT, dl));
8460 RemH = DAG.getNode(ISD::OR, dl, HiLoVT, RemH, PartialRemH,
8462 RemL = PartialRemL;
8463 }
8464 }
8465 Result.push_back(RemL);
8466 Result.push_back(RemH);
8467 }
8468
8469 return true;
8470}
8471
8472bool TargetLowering::expandUDIVREMByConstantViaUMulHiMagic(
8473 SDNode *N, const APInt &Divisor, SmallVectorImpl<SDValue> &Result,
8474 EVT HiLoVT, SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8475
8476 SDValue N0 = N->getOperand(0);
8477 EVT VT = N0->getValueType(0);
8478 SDLoc DL{N};
8479
8480 assert(!Divisor.isOne() && "Magic algorithm does not work for division by 1");
8481
8482 // This helper creates a MUL_LOHI of the pair (LL, LH) by a constant.
8483 auto MakeMUL_LOHIByConst = [&](unsigned Opc, SDValue LL, SDValue LH,
8484 const APInt &Const,
8485 SmallVectorImpl<SDValue> &Result) {
8486 SDValue LHS = DAG.getNode(ISD::BUILD_PAIR, DL, VT, LL, LH);
8487 SDValue RHS = DAG.getConstant(Const, DL, VT);
8488 auto [RL, RH] = DAG.SplitScalar(RHS, DL, HiLoVT, HiLoVT);
8489 return expandMUL_LOHI(Opc, VT, DL, LHS, RHS, Result, HiLoVT, DAG,
8491 LL, LH, RL, RH);
8492 };
8493
8494 // This helper creates an ADD/SUB of the pairs (LL, LH) and (RL, RH).
8495 auto MakeAddSubLong = [&](unsigned Opc, SDValue LL, SDValue LH, SDValue RL,
8496 SDValue RH) {
8497 SDValue AddSubNode =
8499 DAG.getVTList(HiLoVT, MVT::i1), LL, RL);
8500 SDValue OutL = AddSubNode.getValue(0);
8501 SDValue Overflow = AddSubNode.getValue(1);
8502 SDValue AddSubWithOverflow =
8504 DAG.getVTList(HiLoVT, MVT::i1), LH, RH, Overflow);
8505 SDValue OutH = AddSubWithOverflow.getValue(0);
8506 return std::make_pair(OutL, OutH);
8507 };
8508
8509 // This helper creates a SRL of the pair (LL, LH) by Shift.
8510 auto MakeSRLLong = [&](SDValue LL, SDValue LH, unsigned Shift) {
8511 unsigned HBitWidth = HiLoVT.getScalarSizeInBits();
8512 if (Shift < HBitWidth) {
8513 SDValue ShAmt = DAG.getShiftAmountConstant(Shift, HiLoVT, DL);
8514 SDValue ResL = DAG.getNode(ISD::FSHR, DL, HiLoVT, LH, LL, ShAmt);
8515 SDValue ResH = DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt);
8516 return std::make_pair(ResL, ResH);
8517 }
8518 SDValue Zero = DAG.getConstant(0, DL, HiLoVT);
8519 if (Shift == HBitWidth)
8520 return std::make_pair(LH, Zero);
8521 assert(Shift - HBitWidth < HBitWidth &&
8522 "We shouldn't generate an undefined shift");
8523 SDValue ShAmt = DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, DL);
8524 return std::make_pair(DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt), Zero);
8525 };
8526
8527 // Knowledge of leading zeros may help to reduce the multiplier.
8528 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
8529
8530 UnsignedDivisionByConstantInfo Magics = UnsignedDivisionByConstantInfo::get(
8531 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()));
8532
8533 assert(!LL == !LH && "Expected both input halves or no input halves!");
8534 if (!LL)
8535 std::tie(LL, LH) = DAG.SplitScalar(N0, DL, HiLoVT, HiLoVT);
8536 SDValue QL = LL;
8537 SDValue QH = LH;
8538 if (Magics.PreShift != 0)
8539 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PreShift);
8540
8541 SmallVector<SDValue, 4> UMulResult;
8542 if (!MakeMUL_LOHIByConst(ISD::UMUL_LOHI, QL, QH, Magics.Magic, UMulResult))
8543 return false;
8544
8545 QL = UMulResult[2];
8546 QH = UMulResult[3];
8547
8548 if (Magics.IsAdd) {
8549 auto [NPQL, NPQH] = MakeAddSubLong(ISD::SUB, LL, LH, QL, QH);
8550 std::tie(NPQL, NPQH) = MakeSRLLong(NPQL, NPQH, 1);
8551 std::tie(QL, QH) = MakeAddSubLong(ISD::ADD, NPQL, NPQH, QL, QH);
8552 }
8553
8554 if (Magics.PostShift != 0)
8555 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PostShift);
8556
8557 unsigned Opcode = N->getOpcode();
8558 if (Opcode != ISD::UREM) {
8559 Result.push_back(QL);
8560 Result.push_back(QH);
8561 }
8562
8563 if (Opcode != ISD::UDIV) {
8564 SmallVector<SDValue, 2> MulResult;
8565 if (!MakeMUL_LOHIByConst(ISD::MUL, QL, QH, Divisor, MulResult))
8566 return false;
8567
8568 assert(MulResult.size() == 2);
8569
8570 auto [RemL, RemH] =
8571 MakeAddSubLong(ISD::SUB, LL, LH, MulResult[0], MulResult[1]);
8572
8573 Result.push_back(RemL);
8574 Result.push_back(RemH);
8575 }
8576
8577 return true;
8578}
8579
8582 EVT HiLoVT, SelectionDAG &DAG,
8583 SDValue LL, SDValue LH) const {
8584 unsigned Opcode = N->getOpcode();
8585
8586 // TODO: Support signed division/remainder.
8587 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM)
8588 return false;
8589 assert(
8590 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) &&
8591 "Unexpected opcode");
8592
8593 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1));
8594 if (!CN)
8595 return false;
8596
8597 APInt Divisor = CN->getAPIntValue();
8598
8599 // We depend on the UREM by constant optimization in DAGCombiner that requires
8600 // high multiply.
8601 if (!isOperationLegalOrCustom(ISD::MULHU, HiLoVT) &&
8603 return false;
8604
8605 // Don't expand if optimizing for size.
8606 if (DAG.shouldOptForSize())
8607 return false;
8608
8609 // Early out for 0 or 1 divisors.
8610 if (Divisor.ule(1))
8611 return false;
8612
8613 if (expandUDIVREMByConstantViaUREMDecomposition(N, Divisor, Result, HiLoVT,
8614 DAG, LL, LH))
8615 return true;
8616
8617 if (expandUDIVREMByConstantViaUMulHiMagic(N, Divisor, Result, HiLoVT, DAG, LL,
8618 LH))
8619 return true;
8620
8621 return false;
8622}
8623
8624// Check that (every element of) Z is undef or not an exact multiple of BW.
8625static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
8627 Z,
8628 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
8629 /*AllowUndefs=*/true, /*AllowTruncation=*/true);
8630}
8631
8633 EVT VT = Node->getValueType(0);
8634 SDValue ShX, ShY;
8635 SDValue ShAmt, InvShAmt;
8636 SDValue X = Node->getOperand(0);
8637 SDValue Y = Node->getOperand(1);
8638 SDValue Z = Node->getOperand(2);
8639 SDValue Mask = Node->getOperand(3);
8640 SDValue VL = Node->getOperand(4);
8641
8642 unsigned BW = VT.getScalarSizeInBits();
8643 bool IsFSHL = Node->getOpcode() == ISD::VP_FSHL;
8644 SDLoc DL(SDValue(Node, 0));
8645
8646 EVT ShVT = Z.getValueType();
8647 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8648 // fshl: X << C | Y >> (BW - C)
8649 // fshr: X << (BW - C) | Y >> C
8650 // where C = Z % BW is not zero
8651 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8652 ShAmt = DAG.getNode(ISD::VP_UREM, DL, ShVT, Z, BitWidthC, Mask, VL);
8653 InvShAmt = DAG.getNode(ISD::VP_SUB, DL, ShVT, BitWidthC, ShAmt, Mask, VL);
8654 ShX = DAG.getNode(ISD::VP_SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt, Mask,
8655 VL);
8656 ShY = DAG.getNode(ISD::VP_SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt, Mask,
8657 VL);
8658 } else {
8659 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
8660 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
8661 SDValue BitMask = DAG.getConstant(BW - 1, DL, ShVT);
8662 if (isPowerOf2_32(BW)) {
8663 // Z % BW -> Z & (BW - 1)
8664 ShAmt = DAG.getNode(ISD::VP_AND, DL, ShVT, Z, BitMask, Mask, VL);
8665 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
8666 SDValue NotZ = DAG.getNode(ISD::VP_XOR, DL, ShVT, Z,
8667 DAG.getAllOnesConstant(DL, ShVT), Mask, VL);
8668 InvShAmt = DAG.getNode(ISD::VP_AND, DL, ShVT, NotZ, BitMask, Mask, VL);
8669 } else {
8670 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8671 ShAmt = DAG.getNode(ISD::VP_UREM, DL, ShVT, Z, BitWidthC, Mask, VL);
8672 InvShAmt = DAG.getNode(ISD::VP_SUB, DL, ShVT, BitMask, ShAmt, Mask, VL);
8673 }
8674
8675 SDValue One = DAG.getConstant(1, DL, ShVT);
8676 if (IsFSHL) {
8677 ShX = DAG.getNode(ISD::VP_SHL, DL, VT, X, ShAmt, Mask, VL);
8678 SDValue ShY1 = DAG.getNode(ISD::VP_SRL, DL, VT, Y, One, Mask, VL);
8679 ShY = DAG.getNode(ISD::VP_SRL, DL, VT, ShY1, InvShAmt, Mask, VL);
8680 } else {
8681 SDValue ShX1 = DAG.getNode(ISD::VP_SHL, DL, VT, X, One, Mask, VL);
8682 ShX = DAG.getNode(ISD::VP_SHL, DL, VT, ShX1, InvShAmt, Mask, VL);
8683 ShY = DAG.getNode(ISD::VP_SRL, DL, VT, Y, ShAmt, Mask, VL);
8684 }
8685 }
8686 return DAG.getNode(ISD::VP_OR, DL, VT, ShX, ShY, Mask, VL);
8687}
8688
8690 SelectionDAG &DAG) const {
8691 if (Node->isVPOpcode())
8692 return expandVPFunnelShift(Node, DAG);
8693
8694 EVT VT = Node->getValueType(0);
8695
8696 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
8700 return SDValue();
8701
8702 SDValue X = Node->getOperand(0);
8703 SDValue Y = Node->getOperand(1);
8704 SDValue Z = Node->getOperand(2);
8705
8706 unsigned BW = VT.getScalarSizeInBits();
8707 bool IsFSHL = Node->getOpcode() == ISD::FSHL;
8708 SDLoc DL(SDValue(Node, 0));
8709
8710 EVT ShVT = Z.getValueType();
8711
8712 // If a funnel shift in the other direction is more supported, use it.
8713 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
8714 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
8715 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
8716 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8717 // fshl X, Y, Z -> fshr X, Y, -Z
8718 // fshr X, Y, Z -> fshl X, Y, -Z
8719 Z = DAG.getNegative(Z, DL, ShVT);
8720 } else {
8721 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
8722 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
8723 SDValue One = DAG.getConstant(1, DL, ShVT);
8724 if (IsFSHL) {
8725 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
8726 X = DAG.getNode(ISD::SRL, DL, VT, X, One);
8727 } else {
8728 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
8729 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
8730 }
8731 Z = DAG.getNOT(DL, Z, ShVT);
8732 }
8733 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
8734 }
8735
8736 SDValue ShX, ShY;
8737 SDValue ShAmt, InvShAmt;
8738 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
8739 // fshl: X << C | Y >> (BW - C)
8740 // fshr: X << (BW - C) | Y >> C
8741 // where C = Z % BW is not zero
8742 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8743 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
8744 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
8745 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
8746 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
8747 } else {
8748 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
8749 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
8750 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
8751 if (isPowerOf2_32(BW)) {
8752 // Z % BW -> Z & (BW - 1)
8753 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
8754 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
8755 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
8756 } else {
8757 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
8758 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
8759 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
8760 }
8761
8762 SDValue One = DAG.getConstant(1, DL, ShVT);
8763 if (IsFSHL) {
8764 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
8765 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
8766 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
8767 } else {
8768 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
8769 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
8770 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
8771 }
8772 }
8773 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
8774}
8775
8776// TODO: Merge with expandFunnelShift.
8778 SelectionDAG &DAG) const {
8779 EVT VT = Node->getValueType(0);
8780 unsigned EltSizeInBits = VT.getScalarSizeInBits();
8781 bool IsLeft = Node->getOpcode() == ISD::ROTL;
8782 SDValue Op0 = Node->getOperand(0);
8783 SDValue Op1 = Node->getOperand(1);
8784 SDLoc DL(SDValue(Node, 0));
8785
8786 EVT ShVT = Op1.getValueType();
8787 SDValue Zero = DAG.getConstant(0, DL, ShVT);
8788
8789 // If a rotate in the other direction is more supported, use it.
8790 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
8791 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
8792 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
8793 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
8794 return DAG.getNode(RevRot, DL, VT, Op0, Sub);
8795 }
8796
8797 if (!AllowVectorOps && VT.isVector() &&
8803 return SDValue();
8804
8805 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
8806 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
8807 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
8808 SDValue ShVal;
8809 SDValue HsVal;
8810 if (isPowerOf2_32(EltSizeInBits)) {
8811 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
8812 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
8813 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
8814 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
8815 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
8816 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
8817 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
8818 } else {
8819 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
8820 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
8821 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
8822 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
8823 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
8824 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
8825 SDValue One = DAG.getConstant(1, DL, ShVT);
8826 HsVal =
8827 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
8828 }
8829 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
8830}
8831
8832/// Check if CLMUL on VT can eventually reach a type with legal CLMUL through
8833/// a chain of halving decompositions (halving element width) and/or vector
8834/// widening (doubling element count). This guides expansion strategy selection:
8835/// if true, the halving/widening path produces better code than bit-by-bit.
8836///
8837/// HalveDepth tracks halving steps only (each creates ~4x more operations).
8838/// Widening steps are cheap (O(1) pad/extract) and don't count.
8839/// Limiting halvings to 2 prevents exponential blowup:
8840/// 1 halving: ~4 sub-CLMULs (good, e.g. v8i16 -> v8i8)
8841/// 2 halvings: ~16 sub-CLMULs (acceptable, e.g. v4i32 -> v4i16 -> v8i8)
8842/// 3 halvings: ~64 sub-CLMULs (worse than bit-by-bit expansion)
8844 EVT VT, unsigned HalveDepth = 0,
8845 unsigned TotalDepth = 0) {
8846 if (HalveDepth > 2 || TotalDepth > 8 || !VT.isFixedLengthVector())
8847 return false;
8849 return true;
8850 if (!TLI.isTypeLegal(VT))
8851 return false;
8852
8853 unsigned BW = VT.getScalarSizeInBits();
8854
8855 // Halve: halve element width, same element count.
8856 // This is the expensive step -- each halving creates ~4x more operations.
8857 if (BW % 2 == 0) {
8858 EVT HalfEltVT = EVT::getIntegerVT(Ctx, BW / 2);
8859 EVT HalfVT = VT.changeVectorElementType(Ctx, HalfEltVT);
8860 if (TLI.isTypeLegal(HalfVT) &&
8861 canNarrowCLMULToLegal(TLI, Ctx, HalfVT, HalveDepth + 1, TotalDepth + 1))
8862 return true;
8863 }
8864
8865 // Widen: double element count (fixed-width vectors only).
8866 // This is cheap -- just INSERT_SUBVECTOR + EXTRACT_SUBVECTOR.
8867 EVT WideVT = VT.getDoubleNumVectorElementsVT(Ctx);
8868 if (TLI.isTypeLegal(WideVT) &&
8869 canNarrowCLMULToLegal(TLI, Ctx, WideVT, HalveDepth, TotalDepth + 1))
8870 return true;
8871
8872 return false;
8873}
8874
8876 SDLoc DL(Node);
8877 EVT VT = Node->getValueType(0);
8878 SDValue X = Node->getOperand(0);
8879 SDValue Y = Node->getOperand(1);
8880 unsigned BW = VT.getScalarSizeInBits();
8881 unsigned Opcode = Node->getOpcode();
8882 LLVMContext &Ctx = *DAG.getContext();
8883
8884 switch (Opcode) {
8885 case ISD::CLMUL: {
8886 // For vector types, try decomposition strategies that leverage legal
8887 // CLMUL on narrower or wider element types, avoiding the expensive
8888 // bit-by-bit expansion.
8889 if (VT.isVector()) {
8890 // Strategy 1: Halving decomposition to half-element-width CLMUL.
8891 // Applies ExpandIntRes_CLMUL's identity element-wise:
8892 // CLMUL(X, Y) = (Hi << HalfBW) | Lo
8893 // where:
8894 // Lo = CLMUL(XLo, YLo)
8895 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
8896 unsigned HalfBW = BW / 2;
8897 if (BW % 2 == 0) {
8898 EVT HalfEltVT = EVT::getIntegerVT(Ctx, HalfBW);
8899 EVT HalfVT =
8900 EVT::getVectorVT(Ctx, HalfEltVT, VT.getVectorElementCount());
8901 if (isTypeLegal(HalfVT) && canNarrowCLMULToLegal(*this, Ctx, HalfVT,
8902 /*HalveDepth=*/1)) {
8903 SDValue ShAmt = DAG.getShiftAmountConstant(HalfBW, VT, DL);
8904
8905 // Extract low and high halves of each element.
8906 SDValue XLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, X);
8907 SDValue XHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
8908 DAG.getNode(ISD::SRL, DL, VT, X, ShAmt));
8909 SDValue YLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, Y);
8910 SDValue YHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
8911 DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt));
8912
8913 // Lo = CLMUL(XLo, YLo)
8914 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YLo);
8915
8916 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
8917 SDValue LoH = DAG.getNode(ISD::CLMULH, DL, HalfVT, XLo, YLo);
8918 SDValue Cross1 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YHi);
8919 SDValue Cross2 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XHi, YLo);
8920 SDValue Cross = DAG.getNode(ISD::XOR, DL, HalfVT, Cross1, Cross2);
8921 SDValue Hi = DAG.getNode(ISD::XOR, DL, HalfVT, LoH, Cross);
8922
8923 // Reassemble: Result = ZExt(Lo) | (AnyExt(Hi) << HalfBW)
8924 SDValue LoExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo);
8925 SDValue HiExt = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Hi);
8926 SDValue HiShifted = DAG.getNode(ISD::SHL, DL, VT, HiExt, ShAmt);
8927 return DAG.getNode(ISD::OR, DL, VT, LoExt, HiShifted);
8928 }
8929 }
8930
8931 // Strategy 2: Promote to double-element-width CLMUL.
8932 // CLMUL(X, Y) = Trunc(CLMUL(AnyExt(X), AnyExt(Y)))
8933 {
8934 EVT ExtVT = VT.widenIntegerElementType(Ctx);
8935 if (isTypeLegal(ExtVT) && isOperationLegalOrCustom(ISD::CLMUL, ExtVT)) {
8936 // If CLMUL on ExtVT is Custom (not Legal), the target may
8937 // scalarize it, costing O(NumElements) scalar ops. The bit-by-bit
8938 // fallback costs O(BW) vectorized iterations. Only widen when
8939 // element count is small enough that scalarization is cheaper.
8940 unsigned NumElts = VT.getVectorMinNumElements();
8941 if (isOperationLegal(ISD::CLMUL, ExtVT) || NumElts < BW) {
8942 SDValue XExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, X);
8943 SDValue YExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, Y);
8944 SDValue Mul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
8945 return DAG.getNode(ISD::TRUNCATE, DL, VT, Mul);
8946 }
8947 }
8948 }
8949
8950 // Strategy 3: Widen element count (pad with undef, do CLMUL on wider
8951 // vector, extract lower result). CLMUL is element-wise, so upper
8952 // (undef) lanes don't affect the lower results.
8953 // e.g. v4i16 => pad to v8i16 => halve to v8i8 PMUL => extract v4i16.
8954 if (auto EC = VT.getVectorElementCount(); EC.isFixed()) {
8955 EVT WideVT = EVT::getVectorVT(Ctx, VT.getVectorElementType(), EC * 2);
8956 if (isTypeLegal(WideVT) && canNarrowCLMULToLegal(*this, Ctx, WideVT)) {
8957 SDValue Undef = DAG.getUNDEF(WideVT);
8958 SDValue XWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
8959 X, DAG.getVectorIdxConstant(0, DL));
8960 SDValue YWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
8961 Y, DAG.getVectorIdxConstant(0, DL));
8962 SDValue WideRes = DAG.getNode(ISD::CLMUL, DL, WideVT, XWide, YWide);
8963 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WideRes,
8964 DAG.getVectorIdxConstant(0, DL));
8965 }
8966 }
8967 }
8968
8969 // Special case: clmul(X, ~0) is equivalent to a "parallel prefix XOR" or
8970 // "bitwise parity" operation.
8972 SDValue R = X;
8973 for (unsigned I = 1; I < BW; I <<= 1) {
8974 SDValue ShAmt = DAG.getShiftAmountConstant(I, VT, DL);
8975 SDValue Shifted = DAG.getNode(ISD::SHL, DL, VT, R, ShAmt);
8976 R = DAG.getNode(ISD::XOR, DL, VT, R, Shifted);
8977 }
8978 return R;
8979 }
8980
8981 // NOTE: If you change this expansion, please update the cost model
8982 // calculation in BasicTTIImpl::getTypeBasedIntrinsicInstrCost for
8983 // Intrinsic::clmul.
8984
8985 // Strategy 4: multiplication with holes.
8986 //
8987 // Uses "holes" (sequences of zeroes) to avoid carry spilling. When carries
8988 // do occur, they wind up in a "hole" and are subsequently masked out of the
8989 // result.
8990 //
8991 // A hole of 3 bits is optimal for 32-bit and 64-bit inputs. 128-bit
8992 // integers need a larger hole, and for smaller integers the fallback below
8993 // is more efficient.
8994 //
8995 // Based on bmul64 in bearssl and bmul in the rust polyval crate.
8996 if (BW >= 32 && BW <= 64 &&
8998
8999 // Set every fourth bit of each nibble, equivalent to 0b00010001...0001.
9000 APInt MaskVal = APInt::getSplat(BW, APInt(4, 0b0001));
9001
9002 // Create versions of X and Y that keep only the I-th bit of
9003 // each nibble.
9004 SDValue M[4], Xp[4], Yp[4];
9005 for (unsigned I = 0; I < 4; ++I) {
9006 M[I] = DAG.getConstant(MaskVal.shl(I), DL, VT);
9007 Xp[I] = DAG.getNode(ISD::AND, DL, VT, X, M[I]);
9008 Yp[I] = DAG.getNode(ISD::AND, DL, VT, Y, M[I]);
9009 }
9010
9011 // Codegens these expressions (16 multiplications):
9012 //
9013 // z0 = (x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1);
9014 // z1 = (x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2);
9015 // z2 = (x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3);
9016 // z3 = (x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0);
9017 SDValue Res = DAG.getConstant(0, DL, VT);
9018 for (unsigned I = 0; I < 4; ++I) {
9019 SDValue Zi = DAG.getConstant(0, DL, VT);
9020 for (unsigned J = 0; J < 4; ++J) {
9021 unsigned K = (I + 4 - J) % 4;
9022 SDValue P = DAG.getNode(ISD::MUL, DL, VT, Xp[J], Yp[K]);
9023 Zi = DAG.getNode(ISD::XOR, DL, VT, Zi, P);
9024 }
9025
9026 // Keep only the bits belonging to this iteration, and bitwise or it all
9027 // together.
9028 Zi = DAG.getNode(ISD::AND, DL, VT, Zi, M[I]);
9029 Res = DAG.getNode(ISD::OR, DL, VT, Res, Zi, SDNodeFlags::Disjoint);
9030 }
9031 return Res;
9032 }
9033
9034 // Strategy 5: the naive fallback.
9035 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
9036
9037 SDValue Res = DAG.getConstant(0, DL, VT);
9038 for (unsigned I = 0; I < BW; ++I) {
9039 SDValue ShiftAmt = DAG.getShiftAmountConstant(I, VT, DL);
9040 SDValue Mask = DAG.getConstant(APInt::getOneBitSet(BW, I), DL, VT);
9041 SDValue YMasked = DAG.getNode(ISD::AND, DL, VT, Y, Mask);
9042
9043 // For targets with a fast bit test instruction (e.g., x86 BT) or without
9044 // multiply, use a shift-based expansion to avoid expensive MUL
9045 // instructions.
9046 SDValue Part;
9047 if (!hasBitTest(Y, ShiftAmt) &&
9050 Part = DAG.getNode(ISD::MUL, DL, VT, X, YMasked);
9051 } else {
9052 // Canonical bit test: (Y & (1 << I)) != 0
9053 SDValue Zero = DAG.getConstant(0, DL, VT);
9054 SDValue Cond = DAG.getSetCC(DL, SetCCVT, YMasked, Zero, ISD::SETEQ);
9055 SDValue XShifted = DAG.getNode(ISD::SHL, DL, VT, X, ShiftAmt);
9056 Part = DAG.getSelect(DL, VT, Cond, Zero, XShifted);
9057 }
9058 Res = DAG.getNode(ISD::XOR, DL, VT, Res, Part);
9059 }
9060 return Res;
9061 }
9062 case ISD::CLMULR:
9063 // If we have CLMUL/CLMULH, merge the shifted results to form CLMULR.
9066 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, VT, X, Y);
9067 SDValue Hi = DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
9068 Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
9069 DAG.getShiftAmountConstant(BW - 1, VT, DL));
9070 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
9071 DAG.getShiftAmountConstant(1, VT, DL));
9072 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
9073 }
9074 [[fallthrough]];
9075 case ISD::CLMULH: {
9076 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9077 // Use bitreverse-based lowering (CLMULR/H = rev(CLMUL(rev,rev)) >> S)
9078 // when any of these hold:
9079 // (a) ZERO_EXTEND to ExtVT or SRL on ExtVT isn't legal.
9080 // (b) CLMUL is legal on VT but not on ExtVT (e.g. v8i8 on AArch64).
9081 // (c) CLMUL on ExtVT isn't legal, but CLMUL on VT can be efficiently
9082 // expanded via halving/widening to reach legal CLMUL. The bitreverse
9083 // path creates CLMUL(VT) which will be expanded efficiently. The
9084 // promote path would create CLMUL(ExtVT) => halving => CLMULH(VT),
9085 // causing a cycle.
9086 // Note: when CLMUL is legal on ExtVT, the zext => CLMUL(ExtVT) => shift
9087 // => trunc path is preferred over the bitreverse path, as it avoids the
9088 // cost of 3 bitreverse operations.
9093 canNarrowCLMULToLegal(*this, Ctx, VT)))) {
9094 SDValue XRev = DAG.getNode(ISD::BITREVERSE, DL, VT, X);
9095 SDValue YRev = DAG.getNode(ISD::BITREVERSE, DL, VT, Y);
9096 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, VT, XRev, YRev);
9097 SDValue Res = DAG.getNode(ISD::BITREVERSE, DL, VT, ClMul);
9098 if (Opcode == ISD::CLMULH)
9099 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
9100 DAG.getShiftAmountConstant(1, VT, DL));
9101 return Res;
9102 }
9103 SDValue XExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, X);
9104 SDValue YExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Y);
9105 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9106 unsigned ShAmt = Opcode == ISD::CLMULR ? BW - 1 : BW;
9107 SDValue HiBits = DAG.getNode(ISD::SRL, DL, ExtVT, ClMul,
9108 DAG.getShiftAmountConstant(ShAmt, ExtVT, DL));
9109 return DAG.getNode(ISD::TRUNCATE, DL, VT, HiBits);
9110 }
9111 }
9112 llvm_unreachable("Expected CLMUL, CLMULR, or CLMULH");
9113}
9114
9116 SDLoc DL(Node);
9117 EVT VT = Node->getValueType(0);
9118 SDValue Val = Node->getOperand(0);
9119 SDValue Msk = Node->getOperand(1);
9120 unsigned BW = VT.getScalarSizeInBits();
9121
9122 // Hacker's Delight §7-4: Compress, or Generalized Extract
9123 SDValue X = DAG.getNode(ISD::AND, DL, VT, Val, Msk);
9124 SDValue M = Msk;
9125 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9126 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, M, VT), One);
9127
9128 // Repeatedly compute which bits would shift to the right by an odd amount,
9129 // shift all such bits in parallel using a mask, and double the shift amount.
9130 for (unsigned I = 1; I < BW; I *= 2) {
9131 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9132 SDValue Mp =
9133 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9134 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, M);
9135 SDValue ShiftI = DAG.getShiftAmountConstant(I, VT, DL);
9136 SDValue MvS = DAG.getNode(ISD::SRL, DL, VT, Mv, ShiftI);
9137 M = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, M, Mv), MvS,
9139 SDValue T = DAG.getNode(ISD::AND, DL, VT, X, Mv);
9140 SDValue TS = DAG.getNode(ISD::SRL, DL, VT, T, ShiftI);
9141 X = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, X, T), TS,
9143 if (I * 2 < BW)
9144 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9145 }
9146
9147 return X;
9148}
9149
9151 SDLoc DL(Node);
9152 EVT VT = Node->getValueType(0);
9153 SDValue Val = Node->getOperand(0);
9154 SDValue Msk = Node->getOperand(1);
9155 unsigned BW = VT.getScalarSizeInBits();
9156
9157 // Hacker's Delight §7-5: Expand, or Generalized Insert.
9158 unsigned LogBW = Log2_32_Ceil(BW);
9159 SmallVector<SDValue, 8> MvArray(LogBW);
9160 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9161 SDValue Mc = Msk;
9162 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, Msk, VT), One);
9163
9164 // First pass: compute move masks for each power of two that a bit moves by.
9165 for (unsigned S = 0; S < LogBW; ++S) {
9166 unsigned ShiftS = 1u << S;
9167 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9168 SDValue Mp =
9169 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9170 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, Mc);
9171 MvArray[S] = Mv;
9172 if (S + 1 < LogBW) {
9173 SDValue McXorMv = DAG.getNode(ISD::XOR, DL, VT, Mc, Mv);
9174 SDValue MvShifted = DAG.getNode(
9175 ISD::SRL, DL, VT, Mv, DAG.getShiftAmountConstant(ShiftS, VT, DL));
9176 Mc = DAG.getNode(ISD::OR, DL, VT, McXorMv, MvShifted,
9178 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9179 }
9180 }
9181
9182 // Second pass: move bits by 32, 16, 8, 4, 2, 1, using masks, in parallel.
9183 // Each pass handles half the shift amount of the previous pass.
9184 SDValue X = Val;
9185 for (int S = (int)LogBW - 1; S >= 0; --S) {
9186 SDValue ShiftSv = DAG.getShiftAmountConstant(1ull << S, VT, DL);
9187 SDValue T = DAG.getNode(ISD::SHL, DL, VT, X, ShiftSv);
9188 SDValue UnshiftedBits =
9189 DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, MvArray[S], VT));
9190 SDValue ShiftedBits = DAG.getNode(ISD::AND, DL, VT, T, MvArray[S]);
9191 X = DAG.getNode(ISD::OR, DL, VT, UnshiftedBits, ShiftedBits,
9193 }
9194
9195 return DAG.getNode(ISD::AND, DL, VT, X, Msk);
9196}
9197
9199 SelectionDAG &DAG) const {
9200 assert(Node->getNumOperands() == 3 && "Not a double-shift!");
9201 EVT VT = Node->getValueType(0);
9202 unsigned VTBits = VT.getScalarSizeInBits();
9203 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
9204
9205 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
9206 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
9207 SDValue ShOpLo = Node->getOperand(0);
9208 SDValue ShOpHi = Node->getOperand(1);
9209 SDValue ShAmt = Node->getOperand(2);
9210 EVT ShAmtVT = ShAmt.getValueType();
9211 EVT ShAmtCCVT =
9212 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
9213 SDLoc dl(Node);
9214
9215 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
9216 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
9217 // away during isel.
9218 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9219 DAG.getConstant(VTBits - 1, dl, ShAmtVT));
9220 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9221 DAG.getConstant(VTBits - 1, dl, ShAmtVT))
9222 : DAG.getConstant(0, dl, VT);
9223
9224 SDValue Tmp2, Tmp3;
9225 if (IsSHL) {
9226 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
9227 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9228 } else {
9229 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
9230 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9231 }
9232
9233 // If the shift amount is larger or equal than the width of a part we don't
9234 // use the result from the FSHL/FSHR. Insert a test and select the appropriate
9235 // values for large shift amounts.
9236 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9237 DAG.getConstant(VTBits, dl, ShAmtVT));
9238 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
9239 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
9240
9241 if (IsSHL) {
9242 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9243 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9244 } else {
9245 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9246 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9247 }
9248}
9249
9251 SelectionDAG &DAG) const {
9252 // This implements llvm.canonicalize.f* by multiplication with 1.0, as
9253 // suggested in
9254 // https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic.
9255 // It uses strict_fp operations even outside a strict_fp context in order
9256 // to guarantee that the canonicalization is not optimized away by later
9257 // passes. The result chain introduced by that is intentionally ignored
9258 // since no ordering requirement is intended here.
9259 EVT VT = Node->getValueType(0);
9260 SDLoc DL(Node);
9261 SDNodeFlags Flags = Node->getFlags();
9262 Flags.setNoFPExcept(true);
9263 SDValue One = DAG.getConstantFP(1.0, DL, VT);
9264 SDValue Mul =
9265 DAG.getNode(ISD::STRICT_FMUL, DL, {VT, MVT::Other},
9266 {DAG.getEntryNode(), Node->getOperand(0), One}, Flags);
9267 return Mul;
9268}
9269
9271 SelectionDAG &DAG) const {
9272 // Expand conversion from a native IEEE float type to an arbitrary FP format
9273 // returning the result as an integer using bit manipulation.
9274 EVT ResVT = Node->getValueType(0);
9275 SDLoc dl(Node);
9276
9277 SDValue FloatVal = Node->getOperand(0);
9278 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9279 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9280 const auto RoundMode =
9281 static_cast<RoundingMode>(Node->getConstantOperandVal(2));
9282 const bool Saturate = Node->getConstantOperandVal(3) != 0;
9283
9284 // Supported destination formats.
9285 switch (Sem) {
9291 break;
9292 default:
9293 DAG.getContext()->emitError("CONVERT_TO_ARBITRARY_FP: not implemented "
9294 "destination format (semantics enum " +
9295 Twine(SemEnum) + ")");
9296 return SDValue();
9297 }
9298
9299 // Supported rounding modes.
9300 switch (RoundMode) {
9306 break;
9307 default:
9308 DAG.getContext()->emitError(
9309 "CONVERT_TO_ARBITRARY_FP: unsupported rounding mode (enum " +
9310 Twine(static_cast<int>(RoundMode)) + ")");
9311 return SDValue();
9312 }
9313
9314 // Destination format parameters.
9315 const fltSemantics &DstSem = APFloatBase::EnumToSemantics(Sem);
9316 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9317 const unsigned DstPrecision = APFloat::semanticsPrecision(DstSem);
9318 const unsigned DstMant = DstPrecision - 1;
9319 const unsigned DstExpBits = DstBits - DstMant - 1;
9320 const int DstBias = 1 - APFloat::semanticsMinExponent(DstSem);
9321 const unsigned DstExpMax = (1U << DstExpBits) - 1;
9322 const uint64_t DstMantMask = (DstMant > 0) ? ((1ULL << DstMant) - 1) : 0;
9323 const fltNonfiniteBehavior DstNFBehavior = DstSem.nonFiniteBehavior;
9324 const fltNanEncoding DstNanEnc = DstSem.nanEncoding;
9325
9326 // Compute the maximum normal exponent for the destination format.
9327 const unsigned DstExpMaxNormal =
9328 DstNFBehavior == fltNonfiniteBehavior::IEEE754 ? DstExpMax - 1
9329 : DstExpMax;
9330
9331 // For NanOnly formats the max exponent field for finite values
9332 // is DstExpMax, but the encoding with exp = DstExpMax and
9333 // mant = all-ones is NaN. So DstExpMaxNormal = DstExpMax, but max
9334 // mantissa at that exponent is DstMantMask - 1 (if NanEnc == AllOnes) to
9335 // avoid the NaN encoding.
9336 uint64_t DstMaxMantAtMaxExp = DstMantMask;
9337 if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9338 DstNanEnc == fltNanEncoding::AllOnes)
9339 DstMaxMantAtMaxExp = DstMantMask - 1;
9340
9341 // Source format parameters.
9342 EVT SrcVT = FloatVal.getValueType();
9343 const fltSemantics &SrcSem = SrcVT.getScalarType().getFltSemantics();
9344 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9345 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9346 const unsigned SrcMant = SrcPrecision - 1;
9347 const uint64_t SrcMantMask = (1ULL << SrcMant) - 1;
9348
9349 // Work in the source integer type. Match the destination shape so the
9350 // expansion stays vector when ResVT is a vector.
9351 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), SrcBits);
9352 EVT IntVT = ResVT.changeElementType(*DAG.getContext(), IntScalarVT);
9353 EVT SetCCVT =
9354 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9355 EVT FPSetCCVT =
9356 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
9357
9358 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9359 SDValue One = DAG.getConstant(1, dl, IntVT);
9360
9361 // Bitcast source float to integer to extract the sign bit.
9362 SDValue Src = DAG.getNode(ISD::BITCAST, dl, IntVT, FloatVal);
9363 SDValue SignBit =
9364 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9365 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl));
9366
9367 // Classify the input.
9368 SDValue FPZero = DAG.getConstantFP(0.0, dl, SrcVT);
9369 SDValue FPInf = DAG.getConstantFP(APFloat::getInf(SrcSem), dl, SrcVT);
9370 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, SrcVT, FloatVal);
9371 SDValue IsNaN = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETUO);
9372 SDValue IsInf = DAG.getSetCC(dl, FPSetCCVT, AbsVal, FPInf, ISD::SETOEQ);
9373 SDValue IsZero = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOEQ);
9374
9375 // Split into a normalized fraction and unbiased exponent. FFREXP normalizes
9376 // source denormals automatically. The result is unspecified for Inf/NaN, but
9377 // those inputs are detected above and override the final result.
9378 EVT FrexpExpScalarVT =
9380 EVT FrexpExpVT = SrcVT.changeElementType(*DAG.getContext(), FrexpExpScalarVT);
9381 SDValue Frexp =
9382 DAG.getNode(ISD::FFREXP, dl, DAG.getVTList(SrcVT, FrexpExpVT), FloatVal);
9383 SDValue FrexpFrac = Frexp.getValue(0);
9384 SDValue FrexpExp = Frexp.getValue(1);
9385
9386 SDValue FrexpFracInt = DAG.getNode(ISD::BITCAST, dl, IntVT, FrexpFrac);
9387 SDValue EffSrcMant = DAG.getNode(ISD::AND, dl, IntVT, FrexpFracInt,
9388 DAG.getConstant(SrcMantMask, dl, IntVT));
9389
9390 SDValue FrexpExpExt = DAG.getSExtOrTrunc(FrexpExp, dl, IntVT);
9391 SDValue NewExp = DAG.getNode(ISD::ADD, dl, IntVT, FrexpExpExt,
9392 DAG.getConstant(DstBias - 1, dl, IntVT));
9393
9394 // Compute rounding increment given the round bit, sticky bits, and LSB
9395 // of the truncated mantissa.
9396 auto ComputeRoundUp = [&](SDValue RoundBit, SDValue StickyBits,
9397 SDValue LSB) -> SDValue {
9398 switch (RoundMode) {
9400 // Round up if round_bit && (sticky || lsb)
9401 SDValue StickyOrLSB = DAG.getNode(ISD::OR, dl, IntVT, StickyBits, LSB);
9402 return DAG.getNode(ISD::AND, dl, IntVT, RoundBit, StickyOrLSB);
9403 }
9405 return Zero;
9407 // Round up if positive and any truncated bits are set.
9408 SDValue AnyTruncBits =
9409 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9410 SDValue HasTruncBits =
9411 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9412 SDValue IsPositive = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETEQ);
9413 SDValue DoRound =
9414 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsPositive);
9415 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9416 }
9418 // Round up if negative and any truncated bits are set (to -Inf).
9419 SDValue AnyTruncBits =
9420 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9421 SDValue HasTruncBits =
9422 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9423 SDValue IsNegative = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETNE);
9424 SDValue DoRound =
9425 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsNegative);
9426 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9427 }
9429 return RoundBit;
9430 default:
9431 llvm_unreachable("unsupported rounding mode");
9432 }
9433 };
9434
9435 // Round mantissa from SrcMant bits to DstMant bits.
9436 SDValue TruncMant;
9437 SDValue RoundUp;
9438 if (SrcMant > DstMant) {
9439 const unsigned Shift = SrcMant - DstMant;
9440 SDValue ShiftConst = DAG.getShiftAmountConstant(Shift, IntVT, dl);
9441 TruncMant = DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, ShiftConst);
9442
9443 // Check bit at position Shift - 1 aka the round bit.
9444 SDValue RoundBit;
9445 if (Shift >= 1) {
9446 SDValue RoundBitShift = DAG.getShiftAmountConstant(Shift - 1, IntVT, dl);
9447 SDValue ShiftedMant =
9448 DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, RoundBitShift);
9449 RoundBit = DAG.getNode(ISD::AND, dl, IntVT, ShiftedMant, One);
9450 } else {
9451 RoundBit = Zero;
9452 }
9453
9454 // OR of all bits below the round bit to get sticky bits.
9455 SDValue StickyBits;
9456 if (Shift >= 2) {
9457 uint64_t StickyMask = maskTrailingOnes<uint64_t>(Shift - 1);
9458 StickyBits = DAG.getNode(ISD::AND, dl, IntVT, EffSrcMant,
9459 DAG.getConstant(StickyMask, dl, IntVT));
9460 StickyBits = DAG.getSetCC(dl, SetCCVT, StickyBits, Zero, ISD::SETNE);
9461 StickyBits = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, StickyBits);
9462 } else {
9463 StickyBits = Zero;
9464 }
9465
9466 // LSB of truncated mantissa.
9467 SDValue LSB = DAG.getNode(ISD::AND, dl, IntVT, TruncMant, One);
9468
9469 RoundUp = ComputeRoundUp(RoundBit, StickyBits, LSB);
9470 } else {
9471 // If DstMant >= SrcMant, then no rounding needed, just shift left.
9472 SDValue MantShift =
9473 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9474 TruncMant = DAG.getNode(ISD::SHL, dl, IntVT, EffSrcMant, MantShift);
9475 RoundUp = Zero;
9476 }
9477
9478 // Apply rounding.
9479 SDValue RoundedMant = DAG.getNode(ISD::ADD, dl, IntVT, TruncMant, RoundUp);
9480
9481 // Handle mantissa overflow from rounding.
9482 // If rounded_mant > DstMantMask, carry into exponent.
9483 SDValue MantOverflow =
9484 DAG.getSetCC(dl, SetCCVT, RoundedMant,
9485 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9486 // On overflow: mant = 0, exp += 1.
9487 SDValue AdjMant = DAG.getSelect(dl, IntVT, MantOverflow, Zero, RoundedMant);
9488 SDValue AdjExp =
9489 DAG.getNode(ISD::ADD, dl, IntVT, NewExp,
9490 DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, MantOverflow));
9491
9492 // Precompute sign shifted to MSB of destination.
9493 SDValue SignShifted =
9494 DAG.getNode(ISD::SHL, dl, IntVT, SignBit,
9495 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl));
9496
9497 // Destination denormal conversion (when new_exp <= 0).
9498 // Shift the mantissa right by 1 - new_exp additional bits and set the
9499 // exponent field to 0.
9500 SDValue ExpIsNeg = DAG.getSetCC(dl, SetCCVT, AdjExp,
9501 DAG.getConstant(1, dl, IntVT), ISD::SETLT);
9502
9503 SDValue DenormResult;
9504 {
9505 // denorm_shift = 1 - NewExp.
9506 SDValue DenormShift = DAG.getNode(ISD::SUB, dl, IntVT, One, NewExp);
9507
9508 // full_src_mant = (1 << SrcMant) | EffSrcMant.
9509 SDValue ImplicitOne =
9510 DAG.getNode(ISD::SHL, dl, IntVT, One,
9511 DAG.getShiftAmountConstant(SrcMant, IntVT, dl));
9512 SDValue FullSrcMant =
9513 DAG.getNode(ISD::OR, dl, IntVT, EffSrcMant, ImplicitOne);
9514
9515 // Total right shift = DenormShift + (SrcMant - DstMant).
9516 int64_t MantDelta = static_cast<int64_t>(SrcMant) - DstMant;
9517 SDValue TotalShift =
9518 DAG.getNode(ISD::ADD, dl, IntVT, DenormShift,
9519 DAG.getSignedConstant(MantDelta, dl, IntVT));
9520
9521 // Clamp total shift to avoid UB, then truncate denorm mantissa.
9522 EVT ShiftVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9523 SDValue MaxShift = DAG.getConstant(SrcBits - 1, dl, IntVT);
9524 SDValue ClampedShift =
9525 DAG.getNode(ISD::UMIN, dl, IntVT, TotalShift, MaxShift);
9526 SDValue DenormTruncMant =
9527 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant,
9528 DAG.getZExtOrTrunc(ClampedShift, dl, ShiftVT));
9529
9530 // Rounding for denorm path.
9531 SDValue DenormRoundUp;
9532 {
9533 // Round bit is at position TotalShift - 1 of FullSrcMant.
9534 // Clamp to at least 1 so the subtraction doesn't underflow and create
9535 // shift nodes with invalid shift amounts.
9536 SDValue SafeShift = DAG.getNode(ISD::UMAX, dl, IntVT, ClampedShift, One);
9537 SDValue RoundBitPos = DAG.getNode(ISD::SUB, dl, IntVT, SafeShift, One);
9538 SDValue RoundBitPosAmt = DAG.getZExtOrTrunc(RoundBitPos, dl, ShiftVT);
9539 SDValue DenormRoundBit = DAG.getNode(
9540 ISD::AND, dl, IntVT,
9541 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant, RoundBitPosAmt), One);
9542
9543 // Sticky: all bits below round bit.
9544 // sticky_mask = (1 << RoundBitPos) - 1
9545 SDValue StickyMask = DAG.getNode(
9546 ISD::SUB, dl, IntVT,
9547 DAG.getNode(ISD::SHL, dl, IntVT, One, RoundBitPosAmt), One);
9548 SDValue DenormStickyBits =
9549 DAG.getNode(ISD::AND, dl, IntVT, FullSrcMant, StickyMask);
9550 SDValue HasSticky = DAG.getNode(
9551 ISD::ZERO_EXTEND, dl, IntVT,
9552 DAG.getSetCC(dl, SetCCVT, DenormStickyBits, Zero, ISD::SETNE));
9553
9554 SDValue DenormLSB =
9555 DAG.getNode(ISD::AND, dl, IntVT, DenormTruncMant, One);
9556
9557 DenormRoundUp = ComputeRoundUp(DenormRoundBit, HasSticky, DenormLSB);
9558
9559 // Only apply rounding if TotalShift >= 1 (i.e., there are bits to round).
9560 SDValue ShiftGEOne =
9561 DAG.getSetCC(dl, SetCCVT, ClampedShift, One, ISD::SETUGE);
9562 DenormRoundUp = DAG.getSelect(dl, IntVT, ShiftGEOne, DenormRoundUp, Zero);
9563 }
9564
9565 SDValue DenormRoundedMant =
9566 DAG.getNode(ISD::ADD, dl, IntVT, DenormTruncMant, DenormRoundUp);
9567
9568 // If rounding caused overflow into the normal range, then we get the
9569 // smallest normal number.
9570 SDValue DenormMantOF =
9571 DAG.getSetCC(dl, SetCCVT, DenormRoundedMant,
9572 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9573 SDValue DenormFinalMant =
9574 DAG.getSelect(dl, IntVT, DenormMantOF, Zero, DenormRoundedMant);
9575 SDValue DenormFinalExp = DAG.getSelect(dl, IntVT, DenormMantOF, One, Zero);
9576
9577 // Assemble: sign | (exp << DstMant) | mant
9578 SDValue DenormExpShifted =
9579 DAG.getNode(ISD::SHL, dl, IntVT, DenormFinalExp,
9580 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9581 DenormResult = DAG.getNode(
9582 ISD::OR, dl, IntVT,
9583 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
9584 DenormFinalMant);
9585 }
9586
9587 // Exponent overflow detection.
9588 SDValue ExpOF =
9589 DAG.getSetCC(dl, SetCCVT, AdjExp,
9590 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETGT);
9591
9592 // Also check if AdjExp == DstExpMaxNormal and mantissa overflow into
9593 // a value that exceeds the max allowed mantissa at that exponent.
9594 SDValue ExpAtMax =
9595 DAG.getSetCC(dl, SetCCVT, AdjExp,
9596 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETEQ);
9597 SDValue MantExceedsMax =
9598 DAG.getSetCC(dl, SetCCVT, AdjMant,
9599 DAG.getConstant(DstMaxMantAtMaxExp, dl, IntVT), ISD::SETGT);
9600 SDValue ExpMantOF =
9601 DAG.getNode(ISD::AND, dl, SetCCVT, ExpAtMax, MantExceedsMax);
9602 SDValue IsOverflow = DAG.getNode(ISD::OR, dl, SetCCVT, ExpOF, ExpMantOF);
9603
9604 // Build overflow result.
9606
9607 if (Saturate) {
9608 // Clamp to max finite value:
9609 // sign | (DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp
9610 uint64_t MaxFinite =
9611 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9612 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9613 DAG.getConstant(MaxFinite, dl, IntVT));
9614 } else if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9615 // Produce infinity.
9616 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9617 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9618 DAG.getConstant(InfBits, dl, IntVT));
9619 } else {
9620 // Emit poison if no Inf in format and not saturating.
9621 OverflowResult = DAG.getPOISON(IntVT);
9622 }
9623
9624 // Assemble normal result: sign | (AdjExp << DstMant) | AdjMant
9625 SDValue NormExpShifted =
9626 DAG.getNode(ISD::SHL, dl, IntVT, AdjExp,
9627 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
9628 SDValue NormResult = DAG.getNode(
9629 ISD::OR, dl, IntVT,
9630 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted), AdjMant);
9631
9632 // Build special-value results.
9633 SDValue NaNResult;
9634 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9635 // Produce canonical NaN.
9636 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
9637 NaNResult =
9638 DAG.getConstant(((uint64_t)DstExpMax << DstMant) | QNaNBit, dl, IntVT);
9639 } else if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9640 DstNanEnc == fltNanEncoding::AllOnes) {
9641 // E4M3FN-style: NaN is exp=all-ones, mant=all-ones.
9642 NaNResult = DAG.getConstant(((uint64_t)DstExpMax << DstMant) | DstMantMask,
9643 dl, IntVT);
9644 } else {
9645 // NaN -> poison for finite only values.
9646 NaNResult = DAG.getPOISON(IntVT);
9647 }
9648
9649 // Inf handling.
9650 SDValue InfResult;
9651 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
9652 // Produce signed infinity.
9653 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
9654 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9655 DAG.getConstant(InfBits, dl, IntVT));
9656 } else if (Saturate) {
9657 // Inf saturates to max finite.
9658 uint64_t MaxFinite =
9659 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
9660 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9661 DAG.getConstant(MaxFinite, dl, IntVT));
9662 } else {
9663 // No Inf and not saturating -> poison.
9664 InfResult = DAG.getPOISON(IntVT);
9665 }
9666
9667 SDValue ZeroResult = SignShifted;
9668
9669 // Final selection in an order: NaN takes priority, then Inf, then Zero.
9670 SDValue FiniteResult =
9671 DAG.getSelect(dl, IntVT, ExpIsNeg, DenormResult, NormResult);
9672 FiniteResult =
9673 DAG.getSelect(dl, IntVT, IsOverflow, OverflowResult, FiniteResult);
9674
9675 SDValue Result = FiniteResult;
9676 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
9677 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
9678 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
9679
9680 // Truncate to destination integer type.
9681 return DAG.getZExtOrTrunc(Result, dl, ResVT);
9682}
9683
9684SDValue
9686 SelectionDAG &DAG) const {
9687 SDLoc dl(Node);
9688 EVT DstVT = Node->getValueType(0);
9689 EVT DstScalarVT = DstVT.getScalarType();
9690
9691 SDValue IntVal = Node->getOperand(0);
9692 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9693 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9694
9695 // Supported source formats.
9696 switch (Sem) {
9702 break;
9703 default:
9704 DAG.getContext()->emitError("CONVERT_FROM_ARBITRARY_FP: not implemented "
9705 "source format (semantics enum " +
9706 Twine(SemEnum) + ")");
9707 return SDValue();
9708 }
9709
9710 const fltSemantics &SrcSem = APFloatBase::EnumToSemantics(Sem);
9711 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9712 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9713 const unsigned SrcMant = SrcPrecision - 1;
9714 const unsigned SrcExp = SrcBits - SrcMant - 1;
9715 const int SrcBias = 1 - APFloat::semanticsMinExponent(SrcSem);
9716 const fltNonfiniteBehavior NFBehavior = SrcSem.nonFiniteBehavior;
9717
9718 // Destination format parameters.
9719 const fltSemantics &DstSem = DstScalarVT.getFltSemantics();
9720 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9721 const unsigned DstMant = APFloat::semanticsPrecision(DstSem) - 1;
9722 const unsigned DstExpBits = DstBits - DstMant - 1;
9723 const int DstMinExp = APFloat::semanticsMinExponent(DstSem);
9724 const int DstBias = 1 - DstMinExp;
9725 const uint64_t DstExpAllOnes = (1ULL << DstExpBits) - 1;
9726
9727 // Work in an integer type matching the destination float width.
9728 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), DstBits);
9729 EVT IntVT = DstVT.isVector()
9730 ? EVT::getVectorVT(*DAG.getContext(), IntScalarVT,
9731 DstVT.getVectorElementCount())
9732 : IntScalarVT;
9733
9734 SDValue Src = DAG.getZExtOrTrunc(IntVal, dl, IntVT);
9735
9736 EVT SetCCVT =
9737 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9738
9739 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9740 SDValue One = DAG.getConstant(1, dl, IntVT);
9741
9742 // Extract bit fields.
9743 const uint64_t MantMask = (SrcMant > 0) ? ((1ULL << SrcMant) - 1) : 0;
9744 const uint64_t ExpMask = (1ULL << SrcExp) - 1;
9745
9746 SDValue MantField = DAG.getNode(ISD::AND, dl, IntVT, Src,
9747 DAG.getConstant(MantMask, dl, IntVT));
9748
9749 SDValue ExpField =
9750 DAG.getNode(ISD::AND, dl, IntVT,
9751 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9752 DAG.getShiftAmountConstant(SrcMant, IntVT, dl)),
9753 DAG.getConstant(ExpMask, dl, IntVT));
9754
9755 SDValue SignBit =
9756 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9757 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl));
9758
9759 SDValue SignShifted =
9760 DAG.getNode(ISD::SHL, dl, IntVT, SignBit,
9761 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl));
9762
9763 // Classify the input.
9764 SDValue ExpAllOnes = DAG.getConstant(ExpMask, dl, IntVT);
9765 SDValue IsExpAllOnes =
9766 DAG.getSetCC(dl, SetCCVT, ExpField, ExpAllOnes, ISD::SETEQ);
9767 SDValue IsExpZero = DAG.getSetCC(dl, SetCCVT, ExpField, Zero, ISD::SETEQ);
9768 SDValue IsMantZero = DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETEQ);
9769 SDValue IsMantNonZero =
9770 DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETNE);
9771
9772 SDValue IsNaN;
9773 if (NFBehavior == fltNonfiniteBehavior::FiniteOnly) {
9774 IsNaN = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
9775 } else if (NFBehavior == fltNonfiniteBehavior::IEEE754) {
9776 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantNonZero);
9777 } else {
9779 SDValue MantAllOnes = DAG.getConstant(MantMask, dl, IntVT);
9780 SDValue IsMantAllOnes =
9781 DAG.getSetCC(dl, SetCCVT, MantField, MantAllOnes, ISD::SETEQ);
9782 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantAllOnes);
9783 }
9784
9785 SDValue IsInf;
9786 if (NFBehavior == fltNonfiniteBehavior::IEEE754)
9787 IsInf = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantZero);
9788 else
9789 IsInf = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
9790
9791 SDValue IsZero = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantZero);
9792 SDValue IsDenorm =
9793 DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantNonZero);
9794
9795 // Normal value conversion.
9796 const int BiasAdjust = DstBias - SrcBias;
9797 SDValue NormDstExp =
9798 DAG.getNode(ISD::ADD, dl, IntVT, ExpField,
9799 DAG.getConstant(APInt(DstBits, BiasAdjust, true), dl, IntVT));
9800
9801 SDValue NormDstMant;
9802 if (DstMant > SrcMant) {
9803 SDValue NormDstMantShift =
9804 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9805 NormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, MantField, NormDstMantShift);
9806 } else {
9807 NormDstMant = MantField;
9808 }
9809
9810 SDValue DstMantShift = DAG.getShiftAmountConstant(DstMant, IntVT, dl);
9811 SDValue NormExpShifted =
9812 DAG.getNode(ISD::SHL, dl, IntVT, NormDstExp, DstMantShift);
9813 SDValue NormResult =
9814 DAG.getNode(ISD::OR, dl, IntVT,
9815 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted),
9816 NormDstMant);
9817
9818 // Denormal value conversion.
9819 SDValue DenormResult;
9820 {
9821 const unsigned IntVTBits = DstBits;
9822 SDValue LeadingZeros =
9823 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, IntVT, MantField);
9824
9825 const int DenormExpConst =
9826 (int)IntVTBits + DstBias - SrcBias - (int)SrcMant;
9827 SDValue DenormDstExp = DAG.getNode(
9828 ISD::SUB, dl, IntVT,
9829 DAG.getConstant(APInt(DstBits, DenormExpConst, true), dl, IntVT),
9830 LeadingZeros);
9831
9832 SDValue MantMSB =
9833 DAG.getNode(ISD::SUB, dl, IntVT,
9834 DAG.getConstant(IntVTBits - 1, dl, IntVT), LeadingZeros);
9835
9836 SDValue LeadingOne = DAG.getNode(ISD::SHL, dl, IntVT, One, MantMSB);
9837 SDValue Frac = DAG.getNode(ISD::XOR, dl, IntVT, MantField, LeadingOne);
9838
9839 const unsigned ShiftSub = IntVTBits - 1 - DstMant;
9840 SDValue ShiftAmount = DAG.getNode(ISD::SUB, dl, IntVT, LeadingZeros,
9841 DAG.getConstant(ShiftSub, dl, IntVT));
9842
9843 SDValue DenormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, Frac, ShiftAmount);
9844
9845 SDValue DenormExpShifted =
9846 DAG.getNode(ISD::SHL, dl, IntVT, DenormDstExp, DstMantShift);
9847 DenormResult = DAG.getNode(
9848 ISD::OR, dl, IntVT,
9849 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
9850 DenormDstMant);
9851 }
9852
9853 SDValue FiniteResult =
9854 DAG.getSelect(dl, IntVT, IsDenorm, DenormResult, NormResult);
9855
9856 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
9857 SDValue NaNResult =
9858 DAG.getConstant((DstExpAllOnes << DstMant) | QNaNBit, dl, IntVT);
9859
9860 SDValue InfResult =
9861 DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
9862 DAG.getConstant(DstExpAllOnes << DstMant, dl, IntVT));
9863
9864 SDValue ZeroResult = SignShifted;
9865
9866 SDValue Result = FiniteResult;
9867 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
9868 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
9869 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
9870
9871 return DAG.getNode(ISD::BITCAST, dl, DstVT, Result);
9872}
9873
9875 SelectionDAG &DAG) const {
9876 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
9877 SDValue Src = Node->getOperand(OpNo);
9878 EVT SrcVT = Src.getValueType();
9879 EVT DstVT = Node->getValueType(0);
9880 SDLoc dl(SDValue(Node, 0));
9881
9882 // FIXME: Only f32 to i64 conversions are supported.
9883 if (SrcVT != MVT::f32 || DstVT != MVT::i64)
9884 return false;
9885
9886 if (Node->isStrictFPOpcode())
9887 // When a NaN is converted to an integer a trap is allowed. We can't
9888 // use this expansion here because it would eliminate that trap. Other
9889 // traps are also allowed and cannot be eliminated. See
9890 // IEEE 754-2008 sec 5.8.
9891 return false;
9892
9893 // Expand f32 -> i64 conversion
9894 // This algorithm comes from compiler-rt's implementation of fixsfdi:
9895 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
9896 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
9897 EVT IntVT = SrcVT.changeTypeToInteger();
9898 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9899
9900 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
9901 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
9902 SDValue Bias = DAG.getConstant(127, dl, IntVT);
9903 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
9904 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
9905 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
9906
9907 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
9908
9909 SDValue ExponentBits = DAG.getNode(
9910 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
9911 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
9912 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
9913
9914 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
9915 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
9916 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
9917 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
9918
9919 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
9920 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
9921 DAG.getConstant(0x00800000, dl, IntVT));
9922
9923 R = DAG.getZExtOrTrunc(R, dl, DstVT);
9924
9925 R = DAG.getSelectCC(
9926 dl, Exponent, ExponentLoBit,
9927 DAG.getNode(ISD::SHL, dl, DstVT, R,
9928 DAG.getZExtOrTrunc(
9929 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
9930 dl, IntShVT)),
9931 DAG.getNode(ISD::SRL, dl, DstVT, R,
9932 DAG.getZExtOrTrunc(
9933 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
9934 dl, IntShVT)),
9935 ISD::SETGT);
9936
9937 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
9938 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
9939
9940 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
9941 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
9942 return true;
9943}
9944
9946 SDValue &Chain,
9947 SelectionDAG &DAG) const {
9948 SDLoc dl(SDValue(Node, 0));
9949 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
9950 SDValue Src = Node->getOperand(OpNo);
9951
9952 EVT SrcVT = Src.getValueType();
9953 EVT DstVT = Node->getValueType(0);
9954 EVT SetCCVT =
9955 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
9956 EVT DstSetCCVT =
9957 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
9958
9959 // Only expand vector types if we have the appropriate vector bit operations.
9960 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
9962 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
9964 return false;
9965
9966 // If the maximum float value is smaller then the signed integer range,
9967 // the destination signmask can't be represented by the float, so we can
9968 // just use FP_TO_SINT directly.
9969 const fltSemantics &APFSem = SrcVT.getFltSemantics();
9970 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
9971 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
9973 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
9974 if (Node->isStrictFPOpcode()) {
9975 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
9976 { Node->getOperand(0), Src });
9977 Chain = Result.getValue(1);
9978 } else
9979 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
9980 return true;
9981 }
9982
9983 // Don't expand it if there isn't cheap fsub instruction.
9985 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
9986 return false;
9987
9988 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
9989 SDValue Sel;
9990
9991 if (Node->isStrictFPOpcode()) {
9992 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
9993 Node->getOperand(0), /*IsSignaling*/ true);
9994 Chain = Sel.getValue(1);
9995 } else {
9996 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
9997 }
9998
9999 bool Strict = Node->isStrictFPOpcode() ||
10000 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
10001
10002 if (Strict) {
10003 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
10004 // signmask then offset (the result of which should be fully representable).
10005 // Sel = Src < 0x8000000000000000
10006 // FltOfs = select Sel, 0, 0x8000000000000000
10007 // IntOfs = select Sel, 0, 0x8000000000000000
10008 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
10009
10010 // TODO: Should any fast-math-flags be set for the FSUB?
10011 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
10012 DAG.getConstantFP(0.0, dl, SrcVT), Cst);
10013 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10014 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
10015 DAG.getConstant(0, dl, DstVT),
10016 DAG.getConstant(SignMask, dl, DstVT));
10017 SDValue SInt;
10018 if (Node->isStrictFPOpcode()) {
10019 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
10020 { Chain, Src, FltOfs });
10021 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10022 { Val.getValue(1), Val });
10023 Chain = SInt.getValue(1);
10024 } else {
10025 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
10026 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
10027 }
10028 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
10029 } else {
10030 // Expand based on maximum range of FP_TO_SINT:
10031 // True = fp_to_sint(Src)
10032 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
10033 // Result = select (Src < 0x8000000000000000), True, False
10034
10035 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10036 // TODO: Should any fast-math-flags be set for the FSUB?
10037 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
10038 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
10039 False = DAG.getNode(ISD::XOR, dl, DstVT, False,
10040 DAG.getConstant(SignMask, dl, DstVT));
10041 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10042 Result = DAG.getSelect(dl, DstVT, Sel, True, False);
10043 }
10044 return true;
10045}
10046
10048 SDValue &Chain, SelectionDAG &DAG) const {
10049 // This transform is not correct for converting 0 when rounding mode is set
10050 // to round toward negative infinity which will produce -0.0. So disable
10051 // under strictfp.
10052 if (Node->isStrictFPOpcode())
10053 return false;
10054
10055 SDValue Src = Node->getOperand(0);
10056 EVT SrcVT = Src.getValueType();
10057 EVT DstVT = Node->getValueType(0);
10058
10059 // If the input is known to be non-negative and SINT_TO_FP is legal then use
10060 // it.
10061 if (Node->getFlags().hasNonNeg() &&
10063 Result =
10064 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0));
10065 return true;
10066 }
10067
10068 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
10069 return false;
10070
10071 // Only expand vector types if we have the appropriate vector bit
10072 // operations.
10073 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
10078 return false;
10079
10080 SDLoc dl(SDValue(Node, 0));
10081
10082 // Implementation of unsigned i64 to f64 following the algorithm in
10083 // __floatundidf in compiler_rt. This implementation performs rounding
10084 // correctly in all rounding modes with the exception of converting 0
10085 // when rounding toward negative infinity. In that case the fsub will
10086 // produce -0.0. This will be added to +0.0 and produce -0.0 which is
10087 // incorrect.
10088 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
10089 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
10090 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
10091 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
10092 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
10093 SDValue HiShift = DAG.getShiftAmountConstant(32, SrcVT, dl);
10094
10095 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
10096 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
10097 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
10098 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
10099 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
10100 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
10101 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
10102 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
10103 return true;
10104}
10105
10106SDValue
10108 SelectionDAG &DAG) const {
10109 unsigned Opcode = Node->getOpcode();
10110 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
10111 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
10112 "Wrong opcode");
10113
10114 if (Node->getFlags().hasNoNaNs()) {
10115 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
10116 EVT VT = Node->getValueType(0);
10117 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) ||
10119 VT.isVector())
10120 return SDValue();
10121 SDValue Op1 = Node->getOperand(0);
10122 SDValue Op2 = Node->getOperand(1);
10123 return DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred,
10124 Node->getFlags());
10125 }
10126
10127 return SDValue();
10128}
10129
10131 SelectionDAG &DAG) const {
10132 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG))
10133 return Expanded;
10134
10135 EVT VT = Node->getValueType(0);
10136 if (VT.isScalableVector())
10138 "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
10139
10140 SDLoc dl(Node);
10141 unsigned NewOp =
10143
10144 if (isOperationLegalOrCustom(NewOp, VT)) {
10145 SDValue Quiet0 = Node->getOperand(0);
10146 SDValue Quiet1 = Node->getOperand(1);
10147
10148 if (!Node->getFlags().hasNoNaNs()) {
10149 // Insert canonicalizes if it's possible we need to quiet to get correct
10150 // sNaN behavior.
10151 if (!DAG.isKnownNeverSNaN(Quiet0)) {
10152 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
10153 Node->getFlags());
10154 }
10155 if (!DAG.isKnownNeverSNaN(Quiet1)) {
10156 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
10157 Node->getFlags());
10158 }
10159 }
10160
10161 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
10162 }
10163
10164 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
10165 // instead if there are no NaNs.
10166 if (Node->getFlags().hasNoNaNs() ||
10167 (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
10168 DAG.isKnownNeverNaN(Node->getOperand(1)))) {
10169 unsigned IEEE2018Op =
10170 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
10171 if (isOperationLegalOrCustom(IEEE2018Op, VT))
10172 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
10173 Node->getOperand(1), Node->getFlags());
10174 }
10175
10177 return SelCC;
10178
10179 return SDValue();
10180}
10181
10183 const TargetLowering &TLI,
10184 const SDLoc &DL, SDValue Val,
10185 FPClassTest FPClass) {
10186 EVT VT = Val.getValueType();
10187 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10188 EVT IntVT = VT.changeTypeToInteger();
10189 EVT FloatVT = VT.changeElementType(*DAG.getContext(), MVT::f32);
10190 SDValue TestZero = DAG.getTargetConstant(FPClass, DL, MVT::i32);
10191 if (!TLI.isTypeLegal(IntVT) &&
10193 Val = DAG.getNode(ISD::FP_ROUND, DL, FloatVT, Val,
10194 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
10195 return DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, Val, TestZero);
10196}
10197
10199 SelectionDAG &DAG) const {
10200 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG))
10201 return Expanded;
10202
10203 SDLoc DL(N);
10204 SDValue LHS = N->getOperand(0);
10205 SDValue RHS = N->getOperand(1);
10206 unsigned Opc = N->getOpcode();
10207 EVT VT = N->getValueType(0);
10208 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10209 bool IsMax = Opc == ISD::FMAXIMUM;
10210 SDNodeFlags Flags = N->getFlags();
10211
10212 // First, implement comparison not propagating NaN. If no native fmin or fmax
10213 // available, use plain select with setcc instead.
10215 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
10216 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM;
10217
10218 // FIXME: We should probably define fminnum/fmaxnum variants with correct
10219 // signed zero behavior.
10220 bool MinMaxMustRespectOrderedZero = false;
10221
10222 if (isOperationLegalOrCustom(CompOpcIeee, VT)) {
10223 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags);
10224 MinMaxMustRespectOrderedZero = true;
10225 } else if (isOperationLegalOrCustom(CompOpc, VT)) {
10226 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags);
10227 } else {
10229 return DAG.UnrollVectorOp(N);
10230
10231 // NaN (if exists) will be propagated later, so orderness doesn't matter.
10232 SDValue Compare =
10233 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT);
10234 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags);
10235 }
10236
10237 // Propagate any NaN of both operands
10238 if (!N->getFlags().hasNoNaNs() &&
10239 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) {
10240 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(),
10242 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO),
10243 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags);
10244 }
10245
10246 // fminimum/fmaximum requires -0.0 less than +0.0
10247 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() &&
10248 !DAG.isKnownNeverLogicalZero(RHS) && !DAG.isKnownNeverLogicalZero(LHS)) {
10249 SDValue IsEqual = DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETOEQ);
10251 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10252 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, RHS, Flags);
10253 MinMax = DAG.getSelect(DL, VT, IsEqual, RetZero, MinMax, Flags);
10254 }
10255
10256 return MinMax;
10257}
10258
10260 SelectionDAG &DAG) const {
10261 SDLoc DL(Node);
10262 SDValue LHS = Node->getOperand(0);
10263 SDValue RHS = Node->getOperand(1);
10264 unsigned Opc = Node->getOpcode();
10265 EVT VT = Node->getValueType(0);
10266 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10267 bool IsMax = Opc == ISD::FMAXIMUMNUM;
10268 SDNodeFlags Flags = Node->getFlags();
10269
10270 unsigned NewOp =
10272
10273 if (isOperationLegalOrCustom(NewOp, VT)) {
10274 if (!Flags.hasNoNaNs()) {
10275 // Insert canonicalizes if it's possible we need to quiet to get correct
10276 // sNaN behavior.
10277 if (!DAG.isKnownNeverSNaN(LHS)) {
10278 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags);
10279 }
10280 if (!DAG.isKnownNeverSNaN(RHS)) {
10281 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags);
10282 }
10283 }
10284
10285 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags);
10286 }
10287
10288 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has
10289 // same behaviors for all of other cases: +0.0 vs -0.0 included.
10290 if (Flags.hasNoNaNs() ||
10291 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) {
10292 unsigned IEEE2019Op =
10294 if (isOperationLegalOrCustom(IEEE2019Op, VT))
10295 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags);
10296 }
10297
10298 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return
10299 // either one for +0.0 vs -0.0.
10300 if ((Flags.hasNoNaNs() ||
10301 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) &&
10302 (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10303 DAG.isKnownNeverLogicalZero(RHS))) {
10304 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM;
10305 if (isOperationLegalOrCustom(IEEE2008Op, VT))
10306 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags);
10307 }
10308
10309 if (VT.isVector() &&
10312 return DAG.UnrollVectorOp(Node);
10313
10314 // If only one operand is NaN, override it with another operand.
10315 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) {
10316 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO);
10317 }
10318 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) {
10319 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO);
10320 }
10321
10322 // Always prefer RHS if equal.
10323 SDValue MinMax =
10324 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT);
10325
10326 // TODO: We need quiet sNaN if strictfp.
10327
10328 // Fixup signed zero behavior.
10329 if (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10330 DAG.isKnownNeverLogicalZero(RHS)) {
10331 return MinMax;
10332 }
10333 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax,
10334 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ);
10336 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10337 // It's OK to select from LHS and MinMax, with only one ISD::IS_FPCLASS, as
10338 // we preferred RHS when generate MinMax, if the operands are equal.
10339 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, MinMax, Flags);
10340 return DAG.getSelect(DL, VT, IsZero, RetZero, MinMax, Flags);
10341}
10342
10343/// Returns a true value if if this FPClassTest can be performed with an ordered
10344/// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
10345/// std::nullopt if it cannot be performed as a compare with 0.
10346static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
10347 const fltSemantics &Semantics,
10348 const MachineFunction &MF) {
10349 FPClassTest OrderedMask = Test & ~fcNan;
10350 FPClassTest NanTest = Test & fcNan;
10351 bool IsOrdered = NanTest == fcNone;
10352 bool IsUnordered = NanTest == fcNan;
10353
10354 // Skip cases that are testing for only a qnan or snan.
10355 if (!IsOrdered && !IsUnordered)
10356 return std::nullopt;
10357
10358 if (OrderedMask == fcZero &&
10359 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
10360 return IsOrdered;
10361 if (OrderedMask == (fcZero | fcSubnormal) &&
10362 MF.getDenormalMode(Semantics).inputsAreZero())
10363 return IsOrdered;
10364 return std::nullopt;
10365}
10366
10368 const FPClassTest OrigTestMask,
10369 SDNodeFlags Flags, const SDLoc &DL,
10370 SelectionDAG &DAG) const {
10371 EVT OperandVT = Op.getValueType();
10372 assert(OperandVT.isFloatingPoint());
10373 FPClassTest Test = OrigTestMask;
10374
10375 // Degenerated cases.
10376 if (Test == fcNone)
10377 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
10378 if (Test == fcAllFlags)
10379 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
10380
10381 // PPC double double is a pair of doubles, of which the higher part determines
10382 // the value class.
10383 if (OperandVT == MVT::ppcf128) {
10384 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
10385 DAG.getConstant(1, DL, MVT::i32));
10386 OperandVT = MVT::f64;
10387 }
10388
10389 // Floating-point type properties.
10390 EVT ScalarFloatVT = OperandVT.getScalarType();
10391 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
10392 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
10393 bool IsF80 = (ScalarFloatVT == MVT::f80);
10394
10395 // Some checks can be implemented using float comparisons, if floating point
10396 // exceptions are ignored.
10397 if (Flags.hasNoFPExcept() &&
10399 FPClassTest FPTestMask = Test;
10400 bool IsInvertedFP = false;
10401
10402 if (FPClassTest InvertedFPCheck =
10403 invertFPClassTestIfSimpler(FPTestMask, true)) {
10404 FPTestMask = InvertedFPCheck;
10405 IsInvertedFP = true;
10406 }
10407
10408 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ;
10409 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ;
10410
10411 // See if we can fold an | fcNan into an unordered compare.
10412 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan;
10413
10414 // Can't fold the ordered check if we're only testing for snan or qnan
10415 // individually.
10416 if ((FPTestMask & fcNan) != fcNan)
10417 OrderedFPTestMask = FPTestMask;
10418
10419 const bool IsOrdered = FPTestMask == OrderedFPTestMask;
10420
10421 if (std::optional<bool> IsCmp0 =
10422 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction());
10423 IsCmp0 && (isCondCodeLegalOrCustom(
10424 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
10425 OperandVT.getScalarType().getSimpleVT()))) {
10426
10427 // If denormals could be implicitly treated as 0, this is not equivalent
10428 // to a compare with 0 since it will also be true for denormals.
10429 return DAG.getSetCC(DL, ResultVT, Op,
10430 DAG.getConstantFP(0.0, DL, OperandVT),
10431 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
10432 }
10433
10434 if (FPTestMask == fcNan &&
10436 OperandVT.getScalarType().getSimpleVT()))
10437 return DAG.getSetCC(DL, ResultVT, Op, Op,
10438 IsInvertedFP ? ISD::SETO : ISD::SETUO);
10439
10440 bool IsOrderedInf = FPTestMask == fcInf;
10441 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) &&
10442 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode
10443 : UnorderedCmpOpcode,
10444 OperandVT.getScalarType().getSimpleVT()) &&
10447 (OperandVT.isVector() &&
10449 // isinf(x) --> fabs(x) == inf
10450 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10451 SDValue Inf =
10452 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10453 return DAG.getSetCC(DL, ResultVT, Abs, Inf,
10454 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode);
10455 }
10456
10457 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) &&
10458 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode
10459 : UnorderedCmpOpcode,
10460 OperandVT.getSimpleVT())) {
10461 // isposinf(x) --> x == inf
10462 // isneginf(x) --> x == -inf
10463 // isposinf(x) || nan --> x u== inf
10464 // isneginf(x) || nan --> x u== -inf
10465
10466 SDValue Inf = DAG.getConstantFP(
10467 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL,
10468 OperandVT);
10469 return DAG.getSetCC(DL, ResultVT, Op, Inf,
10470 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode);
10471 }
10472
10473 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) {
10474 // TODO: Could handle ordered case, but it produces worse code for
10475 // x86. Maybe handle ordered if fabs is free?
10476
10477 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10478 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT;
10479
10480 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp,
10481 OperandVT.getScalarType().getSimpleVT())) {
10482 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal
10483
10484 // TODO: Maybe only makes sense if fabs is free. Integer test of
10485 // exponent bits seems better for x86.
10486 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10487 SDValue SmallestNormal = DAG.getConstantFP(
10488 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10489 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal,
10490 IsOrdered ? OrderedOp : UnorderedOp);
10491 }
10492 }
10493
10494 if (FPTestMask == fcNormal) {
10495 // TODO: Handle unordered
10496 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10497 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE;
10498
10499 if (isCondCodeLegalOrCustom(IsFiniteOp,
10500 OperandVT.getScalarType().getSimpleVT()) &&
10501 isCondCodeLegalOrCustom(IsNormalOp,
10502 OperandVT.getScalarType().getSimpleVT()) &&
10503 isFAbsFree(OperandVT)) {
10504 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal)
10505 SDValue Inf =
10506 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10507 SDValue SmallestNormal = DAG.getConstantFP(
10508 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10509
10510 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10511 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp);
10512 SDValue IsNormal =
10513 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp);
10514 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND;
10515 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal);
10516 }
10517 }
10518 }
10519
10520 // Some checks may be represented as inversion of simpler check, for example
10521 // "inf|normal|subnormal|zero" => !"nan".
10522 bool IsInverted = false;
10523
10524 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) {
10525 Test = InvertedCheck;
10526 IsInverted = true;
10527 }
10528
10529 // In the general case use integer operations.
10530 unsigned BitSize = OperandVT.getScalarSizeInBits();
10531 EVT IntVT = OperandVT.changeElementType(
10532 *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), BitSize));
10533 SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
10534
10535 // Various masks.
10536 APInt SignBit = APInt::getSignMask(BitSize);
10537 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign.
10538 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
10539 const unsigned ExplicitIntBitInF80 = 63;
10540 APInt ExpMask = Inf;
10541 if (IsF80)
10542 ExpMask.clearBit(ExplicitIntBitInF80);
10543 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
10544 APInt QNaNBitMask =
10545 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
10546 APInt InversionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
10547
10548 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
10549 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
10550 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
10551 SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
10552 SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
10553 SDValue ResultInversionMask = DAG.getConstant(InversionMask, DL, ResultVT);
10554
10555 SDValue Res;
10556 const auto appendResult = [&](SDValue PartialRes) {
10557 if (PartialRes) {
10558 if (Res)
10559 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
10560 else
10561 Res = PartialRes;
10562 }
10563 };
10564
10565 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
10566 const auto getIntBitIsSet = [&]() -> SDValue {
10567 if (!IntBitIsSetV) {
10568 APInt IntBitMask(BitSize, 0);
10569 IntBitMask.setBit(ExplicitIntBitInF80);
10570 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
10571 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
10572 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
10573 }
10574 return IntBitIsSetV;
10575 };
10576
10577 // Split the value into sign bit and absolute value.
10578 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
10579 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
10580 DAG.getConstant(0, DL, IntVT), ISD::SETLT);
10581
10582 // Tests that involve more than one class should be processed first.
10583 SDValue PartialRes;
10584
10585 if (IsF80)
10586 ; // Detect finite numbers of f80 by checking individual classes because
10587 // they have different settings of the explicit integer bit.
10588 else if ((Test & fcFinite) == fcFinite) {
10589 // finite(V) ==> (a << 1) < (inf << 1)
10590 //
10591 // See https://github.com/llvm/llvm-project/issues/169270, this is slightly
10592 // shorter than the `finite(V) ==> abs(V) < exp_mask` formula used before.
10593
10595 "finite check requires IEEE-like FP");
10596
10597 SDValue One = DAG.getShiftAmountConstant(1, IntVT, DL);
10598 SDValue TwiceOp = DAG.getNode(ISD::SHL, DL, IntVT, OpAsInt, One);
10599 SDValue TwiceInf = DAG.getNode(ISD::SHL, DL, IntVT, ExpMaskV, One);
10600
10601 PartialRes = DAG.getSetCC(DL, ResultVT, TwiceOp, TwiceInf, ISD::SETULT);
10602 Test &= ~fcFinite;
10603 } else if ((Test & fcFinite) == fcPosFinite) {
10604 // finite(V) && V > 0 ==> V < exp_mask
10605 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
10606 Test &= ~fcPosFinite;
10607 } else if ((Test & fcFinite) == fcNegFinite) {
10608 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
10609 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
10610 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10611 Test &= ~fcNegFinite;
10612 }
10613 appendResult(PartialRes);
10614
10615 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
10616 // fcZero | fcSubnormal => test all exponent bits are 0
10617 // TODO: Handle sign bit specific cases
10618 if (PartialCheck == (fcZero | fcSubnormal)) {
10619 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
10620 SDValue ExpIsZero =
10621 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
10622 appendResult(ExpIsZero);
10623 Test &= ~PartialCheck & fcAllFlags;
10624 }
10625 }
10626
10627 // Check for individual classes.
10628
10629 if (unsigned PartialCheck = Test & fcZero) {
10630 if (PartialCheck == fcPosZero)
10631 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
10632 else if (PartialCheck == fcZero)
10633 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
10634 else // ISD::fcNegZero
10635 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
10636 appendResult(PartialRes);
10637 }
10638
10639 if (unsigned PartialCheck = Test & fcSubnormal) {
10640 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
10641 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
10642 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
10643 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
10644 SDValue VMinusOneV =
10645 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
10646 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
10647 if (PartialCheck == fcNegSubnormal)
10648 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10649 appendResult(PartialRes);
10650 }
10651
10652 if (unsigned PartialCheck = Test & fcInf) {
10653 if (PartialCheck == fcPosInf)
10654 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
10655 else if (PartialCheck == fcInf)
10656 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
10657 else { // ISD::fcNegInf
10658 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
10659 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
10660 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
10661 }
10662 appendResult(PartialRes);
10663 }
10664
10665 if (unsigned PartialCheck = Test & fcNan) {
10666 APInt InfWithQnanBit = Inf | QNaNBitMask;
10667 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
10668 if (PartialCheck == fcNan) {
10669 // isnan(V) ==> abs(V) > int(inf)
10670 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
10671 if (IsF80) {
10672 // Recognize unsupported values as NaNs for compatibility with glibc.
10673 // In them (exp(V)==0) == int_bit.
10674 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
10675 SDValue ExpIsZero =
10676 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
10677 SDValue IsPseudo =
10678 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
10679 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
10680 }
10681 } else if (PartialCheck == fcQNan) {
10682 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
10683 PartialRes =
10684 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
10685 } else { // ISD::fcSNan
10686 // issignaling(V) ==> abs(V) > unsigned(Inf) &&
10687 // abs(V) < (unsigned(Inf) | quiet_bit)
10688 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
10689 SDValue IsNotQnan =
10690 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
10691 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
10692 }
10693 appendResult(PartialRes);
10694 }
10695
10696 if (unsigned PartialCheck = Test & fcNormal) {
10697 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
10698 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
10699 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
10700 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
10701 APInt ExpLimit = ExpMask - ExpLSB;
10702 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
10703 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
10704 if (PartialCheck == fcNegNormal)
10705 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
10706 else if (PartialCheck == fcPosNormal) {
10707 SDValue PosSignV =
10708 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInversionMask);
10709 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
10710 }
10711 if (IsF80)
10712 PartialRes =
10713 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
10714 appendResult(PartialRes);
10715 }
10716
10717 if (!Res)
10718 return DAG.getConstant(IsInverted, DL, ResultVT);
10719 if (IsInverted)
10720 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInversionMask);
10721 return Res;
10722}
10723
10724// Only expand vector types if we have the appropriate vector bit operations.
10725static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
10726 assert(VT.isVector() && "Expected vector type");
10727 unsigned Len = VT.getScalarSizeInBits();
10728 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
10731 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
10733}
10734
10736 SDLoc dl(Node);
10737 EVT VT = Node->getValueType(0);
10738 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
10739 SDValue Op = Node->getOperand(0);
10740 unsigned Len = VT.getScalarSizeInBits();
10741 assert(VT.isInteger() && "CTPOP not implemented for this type.");
10742
10743 // TODO: Add support for irregular type lengths.
10744 if (!(Len <= 128 && Len % 8 == 0))
10745 return SDValue();
10746
10747 // Only expand vector types if we have the appropriate vector bit operations.
10748 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
10749 return SDValue();
10750
10751 // This is the "best" algorithm from
10752 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
10753 SDValue Mask55 =
10754 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
10755 SDValue Mask33 =
10756 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
10757 SDValue Mask0F =
10758 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
10759
10760 // v = v - ((v >> 1) & 0x55555555...)
10761 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
10762 DAG.getNode(ISD::AND, dl, VT,
10763 DAG.getNode(ISD::SRL, dl, VT, Op,
10764 DAG.getConstant(1, dl, ShVT)),
10765 Mask55));
10766 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
10767 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
10768 DAG.getNode(ISD::AND, dl, VT,
10769 DAG.getNode(ISD::SRL, dl, VT, Op,
10770 DAG.getConstant(2, dl, ShVT)),
10771 Mask33));
10772 // v = (v + (v >> 4)) & 0x0F0F0F0F...
10773 Op = DAG.getNode(ISD::AND, dl, VT,
10774 DAG.getNode(ISD::ADD, dl, VT, Op,
10775 DAG.getNode(ISD::SRL, dl, VT, Op,
10776 DAG.getConstant(4, dl, ShVT))),
10777 Mask0F);
10778
10779 if (Len <= 8)
10780 return Op;
10781
10782 // Avoid the multiply if we only have 2 bytes to add.
10783 // TODO: Only doing this for scalars because vectors weren't as obviously
10784 // improved.
10785 if (Len == 16 && !VT.isVector()) {
10786 // v = (v + (v >> 8)) & 0x00FF;
10787 return DAG.getNode(ISD::AND, dl, VT,
10788 DAG.getNode(ISD::ADD, dl, VT, Op,
10789 DAG.getNode(ISD::SRL, dl, VT, Op,
10790 DAG.getConstant(8, dl, ShVT))),
10791 DAG.getConstant(0xFF, dl, VT));
10792 }
10793
10794 // v = (v * 0x01010101...) >> (Len - 8)
10795 SDValue V;
10798 SDValue Mask01 =
10799 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
10800 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01);
10801 } else {
10802 V = Op;
10803 for (unsigned Shift = 8; Shift < Len; Shift *= 2) {
10804 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl);
10805 V = DAG.getNode(ISD::ADD, dl, VT, V,
10806 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC));
10807 }
10808 }
10809 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT));
10810}
10811
10813 SDLoc dl(Node);
10814 EVT VT = Node->getValueType(0);
10815 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
10816 SDValue Op = Node->getOperand(0);
10817 SDValue Mask = Node->getOperand(1);
10818 SDValue VL = Node->getOperand(2);
10819 unsigned Len = VT.getScalarSizeInBits();
10820 assert(VT.isInteger() && "VP_CTPOP not implemented for this type.");
10821
10822 // TODO: Add support for irregular type lengths.
10823 if (!(Len <= 128 && Len % 8 == 0))
10824 return SDValue();
10825
10826 // This is same algorithm of expandCTPOP from
10827 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
10828 SDValue Mask55 =
10829 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
10830 SDValue Mask33 =
10831 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
10832 SDValue Mask0F =
10833 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
10834
10835 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5;
10836
10837 // v = v - ((v >> 1) & 0x55555555...)
10838 Tmp1 = DAG.getNode(ISD::VP_AND, dl, VT,
10839 DAG.getNode(ISD::VP_SRL, dl, VT, Op,
10840 DAG.getConstant(1, dl, ShVT), Mask, VL),
10841 Mask55, Mask, VL);
10842 Op = DAG.getNode(ISD::VP_SUB, dl, VT, Op, Tmp1, Mask, VL);
10843
10844 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
10845 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Op, Mask33, Mask, VL);
10846 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT,
10847 DAG.getNode(ISD::VP_SRL, dl, VT, Op,
10848 DAG.getConstant(2, dl, ShVT), Mask, VL),
10849 Mask33, Mask, VL);
10850 Op = DAG.getNode(ISD::VP_ADD, dl, VT, Tmp2, Tmp3, Mask, VL);
10851
10852 // v = (v + (v >> 4)) & 0x0F0F0F0F...
10853 Tmp4 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(4, dl, ShVT),
10854 Mask, VL),
10855 Tmp5 = DAG.getNode(ISD::VP_ADD, dl, VT, Op, Tmp4, Mask, VL);
10856 Op = DAG.getNode(ISD::VP_AND, dl, VT, Tmp5, Mask0F, Mask, VL);
10857
10858 if (Len <= 8)
10859 return Op;
10860
10861 // v = (v * 0x01010101...) >> (Len - 8)
10862 SDValue V;
10864 ISD::VP_MUL, getTypeToTransformTo(*DAG.getContext(), VT))) {
10865 SDValue Mask01 =
10866 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
10867 V = DAG.getNode(ISD::VP_MUL, dl, VT, Op, Mask01, Mask, VL);
10868 } else {
10869 V = Op;
10870 for (unsigned Shift = 8; Shift < Len; Shift *= 2) {
10871 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl);
10872 V = DAG.getNode(ISD::VP_ADD, dl, VT, V,
10873 DAG.getNode(ISD::VP_SHL, dl, VT, V, ShiftC, Mask, VL),
10874 Mask, VL);
10875 }
10876 }
10877 return DAG.getNode(ISD::VP_SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT),
10878 Mask, VL);
10879}
10880
10882 SDLoc dl(Node);
10883 EVT VT = Node->getValueType(0);
10884 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
10885 SDValue Op = Node->getOperand(0);
10886 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
10887
10888 // If the non-ZERO_POISON version is supported we can use that instead.
10889 if (Node->getOpcode() == ISD::CTLZ_ZERO_POISON &&
10891 return DAG.getNode(ISD::CTLZ, dl, VT, Op);
10892
10893 // If the ZERO_POISON version is supported use that and handle the zero case.
10895 EVT SetCCVT =
10896 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10897 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Op);
10898 SDValue Zero = DAG.getConstant(0, dl, VT);
10899 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
10900 return DAG.getSelect(dl, VT, SrcIsZero,
10901 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
10902 }
10903
10904 // Only expand vector types if we have the appropriate vector bit operations.
10905 // This includes the operations needed to expand CTPOP if it isn't supported.
10906 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
10908 !canExpandVectorCTPOP(*this, VT)) ||
10911 return SDValue();
10912
10913 // for now, we do this:
10914 // x = x | (x >> 1);
10915 // x = x | (x >> 2);
10916 // ...
10917 // x = x | (x >>16);
10918 // x = x | (x >>32); // for 64-bit input
10919 // return popcount(~x);
10920 //
10921 // Ref: "Hacker's Delight" by Henry Warren
10922 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
10923 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
10924 Op = DAG.getNode(ISD::OR, dl, VT, Op,
10925 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
10926 }
10927 Op = DAG.getNOT(dl, Op, VT);
10928 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
10929}
10930
10932 SDLoc dl(Node);
10933 EVT VT = Node->getValueType(0);
10934 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
10935 SDValue Op = Node->getOperand(0);
10936 SDValue Mask = Node->getOperand(1);
10937 SDValue VL = Node->getOperand(2);
10938 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
10939
10940 // do this:
10941 // x = x | (x >> 1);
10942 // x = x | (x >> 2);
10943 // ...
10944 // x = x | (x >>16);
10945 // x = x | (x >>32); // for 64-bit input
10946 // return popcount(~x);
10947 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
10948 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
10949 Op = DAG.getNode(ISD::VP_OR, dl, VT, Op,
10950 DAG.getNode(ISD::VP_SRL, dl, VT, Op, Tmp, Mask, VL), Mask,
10951 VL);
10952 }
10953 Op = DAG.getNode(ISD::VP_XOR, dl, VT, Op, DAG.getAllOnesConstant(dl, VT),
10954 Mask, VL);
10955 return DAG.getNode(ISD::VP_CTPOP, dl, VT, Op, Mask, VL);
10956}
10957
10959 SDLoc dl(Node);
10960 EVT VT = Node->getValueType(0);
10961 SDValue Op = DAG.getFreeze(Node->getOperand(0));
10962 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
10963
10964 // CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
10965 // This transforms the sign bits into leading zeros that can be counted.
10966 SDValue ShiftAmt = DAG.getShiftAmountConstant(NumBitsPerElt - 1, VT, dl);
10967 SDValue SignBit = DAG.getNode(ISD::SRA, dl, VT, Op, ShiftAmt);
10968 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, SignBit);
10969 SDValue Shl =
10970 DAG.getNode(ISD::SHL, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
10971 SDValue Or = DAG.getNode(ISD::OR, dl, VT, Shl, DAG.getConstant(1, dl, VT));
10972 return DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Or);
10973}
10974
10976 const SDLoc &DL, EVT VT, SDValue Op,
10977 unsigned BitWidth) const {
10978 if (BitWidth != 32 && BitWidth != 64)
10979 return SDValue();
10980
10981 const DataLayout &TD = DAG.getDataLayout();
10983 return SDValue();
10984
10985 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
10986 : APInt(64, 0x0218A392CD3D5DBFULL);
10987 MachinePointerInfo PtrInfo =
10989 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
10990 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
10991 SDValue Lookup = DAG.getNode(
10992 ISD::SRL, DL, VT,
10993 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
10994 DAG.getConstant(DeBruijn, DL, VT)),
10995 DAG.getShiftAmountConstant(ShiftAmt, VT, DL));
10997
10999 for (unsigned i = 0; i < BitWidth; i++) {
11000 APInt Shl = DeBruijn.shl(i);
11001 APInt Lshr = Shl.lshr(ShiftAmt);
11002 Table[Lshr.getZExtValue()] = i;
11003 }
11004
11005 // Create a ConstantArray in Constant Pool
11006 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
11007 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
11008 TD.getPrefTypeAlign(CA->getType()));
11009 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
11010 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
11011 PtrInfo, MVT::i8);
11012 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
11013 return ExtLoad;
11014
11015 EVT SetCCVT =
11016 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11017 SDValue Zero = DAG.getConstant(0, DL, VT);
11018 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
11019 return DAG.getSelect(DL, VT, SrcIsZero,
11020 DAG.getConstant(BitWidth, DL, VT), ExtLoad);
11021}
11022
11024 SDLoc dl(Node);
11025 EVT VT = Node->getValueType(0);
11026 SDValue Op = Node->getOperand(0);
11027 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11028
11029 // If the non-ZERO_POISON version is supported we can use that instead.
11030 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON &&
11032 return DAG.getNode(ISD::CTTZ, dl, VT, Op);
11033
11034 // If the ZERO_POISON version is supported use that and handle the zero case.
11036 EVT SetCCVT =
11037 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11038 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_POISON, dl, VT, Op);
11039 SDValue Zero = DAG.getConstant(0, dl, VT);
11040 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11041 return DAG.getSelect(dl, VT, SrcIsZero,
11042 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
11043 }
11044
11045 // Only expand vector types if we have the appropriate vector bit operations.
11046 // This includes the operations needed to expand CTPOP if it isn't supported.
11047 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11050 !canExpandVectorCTPOP(*this, VT)) ||
11054 return SDValue();
11055
11056 // Emit Table Lookup if ISD::CTPOP used in the fallback path below is going
11057 // to be expanded or converted to a libcall.
11060 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
11061 return V;
11062
11063 // for now, we use: { return popcount(~x & (x - 1)); }
11064 // unless the target has ctlz but not ctpop, in which case we use:
11065 // { return 32 - nlz(~x & (x-1)); }
11066 // Ref: "Hacker's Delight" by Henry Warren
11067 SDValue Tmp = DAG.getNode(
11068 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
11069 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
11070
11071 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
11073 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
11074 DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
11075 }
11076
11077 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
11078}
11079
11081 SDValue Op = Node->getOperand(0);
11082 SDValue Mask = Node->getOperand(1);
11083 SDValue VL = Node->getOperand(2);
11084 SDLoc dl(Node);
11085 EVT VT = Node->getValueType(0);
11086
11087 // Same as the vector part of expandCTTZ, use: popcount(~x & (x - 1))
11088 SDValue Not = DAG.getNode(ISD::VP_XOR, dl, VT, Op,
11089 DAG.getAllOnesConstant(dl, VT), Mask, VL);
11090 SDValue MinusOne = DAG.getNode(ISD::VP_SUB, dl, VT, Op,
11091 DAG.getConstant(1, dl, VT), Mask, VL);
11092 SDValue Tmp = DAG.getNode(ISD::VP_AND, dl, VT, Not, MinusOne, Mask, VL);
11093 return DAG.getNode(ISD::VP_CTPOP, dl, VT, Tmp, Mask, VL);
11094}
11095
11097 SelectionDAG &DAG) const {
11098 // %cond = to_bool_vec %source
11099 // %splat = splat /*val=*/VL
11100 // %tz = step_vector
11101 // %v = vp.select %cond, /*true=*/tz, /*false=*/%splat
11102 // %r = vp.reduce.umin %v
11103 SDLoc DL(N);
11104 SDValue Source = N->getOperand(0);
11105 SDValue Mask = N->getOperand(1);
11106 SDValue EVL = N->getOperand(2);
11107 EVT SrcVT = Source.getValueType();
11108 EVT ResVT = N->getValueType(0);
11109 EVT ResVecVT =
11110 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount());
11111
11112 // Convert to boolean vector.
11113 if (SrcVT.getScalarType() != MVT::i1) {
11114 SDValue AllZero = DAG.getConstant(0, DL, SrcVT);
11115 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
11116 SrcVT.getVectorElementCount());
11117 Source = DAG.getNode(ISD::VP_SETCC, DL, SrcVT, Source, AllZero,
11118 DAG.getCondCode(ISD::SETNE), Mask, EVL);
11119 }
11120
11121 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT);
11122 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL);
11123 SDValue StepVec = DAG.getStepVector(DL, ResVecVT);
11124 SDValue Select =
11125 DAG.getNode(ISD::VP_SELECT, DL, ResVecVT, Source, StepVec, Splat, EVL);
11126 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL);
11127}
11128
11129/// Returns a type-legalized version of \p Mask as the first item in the
11130/// pair. The second item contains a type-legalized step vector that's
11131/// guaranteed to fit the number of elements in \p Mask.
11132/// If the stepvector would require splitting, returns an empty SDValue
11133/// as the second item to signal that the operation should be split instead.
11134static std::pair<SDValue, SDValue>
11136 SelectionDAG &DAG) {
11137 EVT MaskVT = Mask.getValueType();
11138 EVT BoolVT = MaskVT.getScalarType();
11139
11140 // Find a suitable type for a stepvector.
11141 // If zero is poison, we can assume the upper limit of the result is VF-1.
11142 ConstantRange VScaleRange(1, /*isFullSet=*/true); // Fixed length default.
11143 if (MaskVT.isScalableVector())
11144 VScaleRange = getVScaleRange(&DAG.getMachineFunction().getFunction(), 64);
11145 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11146 uint64_t EltWidth = TLI.getBitWidthForCttzElements(
11147 EVT(TLI.getVectorIdxTy(DAG.getDataLayout())),
11148 MaskVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
11149 // If the step vector element type is smaller than the mask element type,
11150 // use the mask type directly to avoid widening issues.
11151 EltWidth = std::max(EltWidth, BoolVT.getFixedSizeInBits());
11152 EVT StepVT = MVT::getIntegerVT(EltWidth);
11153 EVT StepVecVT = MaskVT.changeVectorElementType(*DAG.getContext(), StepVT);
11154
11155 // If promotion or widening is required to make the type legal, do it here.
11156 // Promotion of integers within LegalizeVectorOps is looking for types of
11157 // the same size but with a smaller number of larger elements, not the usual
11158 // larger size with the same number of larger elements.
11160 TLI.getTypeAction(*DAG.getContext(), StepVecVT);
11161 SDValue StepVec;
11162 if (TypeAction == TargetLowering::TypePromoteInteger) {
11163 StepVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11164 StepVec = DAG.getStepVector(DL, StepVecVT);
11165 } else if (TypeAction == TargetLowering::TypeWidenVector) {
11166 // For widening, the element count changes. Create a step vector with only
11167 // the original elements valid and zeros for padding. Also widen the mask.
11168 EVT WideVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11169 unsigned WideNumElts = WideVecVT.getVectorNumElements();
11170
11171 // Build widened step vector: <0, 1, ..., OrigNumElts-1, poison, poison, ..>
11172 SDValue OrigStepVec = DAG.getStepVector(DL, StepVecVT);
11173 SDValue UndefStep = DAG.getPOISON(WideVecVT);
11174 StepVec = DAG.getInsertSubvector(DL, UndefStep, OrigStepVec, 0);
11175
11176 // Widen mask: pad with zeros.
11177 EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(), BoolVT, WideNumElts);
11178 SDValue ZeroMask = DAG.getConstant(0, DL, WideMaskVT);
11179 Mask = DAG.getInsertSubvector(DL, ZeroMask, Mask, 0);
11180 } else if (TypeAction == TargetLowering::TypeSplitVector) {
11181 // The stepvector type would require splitting. Signal to the caller
11182 // that the operation should be split instead of expanded.
11183 return {Mask, SDValue()};
11184 } else {
11185 StepVec = DAG.getStepVector(DL, StepVecVT);
11186 }
11187
11188 return {Mask, StepVec};
11189}
11190
11192 SelectionDAG &DAG) const {
11193 SDLoc DL(N);
11194 auto [Mask, StepVec] = getLegalMaskAndStepVector(
11195 N->getOperand(0), /*ZeroIsPoison=*/true, DL, DAG);
11196
11197 // If StepVec is empty, the stepvector would require splitting.
11198 // Split the operation instead and let it be recursively legalized.
11199 if (!StepVec) {
11200 EVT MaskVT = N->getOperand(0).getValueType();
11201 EVT ResVT = N->getValueType(0);
11202
11203 // Split the mask
11204 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(MaskVT);
11205 auto [MaskLo, MaskHi] = DAG.SplitVector(N->getOperand(0), DL);
11206
11207 // Create split VECTOR_FIND_LAST_ACTIVE operations
11208 SDValue LoResult =
11209 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskLo);
11210 SDValue HiResult =
11211 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskHi);
11212
11213 // Check if any lane is active in the high mask.
11214 SDValue AnyHiActive = DAG.getNode(ISD::VECREDUCE_OR, DL, MVT::i1, MaskHi);
11216 AnyHiActive, DL,
11217 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i1),
11218 MVT::i1);
11219
11220 // Adjust HiResult by adding the number of elements in Lo
11221 SDValue LoNumElts =
11222 DAG.getElementCount(DL, ResVT, LoVT.getVectorElementCount());
11223 SDValue AdjustedHiResult =
11224 DAG.getNode(ISD::ADD, DL, ResVT, HiResult, LoNumElts);
11225
11226 // Return: AnyHiActive ? AdjustedHiResult : LoResult;
11227 return DAG.getNode(ISD::SELECT, DL, ResVT, Cond, AdjustedHiResult,
11228 LoResult);
11229 }
11230
11231 EVT StepVecVT = StepVec.getValueType();
11232 EVT StepVT = StepVec.getValueType().getVectorElementType();
11233
11234 // Zero out lanes with inactive elements, then find the highest remaining
11235 // value from the stepvector.
11236 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
11237 SDValue ActiveElts = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
11238 SDValue HighestIdx = DAG.getNode(ISD::VECREDUCE_UMAX, DL, StepVT, ActiveElts);
11239 return DAG.getZExtOrTrunc(HighestIdx, DL, N->getValueType(0));
11240}
11241
11243 SelectionDAG &DAG) const {
11244 SDLoc DL(N);
11245 EVT VT = N->getValueType(0);
11246 SDValue SourceValue = N->getOperand(0);
11247 SDValue SinkValue = N->getOperand(1);
11248 SDValue EltSizeInBytes = N->getOperand(2);
11249
11250 // Note: The lane offset is scalable if the mask is scalable.
11251 ElementCount LaneOffsetEC =
11252 ElementCount::get(N->getConstantOperandVal(3), VT.isScalableVT());
11253
11254 EVT AddrVT = SourceValue->getValueType(0);
11255 bool IsReadAfterWrite = N->getOpcode() == ISD::LOOP_DEPENDENCE_RAW_MASK;
11256
11257 // Take the difference between the pointers and divided by the element size,
11258 // to see how many lanes separate them.
11259 SDValue Diff = DAG.getNode(ISD::SUB, DL, AddrVT, SinkValue, SourceValue);
11260 if (IsReadAfterWrite)
11261 Diff = DAG.getNode(ISD::ABS, DL, AddrVT, Diff);
11262 Diff = DAG.getNode(ISD::SDIV, DL, AddrVT, Diff, EltSizeInBytes);
11263
11264 // The pointers do not alias if:
11265 // * Diff <= 0 (WAR_MASK)
11266 // * Diff == 0 (RAW_MASK)
11267 EVT CmpVT =
11268 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), AddrVT);
11269 SDValue Zero = DAG.getConstant(0, DL, AddrVT);
11270 SDValue Cmp = DAG.getSetCC(DL, CmpVT, Diff, Zero,
11271 IsReadAfterWrite ? ISD::SETEQ : ISD::SETLE);
11272
11273 // The pointers do not alias if:
11274 // Lane + LaneOffset < Diff (WAR/RAW_MASK)
11275 SDValue LaneOffset = DAG.getElementCount(DL, AddrVT, LaneOffsetEC);
11276 SDValue MaskN = DAG.getSelect(
11277 DL, AddrVT, Cmp,
11279 AddrVT),
11280 Diff);
11281
11282 return DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, VT, LaneOffset, MaskN);
11283}
11284
11286 bool IsNegative) const {
11287 SDLoc dl(N);
11288 EVT VT = N->getValueType(0);
11289 SDValue Op = N->getOperand(0);
11290
11291 // If expanding ABS_MIN_POISON, fall back to ABS if the target supports it.
11292 if (N->getOpcode() == ISD::ABS_MIN_POISON &&
11294 SDValue AbsVal = DAG.getNode(ISD::ABS, dl, VT, Op);
11295 if (IsNegative)
11296 return DAG.getNegative(AbsVal, dl, VT);
11297 return AbsVal;
11298 }
11299
11300 // abs(x) -> smax(x,sub(0,x))
11301 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11303 SDValue Zero = DAG.getConstant(0, dl, VT);
11304 Op = DAG.getFreeze(Op);
11305 return DAG.getNode(ISD::SMAX, dl, VT, Op,
11306 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11307 }
11308
11309 // abs(x) -> umin(x,sub(0,x))
11310 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11312 SDValue Zero = DAG.getConstant(0, dl, VT);
11313 Op = DAG.getFreeze(Op);
11314 return DAG.getNode(ISD::UMIN, dl, VT, Op,
11315 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11316 }
11317
11318 // 0 - abs(x) -> smin(x, sub(0,x))
11319 if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
11321 SDValue Zero = DAG.getConstant(0, dl, VT);
11322 Op = DAG.getFreeze(Op);
11323 return DAG.getNode(ISD::SMIN, dl, VT, Op,
11324 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11325 }
11326
11327 // Only expand vector types if we have the appropriate vector operations.
11328 if (VT.isVector() &&
11330 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
11331 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
11333 return SDValue();
11334
11335 Op = DAG.getFreeze(Op);
11336 SDValue Shift = DAG.getNode(
11337 ISD::SRA, dl, VT, Op,
11338 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11339 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
11340
11341 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
11342 if (!IsNegative)
11343 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
11344
11345 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
11346 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
11347}
11348
11350 SDLoc dl(N);
11351 EVT VT = N->getValueType(0);
11352 SDValue LHS = N->getOperand(0);
11353 SDValue RHS = N->getOperand(1);
11354 bool IsSigned = N->getOpcode() == ISD::ABDS;
11355
11356 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
11357 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
11358 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
11359 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
11360 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
11361 LHS = DAG.getFreeze(LHS);
11362 RHS = DAG.getFreeze(RHS);
11363 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
11364 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
11365 return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
11366 }
11367
11368 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
11369 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) {
11370 LHS = DAG.getFreeze(LHS);
11371 RHS = DAG.getFreeze(RHS);
11372 return DAG.getNode(ISD::OR, dl, VT,
11373 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
11374 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
11375 }
11376
11377 // If the subtract doesn't overflow then just use abs(sub())
11378 bool IsNonNegative = DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS);
11379
11380 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, LHS, RHS))
11381 return DAG.getNode(ISD::ABS, dl, VT,
11382 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11383
11384 if (DAG.willNotOverflowSub(IsSigned || IsNonNegative, RHS, LHS))
11385 return DAG.getNode(ISD::ABS, dl, VT,
11386 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11387
11388 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11390 LHS = DAG.getFreeze(LHS);
11391 RHS = DAG.getFreeze(RHS);
11392 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
11393
11394 // Branchless expansion iff cmp result is allbits:
11395 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs)))
11396 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs)))
11397 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
11398 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11399 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp);
11400 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor);
11401 }
11402
11403 // Similar to the branchless expansion, if we don't prefer selects, use the
11404 // (sign-extended) usubo overflow flag if the (scalar) type is illegal as this
11405 // is more likely to legalize cleanly: abdu(lhs, rhs) -> sub(xor(sub(lhs,
11406 // rhs), uof(lhs, rhs)), uof(lhs, rhs))
11407 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT) &&
11409 SDValue USubO =
11410 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS});
11411 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1));
11412 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp);
11413 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp);
11414 }
11415
11416 // FIXME: Should really try to split the vector in case it's legal on a
11417 // subvector.
11419 return DAG.UnrollVectorOp(N);
11420
11421 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11422 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11423 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
11424 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11425}
11426
11428 SDLoc dl(N);
11429 EVT VT = N->getValueType(0);
11430 SDValue LHS = N->getOperand(0);
11431 SDValue RHS = N->getOperand(1);
11432
11433 unsigned Opc = N->getOpcode();
11434 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU;
11435 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS;
11436 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB;
11437 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR;
11438 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
11439 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
11441 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) &&
11442 "Unknown AVG node");
11443
11444 // If the operands are already extended, we can add+shift.
11445 bool IsExt =
11446 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 &&
11447 DAG.ComputeNumSignBits(RHS) >= 2) ||
11448 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 &&
11449 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1);
11450 if (IsExt) {
11451 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
11452 if (!IsFloor)
11453 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT));
11454 return DAG.getNode(ShiftOpc, dl, VT, Sum,
11455 DAG.getShiftAmountConstant(1, VT, dl));
11456 }
11457
11458 // For scalars, see if we can efficiently extend/truncate to use add+shift.
11459 if (VT.isScalarInteger()) {
11460 EVT ExtVT = VT.widenIntegerElementType(*DAG.getContext());
11461 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) {
11462 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS);
11463 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS);
11464 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS);
11465 if (!IsFloor)
11466 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg,
11467 DAG.getConstant(1, dl, ExtVT));
11468 // Just use SRL as we will be truncating away the extended sign bits.
11469 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg,
11470 DAG.getShiftAmountConstant(1, ExtVT, dl));
11471 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg);
11472 }
11473 }
11474
11475 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1))
11476 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT) &&
11479 SDValue UAddWithOverflow =
11480 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS});
11481
11482 SDValue Sum = UAddWithOverflow.getValue(0);
11483 SDValue Overflow = UAddWithOverflow.getValue(1);
11484
11485 // Right shift the sum by 1
11486 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum,
11487 DAG.getShiftAmountConstant(1, VT, dl));
11488
11489 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow);
11490 SDValue OverflowShl = DAG.getNode(
11491 ISD::SHL, dl, VT, ZeroExtOverflow,
11492 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11493
11494 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl);
11495 }
11496
11497 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1))
11498 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1))
11499 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1))
11500 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1))
11501 LHS = DAG.getFreeze(LHS);
11502 RHS = DAG.getFreeze(RHS);
11503 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS);
11504 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
11505 SDValue Shift =
11506 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11507 return DAG.getNode(SumOpc, dl, VT, Sign, Shift);
11508}
11509
11511 SDLoc dl(N);
11512 EVT VT = N->getValueType(0);
11513 SDValue Op = N->getOperand(0);
11514
11515 if (!VT.isSimple())
11516 return SDValue();
11517
11518 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11519 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
11520 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
11521 default:
11522 return SDValue();
11523 case MVT::i16:
11524 // Use a rotate by 8. This can be further expanded if necessary.
11525 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11526 case MVT::i32:
11527 // This is meant for ARM specifically, which has ROTR but no ROTL.
11528 // t = x ^ rotr(x, 16)
11529 // t = bic(t, 0x00ff0000)
11530 // t = lshr(t, 8)
11531 // x = t ^ rotr(x, 8)
11533 SDValue Rotr16 =
11534 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(16, dl, SHVT));
11535 SDValue Tmp = DAG.getNode(ISD::XOR, dl, VT, Op, Rotr16);
11536 Tmp = DAG.getNode(ISD::AND, dl, VT, Tmp,
11537 DAG.getConstant(0xFF00FFFF, dl, VT));
11538 Tmp = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(8, dl, SHVT));
11539 SDValue Rotr8 =
11540 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11541 return DAG.getNode(ISD::XOR, dl, VT, Tmp, Rotr8);
11542 }
11543 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11544 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
11545 DAG.getConstant(0xFF00, dl, VT));
11546 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
11547 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11548 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
11549 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11550 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11551 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11552 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11553 case MVT::i64:
11554 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11555 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
11556 DAG.getConstant(255ULL<<8, dl, VT));
11557 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
11558 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
11559 DAG.getConstant(255ULL<<16, dl, VT));
11560 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
11561 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
11562 DAG.getConstant(255ULL<<24, dl, VT));
11563 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
11564 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11565 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
11566 DAG.getConstant(255ULL<<24, dl, VT));
11567 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
11568 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
11569 DAG.getConstant(255ULL<<16, dl, VT));
11570 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
11571 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
11572 DAG.getConstant(255ULL<<8, dl, VT));
11573 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
11574 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
11575 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
11576 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
11577 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
11578 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
11579 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
11580 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
11581 }
11582}
11583
11585 SDLoc dl(N);
11586 EVT VT = N->getValueType(0);
11587 SDValue Op = N->getOperand(0);
11588 SDValue Mask = N->getOperand(1);
11589 SDValue EVL = N->getOperand(2);
11590
11591 if (!VT.isSimple())
11592 return SDValue();
11593
11594 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11595 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
11596 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
11597 default:
11598 return SDValue();
11599 case MVT::i16:
11600 Tmp1 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT),
11601 Mask, EVL);
11602 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT),
11603 Mask, EVL);
11604 return DAG.getNode(ISD::VP_OR, dl, VT, Tmp1, Tmp2, Mask, EVL);
11605 case MVT::i32:
11606 Tmp4 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT),
11607 Mask, EVL);
11608 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Op, DAG.getConstant(0xFF00, dl, VT),
11609 Mask, EVL);
11610 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT),
11611 Mask, EVL);
11612 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT),
11613 Mask, EVL);
11614 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
11615 DAG.getConstant(0xFF00, dl, VT), Mask, EVL);
11616 Tmp1 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT),
11617 Mask, EVL);
11618 Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp3, Mask, EVL);
11619 Tmp2 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp1, Mask, EVL);
11620 return DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp2, Mask, EVL);
11621 case MVT::i64:
11622 Tmp8 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT),
11623 Mask, EVL);
11624 Tmp7 = DAG.getNode(ISD::VP_AND, dl, VT, Op,
11625 DAG.getConstant(255ULL << 8, dl, VT), Mask, EVL);
11626 Tmp7 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT),
11627 Mask, EVL);
11628 Tmp6 = DAG.getNode(ISD::VP_AND, dl, VT, Op,
11629 DAG.getConstant(255ULL << 16, dl, VT), Mask, EVL);
11630 Tmp6 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT),
11631 Mask, EVL);
11632 Tmp5 = DAG.getNode(ISD::VP_AND, dl, VT, Op,
11633 DAG.getConstant(255ULL << 24, dl, VT), Mask, EVL);
11634 Tmp5 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT),
11635 Mask, EVL);
11636 Tmp4 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT),
11637 Mask, EVL);
11638 Tmp4 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp4,
11639 DAG.getConstant(255ULL << 24, dl, VT), Mask, EVL);
11640 Tmp3 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT),
11641 Mask, EVL);
11642 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp3,
11643 DAG.getConstant(255ULL << 16, dl, VT), Mask, EVL);
11644 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT),
11645 Mask, EVL);
11646 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
11647 DAG.getConstant(255ULL << 8, dl, VT), Mask, EVL);
11648 Tmp1 = DAG.getNode(ISD::VP_SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT),
11649 Mask, EVL);
11650 Tmp8 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp7, Mask, EVL);
11651 Tmp6 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp6, Tmp5, Mask, EVL);
11652 Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp3, Mask, EVL);
11653 Tmp2 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp1, Mask, EVL);
11654 Tmp8 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp6, Mask, EVL);
11655 Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp2, Mask, EVL);
11656 return DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp4, Mask, EVL);
11657 }
11658}
11659
11661 SDLoc dl(N);
11662 EVT VT = N->getValueType(0);
11663 SDValue Op = N->getOperand(0);
11664 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11665 unsigned Sz = VT.getScalarSizeInBits();
11666
11667 SDValue Tmp, Tmp2, Tmp3;
11668
11669 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
11670 // and finally the i1 pairs.
11671 // TODO: We can easily support i4/i2 legal types if any target ever does.
11672 if (Sz >= 8 && isPowerOf2_32(Sz)) {
11673 // Create the masks - repeating the pattern every byte.
11674 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
11675 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
11676 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
11677
11678 // BSWAP if the type is wider than a single byte.
11679 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
11680
11681 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
11682 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
11683 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
11684 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
11685 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
11686 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11687
11688 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
11689 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
11690 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
11691 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
11692 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
11693 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11694
11695 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
11696 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
11697 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
11698 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
11699 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
11700 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
11701 return Tmp;
11702 }
11703
11704 Tmp = DAG.getConstant(0, dl, VT);
11705 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
11706 if (I < J)
11707 Tmp2 =
11708 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
11709 else
11710 Tmp2 =
11711 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
11712
11713 APInt Shift = APInt::getOneBitSet(Sz, J);
11714 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
11715 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
11716 }
11717
11718 return Tmp;
11719}
11720
11722 assert(N->getOpcode() == ISD::VP_BITREVERSE);
11723
11724 SDLoc dl(N);
11725 EVT VT = N->getValueType(0);
11726 SDValue Op = N->getOperand(0);
11727 SDValue Mask = N->getOperand(1);
11728 SDValue EVL = N->getOperand(2);
11729 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11730 unsigned Sz = VT.getScalarSizeInBits();
11731
11732 SDValue Tmp, Tmp2, Tmp3;
11733
11734 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
11735 // and finally the i1 pairs.
11736 // TODO: We can easily support i4/i2 legal types if any target ever does.
11737 if (Sz >= 8 && isPowerOf2_32(Sz)) {
11738 // Create the masks - repeating the pattern every byte.
11739 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
11740 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
11741 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
11742
11743 // BSWAP if the type is wider than a single byte.
11744 Tmp = (Sz > 8 ? DAG.getNode(ISD::VP_BSWAP, dl, VT, Op, Mask, EVL) : Op);
11745
11746 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
11747 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT),
11748 Mask, EVL);
11749 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
11750 DAG.getConstant(Mask4, dl, VT), Mask, EVL);
11751 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT),
11752 Mask, EVL);
11753 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT),
11754 Mask, EVL);
11755 Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL);
11756
11757 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
11758 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT),
11759 Mask, EVL);
11760 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
11761 DAG.getConstant(Mask2, dl, VT), Mask, EVL);
11762 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT),
11763 Mask, EVL);
11764 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT),
11765 Mask, EVL);
11766 Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL);
11767
11768 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
11769 Tmp2 = DAG.getNode(ISD::VP_SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT),
11770 Mask, EVL);
11771 Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
11772 DAG.getConstant(Mask1, dl, VT), Mask, EVL);
11773 Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT),
11774 Mask, EVL);
11775 Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT),
11776 Mask, EVL);
11777 Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL);
11778 return Tmp;
11779 }
11780 return SDValue();
11781}
11782
11783std::pair<SDValue, SDValue>
11785 SelectionDAG &DAG) const {
11786 SDLoc SL(LD);
11787 SDValue Chain = LD->getChain();
11788 SDValue BasePTR = LD->getBasePtr();
11789 EVT SrcVT = LD->getMemoryVT();
11790 EVT DstVT = LD->getValueType(0);
11791 ISD::LoadExtType ExtType = LD->getExtensionType();
11792
11793 if (SrcVT.isScalableVector())
11794 report_fatal_error("Cannot scalarize scalable vector loads");
11795
11796 unsigned NumElem = SrcVT.getVectorNumElements();
11797
11798 EVT SrcEltVT = SrcVT.getScalarType();
11799 EVT DstEltVT = DstVT.getScalarType();
11800
11801 // A vector must always be stored in memory as-is, i.e. without any padding
11802 // between the elements, since various code depend on it, e.g. in the
11803 // handling of a bitcast of a vector type to int, which may be done with a
11804 // vector store followed by an integer load. A vector that does not have
11805 // elements that are byte-sized must therefore be stored as an integer
11806 // built out of the extracted vector elements.
11807 if (!SrcEltVT.isByteSized()) {
11808 unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
11809 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
11810
11811 unsigned NumSrcBits = SrcVT.getSizeInBits();
11812 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
11813
11814 unsigned SrcEltBits = SrcEltVT.getSizeInBits();
11815 SDValue SrcEltBitMask = DAG.getConstant(
11816 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
11817
11818 // Load the whole vector and avoid masking off the top bits as it makes
11819 // the codegen worse.
11820 SDValue Load =
11821 DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
11822 LD->getPointerInfo(), SrcIntVT, LD->getBaseAlign(),
11823 LD->getMemOperand()->getFlags(), LD->getAAInfo());
11824
11826 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11827 unsigned ShiftIntoIdx =
11828 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
11829 SDValue ShiftAmount = DAG.getShiftAmountConstant(
11830 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL);
11831 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
11832 SDValue Elt =
11833 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
11834 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
11835
11836 if (ExtType != ISD::NON_EXTLOAD) {
11837 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
11838 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
11839 }
11840
11841 Vals.push_back(Scalar);
11842 }
11843
11844 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
11845 return std::make_pair(Value, Load.getValue(1));
11846 }
11847
11848 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
11849 assert(SrcEltVT.isByteSized());
11850
11852 SmallVector<SDValue, 8> LoadChains;
11853
11854 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11855 SDValue ScalarLoad = DAG.getExtLoad(
11856 ExtType, SL, DstEltVT, Chain, BasePTR,
11857 LD->getPointerInfo().getWithOffset(Idx * Stride), SrcEltVT,
11858 LD->getBaseAlign(), LD->getMemOperand()->getFlags(), LD->getAAInfo());
11859
11860 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
11861
11862 Vals.push_back(ScalarLoad.getValue(0));
11863 LoadChains.push_back(ScalarLoad.getValue(1));
11864 }
11865
11866 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
11867 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
11868
11869 return std::make_pair(Value, NewChain);
11870}
11871
11873 SelectionDAG &DAG) const {
11874 SDLoc SL(ST);
11875
11876 SDValue Chain = ST->getChain();
11877 SDValue BasePtr = ST->getBasePtr();
11878 SDValue Value = ST->getValue();
11879 EVT StVT = ST->getMemoryVT();
11880
11881 if (StVT.isScalableVector())
11882 report_fatal_error("Cannot scalarize scalable vector stores");
11883
11884 // The type of the data we want to save
11885 EVT RegVT = Value.getValueType();
11886 EVT RegSclVT = RegVT.getScalarType();
11887
11888 // The type of data as saved in memory.
11889 EVT MemSclVT = StVT.getScalarType();
11890
11891 unsigned NumElem = StVT.getVectorNumElements();
11892
11893 // A vector must always be stored in memory as-is, i.e. without any padding
11894 // between the elements, since various code depend on it, e.g. in the
11895 // handling of a bitcast of a vector type to int, which may be done with a
11896 // vector store followed by an integer load. A vector that does not have
11897 // elements that are byte-sized must therefore be stored as an integer
11898 // built out of the extracted vector elements.
11899 if (!MemSclVT.isByteSized()) {
11900 unsigned NumBits = StVT.getSizeInBits();
11901 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
11902
11903 SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
11904
11905 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11906 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
11907 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
11908 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
11909 unsigned ShiftIntoIdx =
11910 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
11911 SDValue ShiftAmount =
11912 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
11913 SDValue ShiftedElt =
11914 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
11915 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
11916 }
11917
11918 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
11919 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
11920 ST->getAAInfo());
11921 }
11922
11923 // Store Stride in bytes
11924 unsigned Stride = MemSclVT.getSizeInBits() / 8;
11925 assert(Stride && "Zero stride!");
11926 // Extract each of the elements from the original vector and save them into
11927 // memory individually.
11929 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
11930 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
11931
11932 SDValue Ptr =
11933 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
11934
11935 // This scalar TruncStore may be illegal, but we legalize it later.
11936 SDValue Store = DAG.getTruncStore(
11937 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
11938 MemSclVT, ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
11939 ST->getAAInfo());
11940
11941 Stores.push_back(Store);
11942 }
11943
11944 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
11945}
11946
11947std::pair<SDValue, SDValue>
11949 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
11950 "unaligned indexed loads not implemented!");
11951 SDValue Chain = LD->getChain();
11952 SDValue Ptr = LD->getBasePtr();
11953 EVT VT = LD->getValueType(0);
11954 EVT LoadedVT = LD->getMemoryVT();
11955 SDLoc dl(LD);
11956 auto &MF = DAG.getMachineFunction();
11957
11958 if (VT.isFloatingPoint() || VT.isVector()) {
11959 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
11960 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
11961 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
11962 LoadedVT.isVector()) {
11963 // Scalarize the load and let the individual components be handled.
11964 return scalarizeVectorLoad(LD, DAG);
11965 }
11966
11967 // Expand to a (misaligned) integer load of the same size,
11968 // then bitconvert to floating point or vector.
11969 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
11970 LD->getMemOperand());
11971 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
11972 if (LoadedVT != VT)
11973 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
11974 ISD::ANY_EXTEND, dl, VT, Result);
11975
11976 return std::make_pair(Result, newLoad.getValue(1));
11977 }
11978
11979 // Copy the value to a (aligned) stack slot using (unaligned) integer
11980 // loads and stores, then do a (aligned) load from the stack slot.
11981 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
11982 unsigned LoadedBytes = LoadedVT.getStoreSize();
11983 unsigned RegBytes = RegVT.getSizeInBits() / 8;
11984 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
11985
11986 // Make sure the stack slot is also aligned for the register type.
11987 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
11988 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
11990 SDValue StackPtr = StackBase;
11991 unsigned Offset = 0;
11992
11993 EVT PtrVT = Ptr.getValueType();
11994 EVT StackPtrVT = StackPtr.getValueType();
11995
11996 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
11997 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
11998
11999 // Do all but one copies using the full register width.
12000 for (unsigned i = 1; i < NumRegs; i++) {
12001 // Load one integer register's worth from the original location.
12002 SDValue Load = DAG.getLoad(
12003 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
12004 LD->getBaseAlign(), LD->getMemOperand()->getFlags(), LD->getAAInfo());
12005 // Follow the load with a store to the stack slot. Remember the store.
12006 Stores.push_back(DAG.getStore(
12007 Load.getValue(1), dl, Load, StackPtr,
12008 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
12009 // Increment the pointers.
12010 Offset += RegBytes;
12011
12012 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12013 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12014 }
12015
12016 // The last copy may be partial. Do an extending load.
12017 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
12018 8 * (LoadedBytes - Offset));
12019 SDValue Load = DAG.getExtLoad(
12020 ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
12021 LD->getPointerInfo().getWithOffset(Offset), MemVT, LD->getBaseAlign(),
12022 LD->getMemOperand()->getFlags(), LD->getAAInfo());
12023 // Follow the load with a store to the stack slot. Remember the store.
12024 // On big-endian machines this requires a truncating store to ensure
12025 // that the bits end up in the right place.
12026 Stores.push_back(DAG.getTruncStore(
12027 Load.getValue(1), dl, Load, StackPtr,
12028 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
12029
12030 // The order of the stores doesn't matter - say it with a TokenFactor.
12031 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12032
12033 // Finally, perform the original load only redirected to the stack slot.
12034 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
12035 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
12036 LoadedVT);
12037
12038 // Callers expect a MERGE_VALUES node.
12039 return std::make_pair(Load, TF);
12040 }
12041
12042 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
12043 "Unaligned load of unsupported type.");
12044
12045 // Compute the new VT that is half the size of the old one. This is an
12046 // integer MVT.
12047 unsigned NumBits = LoadedVT.getSizeInBits();
12048 EVT NewLoadedVT;
12049 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
12050 NumBits >>= 1;
12051
12052 Align Alignment = LD->getBaseAlign();
12053 unsigned IncrementSize = NumBits / 8;
12054 ISD::LoadExtType HiExtType = LD->getExtensionType();
12055
12056 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
12057 if (HiExtType == ISD::NON_EXTLOAD)
12058 HiExtType = ISD::ZEXTLOAD;
12059
12060 // Load the value in two parts
12061 SDValue Lo, Hi;
12062 if (DAG.getDataLayout().isLittleEndian()) {
12063 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12064 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12065 LD->getAAInfo());
12066
12067 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12068 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
12069 LD->getPointerInfo().getWithOffset(IncrementSize),
12070 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12071 LD->getAAInfo());
12072 } else {
12073 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12074 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12075 LD->getAAInfo());
12076
12077 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12078 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
12079 LD->getPointerInfo().getWithOffset(IncrementSize),
12080 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12081 LD->getAAInfo());
12082 }
12083
12084 // aggregate the two parts
12085 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl);
12086 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
12087 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
12088
12089 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
12090 Hi.getValue(1));
12091
12092 return std::make_pair(Result, TF);
12093}
12094
12096 SelectionDAG &DAG) const {
12097 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
12098 "unaligned indexed stores not implemented!");
12099 SDValue Chain = ST->getChain();
12100 SDValue Ptr = ST->getBasePtr();
12101 SDValue Val = ST->getValue();
12102 EVT VT = Val.getValueType();
12103 Align Alignment = ST->getBaseAlign();
12104 auto &MF = DAG.getMachineFunction();
12105 EVT StoreMemVT = ST->getMemoryVT();
12106
12107 SDLoc dl(ST);
12108 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
12109 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12110 if (isTypeLegal(intVT)) {
12111 if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
12112 StoreMemVT.isVector()) {
12113 // Scalarize the store and let the individual components be handled.
12114 SDValue Result = scalarizeVectorStore(ST, DAG);
12115 return Result;
12116 }
12117 // Expand to a bitconvert of the value to the integer type of the
12118 // same size, then a (misaligned) int store.
12119 // FIXME: Does not handle truncating floating point stores!
12120 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
12121 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
12122 Alignment, ST->getMemOperand()->getFlags());
12123 return Result;
12124 }
12125 // Do a (aligned) store to a stack slot, then copy from the stack slot
12126 // to the final destination using (unaligned) integer loads and stores.
12127 MVT RegVT = getRegisterType(
12128 *DAG.getContext(),
12129 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
12130 EVT PtrVT = Ptr.getValueType();
12131 unsigned StoredBytes = StoreMemVT.getStoreSize();
12132 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12133 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
12134
12135 // Make sure the stack slot is also aligned for the register type.
12136 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
12137 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
12138
12139 // Perform the original store, only redirected to the stack slot.
12140 SDValue Store = DAG.getTruncStore(
12141 Chain, dl, Val, StackPtr,
12142 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
12143
12144 EVT StackPtrVT = StackPtr.getValueType();
12145
12146 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12147 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12149 unsigned Offset = 0;
12150
12151 // Do all but one copies using the full register width.
12152 for (unsigned i = 1; i < NumRegs; i++) {
12153 // Load one integer register's worth from the stack slot.
12154 SDValue Load = DAG.getLoad(
12155 RegVT, dl, Store, StackPtr,
12156 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
12157 // Store it to the final location. Remember the store.
12158 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
12159 ST->getPointerInfo().getWithOffset(Offset),
12160 ST->getBaseAlign(),
12161 ST->getMemOperand()->getFlags()));
12162 // Increment the pointers.
12163 Offset += RegBytes;
12164 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12165 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12166 }
12167
12168 // The last store may be partial. Do a truncating store. On big-endian
12169 // machines this requires an extending load from the stack slot to ensure
12170 // that the bits are in the right place.
12171 EVT LoadMemVT =
12172 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
12173
12174 // Load from the stack slot.
12175 SDValue Load = DAG.getExtLoad(
12176 ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
12177 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
12178
12179 Stores.push_back(DAG.getTruncStore(
12180 Load.getValue(1), dl, Load, Ptr,
12181 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
12182 ST->getBaseAlign(), ST->getMemOperand()->getFlags(), ST->getAAInfo()));
12183 // The order of the stores doesn't matter - say it with a TokenFactor.
12184 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12185 return Result;
12186 }
12187
12188 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
12189 "Unaligned store of unknown type.");
12190 // Get the half-size VT
12191 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
12192 unsigned NumBits = NewStoredVT.getFixedSizeInBits();
12193 unsigned IncrementSize = NumBits / 8;
12194
12195 // Divide the stored value in two parts.
12196 SDValue ShiftAmount =
12197 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl);
12198 SDValue Lo = Val;
12199 // If Val is a constant, replace the upper bits with 0. The SRL will constant
12200 // fold and not use the upper bits. A smaller constant may be easier to
12201 // materialize.
12202 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
12203 Lo = DAG.getNode(
12204 ISD::AND, dl, VT, Lo,
12205 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
12206 VT));
12207 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
12208
12209 // Store the two parts
12210 SDValue Store1, Store2;
12211 Store1 = DAG.getTruncStore(Chain, dl,
12212 DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
12213 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
12214 ST->getMemOperand()->getFlags());
12215
12216 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12217 Store2 = DAG.getTruncStore(
12218 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
12219 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
12220 ST->getMemOperand()->getFlags(), ST->getAAInfo());
12221
12222 SDValue Result =
12223 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
12224 return Result;
12225}
12226
12227SDValue
12229 const SDLoc &DL, EVT DataVT,
12230 SelectionDAG &DAG,
12231 bool IsCompressedMemory) const {
12233 EVT AddrVT = Addr.getValueType();
12234 EVT MaskVT = Mask.getValueType();
12235 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
12236 "Incompatible types of Data and Mask");
12237 if (IsCompressedMemory) {
12238 // Incrementing the pointer according to number of '1's in the mask.
12239 if (DataVT.isScalableVector()) {
12240 EVT MaskExtVT = MaskVT.changeElementType(*DAG.getContext(), MVT::i32);
12241 SDValue MaskExt = DAG.getNode(ISD::ZERO_EXTEND, DL, MaskExtVT, Mask);
12242 Increment = DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, MaskExt);
12243 } else {
12244 EVT MaskIntVT =
12245 EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
12246 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
12247 if (MaskIntVT.getSizeInBits() < 32) {
12248 MaskInIntReg =
12249 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
12250 MaskIntVT = MVT::i32;
12251 }
12252 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
12253 }
12254 // Scale is an element size in bytes.
12255 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
12256 AddrVT);
12257 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
12258 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
12259 } else
12260 Increment = DAG.getTypeSize(DL, AddrVT, DataVT.getStoreSize());
12261
12262 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
12263}
12264
12266 EVT VecVT, const SDLoc &dl,
12267 ElementCount SubEC) {
12268 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
12269 "Cannot index a scalable vector within a fixed-width vector");
12270
12271 unsigned NElts = VecVT.getVectorMinNumElements();
12272 unsigned NumSubElts = SubEC.getKnownMinValue();
12273 EVT IdxVT = Idx.getValueType();
12274
12275 if (VecVT.isScalableVector() && !SubEC.isScalable()) {
12276 // If this is a constant index and we know the value plus the number of the
12277 // elements in the subvector minus one is less than the minimum number of
12278 // elements then it's safe to return Idx.
12279 if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
12280 if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
12281 return Idx;
12282 SDValue VS =
12283 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
12284 unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
12285 SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
12286 DAG.getConstant(NumSubElts, dl, IdxVT));
12287 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
12288 }
12289 if (isPowerOf2_32(NElts) && NumSubElts == 1) {
12290 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts));
12291 return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
12292 DAG.getConstant(Imm, dl, IdxVT));
12293 }
12294 unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
12295 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
12296 DAG.getConstant(MaxIndex, dl, IdxVT));
12297}
12298
12299SDValue
12301 EVT VecVT, SDValue Index,
12302 const SDNodeFlags PtrArithFlags) const {
12304 DAG, VecPtr, VecVT,
12306 Index, PtrArithFlags);
12307}
12308
12309SDValue
12311 EVT VecVT, EVT SubVecVT, SDValue Index,
12312 const SDNodeFlags PtrArithFlags) const {
12313 SDLoc dl(Index);
12314 // Make sure the index type is big enough to compute in.
12315 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
12316
12317 EVT EltVT = VecVT.getVectorElementType();
12318
12319 // Calculate the element offset and add it to the pointer.
12320 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
12321 assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
12322 "Converting bits to bytes lost precision");
12323 assert(SubVecVT.getVectorElementType() == EltVT &&
12324 "Sub-vector must be a vector with matching element type");
12325 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
12326 SubVecVT.getVectorElementCount());
12327
12328 EVT IdxVT = Index.getValueType();
12329 if (SubVecVT.isScalableVector())
12330 Index =
12331 DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12332 DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
12333
12334 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12335 DAG.getConstant(EltSize, dl, IdxVT));
12336 return DAG.getMemBasePlusOffset(VecPtr, Index, dl, PtrArithFlags);
12337}
12338
12339//===----------------------------------------------------------------------===//
12340// Implementation of Emulated TLS Model
12341//===----------------------------------------------------------------------===//
12342
12344 SelectionDAG &DAG) const {
12345 // Access to address of TLS varialbe xyz is lowered to a function call:
12346 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
12347 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12348 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
12349 SDLoc dl(GA);
12350
12351 ArgListTy Args;
12352 const GlobalValue *GV =
12354 SmallString<32> NameString("__emutls_v.");
12355 NameString += GV->getName();
12356 StringRef EmuTlsVarName(NameString);
12357 const GlobalVariable *EmuTlsVar =
12358 GV->getParent()->getNamedGlobal(EmuTlsVarName);
12359 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
12360 Args.emplace_back(DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT), VoidPtrType);
12361
12362 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
12363
12365 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
12366 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
12367 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12368
12369 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12370 // At last for X86 targets, maybe good for other targets too?
12372 MFI.setAdjustsStack(true); // Is this only for X86 target?
12373 MFI.setHasCalls(true);
12374
12375 assert((GA->getOffset() == 0) &&
12376 "Emulated TLS must have zero offset in GlobalAddressSDNode");
12377 return CallResult.first;
12378}
12379
12381 SelectionDAG &DAG) const {
12382 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
12383 if (!isCtlzFast())
12384 return SDValue();
12385 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12386 SDLoc dl(Op);
12387 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
12388 EVT VT = Op.getOperand(0).getValueType();
12389 SDValue Zext = Op.getOperand(0);
12390 if (VT.bitsLT(MVT::i32)) {
12391 VT = MVT::i32;
12392 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
12393 }
12394 unsigned Log2b = Log2_32(VT.getSizeInBits());
12395 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
12396 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
12397 DAG.getConstant(Log2b, dl, MVT::i32));
12398 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
12399 }
12400 return SDValue();
12401}
12402
12404 SDValue Op0 = Node->getOperand(0);
12405 SDValue Op1 = Node->getOperand(1);
12406 EVT VT = Op0.getValueType();
12407 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12408 unsigned Opcode = Node->getOpcode();
12409 SDLoc DL(Node);
12410
12411 // If both sign bits are zero, flip UMIN/UMAX <-> SMIN/SMAX if legal.
12412 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
12413 if (isOperationLegal(AltOpcode, VT) && DAG.SignBitIsZero(Op0) &&
12414 DAG.SignBitIsZero(Op1))
12415 return DAG.getNode(AltOpcode, DL, VT, Op0, Op1);
12416
12417 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
12418 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
12420 Op0 = DAG.getFreeze(Op0);
12421 SDValue Zero = DAG.getConstant(0, DL, VT);
12422 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12423 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
12424 }
12425
12426 // umin(x,y) -> sub(x,usubsat(x,y))
12427 // TODO: Missing freeze(Op0)?
12428 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
12430 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12431 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
12432 }
12433
12434 // umax(x,y) -> add(x,usubsat(y,x))
12435 // TODO: Missing freeze(Op0)?
12436 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
12438 return DAG.getNode(ISD::ADD, DL, VT, Op0,
12439 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
12440 }
12441
12442 // FIXME: Should really try to split the vector in case it's legal on a
12443 // subvector.
12445 return DAG.UnrollVectorOp(Node);
12446
12447 // Attempt to find an existing SETCC node that we can reuse.
12448 // TODO: Do we need a generic doesSETCCNodeExist?
12449 // TODO: Missing freeze(Op0)/freeze(Op1)?
12450 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
12451 ISD::CondCode PrefCommuteCC,
12452 ISD::CondCode AltCommuteCC) {
12453 SDVTList BoolVTList = DAG.getVTList(BoolVT);
12454 for (ISD::CondCode CC : {PrefCC, AltCC}) {
12455 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12456 {Op0, Op1, DAG.getCondCode(CC)})) {
12457 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12458 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12459 }
12460 }
12461 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
12462 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12463 {Op0, Op1, DAG.getCondCode(CC)})) {
12464 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12465 return DAG.getSelect(DL, VT, Cond, Op1, Op0);
12466 }
12467 }
12468 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
12469 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12470 };
12471
12472 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
12473 // -> Y = (A < B) ? B : A
12474 // -> Y = (A >= B) ? A : B
12475 // -> Y = (A <= B) ? B : A
12476 switch (Opcode) {
12477 case ISD::SMAX:
12478 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
12479 case ISD::SMIN:
12480 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
12481 case ISD::UMAX:
12482 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
12483 case ISD::UMIN:
12484 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
12485 }
12486
12487 llvm_unreachable("How did we get here?");
12488}
12489
12491 unsigned Opcode = Node->getOpcode();
12492 SDValue LHS = Node->getOperand(0);
12493 SDValue RHS = Node->getOperand(1);
12494 EVT VT = LHS.getValueType();
12495 SDLoc dl(Node);
12496
12497 assert(VT == RHS.getValueType() && "Expected operands to be the same type");
12498 assert(VT.isInteger() && "Expected operands to be integers");
12499
12500 // usub.sat(a, b) -> umax(a, b) - b
12501 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
12502 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
12503 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
12504 }
12505
12506 // usub.sat(a, 1) -> sub(a, zext(a != 0))
12507 // Prefer this on targets without legal/cost-effective overflow-carry nodes.
12508 if (Opcode == ISD::USUBSAT && isOneOrOneSplat(RHS) &&
12510 LHS = DAG.getFreeze(LHS);
12511 SDValue Zero = DAG.getConstant(0, dl, VT);
12512 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12513 SDValue IsNonZero = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETNE);
12514 SDValue Subtrahend = DAG.getBoolExtOrTrunc(IsNonZero, dl, VT, BoolVT);
12515 Subtrahend =
12516 DAG.getNode(ISD::AND, dl, VT, Subtrahend, DAG.getConstant(1, dl, VT));
12517 return DAG.getNode(ISD::SUB, dl, VT, LHS, Subtrahend);
12518 }
12519
12520 // uadd.sat(a, b) -> umin(a, ~b) + b
12521 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
12522 SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
12523 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
12524 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
12525 }
12526
12527 unsigned OverflowOp;
12528 switch (Opcode) {
12529 case ISD::SADDSAT:
12530 OverflowOp = ISD::SADDO;
12531 break;
12532 case ISD::UADDSAT:
12533 OverflowOp = ISD::UADDO;
12534 break;
12535 case ISD::SSUBSAT:
12536 OverflowOp = ISD::SSUBO;
12537 break;
12538 case ISD::USUBSAT:
12539 OverflowOp = ISD::USUBO;
12540 break;
12541 default:
12542 llvm_unreachable("Expected method to receive signed or unsigned saturation "
12543 "addition or subtraction node.");
12544 }
12545
12546 // FIXME: Should really try to split the vector in case it's legal on a
12547 // subvector.
12549 return DAG.UnrollVectorOp(Node);
12550
12551 unsigned BitWidth = LHS.getScalarValueSizeInBits();
12552 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12553 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12554 SDValue SumDiff = Result.getValue(0);
12555 SDValue Overflow = Result.getValue(1);
12556 SDValue Zero = DAG.getConstant(0, dl, VT);
12557 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
12558
12559 if (Opcode == ISD::UADDSAT) {
12561 // (LHS + RHS) | OverflowMask
12562 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12563 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
12564 }
12565 // Overflow ? 0xffff.... : (LHS + RHS)
12566 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
12567 }
12568
12569 if (Opcode == ISD::USUBSAT) {
12571 // (LHS - RHS) & ~OverflowMask
12572 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12573 SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
12574 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
12575 }
12576 // Overflow ? 0 : (LHS - RHS)
12577 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
12578 }
12579
12580 assert((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
12581 "Expected signed saturating add/sub opcode");
12582
12583 const APInt MinVal = APInt::getSignedMinValue(BitWidth);
12584 const APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
12585
12586 KnownBits KnownLHS = DAG.computeKnownBits(LHS);
12587 KnownBits KnownRHS = DAG.computeKnownBits(RHS);
12588
12589 // If either of the operand signs are known, then they are guaranteed to
12590 // only saturate in one direction. If non-negative they will saturate
12591 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
12592 //
12593 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
12594 // sign of 'y' has to be flipped.
12595
12596 bool LHSIsNonNegative = KnownLHS.isNonNegative();
12597 bool RHSIsNonNegative =
12598 Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() : KnownRHS.isNegative();
12599 if (LHSIsNonNegative || RHSIsNonNegative) {
12600 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12601 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
12602 }
12603
12604 bool LHSIsNegative = KnownLHS.isNegative();
12605 bool RHSIsNegative =
12606 Opcode == ISD::SADDSAT ? KnownRHS.isNegative() : KnownRHS.isNonNegative();
12607 if (LHSIsNegative || RHSIsNegative) {
12608 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12609 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
12610 }
12611
12612 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
12613 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12614 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
12615 DAG.getConstant(BitWidth - 1, dl, VT));
12616 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
12617 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
12618}
12619
12621 unsigned Opcode = Node->getOpcode();
12622 SDValue LHS = Node->getOperand(0);
12623 SDValue RHS = Node->getOperand(1);
12624 EVT VT = LHS.getValueType();
12625 EVT ResVT = Node->getValueType(0);
12626 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12627 SDLoc dl(Node);
12628
12629 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT);
12630 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT);
12631 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate);
12632 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate);
12633
12634 // We can't perform arithmetic on i1 values. Extending them would
12635 // probably result in worse codegen, so let's just use two selects instead.
12636 // Some targets are also just better off using selects rather than subtraction
12637 // because one of the conditions can be merged with one of the selects.
12638 // And finally, if we don't know the contents of high bits of a boolean value
12639 // we can't perform any arithmetic either.
12641 BoolVT.getScalarSizeInBits() == 1 ||
12643 SDValue SelectZeroOrOne =
12644 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT),
12645 DAG.getConstant(0, dl, ResVT));
12646 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT),
12647 SelectZeroOrOne);
12648 }
12649
12651 std::swap(IsGT, IsLT);
12652 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl,
12653 ResVT);
12654}
12655
12657 unsigned Opcode = Node->getOpcode();
12658 bool IsSigned = Opcode == ISD::SSHLSAT;
12659 SDValue LHS = Node->getOperand(0);
12660 SDValue RHS = Node->getOperand(1);
12661 EVT VT = LHS.getValueType();
12662 SDLoc dl(Node);
12663
12664 assert((Node->getOpcode() == ISD::SSHLSAT ||
12665 Node->getOpcode() == ISD::USHLSAT) &&
12666 "Expected a SHLSAT opcode");
12667 assert(VT.isInteger() && "Expected operands to be integers");
12668
12670 return DAG.UnrollVectorOp(Node);
12671
12672 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
12673
12674 unsigned BW = VT.getScalarSizeInBits();
12675 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12676 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
12677 SDValue Orig =
12678 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
12679
12680 SDValue SatVal;
12681 if (IsSigned) {
12682 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
12683 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
12684 SDValue Cond =
12685 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
12686 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
12687 } else {
12688 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
12689 }
12690 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
12691 return DAG.getSelect(dl, VT, Cond, SatVal, Result);
12692}
12693
12695 bool Signed, SDValue &Lo, SDValue &Hi,
12696 SDValue LHS, SDValue RHS,
12697 SDValue HiLHS, SDValue HiRHS) const {
12698 EVT VT = LHS.getValueType();
12699 assert(RHS.getValueType() == VT && "Mismatching operand types");
12700
12701 assert((HiLHS && HiRHS) || (!HiLHS && !HiRHS));
12702 assert((!Signed || !HiLHS) &&
12703 "Signed flag should only be set when HiLHS and RiRHS are null");
12704
12705 // We'll expand the multiplication by brute force because we have no other
12706 // options. This is a trivially-generalized version of the code from
12707 // Hacker's Delight (itself derived from Knuth's Algorithm M from section
12708 // 4.3.1). If Signed is set, we can use arithmetic right shifts to propagate
12709 // sign bits while calculating the Hi half.
12710 unsigned Bits = VT.getScalarSizeInBits();
12711 unsigned HalfBits = Bits / 2;
12712 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT);
12713 SDValue LL = DAG.getNode(ISD::AND, dl, VT, LHS, Mask);
12714 SDValue RL = DAG.getNode(ISD::AND, dl, VT, RHS, Mask);
12715
12716 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LL, RL);
12717 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask);
12718
12719 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl);
12720 // This is always an unsigned shift.
12721 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift);
12722
12723 unsigned ShiftOpc = Signed ? ISD::SRA : ISD::SRL;
12724 SDValue LH = DAG.getNode(ShiftOpc, dl, VT, LHS, Shift);
12725 SDValue RH = DAG.getNode(ShiftOpc, dl, VT, RHS, Shift);
12726
12727 SDValue U =
12728 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RL), TH);
12729 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask);
12730 SDValue UH = DAG.getNode(ShiftOpc, dl, VT, U, Shift);
12731
12732 SDValue V =
12733 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LL, RH), UL);
12734 SDValue VH = DAG.getNode(ShiftOpc, dl, VT, V, Shift);
12735
12736 Lo = DAG.getNode(ISD::ADD, dl, VT, TL,
12737 DAG.getNode(ISD::SHL, dl, VT, V, Shift));
12738
12739 Hi = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RH),
12740 DAG.getNode(ISD::ADD, dl, VT, UH, VH));
12741
12742 // If HiLHS and HiRHS are set, multiply them by the opposite low part and add
12743 // the products to Hi.
12744 if (HiLHS) {
12745 SDValue RHLL = DAG.getNode(ISD::MUL, dl, VT, HiRHS, LHS);
12746 SDValue RLLH = DAG.getNode(ISD::MUL, dl, VT, RHS, HiLHS);
12747 Hi = DAG.getNode(ISD::ADD, dl, VT, Hi,
12748 DAG.getNode(ISD::ADD, dl, VT, RHLL, RLLH));
12749 }
12750}
12751
12753 bool Signed, const SDValue LHS,
12754 const SDValue RHS, SDValue &Lo,
12755 SDValue &Hi) const {
12756 EVT VT = LHS.getValueType();
12757 assert(RHS.getValueType() == VT && "Mismatching operand types");
12758 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
12759 // We can fall back to a libcall with an illegal type for the MUL if we
12760 // have a libcall big enough.
12761 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
12762 if (WideVT == MVT::i16)
12763 LC = RTLIB::MUL_I16;
12764 else if (WideVT == MVT::i32)
12765 LC = RTLIB::MUL_I32;
12766 else if (WideVT == MVT::i64)
12767 LC = RTLIB::MUL_I64;
12768 else if (WideVT == MVT::i128)
12769 LC = RTLIB::MUL_I128;
12770
12771 RTLIB::LibcallImpl LibcallImpl = getLibcallImpl(LC);
12772 if (LibcallImpl == RTLIB::Unsupported) {
12773 forceExpandMultiply(DAG, dl, Signed, Lo, Hi, LHS, RHS);
12774 return;
12775 }
12776
12777 SDValue HiLHS, HiRHS;
12778 if (Signed) {
12779 // The high part is obtained by SRA'ing all but one of the bits of low
12780 // part.
12781 unsigned LoSize = VT.getFixedSizeInBits();
12782 SDValue Shift = DAG.getShiftAmountConstant(LoSize - 1, VT, dl);
12783 HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, Shift);
12784 HiRHS = DAG.getNode(ISD::SRA, dl, VT, RHS, Shift);
12785 } else {
12786 HiLHS = DAG.getConstant(0, dl, VT);
12787 HiRHS = DAG.getConstant(0, dl, VT);
12788 }
12789
12790 // Attempt a libcall.
12791 SDValue Ret;
12793 CallOptions.setIsSigned(Signed);
12794 CallOptions.setIsPostTypeLegalization(true);
12796 // Halves of WideVT are packed into registers in different order
12797 // depending on platform endianness. This is usually handled by
12798 // the C calling convention, but we can't defer to it in
12799 // the legalizer.
12800 SDValue Args[] = {LHS, HiLHS, RHS, HiRHS};
12801 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
12802 } else {
12803 SDValue Args[] = {HiLHS, LHS, HiRHS, RHS};
12804 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
12805 }
12807 "Ret value is a collection of constituent nodes holding result.");
12808 if (DAG.getDataLayout().isLittleEndian()) {
12809 // Same as above.
12810 Lo = Ret.getOperand(0);
12811 Hi = Ret.getOperand(1);
12812 } else {
12813 Lo = Ret.getOperand(1);
12814 Hi = Ret.getOperand(0);
12815 }
12816}
12817
12818SDValue
12820 assert((Node->getOpcode() == ISD::SMULFIX ||
12821 Node->getOpcode() == ISD::UMULFIX ||
12822 Node->getOpcode() == ISD::SMULFIXSAT ||
12823 Node->getOpcode() == ISD::UMULFIXSAT) &&
12824 "Expected a fixed point multiplication opcode");
12825
12826 SDLoc dl(Node);
12827 SDValue LHS = Node->getOperand(0);
12828 SDValue RHS = Node->getOperand(1);
12829 EVT VT = LHS.getValueType();
12830 unsigned Scale = Node->getConstantOperandVal(2);
12831 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
12832 Node->getOpcode() == ISD::UMULFIXSAT);
12833 bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
12834 Node->getOpcode() == ISD::SMULFIXSAT);
12835 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12836 unsigned VTSize = VT.getScalarSizeInBits();
12837
12838 if (!Scale) {
12839 // [us]mul.fix(a, b, 0) -> mul(a, b)
12840 if (!Saturating) {
12842 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
12843 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
12844 SDValue Result =
12845 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12846 SDValue Product = Result.getValue(0);
12847 SDValue Overflow = Result.getValue(1);
12848 SDValue Zero = DAG.getConstant(0, dl, VT);
12849
12850 APInt MinVal = APInt::getSignedMinValue(VTSize);
12851 APInt MaxVal = APInt::getSignedMaxValue(VTSize);
12852 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12853 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12854 // Xor the inputs, if resulting sign bit is 0 the product will be
12855 // positive, else negative.
12856 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
12857 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
12858 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
12859 return DAG.getSelect(dl, VT, Overflow, Result, Product);
12860 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
12861 SDValue Result =
12862 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12863 SDValue Product = Result.getValue(0);
12864 SDValue Overflow = Result.getValue(1);
12865
12866 APInt MaxVal = APInt::getMaxValue(VTSize);
12867 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12868 return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
12869 }
12870 }
12871
12872 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
12873 "Expected scale to be less than the number of bits if signed or at "
12874 "most the number of bits if unsigned.");
12875 assert(LHS.getValueType() == RHS.getValueType() &&
12876 "Expected both operands to be the same type");
12877
12878 // Get the upper and lower bits of the result.
12879 SDValue Lo, Hi;
12880 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
12881 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
12882 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
12883 if (isOperationLegalOrCustom(LoHiOp, VT)) {
12884 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
12885 Lo = Result.getValue(0);
12886 Hi = Result.getValue(1);
12887 } else if (isOperationLegalOrCustom(HiOp, VT)) {
12888 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
12889 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
12890 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
12891 // Try for a multiplication using a wider type.
12892 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
12893 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS);
12894 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS);
12895 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt);
12896 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
12897 SDValue Shifted =
12898 DAG.getNode(ISD::SRA, dl, WideVT, Res,
12899 DAG.getShiftAmountConstant(VTSize, WideVT, dl));
12900 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted);
12901 } else if (VT.isVector()) {
12902 return SDValue();
12903 } else {
12904 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi);
12905 }
12906
12907 if (Scale == VTSize)
12908 // Result is just the top half since we'd be shifting by the width of the
12909 // operand. Overflow impossible so this works for both UMULFIX and
12910 // UMULFIXSAT.
12911 return Hi;
12912
12913 // The result will need to be shifted right by the scale since both operands
12914 // are scaled. The result is given to us in 2 halves, so we only want part of
12915 // both in the result.
12916 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
12917 DAG.getShiftAmountConstant(Scale, VT, dl));
12918 if (!Saturating)
12919 return Result;
12920
12921 if (!Signed) {
12922 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
12923 // widened multiplication) aren't all zeroes.
12924
12925 // Saturate to max if ((Hi >> Scale) != 0),
12926 // which is the same as if (Hi > ((1 << Scale) - 1))
12927 APInt MaxVal = APInt::getMaxValue(VTSize);
12928 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale),
12929 dl, VT);
12930 Result = DAG.getSelectCC(dl, Hi, LowMask,
12931 DAG.getConstant(MaxVal, dl, VT), Result,
12932 ISD::SETUGT);
12933
12934 return Result;
12935 }
12936
12937 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
12938 // widened multiplication) aren't all ones or all zeroes.
12939
12940 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
12941 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
12942
12943 if (Scale == 0) {
12944 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
12945 DAG.getShiftAmountConstant(VTSize - 1, VT, dl));
12946 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
12947 // Saturated to SatMin if wide product is negative, and SatMax if wide
12948 // product is positive ...
12949 SDValue Zero = DAG.getConstant(0, dl, VT);
12950 SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax,
12951 ISD::SETLT);
12952 // ... but only if we overflowed.
12953 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
12954 }
12955
12956 // We handled Scale==0 above so all the bits to examine is in Hi.
12957
12958 // Saturate to max if ((Hi >> (Scale - 1)) > 0),
12959 // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
12960 SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1),
12961 dl, VT);
12962 Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT);
12963 // Saturate to min if (Hi >> (Scale - 1)) < -1),
12964 // which is the same as if (HI < (-1 << (Scale - 1))
12965 SDValue HighMask =
12966 DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1),
12967 dl, VT);
12968 Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT);
12969 return Result;
12970}
12971
12972SDValue
12974 SDValue LHS, SDValue RHS,
12975 unsigned Scale, SelectionDAG &DAG) const {
12976 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
12977 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
12978 "Expected a fixed point division opcode");
12979
12980 EVT VT = LHS.getValueType();
12981 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
12982 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
12983 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12984
12985 // If there is enough room in the type to upscale the LHS or downscale the
12986 // RHS before the division, we can perform it in this type without having to
12987 // resize. For signed operations, the LHS headroom is the number of
12988 // redundant sign bits, and for unsigned ones it is the number of zeroes.
12989 // The headroom for the RHS is the number of trailing zeroes.
12990 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
12992 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
12993
12994 // For signed saturating operations, we need to be able to detect true integer
12995 // division overflow; that is, when you have MIN / -EPS. However, this
12996 // is undefined behavior and if we emit divisions that could take such
12997 // values it may cause undesired behavior (arithmetic exceptions on x86, for
12998 // example).
12999 // Avoid this by requiring an extra bit so that we never get this case.
13000 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
13001 // signed saturating division, we need to emit a whopping 32-bit division.
13002 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
13003 return SDValue();
13004
13005 unsigned LHSShift = std::min(LHSLead, Scale);
13006 unsigned RHSShift = Scale - LHSShift;
13007
13008 // At this point, we know that if we shift the LHS up by LHSShift and the
13009 // RHS down by RHSShift, we can emit a regular division with a final scaling
13010 // factor of Scale.
13011
13012 if (LHSShift)
13013 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
13014 DAG.getShiftAmountConstant(LHSShift, VT, dl));
13015 if (RHSShift)
13016 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
13017 DAG.getShiftAmountConstant(RHSShift, VT, dl));
13018
13019 SDValue Quot;
13020 if (Signed) {
13021 // For signed operations, if the resulting quotient is negative and the
13022 // remainder is nonzero, subtract 1 from the quotient to round towards
13023 // negative infinity.
13024 SDValue Rem;
13025 // FIXME: Ideally we would always produce an SDIVREM here, but if the
13026 // type isn't legal, SDIVREM cannot be expanded. There is no reason why
13027 // we couldn't just form a libcall, but the type legalizer doesn't do it.
13028 if (isTypeLegal(VT) &&
13030 Quot = DAG.getNode(ISD::SDIVREM, dl,
13031 DAG.getVTList(VT, VT),
13032 LHS, RHS);
13033 Rem = Quot.getValue(1);
13034 Quot = Quot.getValue(0);
13035 } else {
13036 Quot = DAG.getNode(ISD::SDIV, dl, VT,
13037 LHS, RHS);
13038 Rem = DAG.getNode(ISD::SREM, dl, VT,
13039 LHS, RHS);
13040 }
13041 SDValue Zero = DAG.getConstant(0, dl, VT);
13042 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
13043 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
13044 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
13045 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
13046 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
13047 DAG.getConstant(1, dl, VT));
13048 Quot = DAG.getSelect(dl, VT,
13049 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
13050 Sub1, Quot);
13051 } else
13052 Quot = DAG.getNode(ISD::UDIV, dl, VT,
13053 LHS, RHS);
13054
13055 return Quot;
13056}
13057
13059 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13060 SDLoc dl(Node);
13061 SDValue LHS = Node->getOperand(0);
13062 SDValue RHS = Node->getOperand(1);
13063 bool IsAdd = Node->getOpcode() == ISD::UADDO;
13064
13065 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
13066 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
13067 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
13068 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
13069 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
13070 { LHS, RHS, CarryIn });
13071 Result = SDValue(NodeCarry.getNode(), 0);
13072 Overflow = SDValue(NodeCarry.getNode(), 1);
13073 return;
13074 }
13075
13076 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13077 LHS.getValueType(), LHS, RHS);
13078
13079 EVT ResultType = Node->getValueType(1);
13080 EVT SetCCType = getSetCCResultType(
13081 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13082 SDValue SetCC;
13083 if (IsAdd && isOneConstant(RHS)) {
13084 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
13085 // the live range of X. We assume comparing with 0 is cheap.
13086 // The general case (X + C) < C is not necessarily beneficial. Although we
13087 // reduce the live range of X, we may introduce the materialization of
13088 // constant C.
13089 SetCC =
13090 DAG.getSetCC(dl, SetCCType, Result,
13091 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
13092 } else if (IsAdd && isAllOnesConstant(RHS)) {
13093 // Special case: uaddo X, -1 overflows if X != 0.
13094 SetCC =
13095 DAG.getSetCC(dl, SetCCType, LHS,
13096 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
13097 } else {
13098 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
13099 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
13100 }
13101 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13102}
13103
13105 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13106 SDLoc dl(Node);
13107 SDValue LHS = Node->getOperand(0);
13108 SDValue RHS = Node->getOperand(1);
13109 bool IsAdd = Node->getOpcode() == ISD::SADDO;
13110
13111 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13112 LHS.getValueType(), LHS, RHS);
13113
13114 EVT ResultType = Node->getValueType(1);
13115 EVT OType = getSetCCResultType(
13116 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13117
13118 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
13119 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
13120 if (isOperationLegal(OpcSat, LHS.getValueType())) {
13121 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
13122 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
13123 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13124 return;
13125 }
13126
13127 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
13128
13129 if (IsAdd) {
13130 // For an addition, the result should be less than one of the operands (LHS)
13131 // if and only if the other operand (RHS) is negative, otherwise there will
13132 // be overflow.
13133 SDValue ResultLowerThanLHS =
13134 DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
13135 SDValue RHSNegative = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETLT);
13136 Overflow = DAG.getBoolExtOrTrunc(
13137 DAG.getNode(ISD::XOR, dl, OType, RHSNegative, ResultLowerThanLHS), dl,
13138 ResultType, ResultType);
13139 } else {
13140 // For subtraction, overflow occurs when the signed comparison of operands
13141 // doesn't match the sign of the result.
13142 SDValue LHSLessThanRHS = DAG.getSetCC(dl, OType, LHS, RHS, ISD::SETLT);
13143 SDValue ResultNegative = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETLT);
13144 Overflow = DAG.getBoolExtOrTrunc(
13145 DAG.getNode(ISD::XOR, dl, OType, LHSLessThanRHS, ResultNegative), dl,
13146 ResultType, ResultType);
13147 }
13148}
13149
13151 SDValue &Overflow, SelectionDAG &DAG) const {
13152 SDLoc dl(Node);
13153 EVT VT = Node->getValueType(0);
13154 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13155 SDValue LHS = Node->getOperand(0);
13156 SDValue RHS = Node->getOperand(1);
13157 bool isSigned = Node->getOpcode() == ISD::SMULO;
13158
13159 // For power-of-two multiplications we can use a simpler shift expansion.
13160 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
13161 const APInt &C = RHSC->getAPIntValue();
13162 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
13163 if (C.isPowerOf2()) {
13164 // smulo(x, signed_min) is same as umulo(x, signed_min).
13165 bool UseArithShift = isSigned && !C.isMinSignedValue();
13166 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl);
13167 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
13168 Overflow = DAG.getSetCC(dl, SetCCVT,
13169 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
13170 dl, VT, Result, ShiftAmt),
13171 LHS, ISD::SETNE);
13172 return true;
13173 }
13174 }
13175
13176 SDValue BottomHalf;
13177 SDValue TopHalf;
13178 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13179
13180 static const unsigned Ops[2][3] =
13183 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
13184 BottomHalf = DAG.getNode(Ops[isSigned][0], dl, DAG.getVTList(VT, VT), LHS,
13185 RHS);
13186 TopHalf = BottomHalf.getValue(1);
13187 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
13188 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13189 TopHalf = DAG.getNode(Ops[isSigned][1], dl, VT, LHS, RHS);
13190 } else if (isTypeLegal(WideVT)) {
13191 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
13192 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
13193 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
13194 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13195 SDValue ShiftAmt =
13196 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13197 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
13198 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
13199 } else {
13200 if (VT.isVector())
13201 return false;
13202
13203 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf);
13204 }
13205
13206 Result = BottomHalf;
13207 if (isSigned) {
13208 SDValue ShiftAmt = DAG.getShiftAmountConstant(
13209 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl);
13210 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
13211 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
13212 } else {
13213 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
13214 DAG.getConstant(0, dl, VT), ISD::SETNE);
13215 }
13216
13217 // Truncate the result if SetCC returns a larger type than needed.
13218 EVT RType = Node->getValueType(1);
13219 if (RType.bitsLT(Overflow.getValueType()))
13220 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
13221
13222 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
13223 "Unexpected result type for S/UMULO legalization");
13224 return true;
13225}
13226
13228 SDLoc dl(Node);
13229 ISD::NodeType BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13230 SDValue Op = Node->getOperand(0);
13231 SDNodeFlags Flags = Node->getFlags();
13232 EVT VT = Op.getValueType();
13233
13234 // Try to use a shuffle reduction for power of two vectors.
13235 if (VT.isPow2VectorType()) {
13236 // See if the reduction opcode is safe to use with widened types.
13237 bool WidenSrc = false;
13238 switch (Node->getOpcode()) {
13241 case ISD::VECREDUCE_ADD:
13242 case ISD::VECREDUCE_MUL:
13243 case ISD::VECREDUCE_AND:
13244 case ISD::VECREDUCE_OR:
13245 case ISD::VECREDUCE_XOR:
13250 WidenSrc = VT.isFixedLengthVector();
13251 break;
13252 }
13253
13255 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13256 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) {
13257 if (WidenSrc && Op.getOpcode() != ISD::BUILD_VECTOR) {
13258 // Attempt to widen the source vectors to a legal op.
13259 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), HalfVT);
13260 if (WideVT.isVector() &&
13261 WideVT.getScalarType() == HalfVT.getScalarType() &&
13262 WideVT.getVectorNumElements() >= HalfVT.getVectorNumElements() &&
13263 isOperationLegalOrCustom(BaseOpcode, WideVT)) {
13264 SDValue Lo, Hi;
13265 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13266 Lo = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Lo, 0);
13267 Hi = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Hi, 0);
13268 Op = DAG.getNode(BaseOpcode, dl, WideVT, Lo, Hi, Flags);
13269 Op = DAG.getExtractSubvector(dl, HalfVT, Op, 0);
13270 VT = HalfVT;
13271 continue;
13272 }
13273 }
13274 break;
13275 }
13276
13277 SDValue Lo, Hi;
13278 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13279 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Flags);
13280 VT = HalfVT;
13281
13282 // Stop if splitting is enough to make the reduction legal.
13283 if (isOperationLegalOrCustom(Node->getOpcode(), HalfVT))
13284 return DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Op,
13285 Flags);
13286 }
13287 }
13288
13289 if (VT.isScalableVector())
13291 "Expanding reductions for scalable vectors is undefined.");
13292
13293 EVT EltVT = VT.getVectorElementType();
13294 unsigned NumElts = VT.getVectorNumElements();
13295
13297 DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
13298
13299 SDValue Res = Ops[0];
13300 for (unsigned i = 1; i < NumElts; i++)
13301 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13302
13303 // Result type may be wider than element type.
13304 if (EltVT != Node->getValueType(0))
13305 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
13306 return Res;
13307}
13308
13310 SDLoc dl(Node);
13311 SDValue AccOp = Node->getOperand(0);
13312 SDValue VecOp = Node->getOperand(1);
13313 SDNodeFlags Flags = Node->getFlags();
13314
13315 EVT VT = VecOp.getValueType();
13316 EVT EltVT = VT.getVectorElementType();
13317
13318 if (VT.isScalableVector())
13320 "Expanding reductions for scalable vectors is undefined.");
13321
13322 unsigned NumElts = VT.getVectorNumElements();
13323
13325 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
13326
13327 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13328
13329 SDValue Res = AccOp;
13330 for (unsigned i = 0; i < NumElts; i++)
13331 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13332
13333 return Res;
13334}
13335
13337 SelectionDAG &DAG) const {
13338 EVT VT = Node->getValueType(0);
13339 SDLoc dl(Node);
13340 bool isSigned = Node->getOpcode() == ISD::SREM;
13341 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
13342 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
13343 SDValue Dividend = Node->getOperand(0);
13344 SDValue Divisor = Node->getOperand(1);
13345 if (isOperationLegalOrCustom(DivRemOpc, VT)) {
13346 SDVTList VTs = DAG.getVTList(VT, VT);
13347 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
13348 return true;
13349 }
13350 if (isOperationLegalOrCustom(DivOpc, VT)) {
13351 // X % Y -> X-X/Y*Y
13352 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
13353 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
13354 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13355 return true;
13356 }
13357 return false;
13358}
13359
13361 SelectionDAG &DAG) const {
13362 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
13363 SDLoc dl(SDValue(Node, 0));
13364 SDValue Src = Node->getOperand(0);
13365
13366 // DstVT is the result type, while SatVT is the size to which we saturate
13367 EVT SrcVT = Src.getValueType();
13368 EVT DstVT = Node->getValueType(0);
13369
13370 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
13371 unsigned SatWidth = SatVT.getScalarSizeInBits();
13372 unsigned DstWidth = DstVT.getScalarSizeInBits();
13373 assert(SatWidth <= DstWidth &&
13374 "Expected saturation width smaller than result width");
13375
13376 // Determine minimum and maximum integer values and their corresponding
13377 // floating-point values.
13378 APInt MinInt, MaxInt;
13379 if (IsSigned) {
13380 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
13381 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
13382 } else {
13383 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
13384 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
13385 }
13386
13387 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
13388 // libcall emission cannot handle this. Large result types will fail.
13389 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
13390 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
13391 SrcVT = Src.getValueType();
13392 }
13393
13394 const fltSemantics &Sem = SrcVT.getFltSemantics();
13395 APFloat MinFloat(Sem);
13396 APFloat MaxFloat(Sem);
13397
13398 APFloat::opStatus MinStatus =
13399 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
13400 APFloat::opStatus MaxStatus =
13401 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
13402 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
13403 !(MaxStatus & APFloat::opStatus::opInexact);
13404
13405 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
13406 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
13407
13408 // If the integer bounds are exactly representable as floats and min/max are
13409 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
13410 // of comparisons and selects.
13411 auto EmitMinMax = [&](unsigned MinOpcode, unsigned MaxOpcode,
13412 bool MayPropagateNaN) {
13413 bool MinMaxLegal = isOperationLegalOrCustom(MinOpcode, SrcVT) &&
13414 isOperationLegalOrCustom(MaxOpcode, SrcVT);
13415 if (!MinMaxLegal)
13416 return SDValue();
13417
13418 SDValue Clamped = Src;
13419
13420 // Clamp Src by MinFloat from below. If !MayPropagateNaN and Src is NaN
13421 // then the result is MinFloat.
13422 Clamped = DAG.getNode(MaxOpcode, dl, SrcVT, Clamped, MinFloatNode);
13423 // Clamp by MaxFloat from above. If !MayPropagateNaN then NaN cannot occur.
13424 Clamped = DAG.getNode(MinOpcode, dl, SrcVT, Clamped, MaxFloatNode);
13425 // Convert clamped value to integer.
13426 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
13427 dl, DstVT, Clamped);
13428
13429 // If !MayPropagateNan and the conversion is unsigned case we're done,
13430 // because we mapped NaN to MinFloat, which will cast to zero.
13431 if (!MayPropagateNaN && !IsSigned)
13432 return FpToInt;
13433
13434 // Otherwise, select 0 if Src is NaN.
13435 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13436 EVT SetCCVT =
13437 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13438 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13439 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
13440 };
13441 if (AreExactFloatBounds) {
13442 if (SDValue Res = EmitMinMax(ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM,
13443 /*MayPropagateNaN=*/false))
13444 return Res;
13445 // These may propagate NaN for sNaN operands.
13446 if (SDValue Res =
13447 EmitMinMax(ISD::FMINNUM, ISD::FMAXNUM, /*MayPropagateNaN=*/true))
13448 return Res;
13449 // These always propagate NaN.
13450 if (SDValue Res =
13451 EmitMinMax(ISD::FMINIMUM, ISD::FMAXIMUM, /*MayPropagateNaN=*/true))
13452 return Res;
13453 }
13454
13455 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
13456 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
13457
13458 // Result of direct conversion. The assumption here is that the operation is
13459 // non-trapping and it's fine to apply it to an out-of-range value if we
13460 // select it away later.
13461 SDValue FpToInt =
13462 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
13463
13464 SDValue Select = FpToInt;
13465
13466 EVT SetCCVT =
13467 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13468
13469 // If Src ULT MinFloat, select MinInt. In particular, this also selects
13470 // MinInt if Src is NaN.
13471 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
13472 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
13473 // If Src OGT MaxFloat, select MaxInt.
13474 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
13475 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
13476
13477 // In the unsigned case we are done, because we mapped NaN to MinInt, which
13478 // is already zero.
13479 if (!IsSigned)
13480 return Select;
13481
13482 // Otherwise, select 0 if Src is NaN.
13483 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13484 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13485 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
13486}
13487
13489 const SDLoc &dl,
13490 SelectionDAG &DAG) const {
13491 EVT OperandVT = Op.getValueType();
13492 if (OperandVT.getScalarType() == ResultVT.getScalarType())
13493 return Op;
13494 EVT ResultIntVT = ResultVT.changeTypeToInteger();
13495 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13496 // can induce double-rounding which may alter the results. We can
13497 // correct for this using a trick explained in: Boldo, Sylvie, and
13498 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13499 // World Congress. 2005.
13500 SDValue Narrow = DAG.getFPExtendOrRound(Op, dl, ResultVT);
13501 SDValue NarrowAsWide = DAG.getFPExtendOrRound(Narrow, dl, OperandVT);
13502
13503 // We can keep the narrow value as-is if narrowing was exact (no
13504 // rounding error), the wide value was NaN (the narrow value is also
13505 // NaN and should be preserved) or if we rounded to the odd value.
13506 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, Narrow);
13507 SDValue One = DAG.getConstant(1, dl, ResultIntVT);
13508 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT);
13509 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One);
13510 EVT ResultIntVTCCVT = getSetCCResultType(
13511 DAG.getDataLayout(), *DAG.getContext(), And.getValueType());
13512 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT);
13513 // The result is already odd so we don't need to do anything.
13514 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE);
13515
13516 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13517 Op.getValueType());
13518 // We keep results which are exact, odd or NaN.
13519 SDValue KeepNarrow =
13520 DAG.getSetCC(dl, WideSetCCVT, Op, NarrowAsWide, ISD::SETUEQ);
13521 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd);
13522 // We morally performed a round-down if AbsNarrow is smaller than
13523 // AbsWide.
13524 SDValue AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op);
13525 SDValue AbsNarrowAsWide = DAG.getNode(ISD::FABS, dl, OperandVT, NarrowAsWide);
13526 SDValue NarrowIsRd =
13527 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT);
13528 // If the narrow value is odd or exact, pick it.
13529 // Otherwise, narrow is even and corresponds to either the rounded-up
13530 // or rounded-down value. If narrow is the rounded-down value, we want
13531 // the rounded-up value as it will be odd.
13532 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne);
13533 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust);
13534 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted);
13535 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op);
13536}
13537
13539 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!");
13540 SDValue Op = Node->getOperand(0);
13541 EVT VT = Node->getValueType(0);
13542 SDLoc dl(Node);
13543 if (VT.getScalarType() == MVT::bf16) {
13544 if (Node->getConstantOperandVal(1) == 1) {
13545 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0));
13546 }
13547 EVT OperandVT = Op.getValueType();
13548 SDValue IsNaN = DAG.getSetCC(
13549 dl,
13550 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT),
13551 Op, Op, ISD::SETUO);
13552
13553 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13554 // can induce double-rounding which may alter the results. We can
13555 // correct for this using a trick explained in: Boldo, Sylvie, and
13556 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13557 // World Congress. 2005.
13558 EVT F32 = VT.changeElementType(*DAG.getContext(), MVT::f32);
13559 EVT I32 = F32.changeTypeToInteger();
13560 Op = expandRoundInexactToOdd(F32, Op, dl, DAG);
13561 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op);
13562
13563 // Conversions should set NaN's quiet bit. This also prevents NaNs from
13564 // turning into infinities.
13565 SDValue NaN =
13566 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32));
13567
13568 // Factor in the contribution of the low 16 bits.
13569 SDValue One = DAG.getConstant(1, dl, I32);
13570 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op,
13571 DAG.getShiftAmountConstant(16, I32, dl));
13572 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One);
13573 SDValue RoundingBias =
13574 DAG.getNode(ISD::ADD, dl, I32, Lsb, DAG.getConstant(0x7fff, dl, I32));
13575 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias);
13576
13577 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into
13578 // 0x80000000.
13579 Op = DAG.getSelect(dl, I32, IsNaN, NaN, Add);
13580
13581 // Now that we have rounded, shift the bits into position.
13582 Op = DAG.getNode(ISD::SRL, dl, I32, Op,
13583 DAG.getShiftAmountConstant(16, I32, dl));
13584 EVT I16 = I32.changeElementType(*DAG.getContext(), MVT::i16);
13585 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op);
13586 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13587 }
13588 return SDValue();
13589}
13590
13592 SelectionDAG &DAG) const {
13593 assert((Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT ||
13594 Node->getOpcode() == ISD::VECTOR_SPLICE_RIGHT) &&
13595 "Unexpected opcode!");
13596 assert((Node->getValueType(0).isScalableVector() ||
13597 !isa<ConstantSDNode>(Node->getOperand(2))) &&
13598 "Fixed length vector types with constant offsets expected to use "
13599 "SHUFFLE_VECTOR!");
13600
13601 EVT VT = Node->getValueType(0);
13602 SDValue V1 = Node->getOperand(0);
13603 SDValue V2 = Node->getOperand(1);
13604 SDValue Offset = Node->getOperand(2);
13605 SDLoc DL(Node);
13606
13607 // Expand through memory thusly:
13608 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
13609 // Store V1, Ptr
13610 // Store V2, Ptr + sizeof(V1)
13611 // if (VECTOR_SPLICE_LEFT)
13612 // Ptr = Ptr + (Offset * sizeof(VT.Elt))
13613 // else
13614 // Ptr = Ptr + sizeof(V1) - (Offset * size(VT.Elt))
13615 // Res = Load Ptr
13616
13617 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
13618
13620 VT.getVectorElementCount() * 2);
13621 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
13622 EVT PtrVT = StackPtr.getValueType();
13623 auto &MF = DAG.getMachineFunction();
13624 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
13625 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
13626
13627 // Store the lo part of CONCAT_VECTORS(V1, V2)
13628 SDValue StoreV1 =
13629 DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo, Alignment);
13630 // Store the hi part of CONCAT_VECTORS(V1, V2)
13631 SDValue VTBytes = DAG.getTypeSize(DL, PtrVT, VT.getStoreSize());
13632 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, VTBytes);
13633 SDValue StoreV2 =
13634 DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo, Alignment);
13635
13636 // NOTE: TrailingBytes must be clamped so as not to read outside of V1:V2.
13637 SDValue EltByteSize =
13638 DAG.getTypeSize(DL, PtrVT, VT.getVectorElementType().getStoreSize());
13639 Offset = DAG.getZExtOrTrunc(Offset, DL, PtrVT);
13640 SDValue TrailingBytes = DAG.getNode(ISD::MUL, DL, PtrVT, Offset, EltByteSize);
13641
13642 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VTBytes);
13643
13644 if (Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT)
13645 StackPtr = DAG.getMemBasePlusOffset(StackPtr, TrailingBytes, DL);
13646 else
13647 StackPtr = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
13648
13649 // Load the spliced result
13650 return DAG.getLoad(VT, DL, StoreV2, StackPtr,
13652}
13653
13655 SelectionDAG &DAG) const {
13656 SDLoc DL(Node);
13657 SDValue Vec = Node->getOperand(0);
13658 SDValue Mask = Node->getOperand(1);
13659 SDValue Passthru = Node->getOperand(2);
13660
13661 EVT VecVT = Vec.getValueType();
13662 EVT ScalarVT = VecVT.getScalarType();
13663 EVT MaskVT = Mask.getValueType();
13664 EVT MaskScalarVT = MaskVT.getScalarType();
13665
13666 // Needs to be handled by targets that have scalable vector types.
13667 if (VecVT.isScalableVector())
13668 report_fatal_error("Cannot expand masked_compress for scalable vectors.");
13669
13670 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
13671 SDValue StackPtr = DAG.CreateStackTemporary(VecVT.getStoreSize(), Alignment);
13672 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
13673 MachinePointerInfo PtrInfo =
13675
13676 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout());
13677 SDValue Chain = DAG.getEntryNode();
13678 SDValue OutPos = DAG.getConstant(0, DL, PositionVT);
13679
13680 bool HasPassthru = !Passthru.isUndef();
13681
13682 // If we have a passthru vector, store it on the stack, overwrite the matching
13683 // positions and then re-write the last element that was potentially
13684 // overwritten even though mask[i] = false.
13685 if (HasPassthru)
13686 Chain = DAG.getStore(Chain, DL, Passthru, StackPtr, PtrInfo, Alignment);
13687
13688 SDValue LastWriteVal;
13689 APInt PassthruSplatVal;
13690 bool IsSplatPassthru =
13691 ISD::isConstantSplatVector(Passthru.getNode(), PassthruSplatVal);
13692
13693 if (IsSplatPassthru) {
13694 // As we do not know which position we wrote to last, we cannot simply
13695 // access that index from the passthru vector. So we first check if passthru
13696 // is a splat vector, to use any element ...
13697 LastWriteVal = DAG.getConstant(PassthruSplatVal, DL, ScalarVT);
13698 } else if (HasPassthru) {
13699 // ... if it is not a splat vector, we need to get the passthru value at
13700 // position = popcount(mask) and re-load it from the stack before it is
13701 // overwritten in the loop below.
13702 EVT PopcountVT = ScalarVT.changeTypeToInteger();
13703 SDValue Popcount = DAG.getNode(
13705 MaskVT.changeVectorElementType(*DAG.getContext(), MVT::i1), Mask);
13706 Popcount = DAG.getNode(
13708 MaskVT.changeVectorElementType(*DAG.getContext(), PopcountVT),
13709 Popcount);
13710 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount);
13711 SDValue LastElmtPtr =
13712 getVectorElementPointer(DAG, StackPtr, VecVT, Popcount);
13713 LastWriteVal = DAG.getLoad(
13714 ScalarVT, DL, Chain, LastElmtPtr,
13716 Chain = LastWriteVal.getValue(1);
13717 }
13718
13719 unsigned NumElms = VecVT.getVectorNumElements();
13720 for (unsigned I = 0; I < NumElms; I++) {
13721 SDValue ValI = DAG.getExtractVectorElt(DL, ScalarVT, Vec, I);
13722 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
13723 Chain = DAG.getStore(
13724 Chain, DL, ValI, OutPtr,
13726
13727 // Get the mask value and add it to the current output position. This
13728 // either increments by 1 if MaskI is true or adds 0 otherwise.
13729 // Freeze in case we have poison/undef mask entries.
13730 SDValue MaskI = DAG.getExtractVectorElt(DL, MaskScalarVT, Mask, I);
13731 MaskI = DAG.getFreeze(MaskI);
13732 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI);
13733 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI);
13734 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI);
13735
13736 if (HasPassthru && I == NumElms - 1) {
13737 SDValue EndOfVector =
13738 DAG.getConstant(VecVT.getVectorNumElements() - 1, DL, PositionVT);
13739 SDValue AllLanesSelected =
13740 DAG.getSetCC(DL, MVT::i1, OutPos, EndOfVector, ISD::CondCode::SETUGT);
13741 OutPos = DAG.getNode(ISD::UMIN, DL, PositionVT, OutPos, EndOfVector);
13742 OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
13743
13744 // Re-write the last ValI if all lanes were selected. Otherwise,
13745 // overwrite the last write it with the passthru value.
13746 LastWriteVal = DAG.getSelect(DL, ScalarVT, AllLanesSelected, ValI,
13747 LastWriteVal, SDNodeFlags::Unpredictable);
13748 Chain = DAG.getStore(
13749 Chain, DL, LastWriteVal, OutPtr,
13751 }
13752 }
13753
13754 return DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo, Alignment);
13755}
13756
13758 SDLoc DL(Node);
13759 EVT VT = Node->getValueType(0);
13760
13761 bool ZeroIsPoison = Node->getOpcode() == ISD::CTTZ_ELTS_ZERO_POISON;
13762 auto [Mask, StepVec] =
13763 getLegalMaskAndStepVector(Node->getOperand(0), ZeroIsPoison, DL, DAG);
13764
13765 // No legal step vector: split mask in half and recombine results.
13766 // LoNumElts uses the non-poison CTTZ_ELTS so its result is well-defined
13767 // (== LoNumElts when no active lane), allowing the SETNE comparison.
13768 // Result: (ResLo != LoNumElts) ? ResLo : (LoNumElts + ResHi)
13769 if (!StepVec) {
13770 EVT ResVT = Node->getValueType(0);
13771 auto [MaskLo, MaskHi] = DAG.SplitVector(Node->getOperand(0), DL);
13772 SDValue LoNumElts = DAG.getElementCount(
13773 DL, ResVT, MaskLo.getValueType().getVectorElementCount());
13774 SDValue ResLo = DAG.getNode(ISD::CTTZ_ELTS, DL, ResVT, MaskLo);
13775 SDValue ResHi = DAG.getNode(Node->getOpcode(), DL, ResVT, MaskHi);
13776 SDValue ResLoNotNumElts = DAG.getSetCC(
13777 DL, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ResVT),
13778 ResLo, LoNumElts, ISD::SETNE);
13779 // Per LangRef, ResVT must be wide enough to hold the total element count,
13780 // so the sum cannot wrap as an unsigned add. NSW is not guaranteed since
13781 // the count is only required to fit unsigned.
13782 SDValue Sum = DAG.getNode(ISD::ADD, DL, ResVT, LoNumElts, ResHi,
13784 return DAG.getSelect(DL, ResVT, ResLoNotNumElts, ResLo, Sum);
13785 }
13786
13787 EVT StepVecVT = StepVec.getValueType();
13788 EVT StepVT = StepVecVT.getVectorElementType();
13789
13790 // Promote the scalar result type early to avoid redundant zexts.
13792 StepVT = getTypeToTransformTo(*DAG.getContext(), StepVT);
13793
13794 SDValue VL =
13795 DAG.getElementCount(DL, StepVT, StepVecVT.getVectorElementCount());
13796 SDValue SplatVL = DAG.getSplat(StepVecVT, DL, VL);
13797 StepVec = DAG.getNode(ISD::SUB, DL, StepVecVT, SplatVL, StepVec);
13798 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
13799 SDValue Select = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
13801 StepVecVT.getVectorElementType(), Select);
13802 SDValue Sub = DAG.getNode(ISD::SUB, DL, StepVT, VL,
13803 DAG.getZExtOrTrunc(Max, DL, StepVT));
13804
13805 return DAG.getZExtOrTrunc(Sub, DL, VT);
13806}
13807
13809 SelectionDAG &DAG) const {
13810 SDLoc DL(N);
13811 SDValue Acc = N->getOperand(0);
13812 SDValue MulLHS = N->getOperand(1);
13813 SDValue MulRHS = N->getOperand(2);
13814 EVT AccVT = Acc.getValueType();
13815 EVT MulOpVT = MulLHS.getValueType();
13816
13817 EVT ExtMulOpVT =
13819 MulOpVT.getVectorElementCount());
13820
13821 unsigned ExtOpcLHS, ExtOpcRHS;
13822 switch (N->getOpcode()) {
13823 default:
13824 llvm_unreachable("Unexpected opcode");
13826 ExtOpcLHS = ExtOpcRHS = ISD::ZERO_EXTEND;
13827 break;
13829 ExtOpcLHS = ExtOpcRHS = ISD::SIGN_EXTEND;
13830 break;
13832 ExtOpcLHS = ExtOpcRHS = ISD::FP_EXTEND;
13833 break;
13834 }
13835
13836 if (ExtMulOpVT != MulOpVT) {
13837 MulLHS = DAG.getNode(ExtOpcLHS, DL, ExtMulOpVT, MulLHS);
13838 MulRHS = DAG.getNode(ExtOpcRHS, DL, ExtMulOpVT, MulRHS);
13839 }
13840 SDValue Input = MulLHS;
13841 if (N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA) {
13842 if (!llvm::isOneOrOneSplatFP(MulRHS))
13843 Input = DAG.getNode(ISD::FMUL, DL, ExtMulOpVT, MulLHS, MulRHS);
13844 } else if (!llvm::isOneOrOneSplat(MulRHS)) {
13845 Input = DAG.getNode(ISD::MUL, DL, ExtMulOpVT, MulLHS, MulRHS);
13846 }
13847
13848 unsigned Stride = AccVT.getVectorMinNumElements();
13849 unsigned ScaleFactor = MulOpVT.getVectorMinNumElements() / Stride;
13850
13851 // Collect all of the subvectors
13852 std::deque<SDValue> Subvectors = {Acc};
13853 for (unsigned I = 0; I < ScaleFactor; I++)
13854 Subvectors.push_back(DAG.getExtractSubvector(DL, AccVT, Input, I * Stride));
13855
13856 unsigned FlatNode =
13857 N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA ? ISD::FADD : ISD::ADD;
13858
13859 // Flatten the subvector tree
13860 while (Subvectors.size() > 1) {
13861 Subvectors.push_back(
13862 DAG.getNode(FlatNode, DL, AccVT, {Subvectors[0], Subvectors[1]}));
13863 Subvectors.pop_front();
13864 Subvectors.pop_front();
13865 }
13866
13867 assert(Subvectors.size() == 1 &&
13868 "There should only be one subvector after tree flattening");
13869
13870 return Subvectors[0];
13871}
13872
13873/// Given a store node \p StoreNode, return true if it is safe to fold that node
13874/// into \p FPNode, which expands to a library call with output pointers.
13876 SDNode *FPNode) {
13878 SmallVector<const SDNode *, 8> DeferredNodes;
13880
13881 // Skip FPNode use by StoreNode (that's the use we want to fold into FPNode).
13882 for (SDValue Op : StoreNode->ops())
13883 if (Op.getNode() != FPNode)
13884 Worklist.push_back(Op.getNode());
13885
13887 while (!Worklist.empty()) {
13888 const SDNode *Node = Worklist.pop_back_val();
13889 auto [_, Inserted] = Visited.insert(Node);
13890 if (!Inserted)
13891 continue;
13892
13893 if (MaxSteps > 0 && Visited.size() >= MaxSteps)
13894 return false;
13895
13896 // Reached the FPNode (would result in a cycle).
13897 // OR Reached CALLSEQ_START (would result in nested call sequences).
13898 if (Node == FPNode || Node->getOpcode() == ISD::CALLSEQ_START)
13899 return false;
13900
13901 if (Node->getOpcode() == ISD::CALLSEQ_END) {
13902 // Defer looking into call sequences (so we can check we're outside one).
13903 // We still need to look through these for the predecessor check.
13904 DeferredNodes.push_back(Node);
13905 continue;
13906 }
13907
13908 for (SDValue Op : Node->ops())
13909 Worklist.push_back(Op.getNode());
13910 }
13911
13912 // True if we're outside a call sequence and don't have the FPNode as a
13913 // predecessor. No cycles or nested call sequences possible.
13914 return !SDNode::hasPredecessorHelper(FPNode, Visited, DeferredNodes,
13915 MaxSteps);
13916}
13917
13919 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
13921 std::optional<unsigned> CallRetResNo) const {
13922 if (LC == RTLIB::UNKNOWN_LIBCALL)
13923 return false;
13924
13925 RTLIB::LibcallImpl LibcallImpl = getLibcallImpl(LC);
13926 if (LibcallImpl == RTLIB::Unsupported)
13927 return false;
13928
13929 LLVMContext &Ctx = *DAG.getContext();
13930 EVT VT = Node->getValueType(0);
13931 unsigned NumResults = Node->getNumValues();
13932
13933 // Find users of the node that store the results (and share input chains). The
13934 // destination pointers can be used instead of creating stack allocations.
13935 SDValue StoresInChain;
13936 SmallVector<StoreSDNode *, 2> ResultStores(NumResults);
13937 for (SDNode *User : Node->users()) {
13939 continue;
13940 auto *ST = cast<StoreSDNode>(User);
13941 SDValue StoreValue = ST->getValue();
13942 unsigned ResNo = StoreValue.getResNo();
13943 // Ensure the store corresponds to an output pointer.
13944 if (CallRetResNo == ResNo)
13945 continue;
13946 // Ensure the store to the default address space and not atomic or volatile.
13947 if (!ST->isSimple() || ST->getAddressSpace() != 0)
13948 continue;
13949 // Ensure all store chains are the same (so they don't alias).
13950 if (StoresInChain && ST->getChain() != StoresInChain)
13951 continue;
13952 // Ensure the store is properly aligned.
13953 Type *StoreType = StoreValue.getValueType().getTypeForEVT(Ctx);
13954 if (ST->getAlign() <
13955 DAG.getDataLayout().getABITypeAlign(StoreType->getScalarType()))
13956 continue;
13957 // Avoid:
13958 // 1. Creating cyclic dependencies.
13959 // 2. Expanding the node to a call within a call sequence.
13961 continue;
13962 ResultStores[ResNo] = ST;
13963 StoresInChain = ST->getChain();
13964 }
13965
13966 ArgListTy Args;
13967
13968 // Pass the arguments.
13969 for (const SDValue &Op : Node->op_values()) {
13970 EVT ArgVT = Op.getValueType();
13971 Type *ArgTy = ArgVT.getTypeForEVT(Ctx);
13972 Args.emplace_back(Op, ArgTy);
13973 }
13974
13975 // Pass the output pointers.
13976 SmallVector<SDValue, 2> ResultPtrs(NumResults);
13978 for (auto [ResNo, ST] : llvm::enumerate(ResultStores)) {
13979 if (ResNo == CallRetResNo)
13980 continue;
13981 EVT ResVT = Node->getValueType(ResNo);
13982 SDValue ResultPtr = ST ? ST->getBasePtr() : DAG.CreateStackTemporary(ResVT);
13983 ResultPtrs[ResNo] = ResultPtr;
13984 Args.emplace_back(ResultPtr, PointerTy);
13985 }
13986
13987 SDLoc DL(Node);
13988
13990 // Pass the vector mask (if required).
13991 EVT MaskVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
13992 SDValue Mask = DAG.getBoolConstant(true, DL, MaskVT, VT);
13993 Args.emplace_back(Mask, MaskVT.getTypeForEVT(Ctx));
13994 }
13995
13996 Type *RetType = CallRetResNo.has_value()
13997 ? Node->getValueType(*CallRetResNo).getTypeForEVT(Ctx)
13998 : Type::getVoidTy(Ctx);
13999 SDValue InChain = StoresInChain ? StoresInChain : DAG.getEntryNode();
14000 SDValue Callee =
14001 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
14003 CLI.setDebugLoc(DL).setChain(InChain).setLibCallee(
14004 getLibcallImplCallingConv(LibcallImpl), RetType, Callee, std::move(Args));
14005
14006 auto [Call, CallChain] = LowerCallTo(CLI);
14007
14008 for (auto [ResNo, ResultPtr] : llvm::enumerate(ResultPtrs)) {
14009 if (ResNo == CallRetResNo) {
14010 Results.push_back(Call);
14011 continue;
14012 }
14013 MachinePointerInfo PtrInfo;
14014 SDValue LoadResult = DAG.getLoad(Node->getValueType(ResNo), DL, CallChain,
14015 ResultPtr, PtrInfo);
14016 SDValue OutChain = LoadResult.getValue(1);
14017
14018 if (StoreSDNode *ST = ResultStores[ResNo]) {
14019 // Replace store with the library call.
14020 DAG.ReplaceAllUsesOfValueWith(SDValue(ST, 0), OutChain);
14021 PtrInfo = ST->getPointerInfo();
14022 } else {
14024 DAG.getMachineFunction(),
14025 cast<FrameIndexSDNode>(ResultPtr)->getIndex());
14026 }
14027
14028 Results.push_back(LoadResult);
14029 }
14030
14031 return true;
14032}
14033
14035 SDValue &LHS, SDValue &RHS,
14036 SDValue &CC, SDValue Mask,
14037 SDValue EVL, bool &NeedInvert,
14038 const SDLoc &dl, SDValue &Chain,
14039 bool IsSignaling) const {
14040 MVT OpVT = LHS.getSimpleValueType();
14041 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
14042 NeedInvert = false;
14043 assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset");
14044 bool IsNonVP = !EVL;
14045 switch (getCondCodeAction(CCCode, OpVT)) {
14046 default:
14047 llvm_unreachable("Unknown condition code action!");
14049 // Nothing to do.
14050 break;
14053 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14054 std::swap(LHS, RHS);
14055 CC = DAG.getCondCode(InvCC);
14056 return true;
14057 }
14058 // Swapping operands didn't work. Try inverting the condition.
14059 bool NeedSwap = false;
14060 InvCC = getSetCCInverse(CCCode, OpVT);
14061 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) {
14062 // If inverting the condition is not enough, try swapping operands
14063 // on top of it.
14064 InvCC = ISD::getSetCCSwappedOperands(InvCC);
14065 NeedSwap = true;
14066 }
14067 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14068 CC = DAG.getCondCode(InvCC);
14069 NeedInvert = true;
14070 if (NeedSwap)
14071 std::swap(LHS, RHS);
14072 return true;
14073 }
14074
14075 // Special case: expand i1 comparisons using logical operations.
14076 if (OpVT == MVT::i1) {
14077 SDValue Ret;
14078 switch (CCCode) {
14079 default:
14080 llvm_unreachable("Unknown integer setcc!");
14081 case ISD::SETEQ: // X == Y --> ~(X ^ Y)
14082 Ret = DAG.getNOT(dl, DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS),
14083 MVT::i1);
14084 break;
14085 case ISD::SETNE: // X != Y --> (X ^ Y)
14086 Ret = DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS);
14087 break;
14088 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
14089 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
14090 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, RHS,
14091 DAG.getNOT(dl, LHS, MVT::i1));
14092 break;
14093 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
14094 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
14095 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, LHS,
14096 DAG.getNOT(dl, RHS, MVT::i1));
14097 break;
14098 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
14099 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
14100 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, RHS,
14101 DAG.getNOT(dl, LHS, MVT::i1));
14102 break;
14103 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
14104 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
14105 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, LHS,
14106 DAG.getNOT(dl, RHS, MVT::i1));
14107 break;
14108 }
14109
14110 LHS = DAG.getZExtOrTrunc(Ret, dl, VT);
14111 RHS = SDValue();
14112 CC = SDValue();
14113 return true;
14114 }
14115
14117 unsigned Opc = 0;
14118 switch (CCCode) {
14119 default:
14120 llvm_unreachable("Don't know how to expand this condition!");
14121 case ISD::SETUO:
14122 if (isCondCodeLegal(ISD::SETUNE, OpVT)) {
14123 CC1 = ISD::SETUNE;
14124 CC2 = ISD::SETUNE;
14125 Opc = ISD::OR;
14126 break;
14127 }
14129 "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
14130 NeedInvert = true;
14131 [[fallthrough]];
14132 case ISD::SETO:
14134 "If SETO is expanded, SETOEQ must be legal!");
14135 CC1 = ISD::SETOEQ;
14136 CC2 = ISD::SETOEQ;
14137 Opc = ISD::AND;
14138 break;
14139 case ISD::SETONE:
14140 case ISD::SETUEQ:
14141 // If the SETUO or SETO CC isn't legal, we might be able to use
14142 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
14143 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
14144 // the operands.
14145 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14146 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) ||
14147 isCondCodeLegal(ISD::SETOLT, OpVT))) {
14148 CC1 = ISD::SETOGT;
14149 CC2 = ISD::SETOLT;
14150 Opc = ISD::OR;
14151 NeedInvert = ((unsigned)CCCode & 0x8U);
14152 break;
14153 }
14154 [[fallthrough]];
14155 case ISD::SETOEQ:
14156 case ISD::SETOGT:
14157 case ISD::SETOGE:
14158 case ISD::SETOLT:
14159 case ISD::SETOLE:
14160 case ISD::SETUNE:
14161 case ISD::SETUGT:
14162 case ISD::SETUGE:
14163 case ISD::SETULT:
14164 case ISD::SETULE:
14165 // If we are floating point, assign and break, otherwise fall through.
14166 if (!OpVT.isInteger()) {
14167 // We can use the 4th bit to tell if we are the unordered
14168 // or ordered version of the opcode.
14169 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14170 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
14171 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
14172 break;
14173 }
14174 // Fallthrough if we are unsigned integer.
14175 [[fallthrough]];
14176 case ISD::SETLE:
14177 case ISD::SETGT:
14178 case ISD::SETGE:
14179 case ISD::SETLT:
14180 case ISD::SETNE:
14181 case ISD::SETEQ:
14182 // If all combinations of inverting the condition and swapping operands
14183 // didn't work then we have no means to expand the condition.
14184 llvm_unreachable("Don't know how to expand this condition!");
14185 }
14186
14187 SDValue SetCC1, SetCC2;
14188 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
14189 // If we aren't the ordered or unorder operation,
14190 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
14191 if (IsNonVP) {
14192 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
14193 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
14194 } else {
14195 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL);
14196 SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL);
14197 }
14198 } else {
14199 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
14200 if (IsNonVP) {
14201 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
14202 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
14203 } else {
14204 SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL);
14205 SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL);
14206 }
14207 }
14208 if (Chain)
14209 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
14210 SetCC2.getValue(1));
14211 if (IsNonVP)
14212 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
14213 else {
14214 // Transform the binary opcode to the VP equivalent.
14215 assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode");
14216 Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND;
14217 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL);
14218 }
14219 RHS = SDValue();
14220 CC = SDValue();
14221 return true;
14222 }
14223 }
14224 return false;
14225}
14226
14228 SelectionDAG &DAG) const {
14229 EVT VT = Node->getValueType(0);
14230 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be
14231 // split into two equal parts.
14232 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2))
14233 return SDValue();
14234
14235 // Restrict expansion to cases where both parts can be concatenated.
14236 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
14237 if (LoVT != HiVT || !isTypeLegal(LoVT))
14238 return SDValue();
14239
14240 SDLoc DL(Node);
14241 unsigned Opcode = Node->getOpcode();
14242
14243 // Don't expand if the result is likely to be unrolled anyway.
14244 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT))
14245 return SDValue();
14246
14247 SmallVector<SDValue, 4> LoOps, HiOps;
14248 for (const SDValue &V : Node->op_values()) {
14249 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT);
14250 LoOps.push_back(Lo);
14251 HiOps.push_back(Hi);
14252 }
14253
14254 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVT, LoOps, Node->getFlags());
14255 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVT, HiOps, Node->getFlags());
14256 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi);
14257}
14258
14260 const SDLoc &DL,
14261 EVT InVecVT, SDValue EltNo,
14262 LoadSDNode *OriginalLoad,
14263 SelectionDAG &DAG) const {
14264 assert(OriginalLoad->isSimple());
14265
14266 EVT VecEltVT = InVecVT.getVectorElementType();
14267
14268 // If the vector element type is not a multiple of a byte then we are unable
14269 // to correctly compute an address to load only the extracted element as a
14270 // scalar.
14271 if (!VecEltVT.isByteSized())
14272 return SDValue();
14273
14274 ISD::LoadExtType ExtTy =
14275 ResultVT.bitsGT(VecEltVT) ? ISD::EXTLOAD : ISD::NON_EXTLOAD;
14276 if (!isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14277 return SDValue();
14278
14279 std::optional<unsigned> ByteOffset;
14280 Align Alignment = OriginalLoad->getAlign();
14282 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14283 int Elt = ConstEltNo->getZExtValue();
14284 ByteOffset = VecEltVT.getSizeInBits() * Elt / 8;
14285 MPI = OriginalLoad->getPointerInfo().getWithOffset(*ByteOffset);
14286 Alignment = commonAlignment(Alignment, *ByteOffset);
14287 } else {
14288 // Discard the pointer info except the address space because the memory
14289 // operand can't represent this new access since the offset is variable.
14290 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
14291 Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
14292 }
14293
14294 if (!shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT, ByteOffset))
14295 return SDValue();
14296
14297 unsigned IsFast = 0;
14298 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
14299 OriginalLoad->getAddressSpace(), Alignment,
14300 OriginalLoad->getMemOperand()->getFlags(), &IsFast) ||
14301 !IsFast)
14302 return SDValue();
14303
14304 // The original DAG loaded the entire vector from memory, so arithmetic
14305 // within it must be inbounds.
14307 DAG, OriginalLoad->getBasePtr(), InVecVT, EltNo);
14308
14309 // We are replacing a vector load with a scalar load. The new load must have
14310 // identical memory op ordering to the original.
14311 SDValue Load;
14312 if (ResultVT.bitsGT(VecEltVT)) {
14313 // If the result type of vextract is wider than the load, then issue an
14314 // extending load instead.
14315 ISD::LoadExtType ExtType =
14316 isLoadLegal(ResultVT, VecEltVT, Alignment,
14317 OriginalLoad->getAddressSpace(), ISD::ZEXTLOAD, false)
14319 : ISD::EXTLOAD;
14320 Load = DAG.getExtLoad(ExtType, DL, ResultVT, OriginalLoad->getChain(),
14321 NewPtr, MPI, VecEltVT, Alignment,
14322 OriginalLoad->getMemOperand()->getFlags(),
14323 OriginalLoad->getAAInfo());
14324 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14325 } else {
14326 // The result type is narrower or the same width as the vector element
14327 Load = DAG.getLoad(VecEltVT, DL, OriginalLoad->getChain(), NewPtr, MPI,
14328 Alignment, OriginalLoad->getMemOperand()->getFlags(),
14329 OriginalLoad->getAAInfo());
14330 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14331 if (ResultVT.bitsLT(VecEltVT))
14332 Load = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, Load);
14333 else
14334 Load = DAG.getBitcast(ResultVT, Load);
14335 }
14336
14337 return Load;
14338}
14339
14340// Set type id for call site info and metadata 'call_target'.
14341// We are filtering for:
14342// a) The call-graph-section use case that wants to know about indirect
14343// calls, or
14344// b) We want to annotate indirect calls.
14346 const CallBase *CB, MachineFunction &MF,
14347 MachineFunction::CallSiteInfo &CSInfo) const {
14348 if (CB && CB->isIndirectCall() &&
14351 CSInfo = MachineFunction::CallSiteInfo(*CB);
14352}
return SDValue()
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
constexpr LLT F32
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
block Block Frequency Analysis
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static std::optional< bool > isBigEndian(const SmallDenseMap< int64_t, int64_t, 8 > &MemOffset2Idx, int64_t LowestIdx)
Given a map from byte offsets in memory to indices in a load/store, determine if that map corresponds...
static bool isSigned(unsigned Opcode)
#define _
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, const APInt &Demanded)
Check to see if the specified operand of the specified instruction is a constant integer.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
lazy value info
static bool isNonZeroModBitWidthOrUndef(const MachineRegisterInfo &MRI, Register Reg, unsigned BW)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
static bool isUndef(const MachineInstr &MI)
Register const TargetRegisterInfo * TRI
#define T
#define T1
uint64_t High
#define P(N)
Function const char * Passes
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
Contains matchers for matching SelectionDAG nodes and values.
This file contains some templates that are useful if you are working with the STL at all.
static cl::opt< unsigned > MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192), cl::desc("DAG combiner limit number of steps when searching DAG " "for predecessor nodes"))
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static std::pair< SDValue, SDValue > getLegalMaskAndStepVector(SDValue Mask, bool ZeroIsPoison, SDLoc DL, SelectionDAG &DAG)
Returns a type-legalized version of Mask as the first item in the pair.
static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, const SDLoc &dl, SelectionDAG &DAG)
static bool lowerImmediateIfPossible(TargetLowering::ConstraintPair &P, SDValue Op, SelectionDAG *DAG, const TargetLowering &TLI)
If we have an immediate, see if we can lower it.
static SDValue expandVPFunnelShift(SDNode *Node, SelectionDAG &DAG)
static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG, const APInt &UndefOp0, const APInt &UndefOp1)
Given a vector binary operation and known undefined elements for each input operand,...
static SDValue BuildExactUDIV(const TargetLowering &TLI, SDNode *N, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created)
Given an exact UDIV by a constant, create a multiplication with the multiplicative inverse of the con...
static SDValue isSpecificZeroAfterMaybeRounding(SelectionDAG &DAG, const TargetLowering &TLI, const SDLoc &DL, SDValue Val, FPClassTest FPClass)
static bool canNarrowCLMULToLegal(const TargetLowering &TLI, LLVMContext &Ctx, EVT VT, unsigned HalveDepth=0, unsigned TotalDepth=0)
Check if CLMUL on VT can eventually reach a type with legal CLMUL through a chain of halving decompos...
static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, EVT VecVT, const SDLoc &dl, ElementCount SubEC)
static unsigned getConstraintPiority(TargetLowering::ConstraintType CT)
Return a number indicating our preference for chosing a type of constraint over another,...
static std::optional< bool > isFCmpEqualZero(FPClassTest Test, const fltSemantics &Semantics, const MachineFunction &MF)
Returns a true value if if this FPClassTest can be performed with an ordered fcmp to 0,...
static bool canFoldStoreIntoLibCallOutputPointers(StoreSDNode *StoreNode, SDNode *FPNode)
Given a store node StoreNode, return true if it is safe to fold that node into FPNode,...
static void turnVectorIntoSplatVector(MutableArrayRef< SDValue > Values, std::function< bool(SDValue)> Predicate, SDValue AlternativeReplacement=SDValue())
If all values in Values that don't match the predicate are same 'splat' value, then replace all value...
static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT)
static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, const SDLoc &dl, SelectionDAG &DAG)
static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created)
Given an exact SDIV by a constant, create a multiplication with the multiplicative inverse of the con...
static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT, SDValue N0, const APInt &C1, ISD::CondCode Cond, const SDLoc &dl, SelectionDAG &DAG)
static SDValue combineShiftToAVG(SDValue Op, TargetLowering::TargetLoweringOpt &TLO, const TargetLowering &TLI, const APInt &DemandedBits, const APInt &DemandedElts, unsigned Depth)
This file describes how to lower LLVM code to machine code.
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT, SelectionDAG &DAG)
Scalarize a vector store, bitcasting to TargetVT to determine the scalar type.
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static LLVM_ABI const llvm::fltSemantics & EnumToSemantics(Semantics S)
Definition APFloat.cpp:123
static constexpr roundingMode rmTowardZero
Definition APFloat.h:349
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:247
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
Definition APFloat.cpp:303
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:345
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:239
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:280
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:361
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1433
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1244
APInt bitcastToAPInt() const
Definition APFloat.h:1457
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1224
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1184
void changeSign()
Definition APFloat.h:1383
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1195
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1599
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1793
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1431
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:450
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:230
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1416
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1076
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1537
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:968
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1355
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1191
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:259
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1692
void setSignBit()
Set the sign bit to 1.
Definition APInt.h:1365
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:217
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1258
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1421
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:841
void negate()
Negate this APInt in place.
Definition APInt.h:1493
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1664
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1623
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:652
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1556
unsigned countLeadingZeros() const
Definition APInt.h:1631
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:357
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:398
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition APInt.h:1460
unsigned logBase2() const
Definition APInt.h:1786
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:476
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:834
void setAllBits()
Set every bit to 1.
Definition APInt.h:1344
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1300
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:406
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:335
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1159
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1028
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1392
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:880
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1266
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1442
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:297
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1413
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:483
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:390
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:287
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
void clearHighBits(unsigned hiBits)
Set top hiBits bits to 0.
Definition APInt.h:1467
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1587
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:865
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:858
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1681
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1230
void setBitVal(unsigned BitPosition, bool BitValue)
Set a given bit to a given value.
Definition APInt.h:1368
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI ConstantSDNode * getConstantSplatNode(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted constant or null if this is not a constant splat.
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
This class represents a function call, abstracting a target machine's calling convention.
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This class represents a range of values.
const APInt & getAPIntValue() const
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:315
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:328
const GlobalValue * getGlobal() const
Module * getParent()
Get the module that this global value is contained inside of...
std::vector< std::string > ConstraintCodeVector
Definition InlineAsm.h:104
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
This class is used to represent ISD::LOAD nodes.
const SDValue & getBasePtr() const
Context object for machine code objects.
Definition MCContext.h:83
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
iterator_range< regclass_iterator > regclasses() const
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:213
Machine Value Type.
SimpleValueType SimpleTy
bool isInteger() const
Return true if this is an integer or a vector integer type.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static MVT getIntegerVT(unsigned BitWidth)
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
Flags getFlags() const
Return the raw flags of the source value,.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI MCRegister getLiveInPhysReg(Register VReg) const
getLiveInPhysReg - If VReg is a live-in virtual register, return the corresponding live-in physical r...
unsigned getAddressSpace() const
Return the address space for the associated pointer.
Align getAlign() const
AAMDNodes getAAInfo() const
Returns the AA info that describes the dereference.
bool isSimple() const
Returns true if the memory operation is neither atomic or volatile.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
const SDValue & getChain() const
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Definition Module.h:521
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Class to represent pointers.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
ArrayRef< SDUse > ops() const
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
SDNodeFlags getFlags() const
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
bool use_empty() const
Return true if there are no nodes using value ResNo of Node.
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getElementCount(const SDLoc &DL, EVT VT, ElementCount EC)
bool willNotOverflowAdd(bool IsSigned, SDValue N0, SDValue N1) const
Determine if the result of the addition of 2 nodes can never overflow.
LLVM_ABI Align getReducedAlign(EVT VT, bool UseABI)
In most cases this function returns the ABI alignment for a given type, except for illegal vector typ...
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI bool isKnownNeverLogicalZero(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
Test whether the given floating point SDValue (or all elements of it, if it is a vector) is known to ...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT, unsigned Opcode)
Convert Op, which must be of integer type, to the integer type VT, by either any/sign/zero-extending ...
SDValue getExtractVectorElt(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Extract element at Idx from Vec.
LLVM_ABI unsigned ComputeMaxSignificantBits(SDValue Op, unsigned Depth=0) const
Get the upper bound on bit size for this Value Op as a signed integer.
LLVM_ABI SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond, const SDLoc &dl, SDNodeFlags Flags={})
Constant fold a setcc to true or false.
bool isKnownNeverSNaN(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
LLVM_ABI SDValue getFreeze(SDValue V)
Return a freeze using the SDLoc of the value operand.
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue makeEquivalentMemoryOrdering(SDValue OldChain, SDValue NewMemOpChain)
If an existing load has uses of its chain, create a token factor node with that chain and the new mem...
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI SDValue getJumpTableDebugInfo(int JTI, SDValue Chain, const SDLoc &DL)
LLVM_ABI std::optional< unsigned > getValidMaximumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getVScale(const SDLoc &DL, EVT VT, APInt MulImm)
Return a node that represents the runtime scaling 'MulImm * RuntimeVL'.
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
static LLVM_ABI unsigned getHasPredecessorMaxSteps()
SDValue getExtractSubvector(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Return the VT typed sub-vector of Vec at Idx.
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr)
Loads are not normal binary operators: their result type is not determined by their operands,...
SDValue getInsertSubvector(const SDLoc &DL, SDValue Vec, SDValue SubVec, unsigned Idx)
Insert SubVec at the Idx element of Vec.
LLVM_ABI SDValue getStepVector(const SDLoc &DL, EVT ResVT, const APInt &StepVal)
Returns a vector of type ResVT whose elements contain the linear sequence <0, Step,...
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
bool willNotOverflowSub(bool IsSigned, SDValue N0, SDValue N1) const
Determine if the result of the sub of 2 nodes can never overflow.
LLVM_ABI bool shouldOptForSize() const
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
const TargetLowering & getTargetLoweringInfo() const
static constexpr unsigned MaxRecursionDepth
LLVM_ABI std::pair< EVT, EVT > GetSplitDestVTs(const EVT &VT) const
Compute the VTs needed for the low/hi parts of a type which is split (or expanded) into two not neces...
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
LLVM_ABI std::optional< unsigned > getValidShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has a uniform shift amount that is less than the element bit-width of the shi...
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
const DataLayout & getDataLayout() const
LLVM_ABI bool doesNodeExist(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops)
Check if a node exists without modifying its flags.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, bool isTargetGA=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI SDValue getTypeSize(const SDLoc &DL, EVT VT, TypeSize TS)
LLVM_ABI std::pair< SDValue, SDValue > SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the vector with EXTRACT_SUBVECTOR using the provided VTs and return the low/high part.
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build SelectCC's if you just have an ISD::CondCode instead of an...
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI bool isIdentityElement(unsigned Opc, SDNodeFlags Flags, SDValue V, unsigned OperandNo, unsigned Depth=0) const
Returns true if V is an identity element of Opc with Flags.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(SDValue Op, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, unsigned Depth=0) const
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
LLVM_ABI bool isKnownNeverZero(SDValue Op, unsigned Depth=0) const
Test whether the given SDValue is known to contain non-zero value(s).
LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SDNodeFlags Flags=SDNodeFlags())
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
LLVM_ABI bool isKnownNeverNaN(SDValue Op, const APInt &DemandedElts, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue (or all elements of it, if it is a vector) is known to never be NaN in...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT)
Create a true or false constant of type VT using the target's BooleanContent for type OpVT.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
SDValue getPOISON(EVT VT)
Return a POISON node. POISON does not have a useful SDLoc.
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI bool isKnownToBeAPowerOfTwo(SDValue Val, bool OrZero=false, unsigned Depth=0) const
Test if the given value is known to have exactly one bit set.
SDValue getSetCCVP(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Mask, SDValue EVL)
Helper function to make it easier to build VP_SETCCs if you just have an ISD::CondCode instead of an ...
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
SDValue getSplat(EVT VT, const SDLoc &DL, SDValue Op)
Returns a node representing a splat of one value into all lanes of the provided vector type.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
static void commuteMask(MutableArrayRef< int > Mask)
Change values in a shuffle permute mask assuming the two vector operands have swapped position.
size_type size() const
Definition SmallPtrSet.h:99
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
iterator end() const
Definition StringRef.h:116
Class to represent struct types.
LLVM_ABI void setAttributes(const CallBase *Call, unsigned ArgIdx)
Set CallLoweringInfo attribute flags based on a call instruction and called function attributes.
bool isOperationExpand(unsigned Op, EVT VT) const
Return true if the specified operation is illegal on this target or unlikely to be made legal with cu...
unsigned getBitWidthForCttzElements(EVT RetVT, ElementCount EC, bool ZeroIsPoison, const ConstantRange *VScaleRange) const
Return the minimum number of bits required to hold the maximum possible number of trailing zero vecto...
virtual bool isShuffleMaskLegal(ArrayRef< int >, EVT) const
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations,...
virtual bool shouldRemoveRedundantExtend(SDValue Op) const
Return true (the default) if it is profitable to remove a sext_inreg(x) where the sext is redundant,...
virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT, std::optional< unsigned > ByteOffset=std::nullopt) const
Return true if it is profitable to reduce a load to a smaller type.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
virtual bool preferSelectsOverBooleanArithmetic(EVT VT) const
Should we prefer selects to doing arithmetic on boolean types.
virtual bool isLegalICmpImmediate(int64_t) const
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
virtual MVT::SimpleValueType getCmpLibcallReturnType() const
Return the ValueType for comparison libcalls.
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
virtual bool isSafeMemOpType(MVT) const
Returns true if it's safe to use load / store of the specified type to expand memcpy / memset inline.
const TargetMachine & getTargetMachine() const
virtual bool isCtpopFast(EVT VT) const
Return true if ctpop instruction is fast.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
bool isPaddedAtMostSignificantBitsWhenStored(EVT VT) const
Indicates if any padding is guaranteed to go at the most significant bits when storing the type to me...
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
virtual bool hasBitTest(SDValue X, SDValue Y) const
Return true if the target has a bit-test instruction: (X & (1 << Y)) ==/!= 0 This knowledge can be us...
EVT getLegalTypeToTransformTo(LLVMContext &Context, EVT VT) const
Perform getTypeToTransformTo repeatedly until a legal type is obtained.
LegalizeAction getCondCodeAction(ISD::CondCode CC, MVT VT) const
Return how the condition code should be treated: either it is legal, needs to be expanded to some oth...
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall implementation.
virtual bool isCommutativeBinOp(unsigned Opcode) const
Returns true if the opcode is a commutative binary operation.
virtual bool isFPImmLegal(const APFloat &, EVT, bool ForCodeSize=false) const
Returns true if the target can instruction select the specified FP immediate natively.
virtual bool shouldTransformSignedTruncationCheck(EVT XVT, unsigned KeptBits) const
Should we tranform the IR-optimal check for whether given truncation down into KeptBits would be trun...
bool isLegalRC(const TargetRegisterInfo &TRI, const TargetRegisterClass &RC) const
Return true if the value types that can be represented by the specified register class are all legal.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not.
EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const
Returns the type for the shift amount of a shift opcode.
virtual bool shouldExtendTypeInLibCall(EVT Type) const
Returns true if arguments should be extended in lib calls.
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const
Return true if creating a shift of the type by the given amount is not profitable.
virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const
Return true if an fpext operation is free (for instance, because single-precision floating-point numb...
virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const
Return the ValueType of the result of SETCC operations.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
BooleanContent getBooleanContents(bool isVec, bool isFloat) const
For targets without i1 registers, this gives the nature of the high-bits of boolean values held in ty...
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal for a comparison of the specified types on this ...
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
ISD::CondCode getSoftFloatCmpLibcallPredicate(RTLIB::LibcallImpl Call) const
Get the comparison predicate that's to be used to test the result of the comparison libcall against z...
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
TargetLoweringBase(const TargetMachine &TM, const TargetSubtargetInfo &STI)
NOTE: The TargetMachine owns TLOF.
virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const
Return the maximum number of "x & (x - 1)" operations that can be done instead of deferring to a cust...
virtual bool shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, unsigned OldShiftOpcode, unsigned NewShiftOpcode, SelectionDAG &DAG) const
Given the pattern (X & (C l>>/<< Y)) ==/!= 0 return true if it should be transformed into: ((X <</l>>...
BooleanContent
Enum that describes how the target represents true/false values.
virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const
Return true if integer divide is usually cheaper than a sequence of several shifts,...
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
Return true if the target supports a memory access of this type for the given address space and align...
virtual bool hasAndNotCompare(SDValue Y) const
Return true if the target should transform: (X & Y) == Y ---> (~X & Y) == 0 (X & Y) !...
virtual bool isNarrowingProfitable(SDNode *N, EVT SrcVT, EVT DestVT) const
Return true if it's profitable to narrow operations of type SrcVT to DestVT.
virtual bool isBinOp(unsigned Opcode) const
Return true if the node is a math/logic binary operator.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Get the libcall impl routine name for the specified libcall.
virtual bool isCtlzFast() const
Return true if ctlz instruction is fast.
virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT, bool IsSigned) const
Return true if it is more correct/profitable to use strict FP_TO_INT conversion operations - canonica...
NegatibleCost
Enum that specifies when a float negation is beneficial.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
std::vector< ArgListEntry > ArgListTy
virtual EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &) const
Returns the target specific optimal type for load and store operations as a result of memset,...
virtual EVT getAsmOperandValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal or custom for a comparison of the specified type...
bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal on this target.
MVT getRegisterType(MVT VT) const
Return the type of registers that this ValueType will eventually require.
virtual bool isFAbsFree(EVT VT) const
Return true if an fabs operation is free to the point where it is never worthwhile to replace it with...
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
MulExpansionKind
Enum that specifies when a multiplication should be expanded.
static ISD::NodeType getExtendForContent(BooleanContent Content)
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
SDValue expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT.
SDValue buildSDIVPow2WithCMov(SDNode *N, const APInt &Divisor, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created) const
Build sdiv by power-of-2 with conditional move instructions Ref: "Hacker's Delight" by Henry Warren 1...
virtual ConstraintWeight getMultipleConstraintMatchWeight(AsmOperandInfo &info, int maIndex) const
Examine constraint type and operand type and determine a weight value.
bool expandMultipleResultFPLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node, SmallVectorImpl< SDValue > &Results, std::optional< unsigned > CallRetResNo={}) const
Expands a node with multiple results to an FP or vector libcall.
SDValue expandVPCTLZ(SDNode *N, SelectionDAG &DAG) const
Expand VP_CTLZ/VP_CTLZ_ZERO_POISON nodes.
bool expandMULO(SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]MULO.
bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, SelectionDAG &DAG, MulExpansionKind Kind, SDValue LL=SDValue(), SDValue LH=SDValue(), SDValue RL=SDValue(), SDValue RH=SDValue()) const
Expand a MUL into two nodes.
SmallVector< ConstraintPair > ConstraintGroup
virtual const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase,...
virtual Align computeKnownAlignForTargetInstr(GISelValueTracking &Analysis, Register R, const MachineRegisterInfo &MRI, unsigned Depth=0) const
Determine the known alignment for the pointer value R.
bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask, APInt &KnownUndef, APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Vector Op.
virtual bool isUsedByReturnOnly(SDNode *, SDValue &) const
Return true if result of the specified node is used by a return node only.
SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const
virtual unsigned getPreferredShrunkVectorSizeInBits(SDValue Op, const APInt &DemandedElts) const
If only low elements of a vector are demanded, shrink the operation to the returned size in bits by c...
virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const
This method can be implemented by targets that want to expose additional information about sign bits ...
SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const
SDValue expandVPBSWAP(SDNode *N, SelectionDAG &DAG) const
Expand VP_BSWAP nodes.
void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS, SDValue &NewRHS, ISD::CondCode &CCCode, const SDLoc &DL, const SDValue OldLHS, const SDValue OldRHS) const
Soften the operands of a comparison.
void forceExpandWideMUL(SelectionDAG &DAG, const SDLoc &dl, bool Signed, const SDValue LHS, const SDValue RHS, SDValue &Lo, SDValue &Hi) const
Calculate full product of LHS and RHS either via a libcall or through brute force expansion of the mu...
SDValue expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const
Expand a VECREDUCE_SEQ_* into an explicit ordered calculation.
SDValue expandFCANONICALIZE(SDNode *Node, SelectionDAG &DAG) const
Expand FCANONICALIZE to FMUL with 1.
SDValue expandCTLZ(SDNode *N, SelectionDAG &DAG) const
Expand CTLZ/CTLZ_ZERO_POISON nodes.
SDValue expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const
Expand BITREVERSE nodes.
SDValue expandCTTZ(SDNode *N, SelectionDAG &DAG) const
Expand CTTZ/CTTZ_ZERO_POISON nodes.
virtual SDValue expandIndirectJTBranch(const SDLoc &dl, SDValue Value, SDValue Addr, int JTI, SelectionDAG &DAG) const
Expands target specific indirect branch for the case of JumpTable expansion.
SDValue expandABD(SDNode *N, SelectionDAG &DAG) const
Expand ABDS/ABDU nodes.
virtual bool targetShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, TargetLoweringOpt &TLO) const
std::vector< AsmOperandInfo > AsmOperandInfoVector
SDValue expandCLMUL(SDNode *N, SelectionDAG &DAG) const
Expand carryless multiply.
SDValue expandShlSat(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]SHLSAT.
SDValue expandIS_FPCLASS(EVT ResultVT, SDValue Op, FPClassTest Test, SDNodeFlags Flags, const SDLoc &DL, SelectionDAG &DAG) const
Expand check for floating point class.
virtual bool isTargetCanonicalConstantNode(SDValue Op) const
Returns true if the given Opc is considered a canonical constant for the target, which should not be ...
SDValue expandFP_TO_INT_SAT(SDNode *N, SelectionDAG &DAG) const
Expand FP_TO_[US]INT_SAT into FP_TO_[US]INT and selects or min/max.
SDValue expandCttzElts(SDNode *Node, SelectionDAG &DAG) const
Expand a CTTZ_ELTS or CTTZ_ELTS_ZERO_POISON by calculating (VL - i) for each active lane (i),...
SDValue getCheaperNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, unsigned Depth=0) const
This is the helper function to return the newly negated expression only when the cost is cheaper.
virtual unsigned computeNumSignBitsForTargetInstr(GISelValueTracking &Analysis, Register R, const APInt &DemandedElts, const MachineRegisterInfo &MRI, unsigned Depth=0) const
This method can be implemented by targets that want to expose additional information about sign bits ...
SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, SelectionDAG &DAG, unsigned Depth=0) const
More limited version of SimplifyDemandedBits that can be used to "lookthrough" ops that don't contrib...
SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const
Expands an unaligned store to 2 half-size stores for integer values, and possibly more for vectors.
SDValue SimplifyMultipleUseDemandedVectorElts(SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG, unsigned Depth=0) const
Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all bits from only some vector eleme...
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const
Determines the optimal series of memory ops to replace the memset / memcpy.
virtual SDValue unwrapAddress(SDValue N) const
void expandSADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::S(ADD|SUB)O.
SDValue expandVPBITREVERSE(SDNode *N, SelectionDAG &DAG) const
Expand VP_BITREVERSE nodes.
SDValue expandABS(SDNode *N, SelectionDAG &DAG, bool IsNegative=false) const
Expand ABS nodes.
SDValue expandVecReduce(SDNode *Node, SelectionDAG &DAG) const
Expand a VECREDUCE_* into an explicit calculation.
bool ShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, TargetLoweringOpt &TLO) const
Check to see if the specified operand of the specified instruction is a constant integer.
virtual bool isGuaranteedNotToBeUndefOrPoisonForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, UndefPoisonKind Kind, unsigned Depth) const
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
SDValue expandVPCTTZElements(SDNode *N, SelectionDAG &DAG) const
Expand VP_CTTZ_ELTS/VP_CTTZ_ELTS_ZERO_POISON nodes.
SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization, bool IsAfterLegalTypes, SmallVectorImpl< SDNode * > &Created) const
Given an ISD::SDIV node expressing a divide by constant, return a DAG expression to select that will ...
virtual const char * getTargetNodeName(unsigned Opcode) const
This method returns the name of a target specific DAG node.
bool expandFP_TO_UINT(SDNode *N, SDValue &Result, SDValue &Chain, SelectionDAG &DAG) const
Expand float to UINT conversion.
bool parametersInCSRMatch(const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, const SmallVectorImpl< CCValAssign > &ArgLocs, const SmallVectorImpl< SDValue > &OutVals) const
Check whether parameters to a call that are passed in callee saved registers are the same as from the...
virtual bool SimplifyDemandedVectorEltsForTargetNode(SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth=0) const
Attempt to simplify any target nodes based on the demanded vector elements, returning true on success...
bool expandREM(SDNode *Node, SDValue &Result, SelectionDAG &DAG) const
Expand an SREM or UREM using SDIV/UDIV or SDIVREM/UDIVREM, if legal.
std::pair< SDValue, SDValue > expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Expands an unaligned load to 2 half-size loads for an integer, and possibly more for vectors.
SDValue expandFMINIMUMNUM_FMAXIMUMNUM(SDNode *N, SelectionDAG &DAG) const
Expand fminimumnum/fmaximumnum into multiple comparison with selects.
void forceExpandMultiply(SelectionDAG &DAG, const SDLoc &dl, bool Signed, SDValue &Lo, SDValue &Hi, SDValue LHS, SDValue RHS, SDValue HiLHS=SDValue(), SDValue HiRHS=SDValue()) const
Calculate the product twice the width of LHS and RHS.
virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, SelectionDAG &DAG) const
Lower TLS global address SDNode for target independent emulated TLS model.
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is 'desirable' to us...
SDValue expandVectorSplice(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::VECTOR_SPLICE.
SDValue getVectorSubVecPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, EVT SubVecVT, SDValue Index, const SDNodeFlags PtrArithFlags=SDNodeFlags()) const
Get a pointer to a sub-vector of type SubVecVT at index Idx located in memory for a vector of type Ve...
SDValue expandLoopDependenceMask(SDNode *N, SelectionDAG &DAG) const
Expand LOOP_DEPENDENCE_MASK nodes.
virtual const char * LowerXConstraint(EVT ConstraintVT) const
Try to replace an X constraint, which matches anything, with another that has more specific requireme...
SDValue expandCTPOP(SDNode *N, SelectionDAG &DAG) const
Expand CTPOP nodes.
virtual void computeKnownBitsForTargetInstr(GISelValueTracking &Analysis, Register R, KnownBits &Known, const APInt &DemandedElts, const MachineRegisterInfo &MRI, unsigned Depth=0) const
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization, bool IsAfterLegalTypes, SmallVectorImpl< SDNode * > &Created) const
Given an ISD::UDIV node expressing a divide by constant, return a DAG expression to select that will ...
SDValue expandVectorNaryOpBySplitting(SDNode *Node, SelectionDAG &DAG) const
~TargetLowering() override
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
SDValue expandBSWAP(SDNode *N, SelectionDAG &DAG) const
Expand BSWAP nodes.
SDValue expandFMINIMUM_FMAXIMUM(SDNode *N, SelectionDAG &DAG) const
Expand fminimum/fmaximum into multiple comparison with selects.
SDValue CTTZTableLookup(SDNode *N, SelectionDAG &DAG, const SDLoc &DL, EVT VT, SDValue Op, unsigned NumBitsPerElt) const
Expand CTTZ via Table Lookup.
bool expandDIVREMByConstant(SDNode *N, SmallVectorImpl< SDValue > &Result, EVT HiLoVT, SelectionDAG &DAG, SDValue LL=SDValue(), SDValue LH=SDValue()) const
Attempt to expand an n-bit div/rem/divrem by constant using an n/2-bit algorithm.
virtual void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
bool isPositionIndependent() const
std::pair< StringRef, TargetLowering::ConstraintType > ConstraintPair
virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, NegatibleCost &Cost, unsigned Depth=0) const
Return the newly negated expression if the cost is not expensive and set the cost in Cost to indicate...
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
ConstraintGroup getConstraintPreferences(AsmOperandInfo &OpInfo) const
Given an OpInfo with list of constraints codes as strings, return a sorted Vector of pairs of constra...
bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const
Expand float(f32) to SINT(i64) conversion.
virtual SDValue SimplifyMultipleUseDemandedBitsForTargetNode(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, SelectionDAG &DAG, unsigned Depth) const
More limited version of SimplifyDemandedBits that can be used to "lookthrough" ops that don't contrib...
virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Glue, const SDLoc &DL, const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const
SDValue buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0, SDValue N1, MutableArrayRef< int > Mask, SelectionDAG &DAG) const
Tries to build a legal vector shuffle using the provided parameters or equivalent variations.
virtual void computeKnownBitsForStackObjectPointer(KnownBits &Known, const MachineFunction &MF, Align Alignment) const
Determine known bits of a pointer to a known valid stack object.
virtual SDValue getPICJumpTableRelocBase(SDValue Table, SelectionDAG &DAG) const
Returns relocation base for the given PIC jumptable.
std::pair< SDValue, SDValue > scalarizeVectorLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Turn load of vector type into a load of the individual elements.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0, bool AssumeSingleUse=false) const
Look at Op.
virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth=0) const
Attempt to simplify any target nodes based on the demanded bits/elts, returning true on success.
virtual bool isDesirableToCommuteXorWithShift(const SDNode *N) const
Return true if it is profitable to combine an XOR of a logical shift to create a logical shift of NOT...
TargetLowering(const TargetLowering &)=delete
virtual bool shouldSimplifyDemandedVectorElts(SDValue Op, const TargetLoweringOpt &TLO) const
Return true if the target supports simplifying demanded vector elements by converting them to undefs.
bool isConstFalseVal(SDValue N) const
Return if the N is a constant or constant vector equal to the false value from getBooleanContents().
SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL, EVT DataVT, SelectionDAG &DAG, bool IsCompressedMemory) const
Increments memory address Addr according to the type of the value DataVT that should be stored.
bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, SDValue &Chain) const
Check whether a given call node is in tail position within its function.
SDValue expandCONVERT_TO_ARBITRARY_FP(SDNode *Node, SelectionDAG &DAG) const
Expand CONVERT_TO_ARBITRARY_FP using bit manipulation.
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
virtual bool isSplatValueForTargetNode(SDValue Op, const APInt &DemandedElts, APInt &UndefElts, const SelectionDAG &DAG, unsigned Depth=0) const
Return true if vector Op has the same value across all DemandedElts, indicating any elements which ma...
SDValue expandRoundInexactToOdd(EVT ResultVT, SDValue Op, const SDLoc &DL, SelectionDAG &DAG) const
Truncate Op to ResultVT.
virtual bool shouldSplitFunctionArgumentsAsLittleEndian(const DataLayout &DL) const
For most targets, an LLVM type must be broken down into multiple smaller types.
SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, bool foldBooleans, DAGCombinerInfo &DCI, const SDLoc &dl) const
Try to simplify a setcc built with the specified operands and cc.
SDValue expandFunnelShift(SDNode *N, SelectionDAG &DAG) const
Expand funnel shift.
virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const
Return true if folding a constant offset with the given GlobalAddress is legal.
bool LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC, SDValue Mask, SDValue EVL, bool &NeedInvert, const SDLoc &dl, SDValue &Chain, bool IsSignaling=false) const
Legalize a SETCC or VP_SETCC with given LHS and RHS and condition code CC on the current target.
bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const
Return if N is a True value when extended to VT.
bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &DemandedBits, TargetLoweringOpt &TLO) const
Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
bool isConstTrueVal(SDValue N) const
Return if the N is a constant or constant vector equal to the true value from getBooleanContents().
SDValue expandVPCTPOP(SDNode *N, SelectionDAG &DAG) const
Expand VP_CTPOP nodes.
SDValue expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, SDValue LHS, SDValue RHS, unsigned Scale, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]DIVFIX[SAT].
SDValue expandPEXT(SDNode *N, SelectionDAG &DAG) const
Expand parallel bit extract (compress).
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
virtual void CollectTargetIntrinsicOperands(const CallInst &I, SmallVectorImpl< SDValue > &Ops, SelectionDAG &DAG) const
virtual bool canCreateUndefOrPoisonForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const
Return true if Op can create undef or poison from non-undef & non-poison operands.
SDValue expandVPCTTZ(SDNode *N, SelectionDAG &DAG) const
Expand VP_CTTZ/VP_CTTZ_ZERO_POISON nodes.
SDValue expandVECTOR_COMPRESS(SDNode *Node, SelectionDAG &DAG) const
Expand a vector VECTOR_COMPRESS into a sequence of extract element, store temporarily,...
virtual const Constant * getTargetConstantFromLoad(LoadSDNode *LD) const
This method returns the constant pool value that will be loaded by LD.
SDValue expandFP_ROUND(SDNode *Node, SelectionDAG &DAG) const
Expand round(fp) to fp conversion.
SDValue createSelectForFMINNUM_FMAXNUM(SDNode *Node, SelectionDAG &DAG) const
Try to convert the fminnum/fmaxnum to a compare/select sequence.
SDValue expandCONVERT_FROM_ARBITRARY_FP(SDNode *Node, SelectionDAG &DAG) const
Expand CONVERT_FROM_ARBITRARY_FP using bit manipulation.
SDValue expandROT(SDNode *N, bool AllowVectorOps, SelectionDAG &DAG) const
Expand rotations.
SDValue annotateStackObjectPointer(SDValue Ptr, SelectionDAG &DAG, const SDLoc &DL, Align Alignment) const
Annotate a stack object pointer with known-bits assertions.
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
virtual SDValue getSqrtInputTest(SDValue Operand, SelectionDAG &DAG, const DenormalMode &Mode, SDNodeFlags Flags={}) const
Return a target-dependent comparison result if the input operand is suitable for use with a square ro...
SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, SDValue Index, const SDNodeFlags PtrArithFlags=SDNodeFlags()) const
Get a pointer to vector element Idx located in memory for a vector of type VecVT starting at a base a...
SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const
Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
virtual bool isGAPlusOffset(SDNode *N, const GlobalValue *&GA, int64_t &Offset) const
Returns true (and the GlobalValue and the offset) if the node is a GlobalAddress + offset.
virtual void computeKnownFPClassForTargetNode(const SDValue Op, KnownFPClass &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const
Determine floating-point class information for a target node.
virtual unsigned getJumpTableEncoding() const
Return the entry encoding for a jump table in the current function.
virtual void computeKnownFPClassForTargetInstr(GISelValueTracking &Analysis, Register R, KnownFPClass &Known, const APInt &DemandedElts, const MachineRegisterInfo &MRI, unsigned Depth=0) const
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
SDValue expandCMP(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]CMP.
void expandShiftParts(SDNode *N, SDValue &Lo, SDValue &Hi, SelectionDAG &DAG) const
Expand shift-by-parts.
virtual bool isKnownNeverNaNForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, bool SNaN=false, unsigned Depth=0) const
If SNaN is false,.
virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const
This method will be invoked for all target nodes and for any target-independent nodes that the target...
SDValue expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[U|S]MULFIX[SAT].
SDValue getInboundsVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, SDValue Index) const
Get a pointer to vector element Idx located in memory for a vector of type VecVT starting at a base a...
SDValue expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US][MIN|MAX].
SDValue expandVectorFindLastActive(SDNode *N, SelectionDAG &DAG) const
Expand VECTOR_FIND_LAST_ACTIVE nodes.
SDValue expandPartialReduceMLA(SDNode *Node, SelectionDAG &DAG) const
Expands PARTIAL_REDUCE_S/UMLA nodes to a series of simpler operations, consisting of zext/sext,...
void expandUADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::U(ADD|SUB)O.
SDValue expandPDEP(SDNode *N, SelectionDAG &DAG) const
Expand parallel bit deposit (expand).
virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created) const
Targets may override this function to provide custom SDIV lowering for power-of-2 denominators.
SDValue scalarizeExtractedVectorLoad(EVT ResultVT, const SDLoc &DL, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad, SelectionDAG &DAG) const
Replace an extraction of a load with a narrowed load.
virtual SDValue BuildSREMPow2(SDNode *N, const APInt &Divisor, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created) const
Targets may override this function to provide custom SREM lowering for power-of-2 denominators.
bool expandUINT_TO_FP(SDNode *N, SDValue &Result, SDValue &Chain, SelectionDAG &DAG) const
Expand UINT(i64) to double(f64) conversion.
bool expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, SDValue LHS, SDValue RHS, SmallVectorImpl< SDValue > &Result, EVT HiLoVT, SelectionDAG &DAG, MulExpansionKind Kind, SDValue LL=SDValue(), SDValue LH=SDValue(), SDValue RL=SDValue(), SDValue RH=SDValue()) const
Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes, respectively,...
SDValue expandAVG(SDNode *N, SelectionDAG &DAG) const
Expand vector/scalar AVGCEILS/AVGCEILU/AVGFLOORS/AVGFLOORU nodes.
SDValue expandCTLS(SDNode *N, SelectionDAG &DAG) const
Expand CTLS (count leading sign bits) nodes.
void setTypeIdForCallsiteInfo(const CallBase *CB, MachineFunction &MF, MachineFunction::CallSiteInfo &CSInfo) const
Primary interface to the complete machine description for the target machine.
bool isPositionIndependent() const
const Triple & getTargetTriple() const
TargetOptions Options
unsigned EmitCallSiteInfo
The flag enables call site info production.
unsigned EmitCallGraphSection
Emit section containing call graph metadata.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual StringRef getRegAsmName(MCRegister Reg) const
Return the assembly name for Reg.
bool isTypeLegalForClass(const TargetRegisterClass &RC, MVT T) const
Return true if the given TargetRegisterClass has the ValueType T.
TargetSubtargetInfo - Generic base class for all target subtargets.
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
Definition Triple.h:866
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:343
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition Value.cpp:717
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
constexpr bool isKnownMultipleOf(ScalarTy RHS) const
This function tells the caller whether the element count is known at compile time to be a multiple of...
Definition TypeSize.h:180
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3040
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:41
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:829
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:261
@ PTRADD
PTRADD represents pointer arithmetic semantics, for targets that opt in using shouldPreservePtrArith(...
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ LOOP_DEPENDENCE_RAW_MASK
@ FGETSIGN
INT = FGETSIGN(FP) - Return the sign bit of the specified floating point value as an integer 0/1 valu...
Definition ISDOpcodes.h:540
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:275
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:602
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:789
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:394
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:294
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:524
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ SMULFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:400
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:863
@ CTTZ_ELTS
Returns the number of number of trailing (least significant) zero elements in a vector.
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:520
@ VECTOR_FIND_LAST_ACTIVE
Finds the index of the last active mask element Operands: Mask.
@ PSEUDO_FMIN
PSEUDO_FMIN is strictly equivalent to op0 olt op1 ?
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:220
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:890
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:586
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:417
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:749
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:920
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:280
@ FMULADD
FMULADD - Performs a * b + c, with, or without, intermediate rounding.
Definition ISDOpcodes.h:530
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:254
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:780
@ SDIVFIX
RESULT = [US]DIVFIX(LHS, RHS, SCALE) - Perform fixed point division on 2 integers with the same width...
Definition ISDOpcodes.h:407
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:798
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:854
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:717
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:667
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ PARTIAL_REDUCE_FMLA
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:352
@ BRIND
BRIND - Indirect branch.
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:543
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:550
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:374
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:806
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:247
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:674
@ GET_ACTIVE_LANE_MASK
GET_ACTIVE_LANE_MASK - this corrosponds to the llvm.get.active.lane.mask intrinsic.
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:230
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:348
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:706
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:771
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:651
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:616
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Perform floating-point minimumNumber or maximumNumber on two values,...
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:578
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:860
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:821
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:386
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:356
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:655
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:909
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:898
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:729
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:413
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:988
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:815
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:328
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:479
@ FMINIMUM
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:936
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:179
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:741
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:205
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:712
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:659
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:304
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:241
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:567
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:797
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:969
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:931
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:955
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:866
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:843
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:536
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:365
@ CALLSEQ_START
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence,...
@ CTTZ_ELTS_ZERO_POISON
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:724
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:213
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:753
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:558
LLVM_ABI NodeType getOppositeSignednessMinMaxOpcode(unsigned MinMaxOpc)
Given a MinMaxOpc of ISD::(U|S)MIN or ISD::(U|S)MAX, returns the corresponding opcode with the opposi...
LLVM_ABI bool isBuildVectorOfConstantSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantSDNode or undef.
LLVM_ABI NodeType getExtForLoadExtType(bool IsFP, LoadExtType)
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
bool isZEXTLoad(const SDNode *N)
Returns true if the specified node is a ZEXTLOAD.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
bool isTrueWhenEqual(CondCode Cond)
Return true if the specified condition returns true if the two operands to the condition are equal.
unsigned getUnorderedFlavor(CondCode Cond)
This function returns 0 if the condition is always false if an operand is a NaN, 1 if the condition i...
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
bool isSignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs a signed comparison when used with integer o...
LLVM_ABI bool isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
LLVM_ABI bool matchBinaryPredicate(SDValue LHS, SDValue RHS, std::function< bool(ConstantSDNode *, ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTypeMismatch=false)
Attempt to match a binary predicate against a pair of scalar/splat constants or every element of a pa...
bool matchUnaryPredicate(SDValue Op, std::function< bool(ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Hook for matching ConstantSDNode predicate.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LLVM_ABI NodeType getVecReduceBaseOpcode(unsigned VecReduceOpcode)
Get underlying scalar opcode for VECREDUCE opcode.
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
bool isUnsignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs an unsigned comparison when used with intege...
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
Or< Preds... > m_AnyOf(const Preds &...preds)
bool sd_match(SDNode *N, const SelectionDAG *DAG, Pattern &&P)
NUses_match< 1, Value_match > m_OneUse()
This is an optimization pass for GlobalISel generic memory operations.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:344
@ Offset
Definition DWP.cpp:573
void stable_sort(R &&Range)
Definition STLExtras.h:2116
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
InstructionCost Cost
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
LLVM_ABI bool isAllOnesOrAllOnesSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant -1 integer or a splatted vector of a constant -1 integer (with...
Definition Utils.cpp:1572
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI FPClassTest invertFPClassTestIfSimpler(FPClassTest Test, bool UseFCmp)
Evaluates if the specified FP class test is better performed as the inverse (i.e.
LLVM_ABI bool isOneOrOneSplatFP(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant floating-point value, or a splatted vector of a constant float...
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
void * PointerTy
LLVM_ABI bool isNullOrNullSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
Definition Utils.cpp:1554
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
LLVM_ABI ConstantFPSDNode * isConstOrConstSplatFP(SDValue N, bool AllowUndefs=false)
Returns the SDNode if it is a constant splat BuildVector or constant float.
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:331
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
auto find_if_not(R &&Range, UnaryPredicate P)
Definition STLExtras.h:1777
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool isOneOrOneSplat(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant 1 integer or a splatted vector of a constant 1 integer (with n...
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:394
@ Other
Any other memory.
Definition ModRef.h:68
To bit_cast(const From &from) noexcept
Definition bit.h:90
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
fltNonfiniteBehavior
Definition APFloat.h:959
DWARFExpression::Operation Op
RoundingMode
Rounding mode.
@ TowardZero
roundTowardZero.
@ NearestTiesToEven
roundTiesToEven.
@ TowardPositive
roundTowardPositive.
@ NearestTiesToAway
roundTiesToAway.
@ TowardNegative
roundTowardNegative.
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isZeroOrZeroSplat(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
LLVM_ABI bool isNullFPConstant(SDValue V)
Returns true if V is an FP constant with a value of positive zero.
APFloat neg(APFloat X)
Returns the negated value of the argument.
Definition APFloat.h:1709
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:77
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
fltNanEncoding
Definition APFloat.h:983
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:373
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:862
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Represent subnormal handling kind for floating point instruction inputs and outputs.
DenormalModeKind Input
Denormal treatment kind for floating point instruction inputs in the default floating-point environme...
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ IEEE
IEEE-754 denormal numbers preserved.
constexpr bool inputsAreZero() const
Return true if input denormals must be implicitly treated as 0.
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:129
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
ElementCount getVectorElementCount() const
Definition ValueTypes.h:373
EVT getDoubleNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:494
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition ValueTypes.h:266
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:382
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
EVT getHalfSizedIntegerVT(LLVMContext &Context) const
Finds the smallest simple value type that is greater than or equal to half the width of this EVT.
Definition ValueTypes.h:453
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
Definition ValueTypes.h:501
TypeSize getStoreSizeInBits() const
Return the number of bits overwritten by a store of the specified value type.
Definition ValueTypes.h:435
EVT changeVectorElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a vector type whose attributes match ourselves with the exception of the element type...
Definition ValueTypes.h:98
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:404
EVT changeVectorElementCount(LLVMContext &Context, ElementCount EC) const
Return a VT for a vector type whose attributes match ourselves with the exception of the element coun...
Definition ValueTypes.h:109
bool isScalableVT() const
Return true if the type is a scalable type.
Definition ValueTypes.h:210
bool isFixedLengthVector() const
Definition ValueTypes.h:199
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
EVT widenIntegerElementType(LLVMContext &Context) const
Return a VT for an integer element type with doubled bit width.
Definition ValueTypes.h:467
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
EVT changeElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a type whose attributes match ourselves with the exception of the element type that i...
Definition ValueTypes.h:121
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
LLVM_ABI const fltSemantics & getFltSemantics() const
Returns an APFloat semantics tag appropriate for the value type.
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:331
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:484
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:165
KnownBits byteSwap() const
Definition KnownBits.h:559
static LLVM_ABI std::optional< bool > sge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGE result.
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
KnownBits reverseBits() const
Definition KnownBits.h:563
KnownBits concat(const KnownBits &Lo) const
Concatenate the bits from Lo onto the bottom of *this.
Definition KnownBits.h:247
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI std::optional< bool > ugt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGT result.
static LLVM_ABI std::optional< bool > slt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SLT result.
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:61
static LLVM_ABI std::optional< bool > ult(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULT result.
static LLVM_ABI std::optional< bool > ule(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULE result.
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
static LLVM_ABI std::optional< bool > sle(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SLE result.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition KnownBits.h:300
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
Matching combinators.
This class contains a discriminated union of information about pointers in memory operands,...
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getUnknownStack(MachineFunction &MF)
Stack memory without other information.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
static LLVM_ABI bool hasVectorMaskArgument(RTLIB::LibcallImpl Impl)
Returns true if the function has a vector mask argument, which is assumed to be the last argument.
These are IR-level optimization flags that may be propagated to SDNodes.
bool hasNoUnsignedWrap() const
bool hasNoSignedWrap() const
void setNoSignedWrap(bool b)
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
Magic data for optimising signed division by a constant.
static LLVM_ABI SignedDivisionByConstantInfo get(const APInt &D)
Calculate the magic numbers required to implement a signed integer division by a constant as a sequen...
This contains information for each constraint that we are lowering.
std::string ConstraintCode
This contains the actual string for the code, like "m".
LLVM_ABI unsigned getMatchedOperand() const
If this is an input matching constraint, this method returns the output operand it matches.
LLVM_ABI bool isMatchingInputConstraint() const
Return true of this is an input operand that is a matching constraint like "4".
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setIsPostTypeLegalization(bool Value=true)
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setSExtResult(bool Value=true)
CallLoweringInfo & setNoReturn(bool Value=true)
CallLoweringInfo & setChain(SDValue InChain)
LLVM_ABI void AddToWorklist(SDNode *N)
LLVM_ABI void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO)
This structure is used to pass arguments to makeLibCall function.
MakeLibCallOptions & setIsPostTypeLegalization(bool Value=true)
MakeLibCallOptions & setTypeListBeforeSoften(ArrayRef< EVT > OpsVT, EVT RetVT)
MakeLibCallOptions & setIsSigned(bool Value=true)
A convenience struct that encapsulates a DAG, and two SDValues for returning information from TargetL...
Magic data for optimising unsigned division by a constant.
static LLVM_ABI UnsignedDivisionByConstantInfo get(const APInt &D, unsigned LeadingZeros=0, bool AllowEvenDivisorOptimization=true, bool AllowWidenOptimization=false)
Calculate the magic numbers required to implement an unsigned integer division by a constant as a seq...
fltNonfiniteBehavior nonFiniteBehavior
Definition APFloat.h:1021
fltNanEncoding nanEncoding
Definition APFloat.h:1023