LLVM 24.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>
40#include <list>
41using namespace llvm;
42using namespace llvm::SDPatternMatch;
43
44/// NOTE: The TargetMachine owns TLOF.
48
49// Define the virtual destructor out-of-line for build efficiency.
51
52const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
53 return nullptr;
54}
55
59
60/// Check whether a given call node is in tail position within its function. If
61/// so, it sets Chain to the input chain of the tail call.
63 SDValue &Chain) const {
65
66 // First, check if tail calls have been disabled in this function.
67 if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
68 return false;
69
70 // Conservatively require the attributes of the call to match those of
71 // the return. Ignore following attributes because they don't affect the
72 // call sequence.
73 AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs());
74 for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
75 Attribute::DereferenceableOrNull, Attribute::NoAlias,
76 Attribute::NonNull, Attribute::NoUndef,
77 Attribute::Range, Attribute::NoFPClass})
78 CallerAttrs.removeAttribute(Attr);
79
80 if (CallerAttrs.hasAttributes())
81 return false;
82
83 // It's not safe to eliminate the sign / zero extension of the return value.
84 if (CallerAttrs.contains(Attribute::ZExt) ||
85 CallerAttrs.contains(Attribute::SExt))
86 return false;
87
88 // Check if the only use is a function return node.
89 return isUsedByReturnOnly(Node, Chain);
90}
91
93 const uint32_t *CallerPreservedMask,
94 const SmallVectorImpl<CCValAssign> &ArgLocs,
95 const SmallVectorImpl<SDValue> &OutVals) const {
96 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
97 const CCValAssign &ArgLoc = ArgLocs[I];
98 if (!ArgLoc.isRegLoc())
99 continue;
100 MCRegister Reg = ArgLoc.getLocReg();
101 // Only look at callee saved registers.
102 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
103 continue;
104 // Check that we pass the value used for the caller.
105 // (We look for a CopyFromReg reading a virtual register that is used
106 // for the function live-in value of register Reg)
107 SDValue Value = OutVals[I];
108 if (Value->getOpcode() == ISD::AssertZext)
109 Value = Value.getOperand(0);
110 if (Value->getOpcode() != ISD::CopyFromReg)
111 return false;
112 Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
113 if (MRI.getLiveInPhysReg(ArgReg) != Reg)
114 return false;
115 }
116 return true;
117}
118
119static bool paramHasAttr(const CallBase &Call, unsigned ArgIdx,
120 Attribute::AttrKind Kind) {
121 return Call.paramHasAttr(ArgIdx, Kind);
122}
123
124static bool paramHasAttr(const AttributeList &Attrs, unsigned ArgIdx,
125 Attribute::AttrKind Kind) {
126 return Attrs.hasParamAttr(ArgIdx, Kind);
127}
128
129static MaybeAlign getParamStackAlign(const CallBase &Call, unsigned ArgIdx) {
130 return Call.getParamStackAlign(ArgIdx);
131}
132
134 unsigned ArgIdx) {
135 return Attrs.getParamStackAlignment(ArgIdx);
136}
137
138static MaybeAlign getParamAlign(const CallBase &Call, unsigned ArgIdx) {
139 return Call.getParamAlign(ArgIdx);
140}
141
142static MaybeAlign getParamAlign(const AttributeList &Attrs, unsigned ArgIdx) {
143 return Attrs.getParamAlignment(ArgIdx);
144}
145
146/// Set CallLoweringInfo attribute flags based on a call instruction
147/// and called function attributes.
148template <typename SourceT>
150 const SourceT &Src, unsigned ArgIdx) {
151 Entry.IsSExt = paramHasAttr(Src, ArgIdx, Attribute::SExt);
152 Entry.IsZExt = paramHasAttr(Src, ArgIdx, Attribute::ZExt);
153 Entry.IsNoExt = paramHasAttr(Src, ArgIdx, Attribute::NoExt);
154 Entry.IsInReg = paramHasAttr(Src, ArgIdx, Attribute::InReg);
155 Entry.IsSRet = paramHasAttr(Src, ArgIdx, Attribute::StructRet);
156 Entry.IsNest = paramHasAttr(Src, ArgIdx, Attribute::Nest);
157 Entry.IsByVal = paramHasAttr(Src, ArgIdx, Attribute::ByVal);
158 Entry.IsPreallocated = paramHasAttr(Src, ArgIdx, Attribute::Preallocated);
159 Entry.IsInAlloca = paramHasAttr(Src, ArgIdx, Attribute::InAlloca);
160 Entry.IsReturned = paramHasAttr(Src, ArgIdx, Attribute::Returned);
161 Entry.IsSwiftSelf = paramHasAttr(Src, ArgIdx, Attribute::SwiftSelf);
162 Entry.IsSwiftAsync = paramHasAttr(Src, ArgIdx, Attribute::SwiftAsync);
163 Entry.IsSwiftError = paramHasAttr(Src, ArgIdx, Attribute::SwiftError);
164 Entry.Alignment = getParamStackAlign(Src, ArgIdx);
165 Entry.IndirectType = nullptr;
166 assert(Entry.IsByVal + Entry.IsPreallocated + Entry.IsInAlloca +
167 Entry.IsSRet <=
168 1 &&
169 "multiple ABI attributes?");
170 if (Entry.IsByVal) {
171 Entry.IndirectType = Src.getParamByValType(ArgIdx);
172 if (!Entry.Alignment)
173 Entry.Alignment = getParamAlign(Src, ArgIdx);
174 }
175 if (Entry.IsPreallocated)
176 Entry.IndirectType = Src.getParamPreallocatedType(ArgIdx);
177 if (Entry.IsInAlloca)
178 Entry.IndirectType = Src.getParamInAllocaType(ArgIdx);
179 if (Entry.IsSRet)
180 Entry.IndirectType = Src.getParamStructRetType(ArgIdx);
181}
182
184 unsigned ArgIdx) {
185 setArgListEntryAttributes(*this, *Call, ArgIdx);
186}
187
189 unsigned ArgIdx) {
190 setArgListEntryAttributes(*this, Attrs, ArgIdx);
191}
192
194 Attribute::AttrKind Attr) {
195 if (Attr != Attribute::None) {
196 if (Attr == Attribute::SExt)
197 IsSExt = true;
198 else if (Attr == Attribute::ZExt)
199 IsZExt = true;
200 else if (Attr == Attribute::NoExt)
201 IsNoExt = true;
202 else
203 llvm_unreachable("Unexpected extension attribute!");
204 }
205}
206
209 const AttributeList &FuncAttrs,
211 // TODO: This assumes each parameter maps to exactly one operand node, which
212 // does not hold when an argument requires type splitting.
213 assert(Ops.size() == FuncTy->getNumParams() &&
214 "argument count does not match the function type");
215 ArgListTy Args;
216 Args.reserve(Ops.size());
217 for (unsigned I = 0, E = FuncTy->getNumParams(); I != E; ++I) {
218 ArgListEntry Entry(Ops[I], FuncTy->getParamType(I));
219 Entry.setAttributes(FuncAttrs, I);
220 Args.push_back(Entry);
221 }
222 return Args;
223}
224
225/// Generate a libcall taking the given operands as arguments and returning a
226/// result of type RetVT.
227std::pair<SDValue, SDValue>
228TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl,
230 MakeLibCallOptions CallOptions, const SDLoc &dl,
231 SDValue InChain) const {
232 if (LibcallImpl == RTLIB::Unsupported)
233 reportFatalInternalError("unsupported library call operation");
234
235 if (!InChain)
236 InChain = DAG.getEntryNode();
237
239 Args.reserve(Ops.size());
240
241 ArrayRef<Type *> OpsTypeOverrides = CallOptions.OpsTypeOverrides;
242 for (unsigned i = 0; i < Ops.size(); ++i) {
243 SDValue NewOp = Ops[i];
244 Type *Ty = i < OpsTypeOverrides.size() && OpsTypeOverrides[i]
245 ? OpsTypeOverrides[i]
246 : NewOp.getValueType().getTypeForEVT(*DAG.getContext());
247 TargetLowering::ArgListEntry Entry(NewOp, Ty);
248 if (CallOptions.IsSoften)
249 Entry.OrigTy =
250 CallOptions.OpsVTBeforeSoften[i].getTypeForEVT(*DAG.getContext());
251
252 Entry.IsSExt =
253 shouldSignExtendTypeInLibCall(Entry.Ty, CallOptions.IsSigned);
254 Entry.IsZExt = !Entry.IsSExt;
255
256 if (CallOptions.IsSoften &&
258 Entry.IsSExt = Entry.IsZExt = false;
259 }
260 Args.push_back(Entry);
261 }
262
263 SDValue Callee =
264 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
265
266 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
267 Type *OrigRetTy = RetTy;
269 bool signExtend = shouldSignExtendTypeInLibCall(RetTy, CallOptions.IsSigned);
270 bool zeroExtend = !signExtend;
271
272 if (CallOptions.IsSoften) {
273 OrigRetTy = CallOptions.RetVTBeforeSoften.getTypeForEVT(*DAG.getContext());
275 signExtend = zeroExtend = false;
276 }
277
278 CLI.setDebugLoc(dl)
279 .setChain(InChain)
280 .setLibCallee(getLibcallImplCallingConv(LibcallImpl), RetTy, OrigRetTy,
281 Callee, std::move(Args))
282 .setNoReturn(CallOptions.DoesNotReturn)
285 .setSExtResult(signExtend)
286 .setZExtResult(zeroExtend);
287 return LowerCallTo(CLI);
288}
289
291 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
292 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
293 const AttributeList &FuncAttributes, EVT *LargestVT) const {
294 EVT VT = getOptimalMemOpType(Context, Op, FuncAttributes);
295
296 if (VT == MVT::Other) {
297 // Use the largest integer type whose alignment constraints are satisfied.
298 VT = MVT::LAST_INTEGER_VALUETYPE;
299 if (Op.isFixedDstAlign()) {
300 bool LoadsFromSrc = Op.isMemcpyOrMemmove() && !Op.isMemcpyStrSrc();
301 while (VT != MVT::i8) {
302 unsigned VTSize = VT.getSizeInBits() / 8;
303 bool DstOk =
304 Op.getDstAlign() >= VTSize ||
305 allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign());
306 bool SrcOk =
307 !LoadsFromSrc || Op.getSrcAlign() >= VTSize ||
308 allowsMisalignedMemoryAccesses(VT, SrcAS, Op.getSrcAlign());
309 if (DstOk && SrcOk)
310 break;
312 }
313 }
314 assert(VT.isInteger());
315
316 // Find the largest legal integer type.
317 MVT LVT = MVT::LAST_INTEGER_VALUETYPE;
318 while (!isTypeLegal(LVT))
319 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
320 assert(LVT.isInteger());
321
322 // If the type we've chosen is larger than the largest legal integer type
323 // then use the largest legal type.
324 if (VT.bitsGT(LVT))
325 VT = LVT;
326 }
327
328 unsigned NumMemOps = 0;
329 uint64_t Size = Op.size();
330 while (Size) {
331 unsigned VTSize = VT.getSizeInBits() / 8;
332 while (VTSize > Size) {
333 // For now, only use non-vector load / store's for the left-over pieces.
334 EVT NewVT = VT;
335 unsigned NewVTSize;
336
337 bool Found = false;
338 if (VT.isVector() || VT.isFloatingPoint()) {
339 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
342 Found = true;
343 else if (NewVT == MVT::i64 &&
345 isSafeMemOpType(MVT::f64)) {
346 // i64 is usually not legal on 32-bit targets, but f64 may be.
347 NewVT = MVT::f64;
348 Found = true;
349 }
350 }
351
352 if (!Found) {
353 do {
354 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
355 if (NewVT == MVT::i8)
356 break;
357 } while (!isSafeMemOpType(NewVT.getSimpleVT()));
358 }
359 NewVTSize = NewVT.getSizeInBits() / 8;
360
361 // If the new VT cannot cover all of the remaining bits, then consider
362 // issuing a (or a pair of) unaligned and overlapping load / store.
363 unsigned Fast;
364 if (NumMemOps && !Op.isVolatile() && NewVTSize < Size &&
366 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
368 Fast)
369 VTSize = Size;
370 else {
371 VT = NewVT;
372 VTSize = NewVTSize;
373 }
374 }
375
376 if (++NumMemOps > Limit)
377 return false;
378
379 MemOps.push_back(VT);
380 Size -= VTSize;
381 }
382
383 return true;
384}
385
386/// Soften the operands of a comparison. This code is shared among BR_CC,
387/// SELECT_CC, and SETCC handlers.
389 SDValue &NewLHS, SDValue &NewRHS,
390 ISD::CondCode &CCCode,
391 const SDLoc &dl, const SDValue OldLHS,
392 const SDValue OldRHS) const {
393 SDValue Chain;
394 return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
395 OldRHS, Chain);
396}
397
398/// Select the libcall and the condition code to test its result against 0 for
399/// an ordered floating-point compare. \p BoolLC is the boolean helper (result
400/// is 0/1). \p TriStateLC is the per-predicate three-way helper and \p
401/// GenericLC the generic single-symbol three-way helper (both return -1/0/1,
402/// tested against 0 with \p TriStateCC). The boolean form is preferred, then
403/// the per-predicate three-way, then the generic three-way.
404static std::pair<RTLIB::Libcall, ISD::CondCode>
405selectFPCmpLibcall(const LibcallLoweringInfo &Libcalls, RTLIB::Libcall BoolLC,
406 RTLIB::Libcall TriStateLC, RTLIB::Libcall GenericLC,
407 ISD::CondCode TriStateCC) {
408 if (Libcalls.getLibcallImpl(BoolLC) != RTLIB::Unsupported)
409 return {BoolLC, ISD::SETNE};
410 if (Libcalls.getLibcallImpl(TriStateLC) != RTLIB::Unsupported)
411 return {TriStateLC, TriStateCC};
412 return {GenericLC, TriStateCC};
413}
414
416 SDValue &NewLHS, SDValue &NewRHS,
417 ISD::CondCode &CCCode,
418 const SDLoc &dl, const SDValue OldLHS,
419 const SDValue OldRHS,
420 SDValue &Chain,
421 bool IsSignaling) const {
422 // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
423 // not supporting it. We can update this code when libgcc provides such
424 // functions.
425
426 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
427 && "Unsupported setcc type!");
428
429 // Expand into one or more soft-fp libcall(s).
430 ISD::CondCode OrigCCCode = CCCode;
431 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
433 bool ShouldInvertCC = false;
434
435 // Expand a compare libcall family name (e.g. OEQ, FCMP3_PRED_OEQ) to the
436 // RTLIB::Libcall for VT.
437#define FP_CMP_LIBCALL(BASE) \
438 RTLIB::getFPLibCall(VT, RTLIB::BASE##_F32, RTLIB::BASE##_F64, \
439 RTLIB::UNKNOWN_LIBCALL, RTLIB::BASE##_F128, \
440 RTLIB::BASE##_PPCF128)
441
442 switch (CCCode) {
443 case ISD::SETEQ:
444 case ISD::SETOEQ:
445 std::tie(LC1, CC1) = selectFPCmpLibcall(
446 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
447 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
448 break;
449 case ISD::SETNE:
450 case ISD::SETUNE:
451 std::tie(LC1, CC1) = selectFPCmpLibcall(
452 DAG.getLibcalls(), FP_CMP_LIBCALL(UNE), FP_CMP_LIBCALL(FCMP3_PRED_UNE),
453 FP_CMP_LIBCALL(FCMP3), ISD::SETNE);
454 // Some ABIs (e.g. AEABI) provide neither a not-equal nor a three-way
455 // compare; obtain not-equal (UNE = !OEQ) by inverting ordered-equal.
456 if (DAG.getLibcalls().getLibcallImpl(LC1) == RTLIB::Unsupported) {
457 std::tie(LC1, CC1) = selectFPCmpLibcall(
458 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ),
459 FP_CMP_LIBCALL(FCMP3_PRED_OEQ), FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
460 ShouldInvertCC = true;
461 }
462 break;
463 case ISD::SETGE:
464 case ISD::SETOGE:
465 std::tie(LC1, CC1) = selectFPCmpLibcall(
466 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE), FP_CMP_LIBCALL(FCMP3_PRED_OGE),
467 FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
468 break;
469 case ISD::SETLT:
470 case ISD::SETOLT:
471 std::tie(LC1, CC1) = selectFPCmpLibcall(
472 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT), FP_CMP_LIBCALL(FCMP3_PRED_OLT),
473 FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
474 break;
475 case ISD::SETLE:
476 case ISD::SETOLE:
477 std::tie(LC1, CC1) = selectFPCmpLibcall(
478 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE), FP_CMP_LIBCALL(FCMP3_PRED_OLE),
479 FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
480 break;
481 case ISD::SETGT:
482 case ISD::SETOGT:
483 std::tie(LC1, CC1) = selectFPCmpLibcall(
484 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT), FP_CMP_LIBCALL(FCMP3_PRED_OGT),
485 FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
486 break;
487 case ISD::SETO:
488 ShouldInvertCC = true;
489 [[fallthrough]];
490 case ISD::SETUO:
491 // Unordered is a boolean everywhere (__unordXf2 returns 0/1).
492 LC1 = FP_CMP_LIBCALL(UO);
493 CC1 = ISD::SETNE;
494 break;
495 case ISD::SETONE:
496 // SETONE = O && UNE
497 ShouldInvertCC = true;
498 [[fallthrough]];
499 case ISD::SETUEQ:
500 LC1 = FP_CMP_LIBCALL(UO);
501 CC1 = ISD::SETNE;
502 std::tie(LC2, CC2) = selectFPCmpLibcall(
503 DAG.getLibcalls(), FP_CMP_LIBCALL(OEQ), FP_CMP_LIBCALL(FCMP3_PRED_OEQ),
504 FP_CMP_LIBCALL(FCMP3), ISD::SETEQ);
505 break;
506 default:
507 // Invert CC for unordered comparisons, handled by the ordered inverse.
508 ShouldInvertCC = true;
509 switch (CCCode) {
510 case ISD::SETULT:
511 std::tie(LC1, CC1) = selectFPCmpLibcall(
512 DAG.getLibcalls(), FP_CMP_LIBCALL(OGE),
513 FP_CMP_LIBCALL(FCMP3_PRED_OGE), FP_CMP_LIBCALL(FCMP3), ISD::SETGE);
514 break;
515 case ISD::SETULE:
516 std::tie(LC1, CC1) = selectFPCmpLibcall(
517 DAG.getLibcalls(), FP_CMP_LIBCALL(OGT),
518 FP_CMP_LIBCALL(FCMP3_PRED_OGT), FP_CMP_LIBCALL(FCMP3), ISD::SETGT);
519 break;
520 case ISD::SETUGT:
521 std::tie(LC1, CC1) = selectFPCmpLibcall(
522 DAG.getLibcalls(), FP_CMP_LIBCALL(OLE),
523 FP_CMP_LIBCALL(FCMP3_PRED_OLE), FP_CMP_LIBCALL(FCMP3), ISD::SETLE);
524 break;
525 case ISD::SETUGE:
526 std::tie(LC1, CC1) = selectFPCmpLibcall(
527 DAG.getLibcalls(), FP_CMP_LIBCALL(OLT),
528 FP_CMP_LIBCALL(FCMP3_PRED_OLT), FP_CMP_LIBCALL(FCMP3), ISD::SETLT);
529 break;
530 default:
531 llvm_unreachable("Do not know how to soften this setcc!");
532 }
533 }
534
535#undef FP_CMP_LIBCALL
536
537 // Use the target specific return value for comparison lib calls.
539 SDValue Ops[2] = {NewLHS, NewRHS};
541 EVT OpsVT[2] = { OldLHS.getValueType(),
542 OldRHS.getValueType() };
543 CallOptions.setTypeListBeforeSoften(OpsVT, RetVT);
544
545 auto ReportNoLibcall = [&]() {
546 DAG.getContext()->emitError(
547 Twine("no libcall available to soften floating-point ") +
548 ISD::getCondCodeName(OrigCCCode) + " compare with type " +
549 VT.getEVTString());
550 NewLHS = DAG.getPOISON(RetVT);
551 NewRHS = DAG.getConstant(0, dl, RetVT);
552 CCCode = ISD::SETNE;
553 };
554
555 // Check availability before makeLibCall, which fatally errors otherwise.
556 RTLIB::LibcallImpl LC1Impl = DAG.getLibcalls().getLibcallImpl(LC1);
557 if (LC1Impl == RTLIB::Unsupported) {
558 ReportNoLibcall();
559 return;
560 }
561
562 auto Call = makeLibCall(DAG, LC1Impl, RetVT, Ops, CallOptions, dl, Chain);
563 NewLHS = Call.first;
564 NewRHS = DAG.getConstant(0, dl, RetVT);
565
566 CCCode = CC1;
567 if (ShouldInvertCC) {
568 assert(RetVT.isInteger());
569 CCCode = getSetCCInverse(CCCode, RetVT);
570 }
571
572 if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
573 // Update Chain.
574 Chain = Call.second;
575 } else {
576 RTLIB::LibcallImpl LC2Impl = DAG.getLibcalls().getLibcallImpl(LC2);
577 if (LC2Impl == RTLIB::Unsupported) {
578 ReportNoLibcall();
579 return;
580 }
581
582 assert(CCCode == (ShouldInvertCC ? ISD::SETEQ : ISD::SETNE) &&
583 "unordered call should be simple boolean");
584
585 EVT SetCCVT =
586 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
588 NewLHS = DAG.getNode(ISD::AssertZext, dl, RetVT, Call.first,
589 DAG.getValueType(MVT::i1));
590 }
591
592 SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
593 auto Call2 = makeLibCall(DAG, LC2Impl, RetVT, Ops, CallOptions, dl, Chain);
594 CCCode = CC2;
595 if (ShouldInvertCC)
596 CCCode = getSetCCInverse(CCCode, RetVT);
597 NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
598 if (Chain)
599 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
600 Call2.second);
601 NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
602 Tmp.getValueType(), Tmp, NewLHS);
603 NewRHS = SDValue();
604 }
605}
606
607/// Return the entry encoding for a jump table in the current function. The
608/// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
610 // In non-pic modes, just use the address of a block.
613
614 // Otherwise, use a label difference.
616}
617
622
623/// This returns the relocation base for the given PIC jumptable, the same as
624/// getPICJumpTableRelocBase, but as an MCExpr.
625const MCExpr *
627 unsigned JTI,MCContext &Ctx) const{
628 // The normal PIC reloc base is the label at the start of the jump table.
629 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
630}
631
633 SDValue Addr, int JTI,
634 SelectionDAG &DAG) const {
635 SDValue Chain = Value;
636 // Jump table debug info is only needed if CodeView is enabled.
638 Chain = DAG.getJumpTableDebugInfo(JTI, Chain, dl);
639 }
640 return DAG.getNode(ISD::BRIND, dl, MVT::Other, Chain, Addr);
641}
642
643bool
645 const TargetMachine &TM = getTargetMachine();
646 const GlobalValue *GV = GA->getGlobal();
647
648 // If the address is not even local to this DSO we will have to load it from
649 // a got and then add the offset.
650 if (!TM.shouldAssumeDSOLocal(GV))
651 return false;
652
653 // If the code is position independent we will have to add a base register.
655 return false;
656
657 // Otherwise we can do it.
658 return true;
659}
660
661//===----------------------------------------------------------------------===//
662// Optimization Methods
663//===----------------------------------------------------------------------===//
664
665/// If the specified instruction has a constant integer operand and there are
666/// bits set in that constant that are not demanded, then clear those bits and
667/// return true.
669 const APInt &DemandedBits,
670 const APInt &DemandedElts,
671 TargetLoweringOpt &TLO) const {
672 SDLoc DL(Op);
673 unsigned Opcode = Op.getOpcode();
674
675 // Early-out if we've ended up calling an undemanded node, leave this to
676 // constant folding.
677 if (DemandedBits.isZero() || DemandedElts.isZero())
678 return false;
679
680 // Do target-specific constant optimization.
681 if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
682 return TLO.New.getNode();
683
684 // FIXME: ISD::SELECT, ISD::SELECT_CC
685 switch (Opcode) {
686 default:
687 break;
688 case ISD::XOR:
689 case ISD::AND:
690 case ISD::OR: {
691 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
692 if (!Op1C || Op1C->isOpaque())
693 return false;
694
695 // If this is a 'not' op, don't touch it because that's a canonical form.
696 const APInt &C = Op1C->getAPIntValue();
697 if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
698 return false;
699
700 if (!C.isSubsetOf(DemandedBits)) {
701 EVT VT = Op.getValueType();
702 SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
703 SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC,
704 Op->getFlags());
705 return TLO.CombineTo(Op, NewOp);
706 }
707
708 break;
709 }
710 }
711
712 return false;
713}
714
716 const APInt &DemandedBits,
717 TargetLoweringOpt &TLO) const {
718 EVT VT = Op.getValueType();
719 APInt DemandedElts = VT.isVector()
721 : APInt(1, 1);
722 return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
723}
724
725/// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
726/// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast,
727/// but it could be generalized for targets with other types of implicit
728/// widening casts.
730 const APInt &DemandedBits,
731 TargetLoweringOpt &TLO) const {
732 assert(Op.getNumOperands() == 2 &&
733 "ShrinkDemandedOp only supports binary operators!");
734 assert(Op.getNode()->getNumValues() == 1 &&
735 "ShrinkDemandedOp only supports nodes with one result!");
736
737 EVT VT = Op.getValueType();
738 SelectionDAG &DAG = TLO.DAG;
739 SDLoc dl(Op);
740
741 // Early return, as this function cannot handle vector types.
742 if (VT.isVector())
743 return false;
744
745 assert(Op.getOperand(0).getValueType().getScalarSizeInBits() == BitWidth &&
746 Op.getOperand(1).getValueType().getScalarSizeInBits() == BitWidth &&
747 "ShrinkDemandedOp only supports operands that have the same size!");
748
749 // Don't do this if the node has another user, which may require the
750 // full value.
751 if (!Op.getNode()->hasOneUse())
752 return false;
753
754 // Search for the smallest integer type with free casts to and from
755 // Op's type. For expedience, just check power-of-2 integer types.
756 unsigned DemandedSize = DemandedBits.getActiveBits();
757 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
758 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
759 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
760 if (isTruncateFree(Op, SmallVT) && isZExtFree(SmallVT, VT)) {
761 // We found a type with free casts.
762
763 // If the operation has the 'disjoint' flag, then the
764 // operands on the new node are also disjoint.
765 SDNodeFlags Flags(Op->getFlags().hasDisjoint() ? SDNodeFlags::Disjoint
767 unsigned Opcode = Op.getOpcode();
768 if (Opcode == ISD::PTRADD) {
769 // It isn't a ptradd anymore if it doesn't operate on the entire
770 // pointer.
771 Opcode = ISD::ADD;
772 }
773 SDValue X = DAG.getNode(
774 Opcode, dl, SmallVT,
775 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
776 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)), Flags);
777 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
778 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, VT, X);
779 return TLO.CombineTo(Op, Z);
780 }
781 }
782 return false;
783}
784
786 DAGCombinerInfo &DCI) const {
787 SelectionDAG &DAG = DCI.DAG;
788 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
789 !DCI.isBeforeLegalizeOps());
791
792 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
793 if (Simplified) {
794 DCI.AddToWorklist(Op.getNode());
796 }
797 return Simplified;
798}
799
801 const APInt &DemandedElts,
802 DAGCombinerInfo &DCI) const {
803 SelectionDAG &DAG = DCI.DAG;
804 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
805 !DCI.isBeforeLegalizeOps());
807
808 bool Simplified =
809 SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
810 if (Simplified) {
811 DCI.AddToWorklist(Op.getNode());
813 }
814 return Simplified;
815}
816
820 unsigned Depth,
821 bool AssumeSingleUse) const {
822 EVT VT = Op.getValueType();
823
824 // Since the number of lanes in a scalable vector is unknown at compile time,
825 // we track one bit which is implicitly broadcast to all lanes. This means
826 // that all lanes in a scalable vector are considered demanded.
827 APInt DemandedElts = VT.isFixedLengthVector()
829 : APInt(1, 1);
830 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
831 AssumeSingleUse);
832}
833
834// TODO: Under what circumstances can we create nodes? Constant folding?
836 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
837 SelectionDAG &DAG, unsigned Depth) const {
838 EVT VT = Op.getValueType();
839
840 // Limit search depth.
842 return SDValue();
843
844 // Ignore UNDEFs.
845 if (Op.isUndef())
846 return SDValue();
847
848 // Not demanding any bits/elts from Op.
849 if (DemandedBits == 0 || DemandedElts == 0)
850 return DAG.getUNDEF(VT);
851
852 bool IsLE = DAG.getDataLayout().isLittleEndian();
853 unsigned NumElts = DemandedElts.getBitWidth();
854 unsigned BitWidth = DemandedBits.getBitWidth();
855 KnownBits LHSKnown, RHSKnown;
856 switch (Op.getOpcode()) {
857 case ISD::Constant: {
858 const APInt &Value = Op->getAsAPIntVal();
859 if (!Value.isZero() && (Value & DemandedBits).isZero())
860 return DAG.getConstant(0, SDLoc(Op), VT);
861 break;
862 }
863 case ISD::BITCAST: {
864 if (VT.isScalableVector())
865 return SDValue();
866
867 SDValue Src = peekThroughBitcasts(Op.getOperand(0));
868 EVT SrcVT = Src.getValueType();
869 EVT DstVT = Op.getValueType();
870 if (SrcVT == DstVT)
871 return Src;
872
873 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
874 unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
875 if (NumSrcEltBits == NumDstEltBits)
877 Src, DemandedBits, DemandedElts, DAG, Depth + 1))
878 return DAG.getBitcast(DstVT, V);
879
880 if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
881 unsigned Scale = NumDstEltBits / NumSrcEltBits;
882 unsigned NumSrcElts = SrcVT.getVectorNumElements();
883 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
884 for (unsigned i = 0; i != Scale; ++i) {
885 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
886 unsigned BitOffset = EltOffset * NumSrcEltBits;
887 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
888 }
889 // Recursive calls below may turn not demanded elements into poison, so we
890 // need to demand all smaller source elements that maps to a demanded
891 // destination element.
892 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
893
895 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
896 return DAG.getBitcast(DstVT, V);
897 }
898
899 // TODO - bigendian once we have test coverage.
900 if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
901 unsigned Scale = NumSrcEltBits / NumDstEltBits;
902 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
903 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
904 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
905 for (unsigned i = 0; i != NumElts; ++i)
906 if (DemandedElts[i]) {
907 unsigned Offset = (i % Scale) * NumDstEltBits;
908 DemandedSrcBits.insertBits(DemandedBits, Offset);
909 DemandedSrcElts.setBit(i / Scale);
910 }
911
913 Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
914 return DAG.getBitcast(DstVT, V);
915 }
916
917 break;
918 }
920 if (!VT.isScalableVector() && !DemandedElts[0])
921 return DAG.getPOISON(VT);
922 break;
923 }
924 case ISD::AND: {
925 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
926 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
927
928 // If all of the demanded bits are known 1 on one side, return the other.
929 // These bits cannot contribute to the result of the 'and' in this
930 // context.
931 if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
932 return Op.getOperand(0);
933 if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
934 return Op.getOperand(1);
935 break;
936 }
937 case ISD::OR: {
938 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
939 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
940
941 // If all of the demanded bits are known zero on one side, return the
942 // other. These bits cannot contribute to the result of the 'or' in this
943 // context.
944 if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
945 return Op.getOperand(0);
946 if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
947 return Op.getOperand(1);
948 break;
949 }
950 case ISD::XOR: {
951 LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
952 RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
953
954 // If all of the demanded bits are known zero on one side, return the
955 // other.
956 if (DemandedBits.isSubsetOf(RHSKnown.Zero))
957 return Op.getOperand(0);
958 if (DemandedBits.isSubsetOf(LHSKnown.Zero))
959 return Op.getOperand(1);
960 break;
961 }
962 case ISD::ADD:
963 case ISD::MUL:
964 case ISD::SMIN:
965 case ISD::SMAX:
966 case ISD::UMIN:
967 case ISD::UMAX: {
968 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(1),
969 DemandedElts, 1, Depth + 1))
970 return Op.getOperand(0);
971
972 if (DAG.isIdentityElement(Op.getOpcode(), Op->getFlags(), Op.getOperand(0),
973 DemandedElts, 0, Depth + 1))
974 return Op.getOperand(1);
975 break;
976 }
977 case ISD::SHL: {
978 // If we are only demanding sign bits then we can use the shift source
979 // directly.
980 if (std::optional<unsigned> MaxSA =
981 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
982 SDValue Op0 = Op.getOperand(0);
983 unsigned ShAmt = *MaxSA;
984 unsigned NumSignBits =
985 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
986 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
987 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
988 return Op0;
989 }
990 break;
991 }
992 case ISD::SRL: {
993 // If we are only demanding sign bits then we can use the shift source
994 // directly.
995 if (std::optional<unsigned> MaxSA =
996 DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
997 SDValue Op0 = Op.getOperand(0);
998 unsigned ShAmt = *MaxSA;
999 // Must already be signbits in DemandedBits bounds, and can't demand any
1000 // shifted in zeroes.
1001 if (DemandedBits.countl_zero() >= ShAmt) {
1002 unsigned NumSignBits =
1003 DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1004 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
1005 return Op0;
1006 }
1007 }
1008 break;
1009 }
1010 case ISD::SETCC: {
1011 SDValue Op0 = Op.getOperand(0);
1012 SDValue Op1 = Op.getOperand(1);
1013 ISD::CondCode CC = Op.getOperandCondCode(2);
1014 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1015 // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1016 // -1, we may be able to bypass the setcc.
1017 if (DemandedBits.isSignMask() &&
1021 // If we're testing X < 0, then this compare isn't needed - just use X!
1022 // FIXME: We're limiting to integer types here, but this should also work
1023 // if we don't care about FP signed-zero. The use of SETLT with FP means
1024 // that we don't care about NaNs.
1025 if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1027 return Op0;
1028 }
1029 break;
1030 }
1032 // If none of the extended bits are demanded, eliminate the sextinreg.
1033 SDValue Op0 = Op.getOperand(0);
1034 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1035 unsigned ExBits = ExVT.getScalarSizeInBits();
1036 if (DemandedBits.getActiveBits() <= ExBits &&
1038 return Op0;
1039 // If the input is already sign extended, just drop the extension.
1040 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1041 if (NumSignBits >= (BitWidth - ExBits + 1))
1042 return Op0;
1043 break;
1044 }
1048 if (VT.isScalableVector())
1049 return SDValue();
1050
1051 // If we only want the lowest element and none of extended bits, then we can
1052 // return the bitcasted source vector.
1053 SDValue Src = Op.getOperand(0);
1054 EVT SrcVT = Src.getValueType();
1055 EVT DstVT = Op.getValueType();
1056 if (IsLE && DemandedElts == 1 &&
1057 DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
1058 DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
1059 return DAG.getBitcast(DstVT, Src);
1060 }
1061 break;
1062 }
1064 if (VT.isScalableVector())
1065 return SDValue();
1066
1067 // If we don't demand the inserted element, return the base vector.
1068 SDValue Vec = Op.getOperand(0);
1069 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1070 EVT VecVT = Vec.getValueType();
1071 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
1072 !DemandedElts[CIdx->getZExtValue()])
1073 return Vec;
1074 break;
1075 }
1076 case ISD::INSERT_SUBVECTOR: {
1077 if (VT.isScalableVector())
1078 return SDValue();
1079
1080 SDValue Vec = Op.getOperand(0);
1081 SDValue Sub = Op.getOperand(1);
1082 uint64_t Idx = Op.getConstantOperandVal(2);
1083 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1084 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1085 // If we don't demand the inserted subvector, return the base vector.
1086 if (DemandedSubElts == 0)
1087 return Vec;
1088 break;
1089 }
1090 case ISD::VECTOR_SHUFFLE: {
1091 assert(!VT.isScalableVector());
1092 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1093
1094 // If all the demanded elts are from one operand and are inline,
1095 // then we can use the operand directly.
1096 bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
1097 for (unsigned i = 0; i != NumElts; ++i) {
1098 int M = ShuffleMask[i];
1099 if (M < 0 || !DemandedElts[i])
1100 continue;
1101 AllUndef = false;
1102 IdentityLHS &= (M == (int)i);
1103 IdentityRHS &= ((M - NumElts) == i);
1104 }
1105
1106 if (AllUndef)
1107 return DAG.getUNDEF(Op.getValueType());
1108 if (IdentityLHS)
1109 return Op.getOperand(0);
1110 if (IdentityRHS)
1111 return Op.getOperand(1);
1112 break;
1113 }
1114 default:
1115 // TODO: Probably okay to remove after audit; here to reduce change size
1116 // in initial enablement patch for scalable vectors
1117 if (VT.isScalableVector())
1118 return SDValue();
1119
1120 if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
1122 Op, DemandedBits, DemandedElts, DAG, Depth))
1123 return V;
1124 break;
1125 }
1126 return SDValue();
1127}
1128
1131 unsigned Depth) const {
1132 EVT VT = Op.getValueType();
1133 // Since the number of lanes in a scalable vector is unknown at compile time,
1134 // we track one bit which is implicitly broadcast to all lanes. This means
1135 // that all lanes in a scalable vector are considered demanded.
1136 APInt DemandedElts = VT.isFixedLengthVector()
1138 : APInt(1, 1);
1139 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1140 Depth);
1141}
1142
1144 SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
1145 unsigned Depth) const {
1146 APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
1147 return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
1148 Depth);
1149}
1150
1151// Find the smallest power-2 type that is at least 8 bits and can hold a value
1152// of type VT that has KnownBits known sign/zero bits. Returns std::nullopt if
1153// that is wider than VT.
1154static std::optional<EVT> getNarrowAVGType(EVT VT, unsigned KnownBits,
1155 LLVMContext &Ctx) {
1156 unsigned MinWidth =
1157 std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1158 EVT NVT = EVT::getIntegerVT(Ctx, llvm::bit_ceil(MinWidth));
1160 return std::nullopt;
1161 if (VT.isVector())
1162 NVT = EVT::getVectorVT(Ctx, NVT, VT.getVectorElementCount());
1163 return NVT;
1164}
1165
1166// Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
1167// or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
1170 const TargetLowering &TLI,
1171 const APInt &DemandedBits,
1172 const APInt &DemandedElts, unsigned Depth) {
1173 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
1174 "SRL or SRA node is required here!");
1175 // Is the right shift using an immediate value of 1?
1176 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
1177 if (!N1C || !N1C->isOne())
1178 return SDValue();
1179
1180 // We are looking for an avgfloor
1181 // add(ext, ext)
1182 // or one of these as a avgceil
1183 // add(add(ext, ext), 1)
1184 // add(add(ext, 1), ext)
1185 // add(ext, add(ext, 1))
1186 SDValue Add = Op.getOperand(0);
1187 if (Add.getOpcode() != ISD::ADD)
1188 return SDValue();
1189
1190 SDValue ExtOpA = Add.getOperand(0);
1191 SDValue ExtOpB = Add.getOperand(1);
1192 SDValue Add2;
1193 auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3, SDValue A) {
1194 ConstantSDNode *ConstOp;
1195 if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
1196 ConstOp->isOne()) {
1197 ExtOpA = Op1;
1198 ExtOpB = Op3;
1199 Add2 = A;
1200 return true;
1201 }
1202 if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
1203 ConstOp->isOne()) {
1204 ExtOpA = Op1;
1205 ExtOpB = Op2;
1206 Add2 = A;
1207 return true;
1208 }
1209 return false;
1210 };
1211 bool IsCeil =
1212 (ExtOpA.getOpcode() == ISD::ADD &&
1213 MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB, ExtOpA)) ||
1214 (ExtOpB.getOpcode() == ISD::ADD &&
1215 MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA, ExtOpB));
1216
1217 // If the shift is signed (sra):
1218 // - Needs >= 2 sign bit for both operands.
1219 // - Needs >= 2 zero bits.
1220 // If the shift is unsigned (srl):
1221 // - Needs >= 1 zero bit for both operands.
1222 // - Needs 1 demanded bit zero and >= 2 sign bits.
1223 SelectionDAG &DAG = TLO.DAG;
1224 unsigned ShiftOpc = Op.getOpcode();
1225 bool IsSigned = false;
1226 unsigned KnownBits;
1227 unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
1228 unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
1229 unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
1230 unsigned NumZeroA =
1231 DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
1232 unsigned NumZeroB =
1233 DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
1234 unsigned NumZero = std::min(NumZeroA, NumZeroB);
1235
1236 switch (ShiftOpc) {
1237 default:
1238 llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
1239 case ISD::SRA: {
1240 if (NumZero >= 2 && NumSigned < NumZero) {
1241 IsSigned = false;
1242 KnownBits = NumZero;
1243 break;
1244 }
1245 if (NumSigned >= 1) {
1246 IsSigned = true;
1247 KnownBits = NumSigned;
1248 break;
1249 }
1250 return SDValue();
1251 }
1252 case ISD::SRL: {
1253 if (NumZero >= 1 && NumSigned < NumZero) {
1254 IsSigned = false;
1255 KnownBits = NumZero;
1256 break;
1257 }
1258 if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1259 IsSigned = true;
1260 KnownBits = NumSigned;
1261 break;
1262 }
1263 return SDValue();
1264 }
1265 }
1266
1267 unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1268 : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1269
1270 // Find the smallest power-2 type that is legal for this vector size and
1271 // operation, given the original type size and the number of known sign/zero
1272 // bits.
1273 EVT VT = Op.getValueType();
1274 std::optional<EVT> NarrowVT =
1276 if (!NarrowVT)
1277 return SDValue();
1278 EVT NVT = *NarrowVT;
1279 if (TLO.LegalTypes() && !TLI.isOperationLegal(AVGOpc, NVT)) {
1280 // If we could not transform, and (both) adds are nuw/nsw, we can use the
1281 // larger type size to do the transform.
1282 if (TLO.LegalOperations() && !TLI.isOperationLegal(AVGOpc, VT))
1283 return SDValue();
1284 if (DAG.willNotOverflowAdd(IsSigned, Add.getOperand(0),
1285 Add.getOperand(1)) &&
1286 (!Add2 || DAG.willNotOverflowAdd(IsSigned, Add2.getOperand(0),
1287 Add2.getOperand(1))))
1288 NVT = VT;
1289 else
1290 return SDValue();
1291 }
1292
1293 // Don't create a AVGFLOOR node with a scalar constant unless its legal as
1294 // this is likely to stop other folds (reassociation, value tracking etc.)
1295 if (!IsCeil && !TLI.isOperationLegal(AVGOpc, NVT) &&
1296 (isa<ConstantSDNode>(ExtOpA) || isa<ConstantSDNode>(ExtOpB)))
1297 return SDValue();
1298
1299 SDLoc DL(Op);
1300 SDValue ResultAVG =
1301 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, ExtOpA, DL, NVT),
1302 DAG.getExtOrTrunc(IsSigned, ExtOpB, DL, NVT));
1303 return DAG.getExtOrTrunc(IsSigned, ResultAVG, DL, VT);
1304}
1305
1306// Attempt to form ext(avgsubfloor(A, B)) from shr(sub(ext(A), ext(B)), 1).
1309 const TargetLowering &TLI,
1310 const APInt &DemandedBits,
1311 const APInt &DemandedElts, unsigned Depth) {
1312 assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
1313 "SRL or SRA node is required here!");
1314 // Is the right shift using an immediate value of 1?
1315 ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
1316 if (!N1C || !N1C->isOne())
1317 return SDValue();
1318
1319 SDValue Sub = Op.getOperand(0);
1320 if (Sub.getOpcode() != ISD::SUB)
1321 return SDValue();
1322
1323 // The result of the avgsub is sign extended to match the sra. For srl, the
1324 // top bit of the result is always zero so it must not be demanded.
1325 if (Op.getOpcode() == ISD::SRL && !DemandedBits.isSignBitClear())
1326 return SDValue();
1327
1328 SDValue A = Sub.getOperand(0);
1329 SDValue B = Sub.getOperand(1);
1330
1331 // If both operands have at least 2 sign bits or at least 1 leading zero, the
1332 // subtract can't overflow and the operands are extended from a narrower type.
1333 SelectionDAG &DAG = TLO.DAG;
1334 bool IsSigned;
1335 unsigned KnownBits;
1336 unsigned NumSigned =
1337 std::min(DAG.ComputeNumSignBits(A, DemandedElts, Depth),
1338 DAG.ComputeNumSignBits(B, DemandedElts, Depth)) -
1339 1;
1340 unsigned NumZero = std::min(
1341 DAG.computeKnownBits(A, DemandedElts, Depth).countMinLeadingZeros(),
1342 DAG.computeKnownBits(B, DemandedElts, Depth).countMinLeadingZeros());
1343 if (NumZero >= 1 && NumSigned < NumZero) {
1344 IsSigned = false;
1345 KnownBits = NumZero;
1346 } else if (NumSigned >= 1) {
1347 IsSigned = true;
1348 KnownBits = NumSigned;
1349 } else {
1350 return SDValue();
1351 }
1352
1353 unsigned AVGOpc = IsSigned ? ISD::AVGSUBFLOORS : ISD::AVGSUBFLOORU;
1354
1355 // Return true if the AVG node is legal or custom on the type VT will be
1356 // legalized to, provided that legalization doesn't change the scalar size.
1357 // That means vectors that are widened or split are accepted, but integers
1358 // that are promoted or expanded are not.
1359 LLVMContext &Ctx = *DAG.getContext();
1360 auto IsLegalAfterTypeLegalization = [&](EVT VT) {
1361 EVT LegalVT = TLI.getLegalTypeToTransformTo(Ctx, VT);
1362 return LegalVT.getScalarSizeInBits() == VT.getScalarSizeInBits() &&
1363 TLI.isOperationLegal(AVGOpc, LegalVT);
1364 };
1365
1366 // Use the narrow type if the node is legal or custom there. Otherwise fall
1367 // back to the original type, which is still correct since the subtract can't
1368 // overflow. Don't form the node if the target can't do it on either type, as
1369 // expanding it may be worse than the original subtract and shift.
1370 // FIXME: Enable for illegal types/operations like combineShiftToAVG.
1371 EVT VT = Op.getValueType();
1372 std::optional<EVT> NarrowVT = getNarrowAVGType(VT, KnownBits, Ctx);
1373 EVT NVT = VT;
1374 if (NarrowVT && IsLegalAfterTypeLegalization(*NarrowVT))
1375 NVT = *NarrowVT;
1376 else if (!IsLegalAfterTypeLegalization(VT))
1377 return SDValue();
1378
1379 // Don't create an AVGSUBFLOOR node with a scalar constant unless it's legal
1380 // as this is likely to stop other folds (reassociation, value tracking etc.)
1381 if (!TLI.isOperationLegal(AVGOpc, NVT) &&
1383 return SDValue();
1384
1385 // The difference of two unsigned values can be negative, so the result is
1386 // always sign extended.
1387 SDLoc DL(Op);
1388 SDValue ResultAVG =
1389 DAG.getNode(AVGOpc, DL, NVT, DAG.getExtOrTrunc(IsSigned, A, DL, NVT),
1390 DAG.getExtOrTrunc(IsSigned, B, DL, NVT));
1391 return DAG.getExtOrTrunc(/*IsSigned=*/true, ResultAVG, DL, VT);
1392}
1393
1394/// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1395/// result of Op are ever used downstream. If we can use this information to
1396/// simplify Op, create a new simplified DAG node and return true, returning the
1397/// original and new nodes in Old and New. Otherwise, analyze the expression and
1398/// return a mask of Known bits for the expression (used to simplify the
1399/// caller). The Known bits may only be accurate for those bits in the
1400/// OriginalDemandedBits and OriginalDemandedElts.
1402 SDValue Op, const APInt &OriginalDemandedBits,
1403 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1404 unsigned Depth, bool AssumeSingleUse) const {
1405 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1406 assert(Op.getScalarValueSizeInBits() == BitWidth &&
1407 "Mask size mismatches value type size!");
1408
1409 // Don't know anything.
1411
1412 EVT VT = Op.getValueType();
1413 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1414 unsigned NumElts = OriginalDemandedElts.getBitWidth();
1415 assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) &&
1416 "Unexpected vector size");
1417
1418 APInt DemandedBits = OriginalDemandedBits;
1419 APInt DemandedElts = OriginalDemandedElts;
1420 SDLoc dl(Op);
1421
1422 // Undef operand.
1423 if (Op.isUndef())
1424 return false;
1425
1426 // We can't simplify target constants.
1427 if (Op.getOpcode() == ISD::TargetConstant)
1428 return false;
1429
1430 if (Op.getOpcode() == ISD::Constant) {
1431 // We know all of the bits for a constant!
1432 Known = KnownBits::makeConstant(Op->getAsAPIntVal());
1433 return false;
1434 }
1435
1436 if (Op.getOpcode() == ISD::ConstantFP) {
1437 // We know all of the bits for a floating point constant!
1439 cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1440 return false;
1441 }
1442
1443 // Other users may use these bits.
1444 bool HasMultiUse = false;
1445 if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) {
1447 // Limit search depth.
1448 return false;
1449 }
1450 // Allow multiple uses, just set the DemandedBits/Elts to all bits.
1452 DemandedElts = APInt::getAllOnes(NumElts);
1453 HasMultiUse = true;
1454 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1455 // Not demanding any bits/elts from Op.
1456 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1457 } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1458 // Limit search depth.
1459 return false;
1460 }
1461
1462 // Before folding to the LHS, recheck bits excluded from its earlier demand
1463 // using the full result demand. Mask identifies these excluded bits.
1464 // KnownMask selects the Zero/One member of the recomputed LHS known bits
1465 // that must cover Mask & DemandedBits.
1466 auto TryFoldToLHS = [&](const APInt &Mask,
1467 const APInt KnownBits::*KnownMask) {
1468 SDValue LHS = Op.getOperand(0);
1469 APInt MaskedBits = Mask & DemandedBits;
1470 if (MaskedBits.isZero())
1471 return TLO.CombineTo(Op, LHS);
1472
1473 KnownBits LHSKnown;
1474 if (SimplifyDemandedBits(LHS, DemandedBits, DemandedElts, LHSKnown, TLO,
1475 Depth + 1))
1476 return true;
1477
1478 return MaskedBits.isSubsetOf(LHSKnown.*KnownMask) && TLO.CombineTo(Op, LHS);
1479 };
1480
1481 // Try reducing the RHS demand using LHS known bits.
1482 // KnownMask selects the LHS Zero/One bits that make RHS bits irrelevant.
1483 auto TryReduceRHSDemand = [&](const KnownBits &LHSKnown,
1484 const APInt KnownBits::*KnownMask) {
1485 SDValue RHS = Op.getOperand(1);
1486 if (!RHS.hasOneUse() || isConstOrConstSplat(RHS, DemandedElts))
1487 return false;
1488
1489 // Reuse LHS facts if the RHS did not reduce its earlier demand. Otherwise,
1490 // query independent facts to avoid using bits outside that demand.
1491 SDValue LHS = Op.getOperand(0);
1492 // Keep only the selected mask, then compute DemandedBits & ~Mask in place.
1493 // This avoids copying the unused KnownBits mask and extra APInt
1494 // temporaries, which can allocate memory for masks wider than one word.
1495 APInt RHSDemandedBits =
1496 DemandedBits.intersects(Known.*KnownMask)
1497 ? TLO.DAG.computeKnownBits(LHS, DemandedElts, Depth + 1).*KnownMask
1498 : LHSKnown.*KnownMask;
1499 RHSDemandedBits.flipAllBits();
1500 RHSDemandedBits &= DemandedBits;
1501 if (RHSDemandedBits == DemandedBits)
1502 return false;
1503
1504 // A failed retry must not replace Known with reduced-demand facts.
1505 KnownBits RetryKnown;
1506 return SimplifyDemandedBits(RHS, RHSDemandedBits, DemandedElts, RetryKnown,
1507 TLO, Depth + 1);
1508 };
1509
1510 KnownBits Known2;
1511 switch (Op.getOpcode()) {
1512 case ISD::SCALAR_TO_VECTOR: {
1513 if (VT.isScalableVector())
1514 return false;
1515 if (!DemandedElts[0])
1516 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
1517
1518 KnownBits SrcKnown;
1519 SDValue Src = Op.getOperand(0);
1520 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1521 APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1522 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1523 return true;
1524
1525 // Upper elements are poison, so only get the knownbits if we just demand
1526 // the bottom element.
1527 if (DemandedElts == 1)
1528 Known = SrcKnown.anyextOrTrunc(BitWidth);
1529 break;
1530 }
1531 case ISD::BUILD_VECTOR:
1532 // Collect the known bits that are shared by every demanded element.
1533 // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1534 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1535 return false; // Don't fall through, will infinitely loop.
1536 case ISD::SPLAT_VECTOR: {
1537 SDValue Scl = Op.getOperand(0);
1538 APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits());
1539 KnownBits KnownScl;
1540 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1541 return true;
1542
1543 // Implicitly truncate the bits to match the official semantics of
1544 // SPLAT_VECTOR.
1545 Known = KnownScl.trunc(BitWidth);
1546 break;
1547 }
1548 case ISD::FREEZE: {
1549 SDValue N0 = Op.getOperand(0);
1551 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
1552 return TLO.CombineTo(Op, N0);
1553 break;
1554 }
1555 case ISD::LOAD: {
1556 auto *LD = cast<LoadSDNode>(Op);
1557 if (getTargetConstantFromLoad(LD)) {
1558 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1559 return false; // Don't fall through, will infinitely loop.
1560 }
1561 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1562 // If this is a ZEXTLoad and we are looking at the loaded value.
1563 EVT MemVT = LD->getMemoryVT();
1564 unsigned MemBits = MemVT.getScalarSizeInBits();
1565 Known.Zero.setBitsFrom(MemBits);
1566 return false; // Don't fall through, will infinitely loop.
1567 }
1568 break;
1569 }
1571 if (VT.isScalableVector())
1572 return false;
1573 SDValue Vec = Op.getOperand(0);
1574 SDValue Scl = Op.getOperand(1);
1575 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1576 EVT VecVT = Vec.getValueType();
1577
1578 // If index isn't constant, assume we need all vector elements AND the
1579 // inserted element.
1580 APInt DemandedVecElts(DemandedElts);
1581 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1582 unsigned Idx = CIdx->getZExtValue();
1583 DemandedVecElts.clearBit(Idx);
1584
1585 // Inserted element is not required.
1586 if (!DemandedElts[Idx])
1587 return TLO.CombineTo(Op, Vec);
1588 }
1589
1590 KnownBits KnownScl;
1591 unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1592 APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1593 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1594 return true;
1595
1596 Known = KnownScl.anyextOrTrunc(BitWidth);
1597
1598 KnownBits KnownVec;
1599 if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1600 Depth + 1))
1601 return true;
1602
1603 if (!!DemandedVecElts)
1604 Known = Known.intersectWith(KnownVec);
1605
1606 return false;
1607 }
1608 case ISD::INSERT_SUBVECTOR: {
1609 if (VT.isScalableVector())
1610 return false;
1611 // Demand any elements from the subvector and the remainder from the src its
1612 // inserted into.
1613 SDValue Src = Op.getOperand(0);
1614 SDValue Sub = Op.getOperand(1);
1615 uint64_t Idx = Op.getConstantOperandVal(2);
1616 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1617 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1618 APInt DemandedSrcElts = DemandedElts;
1619 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
1620
1621 KnownBits KnownSub, KnownSrc;
1622 if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1623 Depth + 1))
1624 return true;
1625 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1626 Depth + 1))
1627 return true;
1628
1629 Known.setAllConflict();
1630 if (!!DemandedSubElts)
1631 Known = Known.intersectWith(KnownSub);
1632 if (!!DemandedSrcElts)
1633 Known = Known.intersectWith(KnownSrc);
1634
1635 // Attempt to avoid multi-use src if we don't need anything from it.
1636 if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1637 !DemandedSrcElts.isAllOnes()) {
1639 Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1641 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1642 if (NewSub || NewSrc) {
1643 NewSub = NewSub ? NewSub : Sub;
1644 NewSrc = NewSrc ? NewSrc : Src;
1645 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1646 Op.getOperand(2));
1647 return TLO.CombineTo(Op, NewOp);
1648 }
1649 }
1650 break;
1651 }
1653 if (VT.isScalableVector())
1654 return false;
1655 // Offset the demanded elts by the subvector index.
1656 SDValue Src = Op.getOperand(0);
1657 if (Src.getValueType().isScalableVector())
1658 break;
1659 uint64_t Idx = Op.getConstantOperandVal(1);
1660 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1661 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1662
1663 if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1664 Depth + 1))
1665 return true;
1666
1667 // Attempt to avoid multi-use src if we don't need anything from it.
1668 if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1670 Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1671 if (DemandedSrc) {
1672 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1673 Op.getOperand(1));
1674 return TLO.CombineTo(Op, NewOp);
1675 }
1676 }
1677 break;
1678 }
1679 case ISD::CONCAT_VECTORS: {
1680 if (VT.isScalableVector())
1681 return false;
1682 Known.setAllConflict();
1683 EVT SubVT = Op.getOperand(0).getValueType();
1684 unsigned NumSubVecs = Op.getNumOperands();
1685 unsigned NumSubElts = SubVT.getVectorNumElements();
1686 for (unsigned i = 0; i != NumSubVecs; ++i) {
1687 APInt DemandedSubElts =
1688 DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1689 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1690 Known2, TLO, Depth + 1))
1691 return true;
1692 // Known bits are shared by every demanded subvector element.
1693 if (!!DemandedSubElts)
1694 Known = Known.intersectWith(Known2);
1695 }
1696 break;
1697 }
1698 case ISD::VECTOR_SHUFFLE: {
1699 assert(!VT.isScalableVector());
1700 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1701
1702 // Collect demanded elements from shuffle operands..
1703 APInt DemandedLHS, DemandedRHS;
1704 if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS,
1705 DemandedRHS))
1706 break;
1707
1708 if (!!DemandedLHS || !!DemandedRHS) {
1709 SDValue Op0 = Op.getOperand(0);
1710 SDValue Op1 = Op.getOperand(1);
1711
1712 Known.setAllConflict();
1713 if (!!DemandedLHS) {
1714 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1715 Depth + 1))
1716 return true;
1717 Known = Known.intersectWith(Known2);
1718 }
1719 if (!!DemandedRHS) {
1720 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1721 Depth + 1))
1722 return true;
1723 Known = Known.intersectWith(Known2);
1724 }
1725
1726 // Attempt to avoid multi-use ops if we don't need anything from them.
1728 Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1730 Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1731 if (DemandedOp0 || DemandedOp1) {
1732 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1733 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1734 SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1735 return TLO.CombineTo(Op, NewOp);
1736 }
1737 }
1738 break;
1739 }
1740 case ISD::AND: {
1741 SDValue Op0 = Op.getOperand(0);
1742 SDValue Op1 = Op.getOperand(1);
1743
1744 // If the RHS is a constant, check to see if the LHS would be zero without
1745 // using the bits from the RHS. Below, we use knowledge about the RHS to
1746 // simplify the LHS, here we're using information from the LHS to simplify
1747 // the RHS.
1748 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1, DemandedElts)) {
1749 // Do not increment Depth here; that can cause an infinite loop.
1750 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1751 // If the LHS already has zeros where RHSC does, this 'and' is dead.
1752 if ((LHSKnown.Zero & DemandedBits) ==
1753 (~RHSC->getAPIntValue() & DemandedBits))
1754 return TLO.CombineTo(Op, Op0);
1755
1756 // If any of the set bits in the RHS are known zero on the LHS, shrink
1757 // the constant.
1758 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1759 DemandedElts, TLO))
1760 return true;
1761
1762 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1763 // constant, but if this 'and' is only clearing bits that were just set by
1764 // the xor, then this 'and' can be eliminated by shrinking the mask of
1765 // the xor. For example, for a 32-bit X:
1766 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1767 if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1768 LHSKnown.One == ~RHSC->getAPIntValue()) {
1769 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1770 return TLO.CombineTo(Op, Xor);
1771 }
1772 }
1773
1774 // (X +/- Y) & Y --> ~X & Y when Y is a power of 2 (or zero).
1775 SDValue X, Y;
1776 if (sd_match(Op,
1777 m_And(m_Value(Y),
1779 m_Sub(m_Value(X), m_Deferred(Y)))))) &&
1780 TLO.DAG.isKnownToBeAPowerOfTwo(Y, DemandedElts, /*OrZero=*/true)) {
1781 return TLO.CombineTo(
1782 Op, TLO.DAG.getNode(ISD::AND, dl, VT, TLO.DAG.getNOT(dl, X, VT), Y));
1783 }
1784
1785 // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I)
1786 // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits).
1787 if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() &&
1788 (Op0.getOperand(0).isUndef() ||
1790 Op0->hasOneUse()) {
1791 unsigned NumSubElts =
1793 unsigned SubIdx = Op0.getConstantOperandVal(2);
1794 APInt DemandedSub =
1795 APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts);
1796 KnownBits KnownSubMask =
1797 TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1);
1798 if (DemandedBits.isSubsetOf(KnownSubMask.One)) {
1799 SDValue NewAnd =
1800 TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1);
1801 SDValue NewInsert =
1802 TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd,
1803 Op0.getOperand(1), Op0.getOperand(2));
1804 return TLO.CombineTo(Op, NewInsert);
1805 }
1806 }
1807
1808 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1809 Depth + 1))
1810 return true;
1811 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1812 Known2, TLO, Depth + 1))
1813 return true;
1814
1815 // If all of the demanded bits are known one on one side, return the other.
1816 // These bits cannot contribute to the result of the 'and'.
1817 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) {
1818 if (TryFoldToLHS(Known.Zero, &KnownBits::Zero))
1819 return true;
1820 }
1821 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1822 return TLO.CombineTo(Op, Op1);
1823 // If all of the demanded bits in the inputs are known zeros, return zero.
1824 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1825 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1826 // If the RHS is a constant, see if we can simplify it.
1827 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1828 TLO))
1829 return true;
1830 // If the operation can be done in a smaller type, do so.
1832 return true;
1833
1834 // Attempt to avoid multi-use ops if we don't need anything from them.
1835 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1837 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1839 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1840 if (DemandedOp0 || DemandedOp1) {
1841 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1842 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1843 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1844 return TLO.CombineTo(Op, NewOp);
1845 }
1846 }
1847
1848 if (TryReduceRHSDemand(Known2, &KnownBits::Zero))
1849 return true;
1850
1851 Known &= Known2;
1852 break;
1853 }
1854 case ISD::OR: {
1855 SDValue Op0 = Op.getOperand(0);
1856 SDValue Op1 = Op.getOperand(1);
1857 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1858 Depth + 1)) {
1859 Op->dropFlags(SDNodeFlags::Disjoint);
1860 return true;
1861 }
1862
1863 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1864 Known2, TLO, Depth + 1)) {
1865 Op->dropFlags(SDNodeFlags::Disjoint);
1866 return true;
1867 }
1868
1869 // If all of the demanded bits are known zero on one side, return the other.
1870 // These bits cannot contribute to the result of the 'or'.
1871 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) {
1872 if (TryFoldToLHS(Known.One, &KnownBits::One)) {
1873 Op->dropFlags(SDNodeFlags::Disjoint);
1874 return true;
1875 }
1876 }
1877 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1878 return TLO.CombineTo(Op, Op1);
1879 // If the RHS is a constant, see if we can simplify it.
1880 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1881 return true;
1882 // If the operation can be done in a smaller type, do so.
1884 return true;
1885
1886 // Attempt to avoid multi-use ops if we don't need anything from them.
1887 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1889 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1891 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1892 if (DemandedOp0 || DemandedOp1) {
1893 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1894 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1895 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1896 return TLO.CombineTo(Op, NewOp);
1897 }
1898 }
1899
1900 // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2))
1901 // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks.
1902 SDValue X, Y, C1, C2;
1905 m_Value(C2)))))) {
1906 if (SDValue C12 =
1907 TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT, {C1, C2})) {
1908 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12);
1909 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2);
1910 return TLO.CombineTo(Op,
1911 TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY));
1912 }
1913 }
1914
1915 if (TryReduceRHSDemand(Known2, &KnownBits::One)) {
1916 Op->dropFlags(SDNodeFlags::Disjoint);
1917 return true;
1918 }
1919
1920 Known |= Known2;
1921 break;
1922 }
1923 case ISD::XOR: {
1924 SDValue Op0 = Op.getOperand(0);
1925 SDValue Op1 = Op.getOperand(1);
1926
1927 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1928 Depth + 1))
1929 return true;
1930 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1931 Depth + 1))
1932 return true;
1933
1934 // If all of the demanded bits are known zero on one side, return the other.
1935 // These bits cannot contribute to the result of the 'xor'.
1936 if (DemandedBits.isSubsetOf(Known.Zero))
1937 return TLO.CombineTo(Op, Op0);
1938 if (DemandedBits.isSubsetOf(Known2.Zero))
1939 return TLO.CombineTo(Op, Op1);
1940 // If the operation can be done in a smaller type, do so.
1942 return true;
1943
1944 // If all of the unknown bits are known to be zero on one side or the other
1945 // turn this into an *inclusive* or.
1946 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1947 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1948 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1949
1950 ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts);
1951 if (C) {
1952 // If one side is a constant, and all of the set bits in the constant are
1953 // also known set on the other side, turn this into an AND, as we know
1954 // the bits will be cleared.
1955 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1956 // NB: it is okay if more bits are known than are requested
1957 if (C->getAPIntValue() == Known2.One) {
1958 SDValue ANDC =
1959 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1960 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1961 }
1962
1963 // If the RHS is a constant, see if we can change it. Don't alter a -1
1964 // constant because that's a 'not' op, and that is better for combining
1965 // and codegen.
1966 if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1967 // We're flipping all demanded bits. Flip the undemanded bits too.
1968 SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1969 return TLO.CombineTo(Op, New);
1970 }
1971
1972 unsigned Op0Opcode = Op0.getOpcode();
1973 if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) {
1974 if (ConstantSDNode *ShiftC =
1975 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1976 // Don't crash on an oversized shift. We can not guarantee that a
1977 // bogus shift has been simplified to undef.
1978 if (ShiftC->getAPIntValue().ult(BitWidth)) {
1979 uint64_t ShiftAmt = ShiftC->getZExtValue();
1981 Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt)
1982 : Ones.lshr(ShiftAmt);
1983 if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) &&
1985 // If the xor constant is a demanded mask, do a 'not' before the
1986 // shift:
1987 // xor (X << ShiftC), XorC --> (not X) << ShiftC
1988 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
1989 SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT);
1990 return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not,
1991 Op0.getOperand(1)));
1992 }
1993 }
1994 }
1995 }
1996 }
1997
1998 // If we can't turn this into a 'not', try to shrink the constant.
1999 if (!C || !C->isAllOnes())
2000 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
2001 return true;
2002
2003 // Attempt to avoid multi-use ops if we don't need anything from them.
2004 if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
2006 Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
2008 Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
2009 if (DemandedOp0 || DemandedOp1) {
2010 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
2011 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
2012 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
2013 return TLO.CombineTo(Op, NewOp);
2014 }
2015 }
2016
2017 Known ^= Known2;
2018 break;
2019 }
2020 case ISD::SELECT:
2021 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
2022 Known, TLO, Depth + 1))
2023 return true;
2024 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
2025 Known2, TLO, Depth + 1))
2026 return true;
2027
2028 // If the operands are constants, see if we can simplify them.
2029 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
2030 return true;
2031
2032 // Only known if known in both the LHS and RHS.
2033 Known = Known.intersectWith(Known2);
2034 break;
2035 case ISD::VSELECT:
2036 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
2037 Known, TLO, Depth + 1))
2038 return true;
2039 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
2040 Known2, TLO, Depth + 1))
2041 return true;
2042
2043 // Only known if known in both the LHS and RHS.
2044 Known = Known.intersectWith(Known2);
2045 break;
2046 case ISD::SELECT_CC:
2047 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, DemandedElts,
2048 Known, TLO, Depth + 1))
2049 return true;
2050 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
2051 Known2, TLO, Depth + 1))
2052 return true;
2053
2054 // If the operands are constants, see if we can simplify them.
2055 if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
2056 return true;
2057
2058 // Only known if known in both the LHS and RHS.
2059 Known = Known.intersectWith(Known2);
2060 break;
2061 case ISD::SETCC: {
2062 SDValue Op0 = Op.getOperand(0);
2063 SDValue Op1 = Op.getOperand(1);
2064 ISD::CondCode CC = Op.getOperandCondCode(2);
2065 // If we're testing X < 0, X >= 0, X <= -1 or X > -1
2066 // (X is of integer type) then we only need the sign mask of the previous
2067 // result
2068 if (Op1.getValueType().isInteger() &&
2069 (((CC == ISD::SETLT || CC == ISD::SETGE) && isNullOrNullSplat(Op1)) ||
2070 ((CC == ISD::SETLE || CC == ISD::SETGT) &&
2071 isAllOnesOrAllOnesSplat(Op1)))) {
2072 KnownBits KnownOp0;
2075 DemandedElts, KnownOp0, TLO, Depth + 1))
2076 return true;
2077 // If (1) we only need the sign-bit, (2) the setcc operands are the same
2078 // width as the setcc result, and (3) the result of a setcc conforms to 0
2079 // or -1, we may be able to bypass the setcc.
2080 if (DemandedBits.isSignMask() &&
2084 // If we remove a >= 0 or > -1 (for integers), we need to introduce a
2085 // NOT Operation
2086 if (CC == ISD::SETGE || CC == ISD::SETGT) {
2087 SDLoc DL(Op);
2088 EVT VT = Op0.getValueType();
2089 SDValue NotOp0 = TLO.DAG.getNOT(DL, Op0, VT);
2090 return TLO.CombineTo(Op, NotOp0);
2091 }
2092 return TLO.CombineTo(Op, Op0);
2093 }
2094 }
2095 if (getBooleanContents(Op0.getValueType()) ==
2097 BitWidth > 1)
2098 Known.Zero.setBitsFrom(1);
2099 break;
2100 }
2101 case ISD::SHL: {
2102 SDValue Op0 = Op.getOperand(0);
2103 SDValue Op1 = Op.getOperand(1);
2104 EVT ShiftVT = Op1.getValueType();
2105
2106 if (std::optional<unsigned> KnownSA =
2107 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2108 unsigned ShAmt = *KnownSA;
2109 if (ShAmt == 0)
2110 return TLO.CombineTo(Op, Op0);
2111
2112 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
2113 // single shift. We can do this if the bottom bits (which are shifted
2114 // out) are never demanded.
2115 // TODO - support non-uniform vector amounts.
2116 if (Op0.getOpcode() == ISD::SRL) {
2117 if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
2118 if (std::optional<unsigned> InnerSA =
2119 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2120 unsigned C1 = *InnerSA;
2121 unsigned Opc = ISD::SHL;
2122 int Diff = ShAmt - C1;
2123 if (Diff < 0) {
2124 Diff = -Diff;
2125 Opc = ISD::SRL;
2126 }
2127 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
2128 return TLO.CombineTo(
2129 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
2130 }
2131 }
2132 }
2133
2134 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
2135 // are not demanded. This will likely allow the anyext to be folded away.
2136 // TODO - support non-uniform vector amounts.
2137 if (Op0.getOpcode() == ISD::ANY_EXTEND) {
2138 SDValue InnerOp = Op0.getOperand(0);
2139 EVT InnerVT = InnerOp.getValueType();
2140 unsigned InnerBits = InnerVT.getScalarSizeInBits();
2141 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
2142 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
2143 SDValue NarrowShl = TLO.DAG.getNode(
2144 ISD::SHL, dl, InnerVT, InnerOp,
2145 TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl));
2146 return TLO.CombineTo(
2147 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
2148 }
2149
2150 // Repeat the SHL optimization above in cases where an extension
2151 // intervenes: (shl (anyext (shr x, c1)), c2) to
2152 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
2153 // aren't demanded (as above) and that the shifted upper c1 bits of
2154 // x aren't demanded.
2155 // TODO - support non-uniform vector amounts.
2156 if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() &&
2157 InnerOp.hasOneUse()) {
2158 if (std::optional<unsigned> SA2 = TLO.DAG.getValidShiftAmount(
2159 InnerOp, DemandedElts, Depth + 2)) {
2160 unsigned InnerShAmt = *SA2;
2161 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
2162 DemandedBits.getActiveBits() <=
2163 (InnerBits - InnerShAmt + ShAmt) &&
2164 DemandedBits.countr_zero() >= ShAmt) {
2165 SDValue NewSA =
2166 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
2167 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
2168 InnerOp.getOperand(0));
2169 return TLO.CombineTo(
2170 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
2171 }
2172 }
2173 }
2174 }
2175
2176 APInt InDemandedMask = DemandedBits.lshr(ShAmt);
2177 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2178 Depth + 1)) {
2179 // Disable the nsw and nuw flags. We can no longer guarantee that we
2180 // won't wrap after simplification.
2181 Op->dropFlags(SDNodeFlags::NoWrap);
2182 return true;
2183 }
2184 Known <<= ShAmt;
2185 // low bits known zero.
2186 Known.Zero.setLowBits(ShAmt);
2187
2188 // Attempt to avoid multi-use ops if we don't need anything from them.
2189 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2191 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2192 if (DemandedOp0) {
2193 SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
2194 return TLO.CombineTo(Op, NewOp);
2195 }
2196 }
2197
2198 // TODO: Can we merge this fold with the one below?
2199 // Try shrinking the operation as long as the shift amount will still be
2200 // in range.
2201 if (ShAmt < DemandedBits.getActiveBits() && !VT.isVector() &&
2202 Op.getNode()->hasOneUse()) {
2203 // Search for the smallest integer type with free casts to and from
2204 // Op's type. For expedience, just check power-of-2 integer types.
2205 unsigned DemandedSize = DemandedBits.getActiveBits();
2206 for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
2207 SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
2208 EVT SmallVT = EVT::getIntegerVT(*TLO.DAG.getContext(), SmallVTBits);
2209 if (isNarrowingProfitable(Op.getNode(), VT, SmallVT) &&
2210 isTypeDesirableForOp(ISD::SHL, SmallVT) &&
2211 isTruncateFree(VT, SmallVT) && isZExtFree(SmallVT, VT) &&
2212 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, SmallVT))) {
2213 assert(DemandedSize <= SmallVTBits &&
2214 "Narrowed below demanded bits?");
2215 // We found a type with free casts.
2216 SDValue NarrowShl = TLO.DAG.getNode(
2217 ISD::SHL, dl, SmallVT,
2218 TLO.DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
2219 TLO.DAG.getShiftAmountConstant(ShAmt, SmallVT, dl));
2220 return TLO.CombineTo(
2221 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
2222 }
2223 }
2224 }
2225
2226 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2227 // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K))
2228 // Only do this if we demand the upper half so the knownbits are correct.
2229 unsigned HalfWidth = BitWidth / 2;
2230 if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth &&
2231 DemandedBits.countLeadingOnes() >= HalfWidth) {
2232 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth);
2233 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2234 isTypeDesirableForOp(ISD::SHL, HalfVT) &&
2235 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2236 (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) {
2237 // If we're demanding the upper bits at all, we must ensure
2238 // that the upper bits of the shift result are known to be zero,
2239 // which is equivalent to the narrow shift being NUW.
2240 if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) {
2241 bool IsNSW = Known.countMinSignBits() > HalfWidth;
2242 SDNodeFlags Flags;
2243 Flags.setNoSignedWrap(IsNSW);
2244 Flags.setNoUnsignedWrap(IsNUW);
2245 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2246 SDValue NewShiftAmt =
2247 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2248 SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp,
2249 NewShiftAmt, Flags);
2250 SDValue NewExt =
2251 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift);
2252 return TLO.CombineTo(Op, NewExt);
2253 }
2254 }
2255 }
2256 } else {
2257 // This is a variable shift, so we can't shift the demand mask by a known
2258 // amount. But if we are not demanding high bits, then we are not
2259 // demanding those bits from the pre-shifted operand either.
2260 if (unsigned CTLZ = DemandedBits.countl_zero()) {
2261 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
2262 if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO,
2263 Depth + 1)) {
2264 // Disable the nsw and nuw flags. We can no longer guarantee that we
2265 // won't wrap after simplification.
2266 Op->dropFlags(SDNodeFlags::NoWrap);
2267 return true;
2268 }
2269 Known.resetAll();
2270 }
2271 }
2272
2273 // If we are only demanding sign bits then we can use the shift source
2274 // directly.
2275 if (std::optional<unsigned> MaxSA =
2276 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2277 unsigned ShAmt = *MaxSA;
2278 unsigned NumSignBits =
2279 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2280 unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
2281 if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
2282 return TLO.CombineTo(Op, Op0);
2283 }
2284 break;
2285 }
2286 case ISD::SRL: {
2287 SDValue Op0 = Op.getOperand(0);
2288 SDValue Op1 = Op.getOperand(1);
2289 EVT ShiftVT = Op1.getValueType();
2290
2291 if (std::optional<unsigned> KnownSA =
2292 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2293 unsigned ShAmt = *KnownSA;
2294 if (ShAmt == 0)
2295 return TLO.CombineTo(Op, Op0);
2296
2297 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
2298 // single shift. We can do this if the top bits (which are shifted out)
2299 // are never demanded.
2300 // TODO - support non-uniform vector amounts.
2301 if (Op0.getOpcode() == ISD::SHL) {
2302 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2303 if (std::optional<unsigned> InnerSA =
2304 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2305 unsigned C1 = *InnerSA;
2306 unsigned Opc = ISD::SRL;
2307 int Diff = ShAmt - C1;
2308 if (Diff < 0) {
2309 Diff = -Diff;
2310 Opc = ISD::SHL;
2311 }
2312 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
2313 return TLO.CombineTo(
2314 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
2315 }
2316 }
2317 }
2318
2319 // If this is (srl (sra X, C1), ShAmt), see if we can combine this into a
2320 // single sra. We can do this if the top bits are never demanded.
2321 if (Op0.getOpcode() == ISD::SRA && Op0.hasOneUse()) {
2322 if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
2323 if (std::optional<unsigned> InnerSA =
2324 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2325 unsigned C1 = *InnerSA;
2326 // Clamp the combined shift amount if it exceeds the bit width.
2327 unsigned Combined = std::min(C1 + ShAmt, BitWidth - 1);
2328 SDValue NewSA = TLO.DAG.getConstant(Combined, dl, ShiftVT);
2329 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRA, dl, VT,
2330 Op0.getOperand(0), NewSA));
2331 }
2332 }
2333 }
2334
2335 APInt InDemandedMask = (DemandedBits << ShAmt);
2336
2337 // If the shift is exact, then it does demand the low bits (and knows that
2338 // they are zero).
2339 if (Op->getFlags().hasExact())
2340 InDemandedMask.setLowBits(ShAmt);
2341
2342 // Narrow shift to lower half - similar to ShrinkDemandedOp.
2343 // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K))
2344 if ((BitWidth % 2) == 0 && !VT.isVector()) {
2346 EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2);
2347 if (isNarrowingProfitable(Op.getNode(), VT, HalfVT) &&
2348 isTypeDesirableForOp(ISD::SRL, HalfVT) &&
2349 isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
2350 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) &&
2351 ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) ||
2352 TLO.DAG.MaskedValueIsZero(Op0, HiBits))) {
2353 SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
2354 SDValue NewShiftAmt =
2355 TLO.DAG.getShiftAmountConstant(ShAmt, HalfVT, dl);
2356 SDValue NewShift =
2357 TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt,
2358 Op->getFlags() & SDNodeFlags::Exact);
2359 return TLO.CombineTo(
2360 Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift));
2361 }
2362 }
2363
2364 // Compute the new bits that are at the top now.
2365 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2366 Depth + 1))
2367 return true;
2368 Known >>= ShAmt;
2369 // High bits known zero.
2370 Known.Zero.setHighBits(ShAmt);
2371
2372 // Attempt to avoid multi-use ops if we don't need anything from them.
2373 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2375 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2376 if (DemandedOp0) {
2377 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1);
2378 return TLO.CombineTo(Op, NewOp);
2379 }
2380 }
2381 } else {
2382 // Use generic knownbits computation as it has support for non-uniform
2383 // shift amounts.
2384 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2385 }
2386
2387 // If we are only demanding sign bits then we can use the shift source
2388 // directly.
2389 if (std::optional<unsigned> MaxSA =
2390 TLO.DAG.getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1)) {
2391 unsigned ShAmt = *MaxSA;
2392 // Must already be signbits in DemandedBits bounds, and can't demand any
2393 // shifted in zeroes.
2394 if (DemandedBits.countl_zero() >= ShAmt) {
2395 unsigned NumSignBits =
2396 TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
2397 if (DemandedBits.countr_zero() >= (BitWidth - NumSignBits))
2398 return TLO.CombineTo(Op, Op0);
2399 }
2400 }
2401
2402 // Try to match AVG patterns (after shift simplification).
2403 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2404 DemandedElts, Depth + 1))
2405 return TLO.CombineTo(Op, AVG);
2406 if (SDValue AVG = combineShiftToAVGSUB(Op, TLO, *this, DemandedBits,
2407 DemandedElts, Depth + 1))
2408 return TLO.CombineTo(Op, AVG);
2409
2410 break;
2411 }
2412 case ISD::SRA: {
2413 SDValue Op0 = Op.getOperand(0);
2414 SDValue Op1 = Op.getOperand(1);
2415 EVT ShiftVT = Op1.getValueType();
2416
2417 // If we only want bits that already match the signbit then we don't need
2418 // to shift.
2419 unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero();
2420 if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
2421 NumHiDemandedBits)
2422 return TLO.CombineTo(Op, Op0);
2423
2424 // If this is an arithmetic shift right and only the low-bit is set, we can
2425 // always convert this into a logical shr, even if the shift amount is
2426 // variable. The low bit of the shift cannot be an input sign bit unless
2427 // the shift amount is >= the size of the datatype, which is undefined.
2428 if (DemandedBits.isOne())
2429 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2430
2431 if (std::optional<unsigned> KnownSA =
2432 TLO.DAG.getValidShiftAmount(Op, DemandedElts, Depth + 1)) {
2433 unsigned ShAmt = *KnownSA;
2434 if (ShAmt == 0)
2435 return TLO.CombineTo(Op, Op0);
2436
2437 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target
2438 // supports sext_inreg.
2439 if (Op0.getOpcode() == ISD::SHL) {
2440 if (std::optional<unsigned> InnerSA =
2441 TLO.DAG.getValidShiftAmount(Op0, DemandedElts, Depth + 2)) {
2442 unsigned LowBits = BitWidth - ShAmt;
2443 EVT ExtVT = VT.changeElementType(
2444 *TLO.DAG.getContext(),
2445 EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits));
2446
2447 if (*InnerSA == ShAmt) {
2448 if (!TLO.LegalOperations() ||
2450 return TLO.CombineTo(
2451 Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
2452 Op0.getOperand(0),
2453 TLO.DAG.getValueType(ExtVT)));
2454
2455 // Even if we can't convert to sext_inreg, we might be able to
2456 // remove this shift pair if the input is already sign extended.
2457 unsigned NumSignBits =
2458 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts);
2459 if (NumSignBits > ShAmt)
2460 return TLO.CombineTo(Op, Op0.getOperand(0));
2461 }
2462 }
2463 }
2464
2465 APInt InDemandedMask = (DemandedBits << ShAmt);
2466
2467 // If the shift is exact, then it does demand the low bits (and knows that
2468 // they are zero).
2469 if (Op->getFlags().hasExact())
2470 InDemandedMask.setLowBits(ShAmt);
2471
2472 // If any of the demanded bits are produced by the sign extension, we also
2473 // demand the input sign bit.
2474 if (DemandedBits.countl_zero() < ShAmt)
2475 InDemandedMask.setSignBit();
2476
2477 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2478 Depth + 1))
2479 return true;
2480 Known >>= ShAmt;
2481
2482 // If the input sign bit is known to be zero, or if none of the top bits
2483 // are demanded, turn this into an unsigned shift right.
2484 if (Known.Zero[BitWidth - ShAmt - 1] ||
2485 DemandedBits.countl_zero() >= ShAmt) {
2486 SDNodeFlags Flags;
2487 Flags.setExact(Op->getFlags().hasExact());
2488 return TLO.CombineTo(
2489 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
2490 }
2491
2492 int Log2 = DemandedBits.exactLogBase2();
2493 if (Log2 >= 0) {
2494 // The bit must come from the sign.
2495 SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
2496 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
2497 }
2498
2499 if (Known.One[BitWidth - ShAmt - 1])
2500 // New bits are known one.
2501 Known.One.setHighBits(ShAmt);
2502
2503 // Attempt to avoid multi-use ops if we don't need anything from them.
2504 if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2506 Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2507 if (DemandedOp0) {
2508 SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
2509 return TLO.CombineTo(Op, NewOp);
2510 }
2511 }
2512 }
2513
2514 // Try to match AVG patterns (after shift simplification).
2515 if (SDValue AVG = combineShiftToAVG(Op, TLO, *this, DemandedBits,
2516 DemandedElts, Depth + 1))
2517 return TLO.CombineTo(Op, AVG);
2518 if (SDValue AVG = combineShiftToAVGSUB(Op, TLO, *this, DemandedBits,
2519 DemandedElts, Depth + 1))
2520 return TLO.CombineTo(Op, AVG);
2521
2522 break;
2523 }
2524 case ISD::FSHL:
2525 case ISD::FSHR: {
2526 SDValue Op0 = Op.getOperand(0);
2527 SDValue Op1 = Op.getOperand(1);
2528 SDValue Op2 = Op.getOperand(2);
2529 bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
2530
2531 if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
2532 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2533
2534 // For fshl, 0-shift returns the 1st arg.
2535 // For fshr, 0-shift returns the 2nd arg.
2536 if (Amt == 0) {
2537 if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
2538 Known, TLO, Depth + 1))
2539 return true;
2540 break;
2541 }
2542
2543 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
2544 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
2545 APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
2546 APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
2547 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2548 Depth + 1))
2549 return true;
2550 if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
2551 Depth + 1))
2552 return true;
2553
2554 Known2 <<= (IsFSHL ? Amt : (BitWidth - Amt));
2555 Known >>= (IsFSHL ? (BitWidth - Amt) : Amt);
2556 Known = Known.unionWith(Known2);
2557
2558 // Attempt to avoid multi-use ops if we don't need anything from them.
2559 if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
2560 !DemandedElts.isAllOnes()) {
2562 Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
2564 Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
2565 if (DemandedOp0 || DemandedOp1) {
2566 DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
2567 DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
2568 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
2569 DemandedOp1, Op2);
2570 return TLO.CombineTo(Op, NewOp);
2571 }
2572 }
2573 }
2574
2575 if (isPowerOf2_32(BitWidth)) {
2576 // Fold FSHR(Op0,Op1,Op2) -> SRL(Op1,Op2)
2577 // iff we're guaranteed not to use Op0.
2578 // TODO: Add FSHL equivalent?
2579 if (!IsFSHL && !DemandedBits.isAllOnes() &&
2580 (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT))) {
2581 KnownBits KnownAmt =
2582 TLO.DAG.computeKnownBits(Op2, DemandedElts, Depth + 1);
2583 unsigned MaxShiftAmt =
2584 KnownAmt.getMaxValue().getLimitedValue(BitWidth - 1);
2585 // Check we don't demand any shifted bits outside Op1.
2586 if (DemandedBits.countl_zero() >= MaxShiftAmt) {
2587 EVT AmtVT = Op2.getValueType();
2588 SDValue NewAmt =
2589 TLO.DAG.getNode(ISD::AND, dl, AmtVT, Op2,
2590 TLO.DAG.getConstant(BitWidth - 1, dl, AmtVT));
2591 SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, Op1, NewAmt);
2592 return TLO.CombineTo(Op, NewOp);
2593 }
2594 }
2595
2596 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2597 APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
2598 if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts, Known2, TLO,
2599 Depth + 1))
2600 return true;
2601 }
2602 break;
2603 }
2604 case ISD::ROTL:
2605 case ISD::ROTR: {
2606 SDValue Op0 = Op.getOperand(0);
2607 SDValue Op1 = Op.getOperand(1);
2608 bool IsROTL = (Op.getOpcode() == ISD::ROTL);
2609
2610 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
2611 if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
2612 return TLO.CombineTo(Op, Op0);
2613
2614 if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
2615 unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2616 unsigned RevAmt = BitWidth - Amt;
2617
2618 // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
2619 // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
2620 APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
2621 if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2622 Depth + 1))
2623 return true;
2624
2625 // rot*(x, 0) --> x
2626 if (Amt == 0)
2627 return TLO.CombineTo(Op, Op0);
2628
2629 // See if we don't demand either half of the rotated bits.
2630 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
2631 DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) {
2632 Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
2633 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
2634 }
2635 if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
2636 DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) {
2637 Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
2638 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2639 }
2640 }
2641
2642 // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2643 if (isPowerOf2_32(BitWidth)) {
2644 APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
2645 if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
2646 Depth + 1))
2647 return true;
2648 }
2649 break;
2650 }
2651 case ISD::SMIN:
2652 case ISD::SMAX:
2653 case ISD::UMIN:
2654 case ISD::UMAX: {
2655 unsigned Opc = Op.getOpcode();
2656 SDValue Op0 = Op.getOperand(0);
2657 SDValue Op1 = Op.getOperand(1);
2658
2659 // If we're only demanding signbits, then we can simplify to OR/AND node.
2660 unsigned BitOp =
2661 (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND;
2662 unsigned NumSignBits =
2663 std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1),
2664 TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1));
2665 unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero();
2666 if (NumSignBits >= NumDemandedUpperBits)
2667 return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1));
2668
2669 // Check if one arg is always less/greater than (or equal) to the other arg.
2670 KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2671 KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2672 switch (Opc) {
2673 case ISD::SMIN:
2674 if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1))
2675 return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1);
2676 if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1))
2677 return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1);
2678 Known = KnownBits::smin(Known0, Known1);
2679 break;
2680 case ISD::SMAX:
2681 if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1))
2682 return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1);
2683 if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1))
2684 return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1);
2685 Known = KnownBits::smax(Known0, Known1);
2686 break;
2687 case ISD::UMIN:
2688 if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1))
2689 return TLO.CombineTo(Op, *IsULE ? Op0 : Op1);
2690 if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1))
2691 return TLO.CombineTo(Op, *IsULT ? Op0 : Op1);
2692 Known = KnownBits::umin(Known0, Known1);
2693 break;
2694 case ISD::UMAX:
2695 if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
2696 return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1);
2697 if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
2698 return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1);
2699 Known = KnownBits::umax(Known0, Known1);
2700 break;
2701 }
2702 break;
2703 }
2704 case ISD::BITREVERSE: {
2705 SDValue Src = Op.getOperand(0);
2706 APInt DemandedSrcBits = DemandedBits.reverseBits();
2707 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2708 Depth + 1))
2709 return true;
2710 Known = Known2.reverseBits();
2711 break;
2712 }
2713 case ISD::BSWAP: {
2714 SDValue Src = Op.getOperand(0);
2715
2716 // If the only bits demanded come from one byte of the bswap result,
2717 // just shift the input byte into position to eliminate the bswap.
2718 unsigned NLZ = DemandedBits.countl_zero();
2719 unsigned NTZ = DemandedBits.countr_zero();
2720
2721 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
2722 // we need all the bits down to bit 8. Likewise, round NLZ. If we
2723 // have 14 leading zeros, round to 8.
2724 NLZ = alignDown(NLZ, 8);
2725 NTZ = alignDown(NTZ, 8);
2726 // If we need exactly one byte, we can do this transformation.
2727 if (BitWidth - NLZ - NTZ == 8) {
2728 // Replace this with either a left or right shift to get the byte into
2729 // the right place.
2730 unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2731 if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2732 unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2733 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
2734 SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2735 return TLO.CombineTo(Op, NewOp);
2736 }
2737 }
2738
2739 APInt DemandedSrcBits = DemandedBits.byteSwap();
2740 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2741 Depth + 1))
2742 return true;
2743 Known = Known2.byteSwap();
2744 break;
2745 }
2746 case ISD::CTPOP: {
2747 // If only 1 bit is demanded, replace with PARITY as long as we're before
2748 // op legalization.
2749 // FIXME: Limit to scalars for now.
2750 if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2751 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2752 Op.getOperand(0)));
2753
2754 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2755 break;
2756 }
2757 case ISD::PDEP: {
2758 SDValue Op0 = Op.getOperand(0);
2759 SDValue Op1 = Op.getOperand(1);
2760
2761 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
2762 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2763
2764 // If the demanded bits has leading zeroes, we don't demand those from the
2765 // mask.
2766 if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
2767 return true;
2768
2769 // The number of possible 1s in the mask determines the number of LSBs of
2770 // operand 0 used. Undemanded bits from the mask don't matter so filter
2771 // them before counting.
2772 KnownBits Known2;
2773 uint64_t Count = (~Known.Zero & LoMask).popcount();
2774 APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
2775 if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
2776 return true;
2777
2778 // Zeroes are retained from the mask, but not ones.
2779 Known.One.clearAllBits();
2780 // The result will have at least as many trailing zeros as the non-mask
2781 // operand since bits can only map to the same or higher bit position.
2782 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
2783 break;
2784 }
2786 SDValue Op0 = Op.getOperand(0);
2787 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2788 unsigned ExVTBits = ExVT.getScalarSizeInBits();
2789
2790 // If we only care about the highest bit, don't bother shifting right.
2791 if (DemandedBits.isSignMask()) {
2792 unsigned MinSignedBits =
2793 TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2794 bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2795 // However if the input is already sign extended we expect the sign
2796 // extension to be dropped altogether later and do not simplify.
2797 if (!AlreadySignExtended) {
2798 // Compute the correct shift amount type, which must be getShiftAmountTy
2799 // for scalar types after legalization.
2800 SDValue ShiftAmt =
2801 TLO.DAG.getShiftAmountConstant(BitWidth - ExVTBits, VT, dl);
2802 return TLO.CombineTo(Op,
2803 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2804 }
2805 }
2806
2807 // If none of the extended bits are demanded, eliminate the sextinreg.
2808 if (DemandedBits.getActiveBits() <= ExVTBits)
2809 return TLO.CombineTo(Op, Op0);
2810
2811 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2812
2813 // Since the sign extended bits are demanded, we know that the sign
2814 // bit is demanded.
2815 InputDemandedBits.setBit(ExVTBits - 1);
2816
2817 if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2818 Depth + 1))
2819 return true;
2820
2821 // If the sign bit of the input is known set or clear, then we know the
2822 // top bits of the result.
2823
2824 // If the input sign bit is known zero, convert this into a zero extension.
2825 if (Known.Zero[ExVTBits - 1])
2826 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2827
2828 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2829 if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2830 Known.One.setBitsFrom(ExVTBits);
2831 Known.Zero &= Mask;
2832 } else { // Input sign bit unknown
2833 Known.Zero &= Mask;
2834 Known.One &= Mask;
2835 }
2836 break;
2837 }
2838 case ISD::BUILD_PAIR: {
2839 EVT HalfVT = Op.getOperand(0).getValueType();
2840 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2841
2842 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2843 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2844
2845 KnownBits KnownLo, KnownHi;
2846
2847 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2848 return true;
2849
2850 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2851 return true;
2852
2853 Known = KnownHi.concat(KnownLo);
2854 break;
2855 }
2857 if (VT.isScalableVector())
2858 return false;
2859 [[fallthrough]];
2860 case ISD::ZERO_EXTEND: {
2861 SDValue Src = Op.getOperand(0);
2862 EVT SrcVT = Src.getValueType();
2863 unsigned InBits = SrcVT.getScalarSizeInBits();
2864 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2865 bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2866
2867 // If none of the top bits are demanded, convert this into an any_extend.
2868 if (DemandedBits.getActiveBits() <= InBits) {
2869 // If we only need the non-extended bits of the bottom element
2870 // then we can just bitcast to the result.
2871 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2872 VT.getSizeInBits() == SrcVT.getSizeInBits())
2873 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2874
2875 unsigned Opc =
2877 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2878 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2879 }
2880
2881 APInt InDemandedBits = DemandedBits.trunc(InBits);
2882 APInt InDemandedElts = DemandedElts.zext(InElts);
2883 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2884 Depth + 1)) {
2885 Op->dropFlags(SDNodeFlags::NonNeg);
2886 return true;
2887 }
2888 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2889 Known = Known.zext(BitWidth);
2890
2891 // Attempt to avoid multi-use ops if we don't need anything from them.
2893 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2894 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2895 break;
2896 }
2898 if (VT.isScalableVector())
2899 return false;
2900 [[fallthrough]];
2901 case ISD::SIGN_EXTEND: {
2902 SDValue Src = Op.getOperand(0);
2903 EVT SrcVT = Src.getValueType();
2904 unsigned InBits = SrcVT.getScalarSizeInBits();
2905 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2906 bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2907
2908 APInt InDemandedElts = DemandedElts.zext(InElts);
2909 APInt InDemandedBits = DemandedBits.trunc(InBits);
2910
2911 // Since some of the sign extended bits are demanded, we know that the sign
2912 // bit is demanded.
2913 InDemandedBits.setBit(InBits - 1);
2914
2915 // If none of the top bits are demanded, convert this into an any_extend.
2916 if (DemandedBits.getActiveBits() <= InBits) {
2917 // If we only need the non-extended bits of the bottom element
2918 // then we can just bitcast to the result.
2919 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2920 VT.getSizeInBits() == SrcVT.getSizeInBits())
2921 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2922
2923 // Don't lose an all signbits 0/-1 splat on targets with 0/-1 booleans.
2925 TLO.DAG.ComputeNumSignBits(Src, InDemandedElts, Depth + 1) !=
2926 InBits) {
2927 unsigned Opc =
2929 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2930 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2931 }
2932 }
2933
2934 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2935 Depth + 1))
2936 return true;
2937 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2938
2939 // If the sign bit is known one, the top bits match.
2940 Known = Known.sext(BitWidth);
2941
2942 // If the sign bit is known zero, convert this to a zero extend.
2943 if (Known.isNonNegative()) {
2944 unsigned Opc =
2946 if (!TLO.LegalOperations() || isOperationLegal(Opc, VT)) {
2947 SDNodeFlags Flags;
2948 if (!IsVecInReg)
2949 Flags |= SDNodeFlags::NonNeg;
2950 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src, Flags));
2951 }
2952 }
2953
2954 // Attempt to avoid multi-use ops if we don't need anything from them.
2956 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2957 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2958 break;
2959 }
2961 if (VT.isScalableVector())
2962 return false;
2963 [[fallthrough]];
2964 case ISD::ANY_EXTEND: {
2965 SDValue Src = Op.getOperand(0);
2966 EVT SrcVT = Src.getValueType();
2967 unsigned InBits = SrcVT.getScalarSizeInBits();
2968 unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2969 bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2970
2971 // If we only need the bottom element then we can just bitcast.
2972 // TODO: Handle ANY_EXTEND?
2973 if (IsLE && IsVecInReg && DemandedElts == 1 &&
2974 VT.getSizeInBits() == SrcVT.getSizeInBits())
2975 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2976
2977 APInt InDemandedBits = DemandedBits.trunc(InBits);
2978 APInt InDemandedElts = DemandedElts.zext(InElts);
2979 if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2980 Depth + 1))
2981 return true;
2982 assert(Known.getBitWidth() == InBits && "Src width has changed?");
2983 Known = Known.anyext(BitWidth);
2984
2985 // Attempt to avoid multi-use ops if we don't need anything from them.
2987 Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2988 return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2989 break;
2990 }
2991 case ISD::TRUNCATE: {
2992 SDValue Src = Op.getOperand(0);
2993
2994 // Simplify the input, using demanded bit information, and compute the known
2995 // zero/one bits live out.
2996 unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2997 APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2998 if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2999 Depth + 1)) {
3000 // Disable the nsw and nuw flags. We can no longer guarantee that we
3001 // won't wrap after simplification.
3002 Op->dropFlags(SDNodeFlags::NoWrap);
3003 return true;
3004 }
3005 Known = Known.trunc(BitWidth);
3006
3007 // Attempt to avoid multi-use ops if we don't need anything from them.
3009 Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
3010 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
3011
3012 // If the input is only used by this truncate, see if we can shrink it based
3013 // on the known demanded bits.
3014 switch (Src.getOpcode()) {
3015 default:
3016 break;
3017 case ISD::SRL:
3018 // Shrink SRL by a constant if none of the high bits shifted in are
3019 // demanded.
3020 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
3021 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
3022 // undesirable.
3023 break;
3024
3025 if (Src.getNode()->hasOneUse()) {
3026 if (isTruncateFree(Src, VT) &&
3027 !isTruncateFree(Src.getValueType(), VT)) {
3028 // If truncate is only free at trunc(srl), do not turn it into
3029 // srl(trunc). The check is done by first check the truncate is free
3030 // at Src's opcode(srl), then check the truncate is not done by
3031 // referencing sub-register. In test, if both trunc(srl) and
3032 // srl(trunc)'s trunc are free, srl(trunc) performs better. If only
3033 // trunc(srl)'s trunc is free, trunc(srl) is better.
3034 break;
3035 }
3036
3037 std::optional<unsigned> ShAmtC =
3038 TLO.DAG.getValidShiftAmount(Src, DemandedElts, Depth + 2);
3039 if (!ShAmtC || *ShAmtC >= BitWidth)
3040 break;
3041 unsigned ShVal = *ShAmtC;
3042
3043 APInt HighBits =
3044 APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
3045 HighBits.lshrInPlace(ShVal);
3046 HighBits = HighBits.trunc(BitWidth);
3047 if (!(HighBits & DemandedBits)) {
3048 // None of the shifted in bits are needed. Add a truncate of the
3049 // shift input, then shift it.
3050 SDValue NewShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
3051 SDValue NewTrunc =
3052 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
3053 return TLO.CombineTo(
3054 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
3055 }
3056 }
3057 break;
3058 }
3059
3060 break;
3061 }
3062 case ISD::AssertZext: {
3063 // AssertZext demands all of the high bits, plus any of the low bits
3064 // demanded by its users.
3065 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3067 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
3068 TLO, Depth + 1))
3069 return true;
3070
3071 Known.Zero |= ~InMask;
3072 Known.One &= (~Known.Zero);
3073 break;
3074 }
3076 SDValue Src = Op.getOperand(0);
3077 SDValue Idx = Op.getOperand(1);
3078 ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
3079 unsigned EltBitWidth = Src.getScalarValueSizeInBits();
3080
3081 if (SrcEltCnt.isScalable())
3082 return false;
3083
3084 // Demand the bits from every vector element without a constant index.
3085 unsigned NumSrcElts = SrcEltCnt.getFixedValue();
3086 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3087 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
3088 if (CIdx->getAPIntValue().ult(NumSrcElts))
3089 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
3090
3091 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3092 // anything about the extended bits.
3093 APInt DemandedSrcBits = DemandedBits;
3094 if (BitWidth > EltBitWidth)
3095 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
3096
3097 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
3098 Depth + 1))
3099 return true;
3100
3101 // Attempt to avoid multi-use ops if we don't need anything from them.
3102 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
3103 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
3104 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
3105 SDValue NewOp =
3106 TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
3107 return TLO.CombineTo(Op, NewOp);
3108 }
3109 }
3110
3111 Known = Known2;
3112 if (BitWidth > EltBitWidth)
3113 Known = Known.anyext(BitWidth);
3114 break;
3115 }
3116 case ISD::BITCAST: {
3117 if (VT.isScalableVector())
3118 return false;
3119 SDValue Src = Op.getOperand(0);
3120 EVT SrcVT = Src.getValueType();
3121 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
3122
3123 // If this is an FP->Int bitcast and if the sign bit is the only
3124 // thing demanded, turn this into a FGETSIGN.
3125 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
3126 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
3127 SrcVT.isFloatingPoint()) {
3129 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
3130 // place. We expect the SHL to be eliminated by other optimizations.
3131 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, VT, Src);
3132 unsigned ShVal = Op.getValueSizeInBits() - 1;
3133 SDValue ShAmt = TLO.DAG.getShiftAmountConstant(ShVal, VT, dl);
3134 return TLO.CombineTo(Op,
3135 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
3136 }
3137 }
3138
3139 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
3140 // Demand the elt/bit if any of the original elts/bits are demanded.
3141 if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
3142 unsigned Scale = BitWidth / NumSrcEltBits;
3143 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3144 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
3145 for (unsigned i = 0; i != Scale; ++i) {
3146 unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
3147 unsigned BitOffset = EltOffset * NumSrcEltBits;
3148 DemandedSrcBits |= DemandedBits.extractBits(NumSrcEltBits, BitOffset);
3149 }
3150 // Recursive calls below may turn not demanded elements into poison, so we
3151 // need to demand all smaller source elements that maps to a demanded
3152 // destination element.
3153 APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3154
3155 APInt KnownSrcUndef, KnownSrcZero;
3156 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
3157 KnownSrcZero, TLO, Depth + 1))
3158 return true;
3159
3160 KnownBits KnownSrcBits;
3161 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
3162 KnownSrcBits, TLO, Depth + 1))
3163 return true;
3164 } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
3165 // TODO - bigendian once we have test coverage.
3166 unsigned Scale = NumSrcEltBits / BitWidth;
3167 unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
3168 APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
3169 APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
3170 for (unsigned i = 0; i != NumElts; ++i)
3171 if (DemandedElts[i]) {
3172 unsigned Offset = (i % Scale) * BitWidth;
3173 DemandedSrcBits.insertBits(DemandedBits, Offset);
3174 DemandedSrcElts.setBit(i / Scale);
3175 }
3176
3177 if (SrcVT.isVector()) {
3178 APInt KnownSrcUndef, KnownSrcZero;
3179 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
3180 KnownSrcZero, TLO, Depth + 1))
3181 return true;
3182 }
3183
3184 KnownBits KnownSrcBits;
3185 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
3186 KnownSrcBits, TLO, Depth + 1))
3187 return true;
3188
3189 // Attempt to avoid multi-use ops if we don't need anything from them.
3190 if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
3191 if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
3192 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
3193 SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc);
3194 return TLO.CombineTo(Op, NewOp);
3195 }
3196 }
3197 }
3198
3199 // If this is a bitcast, let computeKnownBits handle it. Only do this on a
3200 // recursive call where Known may be useful to the caller.
3201 if (Depth > 0) {
3202 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3203 return false;
3204 }
3205 break;
3206 }
3207 case ISD::MUL:
3208 if (DemandedBits.isPowerOf2()) {
3209 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
3210 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
3211 // odd (has LSB set), then the left-shifted low bit of X is the answer.
3212 unsigned CTZ = DemandedBits.countr_zero();
3213 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
3214 if (C && C->getAPIntValue().countr_zero() == CTZ) {
3215 SDValue AmtC = TLO.DAG.getShiftAmountConstant(CTZ, VT, dl);
3216 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
3217 return TLO.CombineTo(Op, Shl);
3218 }
3219 }
3220 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
3221 // X * X is odd iff X is odd.
3222 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
3223 if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
3224 SDValue One = TLO.DAG.getConstant(1, dl, VT);
3225 SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
3226 return TLO.CombineTo(Op, And1);
3227 }
3228 [[fallthrough]];
3229 case ISD::PTRADD:
3230 if (Op.getOperand(0).getValueType() != Op.getOperand(1).getValueType())
3231 break;
3232 // PTRADD behaves like ADD if pointers are represented as integers.
3233 [[fallthrough]];
3234 case ISD::ADD:
3235 case ISD::SUB: {
3236 // Add, Sub, and Mul don't demand any bits in positions beyond that
3237 // of the highest bit demanded of them.
3238 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
3239 SDNodeFlags Flags = Op.getNode()->getFlags();
3240 unsigned DemandedBitsLZ = DemandedBits.countl_zero();
3241 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
3242 KnownBits KnownOp0, KnownOp1;
3243 auto GetDemandedBitsLHSMask = [&](APInt Demanded,
3244 const KnownBits &KnownRHS) {
3245 if (Op.getOpcode() == ISD::MUL)
3246 Demanded.clearHighBits(KnownRHS.countMinTrailingZeros());
3247 return Demanded;
3248 };
3249 if (SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO,
3250 Depth + 1) ||
3251 SimplifyDemandedBits(Op0, GetDemandedBitsLHSMask(LoMask, KnownOp1),
3252 DemandedElts, KnownOp0, TLO, Depth + 1) ||
3253 // See if the operation should be performed at a smaller bit width.
3255 // Disable the nsw and nuw flags. We can no longer guarantee that we
3256 // won't wrap after simplification.
3257 Op->dropFlags(SDNodeFlags::NoWrap);
3258 return true;
3259 }
3260
3261 // neg x with only low bit demanded is simply x.
3262 if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() &&
3263 isNullConstant(Op0))
3264 return TLO.CombineTo(Op, Op1);
3265
3266 // Attempt to avoid multi-use ops if we don't need anything from them.
3267 if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
3269 Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3271 Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
3272 if (DemandedOp0 || DemandedOp1) {
3273 Op0 = DemandedOp0 ? DemandedOp0 : Op0;
3274 Op1 = DemandedOp1 ? DemandedOp1 : Op1;
3275 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1,
3276 Flags & ~SDNodeFlags::NoWrap);
3277 return TLO.CombineTo(Op, NewOp);
3278 }
3279 }
3280
3281 // If we have a constant operand, we may be able to turn it into -1 if we
3282 // do not demand the high bits. This can make the constant smaller to
3283 // encode, allow more general folding, or match specialized instruction
3284 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
3285 // is probably not useful (and could be detrimental).
3287 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
3288 if (C && !C->isAllOnes() && !C->isOne() &&
3289 (C->getAPIntValue() | HighMask).isAllOnes()) {
3290 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
3291 // Disable the nsw and nuw flags. We can no longer guarantee that we
3292 // won't wrap after simplification.
3293 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1,
3294 Flags & ~SDNodeFlags::NoWrap);
3295 return TLO.CombineTo(Op, NewOp);
3296 }
3297
3298 // Match a multiply with a disguised negated-power-of-2 and convert to a
3299 // an equivalent shift-left amount.
3300 // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3301 auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
3302 if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
3303 return 0;
3304
3305 // Don't touch opaque constants. Also, ignore zero and power-of-2
3306 // multiplies. Those will get folded later.
3307 ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
3308 if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
3309 !MulC->getAPIntValue().isPowerOf2()) {
3310 APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
3311 if (UnmaskedC.isNegatedPowerOf2())
3312 return (-UnmaskedC).logBase2();
3313 }
3314 return 0;
3315 };
3316
3317 auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y,
3318 unsigned ShlAmt) {
3319 SDValue ShlAmtC = TLO.DAG.getShiftAmountConstant(ShlAmt, VT, dl);
3320 SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
3321 SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
3322 return TLO.CombineTo(Op, Res);
3323 };
3324
3326 if (Op.getOpcode() == ISD::ADD) {
3327 // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
3328 if (unsigned ShAmt = getShiftLeftAmt(Op0))
3329 return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
3330 // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
3331 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3332 return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
3333 }
3334 if (Op.getOpcode() == ISD::SUB) {
3335 // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
3336 if (unsigned ShAmt = getShiftLeftAmt(Op1))
3337 return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
3338 }
3339 }
3340
3341 if (Op.getOpcode() == ISD::MUL) {
3342 Known = KnownBits::mul(KnownOp0, KnownOp1);
3343 } else { // Op.getOpcode() is either ISD::ADD, ISD::PTRADD, or ISD::SUB.
3345 Op.getOpcode() != ISD::SUB, Flags.hasNoSignedWrap(),
3346 Flags.hasNoUnsignedWrap(), KnownOp0, KnownOp1);
3347 }
3348 break;
3349 }
3350 case ISD::FABS: {
3351 SDValue Op0 = Op.getOperand(0);
3352 APInt SignMask = APInt::getSignMask(BitWidth);
3353
3354 if (!DemandedBits.intersects(SignMask))
3355 return TLO.CombineTo(Op, Op0);
3356
3357 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3358 Depth + 1))
3359 return true;
3360
3361 if (Known.isNonNegative())
3362 return TLO.CombineTo(Op, Op0);
3363 if (Known.isNegative())
3364 return TLO.CombineTo(
3365 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT, Op0, Op->getFlags()));
3366
3367 Known.Zero |= SignMask;
3368 Known.One &= ~SignMask;
3369
3370 break;
3371 }
3372 case ISD::FCOPYSIGN: {
3373 SDValue Op0 = Op.getOperand(0);
3374 SDValue Op1 = Op.getOperand(1);
3375
3376 unsigned BitWidth0 = Op0.getScalarValueSizeInBits();
3377 unsigned BitWidth1 = Op1.getScalarValueSizeInBits();
3378 APInt SignMask0 = APInt::getSignMask(BitWidth0);
3379 APInt SignMask1 = APInt::getSignMask(BitWidth1);
3380
3381 if (!DemandedBits.intersects(SignMask0))
3382 return TLO.CombineTo(Op, Op0);
3383
3384 if (SimplifyDemandedBits(Op0, ~SignMask0 & DemandedBits, DemandedElts,
3385 Known, TLO, Depth + 1) ||
3386 SimplifyDemandedBits(Op1, SignMask1, DemandedElts, Known2, TLO,
3387 Depth + 1))
3388 return true;
3389
3390 if (Known2.isNonNegative())
3391 return TLO.CombineTo(
3392 Op, TLO.DAG.getNode(ISD::FABS, dl, VT, Op0, Op->getFlags()));
3393
3394 if (Known2.isNegative())
3395 return TLO.CombineTo(
3396 Op, TLO.DAG.getNode(ISD::FNEG, dl, VT,
3397 TLO.DAG.getNode(ISD::FABS, SDLoc(Op0), VT, Op0)));
3398
3399 Known.Zero &= ~SignMask0;
3400 Known.One &= ~SignMask0;
3401 break;
3402 }
3403 case ISD::FNEG: {
3404 SDValue Op0 = Op.getOperand(0);
3405 APInt SignMask = APInt::getSignMask(BitWidth);
3406
3407 if (!DemandedBits.intersects(SignMask))
3408 return TLO.CombineTo(Op, Op0);
3409
3410 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known, TLO,
3411 Depth + 1))
3412 return true;
3413
3414 if (!Known.isSignUnknown()) {
3415 Known.Zero ^= SignMask;
3416 Known.One ^= SignMask;
3417 }
3418
3419 break;
3420 }
3421 default:
3422 // We also ask the target about intrinsics (which could be specific to it).
3423 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3424 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
3425 // TODO: Probably okay to remove after audit; here to reduce change size
3426 // in initial enablement patch for scalable vectors
3427 if (Op.getValueType().isScalableVector())
3428 break;
3430 Known, TLO, Depth))
3431 return true;
3432 break;
3433 }
3434
3435 // Just use computeKnownBits to compute output bits.
3436 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
3437 break;
3438 }
3439
3440 // If we know the value of all of the demanded bits, return this as a
3441 // constant.
3443 DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
3444 // Avoid folding to a constant if any OpaqueConstant is involved.
3445 if (llvm::any_of(Op->ops(), [](SDValue V) {
3446 auto *C = dyn_cast<ConstantSDNode>(V);
3447 return C && C->isOpaque();
3448 }))
3449 return false;
3450 if (VT.isInteger())
3451 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
3452 if (VT.isFloatingPoint())
3453 return TLO.CombineTo(
3455 dl, VT));
3456 }
3457
3458 // A multi use 'all demanded elts' simplify failed to find any knownbits.
3459 // Try again just for the original demanded elts.
3460 // Ensure we do this AFTER constant folding above.
3461 if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes())
3462 Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth);
3463
3464 return false;
3465}
3466
3468 const APInt &DemandedElts,
3469 DAGCombinerInfo &DCI) const {
3470 SelectionDAG &DAG = DCI.DAG;
3471 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3472 !DCI.isBeforeLegalizeOps());
3473
3474 APInt KnownUndef, KnownZero;
3475 bool Simplified =
3476 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
3477 if (Simplified) {
3478 DCI.AddToWorklist(Op.getNode());
3479 DCI.CommitTargetLoweringOpt(TLO);
3480 }
3481
3482 return Simplified;
3483}
3484
3485/// Given a vector binary operation and known undefined elements for each input
3486/// operand, compute whether each element of the output is undefined.
3488 const APInt &UndefOp0,
3489 const APInt &UndefOp1) {
3490 EVT VT = BO.getValueType();
3492 "Vector binop only");
3493
3494 EVT EltVT = VT.getVectorElementType();
3495 unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1;
3496 assert(UndefOp0.getBitWidth() == NumElts &&
3497 UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
3498
3499 auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
3500 const APInt &UndefVals) {
3501 if (UndefVals[Index])
3502 return DAG.getUNDEF(EltVT);
3503
3504 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
3505 // Try hard to make sure that the getNode() call is not creating temporary
3506 // nodes. Ignore opaque integers because they do not constant fold.
3507 SDValue Elt = BV->getOperand(Index);
3508 auto *C = dyn_cast<ConstantSDNode>(Elt);
3509 if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
3510 return Elt;
3511 }
3512
3513 return SDValue();
3514 };
3515
3516 APInt KnownUndef = APInt::getZero(NumElts);
3517 for (unsigned i = 0; i != NumElts; ++i) {
3518 // If both inputs for this element are either constant or undef and match
3519 // the element type, compute the constant/undef result for this element of
3520 // the vector.
3521 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
3522 // not handle FP constants. The code within getNode() should be refactored
3523 // to avoid the danger of creating a bogus temporary node here.
3524 SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
3525 SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
3526 if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
3527 if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
3528 KnownUndef.setBit(i);
3529 }
3530 return KnownUndef;
3531}
3532
3534 SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
3535 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
3536 bool AssumeSingleUse) const {
3537 EVT VT = Op.getValueType();
3538 unsigned Opcode = Op.getOpcode();
3539 APInt DemandedElts = OriginalDemandedElts;
3540 unsigned NumElts = DemandedElts.getBitWidth();
3541 assert(VT.isVector() && "Expected vector op");
3542
3543 KnownUndef = KnownZero = APInt::getZero(NumElts);
3544
3546 return false;
3547
3548 // TODO: For now we assume we know nothing about scalable vectors.
3549 if (VT.isScalableVector())
3550 return false;
3551
3552 assert(VT.getVectorNumElements() == NumElts &&
3553 "Mask size mismatches value type element count!");
3554
3555 // Undef operand.
3556 if (Op.isUndef()) {
3557 KnownUndef.setAllBits();
3558 return false;
3559 }
3560
3561 // If Op has other users, assume that all elements are needed.
3562 if (!AssumeSingleUse && !Op.getNode()->hasOneUse())
3563 DemandedElts.setAllBits();
3564
3565 // Not demanding any elements from Op.
3566 if (DemandedElts == 0) {
3567 KnownUndef.setAllBits();
3568 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3569 }
3570
3571 // Limit search depth.
3573 return false;
3574
3575 SDLoc DL(Op);
3576 unsigned EltSizeInBits = VT.getScalarSizeInBits();
3577 bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
3578
3579 auto TryShrinkBinOp = [&](SDValue Op0, SDValue Op1) {
3580 unsigned ShrunkSize = getPreferredShrunkVectorSizeInBits(Op, DemandedElts);
3581 if (!ShrunkSize)
3582 return false;
3583
3584 assert(ShrunkSize % EltSizeInBits == 0 &&
3585 "Shrunk size not a multiple of element size");
3586 assert(ShrunkSize < VT.getSizeInBits() &&
3587 "Shrunk size must be < original vector size");
3588 assert(ShrunkSize >= EltSizeInBits * DemandedElts.getActiveBits() &&
3589 "Shrunk size must be >= demanded size");
3590
3591 EVT ShrunkVT = VT.changeVectorElementCount(
3592 *TLO.DAG.getContext(),
3593 ElementCount::getFixed(ShrunkSize / EltSizeInBits));
3594 Op0 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op0, 0);
3595 Op1 = TLO.DAG.getExtractSubvector(DL, ShrunkVT, Op1, 0);
3596 SDValue NewOp =
3597 TLO.DAG.getNode(Opcode, DL, ShrunkVT, Op0, Op1, Op->getFlags());
3598 return TLO.CombineTo(
3599 Op, TLO.DAG.getInsertSubvector(DL, TLO.DAG.getUNDEF(VT), NewOp, 0));
3600 };
3601
3602 // Helper for demanding the specified elements and all the bits of both binary
3603 // operands.
3604 auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
3605 SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
3606 TLO.DAG, Depth + 1);
3607 SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
3608 TLO.DAG, Depth + 1);
3609 if (NewOp0 || NewOp1) {
3610 SDValue NewOp =
3611 TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0,
3612 NewOp1 ? NewOp1 : Op1, Op->getFlags());
3613 return TLO.CombineTo(Op, NewOp);
3614 }
3615
3616 if (TryShrinkBinOp(Op0, Op1))
3617 return true;
3618
3619 return false;
3620 };
3621
3622 switch (Opcode) {
3623 case ISD::SCALAR_TO_VECTOR: {
3624 if (!DemandedElts[0])
3625 return TLO.CombineTo(Op, TLO.DAG.getPOISON(VT));
3626 // Upper elements are poison, not undef - don't mark them as KnownUndef.
3627 break;
3628 }
3629 case ISD::BITCAST: {
3630 SDValue Src = Op.getOperand(0);
3631 EVT SrcVT = Src.getValueType();
3632
3633 if (!SrcVT.isVector()) {
3634 // TODO - bigendian once we have test coverage.
3635 if (IsLE) {
3636 APInt DemandedSrcBits = APInt::getZero(SrcVT.getSizeInBits());
3637 unsigned EltSize = VT.getScalarSizeInBits();
3638 for (unsigned I = 0; I != NumElts; ++I) {
3639 if (DemandedElts[I]) {
3640 unsigned Offset = I * EltSize;
3641 DemandedSrcBits.setBits(Offset, Offset + EltSize);
3642 }
3643 }
3645 if (SimplifyDemandedBits(Src, DemandedSrcBits, Known, TLO, Depth + 1))
3646 return true;
3647 }
3648 break;
3649 }
3650
3651 // Fast handling of 'identity' bitcasts.
3652 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3653 if (NumSrcElts == NumElts)
3654 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
3655 KnownZero, TLO, Depth + 1);
3656
3657 APInt SrcDemandedElts, SrcZero, SrcUndef;
3658
3659 // Bitcast from 'large element' src vector to 'small element' vector, we
3660 // must demand a source element if any DemandedElt maps to it.
3661 if ((NumElts % NumSrcElts) == 0) {
3662 unsigned Scale = NumElts / NumSrcElts;
3663 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3664 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3665 TLO, Depth + 1))
3666 return true;
3667
3668 // Try calling SimplifyDemandedBits, converting demanded elts to the bits
3669 // of the large element.
3670 // TODO - bigendian once we have test coverage.
3671 if (IsLE) {
3672 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
3673 APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
3674 for (unsigned i = 0; i != NumElts; ++i)
3675 if (DemandedElts[i]) {
3676 unsigned Ofs = (i % Scale) * EltSizeInBits;
3677 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
3678 }
3679
3681 if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
3682 TLO, Depth + 1))
3683 return true;
3684
3685 // The bitcast has split each wide element into a number of
3686 // narrow subelements. We have just computed the Known bits
3687 // for wide elements. See if element splitting results in
3688 // some subelements being zero. Only for demanded elements!
3689 for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
3690 if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
3691 .isAllOnes())
3692 continue;
3693 for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
3694 unsigned Elt = Scale * SrcElt + SubElt;
3695 // A wholly-undef source lane is reported as undef below; don't also
3696 // flag it as zero, keeping the undef and zero sets disjoint.
3697 if (DemandedElts[Elt] && !SrcUndef[SrcElt])
3698 KnownZero.setBit(Elt);
3699 }
3700 }
3701 }
3702
3703 // If the src element is zero/undef then all the output elements will be -
3704 // only demanded elements are guaranteed to be correct.
3705 for (unsigned i = 0; i != NumSrcElts; ++i) {
3706 if (SrcDemandedElts[i]) {
3707 if (SrcZero[i])
3708 KnownZero.setBits(i * Scale, (i + 1) * Scale);
3709 if (SrcUndef[i])
3710 KnownUndef.setBits(i * Scale, (i + 1) * Scale);
3711 }
3712 }
3713 }
3714
3715 // Bitcast from 'small element' src vector to 'large element' vector, we
3716 // demand all smaller source elements covered by the larger demanded element
3717 // of this vector.
3718 if ((NumSrcElts % NumElts) == 0) {
3719 unsigned Scale = NumSrcElts / NumElts;
3720 SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3721 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3722 TLO, Depth + 1))
3723 return true;
3724
3725 // If all the src elements covering an output element are zero/undef, then
3726 // the output element will be as well, assuming it was demanded.
3727 for (unsigned i = 0; i != NumElts; ++i) {
3728 if (DemandedElts[i]) {
3729 if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
3730 KnownZero.setBit(i);
3731 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
3732 KnownUndef.setBit(i);
3733 }
3734 }
3735 }
3736 break;
3737 }
3738 case ISD::FREEZE: {
3739 SDValue N0 = Op.getOperand(0);
3741 N0, DemandedElts, UndefPoisonKind::UndefOrPoison, Depth + 1))
3742 return TLO.CombineTo(Op, N0);
3743
3744 // TODO: Replace this with the general fold from DAGCombiner::visitFREEZE
3745 // freeze(op(x, ...)) -> op(freeze(x), ...).
3746 // Don't sink the freeze below SCALAR_TO_VECTOR when the scalar is a load
3747 // of a promoted (wider than the element) type: freeze(load) can never be
3748 // folded away (the loaded value may be poison in memory), and the extra
3749 // freeze node then blocks ISel patterns matching scalar_to_vector of a
3750 // load, e.g. the AArch64 scalar_to_vector(extload) -> ldr b/h forms.
3751 // freeze(scalar_to_vector(load)) is equivalent for the demanded element
3752 // zero, and ISel selects the freeze as a plain copy.
3753 if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR && DemandedElts == 1) {
3754 SDValue Scalar = N0.getOperand(0);
3755 bool IsPromotedLoad = Scalar.getOpcode() == ISD::LOAD &&
3756 Scalar.getValueType() != VT.getVectorElementType();
3757 if (!IsPromotedLoad)
3758 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
3759 TLO.DAG.getFreeze(Scalar)));
3760 }
3761 break;
3762 }
3763 case ISD::BUILD_VECTOR: {
3764 // Check all elements and simplify any unused elements with UNDEF.
3765 if (!DemandedElts.isAllOnes()) {
3766 // Don't simplify BROADCASTS.
3767 if (llvm::any_of(Op->op_values(),
3768 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
3770 bool Updated = false;
3771 for (unsigned i = 0; i != NumElts; ++i) {
3772 if (!DemandedElts[i] && !Ops[i].isUndef()) {
3773 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
3774 KnownUndef.setBit(i);
3775 Updated = true;
3776 }
3777 }
3778 if (Updated)
3779 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
3780 }
3781 }
3782 for (unsigned i = 0; i != NumElts; ++i) {
3783 SDValue SrcOp = Op.getOperand(i);
3784 if (SrcOp.isUndef()) {
3785 KnownUndef.setBit(i);
3786 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
3788 KnownZero.setBit(i);
3789 }
3790 }
3791 break;
3792 }
3793 case ISD::CONCAT_VECTORS: {
3794 EVT SubVT = Op.getOperand(0).getValueType();
3795 unsigned NumSubVecs = Op.getNumOperands();
3796 unsigned NumSubElts = SubVT.getVectorNumElements();
3797 for (unsigned i = 0; i != NumSubVecs; ++i) {
3798 SDValue SubOp = Op.getOperand(i);
3799 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3800 APInt SubUndef, SubZero;
3801 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
3802 Depth + 1))
3803 return true;
3804 KnownUndef.insertBits(SubUndef, i * NumSubElts);
3805 KnownZero.insertBits(SubZero, i * NumSubElts);
3806 }
3807
3808 // Attempt to avoid multi-use ops if we don't need anything from them.
3809 if (!DemandedElts.isAllOnes()) {
3810 bool FoundNewSub = false;
3811 SmallVector<SDValue, 2> DemandedSubOps;
3812 for (unsigned i = 0; i != NumSubVecs; ++i) {
3813 SDValue SubOp = Op.getOperand(i);
3814 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3816 SubOp, SubElts, TLO.DAG, Depth + 1);
3817 DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
3818 FoundNewSub = NewSubOp ? true : FoundNewSub;
3819 }
3820 if (FoundNewSub) {
3821 SDValue NewOp =
3822 TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
3823 return TLO.CombineTo(Op, NewOp);
3824 }
3825 }
3826 break;
3827 }
3828 case ISD::INSERT_SUBVECTOR: {
3829 // Demand any elements from the subvector and the remainder from the src it
3830 // is inserted into.
3831 SDValue Src = Op.getOperand(0);
3832 SDValue Sub = Op.getOperand(1);
3833 uint64_t Idx = Op.getConstantOperandVal(2);
3834 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3835 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3836 APInt DemandedSrcElts = DemandedElts;
3837 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3838
3839 // If none of the sub operand elements are demanded, bypass the insert.
3840 if (!DemandedSubElts)
3841 return TLO.CombineTo(Op, Src);
3842
3843 APInt SubUndef, SubZero;
3844 if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
3845 Depth + 1))
3846 return true;
3847
3848 // If none of the src operand elements are demanded, replace it with undef.
3849 if (!DemandedSrcElts && !Src.isUndef())
3850 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3851 TLO.DAG.getUNDEF(VT), Sub,
3852 Op.getOperand(2)));
3853
3854 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
3855 TLO, Depth + 1))
3856 return true;
3857 KnownUndef.insertBits(SubUndef, Idx);
3858 KnownZero.insertBits(SubZero, Idx);
3859
3860 // Attempt to avoid multi-use ops if we don't need anything from them.
3861 if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
3863 Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3865 Sub, DemandedSubElts, TLO.DAG, Depth + 1);
3866 if (NewSrc || NewSub) {
3867 NewSrc = NewSrc ? NewSrc : Src;
3868 NewSub = NewSub ? NewSub : Sub;
3869 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3870 NewSub, Op.getOperand(2));
3871 return TLO.CombineTo(Op, NewOp);
3872 }
3873 }
3874 break;
3875 }
3877 // Offset the demanded elts by the subvector index.
3878 SDValue Src = Op.getOperand(0);
3879 if (Src.getValueType().isScalableVector())
3880 break;
3881 uint64_t Idx = Op.getConstantOperandVal(1);
3882 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3883 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3884
3885 APInt SrcUndef, SrcZero;
3886 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3887 Depth + 1))
3888 return true;
3889 KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3890 KnownZero = SrcZero.extractBits(NumElts, Idx);
3891
3892 // Attempt to avoid multi-use ops if we don't need anything from them.
3893 SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(Src, DemandedSrcElts,
3894 TLO.DAG, Depth + 1);
3895 if (NewSrc) {
3896 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3897 Op.getOperand(1));
3898 return TLO.CombineTo(Op, NewOp);
3899 }
3900 break;
3901 }
3903 SDValue Vec = Op.getOperand(0);
3904 SDValue Scl = Op.getOperand(1);
3905 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3906
3907 // For a legal, constant insertion index, if we don't need this insertion
3908 // then strip it, else remove it from the demanded elts.
3909 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3910 unsigned Idx = CIdx->getZExtValue();
3911 if (!DemandedElts[Idx])
3912 return TLO.CombineTo(Op, Vec);
3913
3914 APInt DemandedVecElts(DemandedElts);
3915 DemandedVecElts.clearBit(Idx);
3916 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3917 KnownZero, TLO, Depth + 1))
3918 return true;
3919
3920 KnownUndef.setBitVal(Idx, Scl.isUndef());
3921
3922 KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3923 break;
3924 }
3925
3926 APInt VecUndef, VecZero;
3927 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3928 Depth + 1))
3929 return true;
3930 // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3931 break;
3932 }
3933 case ISD::VSELECT: {
3934 SDValue Sel = Op.getOperand(0);
3935 SDValue LHS = Op.getOperand(1);
3936 SDValue RHS = Op.getOperand(2);
3937
3938 // Try to transform the select condition based on the current demanded
3939 // elements.
3940 APInt UndefSel, ZeroSel;
3941 if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO,
3942 Depth + 1))
3943 return true;
3944
3945 // See if we can simplify either vselect operand.
3946 APInt DemandedLHS(DemandedElts);
3947 APInt DemandedRHS(DemandedElts);
3948 APInt UndefLHS, ZeroLHS;
3949 APInt UndefRHS, ZeroRHS;
3950 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3951 Depth + 1))
3952 return true;
3953 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3954 Depth + 1))
3955 return true;
3956
3957 KnownUndef = UndefLHS & UndefRHS;
3958 KnownZero = ZeroLHS & ZeroRHS;
3959
3960 // If we know that the selected element is always zero, we don't need the
3961 // select value element.
3962 APInt DemandedSel = DemandedElts & ~KnownZero;
3963 if (DemandedSel != DemandedElts)
3964 if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO,
3965 Depth + 1))
3966 return true;
3967
3968 break;
3969 }
3970 case ISD::VECTOR_SHUFFLE: {
3971 SDValue LHS = Op.getOperand(0);
3972 SDValue RHS = Op.getOperand(1);
3973 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3974
3975 // Collect demanded elements from shuffle operands..
3976 APInt DemandedLHS(NumElts, 0);
3977 APInt DemandedRHS(NumElts, 0);
3978 for (unsigned i = 0; i != NumElts; ++i) {
3979 int M = ShuffleMask[i];
3980 if (M < 0 || !DemandedElts[i])
3981 continue;
3982 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3983 if (M < (int)NumElts)
3984 DemandedLHS.setBit(M);
3985 else
3986 DemandedRHS.setBit(M - NumElts);
3987 }
3988
3989 // If either side isn't demanded, replace it by UNDEF. We handle this
3990 // explicitly here to also simplify in case of multiple uses (on the
3991 // contrary to the SimplifyDemandedVectorElts calls below).
3992 bool FoldLHS = !DemandedLHS && !LHS.isUndef();
3993 bool FoldRHS = !DemandedRHS && !RHS.isUndef();
3994 if (FoldLHS || FoldRHS) {
3995 LHS = FoldLHS ? TLO.DAG.getUNDEF(LHS.getValueType()) : LHS;
3996 RHS = FoldRHS ? TLO.DAG.getUNDEF(RHS.getValueType()) : RHS;
3997 SDValue NewOp =
3998 TLO.DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, ShuffleMask);
3999 return TLO.CombineTo(Op, NewOp);
4000 }
4001
4002 // See if we can simplify either shuffle operand.
4003 APInt UndefLHS, ZeroLHS;
4004 APInt UndefRHS, ZeroRHS;
4005 if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
4006 Depth + 1))
4007 return true;
4008 if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
4009 Depth + 1))
4010 return true;
4011
4012 // Simplify mask using undef elements from LHS/RHS.
4013 bool Updated = false;
4014 bool IdentityLHS = true, IdentityRHS = true;
4015 SmallVector<int, 32> NewMask(ShuffleMask);
4016 for (unsigned i = 0; i != NumElts; ++i) {
4017 int &M = NewMask[i];
4018 if (M < 0)
4019 continue;
4020 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
4021 (M >= (int)NumElts && UndefRHS[M - NumElts])) {
4022 Updated = true;
4023 M = -1;
4024 }
4025 IdentityLHS &= (M < 0) || (M == (int)i);
4026 IdentityRHS &= (M < 0) || ((M - NumElts) == i);
4027 }
4028
4029 // Update legal shuffle masks based on demanded elements if it won't reduce
4030 // to Identity which can cause premature removal of the shuffle mask.
4031 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
4032 SDValue LegalShuffle =
4033 buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG);
4034 if (LegalShuffle)
4035 return TLO.CombineTo(Op, LegalShuffle);
4036 }
4037
4038 // Propagate undef/zero elements from LHS/RHS.
4039 for (unsigned i = 0; i != NumElts; ++i) {
4040 int M = ShuffleMask[i];
4041 if (M < 0) {
4042 KnownUndef.setBit(i);
4043 } else if (M < (int)NumElts) {
4044 if (UndefLHS[M])
4045 KnownUndef.setBit(i);
4046 if (ZeroLHS[M])
4047 KnownZero.setBit(i);
4048 } else {
4049 if (UndefRHS[M - NumElts])
4050 KnownUndef.setBit(i);
4051 if (ZeroRHS[M - NumElts])
4052 KnownZero.setBit(i);
4053 }
4054 }
4055 break;
4056 }
4060 APInt SrcUndef, SrcZero;
4061 SDValue Src = Op.getOperand(0);
4062 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4063 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
4064 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
4065 Depth + 1))
4066 return true;
4067 KnownZero = SrcZero.zextOrTrunc(NumElts);
4068 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
4069
4070 if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
4071 Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
4072 DemandedSrcElts == 1) {
4073 // aext - if we just need the bottom element then we can bitcast.
4074 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
4075 }
4076
4077 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
4078 // zext(undef) upper bits are guaranteed to be zero.
4079 if (DemandedElts.isSubsetOf(KnownUndef))
4080 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4081 KnownUndef.clearAllBits();
4082
4083 // zext - if we just need the bottom element then we can mask:
4084 // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
4085 if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
4086 Op->isOnlyUserOf(Src.getNode()) &&
4087 Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
4088 SDLoc DL(Op);
4089 EVT SrcVT = Src.getValueType();
4090 EVT SrcSVT = SrcVT.getScalarType();
4091
4092 // If we're after type legalization and SrcSVT is not legal, use the
4093 // promoted type for creating constants to avoid creating nodes with
4094 // illegal types.
4095 if (TLO.LegalTypes())
4096 SrcSVT = getLegalTypeToTransformTo(*TLO.DAG.getContext(), SrcSVT);
4097
4098 SmallVector<SDValue> MaskElts;
4099 MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
4100 MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
4101 SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
4102 if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
4103 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
4104 Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
4105 return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
4106 }
4107 }
4108 }
4109 break;
4110 }
4111
4112 // TODO: There are more binop opcodes that could be handled here - MIN,
4113 // MAX, saturated math, etc.
4114 case ISD::ADD: {
4115 SDValue Op0 = Op.getOperand(0);
4116 SDValue Op1 = Op.getOperand(1);
4117 if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
4118 APInt UndefLHS, ZeroLHS;
4119 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4120 Depth + 1, /*AssumeSingleUse*/ true))
4121 return true;
4122 }
4123 [[fallthrough]];
4124 }
4125 case ISD::AVGCEILS:
4126 case ISD::AVGCEILU:
4127 case ISD::AVGFLOORS:
4128 case ISD::AVGFLOORU:
4129 case ISD::AVGSUBFLOORS:
4130 case ISD::AVGSUBFLOORU:
4131 case ISD::OR:
4132 case ISD::XOR:
4133 case ISD::SUB:
4134 case ISD::FADD:
4135 case ISD::FSUB:
4136 case ISD::FMUL:
4137 case ISD::FDIV:
4138 case ISD::FREM:
4139 case ISD::PSEUDO_FMIN:
4140 case ISD::PSEUDO_FMAX: {
4141 SDValue Op0 = Op.getOperand(0);
4142 SDValue Op1 = Op.getOperand(1);
4143
4144 APInt UndefRHS, ZeroRHS;
4145 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
4146 Depth + 1))
4147 return true;
4148 APInt UndefLHS, ZeroLHS;
4149 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4150 Depth + 1))
4151 return true;
4152
4153 KnownZero = ZeroLHS & ZeroRHS;
4154 KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
4155
4156 // Attempt to avoid multi-use ops if we don't need anything from them.
4157 // TODO - use KnownUndef to relax the demandedelts?
4158 if (!DemandedElts.isAllOnes())
4159 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4160 return true;
4161 break;
4162 }
4163 case ISD::SHL:
4164 case ISD::SRL:
4165 case ISD::SRA:
4166 case ISD::ROTL:
4167 case ISD::ROTR: {
4168 SDValue Op0 = Op.getOperand(0);
4169 SDValue Op1 = Op.getOperand(1);
4170
4171 APInt UndefRHS, ZeroRHS;
4172 if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
4173 Depth + 1))
4174 return true;
4175 APInt UndefLHS, ZeroLHS;
4176 if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
4177 Depth + 1))
4178 return true;
4179
4180 KnownZero = ZeroLHS & ~UndefRHS;
4181 KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
4182
4183 // Attempt to avoid multi-use ops if we don't need anything from them.
4184 // TODO - use KnownUndef to relax the demandedelts?
4185 if (!DemandedElts.isAllOnes())
4186 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4187 return true;
4188 break;
4189 }
4190 case ISD::MUL:
4191 case ISD::MULHU:
4192 case ISD::MULHS:
4193 case ISD::AND: {
4194 SDValue Op0 = Op.getOperand(0);
4195 SDValue Op1 = Op.getOperand(1);
4196
4197 APInt SrcUndef, SrcZero;
4198 if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
4199 Depth + 1))
4200 return true;
4201 // FIXME: If we know that a demanded element was zero in Op1 we don't need
4202 // to demand it in Op0 - its guaranteed to be zero. There is however a
4203 // restriction, as we must not make any of the originally demanded elements
4204 // more poisonous. We could reduce amount of elements demanded, but then we
4205 // also need a to inform SimplifyDemandedVectorElts that some elements must
4206 // not be made more poisonous.
4207 if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
4208 TLO, Depth + 1))
4209 return true;
4210
4211 KnownUndef &= DemandedElts;
4212 KnownZero &= DemandedElts;
4213
4214 // If every element pair has a zero/undef/poison then just fold to zero.
4215 // fold (and x, undef/poison) -> 0 / (and x, 0) -> 0
4216 // fold (mul x, undef/poison) -> 0 / (mul x, 0) -> 0
4217 if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef))
4218 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4219
4220 // If either side has a zero element, then the result element is zero, even
4221 // if the other is an UNDEF.
4222 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
4223 // and then handle 'and' nodes with the rest of the binop opcodes.
4224 KnownZero |= SrcZero;
4225 KnownUndef &= SrcUndef;
4226 KnownUndef &= ~KnownZero;
4227
4228 // Attempt to avoid multi-use ops if we don't need anything from them.
4229 if (!DemandedElts.isAllOnes())
4230 if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
4231 return true;
4232 break;
4233 }
4234 case ISD::TRUNCATE:
4235 case ISD::SIGN_EXTEND:
4236 case ISD::ZERO_EXTEND:
4237 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4238 KnownZero, TLO, Depth + 1))
4239 return true;
4240
4241 if (!DemandedElts.isAllOnes())
4243 Op.getOperand(0), DemandedElts, TLO.DAG, Depth + 1))
4244 return TLO.CombineTo(Op, TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp));
4245
4246 if (Op.getOpcode() == ISD::ZERO_EXTEND) {
4247 // zext(undef) upper bits are guaranteed to be zero.
4248 if (DemandedElts.isSubsetOf(KnownUndef))
4249 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
4250 KnownUndef.clearAllBits();
4251 }
4252 break;
4253 case ISD::SINT_TO_FP:
4254 case ISD::UINT_TO_FP:
4255 case ISD::FP_TO_SINT:
4256 case ISD::FP_TO_UINT:
4257 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
4258 KnownZero, TLO, Depth + 1))
4259 return true;
4260 // Don't fall through to generic undef -> undef handling.
4261 return false;
4262 default: {
4263 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
4264 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
4265 KnownZero, TLO, Depth))
4266 return true;
4267 } else {
4269 APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
4270 if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
4271 TLO, Depth, AssumeSingleUse))
4272 return true;
4273 }
4274 break;
4275 }
4276 }
4277
4278 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
4279
4280 // Constant fold all undef cases.
4281 // TODO: Handle zero cases as well.
4282 if (DemandedElts.isSubsetOf(KnownUndef))
4283 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
4284
4285 return false;
4286}
4287
4288/// Determine which of the bits specified in Mask are known to be either zero or
4289/// one and return them in the Known.
4292 const APInt &DemandedElts,
4293 const SelectionDAG &DAG,
4294 unsigned Depth) const {
4295 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4296 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4297 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4298 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4299 "Should use MaskedValueIsZero if you don't know whether Op"
4300 " is a target node!");
4301 Known.resetAll();
4302}
4303
4306 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4307 unsigned Depth) const {
4308 Known.resetAll();
4309}
4310
4313 const APInt &DemandedElts, const MachineRegisterInfo &MRI,
4314 unsigned Depth) const {
4315 Known.resetAll();
4316}
4317
4319 KnownBits &Known, const MachineFunction &, Align Alignment) const {
4320 // The low bits are known zero if the pointer is aligned.
4321 Known.Zero.setLowBits(Log2(Alignment));
4322}
4323
4325 SelectionDAG &DAG,
4326 const SDLoc &DL,
4327 Align Alignment) const {
4328 // Materialize leading-zero stack object pointer facts as AssertZext.
4329 // Alignment-derived low zero bits are not represented on the returned DAG
4330 // value here.
4331 EVT PtrVT = Ptr.getValueType();
4332
4333 unsigned RegSize = PtrVT.getScalarSizeInBits();
4336 Alignment);
4337
4338 unsigned NumZeroBits = Known.countMinLeadingZeros();
4339 if (!NumZeroBits)
4340 return Ptr;
4341
4342 EVT FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
4343 return DAG.getNode(ISD::AssertZext, DL, PtrVT, Ptr, DAG.getValueType(FromVT));
4344}
4345
4351
4352/// This method can be implemented by targets that want to expose additional
4353/// information about sign bits to the DAG Combiner.
4355 const APInt &,
4356 const SelectionDAG &,
4357 unsigned Depth) const {
4358 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4359 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4360 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4361 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4362 "Should use ComputeNumSignBits if you don't know whether Op"
4363 " is a target node!");
4364 return 1;
4365}
4366
4368 GISelValueTracking &Analysis, Register R, const APInt &DemandedElts,
4369 const MachineRegisterInfo &MRI, unsigned Depth) const {
4370 return 1;
4371}
4372
4374 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
4375 TargetLoweringOpt &TLO, unsigned Depth) const {
4376 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4377 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4378 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4379 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4380 "Should use SimplifyDemandedVectorElts if you don't know whether Op"
4381 " is a target node!");
4382 return false;
4383}
4384
4386 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4387 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
4388 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4389 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4390 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4391 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4392 "Should use SimplifyDemandedBits if you don't know whether Op"
4393 " is a target node!");
4394 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
4395 return false;
4396}
4397
4399 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
4400 SelectionDAG &DAG, unsigned Depth) const {
4401 assert(
4402 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4403 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4404 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4405 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4406 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
4407 " is a target node!");
4408 return SDValue();
4409}
4410
4411SDValue
4414 SelectionDAG &DAG) const {
4415 bool LegalMask = isShuffleMaskLegal(Mask, VT);
4416 if (!LegalMask) {
4417 std::swap(N0, N1);
4419 LegalMask = isShuffleMaskLegal(Mask, VT);
4420 }
4421
4422 if (!LegalMask)
4423 return SDValue();
4424
4425 return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
4426}
4427
4429 return nullptr;
4430}
4431
4433 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4434 UndefPoisonKind Kind, unsigned Depth) const {
4435 assert(
4436 (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4437 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4438 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4439 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4440 "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
4441 " is a target node!");
4442
4443 // If Op can't create undef/poison and none of its operands are undef/poison
4444 // then Op is never undef/poison.
4445 return !canCreateUndefOrPoisonForTargetNode(Op, DemandedElts, DAG, Kind,
4446 /*ConsiderFlags*/ true, Depth) &&
4447 all_of(Op->ops(), [&](SDValue V) {
4448 return DAG.isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
4449 });
4450}
4451
4453 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
4454 UndefPoisonKind Kind, bool ConsiderFlags, unsigned Depth) const {
4455 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4456 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4457 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4458 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4459 "Should use canCreateUndefOrPoison if you don't know whether Op"
4460 " is a target node!");
4461 // Be conservative and return true.
4462 return true;
4463}
4464
4467 const APInt &DemandedElts,
4468 const SelectionDAG &DAG,
4469 unsigned Depth) const {
4470 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4471 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4472 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4473 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4474 "Should use computeKnownFPClass if you don't know whether Op"
4475 " is a target node!");
4476}
4477
4479 const APInt &DemandedElts,
4480 const SelectionDAG &DAG,
4481 bool SNaN,
4482 unsigned Depth) const {
4483 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4484 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4485 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4486 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4487 "Should use isKnownNeverNaN if you don't know whether Op"
4488 " is a target node!");
4489 return false;
4490}
4491
4493 const APInt &DemandedElts,
4494 APInt &UndefElts,
4495 const SelectionDAG &DAG,
4496 unsigned Depth) const {
4497 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
4498 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4499 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
4500 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
4501 "Should use isSplatValue if you don't know whether Op"
4502 " is a target node!");
4503 return false;
4504}
4505
4506// FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
4507// work with truncating build vectors and vectors with elements of less than
4508// 8 bits.
4510 if (!N)
4511 return false;
4512
4513 unsigned EltWidth;
4514 APInt CVal;
4515 if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
4516 /*AllowTruncation=*/true)) {
4517 CVal = CN->getAPIntValue();
4518 EltWidth = N.getValueType().getScalarSizeInBits();
4519 } else
4520 return false;
4521
4522 // If this is a truncating splat, truncate the splat value.
4523 // Otherwise, we may fail to match the expected values below.
4524 if (EltWidth < CVal.getBitWidth())
4525 CVal = CVal.trunc(EltWidth);
4526
4527 switch (getBooleanContents(N.getValueType())) {
4529 return CVal[0];
4531 return CVal.isOne();
4533 return CVal.isAllOnes();
4534 }
4535
4536 llvm_unreachable("Invalid boolean contents");
4537}
4538
4540 if (!N)
4541 return false;
4542
4544 if (!CN) {
4546 if (!BV)
4547 return false;
4548
4549 // Only interested in constant splats, we don't care about undef
4550 // elements in identifying boolean constants and getConstantSplatNode
4551 // returns NULL if all ops are undef;
4552 CN = BV->getConstantSplatNode();
4553 if (!CN)
4554 return false;
4555 }
4556
4557 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
4558 return !CN->getAPIntValue()[0];
4559
4560 return CN->isZero();
4561}
4562
4564 bool SExt) const {
4565 if (VT == MVT::i1)
4566 return N->isOne();
4567
4569 switch (Cnt) {
4571 // An extended value of 1 is always true, unless its original type is i1,
4572 // in which case it will be sign extended to -1.
4573 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
4576 return N->isAllOnes() && SExt;
4577 }
4578 llvm_unreachable("Unexpected enumeration.");
4579}
4580
4581/// This helper function of SimplifySetCC tries to optimize the comparison when
4582/// either operand of the SetCC node is a bitwise-and instruction.
4583SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
4584 ISD::CondCode Cond, const SDLoc &DL,
4585 DAGCombinerInfo &DCI) const {
4586 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
4587 std::swap(N0, N1);
4588
4589 SelectionDAG &DAG = DCI.DAG;
4590 EVT OpVT = N0.getValueType();
4591 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
4592 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4593 return SDValue();
4594
4595 // (X & Y) != 0 --> zextOrTrunc(X & Y)
4596 // iff everything but LSB is known zero:
4597 if (Cond == ISD::SETNE && isNullConstant(N1) &&
4600 unsigned NumEltBits = OpVT.getScalarSizeInBits();
4601 APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
4602 if (DAG.MaskedValueIsZero(N0, UpperBits))
4603 return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
4604 }
4605
4606 // Try to eliminate a power-of-2 mask constant by converting to a signbit
4607 // test in a narrow type that we can truncate to with no cost. Examples:
4608 // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0
4609 // (i32 X & 32768) != 0 --> (trunc X to i16) < 0
4610 // TODO: This conservatively checks for type legality on the source and
4611 // destination types. That may inhibit optimizations, but it also
4612 // allows setcc->shift transforms that may be more beneficial.
4613 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4614 if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() &&
4615 isTypeLegal(OpVT) && N0.hasOneUse()) {
4616 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(),
4617 AndC->getAPIntValue().getActiveBits());
4618 if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) {
4619 SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT);
4620 SDValue Zero = DAG.getConstant(0, DL, NarrowVT);
4621 return DAG.getSetCC(DL, VT, Trunc, Zero,
4623 }
4624 }
4625
4626 // Match these patterns in any of their permutations:
4627 // (X & Y) == Y
4628 // (X & Y) != Y
4629 SDValue X, Y;
4630 if (N0.getOperand(0) == N1) {
4631 X = N0.getOperand(1);
4632 Y = N0.getOperand(0);
4633 } else if (N0.getOperand(1) == N1) {
4634 X = N0.getOperand(0);
4635 Y = N0.getOperand(1);
4636 } else {
4637 return SDValue();
4638 }
4639
4640 // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if
4641 // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as
4642 // its liable to create and infinite loop.
4643 SDValue Zero = DAG.getConstant(0, DL, OpVT);
4644 if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) &&
4646 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
4647 // Note that where Y is variable and is known to have at most one bit set
4648 // (for example, if it is Z & 1) we cannot do this; the expressions are not
4649 // equivalent when Y == 0.
4650 assert(OpVT.isInteger());
4652 if (DCI.isBeforeLegalizeOps() ||
4654 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
4655 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
4656 // If the target supports an 'and-not' or 'and-complement' logic operation,
4657 // try to use that to make a comparison operation more efficient.
4658 // But don't do this transform if the mask is a single bit because there are
4659 // more efficient ways to deal with that case (for example, 'bt' on x86 or
4660 // 'rlwinm' on PPC).
4661
4662 // Bail out if the compare operand that we want to turn into a zero is
4663 // already a zero (otherwise, infinite loop).
4664 if (isNullConstant(Y))
4665 return SDValue();
4666
4667 // Transform this into: ~X & Y == 0.
4668 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
4669 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
4670 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
4671 }
4672
4673 return SDValue();
4674}
4675
4676/// This helper function of SimplifySetCC tries to optimize the comparison when
4677/// either operand of the SetCC node is a bitwise-or instruction.
4678/// For now, this just transforms (X | Y) ==/!= Y into X & ~Y ==/!= 0.
4679SDValue TargetLowering::foldSetCCWithOr(EVT VT, SDValue N0, SDValue N1,
4680 ISD::CondCode Cond, const SDLoc &DL,
4681 DAGCombinerInfo &DCI) const {
4682 if (N1.getOpcode() == ISD::OR && N0.getOpcode() != ISD::OR)
4683 std::swap(N0, N1);
4684
4685 SelectionDAG &DAG = DCI.DAG;
4686 EVT OpVT = N0.getValueType();
4687 if (!N0.hasOneUse() || !OpVT.isInteger() ||
4688 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
4689 return SDValue();
4690
4691 // (X | Y) == Y
4692 // (X | Y) != Y
4693 SDValue X;
4694 if (sd_match(N0, m_Or(m_Value(X), m_Specific(N1))) && hasAndNotCompare(X)) {
4695 // If the target supports an 'and-not' or 'and-complement' logic operation,
4696 // try to use that to make a comparison operation more efficient.
4697
4698 // Bail out if the compare operand that we want to turn into a zero is
4699 // already a zero (otherwise, infinite loop).
4700 if (isNullConstant(N1))
4701 return SDValue();
4702
4703 // Transform this into: X & ~Y ==/!= 0.
4704 SDValue NotY = DAG.getNOT(SDLoc(N1), N1, OpVT);
4705 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, X, NotY);
4706 return DAG.getSetCC(DL, VT, NewAnd, DAG.getConstant(0, DL, OpVT), Cond);
4707 }
4708
4709 return SDValue();
4710}
4711
4712/// There are multiple IR patterns that could be checking whether certain
4713/// truncation of a signed number would be lossy or not. The pattern which is
4714/// best at IR level, may not lower optimally. Thus, we want to unfold it.
4715/// We are looking for the following pattern: (KeptBits is a constant)
4716/// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
4717/// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
4718/// KeptBits also can't be 1, that would have been folded to %x dstcond 0
4719/// We will unfold it into the natural trunc+sext pattern:
4720/// ((%x << C) a>> C) dstcond %x
4721/// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
4722SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
4723 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
4724 const SDLoc &DL) const {
4725 // We must be comparing with a constant.
4726 ConstantSDNode *C1;
4727 if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
4728 return SDValue();
4729
4730 // N0 should be: add %x, (1 << (KeptBits-1))
4731 if (N0->getOpcode() != ISD::ADD)
4732 return SDValue();
4733
4734 // And we must be 'add'ing a constant.
4735 ConstantSDNode *C01;
4736 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
4737 return SDValue();
4738
4739 SDValue X = N0->getOperand(0);
4740 EVT XVT = X.getValueType();
4741
4742 // Validate constants ...
4743
4744 APInt I1 = C1->getAPIntValue();
4745
4746 ISD::CondCode NewCond;
4747 if (Cond == ISD::CondCode::SETULT) {
4748 NewCond = ISD::CondCode::SETEQ;
4749 } else if (Cond == ISD::CondCode::SETULE) {
4750 NewCond = ISD::CondCode::SETEQ;
4751 // But need to 'canonicalize' the constant.
4752 I1 += 1;
4753 } else if (Cond == ISD::CondCode::SETUGT) {
4754 NewCond = ISD::CondCode::SETNE;
4755 // But need to 'canonicalize' the constant.
4756 I1 += 1;
4757 } else if (Cond == ISD::CondCode::SETUGE) {
4758 NewCond = ISD::CondCode::SETNE;
4759 } else
4760 return SDValue();
4761
4762 APInt I01 = C01->getAPIntValue();
4763
4764 auto checkConstants = [&I1, &I01]() -> bool {
4765 // Both of them must be power-of-two, and the constant from setcc is bigger.
4766 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
4767 };
4768
4769 if (checkConstants()) {
4770 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
4771 } else {
4772 // What if we invert constants? (and the target predicate)
4773 I1.negate();
4774 I01.negate();
4775 assert(XVT.isInteger());
4776 NewCond = getSetCCInverse(NewCond, XVT);
4777 if (!checkConstants())
4778 return SDValue();
4779 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
4780 }
4781
4782 // They are power-of-two, so which bit is set?
4783 const unsigned KeptBits = I1.logBase2();
4784 const unsigned KeptBitsMinusOne = I01.logBase2();
4785
4786 // Magic!
4787 if (KeptBits != (KeptBitsMinusOne + 1))
4788 return SDValue();
4789 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
4790
4791 // We don't want to do this in every single case.
4792 SelectionDAG &DAG = DCI.DAG;
4793 if (!shouldTransformSignedTruncationCheck(XVT, KeptBits))
4794 return SDValue();
4795
4796 // Unfold into: sext_inreg(%x) cond %x
4797 // Where 'cond' will be either 'eq' or 'ne'.
4798 SDValue SExtInReg = DAG.getNode(
4800 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), KeptBits)));
4801 return DAG.getSetCC(DL, SCCVT, SExtInReg, X, NewCond);
4802}
4803
4804// (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
4805SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
4806 EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4807 DAGCombinerInfo &DCI, const SDLoc &DL) const {
4809 "Should be a comparison with 0.");
4810 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4811 "Valid only for [in]equality comparisons.");
4812
4813 unsigned NewShiftOpcode;
4814 SDValue X, C, Y;
4815
4816 SelectionDAG &DAG = DCI.DAG;
4817
4818 // Look for '(C l>>/<< Y)'.
4819 auto Match = [&NewShiftOpcode, &X, &C, &Y, &DAG, this](SDValue V) {
4820 // The shift should be one-use.
4821 if (!V.hasOneUse())
4822 return false;
4823 unsigned OldShiftOpcode = V.getOpcode();
4824 switch (OldShiftOpcode) {
4825 case ISD::SHL:
4826 NewShiftOpcode = ISD::SRL;
4827 break;
4828 case ISD::SRL:
4829 NewShiftOpcode = ISD::SHL;
4830 break;
4831 default:
4832 return false; // must be a logical shift.
4833 }
4834 // We should be shifting a constant.
4835 // FIXME: best to use isConstantOrConstantVector().
4836 C = V.getOperand(0);
4837 ConstantSDNode *CC =
4838 isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4839 if (!CC)
4840 return false;
4841 Y = V.getOperand(1);
4842
4843 ConstantSDNode *XC =
4844 isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4846 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
4847 };
4848
4849 // LHS of comparison should be an one-use 'and'.
4850 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
4851 return SDValue();
4852
4853 X = N0.getOperand(0);
4854 SDValue Mask = N0.getOperand(1);
4855
4856 // 'and' is commutative!
4857 if (!Match(Mask)) {
4858 std::swap(X, Mask);
4859 if (!Match(Mask))
4860 return SDValue();
4861 }
4862
4863 EVT VT = X.getValueType();
4864
4865 // Produce:
4866 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
4867 SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
4868 SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
4869 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
4870 return T2;
4871}
4872
4873/// Try to fold an equality comparison with a {add/sub/xor} binary operation as
4874/// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
4875/// handle the commuted versions of these patterns.
4876SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
4877 ISD::CondCode Cond, const SDLoc &DL,
4878 DAGCombinerInfo &DCI) const {
4879 unsigned BOpcode = N0.getOpcode();
4880 assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
4881 "Unexpected binop");
4882 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
4883
4884 // (X + Y) == X --> Y == 0
4885 // (X - Y) == X --> Y == 0
4886 // (X ^ Y) == X --> Y == 0
4887 SelectionDAG &DAG = DCI.DAG;
4888 EVT OpVT = N0.getValueType();
4889 SDValue X = N0.getOperand(0);
4890 SDValue Y = N0.getOperand(1);
4891 if (X == N1)
4892 return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
4893
4894 if (Y != N1)
4895 return SDValue();
4896
4897 // (X + Y) == Y --> X == 0
4898 // (X ^ Y) == Y --> X == 0
4899 if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
4900 return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
4901
4902 // The shift would not be valid if the operands are boolean (i1).
4903 if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
4904 return SDValue();
4905
4906 // (X - Y) == Y --> X == Y << 1
4907 SDValue One = DAG.getShiftAmountConstant(1, OpVT, DL);
4908 SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
4909 if (!DCI.isCalledByLegalizer())
4910 DCI.AddToWorklist(YShl1.getNode());
4911 return DAG.getSetCC(DL, VT, X, YShl1, Cond);
4912}
4913
4915 SDValue N0, const APInt &C1,
4916 ISD::CondCode Cond, const SDLoc &dl,
4917 SelectionDAG &DAG) {
4918 // Look through truncs that don't change the value of a ctpop.
4919 // FIXME: Add vector support? Need to be careful with setcc result type below.
4920 SDValue CTPOP = N0;
4921 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
4923 CTPOP = N0.getOperand(0);
4924
4925 if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
4926 return SDValue();
4927
4928 EVT CTVT = CTPOP.getValueType();
4929 SDValue CTOp = CTPOP.getOperand(0);
4930
4931 // Expand a power-of-2-or-zero comparison based on ctpop:
4932 // (ctpop x) u< 2 -> (x & x-1) == 0
4933 // (ctpop x) u> 1 -> (x & x-1) != 0
4934 if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
4935 // Keep the CTPOP if it is a cheap vector op.
4936 if (CTVT.isVector() && TLI.isCtpopFast(CTVT))
4937 return SDValue();
4938
4939 unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
4940 if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
4941 return SDValue();
4942 if (C1 == 0 && (Cond == ISD::SETULT))
4943 return SDValue(); // This is handled elsewhere.
4944
4945 unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
4946
4947 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4948 SDValue Result = CTOp;
4949 for (unsigned i = 0; i < Passes; i++) {
4950 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
4951 Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
4952 }
4954 return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
4955 }
4956
4957 // Expand a power-of-2 comparison based on ctpop
4958 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
4959 // Keep the CTPOP if it is cheap.
4960 if (TLI.isCtpopFast(CTVT))
4961 return SDValue();
4962
4963 SDValue Zero = DAG.getConstant(0, dl, CTVT);
4964 SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4965 assert(CTVT.isInteger());
4966 SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
4967
4968 // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so
4969 // check before emitting a potentially unnecessary op.
4970 if (DAG.isKnownNeverZero(CTOp)) {
4971 // (ctpop x) == 1 --> (x & x-1) == 0
4972 // (ctpop x) != 1 --> (x & x-1) != 0
4973 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
4974 SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
4975 return RHS;
4976 }
4977
4978 // (ctpop x) == 1 --> (x ^ x-1) > x-1
4979 // (ctpop x) != 1 --> (x ^ x-1) <= x-1
4980 SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add);
4982 return DAG.getSetCC(dl, VT, Xor, Add, CmpCond);
4983 }
4984
4985 return SDValue();
4986}
4987
4989 ISD::CondCode Cond, const SDLoc &dl,
4990 SelectionDAG &DAG) {
4991 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4992 return SDValue();
4993
4994 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4995 if (!C1 || !(C1->isZero() || C1->isAllOnes()))
4996 return SDValue();
4997
4998 auto getRotateSource = [](SDValue X) {
4999 if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
5000 return X.getOperand(0);
5001 return SDValue();
5002 };
5003
5004 // Peek through a rotated value compared against 0 or -1:
5005 // (rot X, Y) == 0/-1 --> X == 0/-1
5006 // (rot X, Y) != 0/-1 --> X != 0/-1
5007 if (SDValue R = getRotateSource(N0))
5008 return DAG.getSetCC(dl, VT, R, N1, Cond);
5009
5010 // Peek through an 'or' of a rotated value compared against 0:
5011 // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
5012 // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
5013 //
5014 // TODO: Add the 'and' with -1 sibling.
5015 // TODO: Recurse through a series of 'or' ops to find the rotate.
5016 EVT OpVT = N0.getValueType();
5017 if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
5018 if (SDValue R = getRotateSource(N0.getOperand(0))) {
5019 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
5020 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5021 }
5022 if (SDValue R = getRotateSource(N0.getOperand(1))) {
5023 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
5024 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5025 }
5026 }
5027
5028 return SDValue();
5029}
5030
5032 ISD::CondCode Cond, const SDLoc &dl,
5033 SelectionDAG &DAG) {
5034 // If we are testing for all-bits-clear, we might be able to do that with
5035 // less shifting since bit-order does not matter.
5036 if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
5037 return SDValue();
5038
5039 auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
5040 if (!C1 || !C1->isZero())
5041 return SDValue();
5042
5043 if (!N0.hasOneUse() ||
5044 (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
5045 return SDValue();
5046
5047 unsigned BitWidth = N0.getScalarValueSizeInBits();
5048 auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
5049 if (!ShAmtC)
5050 return SDValue();
5051
5052 uint64_t ShAmt = ShAmtC->getAPIntValue().urem(BitWidth);
5053 if (ShAmt == 0)
5054 return SDValue();
5055
5056 // Canonicalize fshr as fshl to reduce pattern-matching.
5057 if (N0.getOpcode() == ISD::FSHR)
5058 ShAmt = BitWidth - ShAmt;
5059
5060 // Match an 'or' with a specific operand 'Other' in either commuted variant.
5061 SDValue X, Y;
5062 auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
5063 if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
5064 return false;
5065 if (Or.getOperand(0) == Other) {
5066 X = Or.getOperand(0);
5067 Y = Or.getOperand(1);
5068 return true;
5069 }
5070 if (Or.getOperand(1) == Other) {
5071 X = Or.getOperand(1);
5072 Y = Or.getOperand(0);
5073 return true;
5074 }
5075 return false;
5076 };
5077
5078 EVT OpVT = N0.getValueType();
5079 EVT ShAmtVT = N0.getOperand(2).getValueType();
5080 SDValue F0 = N0.getOperand(0);
5081 SDValue F1 = N0.getOperand(1);
5082 if (matchOr(F0, F1)) {
5083 // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
5084 SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
5085 SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
5086 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
5087 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5088 }
5089 if (matchOr(F1, F0)) {
5090 // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
5091 SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
5092 SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
5093 SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
5094 return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
5095 }
5096
5097 return SDValue();
5098}
5099
5100/// Try to simplify a setcc built with the specified operands and cc. If it is
5101/// unable to simplify it, return a null SDValue.
5103 ISD::CondCode Cond, bool foldBooleans,
5104 DAGCombinerInfo &DCI,
5105 const SDLoc &dl) const {
5106 SelectionDAG &DAG = DCI.DAG;
5107 const DataLayout &Layout = DAG.getDataLayout();
5108 EVT OpVT = N0.getValueType();
5110
5111 // Constant fold or commute setcc.
5112 if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
5113 return Fold;
5114
5115 bool N0ConstOrSplat =
5116 isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
5117 bool N1ConstOrSplat =
5118 isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
5119
5120 // Canonicalize toward having the constant on the RHS.
5121 // TODO: Handle non-splat vector constants. All undef causes trouble.
5122 // FIXME: We can't yet fold constant scalable vector splats, so avoid an
5123 // infinite loop here when we encounter one.
5125 if (N0ConstOrSplat && !N1ConstOrSplat &&
5126 (DCI.isBeforeLegalizeOps() ||
5127 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
5128 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
5129
5130 // If we have a subtract with the same 2 non-constant operands as this setcc
5131 // -- but in reverse order -- then try to commute the operands of this setcc
5132 // to match. A matching pair of setcc (cmp) and sub may be combined into 1
5133 // instruction on some targets.
5134 if (!N0ConstOrSplat && !N1ConstOrSplat &&
5135 (DCI.isBeforeLegalizeOps() ||
5136 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
5137 DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
5138 !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
5139 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
5140
5141 if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
5142 return V;
5143
5144 if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
5145 return V;
5146
5147 if (auto *N1C = isConstOrConstSplat(N1)) {
5148 const APInt &C1 = N1C->getAPIntValue();
5149
5150 // Optimize some CTPOP cases.
5151 if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
5152 return V;
5153
5154 // For equality to 0 of a no-wrap multiply, decompose and test each op:
5155 // X * Y == 0 --> (X == 0) || (Y == 0)
5156 // X * Y != 0 --> (X != 0) && (Y != 0)
5157 // TODO: This bails out if minsize is set, but if the target doesn't have a
5158 // single instruction multiply for this type, it would likely be
5159 // smaller to decompose.
5160 if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5161 N0.getOpcode() == ISD::MUL && N0.hasOneUse() &&
5162 (N0->getFlags().hasNoUnsignedWrap() ||
5163 N0->getFlags().hasNoSignedWrap()) &&
5164 !Attr.hasFnAttr(Attribute::MinSize)) {
5165 SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5166 SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond);
5167 unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND;
5168 return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero);
5169 }
5170
5171 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
5172 // equality comparison, then we're just comparing whether X itself is
5173 // zero.
5174 if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
5175 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
5177 if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
5178 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5179 ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
5180 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
5181 // (srl (ctlz x), 5) == 0 -> X != 0
5182 // (srl (ctlz x), 5) != 1 -> X != 0
5183 Cond = ISD::SETNE;
5184 } else {
5185 // (srl (ctlz x), 5) != 0 -> X == 0
5186 // (srl (ctlz x), 5) == 1 -> X == 0
5187 Cond = ISD::SETEQ;
5188 }
5189 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
5190 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
5191 Cond);
5192 }
5193 }
5194 }
5195 }
5196
5197 // setcc X, 0, setlt --> X (when X is all sign bits)
5198 // setcc X, 0, setne --> X (when X is all sign bits)
5199 //
5200 // When we know that X has 0 or -1 in each element (or scalar), this
5201 // comparison will produce X. This is only true when boolean contents are
5202 // represented via 0s and -1s.
5203 if (VT == OpVT &&
5204 // Check that the result of setcc is 0 and -1.
5206 // Match only for checks X < 0 and X != 0
5207 (Cond == ISD::SETLT || Cond == ISD::SETNE) && isNullOrNullSplat(N1) &&
5208 // The identity holds iff we know all sign bits for all lanes.
5210 return N0;
5211
5212 // FIXME: Support vectors.
5213 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5214 const APInt &C1 = N1C->getAPIntValue();
5215
5216 // (zext x) == C --> x == (trunc C)
5217 // (sext x) == C --> x == (trunc C)
5218 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5219 DCI.isBeforeLegalize() && N0->hasOneUse()) {
5220 unsigned MinBits = N0.getValueSizeInBits();
5221 SDValue PreExt;
5222 bool Signed = false;
5223 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
5224 // ZExt
5225 MinBits = N0->getOperand(0).getValueSizeInBits();
5226 PreExt = N0->getOperand(0);
5227 } else if (N0->getOpcode() == ISD::AND) {
5228 // DAGCombine turns costly ZExts into ANDs
5229 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
5230 if ((C->getAPIntValue()+1).isPowerOf2()) {
5231 MinBits = C->getAPIntValue().countr_one();
5232 PreExt = N0->getOperand(0);
5233 }
5234 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
5235 // SExt
5236 MinBits = N0->getOperand(0).getValueSizeInBits();
5237 PreExt = N0->getOperand(0);
5238 Signed = true;
5239 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
5240 // ZEXTLOAD / SEXTLOAD
5241 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
5242 MinBits = LN0->getMemoryVT().getSizeInBits();
5243 PreExt = N0;
5244 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
5245 Signed = true;
5246 MinBits = LN0->getMemoryVT().getSizeInBits();
5247 PreExt = N0;
5248 }
5249 }
5250
5251 // Figure out how many bits we need to preserve this constant.
5252 unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits();
5253
5254 // Make sure we're not losing bits from the constant.
5255 if (MinBits > 0 &&
5256 MinBits < C1.getBitWidth() &&
5257 MinBits >= ReqdBits) {
5258 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
5259 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
5260 // Will get folded away.
5261 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
5262 if (MinBits == 1 && C1 == 1)
5263 // Invert the condition.
5264 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
5266 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
5267 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
5268 }
5269
5270 // If truncating the setcc operands is not desirable, we can still
5271 // simplify the expression in some cases:
5272 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
5273 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
5274 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
5275 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
5276 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
5277 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
5278 SDValue TopSetCC = N0->getOperand(0);
5279 unsigned N0Opc = N0->getOpcode();
5280 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
5281 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
5282 TopSetCC.getOpcode() == ISD::SETCC &&
5283 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
5284 (isConstFalseVal(N1) ||
5285 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
5286
5287 bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
5288 (!N1C->isZero() && Cond == ISD::SETNE);
5289
5290 if (!Inverse)
5291 return TopSetCC;
5292
5293 ISD::CondCode InvCond =
5295 TopSetCC.getOperand(0).getValueType());
5296 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
5297 TopSetCC.getOperand(1), InvCond);
5298 }
5299 }
5300 }
5301
5302 // If the LHS is '(and load, const)', the RHS is 0, the test is for
5303 // equality or unsigned, and all 1 bits of the const are in the same
5304 // partial word, see if we can shorten the load.
5305 if (DCI.isBeforeLegalize() &&
5307 N0.getOpcode() == ISD::AND && C1 == 0 &&
5308 N0.getNode()->hasOneUse() &&
5309 isa<LoadSDNode>(N0.getOperand(0)) &&
5310 N0.getOperand(0).getNode()->hasOneUse() &&
5312 auto *Lod = cast<LoadSDNode>(N0.getOperand(0));
5313 APInt bestMask;
5314 unsigned bestWidth = 0, bestOffset = 0;
5315 if (Lod->isSimple() && Lod->isUnindexed() &&
5316 (Lod->getMemoryVT().isByteSized() ||
5317 isPaddedAtMostSignificantBitsWhenStored(Lod->getMemoryVT()))) {
5318 unsigned memWidth = Lod->getMemoryVT().getStoreSizeInBits();
5319 unsigned origWidth = N0.getValueSizeInBits();
5320 unsigned maskWidth = origWidth;
5321 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
5322 // 8 bits, but have to be careful...
5323 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
5324 origWidth = Lod->getMemoryVT().getSizeInBits();
5325 const APInt &Mask = N0.getConstantOperandAPInt(1);
5326 // Only consider power-of-2 widths (and at least one byte) as candiates
5327 // for the narrowed load.
5328 for (unsigned width = 8; width < origWidth; width *= 2) {
5329 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), width);
5330 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
5331 // Avoid accessing any padding here for now (we could use memWidth
5332 // instead of origWidth here otherwise).
5333 unsigned maxOffset = origWidth - width;
5334 for (unsigned offset = 0; offset <= maxOffset; offset += 8) {
5335 if (Mask.isSubsetOf(newMask)) {
5336 unsigned ptrOffset =
5337 Layout.isLittleEndian() ? offset : memWidth - width - offset;
5338 unsigned IsFast = 0;
5339 assert((ptrOffset % 8) == 0 && "Non-Bytealigned pointer offset");
5340 Align NewAlign = commonAlignment(Lod->getAlign(), ptrOffset / 8);
5342 ptrOffset / 8) &&
5344 *DAG.getContext(), Layout, newVT, Lod->getAddressSpace(),
5345 NewAlign, Lod->getMemOperand()->getFlags(), &IsFast) &&
5346 IsFast) {
5347 bestOffset = ptrOffset / 8;
5348 bestMask = Mask.lshr(offset);
5349 bestWidth = width;
5350 break;
5351 }
5352 }
5353 newMask <<= 8;
5354 }
5355 if (bestWidth)
5356 break;
5357 }
5358 }
5359 if (bestWidth) {
5360 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
5361 SDValue Ptr = Lod->getBasePtr();
5362 if (bestOffset != 0)
5363 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(bestOffset));
5364 SDValue NewLoad =
5365 DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
5366 Lod->getPointerInfo().getWithOffset(bestOffset),
5367 Lod->getBaseAlign(), MachineMemOperand::MONone,
5368 Lod->getMMOMetadataForSubAccess());
5369 SDValue And =
5370 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
5371 DAG.getConstant(bestMask.trunc(bestWidth), dl, newVT));
5372 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0LL, dl, newVT), Cond);
5373 }
5374 }
5375
5376 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
5377 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
5378 unsigned InSize = N0.getOperand(0).getValueSizeInBits();
5379
5380 // If the comparison constant has bits in the upper part, the
5381 // zero-extended value could never match.
5382 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
5383 C1.getBitWidth() - InSize))) {
5384 switch (Cond) {
5385 case ISD::SETUGT:
5386 case ISD::SETUGE:
5387 case ISD::SETEQ:
5388 return DAG.getConstant(0, dl, VT);
5389 case ISD::SETULT:
5390 case ISD::SETULE:
5391 case ISD::SETNE:
5392 return DAG.getConstant(1, dl, VT);
5393 case ISD::SETGT:
5394 case ISD::SETGE:
5395 // True if the sign bit of C1 is set.
5396 return DAG.getConstant(C1.isNegative(), dl, VT);
5397 case ISD::SETLT:
5398 case ISD::SETLE:
5399 // True if the sign bit of C1 isn't set.
5400 return DAG.getConstant(C1.isNonNegative(), dl, VT);
5401 default:
5402 break;
5403 }
5404 }
5405
5406 // Otherwise, we can perform the comparison with the low bits.
5407 switch (Cond) {
5408 case ISD::SETEQ:
5409 case ISD::SETNE:
5410 case ISD::SETUGT:
5411 case ISD::SETUGE:
5412 case ISD::SETULT:
5413 case ISD::SETULE: {
5414 EVT newVT = N0.getOperand(0).getValueType();
5415 // FIXME: Should use isNarrowingProfitable.
5416 if (DCI.isBeforeLegalizeOps() ||
5417 (isOperationLegal(ISD::SETCC, newVT) &&
5418 isCondCodeLegal(Cond, newVT.getSimpleVT()) &&
5420 EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
5421 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
5422
5423 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
5424 NewConst, Cond);
5425 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
5426 }
5427 break;
5428 }
5429 default:
5430 break; // todo, be more careful with signed comparisons
5431 }
5432 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5433 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5435 OpVT)) {
5436 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
5437 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
5438 EVT ExtDstTy = N0.getValueType();
5439 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
5440
5441 // If the constant doesn't fit into the number of bits for the source of
5442 // the sign extension, it is impossible for both sides to be equal.
5443 if (C1.getSignificantBits() > ExtSrcTyBits)
5444 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
5445
5446 assert(ExtDstTy == N0.getOperand(0).getValueType() &&
5447 ExtDstTy != ExtSrcTy && "Unexpected types!");
5448 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
5449 SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
5450 DAG.getConstant(Imm, dl, ExtDstTy));
5451 if (!DCI.isCalledByLegalizer())
5452 DCI.AddToWorklist(ZextOp.getNode());
5453 // Otherwise, make this a use of a zext.
5454 return DAG.getSetCC(dl, VT, ZextOp,
5455 DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
5456 } else if ((N1C->isZero() || N1C->isOne()) &&
5457 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5458 // SETCC (X), [0|1], [EQ|NE] -> X if X is known 0/1. i1 types are
5459 // excluded as they are handled below whilst checking for foldBooleans.
5460 if ((N0.getOpcode() == ISD::SETCC || VT.getScalarType() != MVT::i1) &&
5461 isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
5462 (N0.getValueType() == MVT::i1 ||
5466 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
5467 if (TrueWhenTrue)
5468 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
5469 // Invert the condition.
5470 if (N0.getOpcode() == ISD::SETCC) {
5473 if (DCI.isBeforeLegalizeOps() ||
5475 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
5476 }
5477 }
5478
5479 if ((N0.getOpcode() == ISD::XOR ||
5480 (N0.getOpcode() == ISD::AND &&
5481 N0.getOperand(0).getOpcode() == ISD::XOR &&
5482 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
5483 isOneConstant(N0.getOperand(1))) {
5484 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
5485 // can only do this if the top bits are known zero.
5486 unsigned BitWidth = N0.getValueSizeInBits();
5487 if (DAG.MaskedValueIsZero(N0,
5489 BitWidth-1))) {
5490 // Okay, get the un-inverted input value.
5491 SDValue Val;
5492 if (N0.getOpcode() == ISD::XOR) {
5493 Val = N0.getOperand(0);
5494 } else {
5495 assert(N0.getOpcode() == ISD::AND &&
5496 N0.getOperand(0).getOpcode() == ISD::XOR);
5497 // ((X^1)&1)^1 -> X & 1
5498 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
5499 N0.getOperand(0).getOperand(0),
5500 N0.getOperand(1));
5501 }
5502
5503 return DAG.getSetCC(dl, VT, Val, N1,
5505 }
5506 } else if (N1C->isOne()) {
5507 SDValue Op0 = N0;
5508 if (Op0.getOpcode() == ISD::TRUNCATE)
5509 Op0 = Op0.getOperand(0);
5510
5511 if ((Op0.getOpcode() == ISD::XOR) &&
5512 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
5513 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
5514 SDValue XorLHS = Op0.getOperand(0);
5515 SDValue XorRHS = Op0.getOperand(1);
5516 // Ensure that the input setccs return an i1 type or 0/1 value.
5517 if (Op0.getValueType() == MVT::i1 ||
5522 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
5524 return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
5525 }
5526 }
5527 if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
5528 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
5529 if (Op0.getValueType().bitsGT(VT))
5530 Op0 = DAG.getNode(ISD::AND, dl, VT,
5531 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
5532 DAG.getConstant(1, dl, VT));
5533 else if (Op0.getValueType().bitsLT(VT))
5534 Op0 = DAG.getNode(ISD::AND, dl, VT,
5535 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
5536 DAG.getConstant(1, dl, VT));
5537
5538 return DAG.getSetCC(dl, VT, Op0,
5539 DAG.getConstant(0, dl, Op0.getValueType()),
5541 }
5542 if (Op0.getOpcode() == ISD::AssertZext &&
5543 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
5544 return DAG.getSetCC(dl, VT, Op0,
5545 DAG.getConstant(0, dl, Op0.getValueType()),
5547 }
5548 }
5549
5550 // Given:
5551 // icmp eq/ne (urem %x, %y), 0
5552 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
5553 // icmp eq/ne %x, 0
5554 if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
5555 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5556 KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
5557 KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
5558 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
5559 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
5560 }
5561
5562 // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
5563 // and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
5564 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5566 N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
5567 N1C->isAllOnes()) {
5568 return DAG.getSetCC(dl, VT, N0.getOperand(0),
5569 DAG.getConstant(0, dl, OpVT),
5571 }
5572
5573 // fold (setcc (trunc x) c) -> (setcc x c)
5574 if (N0.getOpcode() == ISD::TRUNCATE &&
5576 (N0->getFlags().hasNoSignedWrap() &&
5579 EVT NewVT = N0.getOperand(0).getValueType();
5580 SDValue NewConst = DAG.getConstant(
5582 ? C1.sext(NewVT.getSizeInBits())
5583 : C1.zext(NewVT.getSizeInBits()),
5584 dl, NewVT);
5585 return DAG.getSetCC(dl, VT, N0.getOperand(0), NewConst, Cond);
5586 }
5587
5588 if (SDValue V =
5589 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
5590 return V;
5591 }
5592
5593 // These simplifications apply to splat vectors as well.
5594 // TODO: Handle more splat vector cases.
5595 if (auto *N1C = isConstOrConstSplat(N1)) {
5596 const APInt &C1 = N1C->getAPIntValue();
5597
5598 APInt MinVal, MaxVal;
5599 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
5601 MinVal = APInt::getSignedMinValue(OperandBitSize);
5602 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
5603 } else {
5604 MinVal = APInt::getMinValue(OperandBitSize);
5605 MaxVal = APInt::getMaxValue(OperandBitSize);
5606 }
5607
5608 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
5609 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
5610 // X >= MIN --> true
5611 if (C1 == MinVal)
5612 return DAG.getBoolConstant(true, dl, VT, OpVT);
5613
5614 if (!VT.isVector()) { // TODO: Support this for vectors.
5615 // X >= C0 --> X > (C0 - 1)
5616 APInt C = C1 - 1;
5618 if ((DCI.isBeforeLegalizeOps() ||
5619 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5620 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5621 isLegalICmpImmediate(C.getSExtValue())))) {
5622 return DAG.getSetCC(dl, VT, N0,
5623 DAG.getConstant(C, dl, N1.getValueType()),
5624 NewCC);
5625 }
5626 }
5627 }
5628
5629 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
5630 // X <= MAX --> true
5631 if (C1 == MaxVal)
5632 return DAG.getBoolConstant(true, dl, VT, OpVT);
5633
5634 // X <= C0 --> X < (C0 + 1)
5635 if (!VT.isVector()) { // TODO: Support this for vectors.
5636 APInt C = C1 + 1;
5638 if ((DCI.isBeforeLegalizeOps() ||
5639 isCondCodeLegal(NewCC, OpVT.getSimpleVT())) &&
5640 (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
5641 isLegalICmpImmediate(C.getSExtValue())))) {
5642 return DAG.getSetCC(dl, VT, N0,
5643 DAG.getConstant(C, dl, N1.getValueType()),
5644 NewCC);
5645 }
5646 }
5647 }
5648
5649 if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
5650 if (C1 == MinVal)
5651 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
5652
5653 // TODO: Support this for vectors after legalize ops.
5654 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5655 // Canonicalize setlt X, Max --> setne X, Max
5656 if (C1 == MaxVal)
5657 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5658
5659 // If we have setult X, 1, turn it into seteq X, 0
5660 if (C1 == MinVal+1)
5661 return DAG.getSetCC(dl, VT, N0,
5662 DAG.getConstant(MinVal, dl, N0.getValueType()),
5663 ISD::SETEQ);
5664 }
5665 }
5666
5667 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
5668 if (C1 == MaxVal)
5669 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
5670
5671 // TODO: Support this for vectors after legalize ops.
5672 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5673 // Canonicalize setgt X, Min --> setne X, Min
5674 if (C1 == MinVal)
5675 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
5676
5677 // If we have setugt X, Max-1, turn it into seteq X, Max
5678 if (C1 == MaxVal-1)
5679 return DAG.getSetCC(dl, VT, N0,
5680 DAG.getConstant(MaxVal, dl, N0.getValueType()),
5681 ISD::SETEQ);
5682 }
5683 }
5684
5685 if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
5686 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
5687 if (C1.isZero())
5688 if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
5689 VT, N0, N1, Cond, DCI, dl))
5690 return CC;
5691
5692 // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
5693 // For example, when high 32-bits of i64 X are known clear:
5694 // all bits clear: (X | (Y<<32)) == 0 --> (X | Y) == 0
5695 // all bits set: (X | (Y<<32)) == -1 --> (X & Y) == -1
5696 bool CmpZero = N1C->isZero();
5697 bool CmpNegOne = N1C->isAllOnes();
5698 if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
5699 // Match or(lo,shl(hi,bw/2)) pattern.
5700 auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
5701 unsigned EltBits = V.getScalarValueSizeInBits();
5702 if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
5703 return false;
5704 SDValue LHS = V.getOperand(0);
5705 SDValue RHS = V.getOperand(1);
5706 APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
5707 // Unshifted element must have zero upperbits.
5708 if (RHS.getOpcode() == ISD::SHL &&
5709 isa<ConstantSDNode>(RHS.getOperand(1)) &&
5710 RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5711 DAG.MaskedValueIsZero(LHS, HiBits)) {
5712 Lo = LHS;
5713 Hi = RHS.getOperand(0);
5714 return true;
5715 }
5716 if (LHS.getOpcode() == ISD::SHL &&
5717 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5718 LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
5719 DAG.MaskedValueIsZero(RHS, HiBits)) {
5720 Lo = RHS;
5721 Hi = LHS.getOperand(0);
5722 return true;
5723 }
5724 return false;
5725 };
5726
5727 auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
5728 unsigned EltBits = N0.getScalarValueSizeInBits();
5729 unsigned HalfBits = EltBits / 2;
5730 APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
5731 SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
5732 SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
5733 SDValue NewN0 =
5734 DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
5735 SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
5736 return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
5737 };
5738
5739 SDValue Lo, Hi;
5740 if (IsConcat(N0, Lo, Hi))
5741 return MergeConcat(Lo, Hi);
5742
5743 if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
5744 SDValue Lo0, Lo1, Hi0, Hi1;
5745 if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
5746 IsConcat(N0.getOperand(1), Lo1, Hi1)) {
5747 return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
5748 DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
5749 }
5750 }
5751 }
5752 }
5753
5754 // If we have "setcc X, C0", check to see if we can shrink the immediate
5755 // by changing cc.
5756 // TODO: Support this for vectors after legalize ops.
5757 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5758 // SETUGT X, SINTMAX -> SETLT X, 0
5759 // SETUGE X, SINTMIN -> SETLT X, 0
5760 if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
5761 (Cond == ISD::SETUGE && C1.isMinSignedValue()))
5762 return DAG.getSetCC(dl, VT, N0,
5763 DAG.getConstant(0, dl, N1.getValueType()),
5764 ISD::SETLT);
5765
5766 // SETULT X, SINTMIN -> SETGT X, -1
5767 // SETULE X, SINTMAX -> SETGT X, -1
5768 if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
5769 (Cond == ISD::SETULE && C1.isMaxSignedValue()))
5770 return DAG.getSetCC(dl, VT, N0,
5771 DAG.getAllOnesConstant(dl, N1.getValueType()),
5772 ISD::SETGT);
5773 }
5774 }
5775
5776 // Back to non-vector simplifications.
5777 // TODO: Can we do these for vector splats?
5778 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5779 const APInt &C1 = N1C->getAPIntValue();
5780 EVT ShValTy = N0.getValueType();
5781
5782 // Fold bit comparisons when we can. This will result in an
5783 // incorrect value when boolean false is negative one, unless
5784 // the bitsize is 1 in which case the false value is the same
5785 // in practice regardless of the representation.
5786 if ((VT.getSizeInBits() == 1 ||
5788 (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5789 (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
5790 N0.getOpcode() == ISD::AND) {
5791 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5792 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
5793 // Perform the xform if the AND RHS is a single bit.
5794 unsigned ShCt = AndRHS->getAPIntValue().logBase2();
5795 if (AndRHS->getAPIntValue().isPowerOf2() &&
5796 !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5797 return DAG.getNode(
5798 ISD::TRUNCATE, dl, VT,
5799 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5800 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5801 }
5802 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
5803 // (X & 8) == 8 --> (X & 8) >> 3
5804 // Perform the xform if C1 is a single bit.
5805 unsigned ShCt = C1.logBase2();
5806 if (C1.isPowerOf2() && !shouldAvoidTransformToShift(ShValTy, ShCt)) {
5807 return DAG.getNode(
5808 ISD::TRUNCATE, dl, VT,
5809 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5810 DAG.getShiftAmountConstant(ShCt, ShValTy, dl)));
5811 }
5812 }
5813 }
5814 }
5815
5816 if (C1.getSignificantBits() <= 64 &&
5817 !isLegalICmpImmediate(C1.getSExtValue())) {
5818 // (X & -256) == 256 -> (X >> 8) == 1
5819 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5820 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5821 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5822 const APInt &AndRHSC = AndRHS->getAPIntValue();
5823 if (AndRHSC.isNegatedPowerOf2() && C1.isSubsetOf(AndRHSC)) {
5824 unsigned ShiftBits = AndRHSC.countr_zero();
5825 if (!shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5826 // If using an unsigned shift doesn't yield a legal compare
5827 // immediate, try using sra instead.
5828 APInt NewC = C1.lshr(ShiftBits);
5829 if (NewC.getSignificantBits() <= 64 &&
5831 APInt SignedC = C1.ashr(ShiftBits);
5832 if (SignedC.getSignificantBits() <= 64 &&
5834 SDValue Shift = DAG.getNode(
5835 ISD::SRA, dl, ShValTy, N0.getOperand(0),
5836 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5837 SDValue CmpRHS = DAG.getConstant(SignedC, dl, ShValTy);
5838 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5839 }
5840 }
5841 SDValue Shift = DAG.getNode(
5842 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5843 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5844 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5845 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5846 }
5847 }
5848 }
5849 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
5850 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
5851 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
5852 // X < 0x100000000 -> (X >> 32) < 1
5853 // X >= 0x100000000 -> (X >> 32) >= 1
5854 // X <= 0x0ffffffff -> (X >> 32) < 1
5855 // X > 0x0ffffffff -> (X >> 32) >= 1
5856 unsigned ShiftBits;
5857 APInt NewC = C1;
5858 ISD::CondCode NewCond = Cond;
5859 if (AdjOne) {
5860 ShiftBits = C1.countr_one();
5861 NewC = NewC + 1;
5862 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
5863 } else {
5864 ShiftBits = C1.countr_zero();
5865 }
5866 APInt RangeWidth = NewC;
5867 NewC.lshrInPlace(ShiftBits);
5868 if (ShiftBits && NewC.getSignificantBits() <= 64 &&
5870 !shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5871 // If this is an offset range check, try to move the offset after the
5872 // shift to avoid preserving the pre-shift add with a mask.
5873 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse()) {
5874 if (auto *AddC = isConstOrConstSplat(N0.getOperand(1))) {
5875 const APInt &AddVal = AddC->getAPIntValue();
5876 if (AddVal.countr_zero() >= ShiftBits) {
5877 APInt RangeLower = -AddVal;
5878 bool Overflow;
5879 (void)RangeLower.uadd_ov(RangeWidth, Overflow);
5880 if (!RangeWidth.isZero() && !Overflow) {
5881 SDValue Shift = DAG.getNode(
5882 ISD::SRL, dl, ShValTy, N0.getOperand(0),
5883 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5884 APInt Offset = -RangeLower.lshr(ShiftBits);
5885 SDValue ShiftedAdd =
5886 DAG.getNode(ISD::ADD, dl, ShValTy, Shift,
5887 DAG.getConstant(Offset, dl, ShValTy));
5888 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5889 return DAG.getSetCC(dl, VT, ShiftedAdd, CmpRHS, NewCond);
5890 }
5891 }
5892 }
5893 }
5894 SDValue Shift =
5895 DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5896 DAG.getShiftAmountConstant(ShiftBits, ShValTy, dl));
5897 SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5898 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
5899 }
5900 }
5901 }
5902 }
5903
5905 auto *CFP = cast<ConstantFPSDNode>(N1);
5906 assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
5907
5908 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
5909 // constant if knowing that the operand is non-nan is enough. We prefer to
5910 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
5911 // materialize 0.0.
5912 if (Cond == ISD::SETO || Cond == ISD::SETUO)
5913 return DAG.getSetCC(dl, VT, N0, N0, Cond);
5914
5915 // setcc (fneg x), C -> setcc swap(pred) x, -C
5916 if (N0.getOpcode() == ISD::FNEG) {
5918 if (DCI.isBeforeLegalizeOps() ||
5919 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
5920 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
5921 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
5922 }
5923 }
5924
5925 // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf
5927 !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) {
5928 bool IsFabs = N0.getOpcode() == ISD::FABS;
5929 SDValue Op = IsFabs ? N0.getOperand(0) : N0;
5930 if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) {
5931 FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf)
5932 : (IsFabs ? fcInf : fcPosInf);
5933 if (Cond == ISD::SETUEQ)
5934 Flag |= fcNan;
5935 return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op,
5936 DAG.getTargetConstant(Flag, dl, MVT::i32));
5937 }
5938 }
5939
5940 // If the condition is not legal, see if we can find an equivalent one
5941 // which is legal.
5943 // If the comparison was an awkward floating-point == or != and one of
5944 // the comparison operands is infinity or negative infinity, convert the
5945 // condition to a less-awkward <= or >=.
5946 if (CFP->getValueAPF().isInfinity()) {
5947 bool IsNegInf = CFP->getValueAPF().isNegative();
5949 switch (Cond) {
5950 case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
5951 case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
5952 case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
5953 case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
5954 default: break;
5955 }
5956 if (NewCond != ISD::SETCC_INVALID &&
5957 isCondCodeLegal(NewCond, N0.getSimpleValueType()))
5958 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5959 }
5960 }
5961 }
5962
5963 if (N0 == N1) {
5964 // The sext(setcc()) => setcc() optimization relies on the appropriate
5965 // constant being emitted.
5966 assert(!N0.getValueType().isInteger() &&
5967 "Integer types should be handled by FoldSetCC");
5968
5969 bool EqTrue = ISD::isTrueWhenEqual(Cond);
5970 unsigned UOF = ISD::getUnorderedFlavor(Cond);
5971 if (UOF == 2) // FP operators that are undefined on NaNs.
5972 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5973 if (UOF == unsigned(EqTrue))
5974 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5975 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
5976 // if it is not already.
5977 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
5978 if (NewCond != Cond &&
5979 (DCI.isBeforeLegalizeOps() ||
5980 isCondCodeLegal(NewCond, N0.getSimpleValueType())))
5981 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5982 }
5983
5984 // ~X > ~Y --> Y > X
5985 // ~X < ~Y --> Y < X
5986 // ~X < C --> X > ~C
5987 // ~X > C --> X < ~C
5988 if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) &&
5989 N0.getValueType().isInteger()) {
5990 if (isBitwiseNot(N0)) {
5991 if (isBitwiseNot(N1))
5992 return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond);
5993
5996 SDValue Not = DAG.getNOT(dl, N1, OpVT);
5997 return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond);
5998 }
5999 }
6000 }
6001
6002 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6003 N0.getValueType().isInteger()) {
6004 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
6005 N0.getOpcode() == ISD::XOR) {
6006 // Simplify (X+Y) == (X+Z) --> Y == Z
6007 if (N0.getOpcode() == N1.getOpcode()) {
6008 if (N0.getOperand(0) == N1.getOperand(0))
6009 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
6010 if (N0.getOperand(1) == N1.getOperand(1))
6011 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
6012 if (isCommutativeBinOp(N0.getOpcode())) {
6013 // If X op Y == Y op X, try other combinations.
6014 if (N0.getOperand(0) == N1.getOperand(1))
6015 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
6016 Cond);
6017 if (N0.getOperand(1) == N1.getOperand(0))
6018 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
6019 Cond);
6020 }
6021 }
6022
6023 // If RHS is a legal immediate value for a compare instruction, we need
6024 // to be careful about increasing register pressure needlessly.
6025 bool LegalRHSImm = false;
6026
6027 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
6028 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6029 // Turn (X+C1) == C2 --> X == C2-C1
6030 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
6031 return DAG.getSetCC(
6032 dl, VT, N0.getOperand(0),
6033 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
6034 dl, N0.getValueType()),
6035 Cond);
6036
6037 // Turn (X^C1) == C2 --> X == C1^C2
6038 if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
6039 return DAG.getSetCC(
6040 dl, VT, N0.getOperand(0),
6041 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
6042 dl, N0.getValueType()),
6043 Cond);
6044 }
6045
6046 // Turn (C1-X) == C2 --> X == C1-C2
6047 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
6048 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
6049 return DAG.getSetCC(
6050 dl, VT, N0.getOperand(1),
6051 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
6052 dl, N0.getValueType()),
6053 Cond);
6054
6055 // Could RHSC fold directly into a compare?
6056 if (RHSC->getValueType(0).getSizeInBits() <= 64)
6057 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
6058 }
6059
6060 // (X+Y) == X --> Y == 0 and similar folds.
6061 // Don't do this if X is an immediate that can fold into a cmp
6062 // instruction and X+Y has other uses. It could be an induction variable
6063 // chain, and the transform would increase register pressure.
6064 if (!LegalRHSImm || N0.hasOneUse())
6065 if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
6066 return V;
6067 }
6068
6069 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
6070 N1.getOpcode() == ISD::XOR)
6071 if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
6072 return V;
6073
6074 if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
6075 return V;
6076
6077 if (SDValue V = foldSetCCWithOr(VT, N0, N1, Cond, dl, DCI))
6078 return V;
6079 }
6080
6081 // Fold remainder of division by a constant.
6082 if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
6083 N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
6084 // When division is cheap or optimizing for minimum size,
6085 // fall through to DIVREM creation by skipping this fold.
6086 if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
6087 if (N0.getOpcode() == ISD::UREM) {
6088 if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
6089 return Folded;
6090 } else if (N0.getOpcode() == ISD::SREM) {
6091 if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
6092 return Folded;
6093 }
6094 }
6095 }
6096
6097 // Fold away ALL boolean setcc's.
6098 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
6099 SDValue Temp;
6100 switch (Cond) {
6101 default: llvm_unreachable("Unknown integer setcc!");
6102 case ISD::SETEQ: // X == Y -> ~(X^Y)
6103 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
6104 N0 = DAG.getNOT(dl, Temp, OpVT);
6105 if (!DCI.isCalledByLegalizer())
6106 DCI.AddToWorklist(Temp.getNode());
6107 break;
6108 case ISD::SETNE: // X != Y --> (X^Y)
6109 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
6110 break;
6111 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
6112 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
6113 Temp = DAG.getNOT(dl, N0, OpVT);
6114 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
6115 if (!DCI.isCalledByLegalizer())
6116 DCI.AddToWorklist(Temp.getNode());
6117 break;
6118 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
6119 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
6120 Temp = DAG.getNOT(dl, N1, OpVT);
6121 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
6122 if (!DCI.isCalledByLegalizer())
6123 DCI.AddToWorklist(Temp.getNode());
6124 break;
6125 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
6126 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
6127 Temp = DAG.getNOT(dl, N0, OpVT);
6128 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
6129 if (!DCI.isCalledByLegalizer())
6130 DCI.AddToWorklist(Temp.getNode());
6131 break;
6132 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
6133 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
6134 Temp = DAG.getNOT(dl, N1, OpVT);
6135 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
6136 break;
6137 }
6138 if (VT.getScalarType() != MVT::i1) {
6139 if (!DCI.isCalledByLegalizer())
6140 DCI.AddToWorklist(N0.getNode());
6141 // FIXME: If running after legalize, we probably can't do this.
6143 N0 = DAG.getNode(ExtendCode, dl, VT, N0);
6144 }
6145 return N0;
6146 }
6147
6148 // Fold (setcc (trunc x) (trunc y)) -> (setcc x y)
6149 if (N0.getOpcode() == ISD::TRUNCATE && N1.getOpcode() == ISD::TRUNCATE &&
6150 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
6152 N1->getFlags().hasNoUnsignedWrap()) ||
6154 N1->getFlags().hasNoSignedWrap())) &&
6156 if (VT.getScalarType() == MVT::i1)
6157 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
6158 // For (legal) non vXi1 cases - ensure we adjust the cmp and result types.
6159 EVT OldCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6160 N0.getValueType());
6161 if (VT == OldCCVT) {
6162 EVT NewCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6163 N0.getOperand(0).getValueType());
6164 return DAG.getBoolExtOrTrunc(
6165 DAG.getSetCC(dl, NewCCVT, N0.getOperand(0), N1.getOperand(0), Cond),
6166 dl, VT, N0.getOperand(0).getValueType());
6167 }
6168 }
6169
6170 // Fold (setcc (sub nsw a, b), zero, s??) -> (setcc a, b, s??)
6171 // TODO: Remove that .isVector() check
6172 if (VT.isVector() && isZeroOrZeroSplat(N1) && N0.getOpcode() == ISD::SUB &&
6174 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), Cond);
6175 }
6176
6177 // Could not fold it.
6178 return SDValue();
6179}
6180
6181/// Returns true (and the GlobalValue and the offset) if the node is a
6182/// GlobalAddress + offset.
6184 int64_t &Offset) const {
6185
6186 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
6187
6188 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
6189 GA = GASD->getGlobal();
6190 Offset += GASD->getOffset();
6191 return true;
6192 }
6193
6194 if (N->isAnyAdd()) {
6195 SDValue N1 = N->getOperand(0);
6196 SDValue N2 = N->getOperand(1);
6197 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
6198 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
6199 Offset += V->getSExtValue();
6200 return true;
6201 }
6202 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
6203 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
6204 Offset += V->getSExtValue();
6205 return true;
6206 }
6207 }
6208 }
6209
6210 return false;
6211}
6212
6214 DAGCombinerInfo &DCI) const {
6215 // Default implementation: no optimization.
6216 return SDValue();
6217}
6218
6219//===----------------------------------------------------------------------===//
6220// Inline Assembler Implementation Methods
6221//===----------------------------------------------------------------------===//
6222
6225 unsigned S = Constraint.size();
6226
6227 if (S == 1) {
6228 switch (Constraint[0]) {
6229 default: break;
6230 case 'r':
6231 return C_RegisterClass;
6232 case 'm': // memory
6233 case 'o': // offsetable
6234 case 'V': // not offsetable
6235 return C_Memory;
6236 case 'p': // Address.
6237 return C_Address;
6238 case 'n': // Simple Integer
6239 case 'E': // Floating Point Constant
6240 case 'F': // Floating Point Constant
6241 return C_Immediate;
6242 case 'i': // Simple Integer or Relocatable Constant
6243 case 's': // Relocatable Constant
6244 case 'X': // Allow ANY value.
6245 case 'I': // Target registers.
6246 case 'J':
6247 case 'K':
6248 case 'L':
6249 case 'M':
6250 case 'N':
6251 case 'O':
6252 case 'P':
6253 case '<':
6254 case '>':
6255 return C_Other;
6256 }
6257 }
6258
6259 if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
6260 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
6261 return C_Memory;
6262 return C_Register;
6263 }
6264 return C_Unknown;
6265}
6266
6267/// Try to replace an X constraint, which matches anything, with another that
6268/// has more specific requirements based on the type of the corresponding
6269/// operand.
6270const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6271 if (ConstraintVT.isInteger())
6272 return "r";
6273 if (ConstraintVT.isFloatingPoint())
6274 return "f"; // works for many targets
6275 return nullptr;
6276}
6277
6279 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
6280 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
6281 return SDValue();
6282}
6283
6284/// Lower the specified operand into the Ops vector.
6285/// If it is invalid, don't add anything to Ops.
6287 StringRef Constraint,
6288 std::vector<SDValue> &Ops,
6289 SelectionDAG &DAG) const {
6290
6291 if (Constraint.size() > 1)
6292 return;
6293
6294 char ConstraintLetter = Constraint[0];
6295 switch (ConstraintLetter) {
6296 default: break;
6297 case 'X': // Allows any operand
6298 case 'i': // Simple Integer or Relocatable Constant
6299 case 'n': // Simple Integer
6300 case 's': { // Relocatable Constant
6301
6303 uint64_t Offset = 0;
6304
6305 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
6306 // etc., since getelementpointer is variadic. We can't use
6307 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
6308 // while in this case the GA may be furthest from the root node which is
6309 // likely an ISD::ADD.
6310 while (true) {
6311 if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
6312 // gcc prints these as sign extended. Sign extend value to 64 bits
6313 // now; without this it would get ZExt'd later in
6314 // ScheduleDAGSDNodes::EmitNode, which is very generic.
6315 bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
6316 BooleanContent BCont = getBooleanContents(MVT::i64);
6317 ISD::NodeType ExtOpc =
6318 IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
6319 int64_t ExtVal =
6320 ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
6321 Ops.push_back(
6322 DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
6323 return;
6324 }
6325 if (ConstraintLetter != 'n') {
6326 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6327 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6328 GA->getValueType(0),
6329 Offset + GA->getOffset()));
6330 return;
6331 }
6332 if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
6333 Ops.push_back(DAG.getTargetBlockAddress(
6334 BA->getBlockAddress(), BA->getValueType(0),
6335 Offset + BA->getOffset(), BA->getTargetFlags()));
6336 return;
6337 }
6339 Ops.push_back(Op);
6340 return;
6341 }
6342 }
6343 const unsigned OpCode = Op.getOpcode();
6344 if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
6345 if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
6346 Op = Op.getOperand(1);
6347 // Subtraction is not commutative.
6348 else if (OpCode == ISD::ADD &&
6349 (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
6350 Op = Op.getOperand(0);
6351 else
6352 return;
6353 Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
6354 continue;
6355 }
6356 return;
6357 }
6358 break;
6359 }
6360 }
6361}
6362
6366
6367std::pair<unsigned, const TargetRegisterClass *>
6369 StringRef Constraint,
6370 MVT VT) const {
6371 if (!Constraint.starts_with("{"))
6372 return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
6373 assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
6374
6375 // Remove the braces from around the name.
6376 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
6377
6378 std::pair<unsigned, const TargetRegisterClass *> R =
6379 std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
6380
6381 // Figure out which register class contains this reg.
6382 for (const TargetRegisterClass &RC : RI->regclasses()) {
6383 // If none of the value types for this register class are valid, we
6384 // can't use it. For example, 64-bit reg classes on 32-bit targets.
6385 if (!isLegalRC(*RI, RC))
6386 continue;
6387
6388 for (const MCPhysReg &PR : RC) {
6389 if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
6390 std::pair<unsigned, const TargetRegisterClass *> S =
6391 std::make_pair(PR, &RC);
6392
6393 // If this register class has the requested value type, return it,
6394 // otherwise keep searching and return the first class found
6395 // if no other is found which explicitly has the requested type.
6396 if (RI->isTypeLegalForClass(RC, VT))
6397 return S;
6398 if (!R.second)
6399 R = S;
6400 }
6401 }
6402 }
6403
6404 return R;
6405}
6406
6407//===----------------------------------------------------------------------===//
6408// Constraint Selection.
6409
6410/// Return true of this is an input operand that is a matching constraint like
6411/// "4".
6413 assert(!ConstraintCode.empty() && "No known constraint!");
6414 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
6415}
6416
6417/// If this is an input matching constraint, this method returns the output
6418/// operand it matches.
6420 assert(!ConstraintCode.empty() && "No known constraint!");
6421 return atoi(ConstraintCode.c_str());
6422}
6423
6424/// Split up the constraint string from the inline assembly value into the
6425/// specific constraints and their prefixes, and also tie in the associated
6426/// operand values.
6427/// If this returns an empty vector, and if the constraint string itself
6428/// isn't empty, there was an error parsing.
6431 const TargetRegisterInfo *TRI,
6432 const CallBase &Call) const {
6433 /// Information about all of the constraints.
6434 AsmOperandInfoVector ConstraintOperands;
6435 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
6436 unsigned maCount = 0; // Largest number of multiple alternative constraints.
6437
6438 // Do a prepass over the constraints, canonicalizing them, and building up the
6439 // ConstraintOperands list.
6440 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6441 unsigned ResNo = 0; // ResNo - The result number of the next output.
6442 unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
6443
6444 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
6445 ConstraintOperands.emplace_back(std::move(CI));
6446 AsmOperandInfo &OpInfo = ConstraintOperands.back();
6447
6448 // Update multiple alternative constraint count.
6449 if (OpInfo.multipleAlternatives.size() > maCount)
6450 maCount = OpInfo.multipleAlternatives.size();
6451
6452 OpInfo.ConstraintVT = MVT::Other;
6453
6454 // Compute the value type for each operand.
6455 switch (OpInfo.Type) {
6456 case InlineAsm::isOutput: {
6457 // Indirect outputs just consume an argument.
6458 if (OpInfo.isIndirect) {
6459 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6460 break;
6461 }
6462
6463 // The return value of the call is this value. As such, there is no
6464 // corresponding argument.
6465 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
6466 EVT VT;
6467 if (auto *STy = dyn_cast<StructType>(Call.getType())) {
6468 VT = getAsmOperandValueType(DL, STy->getElementType(ResNo));
6469 } else {
6470 assert(ResNo == 0 && "Asm only has one result!");
6471 VT = getAsmOperandValueType(DL, Call.getType());
6472 }
6473 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6474 ++ResNo;
6475 break;
6476 }
6477 case InlineAsm::isInput:
6478 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
6479 break;
6480 case InlineAsm::isLabel:
6481 OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo);
6482 ++LabelNo;
6483 continue;
6485 // Nothing to do.
6486 break;
6487 }
6488
6489 if (OpInfo.CallOperandVal) {
6490 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
6491 if (OpInfo.isIndirect) {
6492 OpTy = Call.getParamElementType(ArgNo);
6493 assert(OpTy && "Indirect operand must have elementtype attribute");
6494 }
6495
6496 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6498 if (STy->getNumElements() == 1)
6499 OpTy = STy->getElementType(0);
6500
6501 // If OpTy is not a single value, it may be a struct/union that we
6502 // can tile with integers.
6503 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6504 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
6505 switch (BitSize) {
6506 default: break;
6507 case 1:
6508 case 8:
6509 case 16:
6510 case 32:
6511 case 64:
6512 case 128:
6513 OpTy = IntegerType::get(OpTy->getContext(), BitSize);
6514 break;
6515 }
6516 }
6517
6518 EVT VT = getAsmOperandValueType(DL, OpTy, true);
6519 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
6520 ArgNo++;
6521 }
6522 }
6523
6524 // If we have multiple alternative constraints, select the best alternative.
6525 if (!ConstraintOperands.empty()) {
6526 if (maCount) {
6527 unsigned bestMAIndex = 0;
6528 int bestWeight = -1;
6529 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
6530 int weight = -1;
6531 unsigned maIndex;
6532 // Compute the sums of the weights for each alternative, keeping track
6533 // of the best (highest weight) one so far.
6534 for (maIndex = 0; maIndex < maCount; ++maIndex) {
6535 int weightSum = 0;
6536 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6537 cIndex != eIndex; ++cIndex) {
6538 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6539 if (OpInfo.Type == InlineAsm::isClobber)
6540 continue;
6541
6542 // If this is an output operand with a matching input operand,
6543 // look up the matching input. If their types mismatch, e.g. one
6544 // is an integer, the other is floating point, or their sizes are
6545 // different, flag it as an maCantMatch.
6546 if (OpInfo.hasMatchingInput()) {
6547 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6548 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6549 if ((OpInfo.ConstraintVT.isInteger() !=
6550 Input.ConstraintVT.isInteger()) ||
6551 (OpInfo.ConstraintVT.getSizeInBits() !=
6552 Input.ConstraintVT.getSizeInBits())) {
6553 weightSum = -1; // Can't match.
6554 break;
6555 }
6556 }
6557 }
6558 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
6559 if (weight == -1) {
6560 weightSum = -1;
6561 break;
6562 }
6563 weightSum += weight;
6564 }
6565 // Update best.
6566 if (weightSum > bestWeight) {
6567 bestWeight = weightSum;
6568 bestMAIndex = maIndex;
6569 }
6570 }
6571
6572 // Now select chosen alternative in each constraint.
6573 for (AsmOperandInfo &cInfo : ConstraintOperands)
6574 if (cInfo.Type != InlineAsm::isClobber)
6575 cInfo.selectAlternative(bestMAIndex);
6576 }
6577 }
6578
6579 // Check and hook up tied operands, choose constraint code to use.
6580 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
6581 cIndex != eIndex; ++cIndex) {
6582 AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
6583
6584 // If this is an output operand with a matching input operand, look up the
6585 // matching input. If their types mismatch, e.g. one is an integer, the
6586 // other is floating point, or their sizes are different, flag it as an
6587 // error.
6588 if (OpInfo.hasMatchingInput()) {
6589 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6590
6591 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6592 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6593 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6594 OpInfo.ConstraintVT);
6595 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6596 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6597 Input.ConstraintVT);
6598 const bool OutOpIsIntOrFP = OpInfo.ConstraintVT.isInteger() ||
6599 OpInfo.ConstraintVT.isFloatingPoint();
6600 const bool InOpIsIntOrFP = Input.ConstraintVT.isInteger() ||
6601 Input.ConstraintVT.isFloatingPoint();
6602 if ((OutOpIsIntOrFP != InOpIsIntOrFP) ||
6603 (MatchRC.second != InputRC.second)) {
6604 report_fatal_error("Unsupported asm: input constraint"
6605 " with a matching output constraint of"
6606 " incompatible type!");
6607 }
6608 }
6609 }
6610 }
6611
6612 return ConstraintOperands;
6613}
6614
6615/// Return a number indicating our preference for chosing a type of constraint
6616/// over another, for the purpose of sorting them. Immediates are almost always
6617/// preferrable (when they can be emitted). A higher return value means a
6618/// stronger preference for one constraint type relative to another.
6619/// FIXME: We should prefer registers over memory but doing so may lead to
6620/// unrecoverable register exhaustion later.
6621/// https://github.com/llvm/llvm-project/issues/20571
6623 switch (CT) {
6626 return 4;
6629 return 3;
6631 return 2;
6633 return 1;
6635 return 0;
6636 }
6637 llvm_unreachable("Invalid constraint type");
6638}
6639
6640/// Examine constraint type and operand type and determine a weight value.
6641/// This object must already have been set up with the operand type
6642/// and the current alternative constraint selected.
6645 AsmOperandInfo &info, int maIndex) const {
6647 if (maIndex >= (int)info.multipleAlternatives.size())
6648 rCodes = &info.Codes;
6649 else
6650 rCodes = &info.multipleAlternatives[maIndex].Codes;
6651 ConstraintWeight BestWeight = CW_Invalid;
6652
6653 // Loop over the options, keeping track of the most general one.
6654 for (const std::string &rCode : *rCodes) {
6655 ConstraintWeight weight =
6656 getSingleConstraintMatchWeight(info, rCode.c_str());
6657 if (weight > BestWeight)
6658 BestWeight = weight;
6659 }
6660
6661 return BestWeight;
6662}
6663
6664/// Examine constraint type and operand type and determine a weight value.
6665/// This object must already have been set up with the operand type
6666/// and the current alternative constraint selected.
6669 AsmOperandInfo &info, const char *constraint) const {
6671 Value *CallOperandVal = info.CallOperandVal;
6672 // If we don't have a value, we can't do a match,
6673 // but allow it at the lowest weight.
6674 if (!CallOperandVal)
6675 return CW_Default;
6676 // Look at the constraint type.
6677 switch (*constraint) {
6678 case 'i': // immediate integer.
6679 case 'n': // immediate integer with a known value.
6680 if (isa<ConstantInt>(CallOperandVal))
6681 weight = CW_Constant;
6682 break;
6683 case 's': // non-explicit intregal immediate.
6684 if (isa<GlobalValue>(CallOperandVal))
6685 weight = CW_Constant;
6686 break;
6687 case 'E': // immediate float if host format.
6688 case 'F': // immediate float.
6689 if (isa<ConstantFP>(CallOperandVal))
6690 weight = CW_Constant;
6691 break;
6692 case '<': // memory operand with autodecrement.
6693 case '>': // memory operand with autoincrement.
6694 case 'm': // memory operand.
6695 case 'o': // offsettable memory operand
6696 case 'V': // non-offsettable memory operand
6697 weight = CW_Memory;
6698 break;
6699 case 'r': // general register.
6700 case 'g': // general register, memory operand or immediate integer.
6701 // note: Clang converts "g" to "imr".
6702 if (CallOperandVal->getType()->isIntegerTy())
6703 weight = CW_Register;
6704 break;
6705 case 'X': // any operand.
6706 default:
6707 weight = CW_Default;
6708 break;
6709 }
6710 return weight;
6711}
6712
6713/// If there are multiple different constraints that we could pick for this
6714/// operand (e.g. "imr") try to pick the 'best' one.
6715/// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall
6716/// into seven classes:
6717/// Register -> one specific register
6718/// RegisterClass -> a group of regs
6719/// Memory -> memory
6720/// Address -> a symbolic memory reference
6721/// Immediate -> immediate values
6722/// Other -> magic values (such as "Flag Output Operands")
6723/// Unknown -> something we don't recognize yet and can't handle
6724/// Ideally, we would pick the most specific constraint possible: if we have
6725/// something that fits into a register, we would pick it. The problem here
6726/// is that if we have something that could either be in a register or in
6727/// memory that use of the register could cause selection of *other*
6728/// operands to fail: they might only succeed if we pick memory. Because of
6729/// this the heuristic we use is:
6730///
6731/// 1) If there is an 'other' constraint, and if the operand is valid for
6732/// that constraint, use it. This makes us take advantage of 'i'
6733/// constraints when available.
6734/// 2) Otherwise, pick the most general constraint present. This prefers
6735/// 'm' over 'r', for example.
6736///
6738 TargetLowering::AsmOperandInfo &OpInfo) const {
6739 ConstraintGroup Ret;
6740
6741 Ret.reserve(OpInfo.Codes.size());
6742 for (StringRef Code : OpInfo.Codes) {
6744
6745 // Indirect 'other' or 'immediate' constraints are not allowed.
6746 if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
6747 CType == TargetLowering::C_Register ||
6749 continue;
6750
6751 // Things with matching constraints can only be registers, per gcc
6752 // documentation. This mainly affects "g" constraints.
6753 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
6754 continue;
6755
6756 Ret.emplace_back(Code, CType);
6757 }
6758
6760 return getConstraintPiority(a.second) > getConstraintPiority(b.second);
6761 });
6762
6763 return Ret;
6764}
6765
6766/// If we have an immediate, see if we can lower it. Return true if we can,
6767/// false otherwise.
6769 SDValue Op, SelectionDAG *DAG,
6770 const TargetLowering &TLI) {
6771
6772 assert((P.second == TargetLowering::C_Other ||
6773 P.second == TargetLowering::C_Immediate) &&
6774 "need immediate or other");
6775
6776 if (!Op.getNode())
6777 return false;
6778
6779 std::vector<SDValue> ResultOps;
6780 TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG);
6781 return !ResultOps.empty();
6782}
6783
6784/// Determines the constraint code and constraint type to use for the specific
6785/// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
6787 SDValue Op,
6788 SelectionDAG *DAG) const {
6789 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
6790
6791 // Single-letter constraints ('r') are very common.
6792 if (OpInfo.Codes.size() == 1) {
6793 OpInfo.ConstraintCode = OpInfo.Codes[0];
6794 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6795 } else {
6797 if (G.empty())
6798 return;
6799
6800 unsigned BestIdx = 0;
6801 for (const unsigned E = G.size();
6802 BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other ||
6803 G[BestIdx].second == TargetLowering::C_Immediate);
6804 ++BestIdx) {
6805 if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this))
6806 break;
6807 // If we're out of constraints, just pick the first one.
6808 if (BestIdx + 1 == E) {
6809 BestIdx = 0;
6810 break;
6811 }
6812 }
6813
6814 OpInfo.ConstraintCode = G[BestIdx].first;
6815 OpInfo.ConstraintType = G[BestIdx].second;
6816 }
6817
6818 // 'X' matches anything.
6819 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
6820 // Constants are handled elsewhere. For Functions, the type here is the
6821 // type of the result, which is not what we want to look at; leave them
6822 // alone.
6823 Value *v = OpInfo.CallOperandVal;
6824 if (isa<ConstantInt>(v) || isa<Function>(v)) {
6825 return;
6826 }
6827
6828 if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
6829 OpInfo.ConstraintCode = "i";
6830 return;
6831 }
6832
6833 // Otherwise, try to resolve it to something we know about by looking at
6834 // the actual operand type.
6835 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
6836 OpInfo.ConstraintCode = Repl;
6837 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6838 }
6839 }
6840}
6841
6842/// Given an exact SDIV by a constant, create a multiplication
6843/// with the multiplicative inverse of the constant.
6844/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6846 const SDLoc &dl, SelectionDAG &DAG,
6847 SmallVectorImpl<SDNode *> &Created) {
6848 SDValue Op0 = N->getOperand(0);
6849 SDValue Op1 = N->getOperand(1);
6850 EVT VT = N->getValueType(0);
6851 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6852 EVT ShSVT = ShVT.getScalarType();
6853
6854 bool UseSRA = false;
6855 SmallVector<SDValue, 16> Shifts, Factors;
6856
6857 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6858 if (C->isZero())
6859 return false;
6860
6861 EVT CT = C->getValueType(0);
6862 APInt Divisor = C->getAPIntValue();
6863 unsigned Shift = Divisor.countr_zero();
6864 if (Shift) {
6865 Divisor.ashrInPlace(Shift);
6866 UseSRA = true;
6867 }
6868 APInt Factor = Divisor.multiplicativeInverse();
6869 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6870 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6871 return true;
6872 };
6873
6874 // Collect all magic values from the build vector.
6875 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
6876 return SDValue();
6877
6878 SDValue Shift, Factor;
6879 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6880 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6881 Factor = DAG.getBuildVector(VT, dl, Factors);
6882 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6883 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6884 "Expected matchUnaryPredicate to return one element for scalable "
6885 "vectors");
6886 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6887 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6888 } else {
6889 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6890 Shift = Shifts[0];
6891 Factor = Factors[0];
6892 }
6893
6894 SDValue Res = Op0;
6895 if (UseSRA) {
6896 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, SDNodeFlags::Exact);
6897 Created.push_back(Res.getNode());
6898 }
6899
6900 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6901}
6902
6903/// Given an exact UDIV by a constant, create a multiplication
6904/// with the multiplicative inverse of the constant.
6905/// Ref: "Hacker's Delight" by Henry Warren, 2nd Edition, p. 242
6907 const SDLoc &dl, SelectionDAG &DAG,
6908 SmallVectorImpl<SDNode *> &Created) {
6909 EVT VT = N->getValueType(0);
6910 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6911 EVT ShSVT = ShVT.getScalarType();
6912
6913 bool UseSRL = false;
6914 SmallVector<SDValue, 16> Shifts, Factors;
6915
6916 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6917 if (C->isZero())
6918 return false;
6919
6920 EVT CT = C->getValueType(0);
6921 APInt Divisor = C->getAPIntValue();
6922 unsigned Shift = Divisor.countr_zero();
6923 if (Shift) {
6924 Divisor.lshrInPlace(Shift);
6925 UseSRL = true;
6926 }
6927 // Calculate the multiplicative inverse modulo BW.
6928 APInt Factor = Divisor.multiplicativeInverse();
6929 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6930 Factors.push_back(DAG.getConstant(Factor, dl, CT));
6931 return true;
6932 };
6933
6934 SDValue Op1 = N->getOperand(1);
6935
6936 // Collect all magic values from the build vector.
6937 if (!ISD::matchUnaryPredicate(Op1, BuildUDIVPattern))
6938 return SDValue();
6939
6940 SDValue Shift, Factor;
6941 if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6942 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6943 Factor = DAG.getBuildVector(VT, dl, Factors);
6944 } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6945 assert(Shifts.size() == 1 && Factors.size() == 1 &&
6946 "Expected matchUnaryPredicate to return one element for scalable "
6947 "vectors");
6948 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6949 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6950 } else {
6951 assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6952 Shift = Shifts[0];
6953 Factor = Factors[0];
6954 }
6955
6956 SDValue Res = N->getOperand(0);
6957 if (UseSRL) {
6958 Res = DAG.getNode(ISD::SRL, dl, VT, Res, Shift, SDNodeFlags::Exact);
6959 Created.push_back(Res.getNode());
6960 }
6961
6962 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6963}
6964
6966 SelectionDAG &DAG,
6967 SmallVectorImpl<SDNode *> &Created) const {
6969 if (isIntDivCheap(N->getValueType(0), Attr))
6970 return SDValue(N, 0); // Lower SDIV as SDIV
6971 return SDValue();
6972}
6973
6974SDValue
6976 SelectionDAG &DAG,
6977 SmallVectorImpl<SDNode *> &Created) const {
6979 if (isIntDivCheap(N->getValueType(0), Attr))
6980 return SDValue(N, 0); // Lower SREM as SREM
6981 return SDValue();
6982}
6983
6984/// Build sdiv by power-of-2 with conditional move instructions
6985/// Ref: "Hacker's Delight" by Henry Warren 10-1
6986/// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into:
6987/// bgez x, label
6988/// add x, x, 2**k-1
6989/// label:
6990/// sra res, x, k
6991/// neg res, res (when the divisor is negative)
6993 SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
6994 SmallVectorImpl<SDNode *> &Created) const {
6995 unsigned Lg2 = Divisor.countr_zero();
6996 EVT VT = N->getValueType(0);
6997
6998 SDLoc DL(N);
6999 SDValue N0 = N->getOperand(0);
7000 SDValue Zero = DAG.getConstant(0, DL, VT);
7001 APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
7002 SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
7003
7004 // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
7005 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7006 SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT);
7007 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7008 SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
7009
7010 Created.push_back(Cmp.getNode());
7011 Created.push_back(Add.getNode());
7012 Created.push_back(CMov.getNode());
7013
7014 // Divide by pow2.
7015 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, CMov,
7016 DAG.getShiftAmountConstant(Lg2, VT, DL));
7017
7018 // If we're dividing by a positive value, we're done. Otherwise, we must
7019 // negate the result.
7020 if (Divisor.isNonNegative())
7021 return SRA;
7022
7023 Created.push_back(SRA.getNode());
7024 return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
7025}
7026
7027/// Given an ISD::SDIV node expressing a divide by constant,
7028/// return a DAG expression to select that will generate the same value by
7029/// multiplying by a magic number.
7030/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
7032 bool IsAfterLegalization,
7033 bool IsAfterLegalTypes,
7034 SmallVectorImpl<SDNode *> &Created) const {
7035 SDLoc dl(N);
7036
7037 // If the sdiv has an 'exact' bit we can use a simpler lowering.
7038 if (N->getFlags().hasExact())
7039 return BuildExactSDIV(*this, N, dl, DAG, Created);
7040
7041 EVT VT = N->getValueType(0);
7042 EVT SVT = VT.getScalarType();
7043 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7044 EVT ShSVT = ShVT.getScalarType();
7045 unsigned EltBits = VT.getScalarSizeInBits();
7046 EVT MulVT;
7047
7048 // Check to see if we can do this.
7049 // FIXME: We should be more aggressive here.
7050 EVT QueryVT = VT;
7051 if (VT.isVector()) {
7052 // If the vector type will be legalized to a vector type with the same
7053 // element type, allow the transform before type legalization if MULHS or
7054 // SMUL_LOHI are supported.
7055 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
7056 if (!QueryVT.isVector() ||
7058 return SDValue();
7059 } else if (!isTypeLegal(VT)) {
7060 // Limit this to simple scalars for now.
7061 if (!VT.isSimple())
7062 return SDValue();
7063
7064 // If this type will be promoted to a large enough type with a legal
7065 // multiply operation, we can go ahead and do this transform.
7067 return SDValue();
7068
7069 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
7070 if (MulVT.getSizeInBits() < (2 * EltBits) ||
7071 !isOperationLegal(ISD::MUL, MulVT))
7072 return SDValue();
7073 }
7074
7075 bool HasMULHS =
7076 isOperationLegalOrCustom(ISD::MULHS, QueryVT, IsAfterLegalization);
7077 bool HasSMUL_LOHI =
7078 isOperationLegalOrCustom(ISD::SMUL_LOHI, QueryVT, IsAfterLegalization);
7079
7080 if (isTypeLegal(VT) && !HasMULHS && !HasSMUL_LOHI && MulVT == EVT()) {
7081 // If type twice as wide legal, widen and use a mul plus a shift.
7082 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
7083 // Some targets like AMDGPU try to go from SDIV to SDIVREM which is then
7084 // custom lowered. This is very expensive so avoid it at all costs for
7085 // constant divisors.
7086 if ((!IsAfterLegalTypes && isOperationExpand(ISD::SDIV, VT) &&
7089 MulVT = WideVT;
7090 }
7091
7092 if (!HasMULHS && !HasSMUL_LOHI && MulVT == EVT())
7093 return SDValue();
7094
7095 // If we're after type legalization and SVT is not legal, use the
7096 // promoted type for creating constants to avoid creating nodes with
7097 // illegal types.
7098 if (IsAfterLegalTypes && VT.isVector()) {
7099 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7100 if (SVT.bitsLT(VT.getScalarType()))
7101 return SDValue();
7102 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7103 if (ShSVT.bitsLT(ShVT.getScalarType()))
7104 return SDValue();
7105 }
7106 const unsigned SVTBits = SVT.getSizeInBits();
7107
7108 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
7109
7110 auto BuildSDIVPattern = [&](ConstantSDNode *C) {
7111 if (C->isZero())
7112 return false;
7113 // Truncate the divisor to the target scalar type in case it was promoted
7114 // during type legalization.
7115 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7117 int NumeratorFactor = 0;
7118 int ShiftMask = -1;
7119
7120 if (Divisor.isOne() || Divisor.isAllOnes()) {
7121 // If d is +1/-1, we just multiply the numerator by +1/-1.
7122 NumeratorFactor = Divisor.getSExtValue();
7123 magics.Magic = 0;
7124 magics.ShiftAmount = 0;
7125 ShiftMask = 0;
7126 } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
7127 // If d > 0 and m < 0, add the numerator.
7128 NumeratorFactor = 1;
7129 } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
7130 // If d < 0 and m > 0, subtract the numerator.
7131 NumeratorFactor = -1;
7132 }
7133
7134 MagicFactors.push_back(
7135 DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT));
7136 Factors.push_back(DAG.getSignedConstant(NumeratorFactor, dl, SVT));
7137 Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
7138 ShiftMasks.push_back(DAG.getSignedConstant(ShiftMask, dl, SVT));
7139 return true;
7140 };
7141
7142 SDValue N0 = N->getOperand(0);
7143 SDValue N1 = N->getOperand(1);
7144
7145 // Collect the shifts / magic values from each element.
7146 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern, /*AllowUndefs=*/false,
7147 /*AllowTruncation=*/true))
7148 return SDValue();
7149
7150 SDValue MagicFactor, Factor, Shift, ShiftMask;
7151 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7152 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7153 Factor = DAG.getBuildVector(VT, dl, Factors);
7154 Shift = DAG.getBuildVector(ShVT, dl, Shifts);
7155 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
7156 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7157 assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
7158 Shifts.size() == 1 && ShiftMasks.size() == 1 &&
7159 "Expected matchUnaryPredicate to return one element for scalable "
7160 "vectors");
7161 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7162 Factor = DAG.getSplatVector(VT, dl, Factors[0]);
7163 Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
7164 ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
7165 } else {
7166 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7167 MagicFactor = MagicFactors[0];
7168 Factor = Factors[0];
7169 Shift = Shifts[0];
7170 ShiftMask = ShiftMasks[0];
7171 }
7172
7173 // Multiply the numerator (operand 0) by the magic value.
7174 auto GetMULHS = [&](SDValue X, SDValue Y) {
7175 if (HasMULHS)
7176 return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
7177 if (HasSMUL_LOHI) {
7178 SDValue LoHi =
7179 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7180 return LoHi.getValue(1);
7181 }
7182
7183 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
7184 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
7185 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7186 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7187 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7188 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7189 };
7190
7191 SDValue Q = GetMULHS(N0, MagicFactor);
7192 if (!Q)
7193 return SDValue();
7194
7195 Created.push_back(Q.getNode());
7196
7197 // (Optionally) Add/subtract the numerator using Factor.
7198 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
7199 Created.push_back(Factor.getNode());
7200 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
7201 Created.push_back(Q.getNode());
7202
7203 // Shift right algebraic by shift value.
7204 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
7205 Created.push_back(Q.getNode());
7206
7207 // Extract the sign bit, mask it and add it to the quotient.
7208 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
7209 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
7210 Created.push_back(T.getNode());
7211 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
7212 Created.push_back(T.getNode());
7213 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
7214}
7215
7216/// Given an ISD::UDIV node expressing a divide by constant,
7217/// return a DAG expression to select that will generate the same value by
7218/// multiplying by a magic number.
7219/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
7221 bool IsAfterLegalization,
7222 bool IsAfterLegalTypes,
7223 SmallVectorImpl<SDNode *> &Created) const {
7224 SDLoc dl(N);
7225
7226 // If the udiv has an 'exact' bit we can use a simpler lowering.
7227 if (N->getFlags().hasExact())
7228 return BuildExactUDIV(*this, N, dl, DAG, Created);
7229
7230 EVT VT = N->getValueType(0);
7231 EVT SVT = VT.getScalarType();
7232 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7233 EVT ShSVT = ShVT.getScalarType();
7234 unsigned EltBits = VT.getScalarSizeInBits();
7235 EVT MulVT;
7236
7237 // Check to see if we can do this.
7238 // FIXME: We should be more aggressive here.
7239 EVT QueryVT = VT;
7240 if (VT.isVector()) {
7241 // If the vector type will be legalized to a vector type with the same
7242 // element type, allow the transform before type legalization if MULHU or
7243 // UMUL_LOHI are supported.
7244 QueryVT = getLegalTypeToTransformTo(*DAG.getContext(), VT);
7245 if (!QueryVT.isVector() ||
7247 return SDValue();
7248 } else if (!isTypeLegal(VT)) {
7249 // Limit this to simple scalars for now.
7250 if (!VT.isSimple())
7251 return SDValue();
7252
7253 // If this type will be promoted to a large enough type with a legal
7254 // multiply operation, we can go ahead and do this transform.
7256 return SDValue();
7257
7258 MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
7259 if (MulVT.getSizeInBits() < (2 * EltBits) ||
7260 !isOperationLegal(ISD::MUL, MulVT))
7261 return SDValue();
7262 }
7263
7264 bool HasMULHU =
7265 isOperationLegalOrCustom(ISD::MULHU, QueryVT, IsAfterLegalization);
7266 bool HasUMUL_LOHI =
7267 isOperationLegalOrCustom(ISD::UMUL_LOHI, QueryVT, IsAfterLegalization);
7268
7269 if (isTypeLegal(VT) && !HasMULHU && !HasUMUL_LOHI && MulVT == EVT()) {
7270 // If type twice as wide legal, widen and use a mul plus a shift.
7271 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
7272 // Some targets like AMDGPU try to go from UDIV to UDIVREM which is then
7273 // custom lowered. This is very expensive so avoid it at all costs for
7274 // constant divisors.
7275 if ((!IsAfterLegalTypes && isOperationExpand(ISD::UDIV, VT) &&
7278 MulVT = WideVT;
7279 }
7280
7281 if (!HasMULHU && !HasUMUL_LOHI && MulVT == EVT())
7282 return SDValue();
7283
7284 SDValue N0 = N->getOperand(0);
7285 SDValue N1 = N->getOperand(1);
7286
7287 // Try to use leading zeros of the dividend to reduce the multiplier and
7288 // avoid expensive fixups.
7289 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
7290
7291 // If we're after type legalization and SVT is not legal, use the
7292 // promoted type for creating constants to avoid creating nodes with
7293 // illegal types.
7294 if (IsAfterLegalTypes && VT.isVector()) {
7295 SVT = getTypeToTransformTo(*DAG.getContext(), SVT);
7296 if (SVT.bitsLT(VT.getScalarType()))
7297 return SDValue();
7298 ShSVT = getTypeToTransformTo(*DAG.getContext(), ShSVT);
7299 if (ShSVT.bitsLT(ShVT.getScalarType()))
7300 return SDValue();
7301 }
7302 const unsigned SVTBits = SVT.getSizeInBits();
7303
7304 // Allow i32 to be widened to i64 for uncooperative divisors if i64 MULHU or
7305 // UMUL_LOHI is supported.
7306 const EVT WideSVT = MVT::i64;
7307 const bool HasWideMULHU =
7308 VT == MVT::i32 &&
7309 isOperationLegalOrCustom(ISD::MULHU, WideSVT, IsAfterLegalization);
7310 const bool HasWideUMUL_LOHI =
7311 VT == MVT::i32 &&
7312 isOperationLegalOrCustom(ISD::UMUL_LOHI, WideSVT, IsAfterLegalization);
7313 const bool AllowWiden = (HasWideMULHU || HasWideUMUL_LOHI);
7314
7315 // For even divisors with a 33-bit magic number, the widened high-multiply
7316 // path is only worthwhile over the even-divisor rewrite on targets that
7317 // zero-extend i32 to i64 for free (e.g. x86-64 and AArch64). Elsewhere (e.g.
7318 // RISC-V) keep the even-divisor rewrite, which avoids the explicit extension.
7319 const bool AllowEvenToWiden = AllowWiden && isZExtFree(VT, WideSVT);
7320
7321 bool UseNPQ = false, UsePreShift = false, UsePostShift = false;
7322 bool UseWiden = false;
7323 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
7324
7325 auto BuildUDIVPattern = [&](ConstantSDNode *C) {
7326 if (C->isZero())
7327 return false;
7328 // Truncate the divisor to the target scalar type in case it was promoted
7329 // during type legalization.
7330 APInt Divisor = C->getAPIntValue().trunc(EltBits);
7331
7332 SDValue PreShift, MagicFactor, NPQFactor, PostShift;
7333
7334 // Magic algorithm doesn't work for division by 1. We need to emit a select
7335 // at the end.
7336 if (Divisor.isOne()) {
7337 PreShift = PostShift = DAG.getUNDEF(ShSVT);
7338 MagicFactor = NPQFactor = DAG.getUNDEF(SVT);
7339 } else {
7342 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()),
7343 /*AllowEvenDivisorOptimization=*/!AllowEvenToWiden,
7344 /*AllowWidenOptimization=*/AllowWiden);
7345
7346 if (magics.Widen) {
7347 UseWiden = true;
7348 MagicFactor = DAG.getConstant(magics.Magic, dl, WideSVT);
7349 } else {
7350 MagicFactor = DAG.getConstant(magics.Magic.zext(SVTBits), dl, SVT);
7351 }
7352
7353 assert(magics.PreShift < Divisor.getBitWidth() &&
7354 "We shouldn't generate an undefined shift!");
7355 assert(magics.PostShift < Divisor.getBitWidth() &&
7356 "We shouldn't generate an undefined shift!");
7357 assert((!magics.IsAdd || magics.PreShift == 0) &&
7358 "Unexpected pre-shift");
7359 PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT);
7360 PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT);
7361 NPQFactor = DAG.getConstant(
7362 magics.IsAdd ? APInt::getOneBitSet(SVTBits, EltBits - 1)
7363 : APInt::getZero(SVTBits),
7364 dl, SVT);
7365 UseNPQ |= magics.IsAdd;
7366 UsePreShift |= magics.PreShift != 0;
7367 UsePostShift |= magics.PostShift != 0;
7368 }
7369
7370 PreShifts.push_back(PreShift);
7371 MagicFactors.push_back(MagicFactor);
7372 NPQFactors.push_back(NPQFactor);
7373 PostShifts.push_back(PostShift);
7374 return true;
7375 };
7376
7377 // Collect the shifts/magic values from each element.
7378 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern, /*AllowUndefs=*/false,
7379 /*AllowTruncation=*/true))
7380 return SDValue();
7381
7382 SDValue PreShift, PostShift, MagicFactor, NPQFactor;
7383 if (N1.getOpcode() == ISD::BUILD_VECTOR) {
7384 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
7385 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
7386 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
7387 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
7388 } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
7389 assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
7390 NPQFactors.size() == 1 && PostShifts.size() == 1 &&
7391 "Expected matchUnaryPredicate to return one for scalable vectors");
7392 PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
7393 MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
7394 NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
7395 PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
7396 } else {
7397 assert(isa<ConstantSDNode>(N1) && "Expected a constant");
7398 PreShift = PreShifts[0];
7399 MagicFactor = MagicFactors[0];
7400 PostShift = PostShifts[0];
7401 }
7402
7403 if (UseWiden) {
7404 // Compute: (WideSVT(x) * MagicFactor) >> WideSVTBits.
7405 SDValue WideN0 = DAG.getNode(ISD::ZERO_EXTEND, dl, WideSVT, N0);
7406
7407 // Perform WideSVTxWideSVT -> 2*WideSVT multiplication and extract high
7408 // WideSVT bits
7409 SDValue High;
7410 if (HasWideMULHU) {
7411 High = DAG.getNode(ISD::MULHU, dl, WideSVT, WideN0, MagicFactor);
7412 } else {
7413 assert(HasWideUMUL_LOHI);
7414 SDValue LoHi =
7415 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(WideSVT, WideSVT),
7416 WideN0, MagicFactor);
7417 High = LoHi.getValue(1);
7418 }
7419
7420 Created.push_back(High.getNode());
7421 return DAG.getNode(ISD::TRUNCATE, dl, VT, High);
7422 }
7423
7424 SDValue Q = N0;
7425 if (UsePreShift) {
7426 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
7427 Created.push_back(Q.getNode());
7428 }
7429
7430 auto GetMULHU = [&](SDValue X, SDValue Y) {
7431 if (HasMULHU)
7432 return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
7433 if (HasUMUL_LOHI) {
7434 SDValue LoHi =
7435 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
7436 return LoHi.getValue(1);
7437 }
7438
7439 X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
7440 Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
7441 Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
7442 Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
7443 DAG.getShiftAmountConstant(EltBits, MulVT, dl));
7444 return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
7445 };
7446
7447 // Multiply the numerator (operand 0) by the magic value.
7448 Q = GetMULHU(Q, MagicFactor);
7449 if (!Q)
7450 return SDValue();
7451
7452 Created.push_back(Q.getNode());
7453
7454 if (UseNPQ) {
7455 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
7456 Created.push_back(NPQ.getNode());
7457
7458 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
7459 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
7460 if (VT.isVector())
7461 NPQ = GetMULHU(NPQ, NPQFactor);
7462 else
7463 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
7464
7465 Created.push_back(NPQ.getNode());
7466
7467 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
7468 Created.push_back(Q.getNode());
7469 }
7470
7471 if (UsePostShift) {
7472 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
7473 Created.push_back(Q.getNode());
7474 }
7475
7476 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7477
7478 SDValue One = DAG.getConstant(1, dl, VT);
7479 SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
7480 return DAG.getSelect(dl, VT, IsOne, N0, Q);
7481}
7482
7483/// If all values in Values that *don't* match the predicate are same 'splat'
7484/// value, then replace all values with that splat value.
7485/// Else, if AlternativeReplacement was provided, then replace all values that
7486/// do match predicate with AlternativeReplacement value.
7487static void
7489 std::function<bool(SDValue)> Predicate,
7490 SDValue AlternativeReplacement = SDValue()) {
7491 SDValue Replacement;
7492 // Is there a value for which the Predicate does *NOT* match? What is it?
7493 auto SplatValue = llvm::find_if_not(Values, Predicate);
7494 if (SplatValue != Values.end()) {
7495 // Does Values consist only of SplatValue's and values matching Predicate?
7496 if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
7497 return Value == *SplatValue || Predicate(Value);
7498 })) // Then we shall replace values matching predicate with SplatValue.
7499 Replacement = *SplatValue;
7500 }
7501 if (!Replacement) {
7502 // Oops, we did not find the "baseline" splat value.
7503 if (!AlternativeReplacement)
7504 return; // Nothing to do.
7505 // Let's replace with provided value then.
7506 Replacement = AlternativeReplacement;
7507 }
7508 std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
7509}
7510
7511/// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
7512/// where the divisor and comparison target are constants,
7513/// return a DAG expression that will generate the same comparison result
7514/// using only multiplications, additions and shifts/rotations.
7515/// Ref: "Hacker's Delight" 10-17.
7516SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
7517 SDValue CompTargetNode,
7519 DAGCombinerInfo &DCI,
7520 const SDLoc &DL) const {
7522 if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7523 DCI, DL, Built)) {
7524 for (SDNode *N : Built)
7525 DCI.AddToWorklist(N);
7526 return Folded;
7527 }
7528
7529 return SDValue();
7530}
7531
7532SDValue
7533TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
7534 SDValue CompTargetNode, ISD::CondCode Cond,
7535 DAGCombinerInfo &DCI, const SDLoc &DL,
7536 SmallVectorImpl<SDNode *> &Created) const {
7537 // fold (seteq/ne (urem N, D), C) ->
7538 // (setule/ugt (rotr (mul (sub N, C), P), K), Q)
7539 // - D must be constant, with D = D0 * 2^K where D0 is odd
7540 // - P is the multiplicative inverse of D0 modulo 2^W
7541 // - Q = floor(((2^W) - 1) / D)
7542 // where W is the width of the common type of N and D.
7543 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7544 "Only applicable for (in)equality comparisons.");
7545
7546 SelectionDAG &DAG = DCI.DAG;
7547
7548 EVT VT = REMNode.getValueType();
7549 EVT SVT = VT.getScalarType();
7550 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7551 EVT ShSVT = ShVT.getScalarType();
7552
7553 // If MUL is unavailable, we cannot proceed in any case.
7554 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7555 return SDValue();
7556
7557 bool ComparingWithAllZeros = true;
7558 bool AllComparisonsWithNonZerosAreTautological = true;
7559 bool HadTautologicalLanes = false;
7560 bool AllLanesAreTautological = true;
7561 bool HadEvenDivisor = false;
7562 bool AllDivisorsArePowerOfTwo = true;
7563 bool HadTautologicalInvertedLanes = false;
7564 SmallVector<SDValue, 16> PAmts, KAmts, QAmts;
7565
7566 auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
7567 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7568 if (CDiv->isZero())
7569 return false;
7570
7571 const APInt &D = CDiv->getAPIntValue();
7572 const APInt &Cmp = CCmp->getAPIntValue();
7573
7574 ComparingWithAllZeros &= Cmp.isZero();
7575
7576 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7577 // if C2 is not less than C1, the comparison is always false.
7578 // But we will only be able to produce the comparison that will give the
7579 // opposive tautological answer. So this lane would need to be fixed up.
7580 bool TautologicalInvertedLane = D.ule(Cmp);
7581 HadTautologicalInvertedLanes |= TautologicalInvertedLane;
7582
7583 // If all lanes are tautological (either all divisors are ones, or divisor
7584 // is not greater than the constant we are comparing with),
7585 // we will prefer to avoid the fold.
7586 bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
7587 HadTautologicalLanes |= TautologicalLane;
7588 AllLanesAreTautological &= TautologicalLane;
7589
7590 // If we are comparing with non-zero, we need'll need to subtract said
7591 // comparison value from the LHS. But there is no point in doing that if
7592 // every lane where we are comparing with non-zero is tautological..
7593 if (!Cmp.isZero())
7594 AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
7595
7596 // Decompose D into D0 * 2^K
7597 unsigned K = D.countr_zero();
7598 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7599 APInt D0 = D.lshr(K);
7600
7601 // D is even if it has trailing zeros.
7602 HadEvenDivisor |= (K != 0);
7603 // D is a power-of-two if D0 is one.
7604 // If all divisors are power-of-two, we will prefer to avoid the fold.
7605 AllDivisorsArePowerOfTwo &= D0.isOne();
7606
7607 // P = inv(D0, 2^W)
7608 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7609 unsigned W = D.getBitWidth();
7610 APInt P = D0.multiplicativeInverse();
7611 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7612
7613 // Q = floor((2^W - 1) u/ D)
7614 // R = ((2^W - 1) u% D)
7615 APInt Q, R;
7617
7618 // If we are comparing with zero, then that comparison constant is okay,
7619 // else it may need to be one less than that.
7620 if (Cmp.ugt(R))
7621 Q -= 1;
7622
7624 "We are expecting that K is always less than all-ones for ShSVT");
7625
7626 // If the lane is tautological the result can be constant-folded.
7627 if (TautologicalLane) {
7628 // Set P and K amount to a bogus values so we can try to splat them.
7629 P = 0;
7630 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7631 // And ensure that comparison constant is tautological,
7632 // it will always compare true/false.
7633 Q.setAllBits();
7634 } else {
7635 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7636 }
7637
7638 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7639 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7640 return true;
7641 };
7642
7643 SDValue N = REMNode.getOperand(0);
7644 SDValue D = REMNode.getOperand(1);
7645
7646 // Collect the values from each element.
7647 if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
7648 return SDValue();
7649
7650 // If all lanes are tautological, the result can be constant-folded.
7651 if (AllLanesAreTautological)
7652 return SDValue();
7653
7654 // If this is a urem by a powers-of-two, avoid the fold since it can be
7655 // best implemented as a bit test.
7656 if (AllDivisorsArePowerOfTwo)
7657 return SDValue();
7658
7659 SDValue PVal, KVal, QVal;
7660 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7661 if (HadTautologicalLanes) {
7662 // Try to turn PAmts into a splat, since we don't care about the values
7663 // that are currently '0'. If we can't, just keep '0'`s.
7665 // Try to turn KAmts into a splat, since we don't care about the values
7666 // that are currently '-1'. If we can't, change them to '0'`s.
7668 DAG.getConstant(0, DL, ShSVT));
7669 }
7670
7671 PVal = DAG.getBuildVector(VT, DL, PAmts);
7672 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7673 QVal = DAG.getBuildVector(VT, DL, QAmts);
7674 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7675 assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
7676 "Expected matchBinaryPredicate to return one element for "
7677 "SPLAT_VECTORs");
7678 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7679 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7680 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7681 } else {
7682 PVal = PAmts[0];
7683 KVal = KAmts[0];
7684 QVal = QAmts[0];
7685 }
7686
7687 if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
7688 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
7689 return SDValue(); // FIXME: Could/should use `ISD::ADD`?
7690 assert(CompTargetNode.getValueType() == N.getValueType() &&
7691 "Expecting that the types on LHS and RHS of comparisons match.");
7692 N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
7693 }
7694
7695 // (mul N, P)
7696 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7697 Created.push_back(Op0.getNode());
7698
7699 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7700 // divisors as a performance improvement, since rotating by 0 is a no-op.
7701 if (HadEvenDivisor) {
7702 // We need ROTR to do this.
7703 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7704 return SDValue();
7705 // UREM: (rotr (mul N, P), K)
7706 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7707 Created.push_back(Op0.getNode());
7708 }
7709
7710 // UREM: (setule/setugt (rotr (mul N, P), K), Q)
7711 SDValue NewCC =
7712 DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7714 if (!HadTautologicalInvertedLanes)
7715 return NewCC;
7716
7717 // If any lanes previously compared always-false, the NewCC will give
7718 // always-true result for them, so we need to fixup those lanes.
7719 // Or the other way around for inequality predicate.
7720 assert(VT.isVector() && "Can/should only get here for vectors.");
7721 Created.push_back(NewCC.getNode());
7722
7723 // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
7724 // if C2 is not less than C1, the comparison is always false.
7725 // But we have produced the comparison that will give the
7726 // opposive tautological answer. So these lanes would need to be fixed up.
7727 SDValue TautologicalInvertedChannels =
7728 DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
7729 Created.push_back(TautologicalInvertedChannels.getNode());
7730
7731 // NOTE: we avoid letting illegal types through even if we're before legalize
7732 // ops – legalization has a hard time producing good code for this.
7733 if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
7734 // If we have a vector select, let's replace the comparison results in the
7735 // affected lanes with the correct tautological result.
7736 SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
7737 DL, SETCCVT, SETCCVT);
7738 return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
7739 Replacement, NewCC);
7740 }
7741
7742 // Else, we can just invert the comparison result in the appropriate lanes.
7743 //
7744 // NOTE: see the note above VSELECT above.
7745 if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
7746 return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
7747 TautologicalInvertedChannels);
7748
7749 return SDValue(); // Don't know how to lower.
7750}
7751
7752/// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
7753/// where the divisor is constant and the comparison target is zero,
7754/// return a DAG expression that will generate the same comparison result
7755/// using only multiplications, additions and shifts/rotations.
7756/// Ref: "Hacker's Delight" 10-17.
7757SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
7758 SDValue CompTargetNode,
7760 DAGCombinerInfo &DCI,
7761 const SDLoc &DL) const {
7763 if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
7764 DCI, DL, Built)) {
7765 assert(Built.size() <= 7 && "Max size prediction failed.");
7766 for (SDNode *N : Built)
7767 DCI.AddToWorklist(N);
7768 return Folded;
7769 }
7770
7771 return SDValue();
7772}
7773
7774SDValue
7775TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
7776 SDValue CompTargetNode, ISD::CondCode Cond,
7777 DAGCombinerInfo &DCI, const SDLoc &DL,
7778 SmallVectorImpl<SDNode *> &Created) const {
7779 // Derived from Hacker's Delight, 2nd Edition, by Hank Warren. Section 10-17.
7780 // Fold:
7781 // (seteq/ne (srem N, D), 0)
7782 // To:
7783 // (setule/ugt (rotr (add (mul N, P), A), K), Q)
7784 //
7785 // - D must be constant, with D = D0 * 2^K where D0 is odd
7786 // - P is the multiplicative inverse of D0 modulo 2^W
7787 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
7788 // - Q = floor((2 * A) / (2^K))
7789 // where W is the width of the common type of N and D.
7790 //
7791 // When D is a power of two (and thus D0 is 1), the normal
7792 // formula for A and Q don't apply, because the derivation
7793 // depends on D not dividing 2^(W-1), and thus theorem ZRS
7794 // does not apply. This specifically fails when N = INT_MIN.
7795 //
7796 // Instead, for power-of-two D, we use:
7797 // - A = 0
7798 // | -> No offset needed. We're effectively treating it the same as urem.
7799 // - Q = 2^(W-K) - 1
7800 // |-> Test that the top K bits are zero after rotation
7801 assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
7802 "Only applicable for (in)equality comparisons.");
7803
7804 SelectionDAG &DAG = DCI.DAG;
7805
7806 EVT VT = REMNode.getValueType();
7807 EVT SVT = VT.getScalarType();
7808 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7809 EVT ShSVT = ShVT.getScalarType();
7810
7811 // If we are after ops legalization, and MUL is unavailable, we can not
7812 // proceed.
7813 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
7814 return SDValue();
7815
7816 // TODO: Could support comparing with non-zero too.
7817 ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
7818 if (!CompTarget || !CompTarget->isZero())
7819 return SDValue();
7820
7821 bool HadOneDivisor = false;
7822 bool AllDivisorsAreOnes = true;
7823 bool HadEvenDivisor = false;
7824 bool AllDivisorsArePowerOfTwo = true;
7825 SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
7826
7827 auto BuildSREMPattern = [&](ConstantSDNode *C) {
7828 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
7829 if (C->isZero())
7830 return false;
7831
7832 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
7833
7834 // WARNING: this fold is only valid for positive divisors!
7835 // `rem %X, -C` is equivalent to `rem %X, C`
7836 APInt D = C->getAPIntValue().abs();
7837
7838 // If all divisors are ones, we will prefer to avoid the fold.
7839 HadOneDivisor |= D.isOne();
7840 AllDivisorsAreOnes &= D.isOne();
7841
7842 // Decompose D into D0 * 2^K
7843 unsigned K = D.countr_zero();
7844 assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
7845 APInt D0 = D.lshr(K);
7846
7847 // D is even if it has trailing zeros.
7848 HadEvenDivisor |= (K != 0);
7849
7850 // D is a power-of-two if D0 is one. This includes INT_MIN.
7851 // If all divisors are power-of-two, we will prefer to avoid the fold.
7852 AllDivisorsArePowerOfTwo &= D0.isOne();
7853
7854 // P = inv(D0, 2^W)
7855 // 2^W requires W + 1 bits, so we have to extend and then truncate.
7856 unsigned W = D.getBitWidth();
7857 APInt P = D0.multiplicativeInverse();
7858 assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
7859
7860 // A = floor((2^(W - 1) - 1) / D0) & -2^K
7861 APInt A = APInt::getSignedMaxValue(W).udiv(D0);
7862 A.clearLowBits(K);
7863
7864 // Q = floor((2 * A) / (2^K))
7865 APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
7866
7868 "We are expecting that A is always less than all-ones for SVT");
7870 "We are expecting that K is always less than all-ones for ShSVT");
7871
7872 // If D was a power of two, apply the alternate constant derivation.
7873 if (D0.isOne()) {
7874 // A = 0
7875 A = APInt(W, 0);
7876 // - Q = 2^(W-K) - 1
7877 Q = APInt::getLowBitsSet(W, W - K);
7878 }
7879
7880 // If the divisor is 1 the result can be constant-folded.
7881 if (D.isOne()) {
7882 // Set P, A and K to a bogus values so we can try to splat them.
7883 P = 0;
7884 A.setAllBits();
7885 KAmts.push_back(DAG.getAllOnesConstant(DL, ShSVT));
7886
7887 // x ?% 1 == 0 <--> true <--> x u<= -1
7888 Q.setAllBits();
7889 } else {
7890 KAmts.push_back(DAG.getConstant(K, DL, ShSVT));
7891 }
7892
7893 PAmts.push_back(DAG.getConstant(P, DL, SVT));
7894 AAmts.push_back(DAG.getConstant(A, DL, SVT));
7895 QAmts.push_back(DAG.getConstant(Q, DL, SVT));
7896 return true;
7897 };
7898
7899 SDValue N = REMNode.getOperand(0);
7900 SDValue D = REMNode.getOperand(1);
7901
7902 // Collect the values from each element.
7903 if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
7904 return SDValue();
7905
7906 // If this is a srem by a one, avoid the fold since it can be constant-folded.
7907 if (AllDivisorsAreOnes)
7908 return SDValue();
7909
7910 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
7911 // since it can be best implemented as a bit test.
7912 if (AllDivisorsArePowerOfTwo)
7913 return SDValue();
7914
7915 SDValue PVal, AVal, KVal, QVal;
7916 if (D.getOpcode() == ISD::BUILD_VECTOR) {
7917 if (HadOneDivisor) {
7918 // Try to turn PAmts into a splat, since we don't care about the values
7919 // that are currently '0'. If we can't, just keep '0'`s.
7921 // Try to turn AAmts into a splat, since we don't care about the
7922 // values that are currently '-1'. If we can't, change them to '0'`s.
7924 DAG.getConstant(0, DL, SVT));
7925 // Try to turn KAmts into a splat, since we don't care about the values
7926 // that are currently '-1'. If we can't, change them to '0'`s.
7928 DAG.getConstant(0, DL, ShSVT));
7929 }
7930
7931 PVal = DAG.getBuildVector(VT, DL, PAmts);
7932 AVal = DAG.getBuildVector(VT, DL, AAmts);
7933 KVal = DAG.getBuildVector(ShVT, DL, KAmts);
7934 QVal = DAG.getBuildVector(VT, DL, QAmts);
7935 } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
7936 assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
7937 QAmts.size() == 1 &&
7938 "Expected matchUnaryPredicate to return one element for scalable "
7939 "vectors");
7940 PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
7941 AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
7942 KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
7943 QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
7944 } else {
7945 assert(isa<ConstantSDNode>(D) && "Expected a constant");
7946 PVal = PAmts[0];
7947 AVal = AAmts[0];
7948 KVal = KAmts[0];
7949 QVal = QAmts[0];
7950 }
7951
7952 // (mul N, P)
7953 SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
7954 Created.push_back(Op0.getNode());
7955
7956 // We need ADD to do this.
7957 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
7958 return SDValue();
7959
7960 // (add (mul N, P), A)
7961 Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
7962 Created.push_back(Op0.getNode());
7963
7964 // Rotate right only if any divisor was even. We avoid rotates for all-odd
7965 // divisors as a performance improvement, since rotating by 0 is a no-op.
7966 if (HadEvenDivisor) {
7967 // We need ROTR to do this.
7968 if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
7969 return SDValue();
7970 // SREM: (rotr (add (mul N, P), A), K)
7971 Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
7972 Created.push_back(Op0.getNode());
7973 }
7974
7975 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
7976 return DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7978}
7979
7981 const DenormalMode &Mode,
7982 SDNodeFlags Flags) const {
7983 SDLoc DL(Op);
7984 EVT VT = Op.getValueType();
7985 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7986 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
7987
7988 // This is specifically a check for the handling of denormal inputs, not the
7989 // result.
7990 if (Mode.Input == DenormalMode::PreserveSign ||
7991 Mode.Input == DenormalMode::PositiveZero) {
7992 // Test = X == 0.0
7993 return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ, /*Chain=*/{},
7994 /*Signaling=*/false, Flags);
7995 }
7996
7997 // Testing it with denormal inputs to avoid wrong estimate.
7998 //
7999 // Test = fabs(X) < SmallestNormal
8000 const fltSemantics &FltSem = VT.getFltSemantics();
8001 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
8002 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
8003 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op, Flags);
8004 return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT, /*Chain=*/{},
8005 /*Signaling=*/false, Flags);
8006}
8007
8009 bool LegalOps, bool OptForSize,
8011 unsigned Depth) const {
8012 // fneg is removable even if it has multiple uses.
8013 if (Op.getOpcode() == ISD::FNEG) {
8015 return Op.getOperand(0);
8016 }
8017
8018 // Don't recurse exponentially.
8020 return SDValue();
8021
8022 // Pre-increment recursion depth for use in recursive calls.
8023 ++Depth;
8024 const SDNodeFlags Flags = Op->getFlags();
8025 EVT VT = Op.getValueType();
8026 unsigned Opcode = Op.getOpcode();
8027
8028 // Don't allow anything with multiple uses unless we know it is free.
8029 if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
8030 bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
8031 isFPExtFree(VT, Op.getOperand(0).getValueType());
8032 if (!IsFreeExtend)
8033 return SDValue();
8034 }
8035
8036 auto RemoveDeadNode = [&](SDValue N) {
8037 if (N && N.getNode()->use_empty())
8038 DAG.RemoveDeadNode(N.getNode());
8039 };
8040
8041 SDLoc DL(Op);
8042
8043 // Because getNegatedExpression can delete nodes we need a handle to keep
8044 // temporary nodes alive in case the recursion manages to create an identical
8045 // node.
8046 std::list<HandleSDNode> Handles;
8047
8048 switch (Opcode) {
8049 case ISD::ConstantFP: {
8050 // Don't invert constant FP values after legalization unless the target says
8051 // the negated constant is legal.
8052 bool IsOpLegal =
8054 isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
8055 OptForSize);
8056
8057 if (LegalOps && !IsOpLegal)
8058 break;
8059
8060 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
8061 V.changeSign();
8062 SDValue CFP = DAG.getConstantFP(V, DL, VT);
8063
8064 // If we already have the use of the negated floating constant, it is free
8065 // to negate it even it has multiple uses.
8066 if (!Op.hasOneUse() && CFP.use_empty())
8067 break;
8069 return CFP;
8070 }
8071 case ISD::SPLAT_VECTOR: {
8072 // fold splat_vector(fneg(X)) -> splat_vector(-X)
8073 SDValue X = Op.getOperand(0);
8075 break;
8076
8077 SDValue NegX = getCheaperNegatedExpression(X, DAG, LegalOps, OptForSize);
8078 if (!NegX)
8079 break;
8081 return DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, NegX);
8082 }
8083 case ISD::BUILD_VECTOR: {
8084 // Only permit BUILD_VECTOR of constants.
8085 if (llvm::any_of(Op->op_values(), [&](SDValue N) {
8086 return !N.isUndef() && !isa<ConstantFPSDNode>(N);
8087 }))
8088 break;
8089
8090 bool IsOpLegal =
8093 llvm::all_of(Op->op_values(), [&](SDValue N) {
8094 return N.isUndef() ||
8095 isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
8096 OptForSize);
8097 });
8098
8099 if (LegalOps && !IsOpLegal)
8100 break;
8101
8103 for (SDValue C : Op->op_values()) {
8104 if (C.isUndef()) {
8105 Ops.push_back(C);
8106 continue;
8107 }
8108 APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
8109 V.changeSign();
8110 Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
8111 }
8113 return DAG.getBuildVector(VT, DL, Ops);
8114 }
8115 case ISD::FADD: {
8116 if (!Flags.hasNoSignedZeros())
8117 break;
8118
8119 // After operation legalization, it might not be legal to create new FSUBs.
8120 if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
8121 break;
8122 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8123
8124 // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
8126 SDValue NegX =
8127 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8128 // Prevent this node from being deleted by the next call.
8129 if (NegX)
8130 Handles.emplace_back(NegX);
8131
8132 // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
8134 SDValue NegY =
8135 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8136
8137 // We're done with the handles.
8138 Handles.clear();
8139
8140 // Negate the X if its cost is less or equal than Y.
8141 if (NegX && (CostX <= CostY)) {
8142 Cost = CostX;
8143 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
8144 if (NegY != N)
8145 RemoveDeadNode(NegY);
8146 return N;
8147 }
8148
8149 // Negate the Y if it is not expensive.
8150 if (NegY) {
8151 Cost = CostY;
8152 SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
8153 if (NegX != N)
8154 RemoveDeadNode(NegX);
8155 return N;
8156 }
8157 break;
8158 }
8159 case ISD::FSUB: {
8160 // We can't turn -(A-B) into B-A when we honor signed zeros.
8161 if (!Flags.hasNoSignedZeros())
8162 break;
8163
8164 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8165 // fold (fneg (fsub 0, Y)) -> Y
8166 if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
8167 if (C->isZero()) {
8169 return Y;
8170 }
8171
8172 // fold (fneg (fsub X, Y)) -> (fsub Y, X)
8174 return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
8175 }
8176 case ISD::FMUL:
8177 case ISD::FDIV: {
8178 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
8179
8180 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
8182 SDValue NegX =
8183 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8184 // Prevent this node from being deleted by the next call.
8185 if (NegX)
8186 Handles.emplace_back(NegX);
8187
8188 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
8190 SDValue NegY =
8191 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8192
8193 // We're done with the handles.
8194 Handles.clear();
8195
8196 // Negate the X if its cost is less or equal than Y.
8197 if (NegX && (CostX <= CostY)) {
8198 Cost = CostX;
8199 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
8200 if (NegY != N)
8201 RemoveDeadNode(NegY);
8202 return N;
8203 }
8204
8205 // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
8206 if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
8207 if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
8208 break;
8209
8210 // Negate the Y if it is not expensive.
8211 if (NegY) {
8212 Cost = CostY;
8213 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
8214 if (NegX != N)
8215 RemoveDeadNode(NegX);
8216 return N;
8217 }
8218 break;
8219 }
8220 case ISD::FMA:
8221 case ISD::FMULADD:
8222 case ISD::FMAD: {
8223 if (!Flags.hasNoSignedZeros())
8224 break;
8225
8226 SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
8228 SDValue NegZ =
8229 getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
8230 // Give up if fail to negate the Z.
8231 if (!NegZ)
8232 break;
8233
8234 // Prevent this node from being deleted by the next two calls.
8235 Handles.emplace_back(NegZ);
8236
8237 // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
8239 SDValue NegX =
8240 getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
8241 // Prevent this node from being deleted by the next call.
8242 if (NegX)
8243 Handles.emplace_back(NegX);
8244
8245 // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
8247 SDValue NegY =
8248 getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
8249
8250 // We're done with the handles.
8251 Handles.clear();
8252
8253 // Negate the X if its cost is less or equal than Y.
8254 if (NegX && (CostX <= CostY)) {
8255 Cost = std::min(CostX, CostZ);
8256 SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
8257 if (NegY != N)
8258 RemoveDeadNode(NegY);
8259 return N;
8260 }
8261
8262 // Negate the Y if it is not expensive.
8263 if (NegY) {
8264 Cost = std::min(CostY, CostZ);
8265 SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
8266 if (NegX != N)
8267 RemoveDeadNode(NegX);
8268 return N;
8269 }
8270 break;
8271 }
8272
8273 case ISD::FP_EXTEND:
8274 case ISD::FSIN:
8275 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8276 OptForSize, Cost, Depth))
8277 return DAG.getNode(Opcode, DL, VT, NegV);
8278 break;
8279 case ISD::FP_ROUND:
8280 if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
8281 OptForSize, Cost, Depth))
8282 return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
8283 break;
8284 case ISD::SELECT:
8285 case ISD::VSELECT: {
8286 // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS))
8287 // iff at least one cost is cheaper and the other is neutral/cheaper
8288 SDValue LHS = Op.getOperand(1);
8290 SDValue NegLHS =
8291 getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth);
8292 if (!NegLHS || CostLHS > NegatibleCost::Neutral) {
8293 RemoveDeadNode(NegLHS);
8294 break;
8295 }
8296
8297 // Prevent this node from being deleted by the next call.
8298 Handles.emplace_back(NegLHS);
8299
8300 SDValue RHS = Op.getOperand(2);
8302 SDValue NegRHS =
8303 getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth);
8304
8305 // We're done with the handles.
8306 Handles.clear();
8307
8308 if (!NegRHS || CostRHS > NegatibleCost::Neutral ||
8309 (CostLHS != NegatibleCost::Cheaper &&
8310 CostRHS != NegatibleCost::Cheaper)) {
8311 RemoveDeadNode(NegLHS);
8312 RemoveDeadNode(NegRHS);
8313 break;
8314 }
8315
8316 Cost = std::min(CostLHS, CostRHS);
8317 return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS);
8318 }
8319 }
8320
8321 return SDValue();
8322}
8323
8324//===----------------------------------------------------------------------===//
8325// Legalization Utilities
8326//===----------------------------------------------------------------------===//
8327
8328bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
8329 SDValue LHS, SDValue RHS,
8331 EVT HiLoVT, SelectionDAG &DAG,
8332 MulExpansionKind Kind, SDValue LL,
8333 SDValue LH, SDValue RL, SDValue RH) const {
8334 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
8335 Opcode == ISD::SMUL_LOHI);
8336
8337 bool HasMULHS = (Kind == MulExpansionKind::Always) ||
8339 bool HasMULHU = (Kind == MulExpansionKind::Always) ||
8341 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8343 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
8345
8346 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
8347 return false;
8348
8349 unsigned OuterBitSize = VT.getScalarSizeInBits();
8350 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
8351
8352 // LL, LH, RL, and RH must be either all NULL or all set to a value.
8353 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
8354 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
8355
8356 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
8357 bool Signed) -> bool {
8358 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
8359 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
8360 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
8361 Hi = Lo.getValue(1);
8362 return true;
8363 }
8364 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
8365 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
8366 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
8367 return true;
8368 }
8369 return false;
8370 };
8371
8372 SDValue Lo, Hi;
8373
8374 if (!LL.getNode() && !RL.getNode() &&
8376 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
8377 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
8378 }
8379
8380 if (!LL.getNode())
8381 return false;
8382
8383 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
8384 if (DAG.MaskedValueIsZero(LHS, HighMask) &&
8385 DAG.MaskedValueIsZero(RHS, HighMask)) {
8386 // The inputs are both zero-extended.
8387 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
8388 Result.push_back(Lo);
8389 Result.push_back(Hi);
8390 if (Opcode != ISD::MUL) {
8391 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8392 Result.push_back(Zero);
8393 Result.push_back(Zero);
8394 }
8395 return true;
8396 }
8397 }
8398
8399 if (!VT.isVector() && Opcode == ISD::MUL &&
8400 DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize &&
8401 DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) {
8402 // The input values are both sign-extended.
8403 // TODO non-MUL case?
8404 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
8405 Result.push_back(Lo);
8406 Result.push_back(Hi);
8407 return true;
8408 }
8409 }
8410
8411 unsigned ShiftAmount = OuterBitSize - InnerBitSize;
8412 SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
8413
8414 if (!LH.getNode() && !RH.getNode() &&
8417 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
8418 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
8419 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
8420 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
8421 }
8422
8423 if (!LH.getNode())
8424 return false;
8425
8426 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
8427 return false;
8428
8429 Result.push_back(Lo);
8430
8431 if (Opcode == ISD::MUL) {
8432 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
8433 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
8434 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
8435 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
8436 Result.push_back(Hi);
8437 return true;
8438 }
8439
8440 // Compute the full width result.
8441 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
8442 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
8443 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8444 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
8445 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
8446 };
8447
8448 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
8449 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
8450 return false;
8451
8452 // This is effectively the add part of a multiply-add of half-sized operands,
8453 // so it cannot overflow.
8454 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8455
8456 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
8457 return false;
8458
8459 SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
8460 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8461
8462 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
8464 if (UseGlue)
8465 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
8466 Merge(Lo, Hi));
8467 else
8468 Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next,
8469 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
8470
8471 SDValue Carry = Next.getValue(1);
8472 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8473 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8474
8475 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
8476 return false;
8477
8478 if (UseGlue)
8479 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
8480 Carry);
8481 else
8482 Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
8483 Zero, Carry);
8484
8485 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
8486
8487 if (Opcode == ISD::SMUL_LOHI) {
8488 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8489 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
8490 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
8491
8492 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
8493 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
8494 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
8495 }
8496
8497 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8498 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
8499 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
8500 return true;
8501}
8502
8504 SelectionDAG &DAG, MulExpansionKind Kind,
8505 SDValue LL, SDValue LH, SDValue RL,
8506 SDValue RH) const {
8508 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
8509 N->getOperand(0), N->getOperand(1), Result, HiLoVT,
8510 DAG, Kind, LL, LH, RL, RH);
8511 if (Ok) {
8512 assert(Result.size() == 2);
8513 Lo = Result[0];
8514 Hi = Result[1];
8515 }
8516 return Ok;
8517}
8518
8519// Optimize unsigned division or remainder by constants for types twice as large
8520// as a legal VT.
8521//
8522// If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
8523// can be computed
8524// as:
8525// Sum = __builtin_uadd_overflow(Lo, High, &Sum);
8526// Remainder = Sum % Constant;
8527//
8528// If (1 << (BitWidth / 2)) % Constant != 1, we can search for a smaller value
8529// W such that W != (BitWidth / 2) and (1 << W) % Constant == 1. We can break
8530// High:Low into 3 chunks of W bits and compute remainder as
8531// Sum = Chunk0 + Chunk1 + Chunk2;
8532// Remainder = Sum % Constant;
8533//
8534// This is based on "Remainder by Summing Digits" from Hacker's Delight.
8535//
8536// For division, we can compute the remainder using the algorithm described
8537// above, subtract it from the dividend to get an exact multiple of Constant.
8538// Then multiply that exact multiply by the multiplicative inverse modulo
8539// (1 << (BitWidth / 2)) to get the quotient.
8540
8541// If Constant is even, we can shift right the dividend and the divisor by the
8542// number of trailing zeros in Constant before applying the remainder algorithm.
8543// If we're after the quotient, we can subtract this value from the shifted
8544// dividend and multiply by the multiplicative inverse of the shifted divisor.
8545// If we want the remainder, we shift the value left by the number of trailing
8546// zeros and add the bits that were shifted out of the dividend.
8547bool TargetLowering::expandUDIVREMByConstantViaUREMDecomposition(
8548 SDNode *N, APInt Divisor, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
8549 SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8550 unsigned Opcode = N->getOpcode();
8551 EVT VT = N->getValueType(0);
8552
8553 unsigned BitWidth = Divisor.getBitWidth();
8554 unsigned HBitWidth = BitWidth / 2;
8556 HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs");
8557
8558 // If the divisor is even, shift it until it becomes odd.
8559 unsigned TrailingZeros = 0;
8560 if (!Divisor[0]) {
8561 TrailingZeros = Divisor.countr_zero();
8562 Divisor.lshrInPlace(TrailingZeros);
8563 }
8564
8565 // After removing trailing zeros, the divisor needs to be less than
8566 // (1 << HBitWidth).
8567 APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth);
8568 if (Divisor.uge(HalfMaxPlus1))
8569 return false;
8570
8571 // Look for the largest chunk width W such that (1 << W) % Divisor == 1 or
8572 // (1 << W) % Divisor == -1.
8573 unsigned BestChunkWidth = 0, AltChunkWidth = 0;
8574 for (unsigned I = HBitWidth, E = HBitWidth / 2; I > E; --I) {
8575 // Skip HBitWidth-1, it doesn't have enough bits for carries.
8576 if (I == HBitWidth - 1)
8577 continue;
8578
8579 APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
8580
8581 if (Mod.isOne()) {
8582 BestChunkWidth = I;
8583 break;
8584 }
8585
8586 // We have an alternate strategy for Remainder == Divisor - 1.
8587 // FIXME: Support HBitWidth.
8588 if (I != HBitWidth && Mod == Divisor - 1)
8589 AltChunkWidth = I;
8590 }
8591
8592 bool Alternate = false;
8593 if (!BestChunkWidth) {
8594 if (!AltChunkWidth)
8595 return false;
8596 Alternate = true;
8597 BestChunkWidth = AltChunkWidth;
8598 }
8599
8600 SDLoc dl(N);
8601
8602 assert(!LL == !LH && "Expected both input halves or no input halves!");
8603 if (!LL)
8604 std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
8605
8606 bool HasFSHR = isOperationLegal(ISD::FSHR, HiLoVT);
8607
8608 auto GetFSHR = [&](SDValue Lo, SDValue Hi, unsigned ShiftAmt) {
8609 assert(ShiftAmt > 0 && ShiftAmt < HBitWidth);
8610 if (HasFSHR)
8611 return DAG.getNode(ISD::FSHR, dl, HiLoVT, Hi, Lo,
8612 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8613 return DAG.getNode(
8614 ISD::OR, dl, HiLoVT,
8615 DAG.getNode(ISD::SRL, dl, HiLoVT, Lo,
8616 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl)),
8617 DAG.getNode(
8618 ISD::SHL, dl, HiLoVT, Hi,
8619 DAG.getShiftAmountConstant(HBitWidth - ShiftAmt, HiLoVT, dl)));
8620 };
8621
8622 // Helper to perform a right shift on a 128-bit value split into two halves.
8623 // Handles shifts >= HBitWidth by moving Hi to Lo and shifting Hi.
8624 auto ShiftRight = [&](SDValue &Lo, SDValue &Hi, unsigned ShiftAmt) {
8625 if (ShiftAmt == 0)
8626 return;
8627 if (ShiftAmt < HBitWidth) {
8628 Lo = GetFSHR(Lo, Hi, ShiftAmt);
8629 Hi = DAG.getNode(ISD::SRL, dl, HiLoVT, Hi,
8630 DAG.getShiftAmountConstant(ShiftAmt, HiLoVT, dl));
8631 } else if (ShiftAmt == HBitWidth) {
8632 Lo = Hi;
8633 Hi = DAG.getConstant(0, dl, HiLoVT);
8634 } else {
8635 Lo = DAG.getNode(
8636 ISD::SRL, dl, HiLoVT, Hi,
8637 DAG.getShiftAmountConstant(ShiftAmt - HBitWidth, HiLoVT, dl));
8638 Hi = DAG.getConstant(0, dl, HiLoVT);
8639 }
8640 };
8641
8642 // Shift the input by the number of TrailingZeros in the divisor. The
8643 // shifted out bits will be added to the remainder later.
8644 SDValue PartialRemL, PartialRemH;
8645 if (TrailingZeros && Opcode != ISD::UDIV) {
8646 // Save the shifted off bits if we need the remainder.
8647 if (TrailingZeros < HBitWidth) {
8648 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
8649 PartialRemL = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
8650 DAG.getConstant(Mask, dl, HiLoVT));
8651 } else if (TrailingZeros == HBitWidth) {
8652 // All of LL is part of the remainder.
8653 PartialRemL = LL;
8654 } else {
8655 // TrailingZeros > HBitWidth: LL and part of LH are the remainder.
8656 PartialRemL = LL;
8657 APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros - HBitWidth);
8658 PartialRemH = DAG.getNode(ISD::AND, dl, HiLoVT, LH,
8659 DAG.getConstant(Mask, dl, HiLoVT));
8660 }
8661 }
8662
8663 SDValue Sum;
8664 // If BestChunkWidth is HBitWidth add low and high half. If there is a carry
8665 // out, add that to the final sum.
8666 if (BestChunkWidth == HBitWidth) {
8667 assert(!Alternate);
8668 // Shift LH:LL right if there were trailing zeros in the divisor.
8669 ShiftRight(LL, LH, TrailingZeros);
8670
8671 // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
8672 EVT SetCCType =
8673 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
8675 SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType);
8676 Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH);
8677 Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum,
8678 DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1));
8679 } else {
8680 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH);
8681 SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT);
8682 // If the boolean for the target is 0 or 1, we can add the setcc result
8683 // directly.
8684 if (getBooleanContents(HiLoVT) ==
8686 Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT);
8687 else
8688 Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT),
8689 DAG.getConstant(0, dl, HiLoVT));
8690 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
8691 }
8692 } else {
8693 // Otherwise split into multple chunks and add them together. We chose
8694 // BestChunkWidth so that the sum will not overflow.
8695 SDValue Mask = DAG.getConstant(
8696 APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
8697
8698 for (unsigned I = 0; I < BitWidth - TrailingZeros; I += BestChunkWidth) {
8699 // If there were trailing zeros in the divisor, increase the shift amount.
8700 unsigned Shift = I + TrailingZeros;
8701 SDValue Chunk;
8702 if (Shift == 0)
8703 Chunk = LL;
8704 else if (Shift >= HBitWidth)
8705 Chunk = DAG.getNode(
8706 ISD::SRL, dl, HiLoVT, LH,
8707 DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, dl));
8708 else
8709 Chunk = GetFSHR(LL, LH, Shift);
8710 // If we're on the last chunk, we don't need an AND.
8711 if (I + BestChunkWidth < BitWidth - TrailingZeros)
8712 Chunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
8713 if (!Sum) {
8714 Sum = Chunk;
8715 } else {
8716 // For Alternate, we need to subtract odd chunks.
8717 unsigned ChunkNum = I / BestChunkWidth;
8718 unsigned Opc = (Alternate && (ChunkNum % 2) != 0) ? ISD::SUB : ISD::ADD;
8719 Sum = DAG.getNode(Opc, dl, HiLoVT, Sum, Chunk);
8720 }
8721 }
8722
8723 // For Alternate, the sum may be negative, but we need a positive sum. We
8724 // can increase it by a multiple of the divisor to make it positive. For 3
8725 // chunks the largest negative value is -(2^BestChunkWidth - 1). For 4
8726 // chunks, it's 2*-(2^BestChunkWidth - 1). We know that 2^BestChunkWidth + 1
8727 // is a multiple of the divisor. Add that 1 or 2 times to make the sum
8728 // positive.
8729 if (Alternate) {
8730 unsigned NumChunks = divideCeil(BitWidth - TrailingZeros, BestChunkWidth);
8731 assert(NumChunks <= 4);
8732
8733 APInt Adjust = APInt::getOneBitSet(HBitWidth, BestChunkWidth);
8734 Adjust.setBit(0);
8735 // If there are 4 chunks, we need to adjust twice.
8736 if (NumChunks == 4)
8737 Adjust <<= 1;
8738 Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum,
8739 DAG.getConstant(Adjust, dl, HiLoVT));
8740 }
8741 }
8742
8743 // Perform a HiLoVT urem on the Sum using truncated divisor.
8744 SDValue RemL =
8745 DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
8746 DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT));
8747 SDValue RemH = DAG.getConstant(0, dl, HiLoVT);
8748
8749 if (Opcode != ISD::UREM) {
8750 // If we didn't shift LH/LR earlier, do it now.
8751 if (BestChunkWidth != HBitWidth)
8752 ShiftRight(LL, LH, TrailingZeros);
8753
8754 // Subtract the remainder from the shifted dividend.
8755 SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH);
8756 SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH);
8757
8758 Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem);
8759
8760 // Multiply by the multiplicative inverse of the divisor modulo
8761 // (1 << BitWidth).
8762 APInt MulFactor = Divisor.multiplicativeInverse();
8763
8764 SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend,
8765 DAG.getConstant(MulFactor, dl, VT));
8766
8767 // Split the quotient into low and high parts.
8768 SDValue QuotL, QuotH;
8769 std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT);
8770 Result.push_back(QuotL);
8771 Result.push_back(QuotH);
8772 }
8773
8774 if (Opcode != ISD::UDIV) {
8775 // If we shifted the input, shift the remainder left and add the bits we
8776 // shifted off the input.
8777 if (TrailingZeros) {
8778 if (TrailingZeros < HBitWidth) {
8779 // Shift RemH:RemL left by TrailingZeros.
8780 // RemH gets the high bits shifted out of RemL.
8781 RemH = DAG.getNode(
8782 ISD::SRL, dl, HiLoVT, RemL,
8783 DAG.getShiftAmountConstant(HBitWidth - TrailingZeros, HiLoVT, dl));
8784 RemL =
8785 DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
8786 DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
8787 // OR in the partial remainder.
8788 RemL = DAG.getNode(ISD::OR, dl, HiLoVT, RemL, PartialRemL,
8790 } else if (TrailingZeros == HBitWidth) {
8791 // Shift left by exactly HBitWidth: RemH becomes RemL, RemL becomes
8792 // PartialRemL.
8793 RemH = RemL;
8794 RemL = PartialRemL;
8795 } else {
8796 // Shift left by more than HBitWidth.
8797 RemH = DAG.getNode(
8798 ISD::SHL, dl, HiLoVT, RemL,
8799 DAG.getShiftAmountConstant(TrailingZeros - HBitWidth, HiLoVT, dl));
8800 RemH = DAG.getNode(ISD::OR, dl, HiLoVT, RemH, PartialRemH,
8802 RemL = PartialRemL;
8803 }
8804 }
8805 Result.push_back(RemL);
8806 Result.push_back(RemH);
8807 }
8808
8809 return true;
8810}
8811
8812bool TargetLowering::expandUDIVREMByConstantViaUMulHiMagic(
8813 SDNode *N, const APInt &Divisor, SmallVectorImpl<SDValue> &Result,
8814 EVT HiLoVT, SelectionDAG &DAG, SDValue LL, SDValue LH) const {
8815
8816 SDValue N0 = N->getOperand(0);
8817 EVT VT = N0->getValueType(0);
8818 SDLoc DL{N};
8819
8820 assert(!Divisor.isOne() && "Magic algorithm does not work for division by 1");
8821
8822 // This helper creates a MUL_LOHI of the pair (LL, LH) by a constant.
8823 auto MakeMUL_LOHIByConst = [&](unsigned Opc, SDValue LL, SDValue LH,
8824 const APInt &Const,
8825 SmallVectorImpl<SDValue> &Result) {
8826 SDValue LHS = DAG.getNode(ISD::BUILD_PAIR, DL, VT, LL, LH);
8827 SDValue RHS = DAG.getConstant(Const, DL, VT);
8828 auto [RL, RH] = DAG.SplitScalar(RHS, DL, HiLoVT, HiLoVT);
8829 return expandMUL_LOHI(Opc, VT, DL, LHS, RHS, Result, HiLoVT, DAG,
8831 LL, LH, RL, RH);
8832 };
8833
8834 // This helper creates an ADD/SUB of the pairs (LL, LH) and (RL, RH).
8835 auto MakeAddSubLong = [&](unsigned Opc, SDValue LL, SDValue LH, SDValue RL,
8836 SDValue RH) {
8837 SDValue AddSubNode =
8839 DAG.getVTList(HiLoVT, MVT::i1), LL, RL);
8840 SDValue OutL = AddSubNode.getValue(0);
8841 SDValue Overflow = AddSubNode.getValue(1);
8842 SDValue AddSubWithOverflow =
8844 DAG.getVTList(HiLoVT, MVT::i1), LH, RH, Overflow);
8845 SDValue OutH = AddSubWithOverflow.getValue(0);
8846 return std::make_pair(OutL, OutH);
8847 };
8848
8849 // This helper creates a SRL of the pair (LL, LH) by Shift.
8850 auto MakeSRLLong = [&](SDValue LL, SDValue LH, unsigned Shift) {
8851 unsigned HBitWidth = HiLoVT.getScalarSizeInBits();
8852 if (Shift < HBitWidth) {
8853 SDValue ShAmt = DAG.getShiftAmountConstant(Shift, HiLoVT, DL);
8854 SDValue ResL = DAG.getNode(ISD::FSHR, DL, HiLoVT, LH, LL, ShAmt);
8855 SDValue ResH = DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt);
8856 return std::make_pair(ResL, ResH);
8857 }
8858 SDValue Zero = DAG.getConstant(0, DL, HiLoVT);
8859 if (Shift == HBitWidth)
8860 return std::make_pair(LH, Zero);
8861 assert(Shift - HBitWidth < HBitWidth &&
8862 "We shouldn't generate an undefined shift");
8863 SDValue ShAmt = DAG.getShiftAmountConstant(Shift - HBitWidth, HiLoVT, DL);
8864 return std::make_pair(DAG.getNode(ISD::SRL, DL, HiLoVT, LH, ShAmt), Zero);
8865 };
8866
8867 // Knowledge of leading zeros may help to reduce the multiplier.
8868 unsigned KnownLeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
8869
8870 UnsignedDivisionByConstantInfo Magics = UnsignedDivisionByConstantInfo::get(
8871 Divisor, std::min(KnownLeadingZeros, Divisor.countl_zero()));
8872
8873 assert(!LL == !LH && "Expected both input halves or no input halves!");
8874 if (!LL)
8875 std::tie(LL, LH) = DAG.SplitScalar(N0, DL, HiLoVT, HiLoVT);
8876 SDValue QL = LL;
8877 SDValue QH = LH;
8878 if (Magics.PreShift != 0)
8879 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PreShift);
8880
8881 SmallVector<SDValue, 4> UMulResult;
8882 if (!MakeMUL_LOHIByConst(ISD::UMUL_LOHI, QL, QH, Magics.Magic, UMulResult))
8883 return false;
8884
8885 QL = UMulResult[2];
8886 QH = UMulResult[3];
8887
8888 if (Magics.IsAdd) {
8889 auto [NPQL, NPQH] = MakeAddSubLong(ISD::SUB, LL, LH, QL, QH);
8890 std::tie(NPQL, NPQH) = MakeSRLLong(NPQL, NPQH, 1);
8891 std::tie(QL, QH) = MakeAddSubLong(ISD::ADD, NPQL, NPQH, QL, QH);
8892 }
8893
8894 if (Magics.PostShift != 0)
8895 std::tie(QL, QH) = MakeSRLLong(QL, QH, Magics.PostShift);
8896
8897 unsigned Opcode = N->getOpcode();
8898 if (Opcode != ISD::UREM) {
8899 Result.push_back(QL);
8900 Result.push_back(QH);
8901 }
8902
8903 if (Opcode != ISD::UDIV) {
8904 SmallVector<SDValue, 2> MulResult;
8905 if (!MakeMUL_LOHIByConst(ISD::MUL, QL, QH, Divisor, MulResult))
8906 return false;
8907
8908 assert(MulResult.size() == 2);
8909
8910 auto [RemL, RemH] =
8911 MakeAddSubLong(ISD::SUB, LL, LH, MulResult[0], MulResult[1]);
8912
8913 Result.push_back(RemL);
8914 Result.push_back(RemH);
8915 }
8916
8917 return true;
8918}
8919
8922 EVT HiLoVT, SelectionDAG &DAG,
8923 SDValue LL, SDValue LH) const {
8924 unsigned Opcode = N->getOpcode();
8925
8926 // TODO: Support signed division/remainder.
8927 if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM)
8928 return false;
8929 assert(
8930 (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) &&
8931 "Unexpected opcode");
8932
8933 auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1));
8934 if (!CN)
8935 return false;
8936
8937 APInt Divisor = CN->getAPIntValue();
8938
8939 // The generated half-width UREM is normally optimized using high multiply.
8940 // If the wide UREM libcall is unavailable, a legal or custom half-width
8941 // UDIVREM can lower it instead.
8942 bool CanDecomposeUREMWithoutMulHi =
8943 Opcode == ISD::UREM &&
8944 getLibcallImpl(RTLIB::getUREM(N->getValueType(0))) ==
8945 RTLIB::Unsupported &&
8947 if (!CanDecomposeUREMWithoutMulHi &&
8950 return false;
8951
8952 // Prefer the smaller libcall when one is available.
8953 if (DAG.shouldOptForSize() && !CanDecomposeUREMWithoutMulHi)
8954 return false;
8955
8956 // Early out for 0 or 1 divisors.
8957 if (Divisor.ule(1))
8958 return false;
8959
8960 if (expandUDIVREMByConstantViaUREMDecomposition(N, Divisor, Result, HiLoVT,
8961 DAG, LL, LH))
8962 return true;
8963
8964 if (expandUDIVREMByConstantViaUMulHiMagic(N, Divisor, Result, HiLoVT, DAG, LL,
8965 LH))
8966 return true;
8967
8968 return false;
8969}
8970
8971// Check that (every element of) Z is undef or not an exact multiple of BW.
8972static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
8974 Z,
8975 [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
8976 /*AllowUndefs=*/true, /*AllowTruncation=*/true);
8977}
8978
8980 SelectionDAG &DAG) const {
8981 EVT VT = Node->getValueType(0);
8982
8983 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
8987 return SDValue();
8988
8989 SDValue X = Node->getOperand(0);
8990 SDValue Y = Node->getOperand(1);
8991 SDValue Z = Node->getOperand(2);
8992
8993 unsigned BW = VT.getScalarSizeInBits();
8994 bool IsFSHL = Node->getOpcode() == ISD::FSHL;
8995 SDLoc DL(SDValue(Node, 0));
8996
8997 EVT ShVT = Z.getValueType();
8998
8999 // If a funnel shift in the other direction is more supported, use it.
9000 unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
9001 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
9002 isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
9003 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
9004 // fshl X, Y, Z -> fshr X, Y, -Z
9005 // fshr X, Y, Z -> fshl X, Y, -Z
9006 Z = DAG.getNegative(Z, DL, ShVT);
9007 } else {
9008 // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
9009 // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
9010 SDValue One = DAG.getConstant(1, DL, ShVT);
9011 if (IsFSHL) {
9012 Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
9013 X = DAG.getNode(ISD::SRL, DL, VT, X, One);
9014 } else {
9015 X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
9016 Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
9017 }
9018 Z = DAG.getNOT(DL, Z, ShVT);
9019 }
9020 return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
9021 }
9022
9023 SDValue ShX, ShY;
9024 SDValue ShAmt, InvShAmt;
9025 if (isNonZeroModBitWidthOrUndef(Z, BW)) {
9026 // fshl: X << C | Y >> (BW - C)
9027 // fshr: X << (BW - C) | Y >> C
9028 // where C = Z % BW is not zero
9029 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
9030 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
9031 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
9032 ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
9033 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
9034 } else {
9035 // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
9036 // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
9037 SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
9038 if (isPowerOf2_32(BW)) {
9039 // Z % BW -> Z & (BW - 1)
9040 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
9041 // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
9042 InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
9043 } else {
9044 SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
9045 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
9046 InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
9047 }
9048
9049 SDValue One = DAG.getConstant(1, DL, ShVT);
9050 if (IsFSHL) {
9051 ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
9052 SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
9053 ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
9054 } else {
9055 SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
9056 ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
9057 ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
9058 }
9059 }
9060 return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
9061}
9062
9063// TODO: Merge with expandFunnelShift.
9065 SelectionDAG &DAG) const {
9066 EVT VT = Node->getValueType(0);
9067 unsigned EltSizeInBits = VT.getScalarSizeInBits();
9068 bool IsLeft = Node->getOpcode() == ISD::ROTL;
9069 SDValue Op0 = Node->getOperand(0);
9070 SDValue Op1 = Node->getOperand(1);
9071 SDLoc DL(SDValue(Node, 0));
9072
9073 EVT ShVT = Op1.getValueType();
9074 SDValue Zero = DAG.getConstant(0, DL, ShVT);
9075
9076 // If a rotate in the other direction is more supported, use it.
9077 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
9078 if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
9079 isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
9080 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
9081 return DAG.getNode(RevRot, DL, VT, Op0, Sub);
9082 }
9083
9084 if (!AllowVectorOps && VT.isVector() &&
9090 return SDValue();
9091
9092 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
9093 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
9094 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
9095 SDValue ShVal;
9096 SDValue HsVal;
9097 if (isPowerOf2_32(EltSizeInBits)) {
9098 // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
9099 // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
9100 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
9101 SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
9102 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
9103 SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
9104 HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
9105 } else {
9106 // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
9107 // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
9108 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
9109 SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
9110 ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
9111 SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
9112 SDValue One = DAG.getConstant(1, DL, ShVT);
9113 HsVal =
9114 DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
9115 }
9116 return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
9117}
9118
9119/// Check if CLMUL on VT can eventually reach a type with legal CLMUL through
9120/// a chain of halving decompositions (halving element width) and/or vector
9121/// widening (doubling element count). This guides expansion strategy selection:
9122/// if true, the halving/widening path produces better code than bit-by-bit.
9123///
9124/// HalveDepth tracks halving steps only (each creates ~4x more operations).
9125/// Widening steps are cheap (O(1) pad/extract) and don't count.
9126/// Limiting halvings to 2 prevents exponential blowup:
9127/// 1 halving: ~4 sub-CLMULs (good, e.g. v8i16 -> v8i8)
9128/// 2 halvings: ~16 sub-CLMULs (acceptable, e.g. v4i32 -> v4i16 -> v8i8)
9129/// 3 halvings: ~64 sub-CLMULs (worse than bit-by-bit expansion)
9131 EVT VT, unsigned HalveDepth = 0,
9132 unsigned TotalDepth = 0) {
9133 if (HalveDepth > 2 || TotalDepth > 8 || !VT.isFixedLengthVector())
9134 return false;
9135 if (TLI.isOperationLegalOrCustom(ISD::CLMUL, VT))
9136 return true;
9137 if (!TLI.isTypeLegal(VT))
9138 return false;
9139
9140 unsigned BW = VT.getScalarSizeInBits();
9141
9142 // Halve: halve element width, same element count.
9143 // This is the expensive step -- each halving creates ~4x more operations.
9144 if (BW % 2 == 0) {
9145 EVT HalfEltVT = EVT::getIntegerVT(Ctx, BW / 2);
9146 EVT HalfVT = VT.changeVectorElementType(Ctx, HalfEltVT);
9147 if (TLI.isTypeLegal(HalfVT) &&
9148 canNarrowCLMULToLegal(TLI, Ctx, HalfVT, HalveDepth + 1, TotalDepth + 1))
9149 return true;
9150 }
9151
9152 // Widen: double element count (fixed-width vectors only).
9153 // This is cheap -- just INSERT_SUBVECTOR + EXTRACT_SUBVECTOR.
9154 EVT WideVT = VT.getDoubleNumVectorElementsVT(Ctx);
9155 if (TLI.isTypeLegal(WideVT) &&
9156 canNarrowCLMULToLegal(TLI, Ctx, WideVT, HalveDepth, TotalDepth + 1))
9157 return true;
9158
9159 return false;
9160}
9161
9163 SDLoc DL(Node);
9164 EVT VT = Node->getValueType(0);
9165 SDValue X = Node->getOperand(0);
9166 SDValue Y = Node->getOperand(1);
9167 unsigned BW = VT.getScalarSizeInBits();
9168 unsigned Opcode = Node->getOpcode();
9169 LLVMContext &Ctx = *DAG.getContext();
9170
9171 switch (Opcode) {
9172 case ISD::CLMUL: {
9173 // For vector types, try decomposition strategies that leverage legal
9174 // CLMUL on narrower or wider element types, avoiding the expensive
9175 // bit-by-bit expansion.
9176 if (VT.isVector()) {
9177 // Strategy 1: Halving decomposition to half-element-width CLMUL.
9178 // Applies ExpandIntRes_CLMUL's identity element-wise:
9179 // CLMUL(X, Y) = (Hi << HalfBW) | Lo
9180 // where:
9181 // Lo = CLMUL(XLo, YLo)
9182 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9183 unsigned HalfBW = BW / 2;
9184 if (BW % 2 == 0) {
9185 EVT HalfEltVT = EVT::getIntegerVT(Ctx, HalfBW);
9186 EVT HalfVT =
9187 EVT::getVectorVT(Ctx, HalfEltVT, VT.getVectorElementCount());
9188 if (isTypeLegal(HalfVT) && canNarrowCLMULToLegal(*this, Ctx, HalfVT,
9189 /*HalveDepth=*/1)) {
9190 SDValue ShAmt = DAG.getShiftAmountConstant(HalfBW, VT, DL);
9191
9192 // Extract low and high halves of each element.
9193 SDValue XLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, X);
9194 SDValue XHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9195 DAG.getNode(ISD::SRL, DL, VT, X, ShAmt));
9196 SDValue YLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, Y);
9197 SDValue YHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT,
9198 DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt));
9199
9200 // Lo = CLMUL(XLo, YLo)
9201 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YLo);
9202
9203 // Hi = CLMULH(XLo, YLo) ^ CLMUL(XLo, YHi) ^ CLMUL(XHi, YLo)
9204 SDValue LoH = DAG.getNode(ISD::CLMULH, DL, HalfVT, XLo, YLo);
9205 SDValue Cross1 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XLo, YHi);
9206 SDValue Cross2 = DAG.getNode(ISD::CLMUL, DL, HalfVT, XHi, YLo);
9207 SDValue Cross = DAG.getNode(ISD::XOR, DL, HalfVT, Cross1, Cross2);
9208 SDValue Hi = DAG.getNode(ISD::XOR, DL, HalfVT, LoH, Cross);
9209
9210 // Reassemble: Result = ZExt(Lo) | (AnyExt(Hi) << HalfBW)
9211 SDValue LoExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo);
9212 SDValue HiExt = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Hi);
9213 SDValue HiShifted = DAG.getNode(ISD::SHL, DL, VT, HiExt, ShAmt);
9214 return DAG.getNode(ISD::OR, DL, VT, LoExt, HiShifted);
9215 }
9216 }
9217
9218 // Strategy 2: Promote to double-element-width CLMUL.
9219 // CLMUL(X, Y) = Trunc(CLMUL(AnyExt(X), AnyExt(Y)))
9220 {
9221 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9222 if (isTypeLegal(ExtVT) && isOperationLegalOrCustom(ISD::CLMUL, ExtVT)) {
9223 // If CLMUL on ExtVT is Custom (not Legal), the target may
9224 // scalarize it, costing O(NumElements) scalar ops. The bit-by-bit
9225 // fallback costs O(BW) vectorized iterations. Only widen when
9226 // element count is small enough that scalarization is cheaper.
9227 unsigned NumElts = VT.getVectorMinNumElements();
9228 if (isOperationLegal(ISD::CLMUL, ExtVT) || NumElts < BW) {
9229 SDValue XExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, X);
9230 SDValue YExt = DAG.getNode(ISD::ANY_EXTEND, DL, ExtVT, Y);
9231 SDValue Mul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9232 return DAG.getNode(ISD::TRUNCATE, DL, VT, Mul);
9233 }
9234 }
9235 }
9236
9237 // Strategy 3: Widen element count (pad with undef, do CLMUL on wider
9238 // vector, extract lower result). CLMUL is element-wise, so upper
9239 // (undef) lanes don't affect the lower results.
9240 // e.g. v4i16 => pad to v8i16 => halve to v8i8 PMUL => extract v4i16.
9241 if (auto EC = VT.getVectorElementCount(); EC.isFixed()) {
9242 EVT WideVT = EVT::getVectorVT(Ctx, VT.getVectorElementType(), EC * 2);
9243 if (isTypeLegal(WideVT) && canNarrowCLMULToLegal(*this, Ctx, WideVT)) {
9244 SDValue Undef = DAG.getUNDEF(WideVT);
9245 SDValue XWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9246 X, DAG.getVectorIdxConstant(0, DL));
9247 SDValue YWide = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, Undef,
9248 Y, DAG.getVectorIdxConstant(0, DL));
9249 SDValue WideRes = DAG.getNode(ISD::CLMUL, DL, WideVT, XWide, YWide);
9250 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WideRes,
9251 DAG.getVectorIdxConstant(0, DL));
9252 }
9253 }
9254 }
9255
9256 // Special case: clmul(X, Y) where Y is a known constant (splat) that forms
9257 // a contiguous block of trailing ones whose length N is a power of two
9258 // (e.g. i8 0xFF, i8 0x0F, ...) or equal to the operand width. In this
9259 // special case, clmul(X, Y) is equivalent to a "parallel prefix XOR" or
9260 // "bitwise parity" operation on X.
9261 //
9262 // Note: This special currently dose NOT apply when the mask is neither a
9263 // power of two nor equal to the operand width because the loop inside
9264 // behaves as if the mask was bit-ceiled, and "undoing" the XOR with parts
9265 // of that CLMUL is a recursive problem (e.g. CLMUL with a 20-bit mask
9266 // requires correction XOR with CLMUL with 12-bit mask).
9267 if (auto *C = isConstOrConstSplat(Y, /*AllowUndefs=*/true)) {
9268 const APInt &YVal = C->getAPIntValue();
9269 unsigned N = YVal.countr_one();
9270 if (YVal.isAllOnes() || (YVal.isMask() && isPowerOf2_32(N))) {
9271 SDValue R = X;
9272 for (unsigned I = 1; I < N; I <<= 1) {
9273 SDValue ShAmt = DAG.getShiftAmountConstant(I, VT, DL);
9274 SDValue Shifted = DAG.getNode(ISD::SHL, DL, VT, R, ShAmt);
9275 R = DAG.getNode(ISD::XOR, DL, VT, R, Shifted);
9276 }
9277 return R;
9278 }
9279 }
9280
9281 // NOTE: If you change this expansion, please update the cost model
9282 // calculation in BasicTTIImpl::getTypeBasedIntrinsicInstrCost for
9283 // Intrinsic::clmul.
9284
9285 // Strategy 4: multiplication with holes.
9286 //
9287 // Uses "holes" (sequences of zeroes) to avoid carry spilling. When carries
9288 // do occur, they wind up in a "hole" and are subsequently masked out of the
9289 // result.
9290 //
9291 // https://www.bearssl.org/constanttime.html#ghash-for-gcm describes this
9292 // approach.
9293
9294 // Stride S handles operands up to S·2^S bits using S² multiplies.
9295 //
9296 // * BW <= 8 uses S = 2 (holes of 1 bit)
9297 // * BW <= 24 uses S = 3 (holes of 2 bits)
9298 // * BW <= 64 uses S = 4 (holes of 3 bits)
9299 // * BW <= 160 uses S = 5 (holes of 4 bits)
9300 // * BW <= 384 uses S = 6 (holes of 5 bits)
9301 //
9302 // We distribute the BW bits over S phases:
9303 //
9304 // phase 0 keeps bits: 0, S, 2S, ...
9305 // phase 1 keeps bits: 1, S + 1, 2S + 1, ...
9306 // ...
9307 //
9308 // Each phase has up to n = ceil(BW / S) bits set, and the holes are S-1
9309 // bits wide.
9310 //
9311 // Take BW = 4, S = 2, n = 2. The worst case is a fully populated phase (all
9312 // non-hole bits are set to 1) multiplied by itself, 0b0101 * 0b0101. Each
9313 // set bit of one operand shifts a copy of the other, and we add the copies:
9314 //
9315 // col: 4 3 2 1 0
9316 // 0b0101 << 0: 0 0 1 0 1
9317 // 0b0101 << 2: 1 0 1 0 0
9318 // ----------------- +
9319 // count: 1 0 2 0 1
9320 //
9321 // Counting the number of one-bits in each column gives a triangle: the
9322 // counts climb 1, 2, ..., n and back down (here 1, 2, 1 across the data
9323 // columns). So a column holds at most n one-bits, and that maximum n is
9324 // reached in only one column: the peak. Every other column holds at most n
9325 // - 1 one-bits.
9326 //
9327 // A stack of one-bits in a column turns into carries: column 2 above really
9328 // stores the value 1 + 1 = 2 = n. A column spans S bits, its kept bit
9329 // plus S-1 hole bits, and the count is written from the kept bit upward,
9330 // so any count <= 2^S - 1 stays within the column and never interferes with
9331 // the next data bit S positions up. Every non-peak column holds at most n -
9332 // 1, so they all fit as soon as n - 1 <= 2^S - 1.
9333 //
9334 // That leaves only the peak column. Because both operands set all data
9335 // bits, the triangle peaks at the top of the word at the highest data bit
9336 // still inside BW. Here the count reaches exactly n = 2^S and overflows.
9337 // But its carry lands at bit n*S >= BW, off the top, where it (and the
9338 // whole descending half of the triangle) is truncated.
9339 //
9340 // Hence the holes suffice exactly when n = ceil(BW / S) <= 2^S, i.e. BW <=
9341 // S*2^S.
9342 //
9343 // Here we find the smallest S that satisfies this inequality.
9344 unsigned S = 1;
9345 while (S < 32 && divideCeil(BW, S) > (1u << S))
9346 ++S;
9347
9348 // The "multiplication with holes" expansion emits S*S MULs, 3*S ANDs,
9349 // S*(S-1) XORs and S-1 ORs.
9350 unsigned HolesCost = S * S + 3 * S + S * (S - 1) + (S - 1);
9351
9352 // Estimate the cost of the naive algorithm.
9353 KnownBits KnownY = DAG.computeKnownBits(Y);
9354 unsigned NaiveCost = 0;
9355 for (unsigned I = 0; I < BW; ++I) {
9356 // The iteration folds away entirely and is free.
9357 if (KnownY.Zero[I])
9358 continue;
9359
9360 // On targets with a fast bit test instruction more instructions are used
9361 // to not need a (potentially expensive) multiplication. See also below.
9362 if (hasBitTest(Y, DAG.getShiftAmountConstant(I, VT, DL))) {
9363 // AND + SETCC + SHL + SELECT + XOR.
9364 NaiveCost += 5;
9365 } else {
9366 // AND + MUL + XOR.
9367 NaiveCost += 3;
9368 }
9369 }
9370
9371 // Only use multiplication with holes when it is cheaper, else use the naive
9372 // fallback below.
9373 if (HolesCost < NaiveCost &&
9375
9376 // Set a bit every S positions, e.g. for S = 4 this is equivalent to
9377 // 0b...00010001...0001.
9378 APInt MaskVal = APInt::getSplat(BW, APInt(S, 1));
9379
9380 // Create versions of X and Y that keep only the I-th bit of each S-bit
9381 // slice.
9382 SmallVector<SDValue, 4> M(S), Xp(S), Yp(S);
9383 for (unsigned I = 0; I < S; ++I) {
9384 M[I] = DAG.getConstant(MaskVal.shl(I), DL, VT);
9385 Xp[I] = DAG.getNode(ISD::AND, DL, VT, X, M[I]);
9386 Yp[I] = DAG.getNode(ISD::AND, DL, VT, Y, M[I]);
9387 }
9388
9389 // Codegens these expressions (S*S multiplications), e.g. for S=4:
9390 //
9391 // z0 = (x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1);
9392 // z1 = (x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2);
9393 // z2 = (x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3);
9394 // z3 = (x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0);
9395 SDValue Res = DAG.getConstant(0, DL, VT);
9396 for (unsigned I = 0; I < S; ++I) {
9397 SDValue Zi = DAG.getConstant(0, DL, VT);
9398 for (unsigned J = 0; J < S; ++J) {
9399 unsigned K = (I + S - J) % S;
9400 SDValue P = DAG.getNode(ISD::MUL, DL, VT, Xp[J], Yp[K]);
9401 Zi = DAG.getNode(ISD::XOR, DL, VT, Zi, P);
9402 }
9403
9404 // Keep only the bits belonging to this iteration, and bitwise or it all
9405 // together.
9406 Zi = DAG.getNode(ISD::AND, DL, VT, Zi, M[I]);
9407 Res = DAG.getNode(ISD::OR, DL, VT, Res, Zi, SDNodeFlags::Disjoint);
9408 }
9409 return Res;
9410 }
9411
9412 // Strategy 5: the naive fallback.
9413 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
9414
9415 SDValue Res = DAG.getConstant(0, DL, VT);
9416 for (unsigned I = 0; I < BW; ++I) {
9417 SDValue ShiftAmt = DAG.getShiftAmountConstant(I, VT, DL);
9418 SDValue Mask = DAG.getConstant(APInt::getOneBitSet(BW, I), DL, VT);
9419 SDValue YMasked = DAG.getNode(ISD::AND, DL, VT, Y, Mask);
9420
9421 // For targets with a fast bit test instruction (e.g., x86 BT) or without
9422 // multiply, use a shift-based expansion to avoid expensive MUL
9423 // instructions.
9424 SDValue Part;
9425 if (!hasBitTest(Y, ShiftAmt) &&
9428 Part = DAG.getNode(ISD::MUL, DL, VT, X, YMasked);
9429 } else {
9430 // Canonical bit test: (Y & (1 << I)) != 0
9431 SDValue Zero = DAG.getConstant(0, DL, VT);
9432 SDValue Cond = DAG.getSetCC(DL, SetCCVT, YMasked, Zero, ISD::SETEQ);
9433 SDValue XShifted = DAG.getNode(ISD::SHL, DL, VT, X, ShiftAmt);
9434 Part = DAG.getSelect(DL, VT, Cond, Zero, XShifted);
9435 }
9436 Res = DAG.getNode(ISD::XOR, DL, VT, Res, Part);
9437 }
9438 return Res;
9439 }
9440 case ISD::CLMULR:
9441 // If we have CLMUL/CLMULH, merge the shifted results to form CLMULR.
9444 SDValue Lo = DAG.getNode(ISD::CLMUL, DL, VT, X, Y);
9445 SDValue Hi = DAG.getNode(ISD::CLMULH, DL, VT, X, Y);
9446 Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
9447 DAG.getShiftAmountConstant(BW - 1, VT, DL));
9448 Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
9449 DAG.getShiftAmountConstant(1, VT, DL));
9450 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
9451 }
9452 [[fallthrough]];
9453 case ISD::CLMULH: {
9454 EVT ExtVT = VT.widenIntegerElementType(Ctx);
9455 // Use bitreverse-based lowering (CLMULR/H = rev(CLMUL(rev,rev)) >> S)
9456 // when any of these hold:
9457 // (a) ZERO_EXTEND to ExtVT or SRL on ExtVT isn't legal.
9458 // (b) CLMUL is legal on VT but not on ExtVT (e.g. v8i8 on AArch64).
9459 // (c) CLMUL on ExtVT isn't legal, but CLMUL on VT can be efficiently
9460 // expanded via halving/widening to reach legal CLMUL. The bitreverse
9461 // path creates CLMUL(VT) which will be expanded efficiently. The
9462 // promote path would create CLMUL(ExtVT) => halving => CLMULH(VT),
9463 // causing a cycle.
9464 // Note: when CLMUL is legal on ExtVT, the zext => CLMUL(ExtVT) => shift
9465 // => trunc path is preferred over the bitreverse path, as it avoids the
9466 // cost of 3 bitreverse operations.
9471 canNarrowCLMULToLegal(*this, Ctx, VT)))) {
9472 SDValue XRev = DAG.getNode(ISD::BITREVERSE, DL, VT, X);
9473 SDValue YRev = DAG.getNode(ISD::BITREVERSE, DL, VT, Y);
9474 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, VT, XRev, YRev);
9475 SDValue Res = DAG.getNode(ISD::BITREVERSE, DL, VT, ClMul);
9476 if (Opcode == ISD::CLMULH)
9477 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
9478 DAG.getShiftAmountConstant(1, VT, DL));
9479 return Res;
9480 }
9481 SDValue XExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, X);
9482 SDValue YExt = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVT, Y);
9483 SDValue ClMul = DAG.getNode(ISD::CLMUL, DL, ExtVT, XExt, YExt);
9484 unsigned ShAmt = Opcode == ISD::CLMULR ? BW - 1 : BW;
9485 SDValue HiBits = DAG.getNode(ISD::SRL, DL, ExtVT, ClMul,
9486 DAG.getShiftAmountConstant(ShAmt, ExtVT, DL));
9487 return DAG.getNode(ISD::TRUNCATE, DL, VT, HiBits);
9488 }
9489 }
9490 llvm_unreachable("Expected CLMUL, CLMULR, or CLMULH");
9491}
9492
9495 SDLoc dl(Node);
9496 SDValue Val = Node->getOperand(0);
9497 EVT VT = Val.getValueType();
9498 SDNodeFlags Flags = Node->getFlags();
9499
9500 SDValue IntPart = DAG.getNode(ISD::FTRUNC, dl, VT, Val, Flags);
9501 SDValue FracPart = DAG.getNode(ISD::FSUB, dl, VT, Val, IntPart, Flags);
9502
9503 SDValue FracToUse = FracPart;
9504 if (!Flags.hasNoInfs()) {
9505 SDValue Abs = DAG.getNode(ISD::FABS, dl, VT, Val, Flags);
9506 SDValue Inf =
9508 EVT SetCCVT =
9509 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9510 SDValue IsInf = DAG.getSetCC(dl, SetCCVT, Abs, Inf, ISD::SETOEQ);
9511 SDValue Zero = DAG.getConstantFP(0.0, dl, VT);
9512 FracToUse = DAG.getSelect(dl, VT, IsInf, Zero, FracPart);
9513 }
9514
9515 SDValue ResultFrac =
9516 DAG.getNode(ISD::FCOPYSIGN, dl, VT, FracToUse, Val, Flags);
9517 Results.push_back(ResultFrac);
9518 Results.push_back(IntPart);
9519 return true;
9520}
9521
9523 SDLoc DL(Node);
9524 EVT VT = Node->getValueType(0);
9525 SDValue Val = Node->getOperand(0);
9526 SDValue Msk = Node->getOperand(1);
9527 unsigned BW = VT.getScalarSizeInBits();
9528
9529 // Just scalarize if scalar PEXT is legal
9531 return DAG.UnrollVectorOp(Node);
9532
9533 // Hacker's Delight §7-4: Compress, or Generalized Extract
9534 SDValue X = DAG.getNode(ISD::AND, DL, VT, Val, Msk);
9535 SDValue M = Msk;
9536 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9537 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, M, VT), One);
9538
9539 // Repeatedly compute which bits would shift to the right by an odd amount,
9540 // shift all such bits in parallel using a mask, and double the shift amount.
9541 for (unsigned I = 1; I < BW; I *= 2) {
9542 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9543 SDValue Mp =
9544 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9545 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, M);
9546 SDValue ShiftI = DAG.getShiftAmountConstant(I, VT, DL);
9547 SDValue MvS = DAG.getNode(ISD::SRL, DL, VT, Mv, ShiftI);
9548 M = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, M, Mv), MvS,
9550 SDValue T = DAG.getNode(ISD::AND, DL, VT, X, Mv);
9551 SDValue TS = DAG.getNode(ISD::SRL, DL, VT, T, ShiftI);
9552 X = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ISD::XOR, DL, VT, X, T), TS,
9554 if (I * 2 < BW)
9555 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9556 }
9557
9558 return X;
9559}
9560
9562 SDLoc DL(Node);
9563 EVT VT = Node->getValueType(0);
9564 SDValue Val = Node->getOperand(0);
9565 SDValue Msk = Node->getOperand(1);
9566 unsigned BW = VT.getScalarSizeInBits();
9567
9568 // Just scalarize if scalar PDEP is legal
9570 return DAG.UnrollVectorOp(Node);
9571
9572 // Hacker's Delight §7-5: Expand, or Generalized Insert.
9573 unsigned LogBW = Log2_32_Ceil(BW);
9574 SmallVector<SDValue, 8> MvArray(LogBW);
9575 SDValue One = DAG.getShiftAmountConstant(1, VT, DL);
9576 SDValue Mc = Msk;
9577 SDValue Mk = DAG.getNode(ISD::SHL, DL, VT, DAG.getNOT(DL, Msk, VT), One);
9578
9579 // First pass: compute move masks for each power of two that a bit moves by.
9580 for (unsigned S = 0; S < LogBW; ++S) {
9581 unsigned ShiftS = 1u << S;
9582 // This expands the "parallel prefix" operation to clmul(Mk, ~0).
9583 SDValue Mp =
9584 DAG.getNode(ISD::CLMUL, DL, VT, Mk, DAG.getAllOnesConstant(DL, VT));
9585 SDValue Mv = DAG.getNode(ISD::AND, DL, VT, Mp, Mc);
9586 MvArray[S] = Mv;
9587 if (S + 1 < LogBW) {
9588 SDValue McXorMv = DAG.getNode(ISD::XOR, DL, VT, Mc, Mv);
9589 SDValue MvShifted = DAG.getNode(
9590 ISD::SRL, DL, VT, Mv, DAG.getShiftAmountConstant(ShiftS, VT, DL));
9591 Mc = DAG.getNode(ISD::OR, DL, VT, McXorMv, MvShifted,
9593 Mk = DAG.getNode(ISD::AND, DL, VT, Mk, DAG.getNOT(DL, Mp, VT));
9594 }
9595 }
9596
9597 // Second pass: move bits by 32, 16, 8, 4, 2, 1, using masks, in parallel.
9598 // Each pass handles half the shift amount of the previous pass.
9599 SDValue X = Val;
9600 for (int S = (int)LogBW - 1; S >= 0; --S) {
9601 SDValue ShiftSv = DAG.getShiftAmountConstant(1ull << S, VT, DL);
9602 SDValue T = DAG.getNode(ISD::SHL, DL, VT, X, ShiftSv);
9603 SDValue UnshiftedBits =
9604 DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, MvArray[S], VT));
9605 SDValue ShiftedBits = DAG.getNode(ISD::AND, DL, VT, T, MvArray[S]);
9606 X = DAG.getNode(ISD::OR, DL, VT, UnshiftedBits, ShiftedBits,
9608 }
9609
9610 return DAG.getNode(ISD::AND, DL, VT, X, Msk);
9611}
9612
9614 SelectionDAG &DAG) const {
9615 assert(Node->getNumOperands() == 3 && "Not a double-shift!");
9616 EVT VT = Node->getValueType(0);
9617 unsigned VTBits = VT.getScalarSizeInBits();
9618 assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
9619
9620 bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
9621 bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
9622 SDValue ShOpLo = Node->getOperand(0);
9623 SDValue ShOpHi = Node->getOperand(1);
9624 SDValue ShAmt = Node->getOperand(2);
9625 EVT ShAmtVT = ShAmt.getValueType();
9626 EVT ShAmtCCVT =
9627 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
9628 SDLoc dl(Node);
9629
9630 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
9631 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
9632 // away during isel.
9633 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9634 DAG.getConstant(VTBits - 1, dl, ShAmtVT));
9635 SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9636 DAG.getConstant(VTBits - 1, dl, ShAmtVT))
9637 : DAG.getConstant(0, dl, VT);
9638
9639 SDValue Tmp2, Tmp3;
9640 if (IsSHL) {
9641 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
9642 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9643 } else {
9644 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
9645 Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9646 }
9647
9648 // If the shift amount is larger or equal than the width of a part we don't
9649 // use the result from the FSHL/FSHR. Insert a test and select the appropriate
9650 // values for large shift amounts.
9651 SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
9652 DAG.getConstant(VTBits, dl, ShAmtVT));
9653 SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
9654 DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
9655
9656 if (IsSHL) {
9657 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9658 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9659 } else {
9660 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
9661 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
9662 }
9663}
9664
9666 SelectionDAG &DAG) const {
9667 // This implements llvm.canonicalize.f* by multiplication with 1.0, as
9668 // suggested in
9669 // https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic.
9670 // It uses strict_fp operations even outside a strict_fp context in order
9671 // to guarantee that the canonicalization is not optimized away by later
9672 // passes. The result chain introduced by that is intentionally ignored
9673 // since no ordering requirement is intended here.
9674 EVT VT = Node->getValueType(0);
9675 SDLoc DL(Node);
9676 SDNodeFlags Flags = Node->getFlags();
9677 Flags.setNoFPExcept(true);
9678 SDValue One = DAG.getConstantFP(1.0, DL, VT);
9679 SDValue Mul =
9680 DAG.getNode(ISD::STRICT_FMUL, DL, {VT, MVT::Other},
9681 {DAG.getEntryNode(), Node->getOperand(0), One}, Flags);
9682 return Mul;
9683}
9684
9686 SelectionDAG &DAG) const {
9687 // Expand conversion from a native IEEE float type to an arbitrary FP format
9688 // returning the result as an integer using bit manipulation.
9689 EVT ResVT = Node->getValueType(0);
9690 SDLoc dl(Node);
9691
9692 SDValue FloatVal = Node->getOperand(0);
9693 const uint64_t SemEnum = Node->getConstantOperandVal(1);
9694 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
9695 const auto RoundMode =
9696 static_cast<RoundingMode>(Node->getConstantOperandVal(2));
9697 const bool Saturate = Node->getConstantOperandVal(3) != 0;
9698
9699 // Supported destination formats.
9700 switch (Sem) {
9707 break;
9708 default:
9709 DAG.getContext()->emitError("CONVERT_TO_ARBITRARY_FP: not implemented "
9710 "destination format (semantics enum " +
9711 Twine(SemEnum) + ")");
9712 return SDValue();
9713 }
9714
9715 // Supported rounding modes.
9716 switch (RoundMode) {
9722 break;
9723 default:
9724 DAG.getContext()->emitError(
9725 "CONVERT_TO_ARBITRARY_FP: unsupported rounding mode (enum " +
9726 Twine(static_cast<int>(RoundMode)) + ")");
9727 return SDValue();
9728 }
9729
9730 // Destination format parameters.
9731 const fltSemantics &DstSem = APFloatBase::EnumToSemantics(Sem);
9732 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
9733 const unsigned DstPrecision = APFloat::semanticsPrecision(DstSem);
9734 const unsigned DstMant = DstPrecision - 1;
9735 // Unsigned formats spend no bit on the sign.
9736 const bool DstHasSign = APFloat::semanticsHasSignedRepr(DstSem);
9737 const unsigned DstExpBits = DstBits - (DstHasSign ? 1 : 0) - DstMant;
9738 const int DstBias = 1 - APFloat::semanticsMinExponent(DstSem);
9739 const unsigned DstExpMax = (1U << DstExpBits) - 1;
9740 const uint64_t DstMantMask = (DstMant > 0) ? ((1ULL << DstMant) - 1) : 0;
9741 const fltNonfiniteBehavior DstNFBehavior = DstSem.nonFiniteBehavior;
9742 const fltNanEncoding DstNanEnc = DstSem.nanEncoding;
9743
9744 // Compute the maximum normal exponent for the destination format.
9745 const unsigned DstExpMaxNormal =
9746 DstNFBehavior == fltNonfiniteBehavior::IEEE754 ? DstExpMax - 1
9747 : DstExpMax;
9748
9749 // For NanOnly formats the max exponent field for finite values
9750 // is DstExpMax, but the encoding with exp = DstExpMax and
9751 // mant = all-ones is NaN. So DstExpMaxNormal = DstExpMax, but max
9752 // mantissa at that exponent is DstMantMask - 1 (if NanEnc == AllOnes) to
9753 // avoid the NaN encoding.
9754 uint64_t DstMaxMantAtMaxExp = DstMantMask;
9755 if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
9756 DstNanEnc == fltNanEncoding::AllOnes)
9757 DstMaxMantAtMaxExp = DstMantMask - 1;
9758
9759 // Source format parameters.
9760 EVT SrcVT = FloatVal.getValueType();
9761 const fltSemantics &SrcSem = SrcVT.getScalarType().getFltSemantics();
9762 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
9763 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
9764 const unsigned SrcMant = SrcPrecision - 1;
9765 const uint64_t SrcMantMask = (1ULL << SrcMant) - 1;
9766
9767 // Work in the source integer type. Match the destination shape so the
9768 // expansion stays vector when ResVT is a vector.
9769 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), SrcBits);
9770 EVT IntVT = ResVT.changeElementType(*DAG.getContext(), IntScalarVT);
9771 EVT SetCCVT =
9772 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
9773 EVT FPSetCCVT =
9774 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
9775
9776 SDValue Zero = DAG.getConstant(0, dl, IntVT);
9777 SDValue One = DAG.getConstant(1, dl, IntVT);
9778
9779 // Bitcast source float to integer to extract the sign bit.
9780 SDValue Src = DAG.getNode(ISD::BITCAST, dl, IntVT, FloatVal);
9781 SDValue SignBit =
9782 DAG.getNode(ISD::SRL, dl, IntVT, Src,
9783 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl));
9784
9785 // Classify the input.
9786 SDValue FPZero = DAG.getConstantFP(0.0, dl, SrcVT);
9787 SDValue FPInf = DAG.getConstantFP(APFloat::getInf(SrcSem), dl, SrcVT);
9788 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, SrcVT, FloatVal);
9789 SDValue IsNaN = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETUO);
9790 SDValue IsInf = DAG.getSetCC(dl, FPSetCCVT, AbsVal, FPInf, ISD::SETOEQ);
9791 SDValue IsZero = DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOEQ);
9792
9793 // Split into a normalized fraction and unbiased exponent. FFREXP normalizes
9794 // source denormals automatically. The result is unspecified for Inf/NaN, but
9795 // those inputs are detected above and override the final result.
9796 EVT FrexpExpScalarVT =
9798 EVT FrexpExpVT = SrcVT.changeElementType(*DAG.getContext(), FrexpExpScalarVT);
9799 SDValue Frexp =
9800 DAG.getNode(ISD::FFREXP, dl, DAG.getVTList(SrcVT, FrexpExpVT), FloatVal);
9801 SDValue FrexpFrac = Frexp.getValue(0);
9802 SDValue FrexpExp = Frexp.getValue(1);
9803
9804 SDValue FrexpFracInt = DAG.getNode(ISD::BITCAST, dl, IntVT, FrexpFrac);
9805 SDValue EffSrcMant = DAG.getNode(ISD::AND, dl, IntVT, FrexpFracInt,
9806 DAG.getConstant(SrcMantMask, dl, IntVT));
9807
9808 SDValue FrexpExpExt = DAG.getSExtOrTrunc(FrexpExp, dl, IntVT);
9809 SDValue NewExp = DAG.getNode(ISD::ADD, dl, IntVT, FrexpExpExt,
9810 DAG.getConstant(DstBias - 1, dl, IntVT));
9811
9812 // Compute rounding increment given the round bit, sticky bits, and LSB
9813 // of the truncated mantissa.
9814 auto ComputeRoundUp = [&](SDValue RoundBit, SDValue StickyBits,
9815 SDValue LSB) -> SDValue {
9816 switch (RoundMode) {
9818 // Round up if round_bit && (sticky || lsb)
9819 SDValue StickyOrLSB = DAG.getNode(ISD::OR, dl, IntVT, StickyBits, LSB);
9820 return DAG.getNode(ISD::AND, dl, IntVT, RoundBit, StickyOrLSB);
9821 }
9823 return Zero;
9825 // Round up if positive and any truncated bits are set.
9826 SDValue AnyTruncBits =
9827 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9828 SDValue HasTruncBits =
9829 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9830 SDValue IsPositive = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETEQ);
9831 SDValue DoRound =
9832 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsPositive);
9833 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9834 }
9836 // Round up if negative and any truncated bits are set (to -Inf).
9837 SDValue AnyTruncBits =
9838 DAG.getNode(ISD::OR, dl, IntVT, RoundBit, StickyBits);
9839 SDValue HasTruncBits =
9840 DAG.getSetCC(dl, SetCCVT, AnyTruncBits, Zero, ISD::SETNE);
9841 SDValue IsNegative = DAG.getSetCC(dl, SetCCVT, SignBit, Zero, ISD::SETNE);
9842 SDValue DoRound =
9843 DAG.getNode(ISD::AND, dl, SetCCVT, HasTruncBits, IsNegative);
9844 return DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, DoRound);
9845 }
9847 return RoundBit;
9848 default:
9849 llvm_unreachable("unsupported rounding mode");
9850 }
9851 };
9852
9853 // Round mantissa from SrcMant bits to DstMant bits.
9854 SDValue TruncMant;
9855 SDValue RoundUp;
9856 if (SrcMant > DstMant) {
9857 const unsigned Shift = SrcMant - DstMant;
9858 SDValue ShiftConst = DAG.getShiftAmountConstant(Shift, IntVT, dl);
9859 TruncMant = DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, ShiftConst);
9860
9861 // Check bit at position Shift - 1 aka the round bit.
9862 SDValue RoundBit;
9863 if (Shift >= 1) {
9864 SDValue RoundBitShift = DAG.getShiftAmountConstant(Shift - 1, IntVT, dl);
9865 SDValue ShiftedMant =
9866 DAG.getNode(ISD::SRL, dl, IntVT, EffSrcMant, RoundBitShift);
9867 RoundBit = DAG.getNode(ISD::AND, dl, IntVT, ShiftedMant, One);
9868 } else {
9869 RoundBit = Zero;
9870 }
9871
9872 // OR of all bits below the round bit to get sticky bits.
9873 SDValue StickyBits;
9874 if (Shift >= 2) {
9875 uint64_t StickyMask = maskTrailingOnes<uint64_t>(Shift - 1);
9876 StickyBits = DAG.getNode(ISD::AND, dl, IntVT, EffSrcMant,
9877 DAG.getConstant(StickyMask, dl, IntVT));
9878 StickyBits = DAG.getSetCC(dl, SetCCVT, StickyBits, Zero, ISD::SETNE);
9879 StickyBits = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, StickyBits);
9880 } else {
9881 StickyBits = Zero;
9882 }
9883
9884 // LSB of truncated mantissa.
9885 SDValue LSB = DAG.getNode(ISD::AND, dl, IntVT, TruncMant, One);
9886
9887 RoundUp = ComputeRoundUp(RoundBit, StickyBits, LSB);
9888 } else {
9889 // If DstMant >= SrcMant, then no rounding needed, just shift left.
9890 SDValue MantShift =
9891 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
9892 TruncMant = DAG.getNode(ISD::SHL, dl, IntVT, EffSrcMant, MantShift);
9893 RoundUp = Zero;
9894 }
9895
9896 // Apply rounding.
9897 SDValue RoundedMant = DAG.getNode(ISD::ADD, dl, IntVT, TruncMant, RoundUp);
9898
9899 // Handle mantissa overflow from rounding.
9900 // If rounded_mant > DstMantMask, carry into exponent.
9901 SDValue MantOverflow =
9902 DAG.getSetCC(dl, SetCCVT, RoundedMant,
9903 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9904 // On overflow: mant = 0, exp += 1.
9905 SDValue AdjMant = DAG.getSelect(dl, IntVT, MantOverflow, Zero, RoundedMant);
9906 SDValue AdjExp =
9907 DAG.getNode(ISD::ADD, dl, IntVT, NewExp,
9908 DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, MantOverflow));
9909
9910 // Precompute sign shifted to MSB of destination. Unsigned formats have no
9911 // sign bit to merge in.
9912 SDValue SignShifted =
9913 DstHasSign
9914 ? DAG.getNode(ISD::SHL, dl, IntVT, SignBit,
9915 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
9916 : Zero;
9917
9918 // Destination denormal conversion (when new_exp <= 0).
9919 // Shift the mantissa right by 1 - new_exp additional bits and set the
9920 // exponent field to 0.
9921 SDValue ExpIsNeg = DAG.getSetCC(dl, SetCCVT, AdjExp,
9922 DAG.getConstant(1, dl, IntVT), ISD::SETLT);
9923
9924 SDValue DenormResult;
9925 {
9926 // denorm_shift = 1 - NewExp.
9927 SDValue DenormShift = DAG.getNode(ISD::SUB, dl, IntVT, One, NewExp);
9928
9929 // full_src_mant = (1 << SrcMant) | EffSrcMant.
9930 SDValue ImplicitOne =
9931 DAG.getNode(ISD::SHL, dl, IntVT, One,
9932 DAG.getShiftAmountConstant(SrcMant, IntVT, dl));
9933 SDValue FullSrcMant =
9934 DAG.getNode(ISD::OR, dl, IntVT, EffSrcMant, ImplicitOne);
9935
9936 // Total right shift = DenormShift + (SrcMant - DstMant).
9937 int64_t MantDelta = static_cast<int64_t>(SrcMant) - DstMant;
9938 SDValue TotalShift =
9939 DAG.getNode(ISD::ADD, dl, IntVT, DenormShift,
9940 DAG.getSignedConstant(MantDelta, dl, IntVT));
9941
9942 // Clamp total shift to avoid UB, then truncate denorm mantissa.
9943 EVT ShiftVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
9944 SDValue MaxShift = DAG.getConstant(SrcBits - 1, dl, IntVT);
9945 SDValue ClampedShift =
9946 DAG.getNode(ISD::UMIN, dl, IntVT, TotalShift, MaxShift);
9947 SDValue DenormTruncMant =
9948 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant,
9949 DAG.getZExtOrTrunc(ClampedShift, dl, ShiftVT));
9950
9951 // Rounding for denorm path.
9952 SDValue DenormRoundUp;
9953 {
9954 // Round bit is at position TotalShift - 1 of FullSrcMant.
9955 // Clamp to at least 1 so the subtraction doesn't underflow and create
9956 // shift nodes with invalid shift amounts.
9957 SDValue SafeShift = DAG.getNode(ISD::UMAX, dl, IntVT, ClampedShift, One);
9958 SDValue RoundBitPos = DAG.getNode(ISD::SUB, dl, IntVT, SafeShift, One);
9959 SDValue RoundBitPosAmt = DAG.getZExtOrTrunc(RoundBitPos, dl, ShiftVT);
9960 SDValue DenormRoundBit = DAG.getNode(
9961 ISD::AND, dl, IntVT,
9962 DAG.getNode(ISD::SRL, dl, IntVT, FullSrcMant, RoundBitPosAmt), One);
9963
9964 // Sticky: all bits below round bit.
9965 // sticky_mask = (1 << RoundBitPos) - 1
9966 SDValue StickyMask = DAG.getNode(
9967 ISD::SUB, dl, IntVT,
9968 DAG.getNode(ISD::SHL, dl, IntVT, One, RoundBitPosAmt), One);
9969 SDValue DenormStickyBits =
9970 DAG.getNode(ISD::AND, dl, IntVT, FullSrcMant, StickyMask);
9971 SDValue HasSticky = DAG.getNode(
9972 ISD::ZERO_EXTEND, dl, IntVT,
9973 DAG.getSetCC(dl, SetCCVT, DenormStickyBits, Zero, ISD::SETNE));
9974
9975 SDValue DenormLSB =
9976 DAG.getNode(ISD::AND, dl, IntVT, DenormTruncMant, One);
9977
9978 DenormRoundUp = ComputeRoundUp(DenormRoundBit, HasSticky, DenormLSB);
9979
9980 // Only apply rounding if TotalShift >= 1 (i.e., there are bits to round).
9981 SDValue ShiftGEOne =
9982 DAG.getSetCC(dl, SetCCVT, ClampedShift, One, ISD::SETUGE);
9983 DenormRoundUp = DAG.getSelect(dl, IntVT, ShiftGEOne, DenormRoundUp, Zero);
9984 }
9985
9986 SDValue DenormRoundedMant =
9987 DAG.getNode(ISD::ADD, dl, IntVT, DenormTruncMant, DenormRoundUp);
9988
9989 // If rounding caused overflow into the normal range, then we get the
9990 // smallest normal number.
9991 SDValue DenormMantOF =
9992 DAG.getSetCC(dl, SetCCVT, DenormRoundedMant,
9993 DAG.getConstant(DstMantMask, dl, IntVT), ISD::SETGT);
9994 SDValue DenormFinalMant =
9995 DAG.getSelect(dl, IntVT, DenormMantOF, Zero, DenormRoundedMant);
9996 SDValue DenormFinalExp = DAG.getSelect(dl, IntVT, DenormMantOF, One, Zero);
9997
9998 // Assemble: sign | (exp << DstMant) | mant
9999 SDValue DenormExpShifted =
10000 DAG.getNode(ISD::SHL, dl, IntVT, DenormFinalExp,
10001 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
10002 DenormResult = DAG.getNode(
10003 ISD::OR, dl, IntVT,
10004 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10005 DenormFinalMant);
10006 }
10007
10008 // Exponent overflow detection.
10009 SDValue ExpOF =
10010 DAG.getSetCC(dl, SetCCVT, AdjExp,
10011 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETGT);
10012
10013 // Also check if AdjExp == DstExpMaxNormal and mantissa overflow into
10014 // a value that exceeds the max allowed mantissa at that exponent.
10015 SDValue ExpAtMax =
10016 DAG.getSetCC(dl, SetCCVT, AdjExp,
10017 DAG.getConstant(DstExpMaxNormal, dl, IntVT), ISD::SETEQ);
10018 SDValue MantExceedsMax =
10019 DAG.getSetCC(dl, SetCCVT, AdjMant,
10020 DAG.getConstant(DstMaxMantAtMaxExp, dl, IntVT), ISD::SETGT);
10021 SDValue ExpMantOF =
10022 DAG.getNode(ISD::AND, dl, SetCCVT, ExpAtMax, MantExceedsMax);
10023 SDValue IsOverflow = DAG.getNode(ISD::OR, dl, SetCCVT, ExpOF, ExpMantOF);
10024
10025 // Build overflow result.
10027
10028 if (Saturate) {
10029 // Clamp to max finite value:
10030 // sign | (DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp
10031 uint64_t MaxFinite =
10032 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
10033 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10034 DAG.getConstant(MaxFinite, dl, IntVT));
10035 } else if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
10036 // Produce infinity.
10037 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
10038 OverflowResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10039 DAG.getConstant(InfBits, dl, IntVT));
10040 } else {
10041 // Emit poison if no Inf in format and not saturating.
10042 OverflowResult = DAG.getPOISON(IntVT);
10043 }
10044
10045 // Assemble normal result: sign | (AdjExp << DstMant) | AdjMant
10046 SDValue NormExpShifted =
10047 DAG.getNode(ISD::SHL, dl, IntVT, AdjExp,
10048 DAG.getShiftAmountConstant(DstMant, IntVT, dl));
10049 SDValue NormResult = DAG.getNode(
10050 ISD::OR, dl, IntVT,
10051 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted), AdjMant);
10052
10053 // Build special-value results.
10054 SDValue NaNResult;
10055 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
10056 // Produce canonical NaN.
10057 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10058 NaNResult =
10059 DAG.getConstant(((uint64_t)DstExpMax << DstMant) | QNaNBit, dl, IntVT);
10060 } else if (DstNFBehavior == fltNonfiniteBehavior::NanOnly &&
10061 DstNanEnc == fltNanEncoding::AllOnes) {
10062 // E4M3FN-style: NaN is exp=all-ones, mant=all-ones.
10063 NaNResult = DAG.getConstant(((uint64_t)DstExpMax << DstMant) | DstMantMask,
10064 dl, IntVT);
10065 } else {
10066 // NaN -> poison for finite only values.
10067 NaNResult = DAG.getPOISON(IntVT);
10068 }
10069
10070 // Inf handling.
10071 SDValue InfResult;
10072 if (DstNFBehavior == fltNonfiniteBehavior::IEEE754) {
10073 // Produce signed infinity.
10074 uint64_t InfBits = (uint64_t)DstExpMax << DstMant;
10075 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10076 DAG.getConstant(InfBits, dl, IntVT));
10077 } else if (Saturate) {
10078 // Inf saturates to max finite.
10079 uint64_t MaxFinite =
10080 ((uint64_t)DstExpMaxNormal << DstMant) | DstMaxMantAtMaxExp;
10081 InfResult = DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10082 DAG.getConstant(MaxFinite, dl, IntVT));
10083 } else {
10084 // No Inf and not saturating -> poison.
10085 InfResult = DAG.getPOISON(IntVT);
10086 }
10087
10088 SDValue ZeroResult = SignShifted;
10089
10090 // Final selection in an order: NaN takes priority, then Inf, then Zero.
10091 SDValue FiniteResult =
10092 DAG.getSelect(dl, IntVT, ExpIsNeg, DenormResult, NormResult);
10093 FiniteResult =
10094 DAG.getSelect(dl, IntVT, IsOverflow, OverflowResult, FiniteResult);
10095
10096 SDValue Result = FiniteResult;
10097 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10098 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10099
10100 // Negative values are unrepresentable in an unsigned format: clamp to zero
10101 // when saturating, poison otherwise so no select is needed. -0.0 is handled
10102 // by IsZero above. Run before the NaN case so a negative NaN still yields
10103 // NaN.
10104 if (!DstHasSign && Saturate) {
10105 SDValue IsNegative =
10106 DAG.getSetCC(dl, FPSetCCVT, FloatVal, FPZero, ISD::SETOLT);
10107 Result = DAG.getSelect(dl, IntVT, IsNegative, Zero, Result);
10108 }
10109
10110 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10111
10112 // Truncate to destination integer type.
10113 return DAG.getZExtOrTrunc(Result, dl, ResVT);
10114}
10115
10116SDValue
10118 SelectionDAG &DAG) const {
10119 SDLoc dl(Node);
10120 EVT DstVT = Node->getValueType(0);
10121 EVT DstScalarVT = DstVT.getScalarType();
10122
10123 SDValue IntVal = Node->getOperand(0);
10124 const uint64_t SemEnum = Node->getConstantOperandVal(1);
10125 const auto Sem = static_cast<APFloatBase::Semantics>(SemEnum);
10126
10127 // Supported source formats.
10128 switch (Sem) {
10135 break;
10136 default:
10137 DAG.getContext()->emitError("CONVERT_FROM_ARBITRARY_FP: not implemented "
10138 "source format (semantics enum " +
10139 Twine(SemEnum) + ")");
10140 return SDValue();
10141 }
10142
10143 const fltSemantics &SrcSem = APFloatBase::EnumToSemantics(Sem);
10144 const unsigned SrcBits = APFloat::getSizeInBits(SrcSem);
10145 const unsigned SrcPrecision = APFloat::semanticsPrecision(SrcSem);
10146 const unsigned SrcMant = SrcPrecision - 1;
10147 // Unsigned formats spend no bit on the sign.
10148 const bool SrcHasSign = APFloat::semanticsHasSignedRepr(SrcSem);
10149 const unsigned SrcExp = SrcBits - (SrcHasSign ? 1 : 0) - SrcMant;
10150 const int SrcBias = 1 - APFloat::semanticsMinExponent(SrcSem);
10151 const fltNonfiniteBehavior NFBehavior = SrcSem.nonFiniteBehavior;
10152
10153 // Destination format parameters.
10154 const fltSemantics &DstSem = DstScalarVT.getFltSemantics();
10155 const unsigned DstBits = APFloat::getSizeInBits(DstSem);
10156 const unsigned DstMant = APFloat::semanticsPrecision(DstSem) - 1;
10157 const unsigned DstExpBits = DstBits - DstMant - 1;
10158 const int DstMinExp = APFloat::semanticsMinExponent(DstSem);
10159 const int DstBias = 1 - DstMinExp;
10160 const uint64_t DstExpAllOnes = (1ULL << DstExpBits) - 1;
10161
10162 // Work in an integer type matching the destination float width.
10163 EVT IntScalarVT = EVT::getIntegerVT(*DAG.getContext(), DstBits);
10164 EVT IntVT = IntScalarVT;
10165 if (DstVT.isVector()) {
10166 IntVT = EVT::getVectorVT(*DAG.getContext(), IntScalarVT,
10167 DstVT.getVectorElementCount());
10168 } else if (!isTypeLegal(IntScalarVT)) {
10169 // Avoid generating illegal type as there is no other places that'll
10170 // legalize it. Vector types don't have this problem because they
10171 // are subject to LegalizeVectorOps and another type legalization phase
10172 // will follow.
10173 if (getTypeAction(*DAG.getContext(), IntScalarVT) != TypePromoteInteger) {
10174 // We only know how to handle situations where the legal type is wider.
10175 DAG.getContext()->emitError(
10176 "CONVERT_FROM_ARBITRARY_FP: the requested integer value type for its "
10177 "legalization is not supported");
10178 return SDValue();
10179 }
10180 IntVT = getTypeToTransformTo(*DAG.getContext(), IntScalarVT);
10181 }
10182
10183 SDValue Src = DAG.getZExtOrTrunc(IntVal, dl, IntVT);
10184
10185 EVT SetCCVT =
10186 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), IntVT);
10187
10188 SDValue Zero = DAG.getConstant(0, dl, IntVT);
10189 SDValue One = DAG.getConstant(1, dl, IntVT);
10190
10191 // Extract bit fields.
10192 const uint64_t MantMask = (SrcMant > 0) ? ((1ULL << SrcMant) - 1) : 0;
10193 const uint64_t ExpMask = (1ULL << SrcExp) - 1;
10194
10195 SDValue MantField = DAG.getNode(ISD::AND, dl, IntVT, Src,
10196 DAG.getConstant(MantMask, dl, IntVT));
10197
10198 SDValue ExpField =
10199 DAG.getNode(ISD::AND, dl, IntVT,
10200 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10201 DAG.getShiftAmountConstant(SrcMant, IntVT, dl)),
10202 DAG.getConstant(ExpMask, dl, IntVT));
10203
10204 // An unsigned source has no sign bit; bit SrcBits - 1 is part of the
10205 // exponent.
10206 SDValue SignShifted =
10207 SrcHasSign
10208 ? DAG.getNode(
10209 ISD::SHL, dl, IntVT,
10210 DAG.getNode(ISD::SRL, dl, IntVT, Src,
10211 DAG.getShiftAmountConstant(SrcBits - 1, IntVT, dl)),
10212 DAG.getShiftAmountConstant(DstBits - 1, IntVT, dl))
10213 : Zero;
10214
10215 // Classify the input.
10216 SDValue ExpAllOnes = DAG.getConstant(ExpMask, dl, IntVT);
10217 SDValue IsExpAllOnes =
10218 DAG.getSetCC(dl, SetCCVT, ExpField, ExpAllOnes, ISD::SETEQ);
10219 SDValue IsExpZero = DAG.getSetCC(dl, SetCCVT, ExpField, Zero, ISD::SETEQ);
10220 SDValue IsMantZero = DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETEQ);
10221 SDValue IsMantNonZero =
10222 DAG.getSetCC(dl, SetCCVT, MantField, Zero, ISD::SETNE);
10223
10224 SDValue IsNaN;
10225 if (NFBehavior == fltNonfiniteBehavior::FiniteOnly) {
10226 IsNaN = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10227 } else if (NFBehavior == fltNonfiniteBehavior::IEEE754) {
10228 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantNonZero);
10229 } else {
10231 SDValue MantAllOnes = DAG.getConstant(MantMask, dl, IntVT);
10232 SDValue IsMantAllOnes =
10233 DAG.getSetCC(dl, SetCCVT, MantField, MantAllOnes, ISD::SETEQ);
10234 IsNaN = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantAllOnes);
10235 }
10236
10237 SDValue IsInf;
10238 if (NFBehavior == fltNonfiniteBehavior::IEEE754)
10239 IsInf = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpAllOnes, IsMantZero);
10240 else
10241 IsInf = DAG.getBoolConstant(false, dl, SetCCVT, IntVT);
10242
10243 SDValue IsZero = DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantZero);
10244 SDValue IsDenorm =
10245 DAG.getNode(ISD::AND, dl, SetCCVT, IsExpZero, IsMantNonZero);
10246
10247 // Normal value conversion.
10248 const int BiasAdjust = DstBias - SrcBias;
10249 SDValue NormDstExp = DAG.getNode(
10250 ISD::ADD, dl, IntVT, ExpField,
10251 DAG.getConstant(APInt(IntVT.getScalarSizeInBits(), BiasAdjust, true), dl,
10252 IntVT));
10253
10254 SDValue NormDstMant;
10255 if (DstMant > SrcMant) {
10256 SDValue NormDstMantShift =
10257 DAG.getShiftAmountConstant(DstMant - SrcMant, IntVT, dl);
10258 NormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, MantField, NormDstMantShift);
10259 } else {
10260 NormDstMant = MantField;
10261 }
10262
10263 SDValue DstMantShift = DAG.getShiftAmountConstant(DstMant, IntVT, dl);
10264 SDValue NormExpShifted =
10265 DAG.getNode(ISD::SHL, dl, IntVT, NormDstExp, DstMantShift);
10266 SDValue NormResult =
10267 DAG.getNode(ISD::OR, dl, IntVT,
10268 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, NormExpShifted),
10269 NormDstMant);
10270
10271 // With identical exponent biases, denormal values remain denormal and the
10272 // normal conversion's mantissa shift is sufficient.
10273 SDValue DenormResult = NormResult;
10274 if (BiasAdjust != 0) {
10275 const unsigned IntVTBits = IntVT.getScalarSizeInBits();
10276 SDValue LeadingZeros =
10277 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, IntVT, MantField);
10278
10279 const int DenormExpConst =
10280 (int)IntVTBits + DstBias - SrcBias - (int)SrcMant;
10281 SDValue DenormDstExp = DAG.getNode(
10282 ISD::SUB, dl, IntVT,
10283 DAG.getConstant(APInt(IntVTBits, DenormExpConst, true), dl, IntVT),
10284 LeadingZeros);
10285
10286 SDValue MantMSB =
10287 DAG.getNode(ISD::SUB, dl, IntVT,
10288 DAG.getConstant(IntVTBits - 1, dl, IntVT), LeadingZeros);
10289
10290 SDValue LeadingOne = DAG.getNode(ISD::SHL, dl, IntVT, One, MantMSB);
10291 SDValue Frac = DAG.getNode(ISD::XOR, dl, IntVT, MantField, LeadingOne);
10292
10293 const unsigned ShiftSub = IntVTBits - 1 - DstMant;
10294 SDValue ShiftAmount = DAG.getNode(ISD::SUB, dl, IntVT, LeadingZeros,
10295 DAG.getConstant(ShiftSub, dl, IntVT));
10296
10297 SDValue DenormDstMant = DAG.getNode(ISD::SHL, dl, IntVT, Frac, ShiftAmount);
10298
10299 SDValue DenormExpShifted =
10300 DAG.getNode(ISD::SHL, dl, IntVT, DenormDstExp, DstMantShift);
10301 DenormResult = DAG.getNode(
10302 ISD::OR, dl, IntVT,
10303 DAG.getNode(ISD::OR, dl, IntVT, SignShifted, DenormExpShifted),
10304 DenormDstMant);
10305 }
10306
10307 SDValue FiniteResult =
10308 DAG.getSelect(dl, IntVT, IsDenorm, DenormResult, NormResult);
10309
10310 const uint64_t QNaNBit = (DstMant > 0) ? (1ULL << (DstMant - 1)) : 0;
10311 SDValue NaNResult =
10312 DAG.getConstant((DstExpAllOnes << DstMant) | QNaNBit, dl, IntVT);
10313
10314 SDValue InfResult =
10315 DAG.getNode(ISD::OR, dl, IntVT, SignShifted,
10316 DAG.getConstant(DstExpAllOnes << DstMant, dl, IntVT));
10317
10318 // A source format may have a larger finite exponent range despite having
10319 // fewer bits, as with Float8E5M3FNU converted to half. Its overflowing finite
10320 // values become infinity. The NaN selection below still takes precedence.
10321 if (APFloat::semanticsMaxExponent(SrcSem) >
10323 SDValue IsOverflow =
10324 DAG.getSetCC(dl, SetCCVT, NormDstExp,
10325 DAG.getConstant(DstExpAllOnes, dl, IntVT), ISD::SETUGE);
10326 FiniteResult =
10327 DAG.getSelect(dl, IntVT, IsOverflow, InfResult, FiniteResult);
10328 }
10329
10330 SDValue ZeroResult = SignShifted;
10331
10332 SDValue Result = FiniteResult;
10333 Result = DAG.getSelect(dl, IntVT, IsZero, ZeroResult, Result);
10334 Result = DAG.getSelect(dl, IntVT, IsInf, InfResult, Result);
10335 Result = DAG.getSelect(dl, IntVT, IsNaN, NaNResult, Result);
10336
10337 if (!DstVT.bitsEq(IntVT)) {
10338 // Store to stack before loading it back.
10339 assert(!IntVT.isVector() && IntVT.bitsGT(DstVT));
10340 // IntScalarVT is the original type that has the same width as DstVT.
10341 Align Alignment = DAG.getReducedAlign(IntScalarVT, /*UseABI=*/false);
10342 SDValue StackPtr =
10343 DAG.CreateStackTemporary(IntScalarVT.getStoreSize(), Alignment);
10344 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
10346 MachinePointerInfo PtrInfo =
10347 MachinePointerInfo::getFixedStack(MF, FrameIndex);
10348 SDValue Store = DAG.getTruncStore(DAG.getEntryNode(), dl, Result, StackPtr,
10349 PtrInfo, IntScalarVT, Alignment);
10350
10351 SDValue Load = DAG.getLoad(DstVT, dl, Store, StackPtr, PtrInfo, Alignment);
10352 return DAG.getMergeValues({Load, Load.getValue(1)}, dl);
10353 }
10354
10355 return DAG.getNode(ISD::BITCAST, dl, DstVT, Result);
10356}
10357
10359 SelectionDAG &DAG) const {
10360 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10361 SDValue Src = Node->getOperand(OpNo);
10362 EVT SrcVT = Src.getValueType();
10363 EVT DstVT = Node->getValueType(0);
10364 SDLoc dl(SDValue(Node, 0));
10365
10366 // FIXME: Only f32 to i64 conversions are supported.
10367 if (SrcVT != MVT::f32 || DstVT != MVT::i64)
10368 return false;
10369
10370 if (Node->isStrictFPOpcode())
10371 // When a NaN is converted to an integer a trap is allowed. We can't
10372 // use this expansion here because it would eliminate that trap. Other
10373 // traps are also allowed and cannot be eliminated. See
10374 // IEEE 754-2008 sec 5.8.
10375 return false;
10376
10377 // Expand f32 -> i64 conversion
10378 // This algorithm comes from compiler-rt's implementation of fixsfdi:
10379 // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
10380 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
10381 EVT IntVT = SrcVT.changeTypeToInteger();
10382 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
10383
10384 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
10385 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
10386 SDValue Bias = DAG.getConstant(127, dl, IntVT);
10387 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
10388 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
10389 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
10390
10391 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
10392
10393 SDValue ExponentBits = DAG.getNode(
10394 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
10395 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
10396 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
10397
10398 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
10399 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
10400 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
10401 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
10402
10403 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
10404 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
10405 DAG.getConstant(0x00800000, dl, IntVT));
10406
10407 R = DAG.getZExtOrTrunc(R, dl, DstVT);
10408
10409 R = DAG.getSelectCC(
10410 dl, Exponent, ExponentLoBit,
10411 DAG.getNode(ISD::SHL, dl, DstVT, R,
10412 DAG.getZExtOrTrunc(
10413 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
10414 dl, IntShVT)),
10415 DAG.getNode(ISD::SRL, dl, DstVT, R,
10416 DAG.getZExtOrTrunc(
10417 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
10418 dl, IntShVT)),
10419 ISD::SETGT);
10420
10421 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
10422 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
10423
10424 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
10425 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
10426 return true;
10427}
10428
10430 SDValue &Chain,
10431 SelectionDAG &DAG) const {
10432 SDLoc dl(SDValue(Node, 0));
10433 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
10434 SDValue Src = Node->getOperand(OpNo);
10435
10436 EVT SrcVT = Src.getValueType();
10437 EVT DstVT = Node->getValueType(0);
10438 EVT SetCCVT =
10439 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10440 EVT DstSetCCVT =
10441 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
10442
10443 // Only expand vector types if we have the appropriate vector bit operations.
10444 unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
10446 if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
10448 return false;
10449
10450 // If the maximum float value is smaller then the signed integer range,
10451 // the destination signmask can't be represented by the float, so we can
10452 // just use FP_TO_SINT directly.
10453 const fltSemantics &APFSem = SrcVT.getFltSemantics();
10454 APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
10455 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
10457 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
10458 if (Node->isStrictFPOpcode()) {
10459 Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10460 { Node->getOperand(0), Src });
10461 Chain = Result.getValue(1);
10462 } else
10463 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10464 return true;
10465 }
10466
10467 // Don't expand it if there isn't cheap fsub instruction.
10469 Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
10470 return false;
10471
10472 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
10473 SDValue Sel;
10474
10475 if (Node->isStrictFPOpcode()) {
10476 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
10477 Node->getOperand(0), /*IsSignaling*/ true);
10478 Chain = Sel.getValue(1);
10479 } else {
10480 Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
10481 }
10482
10483 bool Strict = Node->isStrictFPOpcode() ||
10484 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
10485
10486 if (Strict) {
10487 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
10488 // signmask then offset (the result of which should be fully representable).
10489 // Sel = Src < 0x8000000000000000
10490 // FltOfs = select Sel, 0, 0x8000000000000000
10491 // IntOfs = select Sel, 0, 0x8000000000000000
10492 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
10493
10494 // TODO: Should any fast-math-flags be set for the FSUB?
10495 SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
10496 DAG.getConstantFP(0.0, dl, SrcVT), Cst);
10497 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10498 SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
10499 DAG.getConstant(0, dl, DstVT),
10500 DAG.getConstant(SignMask, dl, DstVT));
10501 SDValue SInt;
10502 if (Node->isStrictFPOpcode()) {
10503 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
10504 { Chain, Src, FltOfs });
10505 SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
10506 { Val.getValue(1), Val });
10507 Chain = SInt.getValue(1);
10508 } else {
10509 SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
10510 SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
10511 }
10512 Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
10513 } else {
10514 // Expand based on maximum range of FP_TO_SINT:
10515 // True = fp_to_sint(Src)
10516 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
10517 // Result = select (Src < 0x8000000000000000), True, False
10518
10519 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
10520 // TODO: Should any fast-math-flags be set for the FSUB?
10521 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
10522 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
10523 False = DAG.getNode(ISD::XOR, dl, DstVT, False,
10524 DAG.getConstant(SignMask, dl, DstVT));
10525 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
10526 Result = DAG.getSelect(dl, DstVT, Sel, True, False);
10527 }
10528 return true;
10529}
10530
10532 SDValue &Chain, SelectionDAG &DAG) const {
10533 // This transform is not correct for converting 0 when rounding mode is set
10534 // to round toward negative infinity which will produce -0.0. So disable
10535 // under strictfp.
10536 if (Node->isStrictFPOpcode())
10537 return false;
10538
10539 SDValue Src = Node->getOperand(0);
10540 EVT SrcVT = Src.getValueType();
10541 EVT DstVT = Node->getValueType(0);
10542
10543 // If the input is known to be non-negative and SINT_TO_FP is legal then use
10544 // it.
10545 if (Node->getFlags().hasNonNeg() &&
10547 Result =
10548 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), DstVT, Node->getOperand(0));
10549 return true;
10550 }
10551
10552 if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
10553 return false;
10554
10555 // Only expand vector types if we have the appropriate vector bit
10556 // operations.
10557 if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
10562 return false;
10563
10564 SDLoc dl(SDValue(Node, 0));
10565
10566 // Implementation of unsigned i64 to f64 following the algorithm in
10567 // __floatundidf in compiler_rt. This implementation performs rounding
10568 // correctly in all rounding modes with the exception of converting 0
10569 // when rounding toward negative infinity. In that case the fsub will
10570 // produce -0.0. This will be added to +0.0 and produce -0.0 which is
10571 // incorrect.
10572 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
10573 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
10574 llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
10575 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
10576 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
10577 SDValue HiShift = DAG.getShiftAmountConstant(32, SrcVT, dl);
10578
10579 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
10580 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
10581 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
10582 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
10583 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
10584 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
10585 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
10586 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
10587 return true;
10588}
10589
10590SDValue
10592 SelectionDAG &DAG) const {
10593 unsigned Opcode = Node->getOpcode();
10594 assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
10595 Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
10596 "Wrong opcode");
10597
10598 if (Node->getFlags().hasNoNaNs()) {
10599 ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
10600 EVT VT = Node->getValueType(0);
10601 if ((!isCondCodeLegal(Pred, VT.getSimpleVT()) ||
10603 VT.isVector())
10604 return SDValue();
10605 SDValue Op1 = Node->getOperand(0);
10606 SDValue Op2 = Node->getOperand(1);
10607 return DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred,
10608 Node->getFlags());
10609 }
10610
10611 return SDValue();
10612}
10613
10615 SelectionDAG &DAG) const {
10616 if (SDValue Expanded = expandVectorNaryOpBySplitting(Node, DAG))
10617 return Expanded;
10618
10619 EVT VT = Node->getValueType(0);
10620 if (VT.isScalableVector())
10622 "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
10623
10624 SDLoc dl(Node);
10625 unsigned NewOp =
10627
10628 if (isOperationLegalOrCustom(NewOp, VT)) {
10629 SDValue Quiet0 = Node->getOperand(0);
10630 SDValue Quiet1 = Node->getOperand(1);
10631
10632 if (!Node->getFlags().hasNoNaNs()) {
10633 // Insert canonicalizes if it's possible we need to quiet to get correct
10634 // sNaN behavior.
10635 if (!DAG.isKnownNeverSNaN(Quiet0)) {
10636 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
10637 Node->getFlags());
10638 }
10639 if (!DAG.isKnownNeverSNaN(Quiet1)) {
10640 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
10641 Node->getFlags());
10642 }
10643 }
10644
10645 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
10646 }
10647
10648 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
10649 // instead if there are no NaNs.
10650 if (Node->getFlags().hasNoNaNs() ||
10651 (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
10652 DAG.isKnownNeverNaN(Node->getOperand(1)))) {
10653 unsigned IEEE2018Op =
10654 Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
10655 if (isOperationLegalOrCustom(IEEE2018Op, VT))
10656 return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
10657 Node->getOperand(1), Node->getFlags());
10658 }
10659
10661 return SelCC;
10662
10663 return SDValue();
10664}
10665
10667 const TargetLowering &TLI,
10668 const SDLoc &DL, SDValue Val,
10669 FPClassTest FPClass) {
10670 EVT VT = Val.getValueType();
10671 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10672 EVT IntVT = VT.changeTypeToInteger();
10673 EVT FloatVT = VT.changeElementType(*DAG.getContext(), MVT::f32);
10674 SDValue TestZero = DAG.getTargetConstant(FPClass, DL, MVT::i32);
10675 if (!TLI.isTypeLegal(IntVT) &&
10676 !TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, VT))
10677 Val = DAG.getNode(ISD::FP_ROUND, DL, FloatVT, Val,
10678 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
10679 return DAG.getNode(ISD::IS_FPCLASS, DL, CCVT, Val, TestZero);
10680}
10681
10683 SelectionDAG &DAG) const {
10684 if (SDValue Expanded = expandVectorNaryOpBySplitting(N, DAG))
10685 return Expanded;
10686
10687 SDLoc DL(N);
10688 SDValue LHS = N->getOperand(0);
10689 SDValue RHS = N->getOperand(1);
10690 unsigned Opc = N->getOpcode();
10691 EVT VT = N->getValueType(0);
10692 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10693 bool IsMax = Opc == ISD::FMAXIMUM;
10694 SDNodeFlags Flags = N->getFlags();
10695
10696 // First, implement comparison not propagating NaN. If no native fmin or fmax
10697 // available, use plain select with setcc instead.
10699 unsigned CompOpcIeee = IsMax ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
10700 unsigned CompOpc = IsMax ? ISD::FMAXNUM : ISD::FMINNUM;
10701
10702 // FIXME: We should probably define fminnum/fmaxnum variants with correct
10703 // signed zero behavior.
10704 bool MinMaxMustRespectOrderedZero = false;
10705
10706 if (isOperationLegalOrCustom(CompOpcIeee, VT)) {
10707 MinMax = DAG.getNode(CompOpcIeee, DL, VT, LHS, RHS, Flags);
10708 MinMaxMustRespectOrderedZero = true;
10709 } else if (isOperationLegalOrCustom(CompOpc, VT)) {
10710 MinMax = DAG.getNode(CompOpc, DL, VT, LHS, RHS, Flags);
10711 } else {
10713 return DAG.UnrollVectorOp(N);
10714
10715 // NaN (if exists) will be propagated later, so orderness doesn't matter.
10716 SDValue Compare =
10717 DAG.getSetCC(DL, CCVT, LHS, RHS, IsMax ? ISD::SETOGT : ISD::SETOLT);
10718 MinMax = DAG.getSelect(DL, VT, Compare, LHS, RHS, Flags);
10719 }
10720
10721 // Propagate any NaN of both operands
10722 if (!N->getFlags().hasNoNaNs() &&
10723 (!DAG.isKnownNeverNaN(RHS) || !DAG.isKnownNeverNaN(LHS))) {
10724 ConstantFP *FPNaN = ConstantFP::get(*DAG.getContext(),
10726 MinMax = DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETUO),
10727 DAG.getConstantFP(*FPNaN, DL, VT), MinMax, Flags);
10728 }
10729
10730 // fminimum/fmaximum requires -0.0 less than +0.0
10731 if (!MinMaxMustRespectOrderedZero && !N->getFlags().hasNoSignedZeros() &&
10732 !DAG.isKnownNeverLogicalZero(RHS) && !DAG.isKnownNeverLogicalZero(LHS)) {
10733 SDValue IsEqual = DAG.getSetCC(DL, CCVT, LHS, RHS, ISD::SETOEQ);
10735 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10736 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, RHS, Flags);
10737 MinMax = DAG.getSelect(DL, VT, IsEqual, RetZero, MinMax, Flags);
10738 }
10739
10740 return MinMax;
10741}
10742
10744 SelectionDAG &DAG) const {
10745 SDLoc DL(Node);
10746 SDValue LHS = Node->getOperand(0);
10747 SDValue RHS = Node->getOperand(1);
10748 unsigned Opc = Node->getOpcode();
10749 EVT VT = Node->getValueType(0);
10750 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10751 bool IsMax = Opc == ISD::FMAXIMUMNUM;
10752 SDNodeFlags Flags = Node->getFlags();
10753
10754 unsigned NewOp =
10756
10757 if (isOperationLegalOrCustom(NewOp, VT)) {
10758 if (!Flags.hasNoNaNs()) {
10759 // Insert canonicalizes if it's possible we need to quiet to get correct
10760 // sNaN behavior.
10761 if (!DAG.isKnownNeverSNaN(LHS)) {
10762 LHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, LHS, Flags);
10763 }
10764 if (!DAG.isKnownNeverSNaN(RHS)) {
10765 RHS = DAG.getNode(ISD::FCANONICALIZE, DL, VT, RHS, Flags);
10766 }
10767 }
10768
10769 return DAG.getNode(NewOp, DL, VT, LHS, RHS, Flags);
10770 }
10771
10772 // We can use FMINIMUM/FMAXIMUM if there is no NaN, since it has
10773 // same behaviors for all of other cases: +0.0 vs -0.0 included.
10774 if (Flags.hasNoNaNs() ||
10775 (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS))) {
10776 unsigned IEEE2019Op =
10778 if (isOperationLegalOrCustom(IEEE2019Op, VT))
10779 return DAG.getNode(IEEE2019Op, DL, VT, LHS, RHS, Flags);
10780 }
10781
10782 // FMINNUM/FMAXMUM returns qNaN if either operand is sNaN, and it may return
10783 // either one for +0.0 vs -0.0.
10784 if ((Flags.hasNoNaNs() ||
10785 (DAG.isKnownNeverSNaN(LHS) && DAG.isKnownNeverSNaN(RHS))) &&
10786 (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10787 DAG.isKnownNeverLogicalZero(RHS))) {
10788 unsigned IEEE2008Op = Opc == ISD::FMINIMUMNUM ? ISD::FMINNUM : ISD::FMAXNUM;
10789 if (isOperationLegalOrCustom(IEEE2008Op, VT))
10790 return DAG.getNode(IEEE2008Op, DL, VT, LHS, RHS, Flags);
10791 }
10792
10793 if (VT.isVector() &&
10796 return DAG.UnrollVectorOp(Node);
10797
10798 // If only one operand is NaN, override it with another operand.
10799 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(LHS)) {
10800 LHS = DAG.getSelectCC(DL, LHS, LHS, RHS, LHS, ISD::SETUO);
10801 }
10802 if (!Flags.hasNoNaNs() && !DAG.isKnownNeverNaN(RHS)) {
10803 RHS = DAG.getSelectCC(DL, RHS, RHS, LHS, RHS, ISD::SETUO);
10804 }
10805
10806 // Always prefer RHS if equal.
10807 SDValue MinMax =
10808 DAG.getSelectCC(DL, LHS, RHS, LHS, RHS, IsMax ? ISD::SETGT : ISD::SETLT);
10809
10810 // TODO: We need quiet sNaN if strictfp.
10811
10812 // Fixup signed zero behavior.
10813 if (Flags.hasNoSignedZeros() || DAG.isKnownNeverLogicalZero(LHS) ||
10814 DAG.isKnownNeverLogicalZero(RHS)) {
10815 return MinMax;
10816 }
10817 SDValue IsZero = DAG.getSetCC(DL, CCVT, MinMax,
10818 DAG.getConstantFP(0.0, DL, VT), ISD::SETEQ);
10820 DAG, *this, DL, LHS, IsMax ? fcPosZero : fcNegZero);
10821 // It's OK to select from LHS and MinMax, with only one ISD::IS_FPCLASS, as
10822 // we preferred RHS when generate MinMax, if the operands are equal.
10823 SDValue RetZero = DAG.getSelect(DL, VT, IsSpecificZero, LHS, MinMax, Flags);
10824 return DAG.getSelect(DL, VT, IsZero, RetZero, MinMax, Flags);
10825}
10826
10827/// Returns a true value if if this FPClassTest can be performed with an ordered
10828/// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
10829/// std::nullopt if it cannot be performed as a compare with 0.
10830static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
10831 const fltSemantics &Semantics,
10832 const MachineFunction &MF) {
10833 FPClassTest OrderedMask = Test & ~fcNan;
10834 FPClassTest NanTest = Test & fcNan;
10835 bool IsOrdered = NanTest == fcNone;
10836 bool IsUnordered = NanTest == fcNan;
10837
10838 // Skip cases that are testing for only a qnan or snan.
10839 if (!IsOrdered && !IsUnordered)
10840 return std::nullopt;
10841
10842 if (OrderedMask == fcZero &&
10843 MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
10844 return IsOrdered;
10845 if (OrderedMask == (fcZero | fcSubnormal) &&
10846 MF.getDenormalMode(Semantics).inputsAreZero())
10847 return IsOrdered;
10848 return std::nullopt;
10849}
10850
10852 const FPClassTest OrigTestMask,
10853 SDNodeFlags Flags, const SDLoc &DL,
10854 SelectionDAG &DAG) const {
10855 EVT OperandVT = Op.getValueType();
10856 assert(OperandVT.isFloatingPoint());
10857 FPClassTest Test = OrigTestMask;
10858
10859 // Degenerated cases.
10860 if (Test == fcNone)
10861 return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
10862 if (Test == fcAllFlags)
10863 return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
10864
10865 // PPC double double is a pair of doubles, of which the higher part determines
10866 // the value class.
10867 if (OperandVT == MVT::ppcf128) {
10868 Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
10869 DAG.getConstant(1, DL, MVT::i32));
10870 OperandVT = MVT::f64;
10871 }
10872
10873 // Floating-point type properties.
10874 EVT ScalarFloatVT = OperandVT.getScalarType();
10875 const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
10876 const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
10877 bool IsF80 = (ScalarFloatVT == MVT::f80);
10878
10879 // Some checks can be implemented using float comparisons, if floating point
10880 // exceptions are ignored.
10881 if (Flags.hasNoFPExcept() &&
10883 FPClassTest FPTestMask = Test;
10884 bool IsInvertedFP = false;
10885
10886 if (FPClassTest InvertedFPCheck =
10887 invertFPClassTestIfSimpler(FPTestMask, true)) {
10888 FPTestMask = InvertedFPCheck;
10889 IsInvertedFP = true;
10890 }
10891
10892 ISD::CondCode OrderedCmpOpcode = IsInvertedFP ? ISD::SETUNE : ISD::SETOEQ;
10893 ISD::CondCode UnorderedCmpOpcode = IsInvertedFP ? ISD::SETONE : ISD::SETUEQ;
10894
10895 // See if we can fold an | fcNan into an unordered compare.
10896 FPClassTest OrderedFPTestMask = FPTestMask & ~fcNan;
10897
10898 // Can't fold the ordered check if we're only testing for snan or qnan
10899 // individually.
10900 if ((FPTestMask & fcNan) != fcNan)
10901 OrderedFPTestMask = FPTestMask;
10902
10903 const bool IsOrdered = FPTestMask == OrderedFPTestMask;
10904
10905 if (std::optional<bool> IsCmp0 =
10906 isFCmpEqualZero(FPTestMask, Semantics, DAG.getMachineFunction());
10907 IsCmp0 && (isCondCodeLegalOrCustom(
10908 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
10909 OperandVT.getScalarType().getSimpleVT()))) {
10910
10911 // If denormals could be implicitly treated as 0, this is not equivalent
10912 // to a compare with 0 since it will also be true for denormals.
10913 return DAG.getSetCC(DL, ResultVT, Op,
10914 DAG.getConstantFP(0.0, DL, OperandVT),
10915 *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
10916 }
10917
10918 if (FPTestMask == fcNan &&
10920 OperandVT.getScalarType().getSimpleVT()))
10921 return DAG.getSetCC(DL, ResultVT, Op, Op,
10922 IsInvertedFP ? ISD::SETO : ISD::SETUO);
10923
10924 bool IsOrderedInf = FPTestMask == fcInf;
10925 if ((FPTestMask == fcInf || FPTestMask == (fcInf | fcNan)) &&
10926 isCondCodeLegalOrCustom(IsOrderedInf ? OrderedCmpOpcode
10927 : UnorderedCmpOpcode,
10928 OperandVT.getScalarType().getSimpleVT()) &&
10931 (OperandVT.isVector() &&
10933 // isinf(x) --> fabs(x) == inf
10934 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10935 SDValue Inf =
10936 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10937 return DAG.getSetCC(DL, ResultVT, Abs, Inf,
10938 IsOrderedInf ? OrderedCmpOpcode : UnorderedCmpOpcode);
10939 }
10940
10941 if ((OrderedFPTestMask == fcPosInf || OrderedFPTestMask == fcNegInf) &&
10942 isCondCodeLegalOrCustom(IsOrdered ? OrderedCmpOpcode
10943 : UnorderedCmpOpcode,
10944 OperandVT.getSimpleVT())) {
10945 // isposinf(x) --> x == inf
10946 // isneginf(x) --> x == -inf
10947 // isposinf(x) || nan --> x u== inf
10948 // isneginf(x) || nan --> x u== -inf
10949
10950 SDValue Inf = DAG.getConstantFP(
10951 APFloat::getInf(Semantics, OrderedFPTestMask == fcNegInf), DL,
10952 OperandVT);
10953 return DAG.getSetCC(DL, ResultVT, Op, Inf,
10954 IsOrdered ? OrderedCmpOpcode : UnorderedCmpOpcode);
10955 }
10956
10957 if (OrderedFPTestMask == (fcSubnormal | fcZero) && !IsOrdered) {
10958 // TODO: Could handle ordered case, but it produces worse code for
10959 // x86. Maybe handle ordered if fabs is free?
10960
10961 ISD::CondCode OrderedOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10962 ISD::CondCode UnorderedOp = IsInvertedFP ? ISD::SETOGE : ISD::SETULT;
10963
10964 if (isCondCodeLegalOrCustom(IsOrdered ? OrderedOp : UnorderedOp,
10965 OperandVT.getScalarType().getSimpleVT())) {
10966 // (issubnormal(x) || iszero(x)) --> fabs(x) < smallest_normal
10967
10968 // TODO: Maybe only makes sense if fabs is free. Integer test of
10969 // exponent bits seems better for x86.
10970 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10971 SDValue SmallestNormal = DAG.getConstantFP(
10972 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10973 return DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal,
10974 IsOrdered ? OrderedOp : UnorderedOp);
10975 }
10976 }
10977
10978 if (FPTestMask == fcNormal) {
10979 // TODO: Handle unordered
10980 ISD::CondCode IsFiniteOp = IsInvertedFP ? ISD::SETUGE : ISD::SETOLT;
10981 ISD::CondCode IsNormalOp = IsInvertedFP ? ISD::SETOLT : ISD::SETUGE;
10982
10983 if (isCondCodeLegalOrCustom(IsFiniteOp,
10984 OperandVT.getScalarType().getSimpleVT()) &&
10985 isCondCodeLegalOrCustom(IsNormalOp,
10986 OperandVT.getScalarType().getSimpleVT()) &&
10987 isFAbsFree(OperandVT)) {
10988 // isnormal(x) --> fabs(x) < infinity && !(fabs(x) < smallest_normal)
10989 SDValue Inf =
10990 DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
10991 SDValue SmallestNormal = DAG.getConstantFP(
10992 APFloat::getSmallestNormalized(Semantics), DL, OperandVT);
10993
10994 SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
10995 SDValue IsFinite = DAG.getSetCC(DL, ResultVT, Abs, Inf, IsFiniteOp);
10996 SDValue IsNormal =
10997 DAG.getSetCC(DL, ResultVT, Abs, SmallestNormal, IsNormalOp);
10998 unsigned LogicOp = IsInvertedFP ? ISD::OR : ISD::AND;
10999 return DAG.getNode(LogicOp, DL, ResultVT, IsFinite, IsNormal);
11000 }
11001 }
11002 }
11003
11004 // Some checks may be represented as inversion of simpler check, for example
11005 // "inf|normal|subnormal|zero" => !"nan".
11006 bool IsInverted = false;
11007
11008 if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test, false)) {
11009 Test = InvertedCheck;
11010 IsInverted = true;
11011 }
11012
11013 // In the general case use integer operations.
11014 unsigned BitSize = OperandVT.getScalarSizeInBits();
11015 EVT IntVT = OperandVT.changeElementType(
11016 *DAG.getContext(), EVT::getIntegerVT(*DAG.getContext(), BitSize));
11017 SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
11018
11019 // Various masks.
11020 APInt SignBit = APInt::getSignMask(BitSize);
11021 APInt ValueMask = APInt::getSignedMaxValue(BitSize); // All bits but sign.
11022 APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
11023 const unsigned ExplicitIntBitInF80 = 63;
11024 APInt ExpMask = Inf;
11025 if (IsF80)
11026 ExpMask.clearBit(ExplicitIntBitInF80);
11027 APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
11028 APInt QNaNBitMask =
11029 APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
11030 APInt InversionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
11031
11032 SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
11033 SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
11034 SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
11035 SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
11036 SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
11037 SDValue ResultInversionMask = DAG.getConstant(InversionMask, DL, ResultVT);
11038
11039 SDValue Res;
11040 const auto appendResult = [&](SDValue PartialRes) {
11041 if (PartialRes) {
11042 if (Res)
11043 Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
11044 else
11045 Res = PartialRes;
11046 }
11047 };
11048
11049 SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
11050 const auto getIntBitIsSet = [&]() -> SDValue {
11051 if (!IntBitIsSetV) {
11052 APInt IntBitMask(BitSize, 0);
11053 IntBitMask.setBit(ExplicitIntBitInF80);
11054 SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
11055 SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
11056 IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
11057 }
11058 return IntBitIsSetV;
11059 };
11060
11061 // Split the value into sign bit and absolute value.
11062 SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
11063 SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
11064 DAG.getConstant(0, DL, IntVT), ISD::SETLT);
11065
11066 // Tests that involve more than one class should be processed first.
11067 SDValue PartialRes;
11068
11069 if (IsF80)
11070 ; // Detect finite numbers of f80 by checking individual classes because
11071 // they have different settings of the explicit integer bit.
11072 else if ((Test & fcFinite) == fcFinite) {
11073 // finite(V) ==> (a << 1) < (inf << 1)
11074 //
11075 // See https://github.com/llvm/llvm-project/issues/169270, this is slightly
11076 // shorter than the `finite(V) ==> abs(V) < exp_mask` formula used before.
11077
11079 "finite check requires IEEE-like FP");
11080
11081 SDValue One = DAG.getShiftAmountConstant(1, IntVT, DL);
11082 SDValue TwiceOp = DAG.getNode(ISD::SHL, DL, IntVT, OpAsInt, One);
11083 SDValue TwiceInf = DAG.getNode(ISD::SHL, DL, IntVT, ExpMaskV, One);
11084
11085 PartialRes = DAG.getSetCC(DL, ResultVT, TwiceOp, TwiceInf, ISD::SETULT);
11086 Test &= ~fcFinite;
11087 } else if ((Test & fcFinite) == fcPosFinite) {
11088 // finite(V) && V > 0 ==> V < exp_mask
11089 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
11090 Test &= ~fcPosFinite;
11091 } else if ((Test & fcFinite) == fcNegFinite) {
11092 // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
11093 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
11094 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11095 Test &= ~fcNegFinite;
11096 }
11097 appendResult(PartialRes);
11098
11099 if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
11100 // fcZero | fcSubnormal => test all exponent bits are 0
11101 // TODO: Handle sign bit specific cases
11102 if (PartialCheck == (fcZero | fcSubnormal)) {
11103 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
11104 SDValue ExpIsZero =
11105 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
11106 appendResult(ExpIsZero);
11107 Test &= ~PartialCheck & fcAllFlags;
11108 }
11109 }
11110
11111 // Check for individual classes.
11112
11113 if (unsigned PartialCheck = Test & fcZero) {
11114 if (PartialCheck == fcPosZero)
11115 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
11116 else if (PartialCheck == fcZero)
11117 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
11118 else // ISD::fcNegZero
11119 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
11120 appendResult(PartialRes);
11121 }
11122
11123 if (unsigned PartialCheck = Test & fcSubnormal) {
11124 // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
11125 // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
11126 SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
11127 SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
11128 SDValue VMinusOneV =
11129 DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
11130 PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
11131 if (PartialCheck == fcNegSubnormal)
11132 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11133 appendResult(PartialRes);
11134 }
11135
11136 if (unsigned PartialCheck = Test & fcInf) {
11137 if (PartialCheck == fcPosInf)
11138 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
11139 else if (PartialCheck == fcInf)
11140 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
11141 else { // ISD::fcNegInf
11142 APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
11143 SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
11144 PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
11145 }
11146 appendResult(PartialRes);
11147 }
11148
11149 if (unsigned PartialCheck = Test & fcNan) {
11150 APInt InfWithQnanBit = Inf | QNaNBitMask;
11151 SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
11152 if (PartialCheck == fcNan) {
11153 // isnan(V) ==> abs(V) > int(inf)
11154 PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11155 if (IsF80) {
11156 // Recognize unsupported values as NaNs for compatibility with glibc.
11157 // In them (exp(V)==0) == int_bit.
11158 SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
11159 SDValue ExpIsZero =
11160 DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
11161 SDValue IsPseudo =
11162 DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
11163 PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
11164 }
11165 } else if (PartialCheck == fcQNan) {
11166 // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
11167 PartialRes =
11168 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
11169 } else { // ISD::fcSNan
11170 // issignaling(V) ==> abs(V) > unsigned(Inf) &&
11171 // abs(V) < (unsigned(Inf) | quiet_bit)
11172 SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
11173 SDValue IsNotQnan =
11174 DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
11175 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
11176 }
11177 appendResult(PartialRes);
11178 }
11179
11180 if (unsigned PartialCheck = Test & fcNormal) {
11181 // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
11182 APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
11183 SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
11184 SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
11185 APInt ExpLimit = ExpMask - ExpLSB;
11186 SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
11187 PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
11188 if (PartialCheck == fcNegNormal)
11189 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
11190 else if (PartialCheck == fcPosNormal) {
11191 SDValue PosSignV =
11192 DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInversionMask);
11193 PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
11194 }
11195 if (IsF80)
11196 PartialRes =
11197 DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
11198 appendResult(PartialRes);
11199 }
11200
11201 if (!Res)
11202 return DAG.getConstant(IsInverted, DL, ResultVT);
11203 if (IsInverted)
11204 Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInversionMask);
11205 return Res;
11206}
11207
11208// Only expand vector types if we have the appropriate vector bit operations.
11210 assert(VT.isVector() && "Expected vector type");
11211 unsigned Len = VT.getScalarSizeInBits();
11212 return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
11213 TLI.isOperationLegalOrCustom(ISD::SUB, VT) &&
11214 TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
11215 (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
11216 TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT);
11217}
11218
11220 SDLoc dl(Node);
11221 EVT VT = Node->getValueType(0);
11222 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11223 SDValue Op = Node->getOperand(0);
11224 unsigned Len = VT.getScalarSizeInBits();
11225
11226 // Compute effective bit width from known bits, allowing us to shift the
11227 // active bits down if necessary to fit into smaller specialized expansions.
11229 unsigned LZ = Known.countMinLeadingZeros();
11230 unsigned TZ = Known.countMinTrailingZeros();
11231 unsigned ShiftedActiveBits = Known.getBitWidth() - (LZ + TZ);
11232
11233 // Round up to 8-bit boundary for byte-oriented SWAR algorithm
11234 unsigned EffectiveLen = Len;
11235 if (ShiftedActiveBits > 0 && ShiftedActiveBits < Len)
11236 EffectiveLen = std::min(alignTo(ShiftedActiveBits, 8), Len);
11237
11238 assert(VT.isInteger() && "CTPOP not implemented for this type.");
11239
11240 // TODO: Add support for irregular type lengths.
11241 if (!(Len <= 128 && Len % 8 == 0))
11242 return SDValue();
11243
11244 // Only expand vector types if we have the appropriate vector bit operations.
11245 if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
11246 return SDValue();
11247
11248 // If the active bits are not at the low end, shift them down
11249 if (EffectiveLen < Len && TZ > 0) {
11250 Op = DAG.getNode(ISD::SRL, dl, VT, Op,
11251 DAG.getShiftAmountConstant(TZ, VT, dl));
11252 }
11253
11254 // This is the "best" algorithm from
11255 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
11256 SDValue Mask55 =
11257 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
11258 SDValue Mask33 =
11259 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
11260 SDValue Mask0F =
11261 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
11262
11263 // v = v - ((v >> 1) & 0x55555555...)
11264 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
11265 DAG.getNode(ISD::AND, dl, VT,
11266 DAG.getNode(ISD::SRL, dl, VT, Op,
11267 DAG.getConstant(1, dl, ShVT)),
11268 Mask55));
11269 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
11270 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
11271 DAG.getNode(ISD::AND, dl, VT,
11272 DAG.getNode(ISD::SRL, dl, VT, Op,
11273 DAG.getConstant(2, dl, ShVT)),
11274 Mask33));
11275 // v = (v + (v >> 4)) & 0x0F0F0F0F...
11276 Op = DAG.getNode(ISD::AND, dl, VT,
11277 DAG.getNode(ISD::ADD, dl, VT, Op,
11278 DAG.getNode(ISD::SRL, dl, VT, Op,
11279 DAG.getConstant(4, dl, ShVT))),
11280 Mask0F);
11281
11282 if (EffectiveLen <= 8)
11283 return Op;
11284
11285 // Avoid the multiply if we only have 2 bytes to add.
11286 // TODO: Only doing this for scalars because vectors weren't as obviously
11287 // improved.
11288 if (EffectiveLen == 16 && !VT.isVector()) {
11289 // v = (v + (v >> 8)) & 0x00FF;
11290 return DAG.getNode(ISD::AND, dl, VT,
11291 DAG.getNode(ISD::ADD, dl, VT, Op,
11292 DAG.getNode(ISD::SRL, dl, VT, Op,
11293 DAG.getConstant(8, dl, ShVT))),
11294 DAG.getConstant(0xFF, dl, VT));
11295 }
11296
11297 // v = (v * 0x01010101...) >> (Len - 8)
11298 SDValue V;
11301 SDValue Mask01 =
11302 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
11303 V = DAG.getNode(ISD::MUL, dl, VT, Op, Mask01);
11304 } else {
11305 V = Op;
11306 for (unsigned Shift = 8; Shift < EffectiveLen; Shift *= 2) {
11307 SDValue ShiftC = DAG.getShiftAmountConstant(Shift, VT, dl);
11308 V = DAG.getNode(ISD::ADD, dl, VT, V,
11309 DAG.getNode(ISD::SHL, dl, VT, V, ShiftC));
11310 }
11311 }
11312 return DAG.getNode(ISD::SRL, dl, VT, V, DAG.getConstant(Len - 8, dl, ShVT));
11313}
11314
11316 SDLoc dl(Node);
11317 EVT VT = Node->getValueType(0);
11318 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
11319 SDValue Op = Node->getOperand(0);
11320 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11321
11322 // If the non-ZERO_POISON version is supported we can use that instead.
11323 if (Node->getOpcode() == ISD::CTLZ_ZERO_POISON &&
11325 return DAG.getNode(ISD::CTLZ, dl, VT, Op);
11326
11327 // If the ZERO_POISON version is supported use that and handle the zero case.
11329 EVT SetCCVT =
11330 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11331 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Op);
11332 SDValue Zero = DAG.getConstant(0, dl, VT);
11333 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11334 return DAG.getSelect(dl, VT, SrcIsZero,
11335 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
11336 }
11337
11338 // Only expand vector types if we have the appropriate vector bit operations.
11339 // This includes the operations needed to expand CTPOP if it isn't supported.
11340 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11342 !canExpandVectorCTPOP(*this, VT)) ||
11345 return SDValue();
11346
11347 // for now, we do this:
11348 // x = x | (x >> 1);
11349 // x = x | (x >> 2);
11350 // ...
11351 // x = x | (x >>16);
11352 // x = x | (x >>32); // for 64-bit input
11353 // return popcount(~x);
11354 //
11355 // Ref: "Hacker's Delight" by Henry Warren
11356 for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
11357 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
11358 Op = DAG.getNode(ISD::OR, dl, VT, Op,
11359 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
11360 }
11361 Op = DAG.getNOT(dl, Op, VT);
11362 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
11363}
11364
11366 SDLoc dl(Node);
11367 EVT VT = Node->getValueType(0);
11368 SDValue Op = DAG.getFreeze(Node->getOperand(0));
11369 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11370
11371 // CTLS(x) = CTLZ(OR(SHL(XOR(x, SRA(x, BW-1)), 1), 1))
11372 // This transforms the sign bits into leading zeros that can be counted.
11373 SDValue ShiftAmt = DAG.getShiftAmountConstant(NumBitsPerElt - 1, VT, dl);
11374 SDValue SignBit = DAG.getNode(ISD::SRA, dl, VT, Op, ShiftAmt);
11375 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, SignBit);
11376 SDValue Shl =
11377 DAG.getNode(ISD::SHL, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11378 SDValue Or = DAG.getNode(ISD::OR, dl, VT, Shl, DAG.getConstant(1, dl, VT));
11379 return DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, Or);
11380}
11381
11383 const SDLoc &DL, EVT VT, SDValue Op,
11384 unsigned BitWidth) const {
11385 if (BitWidth != 32 && BitWidth != 64)
11386 return SDValue();
11387
11388 const DataLayout &TD = DAG.getDataLayout();
11390 return SDValue();
11391
11392 APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
11393 : APInt(64, 0x0218A392CD3D5DBFULL);
11394 MachinePointerInfo PtrInfo =
11396 unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
11397 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11398 SDValue Lookup = DAG.getNode(
11399 ISD::SRL, DL, VT,
11400 DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
11401 DAG.getConstant(DeBruijn, DL, VT)),
11402 DAG.getShiftAmountConstant(ShiftAmt, VT, DL));
11404
11406 for (unsigned i = 0; i < BitWidth; i++) {
11407 APInt Shl = DeBruijn.shl(i);
11408 APInt Lshr = Shl.lshr(ShiftAmt);
11409 Table[Lshr.getZExtValue()] = i;
11410 }
11411
11412 // Create a ConstantArray in Constant Pool
11413 auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
11414 SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
11415 TD.getPrefTypeAlign(CA->getType()));
11416 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
11417 DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
11418 PtrInfo, MVT::i8);
11419 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
11420 return ExtLoad;
11421
11422 EVT SetCCVT =
11423 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11424 SDValue Zero = DAG.getConstant(0, DL, VT);
11425 SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
11426 return DAG.getSelect(DL, VT, SrcIsZero,
11427 DAG.getConstant(BitWidth, DL, VT), ExtLoad);
11428}
11429
11431 SDLoc dl(Node);
11432 EVT VT = Node->getValueType(0);
11433 SDValue Op = Node->getOperand(0);
11434 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
11435
11436 // If the non-ZERO_POISON version is supported we can use that instead.
11437 if (Node->getOpcode() == ISD::CTTZ_ZERO_POISON &&
11439 return DAG.getNode(ISD::CTTZ, dl, VT, Op);
11440
11441 // If the ZERO_POISON version is supported use that and handle the zero case.
11443 EVT SetCCVT =
11444 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11445 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_POISON, dl, VT, Op);
11446 SDValue Zero = DAG.getConstant(0, dl, VT);
11447 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
11448 return DAG.getSelect(dl, VT, SrcIsZero,
11449 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
11450 }
11451
11452 // Only expand vector types if we have the appropriate vector bit operations.
11453 // This includes the operations needed to expand CTPOP if it isn't supported.
11454 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
11457 !canExpandVectorCTPOP(*this, VT)) ||
11461 return SDValue();
11462
11463 // Emit Table Lookup if ISD::CTPOP used in the fallback path below is going
11464 // to be expanded or converted to a libcall.
11467 if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
11468 return V;
11469
11470 bool UseCTLZ =
11472
11473 // When only ctlz is available and the operand is nonzero we can use:
11474 // { return nlz(x & -x) ^ 31; }
11475 // which is more efficient than:
11476 // { return 32 - nlz(~x & (x - 1)); }.
11477 if (UseCTLZ && Node->getOpcode() == ISD::CTTZ_ZERO_POISON) {
11478 SDValue LowestBit =
11479 DAG.getNode(ISD::AND, dl, VT, Op, DAG.getNegative(Op, dl, VT));
11480 return DAG.getNode(ISD::XOR, dl, VT,
11481 DAG.getNode(ISD::CTLZ_ZERO_POISON, dl, VT, LowestBit),
11482 DAG.getConstant(NumBitsPerElt - 1, dl, VT));
11483 }
11484
11485 // If ctpop is available, we use:
11486 // { return popcount(~x & (x-1)); }
11487 // If the target has ctlz but not ctpop, we use:
11488 // { return 32 - nlz(~x & (x-1)); }
11489 // Ref: "Hacker's Delight" by Henry Warren
11490 SDValue Tmp = DAG.getNode(
11491 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
11492 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
11493
11494 if (UseCTLZ)
11495 return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
11496 DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
11497
11498 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
11499}
11500
11502 SelectionDAG &DAG) const {
11503 // %cond = to_bool_vec %source
11504 // %splat = splat /*val=*/VL
11505 // %tz = step_vector
11506 // %v = select %cond, /*true=*/tz, /*false=*/%splat
11507 // %r = vp.reduce.umin %v
11508 SDLoc DL(N);
11509 SDValue Source = N->getOperand(0);
11510 SDValue Mask = N->getOperand(1);
11511 SDValue EVL = N->getOperand(2);
11512 EVT SrcVT = Source.getValueType();
11513 EVT ResVT = N->getValueType(0);
11514 EVT ResVecVT =
11515 EVT::getVectorVT(*DAG.getContext(), ResVT, SrcVT.getVectorElementCount());
11516
11517 // Convert to boolean vector.
11518 if (SrcVT.getScalarType() != MVT::i1) {
11519 SDValue AllZero = DAG.getConstant(0, DL, SrcVT);
11520 SrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
11521 SrcVT.getVectorElementCount());
11522 Source = DAG.getSetCC(DL, SrcVT, Source, AllZero, ISD::SETNE);
11523 }
11524
11525 SDValue ExtEVL = DAG.getZExtOrTrunc(EVL, DL, ResVT);
11526 SDValue Splat = DAG.getSplat(ResVecVT, DL, ExtEVL);
11527 SDValue StepVec = DAG.getStepVector(DL, ResVecVT);
11528 SDValue Select = DAG.getSelect(DL, ResVecVT, Source, StepVec, Splat);
11529 return DAG.getNode(ISD::VP_REDUCE_UMIN, DL, ResVT, ExtEVL, Select, Mask, EVL);
11530}
11531
11532/// Returns a type-legalized version of \p Mask as the first item in the
11533/// pair. The second item contains a type-legalized step vector that's
11534/// guaranteed to fit the number of elements in \p Mask.
11535/// If the stepvector would require splitting, returns an empty SDValue
11536/// as the second item to signal that the operation should be split instead.
11537static std::pair<SDValue, SDValue>
11539 SelectionDAG &DAG) {
11540 EVT MaskVT = Mask.getValueType();
11541 EVT BoolVT = MaskVT.getScalarType();
11542
11543 // Find a suitable type for a stepvector.
11544 // If zero is poison, we can assume the upper limit of the result is VF-1.
11545 ConstantRange VScaleRange(1, /*isFullSet=*/true); // Fixed length default.
11546 if (MaskVT.isScalableVector())
11547 VScaleRange = getVScaleRange(&DAG.getMachineFunction().getFunction(), 64);
11549 uint64_t EltWidth = TLI.getBitWidthForCttzElements(
11550 EVT(TLI.getVectorIdxTy(DAG.getDataLayout())),
11551 MaskVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
11552 // If the step vector element type is smaller than the mask element type,
11553 // use the mask type directly to avoid widening issues.
11554 EltWidth = std::max(EltWidth, BoolVT.getFixedSizeInBits());
11555 EVT StepVT = MVT::getIntegerVT(EltWidth);
11556 EVT StepVecVT = MaskVT.changeVectorElementType(*DAG.getContext(), StepVT);
11557
11558 // If promotion or widening is required to make the type legal, do it here.
11559 // Promotion of integers within LegalizeVectorOps is looking for types of
11560 // the same size but with a smaller number of larger elements, not the usual
11561 // larger size with the same number of larger elements.
11563 TLI.getTypeAction(*DAG.getContext(), StepVecVT);
11564 SDValue StepVec;
11565 if (TypeAction == TargetLowering::TypePromoteInteger) {
11566 StepVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11567 StepVec = DAG.getStepVector(DL, StepVecVT);
11568 } else if (TypeAction == TargetLowering::TypeWidenVector) {
11569 // For widening, the element count changes. Create a step vector with only
11570 // the original elements valid and zeros for padding. Also widen the mask.
11571 EVT WideVecVT = TLI.getTypeToTransformTo(*DAG.getContext(), StepVecVT);
11572 unsigned WideNumElts = WideVecVT.getVectorNumElements();
11573
11574 // Build widened step vector: <0, 1, ..., OrigNumElts-1, poison, poison, ..>
11575 SDValue OrigStepVec = DAG.getStepVector(DL, StepVecVT);
11576 SDValue UndefStep = DAG.getPOISON(WideVecVT);
11577 StepVec = DAG.getInsertSubvector(DL, UndefStep, OrigStepVec, 0);
11578
11579 // Widen mask: pad with zeros.
11580 EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(), BoolVT, WideNumElts);
11581 SDValue ZeroMask = DAG.getConstant(0, DL, WideMaskVT);
11582 Mask = DAG.getInsertSubvector(DL, ZeroMask, Mask, 0);
11583 } else if (TypeAction == TargetLowering::TypeSplitVector) {
11584 // The stepvector type would require splitting. Signal to the caller
11585 // that the operation should be split instead of expanded.
11586 return {Mask, SDValue()};
11587 } else {
11588 StepVec = DAG.getStepVector(DL, StepVecVT);
11589 }
11590
11591 return {Mask, StepVec};
11592}
11593
11595 SelectionDAG &DAG) const {
11596 SDLoc DL(N);
11597 auto [Mask, StepVec] = getLegalMaskAndStepVector(
11598 N->getOperand(0), /*ZeroIsPoison=*/true, DL, DAG);
11599
11600 // If StepVec is empty, the stepvector would require splitting.
11601 // Split the operation instead and let it be recursively legalized.
11602 if (!StepVec) {
11603 EVT MaskVT = N->getOperand(0).getValueType();
11604 EVT ResVT = N->getValueType(0);
11605
11606 // Split the mask
11607 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(MaskVT);
11608 auto [MaskLo, MaskHi] = DAG.SplitVector(N->getOperand(0), DL);
11609
11610 // Create split VECTOR_FIND_LAST_ACTIVE operations
11611 SDValue LoResult =
11612 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskLo);
11613 SDValue HiResult =
11614 DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, DL, ResVT, MaskHi);
11615
11616 // Check if any lane is active in the high mask.
11617 SDValue AnyHiActive = DAG.getNode(ISD::VECREDUCE_OR, DL, MVT::i1, MaskHi);
11619 AnyHiActive, DL,
11620 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i1),
11621 MVT::i1);
11622
11623 // Adjust HiResult by adding the number of elements in Lo
11624 SDValue LoNumElts =
11625 DAG.getElementCount(DL, ResVT, LoVT.getVectorElementCount());
11626 SDValue AdjustedHiResult =
11627 DAG.getNode(ISD::ADD, DL, ResVT, HiResult, LoNumElts);
11628
11629 // Return: AnyHiActive ? AdjustedHiResult : LoResult;
11630 return DAG.getNode(ISD::SELECT, DL, ResVT, Cond, AdjustedHiResult,
11631 LoResult);
11632 }
11633
11634 EVT StepVecVT = StepVec.getValueType();
11635 EVT StepVT = StepVec.getValueType().getVectorElementType();
11636
11637 // Zero out lanes with inactive elements, then find the highest remaining
11638 // value from the stepvector.
11639 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
11640 SDValue ActiveElts = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
11641 SDValue HighestIdx = DAG.getNode(ISD::VECREDUCE_UMAX, DL, StepVT, ActiveElts);
11642 return DAG.getZExtOrTrunc(HighestIdx, DL, N->getValueType(0));
11643}
11644
11646 SelectionDAG &DAG) const {
11647 SDLoc DL(N);
11648
11649 SDValue Start = N->getOperand(0);
11650 SDValue End = N->getOperand(1);
11651 EVT VT = N->getValueType(0);
11652 EVT OpVT = Start.getValueType();
11653
11654 auto [Mask, StepVector] = getLegalMaskAndStepVector(
11655 DAG.getPOISON(VT), /*ZeroIsPoison=*/false, DL, DAG);
11656
11657 // No legal step vector: split the mask in half and recombine the results.
11658 // Lo = get_active_lane_mask Start, End
11659 // Hi = get_active_lane_mask (uaddsat Start, LoNumElts), End
11660 if (!StepVector) {
11661 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
11662 SDValue Lo = DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, LoVT, Start, End);
11663 SDValue LoNumElts =
11664 DAG.getElementCount(DL, OpVT, LoVT.getVectorElementCount());
11665 SDValue HiStart = DAG.getNode(ISD::UADDSAT, DL, OpVT, Start, LoNumElts);
11666 SDValue Hi = DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, HiVT, HiStart, End);
11667 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
11668 }
11669
11670 // Rebase and saturate the termination value.
11671 SDValue Max =
11672 DAG.getConstant(maxUIntN(std::min(StepVector.getScalarValueSizeInBits(),
11673 OpVT.getScalarSizeInBits())),
11674 DL, OpVT);
11675 End = DAG.getNode(ISD::USUBSAT, DL, OpVT, End, Start);
11676 End = DAG.getNode(ISD::UMIN, DL, OpVT, End, Max);
11677 End = DAG.getZExtOrTrunc(End, DL, StepVector.getValueType().getScalarType());
11678
11679 // cmp <0, 1, 2, 3...>, End
11680 SDValue EndV = DAG.getSplat(StepVector.getValueType(), DL, End);
11681 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11682 StepVector.getValueType());
11683 SDValue Cmp = DAG.getSetCC(DL, CCVT, StepVector, EndV, ISD::SETULT);
11684 SDValue Res = DAG.getBoolExtOrTrunc(Cmp, DL, Mask.getValueType(),
11685 StepVector.getValueType());
11686 if (Mask.getValueType() != VT)
11687 Res = DAG.getExtractSubvector(DL, VT, Res, 0);
11688 return Res;
11689}
11690
11692 SelectionDAG &DAG) const {
11693 SDLoc DL(N);
11694 EVT VT = N->getValueType(0);
11695 SDValue SourceValue = N->getOperand(0);
11696 SDValue SinkValue = N->getOperand(1);
11697 SDValue EltSizeInBytes = N->getOperand(2);
11698
11699 // Note: The lane offset is scalable if the mask is scalable.
11700 ElementCount LaneOffsetEC =
11701 ElementCount::get(N->getConstantOperandVal(3), VT.isScalableVT());
11702
11703 EVT AddrVT = SourceValue->getValueType(0);
11704 bool IsReadAfterWrite = N->getOpcode() == ISD::LOOP_DEPENDENCE_RAW_MASK;
11705
11706 EVT CmpVT =
11707 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), AddrVT);
11708
11709 // Unsigned compare: Source >= Sink.
11710 SDValue SourceAheadOfOrEqualToSink =
11711 DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETUGE);
11712
11713 // Take the difference between the pointers and divided by the element size,
11714 // to see how many lanes separate them.
11715 SDValue Diff = DAG.getNode(ISD::SUB, DL, AddrVT, SinkValue, SourceValue);
11716
11717 // RAW_MASK: Diff = Source >= Sink ? (Source - Sink) : (Sink - Source)
11718 if (IsReadAfterWrite)
11719 Diff = DAG.getSelect(DL, AddrVT, SourceAheadOfOrEqualToSink,
11720 DAG.getNegative(Diff, DL, AddrVT), Diff);
11721
11722 Diff = DAG.getNode(ISD::SDIV, DL, AddrVT, Diff, EltSizeInBytes);
11723
11724 // The pointers do not alias if:
11725 // - Source >= Sink (WAR_MASK)
11726 // - Source == Sink (RAW_MASK)
11727 SDValue NoAlias = SourceAheadOfOrEqualToSink;
11728 if (IsReadAfterWrite)
11729 NoAlias = DAG.getSetCC(DL, CmpVT, SourceValue, SinkValue, ISD::SETEQ);
11730
11731 // The pointers do not alias if:
11732 // Lane + LaneOffset < Diff (WAR/RAW_MASK)
11733 SDValue LaneOffset = DAG.getElementCount(DL, AddrVT, LaneOffsetEC);
11734 SDValue MaskN = DAG.getSelect(
11735 DL, AddrVT, NoAlias,
11737 AddrVT),
11738 Diff);
11739
11740 return DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, DL, VT, LaneOffset, MaskN);
11741}
11742
11744 bool IsNegative) const {
11745 SDLoc dl(N);
11746 EVT VT = N->getValueType(0);
11747 SDValue Op = N->getOperand(0);
11748
11749 // If expanding ABS_MIN_POISON, fall back to ABS if the target supports it.
11750 if (N->getOpcode() == ISD::ABS_MIN_POISON &&
11752 SDValue AbsVal = DAG.getNode(ISD::ABS, dl, VT, Op);
11753 if (IsNegative)
11754 return DAG.getNegative(AbsVal, dl, VT);
11755 return AbsVal;
11756 }
11757
11758 // abs(x) -> smax(x,sub(0,x))
11759 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11761 SDValue Zero = DAG.getConstant(0, dl, VT);
11762 Op = DAG.getFreeze(Op);
11763 return DAG.getNode(ISD::SMAX, dl, VT, Op,
11764 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11765 }
11766
11767 // abs(x) -> umin(x,sub(0,x))
11768 if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
11770 SDValue Zero = DAG.getConstant(0, dl, VT);
11771 Op = DAG.getFreeze(Op);
11772 return DAG.getNode(ISD::UMIN, dl, VT, Op,
11773 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11774 }
11775
11776 // 0 - abs(x) -> smin(x, sub(0,x))
11777 if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
11779 SDValue Zero = DAG.getConstant(0, dl, VT);
11780 Op = DAG.getFreeze(Op);
11781 return DAG.getNode(ISD::SMIN, dl, VT, Op,
11782 DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
11783 }
11784
11785 // Only expand vector types if we have the appropriate vector operations.
11786 if (VT.isVector() &&
11788 (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
11789 (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
11791 return SDValue();
11792
11793 Op = DAG.getFreeze(Op);
11794 SDValue Shift = DAG.getNode(
11795 ISD::SRA, dl, VT, Op,
11796 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11797 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
11798
11799 // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
11800 if (!IsNegative)
11801 return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
11802
11803 // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
11804 return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
11805}
11806
11808 SDLoc dl(N);
11809 EVT VT = N->getValueType(0);
11810 SDValue LHS = N->getOperand(0);
11811 SDValue RHS = N->getOperand(1);
11812 bool IsSigned = N->getOpcode() == ISD::ABDS;
11813
11814 // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
11815 // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
11816 unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
11817 unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
11818 if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
11819 LHS = DAG.getFreeze(LHS);
11820 RHS = DAG.getFreeze(RHS);
11821 SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
11822 SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
11823 return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
11824 }
11825
11826 // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
11827 if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT)) {
11828 LHS = DAG.getFreeze(LHS);
11829 RHS = DAG.getFreeze(RHS);
11830 return DAG.getNode(ISD::OR, dl, VT,
11831 DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
11832 DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
11833 }
11834
11835 // abds: if the sub is nsw -> abs(sub)
11836 // abdu with non-negative operands -> abs(sub)
11837 // The abdu case where the sub is nuw is handled in DAGCombine.
11838 if (IsSigned) {
11839 if (DAG.willNotOverflowSub(/*IsSigned=*/true, LHS, RHS))
11840 return DAG.getNode(ISD::ABS, dl, VT,
11841 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11842
11843 if (DAG.willNotOverflowSub(/*IsSigned=*/true, RHS, LHS))
11844 return DAG.getNode(ISD::ABS, dl, VT,
11845 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11846 } else if (DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS)) {
11847 return DAG.getNode(ISD::ABS, dl, VT,
11848 DAG.getNode(ISD::SUB, dl, VT, LHS, RHS));
11849 }
11850
11851 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
11853 LHS = DAG.getFreeze(LHS);
11854 RHS = DAG.getFreeze(RHS);
11855 SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
11856
11857 // Branchless expansion iff cmp result is allbits:
11858 // abds(lhs, rhs) -> sub(sgt(lhs, rhs), xor(sgt(lhs, rhs), sub(lhs, rhs)))
11859 // abdu(lhs, rhs) -> sub(ugt(lhs, rhs), xor(ugt(lhs, rhs), sub(lhs, rhs)))
11860 if (CCVT == VT && getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
11861 SDValue Diff = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
11862 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Diff, Cmp);
11863 return DAG.getNode(ISD::SUB, dl, VT, Cmp, Xor);
11864 }
11865
11866 // Similar to the branchless expansion, if we don't prefer selects, use the
11867 // (sign-extended) usubo overflow flag if the (scalar) type is illegal as this
11868 // is more likely to legalize cleanly: abdu(lhs, rhs) -> sub(xor(sub(lhs,
11869 // rhs), uof(lhs, rhs)), uof(lhs, rhs))
11870 if (!IsSigned && VT.isScalarInteger() && !isTypeLegal(VT) &&
11872 SDValue USubO =
11873 DAG.getNode(ISD::USUBO, dl, DAG.getVTList(VT, MVT::i1), {LHS, RHS});
11874 SDValue Cmp = DAG.getNode(ISD::SIGN_EXTEND, dl, VT, USubO.getValue(1));
11875 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, USubO.getValue(0), Cmp);
11876 return DAG.getNode(ISD::SUB, dl, VT, Xor, Cmp);
11877 }
11878
11879 // FIXME: Should really try to split the vector in case it's legal on a
11880 // subvector.
11882 return DAG.UnrollVectorOp(N);
11883
11884 // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11885 // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
11886 return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
11887 DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
11888}
11889
11891 SDLoc dl(N);
11892 EVT VT = N->getValueType(0);
11893 SDValue LHS = N->getOperand(0);
11894 SDValue RHS = N->getOperand(1);
11895
11896 unsigned Opc = N->getOpcode();
11897 bool IsFloor = Opc == ISD::AVGFLOORS || Opc == ISD::AVGFLOORU;
11898 bool IsSigned = Opc == ISD::AVGCEILS || Opc == ISD::AVGFLOORS;
11899 unsigned SumOpc = IsFloor ? ISD::ADD : ISD::SUB;
11900 unsigned SignOpc = IsFloor ? ISD::AND : ISD::OR;
11901 unsigned ShiftOpc = IsSigned ? ISD::SRA : ISD::SRL;
11902 unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
11904 Opc == ISD::AVGFLOORU || Opc == ISD::AVGCEILU) &&
11905 "Unknown AVG node");
11906
11907 // If the operands are already extended, we can add+shift.
11908 bool IsExt =
11909 (IsSigned && DAG.ComputeNumSignBits(LHS) >= 2 &&
11910 DAG.ComputeNumSignBits(RHS) >= 2) ||
11911 (!IsSigned && DAG.computeKnownBits(LHS).countMinLeadingZeros() >= 1 &&
11912 DAG.computeKnownBits(RHS).countMinLeadingZeros() >= 1);
11913 if (IsExt) {
11914 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
11915 if (!IsFloor)
11916 Sum = DAG.getNode(ISD::ADD, dl, VT, Sum, DAG.getConstant(1, dl, VT));
11917 return DAG.getNode(ShiftOpc, dl, VT, Sum,
11918 DAG.getShiftAmountConstant(1, VT, dl));
11919 }
11920
11921 // For scalars, see if we can efficiently extend/truncate to use add+shift.
11922 if (VT.isScalarInteger()) {
11923 EVT ExtVT = VT.widenIntegerElementType(*DAG.getContext());
11924 if (isTypeLegal(ExtVT) && isTruncateFree(ExtVT, VT)) {
11925 LHS = DAG.getNode(ExtOpc, dl, ExtVT, LHS);
11926 RHS = DAG.getNode(ExtOpc, dl, ExtVT, RHS);
11927 SDValue Avg = DAG.getNode(ISD::ADD, dl, ExtVT, LHS, RHS);
11928 if (!IsFloor)
11929 Avg = DAG.getNode(ISD::ADD, dl, ExtVT, Avg,
11930 DAG.getConstant(1, dl, ExtVT));
11931 // Just use SRL as we will be truncating away the extended sign bits.
11932 Avg = DAG.getNode(ISD::SRL, dl, ExtVT, Avg,
11933 DAG.getShiftAmountConstant(1, ExtVT, dl));
11934 return DAG.getNode(ISD::TRUNCATE, dl, VT, Avg);
11935 }
11936 }
11937
11938 // avgflooru(lhs, rhs) -> or(lshr(add(lhs, rhs),1),shl(overflow, typesize-1))
11939 if (Opc == ISD::AVGFLOORU && VT.isScalarInteger() && !isTypeLegal(VT) &&
11942 SDValue UAddWithOverflow =
11943 DAG.getNode(ISD::UADDO, dl, DAG.getVTList(VT, MVT::i1), {RHS, LHS});
11944
11945 SDValue Sum = UAddWithOverflow.getValue(0);
11946 SDValue Overflow = UAddWithOverflow.getValue(1);
11947
11948 // Right shift the sum by 1
11949 SDValue LShrVal = DAG.getNode(ISD::SRL, dl, VT, Sum,
11950 DAG.getShiftAmountConstant(1, VT, dl));
11951
11952 SDValue ZeroExtOverflow = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Overflow);
11953 SDValue OverflowShl = DAG.getNode(
11954 ISD::SHL, dl, VT, ZeroExtOverflow,
11955 DAG.getShiftAmountConstant(VT.getScalarSizeInBits() - 1, VT, dl));
11956
11957 return DAG.getNode(ISD::OR, dl, VT, LShrVal, OverflowShl);
11958 }
11959
11960 // avgceils(lhs, rhs) -> sub(or(lhs,rhs),ashr(xor(lhs,rhs),1))
11961 // avgceilu(lhs, rhs) -> sub(or(lhs,rhs),lshr(xor(lhs,rhs),1))
11962 // avgfloors(lhs, rhs) -> add(and(lhs,rhs),ashr(xor(lhs,rhs),1))
11963 // avgflooru(lhs, rhs) -> add(and(lhs,rhs),lshr(xor(lhs,rhs),1))
11964 LHS = DAG.getFreeze(LHS);
11965 RHS = DAG.getFreeze(RHS);
11966 SDValue Sign = DAG.getNode(SignOpc, dl, VT, LHS, RHS);
11967 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
11968 SDValue Shift =
11969 DAG.getNode(ShiftOpc, dl, VT, Xor, DAG.getShiftAmountConstant(1, VT, dl));
11970 return DAG.getNode(SumOpc, dl, VT, Sign, Shift);
11971}
11972
11974 SDLoc dl(N);
11975 EVT VT = N->getValueType(0);
11976 SDValue Op = N->getOperand(0);
11977
11978 if (!VT.isSimple())
11979 return SDValue();
11980
11981 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
11982 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
11983 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
11984 default:
11985 return SDValue();
11986 case MVT::i16:
11987 // Use a rotate by 8. This can be further expanded if necessary.
11988 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
11989 case MVT::i32:
11990 // This is meant for ARM specifically, which has ROTR but no ROTL.
11991 // t = x ^ rotr(x, 16)
11992 // t = bic(t, 0x00ff0000)
11993 // t = lshr(t, 8)
11994 // x = t ^ rotr(x, 8)
11996 SDValue Rotr16 =
11997 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(16, dl, SHVT));
11998 SDValue Tmp = DAG.getNode(ISD::XOR, dl, VT, Op, Rotr16);
11999 Tmp = DAG.getNode(ISD::AND, dl, VT, Tmp,
12000 DAG.getConstant(0xFF00FFFF, dl, VT));
12001 Tmp = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(8, dl, SHVT));
12002 SDValue Rotr8 =
12003 DAG.getNode(ISD::ROTR, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12004 return DAG.getNode(ISD::XOR, dl, VT, Tmp, Rotr8);
12005 }
12006 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
12007 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
12008 DAG.getConstant(0xFF00, dl, VT));
12009 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
12010 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12011 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
12012 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
12013 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
12014 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
12015 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
12016 case MVT::i64:
12017 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
12018 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
12019 DAG.getConstant(255ULL<<8, dl, VT));
12020 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
12021 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
12022 DAG.getConstant(255ULL<<16, dl, VT));
12023 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
12024 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
12025 DAG.getConstant(255ULL<<24, dl, VT));
12026 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
12027 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
12028 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
12029 DAG.getConstant(255ULL<<24, dl, VT));
12030 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
12031 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
12032 DAG.getConstant(255ULL<<16, dl, VT));
12033 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
12034 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
12035 DAG.getConstant(255ULL<<8, dl, VT));
12036 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
12037 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
12038 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
12039 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
12040 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
12041 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
12042 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
12043 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
12044 }
12045}
12046
12048 SDLoc dl(N);
12049 EVT VT = N->getValueType(0);
12050 SDValue Op = N->getOperand(0);
12051 EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
12052 unsigned Sz = VT.getScalarSizeInBits();
12053
12054 SDValue Tmp, Tmp2, Tmp3;
12055
12056 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
12057 // and finally the i1 pairs.
12058 // TODO: We can easily support i4/i2 legal types if any target ever does.
12059 if (Sz >= 8 && isPowerOf2_32(Sz)) {
12060 // Create the masks - repeating the pattern every byte.
12061 APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
12062 APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
12063 APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
12064
12065 // BSWAP if the type is wider than a single byte.
12066 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
12067
12068 // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
12069 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
12070 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
12071 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
12072 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
12073 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
12074
12075 // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
12076 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
12077 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
12078 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
12079 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
12080 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
12081
12082 // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
12083 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
12084 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
12085 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
12086 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
12087 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
12088 return Tmp;
12089 }
12090
12091 Tmp = DAG.getConstant(0, dl, VT);
12092 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
12093 if (I < J)
12094 Tmp2 =
12095 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
12096 else
12097 Tmp2 =
12098 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
12099
12100 APInt Shift = APInt::getOneBitSet(Sz, J);
12101 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
12102 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
12103 }
12104
12105 return Tmp;
12106}
12107
12108std::pair<SDValue, SDValue>
12110 SelectionDAG &DAG) const {
12111 SDLoc SL(LD);
12112 SDValue Chain = LD->getChain();
12113 SDValue BasePTR = LD->getBasePtr();
12114 EVT SrcVT = LD->getMemoryVT();
12115 EVT DstVT = LD->getValueType(0);
12116 ISD::LoadExtType ExtType = LD->getExtensionType();
12117
12118 if (SrcVT.isScalableVector())
12119 report_fatal_error("Cannot scalarize scalable vector loads");
12120
12121 unsigned NumElem = SrcVT.getVectorNumElements();
12122
12123 EVT SrcEltVT = SrcVT.getScalarType();
12124 EVT DstEltVT = DstVT.getScalarType();
12125
12126 // A vector must always be stored in memory as-is, i.e. without any padding
12127 // between the elements, since various code depend on it, e.g. in the
12128 // handling of a bitcast of a vector type to int, which may be done with a
12129 // vector store followed by an integer load. A vector that does not have
12130 // elements that are byte-sized must therefore be stored as an integer
12131 // built out of the extracted vector elements.
12132 if (!SrcEltVT.isByteSized()) {
12133 unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
12134 EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
12135
12136 unsigned NumSrcBits = SrcVT.getSizeInBits();
12137 EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
12138
12139 unsigned SrcEltBits = SrcEltVT.getSizeInBits();
12140 SDValue SrcEltBitMask = DAG.getConstant(
12141 APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
12142
12143 // Load the whole vector and avoid masking off the top bits as it makes
12144 // the codegen worse.
12145 SDValue Load = DAG.getExtLoad(
12146 ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR, LD->getPointerInfo(),
12147 SrcIntVT, LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12148 LD->getMMOMetadataForSubAccess());
12149
12151 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12152 unsigned ShiftIntoIdx =
12153 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12154 SDValue ShiftAmount = DAG.getShiftAmountConstant(
12155 ShiftIntoIdx * SrcEltVT.getSizeInBits(), LoadVT, SL);
12156 SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
12157 SDValue Elt =
12158 DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
12159 SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
12160
12161 if (ExtType != ISD::NON_EXTLOAD) {
12162 unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
12163 Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
12164 }
12165
12166 Vals.push_back(Scalar);
12167 }
12168
12169 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12170 return std::make_pair(Value, Load.getValue(1));
12171 }
12172
12173 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
12174 assert(SrcEltVT.isByteSized());
12175
12177 SmallVector<SDValue, 8> LoadChains;
12178
12179 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12180 SDValue ScalarLoad = DAG.getExtLoad(
12181 ExtType, SL, DstEltVT, Chain, BasePTR,
12182 LD->getPointerInfo().getWithOffset(Idx * Stride), SrcEltVT,
12183 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12184 LD->getMMOMetadataForSubAccess());
12185
12186 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
12187
12188 Vals.push_back(ScalarLoad.getValue(0));
12189 LoadChains.push_back(ScalarLoad.getValue(1));
12190 }
12191
12192 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
12193 SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
12194
12195 return std::make_pair(Value, NewChain);
12196}
12197
12199 SelectionDAG &DAG) const {
12200 SDLoc SL(ST);
12201
12202 SDValue Chain = ST->getChain();
12203 SDValue BasePtr = ST->getBasePtr();
12204 SDValue Value = ST->getValue();
12205 EVT StVT = ST->getMemoryVT();
12206
12207 if (StVT.isScalableVector())
12208 report_fatal_error("Cannot scalarize scalable vector stores");
12209
12210 // The type of the data we want to save
12211 EVT RegVT = Value.getValueType();
12212 EVT RegSclVT = RegVT.getScalarType();
12213
12214 // The type of data as saved in memory.
12215 EVT MemSclVT = StVT.getScalarType();
12216
12217 unsigned NumElem = StVT.getVectorNumElements();
12218
12219 // A vector must always be stored in memory as-is, i.e. without any padding
12220 // between the elements, since various code depend on it, e.g. in the
12221 // handling of a bitcast of a vector type to int, which may be done with a
12222 // vector store followed by an integer load. A vector that does not have
12223 // elements that are byte-sized must therefore be stored as an integer
12224 // built out of the extracted vector elements.
12225 if (!MemSclVT.isByteSized()) {
12226 unsigned NumBits = StVT.getSizeInBits();
12227 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
12228
12229 SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
12230
12231 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12232 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12233 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
12234 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
12235 unsigned ShiftIntoIdx =
12236 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
12237 SDValue ShiftAmount =
12238 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
12239 SDValue ShiftedElt =
12240 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
12241 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
12242 }
12243
12244 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
12245 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12246 ST->getMMOMetadataForSubAccess());
12247 }
12248
12249 // Store Stride in bytes
12250 unsigned Stride = MemSclVT.getSizeInBits() / 8;
12251 assert(Stride && "Zero stride!");
12252 // Extract each of the elements from the original vector and save them into
12253 // memory individually.
12255 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
12256 SDValue Elt = DAG.getExtractVectorElt(SL, RegSclVT, Value, Idx);
12257
12258 SDValue Ptr =
12259 DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
12260
12261 // This scalar TruncStore may be illegal, but we legalize it later.
12263 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
12264 MemSclVT, ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12265 ST->getMMOMetadataForSubAccess());
12266
12267 Stores.push_back(Store);
12268 }
12269
12270 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
12271}
12272
12273std::pair<SDValue, SDValue>
12275 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
12276 "unaligned indexed loads not implemented!");
12277 SDValue Chain = LD->getChain();
12278 SDValue Ptr = LD->getBasePtr();
12279 EVT VT = LD->getValueType(0);
12280 EVT LoadedVT = LD->getMemoryVT();
12281 SDLoc dl(LD);
12282 auto &MF = DAG.getMachineFunction();
12283
12284 if (VT.isFloatingPoint() || VT.isVector()) {
12285 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
12286 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
12287 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
12288 LoadedVT.isVector()) {
12289 // Scalarize the load and let the individual components be handled.
12290 return scalarizeVectorLoad(LD, DAG);
12291 }
12292
12293 // Expand to a (misaligned) integer load of the same size,
12294 // then bitconvert to floating point or vector.
12295 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
12296 LD->getMemOperand());
12297 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
12298 if (LoadedVT != VT)
12299 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
12300 ISD::ANY_EXTEND, dl, VT, Result);
12301
12302 return std::make_pair(Result, newLoad.getValue(1));
12303 }
12304
12305 // Copy the value to a (aligned) stack slot using (unaligned) integer
12306 // loads and stores, then do a (aligned) load from the stack slot.
12307 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
12308 unsigned LoadedBytes = LoadedVT.getStoreSize();
12309 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12310 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
12311
12312 // Make sure the stack slot is also aligned for the register type.
12313 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
12314 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
12316 SDValue StackPtr = StackBase;
12317 unsigned Offset = 0;
12318
12319 EVT PtrVT = Ptr.getValueType();
12320 EVT StackPtrVT = StackPtr.getValueType();
12321
12322 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12323 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12324
12325 // Do all but one copies using the full register width.
12326 for (unsigned i = 1; i < NumRegs; i++) {
12327 // Load one integer register's worth from the original location.
12328 SDValue Load = DAG.getLoad(
12329 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
12330 LD->getBaseAlign(), LD->getMemOperand()->getFlags(),
12331 LD->getMMOMetadataForSubAccess());
12332 // Follow the load with a store to the stack slot. Remember the store.
12333 Stores.push_back(DAG.getStore(
12334 Load.getValue(1), dl, Load, StackPtr,
12335 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
12336 // Increment the pointers.
12337 Offset += RegBytes;
12338
12339 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12340 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12341 }
12342
12343 // The last copy may be partial. Do an extending load.
12344 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
12345 8 * (LoadedBytes - Offset));
12346 SDValue Load = DAG.getExtLoad(
12347 ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
12348 LD->getPointerInfo().getWithOffset(Offset), MemVT, LD->getBaseAlign(),
12349 LD->getMemOperand()->getFlags(), LD->getMMOMetadataForSubAccess());
12350 // Follow the load with a store to the stack slot. Remember the store.
12351 // On big-endian machines this requires a truncating store to ensure
12352 // that the bits end up in the right place.
12353 Stores.push_back(DAG.getTruncStore(
12354 Load.getValue(1), dl, Load, StackPtr,
12355 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
12356
12357 // The order of the stores doesn't matter - say it with a TokenFactor.
12358 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12359
12360 // Finally, perform the original load only redirected to the stack slot.
12361 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
12362 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
12363 LoadedVT);
12364
12365 // Callers expect a MERGE_VALUES node.
12366 return std::make_pair(Load, TF);
12367 }
12368
12369 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
12370 "Unaligned load of unsupported type.");
12371
12372 // Compute the new VT that is half the size of the old one. This is an
12373 // integer MVT.
12374 unsigned NumBits = LoadedVT.getSizeInBits();
12375 EVT NewLoadedVT;
12376 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
12377 NumBits >>= 1;
12378
12379 Align Alignment = LD->getBaseAlign();
12380 unsigned IncrementSize = NumBits / 8;
12381 ISD::LoadExtType HiExtType = LD->getExtensionType();
12382
12383 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
12384 if (HiExtType == ISD::NON_EXTLOAD)
12385 HiExtType = ISD::ZEXTLOAD;
12386
12387 // Load the value in two parts
12388 SDValue Lo, Hi;
12389 if (DAG.getDataLayout().isLittleEndian()) {
12390 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12391 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12392 LD->getMMOMetadataForSubAccess());
12393
12394 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12395 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
12396 LD->getPointerInfo().getWithOffset(IncrementSize),
12397 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12398 LD->getMMOMetadataForSubAccess());
12399 } else {
12400 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
12401 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12402 LD->getMMOMetadataForSubAccess());
12403
12404 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12405 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
12406 LD->getPointerInfo().getWithOffset(IncrementSize),
12407 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
12408 LD->getMMOMetadataForSubAccess());
12409 }
12410
12411 // aggregate the two parts
12412 SDValue ShiftAmount = DAG.getShiftAmountConstant(NumBits, VT, dl);
12413 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
12414 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
12415
12416 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
12417 Hi.getValue(1));
12418
12419 return std::make_pair(Result, TF);
12420}
12421
12423 SelectionDAG &DAG) const {
12424 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
12425 "unaligned indexed stores not implemented!");
12426 SDValue Chain = ST->getChain();
12427 SDValue Ptr = ST->getBasePtr();
12428 SDValue Val = ST->getValue();
12429 EVT VT = Val.getValueType();
12430 Align Alignment = ST->getBaseAlign();
12431 auto &MF = DAG.getMachineFunction();
12432 EVT StoreMemVT = ST->getMemoryVT();
12433
12434 SDLoc dl(ST);
12435 if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
12436 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
12437 if (isTypeLegal(intVT)) {
12438 if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
12439 StoreMemVT.isVector()) {
12440 // Scalarize the store and let the individual components be handled.
12441 SDValue Result = scalarizeVectorStore(ST, DAG);
12442 return Result;
12443 }
12444 // Expand to a bitconvert of the value to the integer type of the
12445 // same size, then a (misaligned) int store.
12446 // FIXME: Does not handle truncating floating point stores!
12447 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
12448 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
12449 Alignment, ST->getMemOperand()->getFlags(),
12450 ST->getMMOMetadataForSubAccess());
12451 return Result;
12452 }
12453 // Do a (aligned) store to a stack slot, then copy from the stack slot
12454 // to the final destination using (unaligned) integer loads and stores.
12455 MVT RegVT = getRegisterType(
12456 *DAG.getContext(),
12457 EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
12458 EVT PtrVT = Ptr.getValueType();
12459 unsigned StoredBytes = StoreMemVT.getStoreSize();
12460 unsigned RegBytes = RegVT.getSizeInBits() / 8;
12461 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
12462
12463 // Make sure the stack slot is also aligned for the register type.
12464 SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
12465 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
12466
12467 // Perform the original store, only redirected to the stack slot.
12469 Chain, dl, Val, StackPtr,
12470 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
12471
12472 EVT StackPtrVT = StackPtr.getValueType();
12473
12474 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
12475 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
12477 unsigned Offset = 0;
12478
12479 // Do all but one copies using the full register width.
12480 for (unsigned i = 1; i < NumRegs; i++) {
12481 // Load one integer register's worth from the stack slot.
12482 SDValue Load = DAG.getLoad(
12483 RegVT, dl, Store, StackPtr,
12484 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
12485 // Store it to the final location. Remember the store.
12486 Stores.push_back(DAG.getStore(
12487 Load.getValue(1), dl, Load, Ptr,
12488 ST->getPointerInfo().getWithOffset(Offset), ST->getBaseAlign(),
12489 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess()));
12490 // Increment the pointers.
12491 Offset += RegBytes;
12492 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
12493 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
12494 }
12495
12496 // The last store may be partial. Do a truncating store. On big-endian
12497 // machines this requires an extending load from the stack slot to ensure
12498 // that the bits are in the right place.
12499 EVT LoadMemVT =
12500 EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
12501
12502 // Load from the stack slot.
12503 SDValue Load = DAG.getExtLoad(
12504 ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
12505 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
12506
12507 Stores.push_back(
12508 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
12509 ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
12510 ST->getBaseAlign(), ST->getMemOperand()->getFlags(),
12511 ST->getMMOMetadataForSubAccess()));
12512 // The order of the stores doesn't matter - say it with a TokenFactor.
12513 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
12514 return Result;
12515 }
12516
12517 assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
12518 "Unaligned store of unknown type.");
12519 // Get the half-size VT
12520 EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
12521 unsigned NumBits = NewStoredVT.getFixedSizeInBits();
12522 unsigned IncrementSize = NumBits / 8;
12523
12524 // Divide the stored value in two parts.
12525 SDValue ShiftAmount =
12526 DAG.getShiftAmountConstant(NumBits, Val.getValueType(), dl);
12527 SDValue Lo = Val;
12528 // If Val is a constant, replace the upper bits with 0. The SRL will constant
12529 // fold and not use the upper bits. A smaller constant may be easier to
12530 // materialize.
12531 if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
12532 Lo = DAG.getNode(
12533 ISD::AND, dl, VT, Lo,
12534 DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
12535 VT));
12536 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
12537
12538 // Store the two parts
12539 SDValue Store1, Store2;
12540 Store1 = DAG.getTruncStore(
12541 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Lo : Hi, Ptr,
12542 ST->getPointerInfo(), NewStoredVT, Alignment,
12543 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12544
12545 Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
12546 Store2 = DAG.getTruncStore(
12547 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
12548 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
12549 ST->getMemOperand()->getFlags(), ST->getMMOMetadataForSubAccess());
12550
12551 SDValue Result =
12552 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
12553 return Result;
12554}
12555
12556SDValue
12558 const SDLoc &DL, EVT DataVT,
12559 SelectionDAG &DAG,
12560 bool IsCompressedMemory) const {
12562 EVT AddrVT = Addr.getValueType();
12563 EVT MaskVT = Mask.getValueType();
12564 assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
12565 "Incompatible types of Data and Mask");
12566 if (IsCompressedMemory) {
12567 // Incrementing the pointer according to number of '1's in the mask.
12568 if (DataVT.isScalableVector()) {
12569 EVT MaskExtVT = MaskVT.changeElementType(*DAG.getContext(), MVT::i32);
12570 SDValue MaskExt = DAG.getNode(ISD::ZERO_EXTEND, DL, MaskExtVT, Mask);
12571 Increment = DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, MaskExt);
12572 } else {
12573 EVT MaskIntVT =
12574 EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
12575 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
12576 if (MaskIntVT.getSizeInBits() < 32) {
12577 MaskInIntReg =
12578 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
12579 MaskIntVT = MVT::i32;
12580 }
12581 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
12582 }
12583 // Scale is an element size in bytes.
12584 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
12585 AddrVT);
12586 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
12587 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
12588 } else
12589 Increment = DAG.getTypeSize(DL, AddrVT, DataVT.getStoreSize());
12590
12591 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
12592}
12593
12595 EVT VecVT, const SDLoc &DL,
12596 ElementCount SubEC) {
12597 assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
12598 "Cannot index a scalable vector within a fixed-width vector");
12599 ElementCount NElts = VecVT.getVectorElementCount();
12600 EVT IdxVT = Idx.getValueType();
12601
12602 // Attempt to prove all accessed lanes sit within VecVT.
12603 ElementCount IdxAsEC;
12604 if (sd_match(Idx, m_ElementCount(IdxAsEC))) {
12605 if (SubEC.isScalar() && ElementCount::isKnownLT(IdxAsEC, NElts))
12606 return Idx;
12607 // Calculate end index as TypeSize to remove possibility of overflow.
12608 if (IdxAsEC.isScalable() == SubEC.isScalable() &&
12609 TypeSize::isKnownLE(TypeSize(IdxAsEC) + TypeSize(SubEC),
12610 TypeSize(NElts)))
12611 return Idx;
12612 }
12613
12614 // Can we mask Idx rather than clamp it.
12615 if (SubEC.isScalar() && NElts.isPowerOf2()) {
12616 SDValue EC = DAG.getElementCount(DL, IdxVT, NElts);
12617 SDValue Mask =
12618 DAG.getNode(ISD::SUB, DL, IdxVT, EC, DAG.getConstant(1, DL, IdxVT));
12619 return DAG.getNode(ISD::AND, DL, IdxVT, Idx, Mask);
12620 }
12621
12622 unsigned SubOpcode =
12624 SDValue MaxSafeIndex =
12625 DAG.getNode(SubOpcode, DL, IdxVT, DAG.getElementCount(DL, IdxVT, NElts),
12626 DAG.getElementCount(DL, IdxVT, SubEC));
12627 return DAG.getNode(ISD::UMIN, DL, IdxVT, Idx, MaxSafeIndex);
12628}
12629
12630SDValue
12632 EVT VecVT, SDValue Index,
12633 const SDNodeFlags PtrArithFlags) const {
12635 DAG, VecPtr, VecVT,
12637 Index, PtrArithFlags);
12638}
12639
12640SDValue
12642 EVT VecVT, EVT SubVecVT, SDValue Index,
12643 const SDNodeFlags PtrArithFlags) const {
12644 SDLoc dl(Index);
12645 // Make sure the index type is big enough to compute in.
12646 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
12647
12648 EVT EltVT = VecVT.getVectorElementType();
12649
12650 // Calculate the element offset and add it to the pointer.
12651 unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
12652 assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
12653 "Converting bits to bytes lost precision");
12654 assert(SubVecVT.getVectorElementType() == EltVT &&
12655 "Sub-vector must be a vector with matching element type");
12656 assert((SubVecVT.getVectorElementCount().isScalar() ||
12657 isa<ConstantSDNode>(Index)) &&
12658 "Subvector Index must be constant!");
12659
12660 // An out-of-range index only makes the vector operation return poison, but
12661 // a load/store through the pointer computed below would be immediate UB, so
12662 // freeze the index before clamping it into range.
12663 if (!DAG.isGuaranteedNotToBePoison(Index))
12664 Index = DAG.getFreeze(Index);
12665
12666 EVT IdxVT = Index.getValueType();
12667 if (SubVecVT.isScalableVector())
12668 Index =
12669 DAG.getVScale(dl, IdxVT, cast<ConstantSDNode>(Index)->getAPIntValue());
12670
12671 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
12672 SubVecVT.getVectorElementCount());
12673 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
12674 DAG.getConstant(EltSize, dl, IdxVT));
12675 return DAG.getMemBasePlusOffset(VecPtr, Index, dl, PtrArithFlags);
12676}
12677
12678//===----------------------------------------------------------------------===//
12679// Implementation of Emulated TLS Model
12680//===----------------------------------------------------------------------===//
12681
12683 SelectionDAG &DAG) const {
12684 // Access to address of TLS varialbe xyz is lowered to a function call:
12685 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
12686 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12687 PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
12688 SDLoc dl(GA);
12689
12690 ArgListTy Args;
12691 const GlobalValue *GV =
12693 SmallString<32> NameString("__emutls_v.");
12694 NameString += GV->getName();
12695 StringRef EmuTlsVarName(NameString);
12696 const GlobalVariable *EmuTlsVar =
12697 GV->getParent()->getNamedGlobal(EmuTlsVarName);
12698 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
12699 Args.emplace_back(DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT), VoidPtrType);
12700
12701 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
12702
12704 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
12705 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
12706 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12707
12708 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12709 // At last for X86 targets, maybe good for other targets too?
12711 MFI.setAdjustsStack(true); // Is this only for X86 target?
12712 MFI.setHasCalls(true);
12713
12714 assert((GA->getOffset() == 0) &&
12715 "Emulated TLS must have zero offset in GlobalAddressSDNode");
12716 return CallResult.first;
12717}
12718
12720 SelectionDAG &DAG) const {
12721 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
12722 if (!isCtlzFast())
12723 return SDValue();
12724 ISD::CondCode CC = Op.getOperandCondCode(2);
12725 SDLoc dl(Op);
12726 if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
12727 EVT VT = Op.getOperand(0).getValueType();
12728 SDValue Zext = Op.getOperand(0);
12729 if (VT.bitsLT(MVT::i32)) {
12730 VT = MVT::i32;
12731 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
12732 }
12733 unsigned Log2b = Log2_32(VT.getSizeInBits());
12734 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
12735 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
12736 DAG.getConstant(Log2b, dl, MVT::i32));
12737 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
12738 }
12739 return SDValue();
12740}
12741
12743 SDValue Op0 = Node->getOperand(0);
12744 SDValue Op1 = Node->getOperand(1);
12745 EVT VT = Op0.getValueType();
12746 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12747 unsigned Opcode = Node->getOpcode();
12748 SDLoc DL(Node);
12749
12750 // If both sign bits are zero, flip UMIN/UMAX <-> SMIN/SMAX if legal.
12751 unsigned AltOpcode = ISD::getOppositeSignednessMinMaxOpcode(Opcode);
12752 if (isOperationLegal(AltOpcode, VT) && DAG.SignBitIsZero(Op0) &&
12753 DAG.SignBitIsZero(Op1))
12754 return DAG.getNode(AltOpcode, DL, VT, Op0, Op1);
12755
12756 // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
12757 if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
12759 Op0 = DAG.getFreeze(Op0);
12760 SDValue Zero = DAG.getConstant(0, DL, VT);
12761 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12762 DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
12763 }
12764
12765 // umin(x,y) -> sub(x,usubsat(x,y))
12766 // TODO: Missing freeze(Op0)?
12767 if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
12769 return DAG.getNode(ISD::SUB, DL, VT, Op0,
12770 DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
12771 }
12772
12773 // umax(x,y) -> add(x,usubsat(y,x))
12774 // TODO: Missing freeze(Op0)?
12775 if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
12777 return DAG.getNode(ISD::ADD, DL, VT, Op0,
12778 DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
12779 }
12780
12781 // FIXME: Should really try to split the vector in case it's legal on a
12782 // subvector.
12784 return DAG.UnrollVectorOp(Node);
12785
12786 // Attempt to find an existing SETCC node that we can reuse.
12787 // TODO: Do we need a generic doesSETCCNodeExist?
12788 // TODO: Missing freeze(Op0)/freeze(Op1)?
12789 auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
12790 ISD::CondCode PrefCommuteCC,
12791 ISD::CondCode AltCommuteCC) {
12792 SDVTList BoolVTList = DAG.getVTList(BoolVT);
12793 for (ISD::CondCode CC : {PrefCC, AltCC}) {
12794 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12795 {Op0, Op1, DAG.getCondCode(CC)})) {
12796 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12797 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12798 }
12799 }
12800 for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
12801 if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
12802 {Op0, Op1, DAG.getCondCode(CC)})) {
12803 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
12804 return DAG.getSelect(DL, VT, Cond, Op1, Op0);
12805 }
12806 }
12807 SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
12808 return DAG.getSelect(DL, VT, Cond, Op0, Op1);
12809 };
12810
12811 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
12812 // -> Y = (A < B) ? B : A
12813 // -> Y = (A >= B) ? A : B
12814 // -> Y = (A <= B) ? B : A
12815 switch (Opcode) {
12816 case ISD::SMAX:
12817 return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
12818 case ISD::SMIN:
12819 return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
12820 case ISD::UMAX:
12821 return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
12822 case ISD::UMIN:
12823 return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
12824 }
12825
12826 llvm_unreachable("How did we get here?");
12827}
12828
12830 unsigned Opcode = Node->getOpcode();
12831 SDValue LHS = Node->getOperand(0);
12832 SDValue RHS = Node->getOperand(1);
12833 EVT VT = LHS.getValueType();
12834 SDLoc dl(Node);
12835
12836 assert(VT == RHS.getValueType() && "Expected operands to be the same type");
12837 assert(VT.isInteger() && "Expected operands to be integers");
12838
12839 // usub.sat(a, b) -> umax(a, b) - b
12840 if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
12841 SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
12842 return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
12843 }
12844
12845 // usub.sat(a, 1) -> sub(a, zext(a != 0))
12846 // Prefer this on targets without legal/cost-effective overflow-carry nodes.
12847 if (Opcode == ISD::USUBSAT && isOneOrOneSplat(RHS) &&
12849 LHS = DAG.getFreeze(LHS);
12850 SDValue Zero = DAG.getConstant(0, dl, VT);
12851 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12852 SDValue IsNonZero = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETNE);
12853 SDValue Subtrahend = DAG.getBoolExtOrTrunc(IsNonZero, dl, VT, BoolVT);
12854 Subtrahend =
12855 DAG.getNode(ISD::AND, dl, VT, Subtrahend, DAG.getConstant(1, dl, VT));
12856 return DAG.getNode(ISD::SUB, dl, VT, LHS, Subtrahend);
12857 }
12858
12859 // uadd.sat(a, b) -> umin(a, ~b) + b
12860 if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
12861 SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
12862 SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
12863 return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
12864 }
12865
12866 unsigned OverflowOp;
12867 switch (Opcode) {
12868 case ISD::SADDSAT:
12869 OverflowOp = ISD::SADDO;
12870 break;
12871 case ISD::UADDSAT:
12872 OverflowOp = ISD::UADDO;
12873 break;
12874 case ISD::SSUBSAT:
12875 OverflowOp = ISD::SSUBO;
12876 break;
12877 case ISD::USUBSAT:
12878 OverflowOp = ISD::USUBO;
12879 break;
12880 default:
12881 llvm_unreachable("Expected method to receive signed or unsigned saturation "
12882 "addition or subtraction node.");
12883 }
12884
12885 // FIXME: Should really try to split the vector in case it's legal on a
12886 // subvector.
12888 return DAG.UnrollVectorOp(Node);
12889
12890 unsigned BitWidth = LHS.getScalarValueSizeInBits();
12891 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12892 SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
12893 SDValue SumDiff = Result.getValue(0);
12894 SDValue Overflow = Result.getValue(1);
12895 SDValue Zero = DAG.getConstant(0, dl, VT);
12896 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
12897
12898 if (Opcode == ISD::UADDSAT) {
12900 // (LHS + RHS) | OverflowMask
12901 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12902 return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
12903 }
12904 // Overflow ? 0xffff.... : (LHS + RHS)
12905 return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
12906 }
12907
12908 if (Opcode == ISD::USUBSAT) {
12910 // (LHS - RHS) & ~OverflowMask
12911 SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
12912 SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
12913 return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
12914 }
12915 // Overflow ? 0 : (LHS - RHS)
12916 return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
12917 }
12918
12919 assert((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
12920 "Expected signed saturating add/sub opcode");
12921
12922 const APInt MinVal = APInt::getSignedMinValue(BitWidth);
12923 const APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
12924
12925 KnownBits KnownLHS = DAG.computeKnownBits(LHS);
12926 KnownBits KnownRHS = DAG.computeKnownBits(RHS);
12927
12928 // If either of the operand signs are known, then they are guaranteed to
12929 // only saturate in one direction. If non-negative they will saturate
12930 // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
12931 //
12932 // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
12933 // sign of 'y' has to be flipped.
12934
12935 bool LHSIsNonNegative = KnownLHS.isNonNegative();
12936 bool RHSIsNonNegative =
12937 Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative() : KnownRHS.isNegative();
12938 if (LHSIsNonNegative || RHSIsNonNegative) {
12939 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
12940 return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
12941 }
12942
12943 bool LHSIsNegative = KnownLHS.isNegative();
12944 bool RHSIsNegative =
12945 Opcode == ISD::SADDSAT ? KnownRHS.isNegative() : KnownRHS.isNonNegative();
12946 if (LHSIsNegative || RHSIsNegative) {
12947 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12948 return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
12949 }
12950
12951 // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
12952 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
12953 SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
12954 DAG.getConstant(BitWidth - 1, dl, VT));
12955 Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
12956 return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
12957}
12958
12960 unsigned Opcode = Node->getOpcode();
12961 SDValue LHS = Node->getOperand(0);
12962 SDValue RHS = Node->getOperand(1);
12963 EVT VT = LHS.getValueType();
12964 EVT ResVT = Node->getValueType(0);
12965 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
12966 SDLoc dl(Node);
12967
12968 auto LTPredicate = (Opcode == ISD::UCMP ? ISD::SETULT : ISD::SETLT);
12969 auto GTPredicate = (Opcode == ISD::UCMP ? ISD::SETUGT : ISD::SETGT);
12970 SDValue IsLT = DAG.getSetCC(dl, BoolVT, LHS, RHS, LTPredicate);
12971 SDValue IsGT = DAG.getSetCC(dl, BoolVT, LHS, RHS, GTPredicate);
12972
12973 // We can't perform arithmetic on i1 values. Extending them would
12974 // probably result in worse codegen, so let's just use two selects instead.
12975 // Some targets are also just better off using selects rather than subtraction
12976 // because one of the conditions can be merged with one of the selects.
12977 // And finally, if we don't know the contents of high bits of a boolean value
12978 // we can't perform any arithmetic either.
12980 BoolVT.getScalarSizeInBits() == 1 ||
12982 SDValue SelectZeroOrOne =
12983 DAG.getSelect(dl, ResVT, IsGT, DAG.getConstant(1, dl, ResVT),
12984 DAG.getConstant(0, dl, ResVT));
12985 return DAG.getSelect(dl, ResVT, IsLT, DAG.getAllOnesConstant(dl, ResVT),
12986 SelectZeroOrOne);
12987 }
12988
12990 std::swap(IsGT, IsLT);
12991 return DAG.getSExtOrTrunc(DAG.getNode(ISD::SUB, dl, BoolVT, IsGT, IsLT), dl,
12992 ResVT);
12993}
12994
12996 unsigned Opcode = Node->getOpcode();
12997 bool IsSigned = Opcode == ISD::SSHLSAT;
12998 SDValue LHS = Node->getOperand(0);
12999 SDValue RHS = Node->getOperand(1);
13000 EVT VT = LHS.getValueType();
13001 SDLoc dl(Node);
13002
13003 assert((Node->getOpcode() == ISD::SSHLSAT ||
13004 Node->getOpcode() == ISD::USHLSAT) &&
13005 "Expected a SHLSAT opcode");
13006 assert(VT.isInteger() && "Expected operands to be integers");
13007
13009 return DAG.UnrollVectorOp(Node);
13010
13011 // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
13012
13013 unsigned BW = VT.getScalarSizeInBits();
13014 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13015 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
13016 SDValue Orig =
13017 DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
13018
13019 SDValue SatVal;
13020 if (IsSigned) {
13021 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
13022 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
13023 SDValue Cond =
13024 DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
13025 SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
13026 } else {
13027 SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
13028 }
13029 SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
13030 return DAG.getSelect(dl, VT, Cond, SatVal, Result);
13031}
13032
13034 bool Signed, SDValue &Lo, SDValue &Hi,
13035 SDValue LHS, SDValue RHS,
13036 SDValue HiLHS, SDValue HiRHS) const {
13037 EVT VT = LHS.getValueType();
13038 assert(RHS.getValueType() == VT && "Mismatching operand types");
13039
13040 assert((HiLHS && HiRHS) || (!HiLHS && !HiRHS));
13041 assert((!Signed || !HiLHS) &&
13042 "Signed flag should only be set when HiLHS and RiRHS are null");
13043
13044 // We'll expand the multiplication by brute force because we have no other
13045 // options. This is a trivially-generalized version of the code from
13046 // Hacker's Delight (itself derived from Knuth's Algorithm M from section
13047 // 4.3.1). If Signed is set, we can use arithmetic right shifts to propagate
13048 // sign bits while calculating the Hi half.
13049 unsigned Bits = VT.getScalarSizeInBits();
13050 unsigned HalfBits = Bits / 2;
13051 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl, VT);
13052 SDValue LL = DAG.getNode(ISD::AND, dl, VT, LHS, Mask);
13053 SDValue RL = DAG.getNode(ISD::AND, dl, VT, RHS, Mask);
13054
13055 SDValue T = DAG.getNode(ISD::MUL, dl, VT, LL, RL);
13056 SDValue TL = DAG.getNode(ISD::AND, dl, VT, T, Mask);
13057
13058 SDValue Shift = DAG.getShiftAmountConstant(HalfBits, VT, dl);
13059 // This is always an unsigned shift.
13060 SDValue TH = DAG.getNode(ISD::SRL, dl, VT, T, Shift);
13061
13062 unsigned ShiftOpc = Signed ? ISD::SRA : ISD::SRL;
13063 SDValue LH = DAG.getNode(ShiftOpc, dl, VT, LHS, Shift);
13064 SDValue RH = DAG.getNode(ShiftOpc, dl, VT, RHS, Shift);
13065
13066 SDValue U =
13067 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RL), TH);
13068 SDValue UL = DAG.getNode(ISD::AND, dl, VT, U, Mask);
13069 SDValue UH = DAG.getNode(ShiftOpc, dl, VT, U, Shift);
13070
13071 SDValue V =
13072 DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LL, RH), UL);
13073 SDValue VH = DAG.getNode(ShiftOpc, dl, VT, V, Shift);
13074
13075 Lo = DAG.getNode(ISD::ADD, dl, VT, TL,
13076 DAG.getNode(ISD::SHL, dl, VT, V, Shift));
13077
13078 Hi = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::MUL, dl, VT, LH, RH),
13079 DAG.getNode(ISD::ADD, dl, VT, UH, VH));
13080
13081 // If HiLHS and HiRHS are set, multiply them by the opposite low part and add
13082 // the products to Hi.
13083 if (HiLHS) {
13084 SDValue RHLL = DAG.getNode(ISD::MUL, dl, VT, HiRHS, LHS);
13085 SDValue RLLH = DAG.getNode(ISD::MUL, dl, VT, RHS, HiLHS);
13086 Hi = DAG.getNode(ISD::ADD, dl, VT, Hi,
13087 DAG.getNode(ISD::ADD, dl, VT, RHLL, RLLH));
13088 }
13089}
13090
13092 bool Signed, const SDValue LHS,
13093 const SDValue RHS, SDValue &Lo,
13094 SDValue &Hi) const {
13095 EVT VT = LHS.getValueType();
13096 assert(RHS.getValueType() == VT && "Mismatching operand types");
13097 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13098 // We can fall back to a libcall with an illegal type for the MUL if we
13099 // have a libcall big enough.
13100 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
13101 if (WideVT == MVT::i16)
13102 LC = RTLIB::MUL_I16;
13103 else if (WideVT == MVT::i32)
13104 LC = RTLIB::MUL_I32;
13105 else if (WideVT == MVT::i64)
13106 LC = RTLIB::MUL_I64;
13107 else if (WideVT == MVT::i128)
13108 LC = RTLIB::MUL_I128;
13109
13110 RTLIB::LibcallImpl LibcallImpl = getLibcallImpl(LC);
13111 if (LibcallImpl == RTLIB::Unsupported) {
13112 forceExpandMultiply(DAG, dl, Signed, Lo, Hi, LHS, RHS);
13113 return;
13114 }
13115
13116 // The libcall takes and returns WideVT values as packed VT halves. This only
13117 // works if VT is legal and WideVT isn't. Otherwise, emit a wide multiply and
13118 // let it legalise normally, possibly into a wider libcall.
13119 if (isTypeLegal(WideVT) || !isTypeLegal(VT)) {
13120 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT,
13121 DAG.getExtOrTrunc(Signed, LHS, dl, WideVT),
13122 DAG.getExtOrTrunc(Signed, RHS, dl, WideVT));
13123 SDValue Shift =
13124 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13125 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13126 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT,
13127 DAG.getNode(ISD::SRL, dl, WideVT, Mul, Shift));
13128 return;
13129 }
13130
13131 SDValue HiLHS, HiRHS;
13132 if (Signed) {
13133 // The high part is obtained by SRA'ing all but one of the bits of low
13134 // part.
13135 unsigned LoSize = VT.getFixedSizeInBits();
13136 SDValue Shift = DAG.getShiftAmountConstant(LoSize - 1, VT, dl);
13137 HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, Shift);
13138 HiRHS = DAG.getNode(ISD::SRA, dl, VT, RHS, Shift);
13139 } else {
13140 HiLHS = DAG.getConstant(0, dl, VT);
13141 HiRHS = DAG.getConstant(0, dl, VT);
13142 }
13143
13144 // Attempt a libcall.
13145 SDValue Ret;
13147 CallOptions.setIsSigned(Signed);
13148 CallOptions.setIsPostTypeLegalization(true);
13150 // Halves of WideVT are packed into registers in different order
13151 // depending on platform endianness. This is usually handled by
13152 // the C calling convention, but we can't defer to it in
13153 // the legalizer.
13154 SDValue Args[] = {LHS, HiLHS, RHS, HiRHS};
13155 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
13156 } else {
13157 SDValue Args[] = {HiLHS, LHS, HiRHS, RHS};
13158 Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
13159 }
13161 "Ret value is a collection of constituent nodes holding result.");
13162 if (DAG.getDataLayout().isLittleEndian()) {
13163 // Same as above.
13164 Lo = Ret.getOperand(0);
13165 Hi = Ret.getOperand(1);
13166 } else {
13167 Lo = Ret.getOperand(1);
13168 Hi = Ret.getOperand(0);
13169 }
13170}
13171
13172SDValue
13174 assert((Node->getOpcode() == ISD::SMULFIX ||
13175 Node->getOpcode() == ISD::UMULFIX ||
13176 Node->getOpcode() == ISD::SMULFIXSAT ||
13177 Node->getOpcode() == ISD::UMULFIXSAT) &&
13178 "Expected a fixed point multiplication opcode");
13179
13180 SDLoc dl(Node);
13181 SDValue LHS = Node->getOperand(0);
13182 SDValue RHS = Node->getOperand(1);
13183 EVT VT = LHS.getValueType();
13184 unsigned Scale = Node->getConstantOperandVal(2);
13185 bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
13186 Node->getOpcode() == ISD::UMULFIXSAT);
13187 bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
13188 Node->getOpcode() == ISD::SMULFIXSAT);
13189 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13190 unsigned VTSize = VT.getScalarSizeInBits();
13191
13192 if (!Scale) {
13193 // [us]mul.fix(a, b, 0) -> mul(a, b)
13194 if (!Saturating) {
13196 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13197 } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
13198 SDValue Result =
13199 DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13200 SDValue Product = Result.getValue(0);
13201 SDValue Overflow = Result.getValue(1);
13202 SDValue Zero = DAG.getConstant(0, dl, VT);
13203
13204 APInt MinVal = APInt::getSignedMinValue(VTSize);
13205 APInt MaxVal = APInt::getSignedMaxValue(VTSize);
13206 SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
13207 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13208 // Xor the inputs, if resulting sign bit is 0 the product will be
13209 // positive, else negative.
13210 SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
13211 SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
13212 Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
13213 return DAG.getSelect(dl, VT, Overflow, Result, Product);
13214 } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
13215 SDValue Result =
13216 DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
13217 SDValue Product = Result.getValue(0);
13218 SDValue Overflow = Result.getValue(1);
13219
13220 APInt MaxVal = APInt::getMaxValue(VTSize);
13221 SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
13222 return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
13223 }
13224 }
13225
13226 assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
13227 "Expected scale to be less than the number of bits if signed or at "
13228 "most the number of bits if unsigned.");
13229 assert(LHS.getValueType() == RHS.getValueType() &&
13230 "Expected both operands to be the same type");
13231
13232 // Select the saturated value when Cond0 <CC> Cond1, keeping it vectorized:
13233 // SELECT_CC is scalarized for vector types, so build SETCC + VSELECT there.
13234 auto getSaturatingSelect = [&](SDValue Cond0, SDValue Cond1, SDValue Sat,
13235 SDValue Val, ISD::CondCode CC) {
13236 if (VT.isVector())
13237 return DAG.getSelect(dl, VT, DAG.getSetCC(dl, BoolVT, Cond0, Cond1, CC),
13238 Sat, Val);
13239 return DAG.getSelectCC(dl, Cond0, Cond1, Sat, Val, CC);
13240 };
13241
13242 // Get the upper and lower bits of the result.
13243 SDValue Lo, Hi;
13244 unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13245 unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
13246 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13247 if (isOperationLegalOrCustom(LoHiOp, VT)) {
13248 SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
13249 Lo = Result.getValue(0);
13250 Hi = Result.getValue(1);
13251 } else if (isOperationLegalOrCustom(HiOp, VT)) {
13252 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13253 Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
13254 } else if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13255 // Try for a multiplication using a wider type.
13256 unsigned Ext = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13257 SDValue LHSExt = DAG.getNode(Ext, dl, WideVT, LHS);
13258 SDValue RHSExt = DAG.getNode(Ext, dl, WideVT, RHS);
13259 SDValue Res = DAG.getNode(ISD::MUL, dl, WideVT, LHSExt, RHSExt);
13260 Lo = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
13261 SDValue Shifted =
13262 DAG.getNode(ISD::SRA, dl, WideVT, Res,
13263 DAG.getShiftAmountConstant(VTSize, WideVT, dl));
13264 Hi = DAG.getNode(ISD::TRUNCATE, dl, VT, Shifted);
13265 } else if (VT.isVector()) {
13266 return SDValue();
13267 } else {
13268 forceExpandWideMUL(DAG, dl, Signed, LHS, RHS, Lo, Hi);
13269 }
13270
13271 if (Scale == VTSize)
13272 // Result is just the top half since we'd be shifting by the width of the
13273 // operand. Overflow impossible so this works for both UMULFIX and
13274 // UMULFIXSAT.
13275 return Hi;
13276
13277 // The result will need to be shifted right by the scale since both operands
13278 // are scaled. The result is given to us in 2 halves, so we only want part of
13279 // both in the result.
13280 SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
13281 DAG.getShiftAmountConstant(Scale, VT, dl));
13282 if (!Saturating)
13283 return Result;
13284
13285 if (!Signed) {
13286 // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
13287 // widened multiplication) aren't all zeroes.
13288
13289 // Saturate to max if ((Hi >> Scale) != 0),
13290 // which is the same as if (Hi > ((1 << Scale) - 1))
13291 APInt MaxVal = APInt::getMaxValue(VTSize);
13292 SDValue LowMask =
13293 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale), dl, VT);
13294 return getSaturatingSelect(Hi, LowMask, DAG.getConstant(MaxVal, dl, VT),
13295 Result, ISD::SETUGT);
13296 }
13297
13298 // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
13299 // widened multiplication) aren't all ones or all zeroes.
13300
13301 SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
13302 SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
13303
13304 if (Scale == 0) {
13305 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
13306 DAG.getShiftAmountConstant(VTSize - 1, VT, dl));
13307 SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
13308 // Saturated to SatMin if wide product is negative, and SatMax if wide
13309 // product is positive ...
13310 SDValue Zero = DAG.getConstant(0, dl, VT);
13311 SDValue ResultIfOverflow =
13312 getSaturatingSelect(Hi, Zero, SatMin, SatMax, ISD::SETLT);
13313 // ... but only if we overflowed.
13314 return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
13315 }
13316
13317 // We handled Scale==0 above so all the bits to examine is in Hi.
13318
13319 // Saturate to max if ((Hi >> (Scale - 1)) > 0),
13320 // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
13321 SDValue LowMask =
13322 DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1), dl, VT);
13323 // Saturate to min if (Hi >> (Scale - 1)) < -1),
13324 // which is the same as if (HI < (-1 << (Scale - 1))
13325 SDValue HighMask = DAG.getConstant(
13326 APInt::getHighBitsSet(VTSize, VTSize - Scale + 1), dl, VT);
13327 Result = getSaturatingSelect(Hi, LowMask, SatMax, Result, ISD::SETGT);
13328 Result = getSaturatingSelect(Hi, HighMask, SatMin, Result, ISD::SETLT);
13329 return Result;
13330}
13331
13332SDValue
13334 SDValue LHS, SDValue RHS,
13335 unsigned Scale, SelectionDAG &DAG) const {
13336 assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
13337 Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
13338 "Expected a fixed point division opcode");
13339
13340 EVT VT = LHS.getValueType();
13341 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
13342 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
13343 EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13344
13345 // If there is enough room in the type to upscale the LHS or downscale the
13346 // RHS before the division, we can perform it in this type without having to
13347 // resize. For signed operations, the LHS headroom is the number of
13348 // redundant sign bits, and for unsigned ones it is the number of zeroes.
13349 // The headroom for the RHS is the number of trailing zeroes.
13350 unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
13352 unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
13353
13354 // For signed saturating operations, we need to be able to detect true integer
13355 // division overflow; that is, when you have MIN / -EPS. However, this
13356 // is undefined behavior and if we emit divisions that could take such
13357 // values it may cause undesired behavior (arithmetic exceptions on x86, for
13358 // example).
13359 // Avoid this by requiring an extra bit so that we never get this case.
13360 // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
13361 // signed saturating division, we need to emit a whopping 32-bit division.
13362 if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
13363 return SDValue();
13364
13365 unsigned LHSShift = std::min(LHSLead, Scale);
13366 unsigned RHSShift = Scale - LHSShift;
13367
13368 // At this point, we know that if we shift the LHS up by LHSShift and the
13369 // RHS down by RHSShift, we can emit a regular division with a final scaling
13370 // factor of Scale.
13371
13372 if (LHSShift)
13373 LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
13374 DAG.getShiftAmountConstant(LHSShift, VT, dl));
13375 if (RHSShift)
13376 RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
13377 DAG.getShiftAmountConstant(RHSShift, VT, dl));
13378
13379 SDValue Quot;
13380 if (Signed) {
13381 // For signed operations, if the resulting quotient is negative and the
13382 // remainder is nonzero, subtract 1 from the quotient to round towards
13383 // negative infinity.
13384 SDValue Rem;
13385 // FIXME: Ideally we would always produce an SDIVREM here, but if the
13386 // type isn't legal, SDIVREM cannot be expanded. There is no reason why
13387 // we couldn't just form a libcall, but the type legalizer doesn't do it.
13388 if (isTypeLegal(VT) &&
13390 Quot = DAG.getNode(ISD::SDIVREM, dl,
13391 DAG.getVTList(VT, VT),
13392 LHS, RHS);
13393 Rem = Quot.getValue(1);
13394 Quot = Quot.getValue(0);
13395 } else {
13396 Quot = DAG.getNode(ISD::SDIV, dl, VT,
13397 LHS, RHS);
13398 Rem = DAG.getNode(ISD::SREM, dl, VT,
13399 LHS, RHS);
13400 }
13401 SDValue Zero = DAG.getConstant(0, dl, VT);
13402 SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
13403 SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
13404 SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
13405 SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
13406 SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
13407 DAG.getConstant(1, dl, VT));
13408 Quot = DAG.getSelect(dl, VT,
13409 DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
13410 Sub1, Quot);
13411 } else
13412 Quot = DAG.getNode(ISD::UDIV, dl, VT,
13413 LHS, RHS);
13414
13415 return Quot;
13416}
13417
13419 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13420 SDLoc dl(Node);
13421 SDValue LHS = Node->getOperand(0);
13422 SDValue RHS = Node->getOperand(1);
13423 bool IsAdd = Node->getOpcode() == ISD::UADDO;
13424
13425 // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
13426 unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
13427 if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
13428 SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
13429 SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
13430 { LHS, RHS, CarryIn });
13431 Result = SDValue(NodeCarry.getNode(), 0);
13432 Overflow = SDValue(NodeCarry.getNode(), 1);
13433 return;
13434 }
13435
13436 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13437 LHS.getValueType(), LHS, RHS);
13438
13439 EVT ResultType = Node->getValueType(1);
13440 EVT SetCCType = getSetCCResultType(
13441 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13442 SDValue SetCC;
13443 if (IsAdd && isOneConstant(RHS)) {
13444 // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
13445 // the live range of X. We assume comparing with 0 is cheap.
13446 // The general case (X + C) < C is not necessarily beneficial. Although we
13447 // reduce the live range of X, we may introduce the materialization of
13448 // constant C.
13449 SetCC =
13450 DAG.getSetCC(dl, SetCCType, Result,
13451 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
13452 } else if (IsAdd && isAllOnesConstant(RHS)) {
13453 // Special case: uaddo X, -1 overflows if X != 0.
13454 SetCC =
13455 DAG.getSetCC(dl, SetCCType, LHS,
13456 DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
13457 } else {
13459 SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
13460 }
13461 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13462}
13463
13465 SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
13466 SDLoc dl(Node);
13467 SDValue LHS = Node->getOperand(0);
13468 SDValue RHS = Node->getOperand(1);
13469 bool IsAdd = Node->getOpcode() == ISD::SADDO;
13470
13471 Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
13472 LHS.getValueType(), LHS, RHS);
13473
13474 EVT ResultType = Node->getValueType(1);
13475 EVT OType = getSetCCResultType(
13476 DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
13477
13478 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
13479 unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
13480 if (isOperationLegal(OpcSat, LHS.getValueType())) {
13481 SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
13482 SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
13483 Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
13484 return;
13485 }
13486
13487 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
13488
13489 if (IsAdd) {
13490 // For an addition, the result should be less than one of the operands (LHS)
13491 // if and only if the other operand (RHS) is negative, otherwise there will
13492 // be overflow.
13493 SDValue ResultLowerThanLHS =
13494 DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
13495 SDValue RHSNegative = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETLT);
13496 Overflow = DAG.getBoolExtOrTrunc(
13497 DAG.getNode(ISD::XOR, dl, OType, RHSNegative, ResultLowerThanLHS), dl,
13498 ResultType, ResultType);
13499 } else {
13500 // For subtraction, overflow occurs when the signed comparison of operands
13501 // doesn't match the sign of the result.
13502 SDValue LHSLessThanRHS = DAG.getSetCC(dl, OType, LHS, RHS, ISD::SETLT);
13503 SDValue ResultNegative = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETLT);
13504 Overflow = DAG.getBoolExtOrTrunc(
13505 DAG.getNode(ISD::XOR, dl, OType, LHSLessThanRHS, ResultNegative), dl,
13506 ResultType, ResultType);
13507 }
13508}
13509
13511 SDValue &Overflow, SelectionDAG &DAG) const {
13512 SDLoc dl(Node);
13513 EVT VT = Node->getValueType(0);
13514 EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
13515 SDValue LHS = Node->getOperand(0);
13516 SDValue RHS = Node->getOperand(1);
13517 bool isSigned = Node->getOpcode() == ISD::SMULO;
13518
13519 // For power-of-two multiplications we can use a simpler shift expansion.
13520 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
13521 const APInt &C = RHSC->getAPIntValue();
13522 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
13523 if (C.isPowerOf2()) {
13524 // smulo(x, signed_min) is same as umulo(x, signed_min).
13525 bool UseArithShift = isSigned && !C.isMinSignedValue();
13526 SDValue ShiftAmt = DAG.getShiftAmountConstant(C.logBase2(), VT, dl);
13527 Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
13528 Overflow = DAG.getSetCC(dl, SetCCVT,
13529 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
13530 dl, VT, Result, ShiftAmt),
13531 LHS, ISD::SETNE);
13532 return true;
13533 }
13534 }
13535
13536 SDValue BottomHalf;
13537 SDValue TopHalf;
13538 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13539
13540 static const unsigned Ops[2][3] =
13543 if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
13544 BottomHalf = DAG.getNode(Ops[isSigned][0], dl, DAG.getVTList(VT, VT), LHS,
13545 RHS);
13546 TopHalf = BottomHalf.getValue(1);
13547 } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
13548 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
13549 TopHalf = DAG.getNode(Ops[isSigned][1], dl, VT, LHS, RHS);
13550 } else if (isTypeLegal(WideVT)) {
13551 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
13552 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
13553 SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
13554 BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
13555 SDValue ShiftAmt =
13556 DAG.getShiftAmountConstant(VT.getScalarSizeInBits(), WideVT, dl);
13557 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
13558 DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
13559 } else {
13560 if (VT.isVector())
13561 return false;
13562
13563 forceExpandWideMUL(DAG, dl, isSigned, LHS, RHS, BottomHalf, TopHalf);
13564 }
13565
13566 Result = BottomHalf;
13567 if (isSigned) {
13568 SDValue ShiftAmt = DAG.getShiftAmountConstant(
13569 VT.getScalarSizeInBits() - 1, BottomHalf.getValueType(), dl);
13570 SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
13571 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
13572 } else {
13573 Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
13574 DAG.getConstant(0, dl, VT), ISD::SETNE);
13575 }
13576
13577 // Truncate the result if SetCC returns a larger type than needed.
13578 EVT RType = Node->getValueType(1);
13579 if (RType.bitsLT(Overflow.getValueType()))
13580 Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
13581
13582 assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
13583 "Unexpected result type for S/UMULO legalization");
13584 return true;
13585}
13586
13588 SDLoc dl(Node);
13589 EVT VT = Node->getValueType(0);
13590 SDValue LHS = Node->getOperand(0);
13591 SDValue RHS = Node->getOperand(1);
13592 bool IsSigned = Node->getOpcode() == ISD::MULHS;
13593
13594 // Use MUL_LOHI if legal/custom for the original type.
13595 unsigned LoHiOp = IsSigned ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
13596 if (isOperationLegalOrCustom(LoHiOp, VT))
13597 return DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS).getValue(1);
13598
13599 // Use a wide multiply if available.
13600 EVT WideVT = VT.widenIntegerElementType(*DAG.getContext());
13601 if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
13602 unsigned BW = VT.getScalarSizeInBits();
13603 LHS = DAG.getExtOrTrunc(IsSigned, LHS, dl, WideVT);
13604 RHS = DAG.getExtOrTrunc(IsSigned, RHS, dl, WideVT);
13605 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13606 DAG.getNode(ISD::SRL, dl, WideVT,
13607 DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS),
13608 DAG.getShiftAmountConstant(BW, WideVT, dl)));
13609 }
13610
13611 // Let fixed-length vectors be scalarised by the caller.
13612 // Expand everything else with a wide multiply.
13613 if (!VT.isFixedLengthVector()) {
13614 SDValue Lo, Hi;
13615 forceExpandWideMUL(DAG, dl, IsSigned, LHS, RHS, Lo, Hi);
13616 return Hi;
13617 }
13618
13619 return SDValue();
13620}
13621
13623 SDLoc dl(Node);
13624 ISD::NodeType BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13625 SDValue Op = Node->getOperand(0);
13626 SDNodeFlags Flags = Node->getFlags();
13627 EVT VT = Op.getValueType();
13628
13629 // Try to use a shuffle reduction for power of two vectors.
13630 if (VT.isPow2VectorType()) {
13631 // See if the reduction opcode is safe to use with widened types.
13632 bool WidenSrc = false;
13633 switch (Node->getOpcode()) {
13636 case ISD::VECREDUCE_ADD:
13637 case ISD::VECREDUCE_MUL:
13638 case ISD::VECREDUCE_AND:
13639 case ISD::VECREDUCE_OR:
13640 case ISD::VECREDUCE_XOR:
13645 WidenSrc = VT.isFixedLengthVector();
13646 break;
13647 }
13648
13650 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13651 if (!isOperationLegalOrCustom(BaseOpcode, HalfVT)) {
13652 if (WidenSrc && Op.getOpcode() != ISD::BUILD_VECTOR) {
13653 // Attempt to widen the source vectors to a legal op.
13654 EVT WideVT = getTypeToTransformTo(*DAG.getContext(), HalfVT);
13655 if (WideVT.isVector() &&
13656 WideVT.getScalarType() == HalfVT.getScalarType() &&
13657 WideVT.getVectorNumElements() >= HalfVT.getVectorNumElements() &&
13658 isOperationLegalOrCustom(BaseOpcode, WideVT)) {
13659 SDValue Lo, Hi;
13660 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13661 Lo = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Lo, 0);
13662 Hi = DAG.getInsertSubvector(dl, DAG.getPOISON(WideVT), Hi, 0);
13663 Op = DAG.getNode(BaseOpcode, dl, WideVT, Lo, Hi, Flags);
13664 Op = DAG.getExtractSubvector(dl, HalfVT, Op, 0);
13665 VT = HalfVT;
13666 continue;
13667 }
13668 }
13669 break;
13670 }
13671
13672 SDValue Lo, Hi;
13673 std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
13674 Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi, Flags);
13675 VT = HalfVT;
13676
13677 // Stop if splitting is enough to make the reduction legal.
13678 if (isOperationLegalOrCustom(Node->getOpcode(), HalfVT))
13679 return DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Op,
13680 Flags);
13681 }
13682 }
13683
13684 if (VT.isScalableVector())
13686 "Expanding reductions for scalable vectors is undefined.");
13687
13688 EVT EltVT = VT.getVectorElementType();
13689 unsigned NumElts = VT.getVectorNumElements();
13690
13692 DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
13693
13694 SDValue Res = Ops[0];
13695 for (unsigned i = 1; i < NumElts; i++)
13696 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13697
13698 // Result type may be wider than element type.
13699 if (EltVT != Node->getValueType(0))
13700 Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
13701 return Res;
13702}
13703
13705 SDLoc dl(Node);
13706 SDValue AccOp = Node->getOperand(0);
13707 SDValue VecOp = Node->getOperand(1);
13708 SDNodeFlags Flags = Node->getFlags();
13709
13710 EVT VT = VecOp.getValueType();
13711 EVT EltVT = VT.getVectorElementType();
13712
13713 if (VT.isScalableVector())
13715 "Expanding reductions for scalable vectors is undefined.");
13716
13717 unsigned NumElts = VT.getVectorNumElements();
13718
13720 DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
13721
13722 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
13723
13724 SDValue Res = AccOp;
13725 for (unsigned i = 0; i < NumElts; i++)
13726 Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
13727
13728 return Res;
13729}
13730
13732 SelectionDAG &DAG) const {
13733 EVT VT = Node->getValueType(0);
13734 SDLoc dl(Node);
13735 bool isSigned = Node->getOpcode() == ISD::SREM;
13736 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
13737 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
13738 SDValue Dividend = Node->getOperand(0);
13739 SDValue Divisor = Node->getOperand(1);
13740 if (isOperationLegalOrCustom(DivRemOpc, VT)) {
13741 SDVTList VTs = DAG.getVTList(VT, VT);
13742 Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
13743 return true;
13744 }
13745 if (isOperationLegalOrCustom(DivOpc, VT)) {
13746 // X % Y -> X-X/Y*Y
13747 SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
13748 SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
13749 Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13750 return true;
13751 }
13752 return false;
13753}
13754
13756 SelectionDAG &DAG) const {
13757 bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
13758 SDLoc dl(SDValue(Node, 0));
13759 SDValue Src = Node->getOperand(0);
13760
13761 // DstVT is the result type, while SatVT is the size to which we saturate
13762 EVT SrcVT = Src.getValueType();
13763 EVT DstVT = Node->getValueType(0);
13764
13765 EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
13766 unsigned SatWidth = SatVT.getScalarSizeInBits();
13767 unsigned DstWidth = DstVT.getScalarSizeInBits();
13768 assert(SatWidth <= DstWidth &&
13769 "Expected saturation width smaller than result width");
13770
13771 // Determine minimum and maximum integer values and their corresponding
13772 // floating-point values.
13773 APInt MinInt, MaxInt;
13774 if (IsSigned) {
13775 MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
13776 MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
13777 } else {
13778 MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
13779 MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
13780 }
13781
13782 // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
13783 // libcall emission cannot handle this. Large result types will fail.
13784 if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
13785 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
13786 SrcVT = Src.getValueType();
13787 }
13788
13789 const fltSemantics &Sem = SrcVT.getFltSemantics();
13790 APFloat MinFloat(Sem);
13791 APFloat MaxFloat(Sem);
13792
13793 APFloat::opStatus MinStatus =
13794 MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
13795 APFloat::opStatus MaxStatus =
13796 MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
13797 bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
13798 !(MaxStatus & APFloat::opStatus::opInexact);
13799
13800 SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
13801 SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
13802
13803 // If the integer bounds are exactly representable as floats and min/max are
13804 // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
13805 // of comparisons and selects.
13806 auto EmitMinMax = [&](unsigned MinOpcode, unsigned MaxOpcode,
13807 bool MayPropagateNaN) {
13808 bool MinMaxLegal = isOperationLegalOrCustom(MinOpcode, SrcVT) &&
13809 isOperationLegalOrCustom(MaxOpcode, SrcVT);
13810 if (!MinMaxLegal)
13811 return SDValue();
13812
13813 SDValue Clamped = Src;
13814
13815 // Clamp Src by MinFloat from below. If !MayPropagateNaN and Src is NaN
13816 // then the result is MinFloat.
13817 Clamped = DAG.getNode(MaxOpcode, dl, SrcVT, Clamped, MinFloatNode);
13818 // Clamp by MaxFloat from above. If !MayPropagateNaN then NaN cannot occur.
13819 Clamped = DAG.getNode(MinOpcode, dl, SrcVT, Clamped, MaxFloatNode);
13820 // Convert clamped value to integer.
13821 SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
13822 dl, DstVT, Clamped);
13823
13824 // If !MayPropagateNan and the conversion is unsigned case we're done,
13825 // because we mapped NaN to MinFloat, which will cast to zero.
13826 if (!MayPropagateNaN && !IsSigned)
13827 return FpToInt;
13828
13829 // Otherwise, select 0 if Src is NaN.
13830 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13831 EVT SetCCVT =
13832 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13833 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13834 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
13835 };
13836 if (AreExactFloatBounds) {
13837 if (SDValue Res = EmitMinMax(ISD::FMINIMUMNUM, ISD::FMAXIMUMNUM,
13838 /*MayPropagateNaN=*/false))
13839 return Res;
13840 // These may propagate NaN for sNaN operands.
13841 if (SDValue Res =
13842 EmitMinMax(ISD::FMINNUM, ISD::FMAXNUM, /*MayPropagateNaN=*/true))
13843 return Res;
13844 // These always propagate NaN.
13845 if (SDValue Res =
13846 EmitMinMax(ISD::FMINIMUM, ISD::FMAXIMUM, /*MayPropagateNaN=*/true))
13847 return Res;
13848 }
13849
13850 SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
13851 SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
13852
13853 // Result of direct conversion. The assumption here is that the operation is
13854 // non-trapping and it's fine to apply it to an out-of-range value if we
13855 // select it away later.
13856 SDValue FpToInt =
13857 DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
13858
13859 SDValue Select = FpToInt;
13860
13861 EVT SetCCVT =
13862 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
13863
13864 // If Src ULT MinFloat, select MinInt. In particular, this also selects
13865 // MinInt if Src is NaN.
13866 SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
13867 Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
13868 // If Src OGT MaxFloat, select MaxInt.
13869 SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
13870 Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
13871
13872 // In the unsigned case we are done, because we mapped NaN to MinInt, which
13873 // is already zero.
13874 if (!IsSigned)
13875 return Select;
13876
13877 // Otherwise, select 0 if Src is NaN.
13878 SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
13879 SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
13880 return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
13881}
13882
13884 const SDLoc &dl,
13885 SelectionDAG &DAG) const {
13886 EVT OperandVT = Op.getValueType();
13887 if (OperandVT.getScalarType() == ResultVT.getScalarType())
13888 return Op;
13889 EVT ResultIntVT = ResultVT.changeTypeToInteger();
13890 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13891 // can induce double-rounding which may alter the results. We can
13892 // correct for this using a trick explained in: Boldo, Sylvie, and
13893 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13894 // World Congress. 2005.
13895 SDValue Narrow = DAG.getFPExtendOrRound(Op, dl, ResultVT);
13896 SDValue NarrowAsWide = DAG.getFPExtendOrRound(Narrow, dl, OperandVT);
13897
13898 // We can keep the narrow value as-is if narrowing was exact (no
13899 // rounding error), the wide value was NaN (the narrow value is also
13900 // NaN and should be preserved) or if we rounded to the odd value.
13901 SDValue NarrowBits = DAG.getNode(ISD::BITCAST, dl, ResultIntVT, Narrow);
13902 SDValue One = DAG.getConstant(1, dl, ResultIntVT);
13903 SDValue NegativeOne = DAG.getAllOnesConstant(dl, ResultIntVT);
13904 SDValue And = DAG.getNode(ISD::AND, dl, ResultIntVT, NarrowBits, One);
13905 EVT ResultIntVTCCVT = getSetCCResultType(
13906 DAG.getDataLayout(), *DAG.getContext(), And.getValueType());
13907 SDValue Zero = DAG.getConstant(0, dl, ResultIntVT);
13908 // The result is already odd so we don't need to do anything.
13909 SDValue AlreadyOdd = DAG.getSetCC(dl, ResultIntVTCCVT, And, Zero, ISD::SETNE);
13910
13911 EVT WideSetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13912 Op.getValueType());
13913 // We keep results which are exact, odd or NaN.
13914 SDValue KeepNarrow =
13915 DAG.getSetCC(dl, WideSetCCVT, Op, NarrowAsWide, ISD::SETUEQ);
13916 KeepNarrow = DAG.getNode(ISD::OR, dl, WideSetCCVT, KeepNarrow, AlreadyOdd);
13917 // We morally performed a round-down if AbsNarrow is smaller than
13918 // AbsWide.
13919 SDValue AbsWide = DAG.getNode(ISD::FABS, dl, OperandVT, Op);
13920 SDValue AbsNarrowAsWide = DAG.getNode(ISD::FABS, dl, OperandVT, NarrowAsWide);
13921 SDValue NarrowIsRd =
13922 DAG.getSetCC(dl, WideSetCCVT, AbsWide, AbsNarrowAsWide, ISD::SETOGT);
13923 // If the narrow value is odd or exact, pick it.
13924 // Otherwise, narrow is even and corresponds to either the rounded-up
13925 // or rounded-down value. If narrow is the rounded-down value, we want
13926 // the rounded-up value as it will be odd.
13927 SDValue Adjust = DAG.getSelect(dl, ResultIntVT, NarrowIsRd, One, NegativeOne);
13928 SDValue Adjusted = DAG.getNode(ISD::ADD, dl, ResultIntVT, NarrowBits, Adjust);
13929 Op = DAG.getSelect(dl, ResultIntVT, KeepNarrow, NarrowBits, Adjusted);
13930 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Op);
13931}
13932
13934 assert(Node->getOpcode() == ISD::FP_ROUND && "Unexpected opcode!");
13935 SDValue Op = Node->getOperand(0);
13936 EVT VT = Node->getValueType(0);
13937 SDLoc dl(Node);
13938 if (VT.getScalarType() == MVT::bf16) {
13939 if (Node->getConstantOperandVal(1) == 1) {
13940 return DAG.getNode(ISD::FP_TO_BF16, dl, VT, Node->getOperand(0));
13941 }
13942 EVT OperandVT = Op.getValueType();
13943
13944 // We are rounding binary64/binary128 -> binary32 -> bfloat16. This
13945 // can induce double-rounding which may alter the results. We can
13946 // correct for this using a trick explained in: Boldo, Sylvie, and
13947 // Guillaume Melquiond. "When double rounding is odd." 17th IMACS
13948 // World Congress. 2005.
13949 EVT F32 = VT.changeElementType(*DAG.getContext(), MVT::f32);
13950 EVT I32 = F32.changeTypeToInteger();
13951 Op = expandRoundInexactToOdd(F32, Op, dl, DAG);
13952 Op = DAG.getNode(ISD::BITCAST, dl, I32, Op);
13953
13954 // Factor in the contribution of the low 16 bits.
13955 SDValue One = DAG.getConstant(1, dl, I32);
13956 SDValue Lsb = DAG.getNode(ISD::SRL, dl, I32, Op,
13957 DAG.getShiftAmountConstant(16, I32, dl));
13958 Lsb = DAG.getNode(ISD::AND, dl, I32, Lsb, One);
13959 SDValue RoundingBias =
13960 DAG.getNode(ISD::ADD, dl, I32, Lsb, DAG.getConstant(0x7fff, dl, I32));
13961 SDValue Add = DAG.getNode(ISD::ADD, dl, I32, Op, RoundingBias);
13962
13963 // Don't round if we had a NaN, we don't want to turn 0x7fffffff into
13964 // 0x80000000.
13965 if (!Node->getFlags().hasNoNaNs() &&
13966 !DAG.isKnownNeverNaN(Node->getOperand(0))) {
13967 // Conversions should set NaN's quiet bit. This also prevents NaNs from
13968 // turning into infinities.
13969 SDValue NaN =
13970 DAG.getNode(ISD::OR, dl, I32, Op, DAG.getConstant(0x400000, dl, I32));
13971
13972 SDValue IsNaN = DAG.getSetCC(
13973 dl,
13974 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), OperandVT),
13975 Node->getOperand(0), Node->getOperand(0), ISD::SETUO);
13976 Add = DAG.getSelect(dl, I32, IsNaN, NaN, Add);
13977 }
13978
13979 // Now that we have rounded, shift the bits into position.
13980 Op = DAG.getNode(ISD::SRL, dl, I32, Add,
13981 DAG.getShiftAmountConstant(16, I32, dl));
13982 EVT I16 = I32.changeElementType(*DAG.getContext(), MVT::i16);
13983 Op = DAG.getNode(ISD::TRUNCATE, dl, I16, Op);
13984 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13985 }
13986 return SDValue();
13987}
13988
13991 SelectionDAG &DAG) const {
13992 assert(Node->getOpcode() == ISD::VECTOR_INTERLEAVE && "Unexpected opcode");
13993 EVT VT = Node->getValueType(0);
13994 unsigned Factor = Node->getNumOperands();
13995 SDLoc DL(Node);
13996
13997 if (Factor > 2 && Factor % 2 == 0) {
13998 SmallVector<EVT> HalfVTs(Factor / 2, VT);
13999 SmallVector<SDValue, 8> LOps, ROps;
14000 // Interleave so we have 2 factors per result:
14001 // a0a1 b0b1 c0c1 d0d1 -> [a0c0 b0d0] [a1c1 b1d1]
14002 for (unsigned I = 0; I < Factor / 2; I++) {
14003 SDValue Interleave =
14004 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, {VT, VT},
14005 {Node->getOperand(I), Node->getOperand(I + Factor / 2)});
14006 LOps.push_back(Interleave.getValue(0));
14007 ROps.push_back(Interleave.getValue(1));
14008 }
14009 // Interleave at Factor/2:
14010 // [a0c0 b0d0] [a1c1 b1d1] -> a0b0 c0d0 a1b1 c1d1
14011 SDValue L = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, LOps);
14012 SDValue R = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, HalfVTs, ROps);
14013 for (unsigned I = 0; I < Factor / 2; I++)
14014 Results.push_back(L.getValue(I));
14015 for (unsigned I = 0; I < Factor / 2; I++)
14016 Results.push_back(R.getValue(I));
14017 return;
14018 }
14019
14020 if (!VT.isFixedLengthVector())
14021 return;
14022
14023 unsigned NumElts = VT.getVectorNumElements();
14024 EVT EltVT = VT.getVectorElementType();
14025
14026 // A factor of two needs only same-width, two-input shuffles.
14027 if (Factor == 2) {
14028 SmallVector<int, 8> Mask = createInterleaveMask(NumElts, Factor);
14029 for (unsigned I = 0; I != Factor; ++I)
14030 Results.push_back(DAG.getVectorShuffle(
14031 VT, DL, Node->getOperand(0), Node->getOperand(1),
14032 ArrayRef<int>(Mask).slice(I * NumElts, NumElts)));
14033 return;
14034 }
14035
14036 SmallVector<SDValue> InterleavedElts;
14037 InterleavedElts.reserve(Factor * NumElts);
14038 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
14039 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
14040 InterleavedElts.push_back(DAG.getExtractVectorElt(
14041 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
14042
14043 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx)
14044 Results.push_back(DAG.getBuildVector(
14045 VT, DL, ArrayRef(InterleavedElts).slice(ResultIdx * NumElts, NumElts)));
14046}
14047
14050 SelectionDAG &DAG) const {
14051 assert(Node->getOpcode() == ISD::VECTOR_DEINTERLEAVE && "Unexpected opcode");
14052 EVT VT = Node->getValueType(0);
14053 unsigned Factor = Node->getNumOperands();
14054 SDLoc DL(Node);
14055
14056 if (Factor > 2 && Factor % 2 == 0) {
14058 SmallVector<EVT> HalfVTs(Factor / 2, VT);
14059 // Deinterleave at Factor/2 so each result contains two factors interleaved:
14060 // a0b0 c0d0 a1b1 c1d1 -> [a0c0 b0d0] [a1c1 b1d1]
14061 SDValue L = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
14062 ArrayRef(Ops).take_front(Factor / 2));
14063 SDValue R = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL, HalfVTs,
14064 ArrayRef(Ops).take_back(Factor / 2));
14065 Results.resize(Factor);
14066 // Deinterleave the 2 factors out:
14067 // [a0c0 a1c1] [b0d0 b1d1] -> a0a1 b0b1 c0c1 d0d1
14068 for (unsigned I = 0; I < Factor / 2; ++I) {
14070 {L.getValue(I), R.getValue(I)});
14071 Results[I] = Deinterleave.getValue(0);
14072 Results[I + Factor / 2] = Deinterleave.getValue(1);
14073 }
14074 return;
14075 }
14076
14077 if (!VT.isFixedLengthVector())
14078 return;
14079
14080 unsigned NumElts = VT.getVectorNumElements();
14081 EVT EltVT = VT.getVectorElementType();
14082
14083 // A factor of two needs only same-width, two-input shuffles.
14084 if (Factor == 2) {
14085 for (unsigned I = 0; I != Factor; ++I)
14086 Results.push_back(
14087 DAG.getVectorShuffle(VT, DL, Node->getOperand(0), Node->getOperand(1),
14088 createStrideMask(I, Factor, NumElts)));
14089 return;
14090 }
14091
14092 SmallVector<SDValue> ConcatElts;
14093 ConcatElts.reserve(Factor * NumElts);
14094 for (unsigned OperandIdx = 0; OperandIdx != Factor; ++OperandIdx)
14095 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
14096 ConcatElts.push_back(DAG.getExtractVectorElt(
14097 DL, EltVT, Node->getOperand(OperandIdx), EltIdx));
14098
14099 SmallVector<SDValue> DeinterleavedElts;
14100 DeinterleavedElts.reserve(Factor * NumElts);
14101 for (unsigned ResultIdx = 0; ResultIdx != Factor; ++ResultIdx) {
14102 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx)
14103 DeinterleavedElts.push_back(ConcatElts[ResultIdx + EltIdx * Factor]);
14104 Results.push_back(DAG.getBuildVector(
14105 VT, DL,
14106 ArrayRef(DeinterleavedElts).slice(ResultIdx * NumElts, NumElts)));
14107 }
14108}
14109
14111 SelectionDAG &DAG) const {
14112 assert((Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT ||
14113 Node->getOpcode() == ISD::VECTOR_SPLICE_RIGHT) &&
14114 "Unexpected opcode!");
14115 assert((Node->getValueType(0).isScalableVector() ||
14116 !isa<ConstantSDNode>(Node->getOperand(2))) &&
14117 "Fixed length vector types with constant offsets expected to use "
14118 "SHUFFLE_VECTOR!");
14119
14120 EVT VT = Node->getValueType(0);
14121 SDValue V1 = Node->getOperand(0);
14122 SDValue V2 = Node->getOperand(1);
14123 SDValue Offset = Node->getOperand(2);
14124 SDLoc DL(Node);
14125
14126 // Expand through memory thusly:
14127 // Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
14128 // Store V1, Ptr
14129 // Store V2, Ptr + sizeof(V1)
14130 // if (VECTOR_SPLICE_LEFT)
14131 // Ptr = Ptr + (Offset * sizeof(VT.Elt))
14132 // else
14133 // Ptr = Ptr + sizeof(V1) - (Offset * size(VT.Elt))
14134 // Res = Load Ptr
14135
14136 Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
14137
14139 VT.getVectorElementCount() * 2);
14140 SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
14141 EVT PtrVT = StackPtr.getValueType();
14142 auto &MF = DAG.getMachineFunction();
14143 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
14144 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
14145
14146 // Store the lo part of CONCAT_VECTORS(V1, V2)
14147 SDValue StoreV1 =
14148 DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo, Alignment);
14149 // Store the hi part of CONCAT_VECTORS(V1, V2)
14150 SDValue VTBytes = DAG.getTypeSize(DL, PtrVT, VT.getStoreSize());
14151 SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, VTBytes);
14152 SDValue StoreV2 =
14153 DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo, Alignment);
14154
14155 // NOTE: TrailingBytes must be clamped so as not to read outside of V1:V2.
14156 SDValue EltByteSize =
14157 DAG.getTypeSize(DL, PtrVT, VT.getVectorElementType().getStoreSize());
14158 Offset = DAG.getZExtOrTrunc(Offset, DL, PtrVT);
14159 SDValue TrailingBytes = DAG.getNode(ISD::MUL, DL, PtrVT, Offset, EltByteSize);
14160
14161 TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VTBytes);
14162
14163 if (Node->getOpcode() == ISD::VECTOR_SPLICE_LEFT)
14164 StackPtr = DAG.getMemBasePlusOffset(StackPtr, TrailingBytes, DL);
14165 else
14166 StackPtr = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
14167
14168 // Load the spliced result
14169 return DAG.getLoad(VT, DL, StoreV2, StackPtr,
14171}
14172
14174 SelectionDAG &DAG) const {
14175 SDLoc DL(Node);
14176 SDValue Vec = Node->getOperand(0);
14177 SDValue Mask = Node->getOperand(1);
14178 SDValue Passthru = Node->getOperand(2);
14179
14180 EVT VecVT = Vec.getValueType();
14181 EVT ScalarVT = VecVT.getScalarType();
14182 EVT MaskVT = Mask.getValueType();
14183 EVT MaskScalarVT = MaskVT.getScalarType();
14184
14185 // Needs to be handled by targets that have scalable vector types.
14186 if (VecVT.isScalableVector())
14187 report_fatal_error("Cannot expand masked_compress for scalable vectors.");
14188
14189 Align Alignment = DAG.getReducedAlign(VecVT, /*UseABI=*/false);
14190 SDValue StackPtr = DAG.CreateStackTemporary(VecVT.getStoreSize(), Alignment);
14191 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
14192 MachinePointerInfo PtrInfo =
14194
14195 MVT PositionVT = getVectorIdxTy(DAG.getDataLayout());
14196 SDValue Chain = DAG.getEntryNode();
14197 SDValue OutPos = DAG.getConstant(0, DL, PositionVT);
14198
14199 bool HasPassthru = !Passthru.isUndef();
14200
14201 // If we have a passthru vector, store it on the stack, overwrite the matching
14202 // positions and then re-write the last element that was potentially
14203 // overwritten even though mask[i] = false.
14204 if (HasPassthru)
14205 Chain = DAG.getStore(Chain, DL, Passthru, StackPtr, PtrInfo, Alignment);
14206
14207 SDValue LastWriteVal;
14208 APInt PassthruSplatVal;
14209 bool IsSplatPassthru =
14210 ISD::isConstantSplatVector(Passthru.getNode(), PassthruSplatVal);
14211
14212 if (IsSplatPassthru) {
14213 // As we do not know which position we wrote to last, we cannot simply
14214 // access that index from the passthru vector. So we first check if passthru
14215 // is a splat vector, to use any element ...
14216 LastWriteVal = DAG.getConstant(PassthruSplatVal, DL, ScalarVT);
14217 } else if (HasPassthru) {
14218 // ... if it is not a splat vector, we need to get the passthru value at
14219 // position = popcount(mask) and re-load it from the stack before it is
14220 // overwritten in the loop below.
14221 EVT PopcountVT = ScalarVT.changeTypeToInteger();
14222 SDValue Popcount = DAG.getNode(
14224 MaskVT.changeVectorElementType(*DAG.getContext(), MVT::i1), Mask);
14225 Popcount = DAG.getNode(
14227 MaskVT.changeVectorElementType(*DAG.getContext(), PopcountVT),
14228 Popcount);
14229 Popcount = DAG.getNode(ISD::VECREDUCE_ADD, DL, PopcountVT, Popcount);
14230 SDValue LastElmtPtr =
14231 getVectorElementPointer(DAG, StackPtr, VecVT, Popcount);
14232 LastWriteVal = DAG.getLoad(
14233 ScalarVT, DL, Chain, LastElmtPtr,
14235 Chain = LastWriteVal.getValue(1);
14236 }
14237
14238 unsigned NumElms = VecVT.getVectorNumElements();
14239 for (unsigned I = 0; I < NumElms; I++) {
14240 SDValue ValI = DAG.getExtractVectorElt(DL, ScalarVT, Vec, I);
14241 SDValue OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14242 Chain = DAG.getStore(
14243 Chain, DL, ValI, OutPtr,
14245
14246 // Get the mask value and add it to the current output position. This
14247 // either increments by 1 if MaskI is true or adds 0 otherwise.
14248 // Freeze in case we have poison/undef mask entries.
14249 SDValue MaskI = DAG.getExtractVectorElt(DL, MaskScalarVT, Mask, I);
14250 MaskI = DAG.getFreeze(MaskI);
14251 MaskI = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, MaskI);
14252 MaskI = DAG.getNode(ISD::ZERO_EXTEND, DL, PositionVT, MaskI);
14253 OutPos = DAG.getNode(ISD::ADD, DL, PositionVT, OutPos, MaskI);
14254
14255 if (HasPassthru && I == NumElms - 1) {
14256 SDValue EndOfVector =
14257 DAG.getConstant(VecVT.getVectorNumElements() - 1, DL, PositionVT);
14258 SDValue AllLanesSelected =
14259 DAG.getSetCC(DL, MVT::i1, OutPos, EndOfVector, ISD::CondCode::SETUGT);
14260 OutPos = DAG.getNode(ISD::UMIN, DL, PositionVT, OutPos, EndOfVector);
14261 OutPtr = getVectorElementPointer(DAG, StackPtr, VecVT, OutPos);
14262
14263 // Re-write the last ValI if all lanes were selected. Otherwise,
14264 // overwrite the last write it with the passthru value.
14265 LastWriteVal = DAG.getSelect(DL, ScalarVT, AllLanesSelected, ValI,
14266 LastWriteVal, SDNodeFlags::Unpredictable);
14267 Chain = DAG.getStore(
14268 Chain, DL, LastWriteVal, OutPtr,
14270 }
14271 }
14272
14273 return DAG.getLoad(VecVT, DL, Chain, StackPtr, PtrInfo, Alignment);
14274}
14275
14277 SDLoc DL(Node);
14278 EVT VT = Node->getValueType(0);
14279 SDValue Op = Node->getOperand(0);
14280 ElementCount EC = Op.getValueType().getVectorElementCount();
14281
14282 bool ZeroIsPoison = Node->getOpcode() == ISD::CTTZ_ELTS_ZERO_POISON;
14283 auto [Mask, StepVec] = getLegalMaskAndStepVector(Op, ZeroIsPoison, DL, DAG);
14284
14285 // No legal step vector: split mask in half and recombine results.
14286 // LoNumElts uses the non-poison CTTZ_ELTS so its result is well-defined
14287 // (== LoNumElts when no active lane), allowing the SETNE comparison.
14288 // Result: (ResLo != LoNumElts) ? ResLo : (LoNumElts + ResHi)
14289 if (!StepVec) {
14290 EVT ResVT = Node->getValueType(0);
14291 auto [MaskLo, MaskHi] = DAG.SplitVector(Op, DL);
14292 SDValue LoNumElts = DAG.getElementCount(
14293 DL, ResVT, MaskLo.getValueType().getVectorElementCount());
14294 SDValue ResLo = DAG.getNode(ISD::CTTZ_ELTS, DL, ResVT, MaskLo);
14295 SDValue ResHi = DAG.getNode(Node->getOpcode(), DL, ResVT, MaskHi);
14296 SDValue ResLoNotNumElts = DAG.getSetCC(
14297 DL, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ResVT),
14298 ResLo, LoNumElts, ISD::SETNE);
14299 // Per LangRef, ResVT must be wide enough to hold the total element count,
14300 // so the sum cannot wrap as an unsigned add. NSW is not guaranteed since
14301 // the count is only required to fit unsigned.
14302 SDValue Sum = DAG.getNode(ISD::ADD, DL, ResVT, LoNumElts, ResHi,
14304 return DAG.getSelect(DL, ResVT, ResLoNotNumElts, ResLo, Sum);
14305 }
14306
14307 EVT StepVecVT = StepVec.getValueType();
14308 EVT StepVT = StepVecVT.getVectorElementType();
14309
14310 // Promote the scalar result type early to avoid redundant zexts.
14312 StepVT = getTypeToTransformTo(*DAG.getContext(), StepVT);
14313
14314 SDValue VL = DAG.getElementCount(DL, StepVT, EC);
14315 SDValue SplatVL = DAG.getSplat(StepVecVT, DL, VL);
14316 StepVec = DAG.getNode(ISD::SUB, DL, StepVecVT, SplatVL, StepVec);
14317 SDValue Zeroes = DAG.getConstant(0, DL, StepVecVT);
14318 SDValue Select = DAG.getSelect(DL, StepVecVT, Mask, StepVec, Zeroes);
14320 StepVecVT.getVectorElementType(), Select);
14321 SDValue Sub = DAG.getNode(ISD::SUB, DL, StepVT, VL,
14322 DAG.getZExtOrTrunc(Max, DL, StepVT));
14323
14324 return DAG.getZExtOrTrunc(Sub, DL, VT);
14325}
14326
14328 SDLoc DL(N);
14329 SDValue Source = N->getOperand(0);
14330 SDValue Needle = N->getOperand(1);
14331 SDValue Mask = N->getOperand(2);
14332 EVT SourceVT = Source.getValueType();
14333 EVT NeedleVT = Needle.getValueType();
14334 EVT ResVT = N->getValueType(0);
14335 EVT CmpVT =
14336 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SourceVT);
14337
14338 assert(NeedleVT.isFixedLengthVector() && "Needle must be a fixed vector");
14339
14340 SDValue Ret = DAG.getConstant(0, DL, CmpVT);
14341 EVT NeedleEltVT = NeedleVT.getVectorElementType();
14342 for (unsigned I = 0, E = NeedleVT.getVectorNumElements(); I != E; ++I) {
14343 SDValue Splat;
14344 if (NeedleVT == SourceVT) {
14345 // Prefer a shuffle over scalar extracts + splat for fixed vectors.
14346 Splat = DAG.getVectorShuffle(
14347 SourceVT, DL, Needle, DAG.getUNDEF(SourceVT),
14349 } else {
14350 SDValue NeedleElt = DAG.getExtractVectorElt(DL, NeedleEltVT, Needle, I);
14351 Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, SourceVT, NeedleElt);
14352 }
14353 SDValue Cmp = DAG.getSetCC(DL, CmpVT, Source, Splat, ISD::SETEQ);
14354 Ret = DAG.getNode(ISD::OR, DL, CmpVT, Ret, Cmp);
14355 }
14356
14357 EVT UseVT = ResVT;
14358 // If the result is immediately truncated, only extend to that type (to avoid
14359 // unnecessary sign/zero extends).
14360 if (N->hasOneUse() && N->user_begin()->getOpcode() == ISD::TRUNCATE)
14361 UseVT = N->user_begin()->getValueType(0);
14362
14363 Mask = DAG.getBoolExtOrTrunc(Mask, DL, UseVT, Mask.getValueType());
14364 Ret = DAG.getBoolExtOrTrunc(Ret, DL, UseVT, Ret.getValueType());
14365
14366 Ret = DAG.getNode(ISD::AND, DL, UseVT, Ret, Mask);
14367 if (UseVT != ResVT)
14368 Ret = DAG.getNode(ISD::ANY_EXTEND, DL, ResVT, Ret);
14369 return Ret;
14370}
14371
14373 SelectionDAG &DAG) const {
14374 SDLoc DL(N);
14375 SDValue Acc = N->getOperand(0);
14376 SDValue MulLHS = N->getOperand(1);
14377 SDValue MulRHS = N->getOperand(2);
14378 EVT AccVT = Acc.getValueType();
14379 EVT MulOpVT = MulLHS.getValueType();
14380
14381 EVT ExtMulOpVT =
14383 MulOpVT.getVectorElementCount());
14384
14385 unsigned ExtOpcLHS, ExtOpcRHS;
14386 switch (N->getOpcode()) {
14387 default:
14388 llvm_unreachable("Unexpected opcode");
14390 ExtOpcLHS = ExtOpcRHS = ISD::ZERO_EXTEND;
14391 break;
14393 ExtOpcLHS = ExtOpcRHS = ISD::SIGN_EXTEND;
14394 break;
14396 ExtOpcLHS = ISD::SIGN_EXTEND;
14397 ExtOpcRHS = ISD::ZERO_EXTEND;
14398 break;
14400 ExtOpcLHS = ExtOpcRHS = ISD::FP_EXTEND;
14401 break;
14402 }
14403
14404 // A wide partial reduction is built from a ladder of narrower ones, a rung
14405 // at a time, each halving the element count and doubling the width.
14406 unsigned Opc = N->getOpcode();
14407 ElementCount MulEC = MulOpVT.getVectorElementCount();
14408 ElementCount AccEC = AccVT.getVectorElementCount();
14409 unsigned CountRatio =
14410 MulEC.hasKnownScalarFactor(AccEC) ? MulEC.getKnownScalarFactor(AccEC) : 0;
14411 unsigned WidthRatio =
14412 AccVT.getScalarSizeInBits() / MulOpVT.getScalarSizeInBits();
14413 if (Opc != ISD::PARTIAL_REDUCE_FMLA && CountRatio > 2 && WidthRatio >= 2) {
14414 LLVMContext &Ctx = *DAG.getContext();
14415 EVT ProdVT = MulOpVT.widenIntegerVectorElementType(Ctx);
14416
14417 // A pure reduction peels one rung and re-enters.
14418 if (llvm::isOneOrOneSplat(MulRHS)) {
14419 EVT RungVT = ProdVT.getHalfNumVectorElementsVT(Ctx);
14420 return DAG.getNode(Opc, DL, AccVT, Acc,
14421 DAG.getNode(Opc, DL, RungVT,
14422 DAG.getConstant(0, DL, RungVT), MulLHS,
14423 MulRHS),
14424 DAG.getConstant(1, DL, RungVT));
14425 }
14426
14427 // A multiply widens the products by one rung, which legalizes back into a
14428 // widening multiply per half, and the ladder re-enters as a plain sum.
14429 SDValue Prod = DAG.getNode(ISD::MUL, DL, ProdVT,
14430 DAG.getNode(ExtOpcLHS, DL, ProdVT, MulLHS),
14431 DAG.getNode(ExtOpcRHS, DL, ProdVT, MulRHS));
14432 auto [Lo, Hi] = DAG.SplitVector(Prod, DL);
14433 SDValue One = DAG.getConstant(1, DL, Lo.getValueType());
14434
14435 // The halves meet at the narrowest rung, so the accumulator is added once.
14436 EVT MidVT = Lo.getValueType()
14437 .widenIntegerVectorElementType(Ctx)
14438 .getHalfNumVectorElementsVT(Ctx);
14440 return DAG.getNode(Opc, DL, AccVT,
14441 DAG.getNode(Opc, DL, AccVT, Acc, Lo, One), Hi, One);
14442 SDValue Mid =
14443 DAG.getNode(Opc, DL, MidVT, DAG.getConstant(0, DL, MidVT), Lo, One);
14444 Mid = DAG.getNode(Opc, DL, MidVT, Mid, Hi, One);
14445 return DAG.getNode(Opc, DL, AccVT, Acc, Mid, DAG.getConstant(1, DL, MidVT));
14446 }
14447
14448 if (ExtMulOpVT != MulOpVT) {
14449 MulLHS = DAG.getNode(ExtOpcLHS, DL, ExtMulOpVT, MulLHS);
14450 MulRHS = DAG.getNode(ExtOpcRHS, DL, ExtMulOpVT, MulRHS);
14451 }
14452 SDValue Input = MulLHS;
14453 // Maintain the FP flags (if any).
14454 SDNodeFlags Flags = N->getFlags();
14455 if (N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA) {
14456 if (!llvm::isOneOrOneSplatFP(MulRHS))
14457 Input = DAG.getNode(ISD::FMUL, DL, ExtMulOpVT, MulLHS, MulRHS, Flags);
14458 } else if (!llvm::isOneOrOneSplat(MulRHS)) {
14459 Input = DAG.getNode(ISD::MUL, DL, ExtMulOpVT, MulLHS, MulRHS);
14460 }
14461
14462 unsigned Stride = AccVT.getVectorMinNumElements();
14463 unsigned ScaleFactor = MulOpVT.getVectorMinNumElements() / Stride;
14464
14465 // Collect all of the subvectors
14466 std::deque<SDValue> Subvectors = {Acc};
14467 for (unsigned I = 0; I < ScaleFactor; I++)
14468 Subvectors.push_back(DAG.getExtractSubvector(DL, AccVT, Input, I * Stride));
14469
14470 unsigned FlatNode =
14471 N->getOpcode() == ISD::PARTIAL_REDUCE_FMLA ? ISD::FADD : ISD::ADD;
14472
14473 // Flatten the subvector tree
14474 while (Subvectors.size() > 1) {
14475 Subvectors.push_back(DAG.getNode(FlatNode, DL, AccVT,
14476 {Subvectors[0], Subvectors[1]}, Flags));
14477 Subvectors.pop_front();
14478 Subvectors.pop_front();
14479 }
14480
14481 assert(Subvectors.size() == 1 &&
14482 "There should only be one subvector after tree flattening");
14483
14484 return Subvectors[0];
14485}
14486
14487/// Given a store node \p StoreNode, return true if it is safe to fold that node
14488/// into \p FPNode, which expands to a library call with output pointers.
14490 SDNode *FPNode) {
14492 SmallVector<const SDNode *, 8> DeferredNodes;
14494
14495 // Skip FPNode use by StoreNode (that's the use we want to fold into FPNode).
14496 for (SDValue Op : StoreNode->ops())
14497 if (Op.getNode() != FPNode)
14498 Worklist.push_back(Op.getNode());
14499
14501 while (!Worklist.empty()) {
14502 const SDNode *Node = Worklist.pop_back_val();
14503 auto [_, Inserted] = Visited.insert(Node);
14504 if (!Inserted)
14505 continue;
14506
14507 if (MaxSteps > 0 && Visited.size() >= MaxSteps)
14508 return false;
14509
14510 // Reached the FPNode (would result in a cycle).
14511 // OR Reached CALLSEQ_START (would result in nested call sequences).
14512 if (Node == FPNode || Node->getOpcode() == ISD::CALLSEQ_START)
14513 return false;
14514
14515 if (Node->getOpcode() == ISD::CALLSEQ_END) {
14516 // Defer looking into call sequences (so we can check we're outside one).
14517 // We still need to look through these for the predecessor check.
14518 DeferredNodes.push_back(Node);
14519 continue;
14520 }
14521
14522 for (SDValue Op : Node->ops())
14523 Worklist.push_back(Op.getNode());
14524 }
14525
14526 // True if we're outside a call sequence and don't have the FPNode as a
14527 // predecessor. No cycles or nested call sequences possible.
14528 return !SDNode::hasPredecessorHelper(FPNode, Visited, DeferredNodes,
14529 MaxSteps);
14530}
14531
14533 SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node,
14535 std::optional<unsigned> CallRetResNo) const {
14536 if (LC == RTLIB::UNKNOWN_LIBCALL)
14537 return false;
14538
14539 RTLIB::LibcallImpl LibcallImpl =
14541 if (LibcallImpl == RTLIB::Unsupported)
14542 return false;
14543
14544 LLVMContext &Ctx = *DAG.getContext();
14545 EVT VT = Node->getValueType(0);
14546 unsigned NumResults = Node->getNumValues();
14547
14548 // Find users of the node that store the results (and share input chains). The
14549 // destination pointers can be used instead of creating stack allocations.
14550 SDValue StoresInChain;
14551 SmallVector<StoreSDNode *, 2> ResultStores(NumResults);
14552 for (SDNode *User : Node->users()) {
14554 continue;
14555 auto *ST = cast<StoreSDNode>(User);
14556 SDValue StoreValue = ST->getValue();
14557 unsigned ResNo = StoreValue.getResNo();
14558 // Ensure the store corresponds to an output pointer.
14559 if (CallRetResNo == ResNo)
14560 continue;
14561 // Ensure the store to the default address space and not atomic or volatile.
14562 if (!ST->isSimple() || ST->getAddressSpace() != 0)
14563 continue;
14564 // Ensure all store chains are the same (so they don't alias).
14565 if (StoresInChain && ST->getChain() != StoresInChain)
14566 continue;
14567 // Ensure the store is properly aligned.
14568 Type *StoreType = StoreValue.getValueType().getTypeForEVT(Ctx);
14569 if (ST->getAlign() <
14570 DAG.getDataLayout().getABITypeAlign(StoreType->getScalarType()))
14571 continue;
14572 // Avoid:
14573 // 1. Creating cyclic dependencies.
14574 // 2. Expanding the node to a call within a call sequence.
14576 continue;
14577 ResultStores[ResNo] = ST;
14578 StoresInChain = ST->getChain();
14579 }
14580
14581 ArgListTy Args;
14582
14583 // Pass the arguments.
14584 for (const SDValue &Op : Node->op_values()) {
14585 EVT ArgVT = Op.getValueType();
14586 Type *ArgTy = ArgVT.getTypeForEVT(Ctx);
14587 Args.emplace_back(Op, ArgTy);
14588 }
14589
14590 // Pass the output pointers.
14591 SmallVector<SDValue, 2> ResultPtrs(NumResults);
14593 for (auto [ResNo, ST] : llvm::enumerate(ResultStores)) {
14594 if (ResNo == CallRetResNo)
14595 continue;
14596 EVT ResVT = Node->getValueType(ResNo);
14597 SDValue ResultPtr = ST ? ST->getBasePtr() : DAG.CreateStackTemporary(ResVT);
14598 ResultPtrs[ResNo] = ResultPtr;
14599 Args.emplace_back(ResultPtr, PointerTy);
14600 }
14601
14602 SDLoc DL(Node);
14603
14605 // Pass the vector mask (if required).
14606 EVT MaskVT = getSetCCResultType(DAG.getDataLayout(), Ctx, VT);
14607 SDValue Mask = DAG.getBoolConstant(true, DL, MaskVT, VT);
14608 Args.emplace_back(Mask, MaskVT.getTypeForEVT(Ctx));
14609 }
14610
14611 Type *RetType = CallRetResNo.has_value()
14612 ? Node->getValueType(*CallRetResNo).getTypeForEVT(Ctx)
14613 : Type::getVoidTy(Ctx);
14614 SDValue InChain = StoresInChain ? StoresInChain : DAG.getEntryNode();
14615 SDValue Callee =
14616 DAG.getExternalSymbol(LibcallImpl, getPointerTy(DAG.getDataLayout()));
14618 CLI.setDebugLoc(DL).setChain(InChain).setLibCallee(
14619 getLibcallImplCallingConv(LibcallImpl), RetType, Callee, std::move(Args));
14620
14621 auto [Call, CallChain] = LowerCallTo(CLI);
14622
14623 for (auto [ResNo, ResultPtr] : llvm::enumerate(ResultPtrs)) {
14624 if (ResNo == CallRetResNo) {
14625 Results.push_back(Call);
14626 continue;
14627 }
14628 MachinePointerInfo PtrInfo;
14629 SDValue LoadResult = DAG.getLoad(Node->getValueType(ResNo), DL, CallChain,
14630 ResultPtr, PtrInfo);
14631 SDValue OutChain = LoadResult.getValue(1);
14632
14633 if (StoreSDNode *ST = ResultStores[ResNo]) {
14634 // Replace store with the library call.
14635 DAG.ReplaceAllUsesOfValueWith(SDValue(ST, 0), OutChain);
14636 PtrInfo = ST->getPointerInfo();
14637 } else {
14639 DAG.getMachineFunction(),
14640 cast<FrameIndexSDNode>(ResultPtr)->getIndex());
14641 }
14642
14643 Results.push_back(LoadResult);
14644 }
14645
14646 return true;
14647}
14648
14650 SDValue &LHS, SDValue &RHS,
14651 SDValue &CC, bool &NeedInvert,
14652 const SDLoc &dl, SDValue &Chain,
14653 bool IsSignaling) const {
14654 MVT OpVT = LHS.getSimpleValueType();
14655 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
14656 NeedInvert = false;
14657 switch (getCondCodeAction(CCCode, OpVT)) {
14658 default:
14659 llvm_unreachable("Unknown condition code action!");
14661 // Nothing to do.
14662 break;
14665 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14666 std::swap(LHS, RHS);
14667 CC = DAG.getCondCode(InvCC);
14668 return true;
14669 }
14670 // Swapping operands didn't work. Try inverting the condition.
14671 bool NeedSwap = false;
14672 InvCC = getSetCCInverse(CCCode, OpVT);
14673 if (!isCondCodeLegalOrCustom(InvCC, OpVT)) {
14674 // If inverting the condition is not enough, try swapping operands
14675 // on top of it.
14676 InvCC = ISD::getSetCCSwappedOperands(InvCC);
14677 NeedSwap = true;
14678 }
14679 if (isCondCodeLegalOrCustom(InvCC, OpVT)) {
14680 CC = DAG.getCondCode(InvCC);
14681 NeedInvert = true;
14682 if (NeedSwap)
14683 std::swap(LHS, RHS);
14684 return true;
14685 }
14686
14687 // Special case: expand i1 comparisons using logical operations.
14688 if (OpVT == MVT::i1) {
14689 SDValue Ret;
14690 switch (CCCode) {
14691 default:
14692 llvm_unreachable("Unknown integer setcc!");
14693 case ISD::SETEQ: // X == Y --> ~(X ^ Y)
14694 Ret = DAG.getNOT(dl, DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS),
14695 MVT::i1);
14696 break;
14697 case ISD::SETNE: // X != Y --> (X ^ Y)
14698 Ret = DAG.getNode(ISD::XOR, dl, MVT::i1, LHS, RHS);
14699 break;
14700 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
14701 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
14702 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, RHS,
14703 DAG.getNOT(dl, LHS, MVT::i1));
14704 break;
14705 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
14706 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
14707 Ret = DAG.getNode(ISD::AND, dl, MVT::i1, LHS,
14708 DAG.getNOT(dl, RHS, MVT::i1));
14709 break;
14710 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
14711 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
14712 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, RHS,
14713 DAG.getNOT(dl, LHS, MVT::i1));
14714 break;
14715 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
14716 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
14717 Ret = DAG.getNode(ISD::OR, dl, MVT::i1, LHS,
14718 DAG.getNOT(dl, RHS, MVT::i1));
14719 break;
14720 }
14721
14722 LHS = DAG.getZExtOrTrunc(Ret, dl, VT);
14723 RHS = SDValue();
14724 CC = SDValue();
14725 return true;
14726 }
14727
14729 unsigned Opc = 0;
14730 switch (CCCode) {
14731 default:
14732 llvm_unreachable("Don't know how to expand this condition!");
14733 case ISD::SETUO:
14734 if (isCondCodeLegal(ISD::SETUNE, OpVT)) {
14735 CC1 = ISD::SETUNE;
14736 CC2 = ISD::SETUNE;
14737 Opc = ISD::OR;
14738 break;
14739 }
14741 "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
14742 NeedInvert = true;
14743 [[fallthrough]];
14744 case ISD::SETO:
14746 "If SETO is expanded, SETOEQ must be legal!");
14747 CC1 = ISD::SETOEQ;
14748 CC2 = ISD::SETOEQ;
14749 Opc = ISD::AND;
14750 break;
14751 case ISD::SETONE:
14752 case ISD::SETUEQ:
14753 // If the SETUO or SETO CC isn't legal, we might be able to use
14754 // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
14755 // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
14756 // the operands.
14757 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14758 if (!isCondCodeLegal(CC2, OpVT) && (isCondCodeLegal(ISD::SETOGT, OpVT) ||
14759 isCondCodeLegal(ISD::SETOLT, OpVT))) {
14760 CC1 = ISD::SETOGT;
14761 CC2 = ISD::SETOLT;
14762 Opc = ISD::OR;
14763 NeedInvert = ((unsigned)CCCode & 0x8U);
14764 break;
14765 }
14766 [[fallthrough]];
14767 case ISD::SETOEQ:
14768 case ISD::SETOGT:
14769 case ISD::SETOGE:
14770 case ISD::SETOLT:
14771 case ISD::SETOLE:
14772 case ISD::SETUNE:
14773 case ISD::SETUGT:
14774 case ISD::SETUGE:
14775 case ISD::SETULT:
14776 case ISD::SETULE:
14777 // If we are floating point, assign and break, otherwise fall through.
14778 if (!OpVT.isInteger()) {
14779 // We can use the 4th bit to tell if we are the unordered
14780 // or ordered version of the opcode.
14781 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
14782 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
14783 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
14784 break;
14785 }
14786 // Fallthrough if we are unsigned integer.
14787 [[fallthrough]];
14788 case ISD::SETLE:
14789 case ISD::SETGT:
14790 case ISD::SETGE:
14791 case ISD::SETLT:
14792 case ISD::SETNE:
14793 case ISD::SETEQ:
14794 // If all combinations of inverting the condition and swapping operands
14795 // didn't work then we have no means to expand the condition.
14796 llvm_unreachable("Don't know how to expand this condition!");
14797 }
14798
14799 SDValue SetCC1, SetCC2;
14800 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
14801 // If we aren't the ordered or unorder operation,
14802 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
14803 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
14804 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
14805 } else {
14806 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
14807 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
14808 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
14809 }
14810 if (Chain)
14811 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
14812 SetCC2.getValue(1));
14813 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
14814 RHS = SDValue();
14815 CC = SDValue();
14816 return true;
14817 }
14818 }
14819 return false;
14820}
14821
14823 SelectionDAG &DAG) const {
14824 EVT VT = Node->getValueType(0);
14825 // Despite its documentation, GetSplitDestVTs will assert if VT cannot be
14826 // split into two equal parts.
14827 if (!VT.isVector() || !VT.getVectorElementCount().isKnownMultipleOf(2))
14828 return SDValue();
14829
14830 // Restrict expansion to cases where both parts can be concatenated.
14831 auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VT);
14832 if (LoVT != HiVT || !isTypeLegal(LoVT))
14833 return SDValue();
14834
14835 SDLoc DL(Node);
14836 unsigned Opcode = Node->getOpcode();
14837
14838 // Don't expand if the result is likely to be unrolled anyway.
14839 if (!isOperationLegalOrCustomOrPromote(Opcode, LoVT))
14840 return SDValue();
14841
14842 SmallVector<SDValue, 4> LoOps, HiOps;
14843 for (const SDValue &V : Node->op_values()) {
14844 if (!V.getValueType().isVector()) {
14845 // Scalar operands pass through to both halves unchanged.
14846 LoOps.push_back(V);
14847 HiOps.push_back(V);
14848 continue;
14849 }
14850 auto [Lo, Hi] = DAG.SplitVector(V, DL, LoVT, HiVT);
14851 LoOps.push_back(Lo);
14852 HiOps.push_back(Hi);
14853 }
14854
14855 bool IsStrict = Node->isStrictFPOpcode();
14856 SDVTList LoVTs =
14857 IsStrict ? DAG.getVTList(LoVT, MVT::Other) : DAG.getVTList(LoVT);
14858 SDVTList HiVTs =
14859 IsStrict ? DAG.getVTList(HiVT, MVT::Other) : DAG.getVTList(HiVT);
14860 SDValue SplitOpLo = DAG.getNode(Opcode, DL, LoVTs, LoOps, Node->getFlags());
14861 SDValue SplitOpHi = DAG.getNode(Opcode, DL, HiVTs, HiOps, Node->getFlags());
14862 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SplitOpLo, SplitOpHi);
14863
14864 if (!IsStrict)
14865 return Res;
14866
14867 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14868 SplitOpLo.getValue(1), SplitOpHi.getValue(1));
14869 return DAG.getMergeValues({Res, Chain}, DL);
14870}
14871
14873 const SDLoc &DL,
14874 EVT InVecVT, SDValue EltNo,
14875 LoadSDNode *OriginalLoad,
14876 SelectionDAG &DAG) const {
14877 assert(OriginalLoad->isSimple());
14878
14879 EVT VecEltVT = InVecVT.getVectorElementType();
14880
14881 // If the vector element type is not a multiple of a byte then we are unable
14882 // to correctly compute an address to load only the extracted element as a
14883 // scalar.
14884 if (!VecEltVT.isByteSized())
14885 return SDValue();
14886
14887 ISD::LoadExtType ExtTy =
14888 ResultVT.bitsGT(VecEltVT) ? ISD::EXTLOAD : ISD::NON_EXTLOAD;
14889 if (!isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
14890 return SDValue();
14891
14892 std::optional<unsigned> ByteOffset;
14893 Align Alignment = OriginalLoad->getAlign();
14895 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
14896 int Elt = ConstEltNo->getZExtValue();
14897 ByteOffset = VecEltVT.getSizeInBits() * Elt / 8;
14898 MPI = OriginalLoad->getPointerInfo().getWithOffset(*ByteOffset);
14899 Alignment = commonAlignment(Alignment, *ByteOffset);
14900 } else {
14901 // Discard the pointer info except the address space because the memory
14902 // operand can't represent this new access since the offset is variable.
14903 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
14904 Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
14905 }
14906
14907 if (!shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT, ByteOffset))
14908 return SDValue();
14909
14910 unsigned IsFast = 0;
14911 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
14912 OriginalLoad->getAddressSpace(), Alignment,
14913 OriginalLoad->getMemOperand()->getFlags(), &IsFast) ||
14914 !IsFast)
14915 return SDValue();
14916
14917 // The original DAG loaded the entire vector from memory, so arithmetic
14918 // within it must be inbounds.
14920 DAG, OriginalLoad->getBasePtr(), InVecVT, EltNo);
14921
14922 // We are replacing a vector load with a scalar load. The new load must have
14923 // identical memory op ordering to the original.
14924 SDValue Load;
14925 if (ResultVT.bitsGT(VecEltVT)) {
14926 // If the result type of vextract is wider than the load, then issue an
14927 // extending load instead.
14928 ISD::LoadExtType ExtType =
14929 isLoadLegal(ResultVT, VecEltVT, Alignment,
14930 OriginalLoad->getAddressSpace(), ISD::ZEXTLOAD, false)
14932 : ISD::EXTLOAD;
14933 Load = DAG.getExtLoad(ExtType, DL, ResultVT, OriginalLoad->getChain(),
14934 NewPtr, MPI, VecEltVT, Alignment,
14935 OriginalLoad->getMemOperand()->getFlags(),
14936 OriginalLoad->getMMOMetadataForSubAccess());
14937 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14938 } else {
14939 // The result type is narrower or the same width as the vector element
14940 Load = DAG.getLoad(VecEltVT, DL, OriginalLoad->getChain(), NewPtr, MPI,
14941 Alignment, OriginalLoad->getMemOperand()->getFlags(),
14942 OriginalLoad->getMMOMetadataForSubAccess());
14943 DAG.makeEquivalentMemoryOrdering(OriginalLoad, Load);
14944 if (ResultVT.bitsLT(VecEltVT))
14945 Load = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, Load);
14946 else
14947 Load = DAG.getBitcast(ResultVT, Load);
14948 }
14949
14950 return Load;
14951}
14952
14953// Set type id for call site info and metadata 'call_target'.
14954// We are filtering for:
14955// a) The call-graph-section use case that wants to know about indirect
14956// calls, or
14957// b) We want to annotate indirect calls.
14959 const CallBase *CB, MachineFunction &MF,
14960 MachineFunction::CallSiteInfo &CSInfo) const {
14961 if (CB && CB->isIndirectCall() &&
14964 CSInfo = MachineFunction::CallSiteInfo(*CB);
14965}
return SDValue()
const TargetLowering & TLI
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
constexpr LLT F32
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
block Block Frequency Analysis
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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 GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-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:540
#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
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
int64_t C1
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
int64_t C0
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.
#define FP_CMP_LIBCALL(BASE)
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 void setArgListEntryAttributes(TargetLoweringBase::ArgListEntry &Entry, const SourceT &Src, unsigned ArgIdx)
Set CallLoweringInfo attribute flags based on a call instruction and called function attributes.
static std::pair< RTLIB::Libcall, ISD::CondCode > selectFPCmpLibcall(const LibcallLoweringInfo &Libcalls, RTLIB::Libcall BoolLC, RTLIB::Libcall TriStateLC, RTLIB::Libcall GenericLC, ISD::CondCode TriStateCC)
Select the libcall and the condition code to test its result against 0 for an ordered floating-point ...
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 combineShiftToAVGSUB(SDValue Op, TargetLowering::TargetLoweringOpt &TLO, const TargetLowering &TLI, const APInt &DemandedBits, const APInt &DemandedElts, unsigned Depth)
static unsigned getConstraintPiority(TargetLowering::ConstraintType CT)
Return a number indicating our preference for chosing a type of constraint over another,...
static std::optional< EVT > getNarrowAVGType(EVT VT, unsigned KnownBits, LLVMContext &Ctx)
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 SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx, EVT VecVT, const SDLoc &DL, ElementCount SubEC)
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 MaybeAlign getParamAlign(const CallBase &Call, unsigned ArgIdx)
static MaybeAlign getParamStackAlign(const CallBase &Call, unsigned ArgIdx)
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)
static bool paramHasAttr(const CallBase &Call, unsigned ArgIdx, Attribute::AttrKind Kind)
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:136
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:343
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:364
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:399
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:339
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:335
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:376
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:377
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1451
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1262
APInt bitcastToAPInt() const
Definition APFloat.h:1475
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1202
void changeSign()
Definition APFloat.h:1401
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1213
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:445
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
void setSignBit()
Set the sign bit to 1.
Definition APInt.h:1360
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1416
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:836
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
void negate()
Negate this APInt in place.
Definition APInt.h:1488
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
unsigned countLeadingZeros() const
Definition APInt.h:1626
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
void flipAllBits()
Toggle every bit to its opposite value.
Definition APInt.h:1472
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition APInt.h:1455
unsigned logBase2() const
Definition APInt.h:1781
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:471
void setAllBits()
Set every bit to 1.
Definition APInt.h:1339
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool isMask(unsigned numBits) const
Definition APInt.h:484
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1387
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1437
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1408
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
void clearHighBits(unsigned hiBits)
Set top hiBits bits to 0.
Definition APInt.h:1462
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:860
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1676
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
void setBitVal(unsigned BitPosition, bool BitValue)
Set a given bit to a given value.
Definition APInt.h:1363
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
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
@ None
No attributes have been set.
Definition Attributes.h:127
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:44
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:306
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
constexpr bool isPowerOf2() const
Definition TypeSize.h:324
Class to represent function types.
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
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:338
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
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...
Tracks which library functions to use for a particular subtarget or function.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
RTLIB::LibcallImpl getVectorLibcallImplOrMasked(RTLIB::Libcall Call) const
Return the implementation for Call, or for its masked variant if Call has no implementation.
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,...
unsigned getAddressSpace() const
Return the address space for the associated pointer.
Align getAlign() const
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.
MMOMetadata getMMOMetadataForSubAccess() const
Returns metadata that can be copied unchanged to an access covering all or part of this access's byte...
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:526
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(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
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
ISD::CondCode getOperandCondCode(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 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 SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
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.
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
bool isGuaranteedNotToBePoison(SDValue Op, unsigned Depth=0) const
Return true if this function can prove that Op is never poison.
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 getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
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 SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
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 getTypeSize(const SDLoc &DL, EVT VT, TypeSize TS)
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 MMOMetadata &Metadata=MMOMetadata())
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 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 SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
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
const LibcallLoweringInfo & getLibcalls() 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.
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
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 setExtAttribute(Attribute::AttrKind Attr)
LLVM_ABI void setAttributes(const CallBase *Call, unsigned ArgIdx)
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...
virtual IntegerType * getCmpLibcallReturnType(LLVMContext &Ctx) const
Return the integer type returned by comparison libcalls.
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 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 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...
bool isFPImmLegal(const APFloat &Imm, EVT VT, bool ForCodeSize=false) const
Returns true if the specified FP immediate can be materialized without a load from the constant pool.
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...
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
EVT getLegalTypeToTransformTo(LLVMContext &Context, EVT VT) const
Perform getTypeToTransformTo repeatedly until a legal type is obtained.
const LibcallLoweringInfo & getLibcallLoweringInfo() const
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 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...
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 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.
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.
void expandVectorDeinterleave(SDNode *Node, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
Expand a VECTOR_DEINTERLEAVE without introducing wider vector types.
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.
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.
bool LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC, bool &NeedInvert, const SDLoc &dl, SDValue &Chain, bool IsSignaling=false) const
Legalize a SETCC with given LHS and RHS and condition code CC on the current target.
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
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 expandGetActiveLaneMask(SDNode *N, SelectionDAG &DAG) const
Expand GET_ACTIVE_LANE_MASK nodes.
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 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 expandMULH(SDNode *Node, SelectionDAG &DAG) const
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 expandVectorInterleave(SDNode *Node, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
Expand a VECTOR_INTERLEAVE without introducing wider vector types.
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.
static ArgListTy getArgListForFunctionType(FunctionType *FuncTy, const AttributeList &FuncAttrs, ArrayRef< SDValue > Ops)
Build a call argument list for FuncTy, taking the argument node values from Ops and the parameter typ...
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.
SDValue expandVectorMatch(SDNode *N, SelectionDAG &DAG) const
Expand VECTOR_MATCH nodes.
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 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 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.
bool expandMODF(SDNode *N, SelectionDAG &DAG, SmallVectorImpl< SDValue > &Results) const
Expand MODF node into fractional and integer parts.
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:870
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:352
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:299
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition Value.cpp:712
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
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:181
constexpr bool hasKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns true if there exists a value X where RHS*X will result in a value whose quantity matches our ...
Definition TypeSize.h:266
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:231
constexpr ScalarTy getKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns a value X where RHS*X will result in a value whose quantity matches our own.
Definition TypeSize.h:274
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:217
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
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:3043
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.
@ 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:43
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:845
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ 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:543
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ AVGSUBFLOORS
AVGSUBFLOORS/AVGSUBFLOORU - Averaging subtract - Subtract two integers using an integer of type i[N+1...
Definition ISDOpcodes.h:733
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:805
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:397
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:296
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:527
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ 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:403
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:879
@ 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:523
@ 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:222
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:906
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:765
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:936
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ FMULADD
FMULADD - Performs a * b + c, with, or without, intermediate rounding.
Definition ISDOpcodes.h:533
@ 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:256
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:796
@ SDIVFIX
RESULT = [US]DIVFIX(LHS, RHS, SCALE) - Perform fixed point division on 2 integers with the same width...
Definition ISDOpcodes.h:410
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:814
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:870
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:725
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:675
@ 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:355
@ BRIND
BRIND - Indirect branch.
@ VECTOR_INTERLEAVE
VECTOR_INTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor to...
Definition ISDOpcodes.h:640
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:822
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:682
@ 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:232
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ 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:714
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:787
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Same as FMINNUM/FMAXNUM, except that a signaling NaN operand deterministi...
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:876
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:837
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:389
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:663
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:925
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:914
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:745
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:416
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:831
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:801
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:482
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:952
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:181
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:757
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:720
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:667
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:306
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:243
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:813
@ 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:985
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:947
@ 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:971
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:882
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:859
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ CALLSEQ_START
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence,...
@ VECTOR_DEINTERLEAVE
VECTOR_DEINTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor ...
Definition ISDOpcodes.h:629
@ CTTZ_ELTS_ZERO_POISON
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:740
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:769
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
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 bool matchBinaryPredicate(SDValue LHS, SDValue RHS, const APInt &DemandedElts, 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...
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.
LLVM_ABI StringRef getCondCodeName(CondCode Operation)
Return the name of the given condition code, e.g. "setoeq".
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.
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...
bool matchUnaryPredicate(SDValue Op, const APInt &DemandedElts, std::function< bool(ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Hook for matching ConstantSDNode predicate.
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)
LLVM_ABI Libcall getUREM(EVT VT)
Or< Preds... > m_AnyOf(const Preds &...preds)
TypeSize_match< ElementCount > m_ElementCount(ElementCount &V)
Match any integer constant or constant multiple of VSCALE that can be represented using ElementCount.
bool sd_match(SDValue N, 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:339
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
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:1755
constexpr uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition MathExtras.h:208
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:1577
@ 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:2570
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.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
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:1559
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:1762
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:326
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
auto find_if_not(R &&Range, UnaryPredicate P)
Definition STLExtras.h:1793
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
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:389
@ Other
Any other memory.
Definition ModRef.h:68
To bit_cast(const From &from) noexcept
Definition bit.h:90
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
@ 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
@ Fast
Assign the register banks as fast as possible (default).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
fltNonfiniteBehavior
Definition APFloat.h:977
DWARFExpression::Operation Op
RoundingMode
Rounding mode.
@ TowardZero
roundTowardZero.
@ NearestTiesToEven
roundTiesToEven.
@ TowardPositive
roundTowardPositive.
@ NearestTiesToAway
roundTiesToAway.
@ TowardNegative
roundTowardNegative.
ArrayRef(const T &OneElt) -> ArrayRef< T >
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:206
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:1742
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
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:78
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
fltNanEncoding
Definition APFloat.h:1001
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:368
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#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:433
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
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:144
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:338
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
ElementCount getVectorElementCount() const
Definition ValueTypes.h:388
EVT getDoubleNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:509
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition ValueTypes.h:281
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:397
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
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:468
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
Definition ValueTypes.h:516
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
TypeSize getStoreSizeInBits() const
Return the number of bits overwritten by a store of the specified value type.
Definition ValueTypes.h:450
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:354
std::string getEVTString() const
This function returns value type as a string, e.g. "i32".
Definition ValueTypes.h:539
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:419
EVT widenIntegerVectorElementType(LLVMContext &Context) const
Return a VT for an integer vector type with the size of the elements doubled.
Definition ValueTypes.h:490
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:225
bool isFixedLengthVector() const
Definition ValueTypes.h:214
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:294
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:482
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:202
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
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:136
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
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:374
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:346
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:499
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
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.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
static 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:1039
fltNanEncoding nanEncoding
Definition APFloat.h:1041